]> Git Repo - J-linux.git/blob - drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c
Documentation/gpu: update dGPU asic info table
[J-linux.git] / drivers / gpu / drm / amd / display / amdgpu_dm / amdgpu_dm.c
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25
26 /* The caprices of the preprocessor require that this be declared right here */
27 #define CREATE_TRACE_POINTS
28
29 #include "dm_services_types.h"
30 #include "dc.h"
31 #include "dc_link_dp.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "amdgpu_dm_trace.h"
42
43 #include "vid.h"
44 #include "amdgpu.h"
45 #include "amdgpu_display.h"
46 #include "amdgpu_ucode.h"
47 #include "atom.h"
48 #include "amdgpu_dm.h"
49 #include "amdgpu_dm_plane.h"
50 #include "amdgpu_dm_crtc.h"
51 #ifdef CONFIG_DRM_AMD_DC_HDCP
52 #include "amdgpu_dm_hdcp.h"
53 #include <drm/display/drm_hdcp_helper.h>
54 #endif
55 #include "amdgpu_pm.h"
56 #include "amdgpu_atombios.h"
57
58 #include "amd_shared.h"
59 #include "amdgpu_dm_irq.h"
60 #include "dm_helpers.h"
61 #include "amdgpu_dm_mst_types.h"
62 #if defined(CONFIG_DEBUG_FS)
63 #include "amdgpu_dm_debugfs.h"
64 #endif
65 #include "amdgpu_dm_psr.h"
66
67 #include "ivsrcid/ivsrcid_vislands30.h"
68
69 #include <linux/module.h>
70 #include <linux/moduleparam.h>
71 #include <linux/types.h>
72 #include <linux/pm_runtime.h>
73 #include <linux/pci.h>
74 #include <linux/firmware.h>
75 #include <linux/component.h>
76 #include <linux/dmi.h>
77
78 #include <drm/display/drm_dp_mst_helper.h>
79 #include <drm/display/drm_hdmi_helper.h>
80 #include <drm/drm_atomic.h>
81 #include <drm/drm_atomic_uapi.h>
82 #include <drm/drm_atomic_helper.h>
83 #include <drm/drm_blend.h>
84 #include <drm/drm_fourcc.h>
85 #include <drm/drm_edid.h>
86 #include <drm/drm_vblank.h>
87 #include <drm/drm_audio_component.h>
88 #include <drm/drm_gem_atomic_helper.h>
89 #include <drm/drm_plane_helper.h>
90
91 #include <acpi/video.h>
92
93 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
94
95 #include "dcn/dcn_1_0_offset.h"
96 #include "dcn/dcn_1_0_sh_mask.h"
97 #include "soc15_hw_ip.h"
98 #include "soc15_common.h"
99 #include "vega10_ip_offset.h"
100
101 #include "gc/gc_11_0_0_offset.h"
102 #include "gc/gc_11_0_0_sh_mask.h"
103
104 #include "modules/inc/mod_freesync.h"
105 #include "modules/power/power_helpers.h"
106 #include "modules/inc/mod_info_packet.h"
107
108 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
109 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
110 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
111 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
112 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
114 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
116 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
118 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
120 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
122 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
124 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
126 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
128 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
130
131 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
132 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
133 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
134 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
135
136 #define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
137 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
138
139 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
140 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
141
142 /* Number of bytes in PSP header for firmware. */
143 #define PSP_HEADER_BYTES 0x100
144
145 /* Number of bytes in PSP footer for firmware. */
146 #define PSP_FOOTER_BYTES 0x100
147
148 /**
149  * DOC: overview
150  *
151  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
152  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
153  * requests into DC requests, and DC responses into DRM responses.
154  *
155  * The root control structure is &struct amdgpu_display_manager.
156  */
157
158 /* basic init/fini API */
159 static int amdgpu_dm_init(struct amdgpu_device *adev);
160 static void amdgpu_dm_fini(struct amdgpu_device *adev);
161 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
162
163 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
164 {
165         switch (link->dpcd_caps.dongle_type) {
166         case DISPLAY_DONGLE_NONE:
167                 return DRM_MODE_SUBCONNECTOR_Native;
168         case DISPLAY_DONGLE_DP_VGA_CONVERTER:
169                 return DRM_MODE_SUBCONNECTOR_VGA;
170         case DISPLAY_DONGLE_DP_DVI_CONVERTER:
171         case DISPLAY_DONGLE_DP_DVI_DONGLE:
172                 return DRM_MODE_SUBCONNECTOR_DVID;
173         case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
174         case DISPLAY_DONGLE_DP_HDMI_DONGLE:
175                 return DRM_MODE_SUBCONNECTOR_HDMIA;
176         case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
177         default:
178                 return DRM_MODE_SUBCONNECTOR_Unknown;
179         }
180 }
181
182 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
183 {
184         struct dc_link *link = aconnector->dc_link;
185         struct drm_connector *connector = &aconnector->base;
186         enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
187
188         if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
189                 return;
190
191         if (aconnector->dc_sink)
192                 subconnector = get_subconnector_type(link);
193
194         drm_object_property_set_value(&connector->base,
195                         connector->dev->mode_config.dp_subconnector_property,
196                         subconnector);
197 }
198
199 /*
200  * initializes drm_device display related structures, based on the information
201  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
202  * drm_encoder, drm_mode_config
203  *
204  * Returns 0 on success
205  */
206 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
207 /* removes and deallocates the drm structures, created by the above function */
208 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
209
210 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
211                                     struct amdgpu_dm_connector *amdgpu_dm_connector,
212                                     u32 link_index,
213                                     struct amdgpu_encoder *amdgpu_encoder);
214 static int amdgpu_dm_encoder_init(struct drm_device *dev,
215                                   struct amdgpu_encoder *aencoder,
216                                   uint32_t link_index);
217
218 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
219
220 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
221
222 static int amdgpu_dm_atomic_check(struct drm_device *dev,
223                                   struct drm_atomic_state *state);
224
225 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
226 static void handle_hpd_rx_irq(void *param);
227
228 static bool
229 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
230                                  struct drm_crtc_state *new_crtc_state);
231 /*
232  * dm_vblank_get_counter
233  *
234  * @brief
235  * Get counter for number of vertical blanks
236  *
237  * @param
238  * struct amdgpu_device *adev - [in] desired amdgpu device
239  * int disp_idx - [in] which CRTC to get the counter from
240  *
241  * @return
242  * Counter for vertical blanks
243  */
244 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
245 {
246         if (crtc >= adev->mode_info.num_crtc)
247                 return 0;
248         else {
249                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
250
251                 if (acrtc->dm_irq_params.stream == NULL) {
252                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
253                                   crtc);
254                         return 0;
255                 }
256
257                 return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
258         }
259 }
260
261 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
262                                   u32 *vbl, u32 *position)
263 {
264         u32 v_blank_start, v_blank_end, h_position, v_position;
265
266         if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
267                 return -EINVAL;
268         else {
269                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
270
271                 if (acrtc->dm_irq_params.stream ==  NULL) {
272                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
273                                   crtc);
274                         return 0;
275                 }
276
277                 /*
278                  * TODO rework base driver to use values directly.
279                  * for now parse it back into reg-format
280                  */
281                 dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
282                                          &v_blank_start,
283                                          &v_blank_end,
284                                          &h_position,
285                                          &v_position);
286
287                 *position = v_position | (h_position << 16);
288                 *vbl = v_blank_start | (v_blank_end << 16);
289         }
290
291         return 0;
292 }
293
294 static bool dm_is_idle(void *handle)
295 {
296         /* XXX todo */
297         return true;
298 }
299
300 static int dm_wait_for_idle(void *handle)
301 {
302         /* XXX todo */
303         return 0;
304 }
305
306 static bool dm_check_soft_reset(void *handle)
307 {
308         return false;
309 }
310
311 static int dm_soft_reset(void *handle)
312 {
313         /* XXX todo */
314         return 0;
315 }
316
317 static struct amdgpu_crtc *
318 get_crtc_by_otg_inst(struct amdgpu_device *adev,
319                      int otg_inst)
320 {
321         struct drm_device *dev = adev_to_drm(adev);
322         struct drm_crtc *crtc;
323         struct amdgpu_crtc *amdgpu_crtc;
324
325         if (WARN_ON(otg_inst == -1))
326                 return adev->mode_info.crtcs[0];
327
328         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
329                 amdgpu_crtc = to_amdgpu_crtc(crtc);
330
331                 if (amdgpu_crtc->otg_inst == otg_inst)
332                         return amdgpu_crtc;
333         }
334
335         return NULL;
336 }
337
338 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
339                                               struct dm_crtc_state *new_state)
340 {
341         if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
342                 return true;
343         else if (amdgpu_dm_vrr_active(old_state) != amdgpu_dm_vrr_active(new_state))
344                 return true;
345         else
346                 return false;
347 }
348
349 /**
350  * dm_pflip_high_irq() - Handle pageflip interrupt
351  * @interrupt_params: ignored
352  *
353  * Handles the pageflip interrupt by notifying all interested parties
354  * that the pageflip has been completed.
355  */
356 static void dm_pflip_high_irq(void *interrupt_params)
357 {
358         struct amdgpu_crtc *amdgpu_crtc;
359         struct common_irq_params *irq_params = interrupt_params;
360         struct amdgpu_device *adev = irq_params->adev;
361         unsigned long flags;
362         struct drm_pending_vblank_event *e;
363         u32 vpos, hpos, v_blank_start, v_blank_end;
364         bool vrr_active;
365
366         amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
367
368         /* IRQ could occur when in initial stage */
369         /* TODO work and BO cleanup */
370         if (amdgpu_crtc == NULL) {
371                 DC_LOG_PFLIP("CRTC is null, returning.\n");
372                 return;
373         }
374
375         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
376
377         if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
378                 DC_LOG_PFLIP("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
379                                                  amdgpu_crtc->pflip_status,
380                                                  AMDGPU_FLIP_SUBMITTED,
381                                                  amdgpu_crtc->crtc_id,
382                                                  amdgpu_crtc);
383                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
384                 return;
385         }
386
387         /* page flip completed. */
388         e = amdgpu_crtc->event;
389         amdgpu_crtc->event = NULL;
390
391         WARN_ON(!e);
392
393         vrr_active = amdgpu_dm_vrr_active_irq(amdgpu_crtc);
394
395         /* Fixed refresh rate, or VRR scanout position outside front-porch? */
396         if (!vrr_active ||
397             !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
398                                       &v_blank_end, &hpos, &vpos) ||
399             (vpos < v_blank_start)) {
400                 /* Update to correct count and vblank timestamp if racing with
401                  * vblank irq. This also updates to the correct vblank timestamp
402                  * even in VRR mode, as scanout is past the front-porch atm.
403                  */
404                 drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
405
406                 /* Wake up userspace by sending the pageflip event with proper
407                  * count and timestamp of vblank of flip completion.
408                  */
409                 if (e) {
410                         drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
411
412                         /* Event sent, so done with vblank for this flip */
413                         drm_crtc_vblank_put(&amdgpu_crtc->base);
414                 }
415         } else if (e) {
416                 /* VRR active and inside front-porch: vblank count and
417                  * timestamp for pageflip event will only be up to date after
418                  * drm_crtc_handle_vblank() has been executed from late vblank
419                  * irq handler after start of back-porch (vline 0). We queue the
420                  * pageflip event for send-out by drm_crtc_handle_vblank() with
421                  * updated timestamp and count, once it runs after us.
422                  *
423                  * We need to open-code this instead of using the helper
424                  * drm_crtc_arm_vblank_event(), as that helper would
425                  * call drm_crtc_accurate_vblank_count(), which we must
426                  * not call in VRR mode while we are in front-porch!
427                  */
428
429                 /* sequence will be replaced by real count during send-out. */
430                 e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
431                 e->pipe = amdgpu_crtc->crtc_id;
432
433                 list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
434                 e = NULL;
435         }
436
437         /* Keep track of vblank of this flip for flip throttling. We use the
438          * cooked hw counter, as that one incremented at start of this vblank
439          * of pageflip completion, so last_flip_vblank is the forbidden count
440          * for queueing new pageflips if vsync + VRR is enabled.
441          */
442         amdgpu_crtc->dm_irq_params.last_flip_vblank =
443                 amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
444
445         amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
446         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
447
448         DC_LOG_PFLIP("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
449                      amdgpu_crtc->crtc_id, amdgpu_crtc,
450                      vrr_active, (int) !e);
451 }
452
453 static void dm_vupdate_high_irq(void *interrupt_params)
454 {
455         struct common_irq_params *irq_params = interrupt_params;
456         struct amdgpu_device *adev = irq_params->adev;
457         struct amdgpu_crtc *acrtc;
458         struct drm_device *drm_dev;
459         struct drm_vblank_crtc *vblank;
460         ktime_t frame_duration_ns, previous_timestamp;
461         unsigned long flags;
462         int vrr_active;
463
464         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
465
466         if (acrtc) {
467                 vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
468                 drm_dev = acrtc->base.dev;
469                 vblank = &drm_dev->vblank[acrtc->base.index];
470                 previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
471                 frame_duration_ns = vblank->time - previous_timestamp;
472
473                 if (frame_duration_ns > 0) {
474                         trace_amdgpu_refresh_rate_track(acrtc->base.index,
475                                                 frame_duration_ns,
476                                                 ktime_divns(NSEC_PER_SEC, frame_duration_ns));
477                         atomic64_set(&irq_params->previous_timestamp, vblank->time);
478                 }
479
480                 DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d\n",
481                               acrtc->crtc_id,
482                               vrr_active);
483
484                 /* Core vblank handling is done here after end of front-porch in
485                  * vrr mode, as vblank timestamping will give valid results
486                  * while now done after front-porch. This will also deliver
487                  * page-flip completion events that have been queued to us
488                  * if a pageflip happened inside front-porch.
489                  */
490                 if (vrr_active) {
491                         dm_crtc_handle_vblank(acrtc);
492
493                         /* BTR processing for pre-DCE12 ASICs */
494                         if (acrtc->dm_irq_params.stream &&
495                             adev->family < AMDGPU_FAMILY_AI) {
496                                 spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
497                                 mod_freesync_handle_v_update(
498                                     adev->dm.freesync_module,
499                                     acrtc->dm_irq_params.stream,
500                                     &acrtc->dm_irq_params.vrr_params);
501
502                                 dc_stream_adjust_vmin_vmax(
503                                     adev->dm.dc,
504                                     acrtc->dm_irq_params.stream,
505                                     &acrtc->dm_irq_params.vrr_params.adjust);
506                                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
507                         }
508                 }
509         }
510 }
511
512 /**
513  * dm_crtc_high_irq() - Handles CRTC interrupt
514  * @interrupt_params: used for determining the CRTC instance
515  *
516  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
517  * event handler.
518  */
519 static void dm_crtc_high_irq(void *interrupt_params)
520 {
521         struct common_irq_params *irq_params = interrupt_params;
522         struct amdgpu_device *adev = irq_params->adev;
523         struct amdgpu_crtc *acrtc;
524         unsigned long flags;
525         int vrr_active;
526
527         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
528         if (!acrtc)
529                 return;
530
531         vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
532
533         DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
534                       vrr_active, acrtc->dm_irq_params.active_planes);
535
536         /**
537          * Core vblank handling at start of front-porch is only possible
538          * in non-vrr mode, as only there vblank timestamping will give
539          * valid results while done in front-porch. Otherwise defer it
540          * to dm_vupdate_high_irq after end of front-porch.
541          */
542         if (!vrr_active)
543                 dm_crtc_handle_vblank(acrtc);
544
545         /**
546          * Following stuff must happen at start of vblank, for crc
547          * computation and below-the-range btr support in vrr mode.
548          */
549         amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
550
551         /* BTR updates need to happen before VUPDATE on Vega and above. */
552         if (adev->family < AMDGPU_FAMILY_AI)
553                 return;
554
555         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
556
557         if (acrtc->dm_irq_params.stream &&
558             acrtc->dm_irq_params.vrr_params.supported &&
559             acrtc->dm_irq_params.freesync_config.state ==
560                     VRR_STATE_ACTIVE_VARIABLE) {
561                 mod_freesync_handle_v_update(adev->dm.freesync_module,
562                                              acrtc->dm_irq_params.stream,
563                                              &acrtc->dm_irq_params.vrr_params);
564
565                 dc_stream_adjust_vmin_vmax(adev->dm.dc, acrtc->dm_irq_params.stream,
566                                            &acrtc->dm_irq_params.vrr_params.adjust);
567         }
568
569         /*
570          * If there aren't any active_planes then DCH HUBP may be clock-gated.
571          * In that case, pageflip completion interrupts won't fire and pageflip
572          * completion events won't get delivered. Prevent this by sending
573          * pending pageflip events from here if a flip is still pending.
574          *
575          * If any planes are enabled, use dm_pflip_high_irq() instead, to
576          * avoid race conditions between flip programming and completion,
577          * which could cause too early flip completion events.
578          */
579         if (adev->family >= AMDGPU_FAMILY_RV &&
580             acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
581             acrtc->dm_irq_params.active_planes == 0) {
582                 if (acrtc->event) {
583                         drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
584                         acrtc->event = NULL;
585                         drm_crtc_vblank_put(&acrtc->base);
586                 }
587                 acrtc->pflip_status = AMDGPU_FLIP_NONE;
588         }
589
590         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
591 }
592
593 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
594 /**
595  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
596  * DCN generation ASICs
597  * @interrupt_params: interrupt parameters
598  *
599  * Used to set crc window/read out crc value at vertical line 0 position
600  */
601 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
602 {
603         struct common_irq_params *irq_params = interrupt_params;
604         struct amdgpu_device *adev = irq_params->adev;
605         struct amdgpu_crtc *acrtc;
606
607         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
608
609         if (!acrtc)
610                 return;
611
612         amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
613 }
614 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
615
616 /**
617  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
618  * @adev: amdgpu_device pointer
619  * @notify: dmub notification structure
620  *
621  * Dmub AUX or SET_CONFIG command completion processing callback
622  * Copies dmub notification to DM which is to be read by AUX command.
623  * issuing thread and also signals the event to wake up the thread.
624  */
625 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
626                                         struct dmub_notification *notify)
627 {
628         if (adev->dm.dmub_notify)
629                 memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
630         if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
631                 complete(&adev->dm.dmub_aux_transfer_done);
632 }
633
634 /**
635  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
636  * @adev: amdgpu_device pointer
637  * @notify: dmub notification structure
638  *
639  * Dmub Hpd interrupt processing callback. Gets displayindex through the
640  * ink index and calls helper to do the processing.
641  */
642 static void dmub_hpd_callback(struct amdgpu_device *adev,
643                               struct dmub_notification *notify)
644 {
645         struct amdgpu_dm_connector *aconnector;
646         struct amdgpu_dm_connector *hpd_aconnector = NULL;
647         struct drm_connector *connector;
648         struct drm_connector_list_iter iter;
649         struct dc_link *link;
650         u8 link_index = 0;
651         struct drm_device *dev;
652
653         if (adev == NULL)
654                 return;
655
656         if (notify == NULL) {
657                 DRM_ERROR("DMUB HPD callback notification was NULL");
658                 return;
659         }
660
661         if (notify->link_index > adev->dm.dc->link_count) {
662                 DRM_ERROR("DMUB HPD index (%u)is abnormal", notify->link_index);
663                 return;
664         }
665
666         link_index = notify->link_index;
667         link = adev->dm.dc->links[link_index];
668         dev = adev->dm.ddev;
669
670         drm_connector_list_iter_begin(dev, &iter);
671         drm_for_each_connector_iter(connector, &iter) {
672                 aconnector = to_amdgpu_dm_connector(connector);
673                 if (link && aconnector->dc_link == link) {
674                         DRM_INFO("DMUB HPD callback: link_index=%u\n", link_index);
675                         hpd_aconnector = aconnector;
676                         break;
677                 }
678         }
679         drm_connector_list_iter_end(&iter);
680
681         if (hpd_aconnector) {
682                 if (notify->type == DMUB_NOTIFICATION_HPD)
683                         handle_hpd_irq_helper(hpd_aconnector);
684                 else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
685                         handle_hpd_rx_irq(hpd_aconnector);
686         }
687 }
688
689 /**
690  * register_dmub_notify_callback - Sets callback for DMUB notify
691  * @adev: amdgpu_device pointer
692  * @type: Type of dmub notification
693  * @callback: Dmub interrupt callback function
694  * @dmub_int_thread_offload: offload indicator
695  *
696  * API to register a dmub callback handler for a dmub notification
697  * Also sets indicator whether callback processing to be offloaded.
698  * to dmub interrupt handling thread
699  * Return: true if successfully registered, false if there is existing registration
700  */
701 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
702                                           enum dmub_notification_type type,
703                                           dmub_notify_interrupt_callback_t callback,
704                                           bool dmub_int_thread_offload)
705 {
706         if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
707                 adev->dm.dmub_callback[type] = callback;
708                 adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
709         } else
710                 return false;
711
712         return true;
713 }
714
715 static void dm_handle_hpd_work(struct work_struct *work)
716 {
717         struct dmub_hpd_work *dmub_hpd_wrk;
718
719         dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
720
721         if (!dmub_hpd_wrk->dmub_notify) {
722                 DRM_ERROR("dmub_hpd_wrk dmub_notify is NULL");
723                 return;
724         }
725
726         if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
727                 dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
728                 dmub_hpd_wrk->dmub_notify);
729         }
730
731         kfree(dmub_hpd_wrk->dmub_notify);
732         kfree(dmub_hpd_wrk);
733
734 }
735
736 #define DMUB_TRACE_MAX_READ 64
737 /**
738  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
739  * @interrupt_params: used for determining the Outbox instance
740  *
741  * Handles the Outbox Interrupt
742  * event handler.
743  */
744 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
745 {
746         struct dmub_notification notify;
747         struct common_irq_params *irq_params = interrupt_params;
748         struct amdgpu_device *adev = irq_params->adev;
749         struct amdgpu_display_manager *dm = &adev->dm;
750         struct dmcub_trace_buf_entry entry = { 0 };
751         u32 count = 0;
752         struct dmub_hpd_work *dmub_hpd_wrk;
753         struct dc_link *plink = NULL;
754
755         if (dc_enable_dmub_notifications(adev->dm.dc) &&
756                 irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
757
758                 do {
759                         dc_stat_get_dmub_notification(adev->dm.dc, &notify);
760                         if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
761                                 DRM_ERROR("DM: notify type %d invalid!", notify.type);
762                                 continue;
763                         }
764                         if (!dm->dmub_callback[notify.type]) {
765                                 DRM_DEBUG_DRIVER("DMUB notification skipped, no handler: type=%d\n", notify.type);
766                                 continue;
767                         }
768                         if (dm->dmub_thread_offload[notify.type] == true) {
769                                 dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
770                                 if (!dmub_hpd_wrk) {
771                                         DRM_ERROR("Failed to allocate dmub_hpd_wrk");
772                                         return;
773                                 }
774                                 dmub_hpd_wrk->dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_ATOMIC);
775                                 if (!dmub_hpd_wrk->dmub_notify) {
776                                         kfree(dmub_hpd_wrk);
777                                         DRM_ERROR("Failed to allocate dmub_hpd_wrk->dmub_notify");
778                                         return;
779                                 }
780                                 INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
781                                 if (dmub_hpd_wrk->dmub_notify)
782                                         memcpy(dmub_hpd_wrk->dmub_notify, &notify, sizeof(struct dmub_notification));
783                                 dmub_hpd_wrk->adev = adev;
784                                 if (notify.type == DMUB_NOTIFICATION_HPD) {
785                                         plink = adev->dm.dc->links[notify.link_index];
786                                         if (plink) {
787                                                 plink->hpd_status =
788                                                         notify.hpd_status == DP_HPD_PLUG;
789                                         }
790                                 }
791                                 queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
792                         } else {
793                                 dm->dmub_callback[notify.type](adev, &notify);
794                         }
795                 } while (notify.pending_notification);
796         }
797
798
799         do {
800                 if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
801                         trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
802                                                         entry.param0, entry.param1);
803
804                         DRM_DEBUG_DRIVER("trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
805                                  entry.trace_code, entry.tick_count, entry.param0, entry.param1);
806                 } else
807                         break;
808
809                 count++;
810
811         } while (count <= DMUB_TRACE_MAX_READ);
812
813         if (count > DMUB_TRACE_MAX_READ)
814                 DRM_DEBUG_DRIVER("Warning : count > DMUB_TRACE_MAX_READ");
815 }
816
817 static int dm_set_clockgating_state(void *handle,
818                   enum amd_clockgating_state state)
819 {
820         return 0;
821 }
822
823 static int dm_set_powergating_state(void *handle,
824                   enum amd_powergating_state state)
825 {
826         return 0;
827 }
828
829 /* Prototypes of private functions */
830 static int dm_early_init(void* handle);
831
832 /* Allocate memory for FBC compressed data  */
833 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
834 {
835         struct drm_device *dev = connector->dev;
836         struct amdgpu_device *adev = drm_to_adev(dev);
837         struct dm_compressor_info *compressor = &adev->dm.compressor;
838         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
839         struct drm_display_mode *mode;
840         unsigned long max_size = 0;
841
842         if (adev->dm.dc->fbc_compressor == NULL)
843                 return;
844
845         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
846                 return;
847
848         if (compressor->bo_ptr)
849                 return;
850
851
852         list_for_each_entry(mode, &connector->modes, head) {
853                 if (max_size < mode->htotal * mode->vtotal)
854                         max_size = mode->htotal * mode->vtotal;
855         }
856
857         if (max_size) {
858                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
859                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
860                             &compressor->gpu_addr, &compressor->cpu_addr);
861
862                 if (r)
863                         DRM_ERROR("DM: Failed to initialize FBC\n");
864                 else {
865                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
866                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
867                 }
868
869         }
870
871 }
872
873 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
874                                           int pipe, bool *enabled,
875                                           unsigned char *buf, int max_bytes)
876 {
877         struct drm_device *dev = dev_get_drvdata(kdev);
878         struct amdgpu_device *adev = drm_to_adev(dev);
879         struct drm_connector *connector;
880         struct drm_connector_list_iter conn_iter;
881         struct amdgpu_dm_connector *aconnector;
882         int ret = 0;
883
884         *enabled = false;
885
886         mutex_lock(&adev->dm.audio_lock);
887
888         drm_connector_list_iter_begin(dev, &conn_iter);
889         drm_for_each_connector_iter(connector, &conn_iter) {
890                 aconnector = to_amdgpu_dm_connector(connector);
891                 if (aconnector->audio_inst != port)
892                         continue;
893
894                 *enabled = true;
895                 ret = drm_eld_size(connector->eld);
896                 memcpy(buf, connector->eld, min(max_bytes, ret));
897
898                 break;
899         }
900         drm_connector_list_iter_end(&conn_iter);
901
902         mutex_unlock(&adev->dm.audio_lock);
903
904         DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
905
906         return ret;
907 }
908
909 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
910         .get_eld = amdgpu_dm_audio_component_get_eld,
911 };
912
913 static int amdgpu_dm_audio_component_bind(struct device *kdev,
914                                        struct device *hda_kdev, void *data)
915 {
916         struct drm_device *dev = dev_get_drvdata(kdev);
917         struct amdgpu_device *adev = drm_to_adev(dev);
918         struct drm_audio_component *acomp = data;
919
920         acomp->ops = &amdgpu_dm_audio_component_ops;
921         acomp->dev = kdev;
922         adev->dm.audio_component = acomp;
923
924         return 0;
925 }
926
927 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
928                                           struct device *hda_kdev, void *data)
929 {
930         struct drm_device *dev = dev_get_drvdata(kdev);
931         struct amdgpu_device *adev = drm_to_adev(dev);
932         struct drm_audio_component *acomp = data;
933
934         acomp->ops = NULL;
935         acomp->dev = NULL;
936         adev->dm.audio_component = NULL;
937 }
938
939 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
940         .bind   = amdgpu_dm_audio_component_bind,
941         .unbind = amdgpu_dm_audio_component_unbind,
942 };
943
944 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
945 {
946         int i, ret;
947
948         if (!amdgpu_audio)
949                 return 0;
950
951         adev->mode_info.audio.enabled = true;
952
953         adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
954
955         for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
956                 adev->mode_info.audio.pin[i].channels = -1;
957                 adev->mode_info.audio.pin[i].rate = -1;
958                 adev->mode_info.audio.pin[i].bits_per_sample = -1;
959                 adev->mode_info.audio.pin[i].status_bits = 0;
960                 adev->mode_info.audio.pin[i].category_code = 0;
961                 adev->mode_info.audio.pin[i].connected = false;
962                 adev->mode_info.audio.pin[i].id =
963                         adev->dm.dc->res_pool->audios[i]->inst;
964                 adev->mode_info.audio.pin[i].offset = 0;
965         }
966
967         ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
968         if (ret < 0)
969                 return ret;
970
971         adev->dm.audio_registered = true;
972
973         return 0;
974 }
975
976 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
977 {
978         if (!amdgpu_audio)
979                 return;
980
981         if (!adev->mode_info.audio.enabled)
982                 return;
983
984         if (adev->dm.audio_registered) {
985                 component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
986                 adev->dm.audio_registered = false;
987         }
988
989         /* TODO: Disable audio? */
990
991         adev->mode_info.audio.enabled = false;
992 }
993
994 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
995 {
996         struct drm_audio_component *acomp = adev->dm.audio_component;
997
998         if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
999                 DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
1000
1001                 acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1002                                                  pin, -1);
1003         }
1004 }
1005
1006 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1007 {
1008         const struct dmcub_firmware_header_v1_0 *hdr;
1009         struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1010         struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1011         const struct firmware *dmub_fw = adev->dm.dmub_fw;
1012         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1013         struct abm *abm = adev->dm.dc->res_pool->abm;
1014         struct dmub_srv_hw_params hw_params;
1015         enum dmub_status status;
1016         const unsigned char *fw_inst_const, *fw_bss_data;
1017         u32 i, fw_inst_const_size, fw_bss_data_size;
1018         bool has_hw_support;
1019
1020         if (!dmub_srv)
1021                 /* DMUB isn't supported on the ASIC. */
1022                 return 0;
1023
1024         if (!fb_info) {
1025                 DRM_ERROR("No framebuffer info for DMUB service.\n");
1026                 return -EINVAL;
1027         }
1028
1029         if (!dmub_fw) {
1030                 /* Firmware required for DMUB support. */
1031                 DRM_ERROR("No firmware provided for DMUB.\n");
1032                 return -EINVAL;
1033         }
1034
1035         status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1036         if (status != DMUB_STATUS_OK) {
1037                 DRM_ERROR("Error checking HW support for DMUB: %d\n", status);
1038                 return -EINVAL;
1039         }
1040
1041         if (!has_hw_support) {
1042                 DRM_INFO("DMUB unsupported on ASIC\n");
1043                 return 0;
1044         }
1045
1046         /* Reset DMCUB if it was previously running - before we overwrite its memory. */
1047         status = dmub_srv_hw_reset(dmub_srv);
1048         if (status != DMUB_STATUS_OK)
1049                 DRM_WARN("Error resetting DMUB HW: %d\n", status);
1050
1051         hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1052
1053         fw_inst_const = dmub_fw->data +
1054                         le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1055                         PSP_HEADER_BYTES;
1056
1057         fw_bss_data = dmub_fw->data +
1058                       le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1059                       le32_to_cpu(hdr->inst_const_bytes);
1060
1061         /* Copy firmware and bios info into FB memory. */
1062         fw_inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
1063                              PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
1064
1065         fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1066
1067         /* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1068          * amdgpu_ucode_init_single_fw will load dmub firmware
1069          * fw_inst_const part to cw0; otherwise, the firmware back door load
1070          * will be done by dm_dmub_hw_init
1071          */
1072         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1073                 memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1074                                 fw_inst_const_size);
1075         }
1076
1077         if (fw_bss_data_size)
1078                 memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1079                        fw_bss_data, fw_bss_data_size);
1080
1081         /* Copy firmware bios info into FB memory. */
1082         memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1083                adev->bios_size);
1084
1085         /* Reset regions that need to be reset. */
1086         memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1087         fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1088
1089         memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1090                fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1091
1092         memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1093                fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1094
1095         /* Initialize hardware. */
1096         memset(&hw_params, 0, sizeof(hw_params));
1097         hw_params.fb_base = adev->gmc.fb_start;
1098         hw_params.fb_offset = adev->vm_manager.vram_base_offset;
1099
1100         /* backdoor load firmware and trigger dmub running */
1101         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1102                 hw_params.load_inst_const = true;
1103
1104         if (dmcu)
1105                 hw_params.psp_version = dmcu->psp_version;
1106
1107         for (i = 0; i < fb_info->num_fb; ++i)
1108                 hw_params.fb[i] = &fb_info->fb[i];
1109
1110         switch (adev->ip_versions[DCE_HWIP][0]) {
1111         case IP_VERSION(3, 1, 3):
1112         case IP_VERSION(3, 1, 4):
1113                 hw_params.dpia_supported = true;
1114                 hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
1115                 break;
1116         default:
1117                 break;
1118         }
1119
1120         status = dmub_srv_hw_init(dmub_srv, &hw_params);
1121         if (status != DMUB_STATUS_OK) {
1122                 DRM_ERROR("Error initializing DMUB HW: %d\n", status);
1123                 return -EINVAL;
1124         }
1125
1126         /* Wait for firmware load to finish. */
1127         status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1128         if (status != DMUB_STATUS_OK)
1129                 DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1130
1131         /* Init DMCU and ABM if available. */
1132         if (dmcu && abm) {
1133                 dmcu->funcs->dmcu_init(dmcu);
1134                 abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1135         }
1136
1137         if (!adev->dm.dc->ctx->dmub_srv)
1138                 adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1139         if (!adev->dm.dc->ctx->dmub_srv) {
1140                 DRM_ERROR("Couldn't allocate DC DMUB server!\n");
1141                 return -ENOMEM;
1142         }
1143
1144         DRM_INFO("DMUB hardware initialized: version=0x%08X\n",
1145                  adev->dm.dmcub_fw_version);
1146
1147         return 0;
1148 }
1149
1150 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1151 {
1152         struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1153         enum dmub_status status;
1154         bool init;
1155
1156         if (!dmub_srv) {
1157                 /* DMUB isn't supported on the ASIC. */
1158                 return;
1159         }
1160
1161         status = dmub_srv_is_hw_init(dmub_srv, &init);
1162         if (status != DMUB_STATUS_OK)
1163                 DRM_WARN("DMUB hardware init check failed: %d\n", status);
1164
1165         if (status == DMUB_STATUS_OK && init) {
1166                 /* Wait for firmware load to finish. */
1167                 status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1168                 if (status != DMUB_STATUS_OK)
1169                         DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1170         } else {
1171                 /* Perform the full hardware initialization. */
1172                 dm_dmub_hw_init(adev);
1173         }
1174 }
1175
1176 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1177 {
1178         u64 pt_base;
1179         u32 logical_addr_low;
1180         u32 logical_addr_high;
1181         u32 agp_base, agp_bot, agp_top;
1182         PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1183
1184         memset(pa_config, 0, sizeof(*pa_config));
1185
1186         logical_addr_low  = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1187         pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1188
1189         if (adev->apu_flags & AMD_APU_IS_RAVEN2)
1190                 /*
1191                  * Raven2 has a HW issue that it is unable to use the vram which
1192                  * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1193                  * workaround that increase system aperture high address (add 1)
1194                  * to get rid of the VM fault and hardware hang.
1195                  */
1196                 logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1197         else
1198                 logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1199
1200         agp_base = 0;
1201         agp_bot = adev->gmc.agp_start >> 24;
1202         agp_top = adev->gmc.agp_end >> 24;
1203
1204
1205         page_table_start.high_part = (u32)(adev->gmc.gart_start >> 44) & 0xF;
1206         page_table_start.low_part = (u32)(adev->gmc.gart_start >> 12);
1207         page_table_end.high_part = (u32)(adev->gmc.gart_end >> 44) & 0xF;
1208         page_table_end.low_part = (u32)(adev->gmc.gart_end >> 12);
1209         page_table_base.high_part = upper_32_bits(pt_base) & 0xF;
1210         page_table_base.low_part = lower_32_bits(pt_base);
1211
1212         pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1213         pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1214
1215         pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24 ;
1216         pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1217         pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1218
1219         pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1220         pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1221         pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1222
1223         pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1224         pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1225         pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1226
1227         pa_config->is_hvm_enabled = 0;
1228
1229 }
1230
1231 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1232 {
1233         struct hpd_rx_irq_offload_work *offload_work;
1234         struct amdgpu_dm_connector *aconnector;
1235         struct dc_link *dc_link;
1236         struct amdgpu_device *adev;
1237         enum dc_connection_type new_connection_type = dc_connection_none;
1238         unsigned long flags;
1239
1240         offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1241         aconnector = offload_work->offload_wq->aconnector;
1242
1243         if (!aconnector) {
1244                 DRM_ERROR("Can't retrieve aconnector in hpd_rx_irq_offload_work");
1245                 goto skip;
1246         }
1247
1248         adev = drm_to_adev(aconnector->base.dev);
1249         dc_link = aconnector->dc_link;
1250
1251         mutex_lock(&aconnector->hpd_lock);
1252         if (!dc_link_detect_sink(dc_link, &new_connection_type))
1253                 DRM_ERROR("KMS: Failed to detect connector\n");
1254         mutex_unlock(&aconnector->hpd_lock);
1255
1256         if (new_connection_type == dc_connection_none)
1257                 goto skip;
1258
1259         if (amdgpu_in_reset(adev))
1260                 goto skip;
1261
1262         mutex_lock(&adev->dm.dc_lock);
1263         if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST)
1264                 dc_link_dp_handle_automated_test(dc_link);
1265         else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1266                         hpd_rx_irq_check_link_loss_status(dc_link, &offload_work->data) &&
1267                         dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1268                 dc_link_dp_handle_link_loss(dc_link);
1269                 spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1270                 offload_work->offload_wq->is_handling_link_loss = false;
1271                 spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1272         }
1273         mutex_unlock(&adev->dm.dc_lock);
1274
1275 skip:
1276         kfree(offload_work);
1277
1278 }
1279
1280 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct dc *dc)
1281 {
1282         int max_caps = dc->caps.max_links;
1283         int i = 0;
1284         struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1285
1286         hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
1287
1288         if (!hpd_rx_offload_wq)
1289                 return NULL;
1290
1291
1292         for (i = 0; i < max_caps; i++) {
1293                 hpd_rx_offload_wq[i].wq =
1294                                     create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1295
1296                 if (hpd_rx_offload_wq[i].wq == NULL) {
1297                         DRM_ERROR("create amdgpu_dm_hpd_rx_offload_wq fail!");
1298                         goto out_err;
1299                 }
1300
1301                 spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1302         }
1303
1304         return hpd_rx_offload_wq;
1305
1306 out_err:
1307         for (i = 0; i < max_caps; i++) {
1308                 if (hpd_rx_offload_wq[i].wq)
1309                         destroy_workqueue(hpd_rx_offload_wq[i].wq);
1310         }
1311         kfree(hpd_rx_offload_wq);
1312         return NULL;
1313 }
1314
1315 struct amdgpu_stutter_quirk {
1316         u16 chip_vendor;
1317         u16 chip_device;
1318         u16 subsys_vendor;
1319         u16 subsys_device;
1320         u8 revision;
1321 };
1322
1323 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1324         /* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1325         { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1326         { 0, 0, 0, 0, 0 },
1327 };
1328
1329 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1330 {
1331         const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1332
1333         while (p && p->chip_device != 0) {
1334                 if (pdev->vendor == p->chip_vendor &&
1335                     pdev->device == p->chip_device &&
1336                     pdev->subsystem_vendor == p->subsys_vendor &&
1337                     pdev->subsystem_device == p->subsys_device &&
1338                     pdev->revision == p->revision) {
1339                         return true;
1340                 }
1341                 ++p;
1342         }
1343         return false;
1344 }
1345
1346 static const struct dmi_system_id hpd_disconnect_quirk_table[] = {
1347         {
1348                 .matches = {
1349                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1350                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3660"),
1351                 },
1352         },
1353         {
1354                 .matches = {
1355                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1356                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3260"),
1357                 },
1358         },
1359         {
1360                 .matches = {
1361                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1362                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3460"),
1363                 },
1364         },
1365         {
1366                 .matches = {
1367                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1368                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower Plus 7010"),
1369                 },
1370         },
1371         {
1372                 .matches = {
1373                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1374                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower 7010"),
1375                 },
1376         },
1377         {
1378                 .matches = {
1379                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1380                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF Plus 7010"),
1381                 },
1382         },
1383         {
1384                 .matches = {
1385                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1386                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF 7010"),
1387                 },
1388         },
1389         {
1390                 .matches = {
1391                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1392                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro Plus 7010"),
1393                 },
1394         },
1395         {
1396                 .matches = {
1397                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1398                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro 7010"),
1399                 },
1400         },
1401         {}
1402         /* TODO: refactor this from a fixed table to a dynamic option */
1403 };
1404
1405 static void retrieve_dmi_info(struct amdgpu_display_manager *dm)
1406 {
1407         const struct dmi_system_id *dmi_id;
1408
1409         dm->aux_hpd_discon_quirk = false;
1410
1411         dmi_id = dmi_first_match(hpd_disconnect_quirk_table);
1412         if (dmi_id) {
1413                 dm->aux_hpd_discon_quirk = true;
1414                 DRM_INFO("aux_hpd_discon_quirk attached\n");
1415         }
1416 }
1417
1418 static int amdgpu_dm_init(struct amdgpu_device *adev)
1419 {
1420         struct dc_init_data init_data;
1421 #ifdef CONFIG_DRM_AMD_DC_HDCP
1422         struct dc_callback_init init_params;
1423 #endif
1424         int r;
1425
1426         adev->dm.ddev = adev_to_drm(adev);
1427         adev->dm.adev = adev;
1428
1429         /* Zero all the fields */
1430         memset(&init_data, 0, sizeof(init_data));
1431 #ifdef CONFIG_DRM_AMD_DC_HDCP
1432         memset(&init_params, 0, sizeof(init_params));
1433 #endif
1434
1435         mutex_init(&adev->dm.dpia_aux_lock);
1436         mutex_init(&adev->dm.dc_lock);
1437         mutex_init(&adev->dm.audio_lock);
1438
1439         if(amdgpu_dm_irq_init(adev)) {
1440                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
1441                 goto error;
1442         }
1443
1444         init_data.asic_id.chip_family = adev->family;
1445
1446         init_data.asic_id.pci_revision_id = adev->pdev->revision;
1447         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1448         init_data.asic_id.chip_id = adev->pdev->device;
1449
1450         init_data.asic_id.vram_width = adev->gmc.vram_width;
1451         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
1452         init_data.asic_id.atombios_base_address =
1453                 adev->mode_info.atom_context->bios;
1454
1455         init_data.driver = adev;
1456
1457         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
1458
1459         if (!adev->dm.cgs_device) {
1460                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
1461                 goto error;
1462         }
1463
1464         init_data.cgs_device = adev->dm.cgs_device;
1465
1466         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1467
1468         switch (adev->ip_versions[DCE_HWIP][0]) {
1469         case IP_VERSION(2, 1, 0):
1470                 switch (adev->dm.dmcub_fw_version) {
1471                 case 0: /* development */
1472                 case 0x1: /* linux-firmware.git hash 6d9f399 */
1473                 case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1474                         init_data.flags.disable_dmcu = false;
1475                         break;
1476                 default:
1477                         init_data.flags.disable_dmcu = true;
1478                 }
1479                 break;
1480         case IP_VERSION(2, 0, 3):
1481                 init_data.flags.disable_dmcu = true;
1482                 break;
1483         default:
1484                 break;
1485         }
1486
1487         switch (adev->asic_type) {
1488         case CHIP_CARRIZO:
1489         case CHIP_STONEY:
1490                 init_data.flags.gpu_vm_support = true;
1491                 break;
1492         default:
1493                 switch (adev->ip_versions[DCE_HWIP][0]) {
1494                 case IP_VERSION(1, 0, 0):
1495                 case IP_VERSION(1, 0, 1):
1496                         /* enable S/G on PCO and RV2 */
1497                         if ((adev->apu_flags & AMD_APU_IS_RAVEN2) ||
1498                             (adev->apu_flags & AMD_APU_IS_PICASSO))
1499                                 init_data.flags.gpu_vm_support = true;
1500                         break;
1501                 case IP_VERSION(2, 1, 0):
1502                 case IP_VERSION(3, 0, 1):
1503                 case IP_VERSION(3, 1, 2):
1504                 case IP_VERSION(3, 1, 3):
1505                 case IP_VERSION(3, 1, 6):
1506                         init_data.flags.gpu_vm_support = true;
1507                         break;
1508                 default:
1509                         break;
1510                 }
1511                 break;
1512         }
1513
1514         if (init_data.flags.gpu_vm_support)
1515                 adev->mode_info.gpu_vm_support = true;
1516
1517         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1518                 init_data.flags.fbc_support = true;
1519
1520         if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1521                 init_data.flags.multi_mon_pp_mclk_switch = true;
1522
1523         if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1524                 init_data.flags.disable_fractional_pwm = true;
1525
1526         if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1527                 init_data.flags.edp_no_power_sequencing = true;
1528
1529         if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1530                 init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1531         if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1532                 init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1533
1534         init_data.flags.seamless_boot_edp_requested = false;
1535
1536         if (check_seamless_boot_capability(adev)) {
1537                 init_data.flags.seamless_boot_edp_requested = true;
1538                 init_data.flags.allow_seamless_boot_optimization = true;
1539                 DRM_INFO("Seamless boot condition check passed\n");
1540         }
1541
1542         init_data.flags.enable_mipi_converter_optimization = true;
1543
1544         init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1545         init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1546
1547         INIT_LIST_HEAD(&adev->dm.da_list);
1548
1549         retrieve_dmi_info(&adev->dm);
1550
1551         /* Display Core create. */
1552         adev->dm.dc = dc_create(&init_data);
1553
1554         if (adev->dm.dc) {
1555                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
1556         } else {
1557                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
1558                 goto error;
1559         }
1560
1561         if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
1562                 adev->dm.dc->debug.force_single_disp_pipe_split = false;
1563                 adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
1564         }
1565
1566         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
1567                 adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
1568         if (dm_should_disable_stutter(adev->pdev))
1569                 adev->dm.dc->debug.disable_stutter = true;
1570
1571         if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
1572                 adev->dm.dc->debug.disable_stutter = true;
1573
1574         if (amdgpu_dc_debug_mask & DC_DISABLE_DSC) {
1575                 adev->dm.dc->debug.disable_dsc = true;
1576         }
1577
1578         if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
1579                 adev->dm.dc->debug.disable_clock_gate = true;
1580
1581         if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
1582                 adev->dm.dc->debug.force_subvp_mclk_switch = true;
1583
1584         adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
1585
1586         /* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
1587         adev->dm.dc->debug.ignore_cable_id = true;
1588
1589         r = dm_dmub_hw_init(adev);
1590         if (r) {
1591                 DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
1592                 goto error;
1593         }
1594
1595         dc_hardware_init(adev->dm.dc);
1596
1597         adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev->dm.dc);
1598         if (!adev->dm.hpd_rx_offload_wq) {
1599                 DRM_ERROR("amdgpu: failed to create hpd rx offload workqueue.\n");
1600                 goto error;
1601         }
1602
1603         if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
1604                 struct dc_phy_addr_space_config pa_config;
1605
1606                 mmhub_read_system_context(adev, &pa_config);
1607
1608                 // Call the DC init_memory func
1609                 dc_setup_system_context(adev->dm.dc, &pa_config);
1610         }
1611
1612         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
1613         if (!adev->dm.freesync_module) {
1614                 DRM_ERROR(
1615                 "amdgpu: failed to initialize freesync_module.\n");
1616         } else
1617                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
1618                                 adev->dm.freesync_module);
1619
1620         amdgpu_dm_init_color_mod();
1621
1622         if (adev->dm.dc->caps.max_links > 0) {
1623                 adev->dm.vblank_control_workqueue =
1624                         create_singlethread_workqueue("dm_vblank_control_workqueue");
1625                 if (!adev->dm.vblank_control_workqueue)
1626                         DRM_ERROR("amdgpu: failed to initialize vblank_workqueue.\n");
1627         }
1628
1629 #ifdef CONFIG_DRM_AMD_DC_HDCP
1630         if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
1631                 adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
1632
1633                 if (!adev->dm.hdcp_workqueue)
1634                         DRM_ERROR("amdgpu: failed to initialize hdcp_workqueue.\n");
1635                 else
1636                         DRM_DEBUG_DRIVER("amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
1637
1638                 dc_init_callbacks(adev->dm.dc, &init_params);
1639         }
1640 #endif
1641 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1642         adev->dm.secure_display_ctxs = amdgpu_dm_crtc_secure_display_create_contexts(adev);
1643         if (!adev->dm.secure_display_ctxs) {
1644                 DRM_ERROR("amdgpu: failed to initialize secure_display_ctxs.\n");
1645         }
1646 #endif
1647         if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1648                 init_completion(&adev->dm.dmub_aux_transfer_done);
1649                 adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
1650                 if (!adev->dm.dmub_notify) {
1651                         DRM_INFO("amdgpu: fail to allocate adev->dm.dmub_notify");
1652                         goto error;
1653                 }
1654
1655                 adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
1656                 if (!adev->dm.delayed_hpd_wq) {
1657                         DRM_ERROR("amdgpu: failed to create hpd offload workqueue.\n");
1658                         goto error;
1659                 }
1660
1661                 amdgpu_dm_outbox_init(adev);
1662                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
1663                         dmub_aux_setconfig_callback, false)) {
1664                         DRM_ERROR("amdgpu: fail to register dmub aux callback");
1665                         goto error;
1666                 }
1667                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD, dmub_hpd_callback, true)) {
1668                         DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1669                         goto error;
1670                 }
1671                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ, dmub_hpd_callback, true)) {
1672                         DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1673                         goto error;
1674                 }
1675         }
1676
1677         /* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
1678          * It is expected that DMUB will resend any pending notifications at this point, for
1679          * example HPD from DPIA.
1680          */
1681         if (dc_is_dmub_outbox_supported(adev->dm.dc))
1682                 dc_enable_dmub_outbox(adev->dm.dc);
1683
1684         if (amdgpu_dm_initialize_drm_device(adev)) {
1685                 DRM_ERROR(
1686                 "amdgpu: failed to initialize sw for display support.\n");
1687                 goto error;
1688         }
1689
1690         /* create fake encoders for MST */
1691         dm_dp_create_fake_mst_encoders(adev);
1692
1693         /* TODO: Add_display_info? */
1694
1695         /* TODO use dynamic cursor width */
1696         adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
1697         adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
1698
1699         if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
1700                 DRM_ERROR(
1701                 "amdgpu: failed to initialize sw for display support.\n");
1702                 goto error;
1703         }
1704
1705
1706         DRM_DEBUG_DRIVER("KMS initialized.\n");
1707
1708         return 0;
1709 error:
1710         amdgpu_dm_fini(adev);
1711
1712         return -EINVAL;
1713 }
1714
1715 static int amdgpu_dm_early_fini(void *handle)
1716 {
1717         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1718
1719         amdgpu_dm_audio_fini(adev);
1720
1721         return 0;
1722 }
1723
1724 static void amdgpu_dm_fini(struct amdgpu_device *adev)
1725 {
1726         int i;
1727
1728         if (adev->dm.vblank_control_workqueue) {
1729                 destroy_workqueue(adev->dm.vblank_control_workqueue);
1730                 adev->dm.vblank_control_workqueue = NULL;
1731         }
1732
1733         amdgpu_dm_destroy_drm_device(&adev->dm);
1734
1735 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1736         if (adev->dm.secure_display_ctxs) {
1737                 for (i = 0; i < adev->mode_info.num_crtc; i++) {
1738                         if (adev->dm.secure_display_ctxs[i].crtc) {
1739                                 flush_work(&adev->dm.secure_display_ctxs[i].notify_ta_work);
1740                                 flush_work(&adev->dm.secure_display_ctxs[i].forward_roi_work);
1741                         }
1742                 }
1743                 kfree(adev->dm.secure_display_ctxs);
1744                 adev->dm.secure_display_ctxs = NULL;
1745         }
1746 #endif
1747 #ifdef CONFIG_DRM_AMD_DC_HDCP
1748         if (adev->dm.hdcp_workqueue) {
1749                 hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
1750                 adev->dm.hdcp_workqueue = NULL;
1751         }
1752
1753         if (adev->dm.dc)
1754                 dc_deinit_callbacks(adev->dm.dc);
1755 #endif
1756
1757         dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
1758
1759         if (dc_enable_dmub_notifications(adev->dm.dc)) {
1760                 kfree(adev->dm.dmub_notify);
1761                 adev->dm.dmub_notify = NULL;
1762                 destroy_workqueue(adev->dm.delayed_hpd_wq);
1763                 adev->dm.delayed_hpd_wq = NULL;
1764         }
1765
1766         if (adev->dm.dmub_bo)
1767                 amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
1768                                       &adev->dm.dmub_bo_gpu_addr,
1769                                       &adev->dm.dmub_bo_cpu_addr);
1770
1771         if (adev->dm.hpd_rx_offload_wq) {
1772                 for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
1773                         if (adev->dm.hpd_rx_offload_wq[i].wq) {
1774                                 destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
1775                                 adev->dm.hpd_rx_offload_wq[i].wq = NULL;
1776                         }
1777                 }
1778
1779                 kfree(adev->dm.hpd_rx_offload_wq);
1780                 adev->dm.hpd_rx_offload_wq = NULL;
1781         }
1782
1783         /* DC Destroy TODO: Replace destroy DAL */
1784         if (adev->dm.dc)
1785                 dc_destroy(&adev->dm.dc);
1786         /*
1787          * TODO: pageflip, vlank interrupt
1788          *
1789          * amdgpu_dm_irq_fini(adev);
1790          */
1791
1792         if (adev->dm.cgs_device) {
1793                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
1794                 adev->dm.cgs_device = NULL;
1795         }
1796         if (adev->dm.freesync_module) {
1797                 mod_freesync_destroy(adev->dm.freesync_module);
1798                 adev->dm.freesync_module = NULL;
1799         }
1800
1801         mutex_destroy(&adev->dm.audio_lock);
1802         mutex_destroy(&adev->dm.dc_lock);
1803         mutex_destroy(&adev->dm.dpia_aux_lock);
1804
1805         return;
1806 }
1807
1808 static int load_dmcu_fw(struct amdgpu_device *adev)
1809 {
1810         const char *fw_name_dmcu = NULL;
1811         int r;
1812         const struct dmcu_firmware_header_v1_0 *hdr;
1813
1814         switch(adev->asic_type) {
1815 #if defined(CONFIG_DRM_AMD_DC_SI)
1816         case CHIP_TAHITI:
1817         case CHIP_PITCAIRN:
1818         case CHIP_VERDE:
1819         case CHIP_OLAND:
1820 #endif
1821         case CHIP_BONAIRE:
1822         case CHIP_HAWAII:
1823         case CHIP_KAVERI:
1824         case CHIP_KABINI:
1825         case CHIP_MULLINS:
1826         case CHIP_TONGA:
1827         case CHIP_FIJI:
1828         case CHIP_CARRIZO:
1829         case CHIP_STONEY:
1830         case CHIP_POLARIS11:
1831         case CHIP_POLARIS10:
1832         case CHIP_POLARIS12:
1833         case CHIP_VEGAM:
1834         case CHIP_VEGA10:
1835         case CHIP_VEGA12:
1836         case CHIP_VEGA20:
1837                 return 0;
1838         case CHIP_NAVI12:
1839                 fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
1840                 break;
1841         case CHIP_RAVEN:
1842                 if (ASICREV_IS_PICASSO(adev->external_rev_id))
1843                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1844                 else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
1845                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1846                 else
1847                         return 0;
1848                 break;
1849         default:
1850                 switch (adev->ip_versions[DCE_HWIP][0]) {
1851                 case IP_VERSION(2, 0, 2):
1852                 case IP_VERSION(2, 0, 3):
1853                 case IP_VERSION(2, 0, 0):
1854                 case IP_VERSION(2, 1, 0):
1855                 case IP_VERSION(3, 0, 0):
1856                 case IP_VERSION(3, 0, 2):
1857                 case IP_VERSION(3, 0, 3):
1858                 case IP_VERSION(3, 0, 1):
1859                 case IP_VERSION(3, 1, 2):
1860                 case IP_VERSION(3, 1, 3):
1861                 case IP_VERSION(3, 1, 4):
1862                 case IP_VERSION(3, 1, 5):
1863                 case IP_VERSION(3, 1, 6):
1864                 case IP_VERSION(3, 2, 0):
1865                 case IP_VERSION(3, 2, 1):
1866                         return 0;
1867                 default:
1868                         break;
1869                 }
1870                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1871                 return -EINVAL;
1872         }
1873
1874         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1875                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
1876                 return 0;
1877         }
1878
1879         r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, fw_name_dmcu);
1880         if (r == -ENODEV) {
1881                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
1882                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
1883                 adev->dm.fw_dmcu = NULL;
1884                 return 0;
1885         }
1886         if (r) {
1887                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
1888                         fw_name_dmcu);
1889                 amdgpu_ucode_release(&adev->dm.fw_dmcu);
1890                 return r;
1891         }
1892
1893         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
1894         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
1895         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
1896         adev->firmware.fw_size +=
1897                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1898
1899         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
1900         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
1901         adev->firmware.fw_size +=
1902                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1903
1904         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
1905
1906         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
1907
1908         return 0;
1909 }
1910
1911 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
1912 {
1913         struct amdgpu_device *adev = ctx;
1914
1915         return dm_read_reg(adev->dm.dc->ctx, address);
1916 }
1917
1918 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
1919                                      uint32_t value)
1920 {
1921         struct amdgpu_device *adev = ctx;
1922
1923         return dm_write_reg(adev->dm.dc->ctx, address, value);
1924 }
1925
1926 static int dm_dmub_sw_init(struct amdgpu_device *adev)
1927 {
1928         struct dmub_srv_create_params create_params;
1929         struct dmub_srv_region_params region_params;
1930         struct dmub_srv_region_info region_info;
1931         struct dmub_srv_fb_params fb_params;
1932         struct dmub_srv_fb_info *fb_info;
1933         struct dmub_srv *dmub_srv;
1934         const struct dmcub_firmware_header_v1_0 *hdr;
1935         enum dmub_asic dmub_asic;
1936         enum dmub_status status;
1937         int r;
1938
1939         switch (adev->ip_versions[DCE_HWIP][0]) {
1940         case IP_VERSION(2, 1, 0):
1941                 dmub_asic = DMUB_ASIC_DCN21;
1942                 break;
1943         case IP_VERSION(3, 0, 0):
1944                 dmub_asic = DMUB_ASIC_DCN30;
1945                 break;
1946         case IP_VERSION(3, 0, 1):
1947                 dmub_asic = DMUB_ASIC_DCN301;
1948                 break;
1949         case IP_VERSION(3, 0, 2):
1950                 dmub_asic = DMUB_ASIC_DCN302;
1951                 break;
1952         case IP_VERSION(3, 0, 3):
1953                 dmub_asic = DMUB_ASIC_DCN303;
1954                 break;
1955         case IP_VERSION(3, 1, 2):
1956         case IP_VERSION(3, 1, 3):
1957                 dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
1958                 break;
1959         case IP_VERSION(3, 1, 4):
1960                 dmub_asic = DMUB_ASIC_DCN314;
1961                 break;
1962         case IP_VERSION(3, 1, 5):
1963                 dmub_asic = DMUB_ASIC_DCN315;
1964                 break;
1965         case IP_VERSION(3, 1, 6):
1966                 dmub_asic = DMUB_ASIC_DCN316;
1967                 break;
1968         case IP_VERSION(3, 2, 0):
1969                 dmub_asic = DMUB_ASIC_DCN32;
1970                 break;
1971         case IP_VERSION(3, 2, 1):
1972                 dmub_asic = DMUB_ASIC_DCN321;
1973                 break;
1974         default:
1975                 /* ASIC doesn't support DMUB. */
1976                 return 0;
1977         }
1978
1979         hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
1980         adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
1981
1982         if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
1983                 adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
1984                         AMDGPU_UCODE_ID_DMCUB;
1985                 adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
1986                         adev->dm.dmub_fw;
1987                 adev->firmware.fw_size +=
1988                         ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
1989
1990                 DRM_INFO("Loading DMUB firmware via PSP: version=0x%08X\n",
1991                          adev->dm.dmcub_fw_version);
1992         }
1993
1994
1995         adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
1996         dmub_srv = adev->dm.dmub_srv;
1997
1998         if (!dmub_srv) {
1999                 DRM_ERROR("Failed to allocate DMUB service!\n");
2000                 return -ENOMEM;
2001         }
2002
2003         memset(&create_params, 0, sizeof(create_params));
2004         create_params.user_ctx = adev;
2005         create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2006         create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2007         create_params.asic = dmub_asic;
2008
2009         /* Create the DMUB service. */
2010         status = dmub_srv_create(dmub_srv, &create_params);
2011         if (status != DMUB_STATUS_OK) {
2012                 DRM_ERROR("Error creating DMUB service: %d\n", status);
2013                 return -EINVAL;
2014         }
2015
2016         /* Calculate the size of all the regions for the DMUB service. */
2017         memset(&region_params, 0, sizeof(region_params));
2018
2019         region_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2020                                         PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
2021         region_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2022         region_params.vbios_size = adev->bios_size;
2023         region_params.fw_bss_data = region_params.bss_data_size ?
2024                 adev->dm.dmub_fw->data +
2025                 le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2026                 le32_to_cpu(hdr->inst_const_bytes) : NULL;
2027         region_params.fw_inst_const =
2028                 adev->dm.dmub_fw->data +
2029                 le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2030                 PSP_HEADER_BYTES;
2031
2032         status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2033                                            &region_info);
2034
2035         if (status != DMUB_STATUS_OK) {
2036                 DRM_ERROR("Error calculating DMUB region info: %d\n", status);
2037                 return -EINVAL;
2038         }
2039
2040         /*
2041          * Allocate a framebuffer based on the total size of all the regions.
2042          * TODO: Move this into GART.
2043          */
2044         r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2045                                     AMDGPU_GEM_DOMAIN_VRAM |
2046                                     AMDGPU_GEM_DOMAIN_GTT,
2047                                     &adev->dm.dmub_bo,
2048                                     &adev->dm.dmub_bo_gpu_addr,
2049                                     &adev->dm.dmub_bo_cpu_addr);
2050         if (r)
2051                 return r;
2052
2053         /* Rebase the regions on the framebuffer address. */
2054         memset(&fb_params, 0, sizeof(fb_params));
2055         fb_params.cpu_addr = adev->dm.dmub_bo_cpu_addr;
2056         fb_params.gpu_addr = adev->dm.dmub_bo_gpu_addr;
2057         fb_params.region_info = &region_info;
2058
2059         adev->dm.dmub_fb_info =
2060                 kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2061         fb_info = adev->dm.dmub_fb_info;
2062
2063         if (!fb_info) {
2064                 DRM_ERROR(
2065                         "Failed to allocate framebuffer info for DMUB service!\n");
2066                 return -ENOMEM;
2067         }
2068
2069         status = dmub_srv_calc_fb_info(dmub_srv, &fb_params, fb_info);
2070         if (status != DMUB_STATUS_OK) {
2071                 DRM_ERROR("Error calculating DMUB FB info: %d\n", status);
2072                 return -EINVAL;
2073         }
2074
2075         return 0;
2076 }
2077
2078 static int dm_sw_init(void *handle)
2079 {
2080         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2081         int r;
2082
2083         r = dm_dmub_sw_init(adev);
2084         if (r)
2085                 return r;
2086
2087         return load_dmcu_fw(adev);
2088 }
2089
2090 static int dm_sw_fini(void *handle)
2091 {
2092         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2093
2094         kfree(adev->dm.dmub_fb_info);
2095         adev->dm.dmub_fb_info = NULL;
2096
2097         if (adev->dm.dmub_srv) {
2098                 dmub_srv_destroy(adev->dm.dmub_srv);
2099                 adev->dm.dmub_srv = NULL;
2100         }
2101
2102         amdgpu_ucode_release(&adev->dm.dmub_fw);
2103         amdgpu_ucode_release(&adev->dm.fw_dmcu);
2104
2105         return 0;
2106 }
2107
2108 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2109 {
2110         struct amdgpu_dm_connector *aconnector;
2111         struct drm_connector *connector;
2112         struct drm_connector_list_iter iter;
2113         int ret = 0;
2114
2115         drm_connector_list_iter_begin(dev, &iter);
2116         drm_for_each_connector_iter(connector, &iter) {
2117                 aconnector = to_amdgpu_dm_connector(connector);
2118                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
2119                     aconnector->mst_mgr.aux) {
2120                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
2121                                          aconnector,
2122                                          aconnector->base.base.id);
2123
2124                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2125                         if (ret < 0) {
2126                                 DRM_ERROR("DM_MST: Failed to start MST\n");
2127                                 aconnector->dc_link->type =
2128                                         dc_connection_single;
2129                                 ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2130                                                                      aconnector->dc_link);
2131                                 break;
2132                         }
2133                 }
2134         }
2135         drm_connector_list_iter_end(&iter);
2136
2137         return ret;
2138 }
2139
2140 static int dm_late_init(void *handle)
2141 {
2142         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2143
2144         struct dmcu_iram_parameters params;
2145         unsigned int linear_lut[16];
2146         int i;
2147         struct dmcu *dmcu = NULL;
2148
2149         dmcu = adev->dm.dc->res_pool->dmcu;
2150
2151         for (i = 0; i < 16; i++)
2152                 linear_lut[i] = 0xFFFF * i / 15;
2153
2154         params.set = 0;
2155         params.backlight_ramping_override = false;
2156         params.backlight_ramping_start = 0xCCCC;
2157         params.backlight_ramping_reduction = 0xCCCCCCCC;
2158         params.backlight_lut_array_size = 16;
2159         params.backlight_lut_array = linear_lut;
2160
2161         /* Min backlight level after ABM reduction,  Don't allow below 1%
2162          * 0xFFFF x 0.01 = 0x28F
2163          */
2164         params.min_abm_backlight = 0x28F;
2165         /* In the case where abm is implemented on dmcub,
2166         * dmcu object will be null.
2167         * ABM 2.4 and up are implemented on dmcub.
2168         */
2169         if (dmcu) {
2170                 if (!dmcu_load_iram(dmcu, params))
2171                         return -EINVAL;
2172         } else if (adev->dm.dc->ctx->dmub_srv) {
2173                 struct dc_link *edp_links[MAX_NUM_EDP];
2174                 int edp_num;
2175
2176                 get_edp_links(adev->dm.dc, edp_links, &edp_num);
2177                 for (i = 0; i < edp_num; i++) {
2178                         if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2179                                 return -EINVAL;
2180                 }
2181         }
2182
2183         return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2184 }
2185
2186 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2187 {
2188         struct amdgpu_dm_connector *aconnector;
2189         struct drm_connector *connector;
2190         struct drm_connector_list_iter iter;
2191         struct drm_dp_mst_topology_mgr *mgr;
2192         int ret;
2193         bool need_hotplug = false;
2194
2195         drm_connector_list_iter_begin(dev, &iter);
2196         drm_for_each_connector_iter(connector, &iter) {
2197                 aconnector = to_amdgpu_dm_connector(connector);
2198                 if (aconnector->dc_link->type != dc_connection_mst_branch ||
2199                     aconnector->mst_port)
2200                         continue;
2201
2202                 mgr = &aconnector->mst_mgr;
2203
2204                 if (suspend) {
2205                         drm_dp_mst_topology_mgr_suspend(mgr);
2206                 } else {
2207                         ret = drm_dp_mst_topology_mgr_resume(mgr, true);
2208                         if (ret < 0) {
2209                                 dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2210                                         aconnector->dc_link);
2211                                 need_hotplug = true;
2212                         }
2213                 }
2214         }
2215         drm_connector_list_iter_end(&iter);
2216
2217         if (need_hotplug)
2218                 drm_kms_helper_hotplug_event(dev);
2219 }
2220
2221 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2222 {
2223         int ret = 0;
2224
2225         /* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2226          * on window driver dc implementation.
2227          * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2228          * should be passed to smu during boot up and resume from s3.
2229          * boot up: dc calculate dcn watermark clock settings within dc_create,
2230          * dcn20_resource_construct
2231          * then call pplib functions below to pass the settings to smu:
2232          * smu_set_watermarks_for_clock_ranges
2233          * smu_set_watermarks_table
2234          * navi10_set_watermarks_table
2235          * smu_write_watermarks_table
2236          *
2237          * For Renoir, clock settings of dcn watermark are also fixed values.
2238          * dc has implemented different flow for window driver:
2239          * dc_hardware_init / dc_set_power_state
2240          * dcn10_init_hw
2241          * notify_wm_ranges
2242          * set_wm_ranges
2243          * -- Linux
2244          * smu_set_watermarks_for_clock_ranges
2245          * renoir_set_watermarks_table
2246          * smu_write_watermarks_table
2247          *
2248          * For Linux,
2249          * dc_hardware_init -> amdgpu_dm_init
2250          * dc_set_power_state --> dm_resume
2251          *
2252          * therefore, this function apply to navi10/12/14 but not Renoir
2253          * *
2254          */
2255         switch (adev->ip_versions[DCE_HWIP][0]) {
2256         case IP_VERSION(2, 0, 2):
2257         case IP_VERSION(2, 0, 0):
2258                 break;
2259         default:
2260                 return 0;
2261         }
2262
2263         ret = amdgpu_dpm_write_watermarks_table(adev);
2264         if (ret) {
2265                 DRM_ERROR("Failed to update WMTABLE!\n");
2266                 return ret;
2267         }
2268
2269         return 0;
2270 }
2271
2272 /**
2273  * dm_hw_init() - Initialize DC device
2274  * @handle: The base driver device containing the amdgpu_dm device.
2275  *
2276  * Initialize the &struct amdgpu_display_manager device. This involves calling
2277  * the initializers of each DM component, then populating the struct with them.
2278  *
2279  * Although the function implies hardware initialization, both hardware and
2280  * software are initialized here. Splitting them out to their relevant init
2281  * hooks is a future TODO item.
2282  *
2283  * Some notable things that are initialized here:
2284  *
2285  * - Display Core, both software and hardware
2286  * - DC modules that we need (freesync and color management)
2287  * - DRM software states
2288  * - Interrupt sources and handlers
2289  * - Vblank support
2290  * - Debug FS entries, if enabled
2291  */
2292 static int dm_hw_init(void *handle)
2293 {
2294         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2295         /* Create DAL display manager */
2296         amdgpu_dm_init(adev);
2297         amdgpu_dm_hpd_init(adev);
2298
2299         return 0;
2300 }
2301
2302 /**
2303  * dm_hw_fini() - Teardown DC device
2304  * @handle: The base driver device containing the amdgpu_dm device.
2305  *
2306  * Teardown components within &struct amdgpu_display_manager that require
2307  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
2308  * were loaded. Also flush IRQ workqueues and disable them.
2309  */
2310 static int dm_hw_fini(void *handle)
2311 {
2312         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2313
2314         amdgpu_dm_hpd_fini(adev);
2315
2316         amdgpu_dm_irq_fini(adev);
2317         amdgpu_dm_fini(adev);
2318         return 0;
2319 }
2320
2321
2322 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
2323                                  struct dc_state *state, bool enable)
2324 {
2325         enum dc_irq_source irq_source;
2326         struct amdgpu_crtc *acrtc;
2327         int rc = -EBUSY;
2328         int i = 0;
2329
2330         for (i = 0; i < state->stream_count; i++) {
2331                 acrtc = get_crtc_by_otg_inst(
2332                                 adev, state->stream_status[i].primary_otg_inst);
2333
2334                 if (acrtc && state->stream_status[i].plane_count != 0) {
2335                         irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
2336                         rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2337                         DRM_DEBUG_VBL("crtc %d - vupdate irq %sabling: r=%d\n",
2338                                       acrtc->crtc_id, enable ? "en" : "dis", rc);
2339                         if (rc)
2340                                 DRM_WARN("Failed to %s pflip interrupts\n",
2341                                          enable ? "enable" : "disable");
2342
2343                         if (enable) {
2344                                 rc = dm_enable_vblank(&acrtc->base);
2345                                 if (rc)
2346                                         DRM_WARN("Failed to enable vblank interrupts\n");
2347                         } else {
2348                                 dm_disable_vblank(&acrtc->base);
2349                         }
2350
2351                 }
2352         }
2353
2354 }
2355
2356 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
2357 {
2358         struct dc_state *context = NULL;
2359         enum dc_status res = DC_ERROR_UNEXPECTED;
2360         int i;
2361         struct dc_stream_state *del_streams[MAX_PIPES];
2362         int del_streams_count = 0;
2363
2364         memset(del_streams, 0, sizeof(del_streams));
2365
2366         context = dc_create_state(dc);
2367         if (context == NULL)
2368                 goto context_alloc_fail;
2369
2370         dc_resource_state_copy_construct_current(dc, context);
2371
2372         /* First remove from context all streams */
2373         for (i = 0; i < context->stream_count; i++) {
2374                 struct dc_stream_state *stream = context->streams[i];
2375
2376                 del_streams[del_streams_count++] = stream;
2377         }
2378
2379         /* Remove all planes for removed streams and then remove the streams */
2380         for (i = 0; i < del_streams_count; i++) {
2381                 if (!dc_rem_all_planes_for_stream(dc, del_streams[i], context)) {
2382                         res = DC_FAIL_DETACH_SURFACES;
2383                         goto fail;
2384                 }
2385
2386                 res = dc_remove_stream_from_ctx(dc, context, del_streams[i]);
2387                 if (res != DC_OK)
2388                         goto fail;
2389         }
2390
2391         res = dc_commit_state(dc, context);
2392
2393 fail:
2394         dc_release_state(context);
2395
2396 context_alloc_fail:
2397         return res;
2398 }
2399
2400 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
2401 {
2402         int i;
2403
2404         if (dm->hpd_rx_offload_wq) {
2405                 for (i = 0; i < dm->dc->caps.max_links; i++)
2406                         flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
2407         }
2408 }
2409
2410 static int dm_suspend(void *handle)
2411 {
2412         struct amdgpu_device *adev = handle;
2413         struct amdgpu_display_manager *dm = &adev->dm;
2414         int ret = 0;
2415
2416         if (amdgpu_in_reset(adev)) {
2417                 mutex_lock(&dm->dc_lock);
2418
2419                 dc_allow_idle_optimizations(adev->dm.dc, false);
2420
2421                 dm->cached_dc_state = dc_copy_state(dm->dc->current_state);
2422
2423                 dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
2424
2425                 amdgpu_dm_commit_zero_streams(dm->dc);
2426
2427                 amdgpu_dm_irq_suspend(adev);
2428
2429                 hpd_rx_irq_work_suspend(dm);
2430
2431                 return ret;
2432         }
2433
2434         WARN_ON(adev->dm.cached_state);
2435         adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
2436
2437         s3_handle_mst(adev_to_drm(adev), true);
2438
2439         amdgpu_dm_irq_suspend(adev);
2440
2441         hpd_rx_irq_work_suspend(dm);
2442
2443         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
2444
2445         return 0;
2446 }
2447
2448 struct amdgpu_dm_connector *
2449 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
2450                                              struct drm_crtc *crtc)
2451 {
2452         u32 i;
2453         struct drm_connector_state *new_con_state;
2454         struct drm_connector *connector;
2455         struct drm_crtc *crtc_from_state;
2456
2457         for_each_new_connector_in_state(state, connector, new_con_state, i) {
2458                 crtc_from_state = new_con_state->crtc;
2459
2460                 if (crtc_from_state == crtc)
2461                         return to_amdgpu_dm_connector(connector);
2462         }
2463
2464         return NULL;
2465 }
2466
2467 static void emulated_link_detect(struct dc_link *link)
2468 {
2469         struct dc_sink_init_data sink_init_data = { 0 };
2470         struct display_sink_capability sink_caps = { 0 };
2471         enum dc_edid_status edid_status;
2472         struct dc_context *dc_ctx = link->ctx;
2473         struct dc_sink *sink = NULL;
2474         struct dc_sink *prev_sink = NULL;
2475
2476         link->type = dc_connection_none;
2477         prev_sink = link->local_sink;
2478
2479         if (prev_sink)
2480                 dc_sink_release(prev_sink);
2481
2482         switch (link->connector_signal) {
2483         case SIGNAL_TYPE_HDMI_TYPE_A: {
2484                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2485                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
2486                 break;
2487         }
2488
2489         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
2490                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2491                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
2492                 break;
2493         }
2494
2495         case SIGNAL_TYPE_DVI_DUAL_LINK: {
2496                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2497                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
2498                 break;
2499         }
2500
2501         case SIGNAL_TYPE_LVDS: {
2502                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2503                 sink_caps.signal = SIGNAL_TYPE_LVDS;
2504                 break;
2505         }
2506
2507         case SIGNAL_TYPE_EDP: {
2508                 sink_caps.transaction_type =
2509                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2510                 sink_caps.signal = SIGNAL_TYPE_EDP;
2511                 break;
2512         }
2513
2514         case SIGNAL_TYPE_DISPLAY_PORT: {
2515                 sink_caps.transaction_type =
2516                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2517                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
2518                 break;
2519         }
2520
2521         default:
2522                 DC_ERROR("Invalid connector type! signal:%d\n",
2523                         link->connector_signal);
2524                 return;
2525         }
2526
2527         sink_init_data.link = link;
2528         sink_init_data.sink_signal = sink_caps.signal;
2529
2530         sink = dc_sink_create(&sink_init_data);
2531         if (!sink) {
2532                 DC_ERROR("Failed to create sink!\n");
2533                 return;
2534         }
2535
2536         /* dc_sink_create returns a new reference */
2537         link->local_sink = sink;
2538
2539         edid_status = dm_helpers_read_local_edid(
2540                         link->ctx,
2541                         link,
2542                         sink);
2543
2544         if (edid_status != EDID_OK)
2545                 DC_ERROR("Failed to read EDID");
2546
2547 }
2548
2549 static void dm_gpureset_commit_state(struct dc_state *dc_state,
2550                                      struct amdgpu_display_manager *dm)
2551 {
2552         struct {
2553                 struct dc_surface_update surface_updates[MAX_SURFACES];
2554                 struct dc_plane_info plane_infos[MAX_SURFACES];
2555                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
2556                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
2557                 struct dc_stream_update stream_update;
2558         } * bundle;
2559         int k, m;
2560
2561         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
2562
2563         if (!bundle) {
2564                 dm_error("Failed to allocate update bundle\n");
2565                 goto cleanup;
2566         }
2567
2568         for (k = 0; k < dc_state->stream_count; k++) {
2569                 bundle->stream_update.stream = dc_state->streams[k];
2570
2571                 for (m = 0; m < dc_state->stream_status->plane_count; m++) {
2572                         bundle->surface_updates[m].surface =
2573                                 dc_state->stream_status->plane_states[m];
2574                         bundle->surface_updates[m].surface->force_full_update =
2575                                 true;
2576                 }
2577                 dc_commit_updates_for_stream(
2578                         dm->dc, bundle->surface_updates,
2579                         dc_state->stream_status->plane_count,
2580                         dc_state->streams[k], &bundle->stream_update, dc_state);
2581         }
2582
2583 cleanup:
2584         kfree(bundle);
2585
2586         return;
2587 }
2588
2589 static int dm_resume(void *handle)
2590 {
2591         struct amdgpu_device *adev = handle;
2592         struct drm_device *ddev = adev_to_drm(adev);
2593         struct amdgpu_display_manager *dm = &adev->dm;
2594         struct amdgpu_dm_connector *aconnector;
2595         struct drm_connector *connector;
2596         struct drm_connector_list_iter iter;
2597         struct drm_crtc *crtc;
2598         struct drm_crtc_state *new_crtc_state;
2599         struct dm_crtc_state *dm_new_crtc_state;
2600         struct drm_plane *plane;
2601         struct drm_plane_state *new_plane_state;
2602         struct dm_plane_state *dm_new_plane_state;
2603         struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
2604         enum dc_connection_type new_connection_type = dc_connection_none;
2605         struct dc_state *dc_state;
2606         int i, r, j;
2607
2608         if (amdgpu_in_reset(adev)) {
2609                 dc_state = dm->cached_dc_state;
2610
2611                 /*
2612                  * The dc->current_state is backed up into dm->cached_dc_state
2613                  * before we commit 0 streams.
2614                  *
2615                  * DC will clear link encoder assignments on the real state
2616                  * but the changes won't propagate over to the copy we made
2617                  * before the 0 streams commit.
2618                  *
2619                  * DC expects that link encoder assignments are *not* valid
2620                  * when committing a state, so as a workaround we can copy
2621                  * off of the current state.
2622                  *
2623                  * We lose the previous assignments, but we had already
2624                  * commit 0 streams anyway.
2625                  */
2626                 link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
2627
2628                 r = dm_dmub_hw_init(adev);
2629                 if (r)
2630                         DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
2631
2632                 dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2633                 dc_resume(dm->dc);
2634
2635                 amdgpu_dm_irq_resume_early(adev);
2636
2637                 for (i = 0; i < dc_state->stream_count; i++) {
2638                         dc_state->streams[i]->mode_changed = true;
2639                         for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
2640                                 dc_state->stream_status[i].plane_states[j]->update_flags.raw
2641                                         = 0xffffffff;
2642                         }
2643                 }
2644
2645                 if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2646                         amdgpu_dm_outbox_init(adev);
2647                         dc_enable_dmub_outbox(adev->dm.dc);
2648                 }
2649
2650                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
2651
2652                 dm_gpureset_commit_state(dm->cached_dc_state, dm);
2653
2654                 dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
2655
2656                 dc_release_state(dm->cached_dc_state);
2657                 dm->cached_dc_state = NULL;
2658
2659                 amdgpu_dm_irq_resume_late(adev);
2660
2661                 mutex_unlock(&dm->dc_lock);
2662
2663                 return 0;
2664         }
2665         /* Recreate dc_state - DC invalidates it when setting power state to S3. */
2666         dc_release_state(dm_state->context);
2667         dm_state->context = dc_create_state(dm->dc);
2668         /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
2669         dc_resource_state_construct(dm->dc, dm_state->context);
2670
2671         /* Before powering on DC we need to re-initialize DMUB. */
2672         dm_dmub_hw_resume(adev);
2673
2674         /* Re-enable outbox interrupts for DPIA. */
2675         if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2676                 amdgpu_dm_outbox_init(adev);
2677                 dc_enable_dmub_outbox(adev->dm.dc);
2678         }
2679
2680         /* power on hardware */
2681         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2682
2683         /* program HPD filter */
2684         dc_resume(dm->dc);
2685
2686         /*
2687          * early enable HPD Rx IRQ, should be done before set mode as short
2688          * pulse interrupts are used for MST
2689          */
2690         amdgpu_dm_irq_resume_early(adev);
2691
2692         /* On resume we need to rewrite the MSTM control bits to enable MST*/
2693         s3_handle_mst(ddev, false);
2694
2695         /* Do detection*/
2696         drm_connector_list_iter_begin(ddev, &iter);
2697         drm_for_each_connector_iter(connector, &iter) {
2698                 aconnector = to_amdgpu_dm_connector(connector);
2699
2700                 if (!aconnector->dc_link)
2701                         continue;
2702
2703                 /*
2704                  * this is the case when traversing through already created
2705                  * MST connectors, should be skipped
2706                  */
2707                 if (aconnector->dc_link->type == dc_connection_mst_branch)
2708                         continue;
2709
2710                 mutex_lock(&aconnector->hpd_lock);
2711                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
2712                         DRM_ERROR("KMS: Failed to detect connector\n");
2713
2714                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
2715                         emulated_link_detect(aconnector->dc_link);
2716                 } else {
2717                         mutex_lock(&dm->dc_lock);
2718                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
2719                         mutex_unlock(&dm->dc_lock);
2720                 }
2721
2722                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2723                         aconnector->fake_enable = false;
2724
2725                 if (aconnector->dc_sink)
2726                         dc_sink_release(aconnector->dc_sink);
2727                 aconnector->dc_sink = NULL;
2728                 amdgpu_dm_update_connector_after_detect(aconnector);
2729                 mutex_unlock(&aconnector->hpd_lock);
2730         }
2731         drm_connector_list_iter_end(&iter);
2732
2733         /* Force mode set in atomic commit */
2734         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
2735                 new_crtc_state->active_changed = true;
2736
2737         /*
2738          * atomic_check is expected to create the dc states. We need to release
2739          * them here, since they were duplicated as part of the suspend
2740          * procedure.
2741          */
2742         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
2743                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
2744                 if (dm_new_crtc_state->stream) {
2745                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
2746                         dc_stream_release(dm_new_crtc_state->stream);
2747                         dm_new_crtc_state->stream = NULL;
2748                 }
2749         }
2750
2751         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
2752                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
2753                 if (dm_new_plane_state->dc_state) {
2754                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
2755                         dc_plane_state_release(dm_new_plane_state->dc_state);
2756                         dm_new_plane_state->dc_state = NULL;
2757                 }
2758         }
2759
2760         drm_atomic_helper_resume(ddev, dm->cached_state);
2761
2762         dm->cached_state = NULL;
2763
2764         amdgpu_dm_irq_resume_late(adev);
2765
2766         amdgpu_dm_smu_write_watermarks_table(adev);
2767
2768         return 0;
2769 }
2770
2771 /**
2772  * DOC: DM Lifecycle
2773  *
2774  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
2775  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
2776  * the base driver's device list to be initialized and torn down accordingly.
2777  *
2778  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
2779  */
2780
2781 static const struct amd_ip_funcs amdgpu_dm_funcs = {
2782         .name = "dm",
2783         .early_init = dm_early_init,
2784         .late_init = dm_late_init,
2785         .sw_init = dm_sw_init,
2786         .sw_fini = dm_sw_fini,
2787         .early_fini = amdgpu_dm_early_fini,
2788         .hw_init = dm_hw_init,
2789         .hw_fini = dm_hw_fini,
2790         .suspend = dm_suspend,
2791         .resume = dm_resume,
2792         .is_idle = dm_is_idle,
2793         .wait_for_idle = dm_wait_for_idle,
2794         .check_soft_reset = dm_check_soft_reset,
2795         .soft_reset = dm_soft_reset,
2796         .set_clockgating_state = dm_set_clockgating_state,
2797         .set_powergating_state = dm_set_powergating_state,
2798 };
2799
2800 const struct amdgpu_ip_block_version dm_ip_block =
2801 {
2802         .type = AMD_IP_BLOCK_TYPE_DCE,
2803         .major = 1,
2804         .minor = 0,
2805         .rev = 0,
2806         .funcs = &amdgpu_dm_funcs,
2807 };
2808
2809
2810 /**
2811  * DOC: atomic
2812  *
2813  * *WIP*
2814  */
2815
2816 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
2817         .fb_create = amdgpu_display_user_framebuffer_create,
2818         .get_format_info = amd_get_format_info,
2819         .atomic_check = amdgpu_dm_atomic_check,
2820         .atomic_commit = drm_atomic_helper_commit,
2821 };
2822
2823 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2824         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2825         .atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
2826 };
2827
2828 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
2829 {
2830         struct amdgpu_dm_backlight_caps *caps;
2831         struct amdgpu_display_manager *dm;
2832         struct drm_connector *conn_base;
2833         struct amdgpu_device *adev;
2834         struct dc_link *link = NULL;
2835         struct drm_luminance_range_info *luminance_range;
2836         int i;
2837
2838         if (!aconnector || !aconnector->dc_link)
2839                 return;
2840
2841         link = aconnector->dc_link;
2842         if (link->connector_signal != SIGNAL_TYPE_EDP)
2843                 return;
2844
2845         conn_base = &aconnector->base;
2846         adev = drm_to_adev(conn_base->dev);
2847         dm = &adev->dm;
2848         for (i = 0; i < dm->num_of_edps; i++) {
2849                 if (link == dm->backlight_link[i])
2850                         break;
2851         }
2852         if (i >= dm->num_of_edps)
2853                 return;
2854         caps = &dm->backlight_caps[i];
2855         caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
2856         caps->aux_support = false;
2857
2858         if (caps->ext_caps->bits.oled == 1 /*||
2859             caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
2860             caps->ext_caps->bits.hdr_aux_backlight_control == 1*/)
2861                 caps->aux_support = true;
2862
2863         if (amdgpu_backlight == 0)
2864                 caps->aux_support = false;
2865         else if (amdgpu_backlight == 1)
2866                 caps->aux_support = true;
2867
2868         luminance_range = &conn_base->display_info.luminance_range;
2869         caps->aux_min_input_signal = luminance_range->min_luminance;
2870         caps->aux_max_input_signal = luminance_range->max_luminance;
2871 }
2872
2873 void amdgpu_dm_update_connector_after_detect(
2874                 struct amdgpu_dm_connector *aconnector)
2875 {
2876         struct drm_connector *connector = &aconnector->base;
2877         struct drm_device *dev = connector->dev;
2878         struct dc_sink *sink;
2879
2880         /* MST handled by drm_mst framework */
2881         if (aconnector->mst_mgr.mst_state == true)
2882                 return;
2883
2884         sink = aconnector->dc_link->local_sink;
2885         if (sink)
2886                 dc_sink_retain(sink);
2887
2888         /*
2889          * Edid mgmt connector gets first update only in mode_valid hook and then
2890          * the connector sink is set to either fake or physical sink depends on link status.
2891          * Skip if already done during boot.
2892          */
2893         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
2894                         && aconnector->dc_em_sink) {
2895
2896                 /*
2897                  * For S3 resume with headless use eml_sink to fake stream
2898                  * because on resume connector->sink is set to NULL
2899                  */
2900                 mutex_lock(&dev->mode_config.mutex);
2901
2902                 if (sink) {
2903                         if (aconnector->dc_sink) {
2904                                 amdgpu_dm_update_freesync_caps(connector, NULL);
2905                                 /*
2906                                  * retain and release below are used to
2907                                  * bump up refcount for sink because the link doesn't point
2908                                  * to it anymore after disconnect, so on next crtc to connector
2909                                  * reshuffle by UMD we will get into unwanted dc_sink release
2910                                  */
2911                                 dc_sink_release(aconnector->dc_sink);
2912                         }
2913                         aconnector->dc_sink = sink;
2914                         dc_sink_retain(aconnector->dc_sink);
2915                         amdgpu_dm_update_freesync_caps(connector,
2916                                         aconnector->edid);
2917                 } else {
2918                         amdgpu_dm_update_freesync_caps(connector, NULL);
2919                         if (!aconnector->dc_sink) {
2920                                 aconnector->dc_sink = aconnector->dc_em_sink;
2921                                 dc_sink_retain(aconnector->dc_sink);
2922                         }
2923                 }
2924
2925                 mutex_unlock(&dev->mode_config.mutex);
2926
2927                 if (sink)
2928                         dc_sink_release(sink);
2929                 return;
2930         }
2931
2932         /*
2933          * TODO: temporary guard to look for proper fix
2934          * if this sink is MST sink, we should not do anything
2935          */
2936         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
2937                 dc_sink_release(sink);
2938                 return;
2939         }
2940
2941         if (aconnector->dc_sink == sink) {
2942                 /*
2943                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
2944                  * Do nothing!!
2945                  */
2946                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
2947                                 aconnector->connector_id);
2948                 if (sink)
2949                         dc_sink_release(sink);
2950                 return;
2951         }
2952
2953         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
2954                 aconnector->connector_id, aconnector->dc_sink, sink);
2955
2956         mutex_lock(&dev->mode_config.mutex);
2957
2958         /*
2959          * 1. Update status of the drm connector
2960          * 2. Send an event and let userspace tell us what to do
2961          */
2962         if (sink) {
2963                 /*
2964                  * TODO: check if we still need the S3 mode update workaround.
2965                  * If yes, put it here.
2966                  */
2967                 if (aconnector->dc_sink) {
2968                         amdgpu_dm_update_freesync_caps(connector, NULL);
2969                         dc_sink_release(aconnector->dc_sink);
2970                 }
2971
2972                 aconnector->dc_sink = sink;
2973                 dc_sink_retain(aconnector->dc_sink);
2974                 if (sink->dc_edid.length == 0) {
2975                         aconnector->edid = NULL;
2976                         if (aconnector->dc_link->aux_mode) {
2977                                 drm_dp_cec_unset_edid(
2978                                         &aconnector->dm_dp_aux.aux);
2979                         }
2980                 } else {
2981                         aconnector->edid =
2982                                 (struct edid *)sink->dc_edid.raw_edid;
2983
2984                         if (aconnector->dc_link->aux_mode)
2985                                 drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
2986                                                     aconnector->edid);
2987                 }
2988
2989                 drm_connector_update_edid_property(connector, aconnector->edid);
2990                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
2991                 update_connector_ext_caps(aconnector);
2992         } else {
2993                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
2994                 amdgpu_dm_update_freesync_caps(connector, NULL);
2995                 drm_connector_update_edid_property(connector, NULL);
2996                 aconnector->num_modes = 0;
2997                 dc_sink_release(aconnector->dc_sink);
2998                 aconnector->dc_sink = NULL;
2999                 aconnector->edid = NULL;
3000 #ifdef CONFIG_DRM_AMD_DC_HDCP
3001                 /* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3002                 if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3003                         connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3004 #endif
3005         }
3006
3007         mutex_unlock(&dev->mode_config.mutex);
3008
3009         update_subconnector_property(aconnector);
3010
3011         if (sink)
3012                 dc_sink_release(sink);
3013 }
3014
3015 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3016 {
3017         struct drm_connector *connector = &aconnector->base;
3018         struct drm_device *dev = connector->dev;
3019         enum dc_connection_type new_connection_type = dc_connection_none;
3020         struct amdgpu_device *adev = drm_to_adev(dev);
3021 #ifdef CONFIG_DRM_AMD_DC_HDCP
3022         struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3023 #endif
3024         bool ret = false;
3025
3026         if (adev->dm.disable_hpd_irq)
3027                 return;
3028
3029         /*
3030          * In case of failure or MST no need to update connector status or notify the OS
3031          * since (for MST case) MST does this in its own context.
3032          */
3033         mutex_lock(&aconnector->hpd_lock);
3034
3035 #ifdef CONFIG_DRM_AMD_DC_HDCP
3036         if (adev->dm.hdcp_workqueue) {
3037                 hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3038                 dm_con_state->update_hdcp = true;
3039         }
3040 #endif
3041         if (aconnector->fake_enable)
3042                 aconnector->fake_enable = false;
3043
3044         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
3045                 DRM_ERROR("KMS: Failed to detect connector\n");
3046
3047         if (aconnector->base.force && new_connection_type == dc_connection_none) {
3048                 emulated_link_detect(aconnector->dc_link);
3049
3050                 drm_modeset_lock_all(dev);
3051                 dm_restore_drm_connector_state(dev, connector);
3052                 drm_modeset_unlock_all(dev);
3053
3054                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3055                         drm_kms_helper_connector_hotplug_event(connector);
3056         } else {
3057                 mutex_lock(&adev->dm.dc_lock);
3058                 ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3059                 mutex_unlock(&adev->dm.dc_lock);
3060                 if (ret) {
3061                         amdgpu_dm_update_connector_after_detect(aconnector);
3062
3063                         drm_modeset_lock_all(dev);
3064                         dm_restore_drm_connector_state(dev, connector);
3065                         drm_modeset_unlock_all(dev);
3066
3067                         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3068                                 drm_kms_helper_connector_hotplug_event(connector);
3069                 }
3070         }
3071         mutex_unlock(&aconnector->hpd_lock);
3072
3073 }
3074
3075 static void handle_hpd_irq(void *param)
3076 {
3077         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3078
3079         handle_hpd_irq_helper(aconnector);
3080
3081 }
3082
3083 static void dm_handle_mst_sideband_msg(struct amdgpu_dm_connector *aconnector)
3084 {
3085         u8 esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
3086         u8 dret;
3087         bool new_irq_handled = false;
3088         int dpcd_addr;
3089         int dpcd_bytes_to_read;
3090
3091         const int max_process_count = 30;
3092         int process_count = 0;
3093
3094         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
3095
3096         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
3097                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
3098                 /* DPCD 0x200 - 0x201 for downstream IRQ */
3099                 dpcd_addr = DP_SINK_COUNT;
3100         } else {
3101                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
3102                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
3103                 dpcd_addr = DP_SINK_COUNT_ESI;
3104         }
3105
3106         dret = drm_dp_dpcd_read(
3107                 &aconnector->dm_dp_aux.aux,
3108                 dpcd_addr,
3109                 esi,
3110                 dpcd_bytes_to_read);
3111
3112         while (dret == dpcd_bytes_to_read &&
3113                 process_count < max_process_count) {
3114                 u8 retry;
3115                 dret = 0;
3116
3117                 process_count++;
3118
3119                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
3120                 /* handle HPD short pulse irq */
3121                 if (aconnector->mst_mgr.mst_state)
3122                         drm_dp_mst_hpd_irq(
3123                                 &aconnector->mst_mgr,
3124                                 esi,
3125                                 &new_irq_handled);
3126
3127                 if (new_irq_handled) {
3128                         /* ACK at DPCD to notify down stream */
3129                         const int ack_dpcd_bytes_to_write =
3130                                 dpcd_bytes_to_read - 1;
3131
3132                         for (retry = 0; retry < 3; retry++) {
3133                                 u8 wret;
3134
3135                                 wret = drm_dp_dpcd_write(
3136                                         &aconnector->dm_dp_aux.aux,
3137                                         dpcd_addr + 1,
3138                                         &esi[1],
3139                                         ack_dpcd_bytes_to_write);
3140                                 if (wret == ack_dpcd_bytes_to_write)
3141                                         break;
3142                         }
3143
3144                         /* check if there is new irq to be handled */
3145                         dret = drm_dp_dpcd_read(
3146                                 &aconnector->dm_dp_aux.aux,
3147                                 dpcd_addr,
3148                                 esi,
3149                                 dpcd_bytes_to_read);
3150
3151                         new_irq_handled = false;
3152                 } else {
3153                         break;
3154                 }
3155         }
3156
3157         if (process_count == max_process_count)
3158                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
3159 }
3160
3161 static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
3162                                                         union hpd_irq_data hpd_irq_data)
3163 {
3164         struct hpd_rx_irq_offload_work *offload_work =
3165                                 kzalloc(sizeof(*offload_work), GFP_KERNEL);
3166
3167         if (!offload_work) {
3168                 DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
3169                 return;
3170         }
3171
3172         INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3173         offload_work->data = hpd_irq_data;
3174         offload_work->offload_wq = offload_wq;
3175
3176         queue_work(offload_wq->wq, &offload_work->work);
3177         DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3178 }
3179
3180 static void handle_hpd_rx_irq(void *param)
3181 {
3182         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3183         struct drm_connector *connector = &aconnector->base;
3184         struct drm_device *dev = connector->dev;
3185         struct dc_link *dc_link = aconnector->dc_link;
3186         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3187         bool result = false;
3188         enum dc_connection_type new_connection_type = dc_connection_none;
3189         struct amdgpu_device *adev = drm_to_adev(dev);
3190         union hpd_irq_data hpd_irq_data;
3191         bool link_loss = false;
3192         bool has_left_work = false;
3193         int idx = aconnector->base.index;
3194         struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3195
3196         memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3197
3198         if (adev->dm.disable_hpd_irq)
3199                 return;
3200
3201         /*
3202          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3203          * conflict, after implement i2c helper, this mutex should be
3204          * retired.
3205          */
3206         mutex_lock(&aconnector->hpd_lock);
3207
3208         result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3209                                                 &link_loss, true, &has_left_work);
3210
3211         if (!has_left_work)
3212                 goto out;
3213
3214         if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3215                 schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3216                 goto out;
3217         }
3218
3219         if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3220                 if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3221                         hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3222                         dm_handle_mst_sideband_msg(aconnector);
3223                         goto out;
3224                 }
3225
3226                 if (link_loss) {
3227                         bool skip = false;
3228
3229                         spin_lock(&offload_wq->offload_lock);
3230                         skip = offload_wq->is_handling_link_loss;
3231
3232                         if (!skip)
3233                                 offload_wq->is_handling_link_loss = true;
3234
3235                         spin_unlock(&offload_wq->offload_lock);
3236
3237                         if (!skip)
3238                                 schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3239
3240                         goto out;
3241                 }
3242         }
3243
3244 out:
3245         if (result && !is_mst_root_connector) {
3246                 /* Downstream Port status changed. */
3247                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
3248                         DRM_ERROR("KMS: Failed to detect connector\n");
3249
3250                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
3251                         emulated_link_detect(dc_link);
3252
3253                         if (aconnector->fake_enable)
3254                                 aconnector->fake_enable = false;
3255
3256                         amdgpu_dm_update_connector_after_detect(aconnector);
3257
3258
3259                         drm_modeset_lock_all(dev);
3260                         dm_restore_drm_connector_state(dev, connector);
3261                         drm_modeset_unlock_all(dev);
3262
3263                         drm_kms_helper_connector_hotplug_event(connector);
3264                 } else {
3265                         bool ret = false;
3266
3267                         mutex_lock(&adev->dm.dc_lock);
3268                         ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
3269                         mutex_unlock(&adev->dm.dc_lock);
3270
3271                         if (ret) {
3272                                 if (aconnector->fake_enable)
3273                                         aconnector->fake_enable = false;
3274
3275                                 amdgpu_dm_update_connector_after_detect(aconnector);
3276
3277                                 drm_modeset_lock_all(dev);
3278                                 dm_restore_drm_connector_state(dev, connector);
3279                                 drm_modeset_unlock_all(dev);
3280
3281                                 drm_kms_helper_connector_hotplug_event(connector);
3282                         }
3283                 }
3284         }
3285 #ifdef CONFIG_DRM_AMD_DC_HDCP
3286         if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
3287                 if (adev->dm.hdcp_workqueue)
3288                         hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
3289         }
3290 #endif
3291
3292         if (dc_link->type != dc_connection_mst_branch)
3293                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
3294
3295         mutex_unlock(&aconnector->hpd_lock);
3296 }
3297
3298 static void register_hpd_handlers(struct amdgpu_device *adev)
3299 {
3300         struct drm_device *dev = adev_to_drm(adev);
3301         struct drm_connector *connector;
3302         struct amdgpu_dm_connector *aconnector;
3303         const struct dc_link *dc_link;
3304         struct dc_interrupt_params int_params = {0};
3305
3306         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3307         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3308
3309         list_for_each_entry(connector,
3310                         &dev->mode_config.connector_list, head) {
3311
3312                 aconnector = to_amdgpu_dm_connector(connector);
3313                 dc_link = aconnector->dc_link;
3314
3315                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
3316                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3317                         int_params.irq_source = dc_link->irq_source_hpd;
3318
3319                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
3320                                         handle_hpd_irq,
3321                                         (void *) aconnector);
3322                 }
3323
3324                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
3325
3326                         /* Also register for DP short pulse (hpd_rx). */
3327                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3328                         int_params.irq_source = dc_link->irq_source_hpd_rx;
3329
3330                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
3331                                         handle_hpd_rx_irq,
3332                                         (void *) aconnector);
3333
3334                         if (adev->dm.hpd_rx_offload_wq)
3335                                 adev->dm.hpd_rx_offload_wq[connector->index].aconnector =
3336                                         aconnector;
3337                 }
3338         }
3339 }
3340
3341 #if defined(CONFIG_DRM_AMD_DC_SI)
3342 /* Register IRQ sources and initialize IRQ callbacks */
3343 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
3344 {
3345         struct dc *dc = adev->dm.dc;
3346         struct common_irq_params *c_irq_params;
3347         struct dc_interrupt_params int_params = {0};
3348         int r;
3349         int i;
3350         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3351
3352         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3353         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3354
3355         /*
3356          * Actions of amdgpu_irq_add_id():
3357          * 1. Register a set() function with base driver.
3358          *    Base driver will call set() function to enable/disable an
3359          *    interrupt in DC hardware.
3360          * 2. Register amdgpu_dm_irq_handler().
3361          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3362          *    coming from DC hardware.
3363          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3364          *    for acknowledging and handling. */
3365
3366         /* Use VBLANK interrupt */
3367         for (i = 0; i < adev->mode_info.num_crtc; i++) {
3368                 r = amdgpu_irq_add_id(adev, client_id, i+1 , &adev->crtc_irq);
3369                 if (r) {
3370                         DRM_ERROR("Failed to add crtc irq id!\n");
3371                         return r;
3372                 }
3373
3374                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3375                 int_params.irq_source =
3376                         dc_interrupt_to_irq_source(dc, i+1 , 0);
3377
3378                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3379
3380                 c_irq_params->adev = adev;
3381                 c_irq_params->irq_src = int_params.irq_source;
3382
3383                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3384                                 dm_crtc_high_irq, c_irq_params);
3385         }
3386
3387         /* Use GRPH_PFLIP interrupt */
3388         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3389                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3390                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3391                 if (r) {
3392                         DRM_ERROR("Failed to add page flip irq id!\n");
3393                         return r;
3394                 }
3395
3396                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3397                 int_params.irq_source =
3398                         dc_interrupt_to_irq_source(dc, i, 0);
3399
3400                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3401
3402                 c_irq_params->adev = adev;
3403                 c_irq_params->irq_src = int_params.irq_source;
3404
3405                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3406                                 dm_pflip_high_irq, c_irq_params);
3407
3408         }
3409
3410         /* HPD */
3411         r = amdgpu_irq_add_id(adev, client_id,
3412                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3413         if (r) {
3414                 DRM_ERROR("Failed to add hpd irq id!\n");
3415                 return r;
3416         }
3417
3418         register_hpd_handlers(adev);
3419
3420         return 0;
3421 }
3422 #endif
3423
3424 /* Register IRQ sources and initialize IRQ callbacks */
3425 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
3426 {
3427         struct dc *dc = adev->dm.dc;
3428         struct common_irq_params *c_irq_params;
3429         struct dc_interrupt_params int_params = {0};
3430         int r;
3431         int i;
3432         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3433
3434         if (adev->family >= AMDGPU_FAMILY_AI)
3435                 client_id = SOC15_IH_CLIENTID_DCE;
3436
3437         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3438         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3439
3440         /*
3441          * Actions of amdgpu_irq_add_id():
3442          * 1. Register a set() function with base driver.
3443          *    Base driver will call set() function to enable/disable an
3444          *    interrupt in DC hardware.
3445          * 2. Register amdgpu_dm_irq_handler().
3446          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3447          *    coming from DC hardware.
3448          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3449          *    for acknowledging and handling. */
3450
3451         /* Use VBLANK interrupt */
3452         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
3453                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
3454                 if (r) {
3455                         DRM_ERROR("Failed to add crtc irq id!\n");
3456                         return r;
3457                 }
3458
3459                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3460                 int_params.irq_source =
3461                         dc_interrupt_to_irq_source(dc, i, 0);
3462
3463                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3464
3465                 c_irq_params->adev = adev;
3466                 c_irq_params->irq_src = int_params.irq_source;
3467
3468                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3469                                 dm_crtc_high_irq, c_irq_params);
3470         }
3471
3472         /* Use VUPDATE interrupt */
3473         for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
3474                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
3475                 if (r) {
3476                         DRM_ERROR("Failed to add vupdate irq id!\n");
3477                         return r;
3478                 }
3479
3480                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3481                 int_params.irq_source =
3482                         dc_interrupt_to_irq_source(dc, i, 0);
3483
3484                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3485
3486                 c_irq_params->adev = adev;
3487                 c_irq_params->irq_src = int_params.irq_source;
3488
3489                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3490                                 dm_vupdate_high_irq, c_irq_params);
3491         }
3492
3493         /* Use GRPH_PFLIP interrupt */
3494         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3495                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3496                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3497                 if (r) {
3498                         DRM_ERROR("Failed to add page flip irq id!\n");
3499                         return r;
3500                 }
3501
3502                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3503                 int_params.irq_source =
3504                         dc_interrupt_to_irq_source(dc, i, 0);
3505
3506                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3507
3508                 c_irq_params->adev = adev;
3509                 c_irq_params->irq_src = int_params.irq_source;
3510
3511                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3512                                 dm_pflip_high_irq, c_irq_params);
3513
3514         }
3515
3516         /* HPD */
3517         r = amdgpu_irq_add_id(adev, client_id,
3518                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3519         if (r) {
3520                 DRM_ERROR("Failed to add hpd irq id!\n");
3521                 return r;
3522         }
3523
3524         register_hpd_handlers(adev);
3525
3526         return 0;
3527 }
3528
3529 /* Register IRQ sources and initialize IRQ callbacks */
3530 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
3531 {
3532         struct dc *dc = adev->dm.dc;
3533         struct common_irq_params *c_irq_params;
3534         struct dc_interrupt_params int_params = {0};
3535         int r;
3536         int i;
3537 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3538         static const unsigned int vrtl_int_srcid[] = {
3539                 DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
3540                 DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
3541                 DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
3542                 DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
3543                 DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
3544                 DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
3545         };
3546 #endif
3547
3548         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3549         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3550
3551         /*
3552          * Actions of amdgpu_irq_add_id():
3553          * 1. Register a set() function with base driver.
3554          *    Base driver will call set() function to enable/disable an
3555          *    interrupt in DC hardware.
3556          * 2. Register amdgpu_dm_irq_handler().
3557          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3558          *    coming from DC hardware.
3559          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3560          *    for acknowledging and handling.
3561          */
3562
3563         /* Use VSTARTUP interrupt */
3564         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
3565                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
3566                         i++) {
3567                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
3568
3569                 if (r) {
3570                         DRM_ERROR("Failed to add crtc irq id!\n");
3571                         return r;
3572                 }
3573
3574                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3575                 int_params.irq_source =
3576                         dc_interrupt_to_irq_source(dc, i, 0);
3577
3578                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3579
3580                 c_irq_params->adev = adev;
3581                 c_irq_params->irq_src = int_params.irq_source;
3582
3583                 amdgpu_dm_irq_register_interrupt(
3584                         adev, &int_params, dm_crtc_high_irq, c_irq_params);
3585         }
3586
3587         /* Use otg vertical line interrupt */
3588 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3589         for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
3590                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
3591                                 vrtl_int_srcid[i], &adev->vline0_irq);
3592
3593                 if (r) {
3594                         DRM_ERROR("Failed to add vline0 irq id!\n");
3595                         return r;
3596                 }
3597
3598                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3599                 int_params.irq_source =
3600                         dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
3601
3602                 if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
3603                         DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
3604                         break;
3605                 }
3606
3607                 c_irq_params = &adev->dm.vline0_params[int_params.irq_source
3608                                         - DC_IRQ_SOURCE_DC1_VLINE0];
3609
3610                 c_irq_params->adev = adev;
3611                 c_irq_params->irq_src = int_params.irq_source;
3612
3613                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3614                                 dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
3615         }
3616 #endif
3617
3618         /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
3619          * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
3620          * to trigger at end of each vblank, regardless of state of the lock,
3621          * matching DCE behaviour.
3622          */
3623         for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
3624              i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
3625              i++) {
3626                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
3627
3628                 if (r) {
3629                         DRM_ERROR("Failed to add vupdate irq id!\n");
3630                         return r;
3631                 }
3632
3633                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3634                 int_params.irq_source =
3635                         dc_interrupt_to_irq_source(dc, i, 0);
3636
3637                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3638
3639                 c_irq_params->adev = adev;
3640                 c_irq_params->irq_src = int_params.irq_source;
3641
3642                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3643                                 dm_vupdate_high_irq, c_irq_params);
3644         }
3645
3646         /* Use GRPH_PFLIP interrupt */
3647         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
3648                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
3649                         i++) {
3650                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
3651                 if (r) {
3652                         DRM_ERROR("Failed to add page flip irq id!\n");
3653                         return r;
3654                 }
3655
3656                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3657                 int_params.irq_source =
3658                         dc_interrupt_to_irq_source(dc, i, 0);
3659
3660                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3661
3662                 c_irq_params->adev = adev;
3663                 c_irq_params->irq_src = int_params.irq_source;
3664
3665                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3666                                 dm_pflip_high_irq, c_irq_params);
3667
3668         }
3669
3670         /* HPD */
3671         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
3672                         &adev->hpd_irq);
3673         if (r) {
3674                 DRM_ERROR("Failed to add hpd irq id!\n");
3675                 return r;
3676         }
3677
3678         register_hpd_handlers(adev);
3679
3680         return 0;
3681 }
3682 /* Register Outbox IRQ sources and initialize IRQ callbacks */
3683 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
3684 {
3685         struct dc *dc = adev->dm.dc;
3686         struct common_irq_params *c_irq_params;
3687         struct dc_interrupt_params int_params = {0};
3688         int r, i;
3689
3690         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3691         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3692
3693         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
3694                         &adev->dmub_outbox_irq);
3695         if (r) {
3696                 DRM_ERROR("Failed to add outbox irq id!\n");
3697                 return r;
3698         }
3699
3700         if (dc->ctx->dmub_srv) {
3701                 i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
3702                 int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3703                 int_params.irq_source =
3704                 dc_interrupt_to_irq_source(dc, i, 0);
3705
3706                 c_irq_params = &adev->dm.dmub_outbox_params[0];
3707
3708                 c_irq_params->adev = adev;
3709                 c_irq_params->irq_src = int_params.irq_source;
3710
3711                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3712                                 dm_dmub_outbox1_low_irq, c_irq_params);
3713         }
3714
3715         return 0;
3716 }
3717
3718 /*
3719  * Acquires the lock for the atomic state object and returns
3720  * the new atomic state.
3721  *
3722  * This should only be called during atomic check.
3723  */
3724 int dm_atomic_get_state(struct drm_atomic_state *state,
3725                         struct dm_atomic_state **dm_state)
3726 {
3727         struct drm_device *dev = state->dev;
3728         struct amdgpu_device *adev = drm_to_adev(dev);
3729         struct amdgpu_display_manager *dm = &adev->dm;
3730         struct drm_private_state *priv_state;
3731
3732         if (*dm_state)
3733                 return 0;
3734
3735         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
3736         if (IS_ERR(priv_state))
3737                 return PTR_ERR(priv_state);
3738
3739         *dm_state = to_dm_atomic_state(priv_state);
3740
3741         return 0;
3742 }
3743
3744 static struct dm_atomic_state *
3745 dm_atomic_get_new_state(struct drm_atomic_state *state)
3746 {
3747         struct drm_device *dev = state->dev;
3748         struct amdgpu_device *adev = drm_to_adev(dev);
3749         struct amdgpu_display_manager *dm = &adev->dm;
3750         struct drm_private_obj *obj;
3751         struct drm_private_state *new_obj_state;
3752         int i;
3753
3754         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
3755                 if (obj->funcs == dm->atomic_obj.funcs)
3756                         return to_dm_atomic_state(new_obj_state);
3757         }
3758
3759         return NULL;
3760 }
3761
3762 static struct drm_private_state *
3763 dm_atomic_duplicate_state(struct drm_private_obj *obj)
3764 {
3765         struct dm_atomic_state *old_state, *new_state;
3766
3767         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
3768         if (!new_state)
3769                 return NULL;
3770
3771         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
3772
3773         old_state = to_dm_atomic_state(obj->state);
3774
3775         if (old_state && old_state->context)
3776                 new_state->context = dc_copy_state(old_state->context);
3777
3778         if (!new_state->context) {
3779                 kfree(new_state);
3780                 return NULL;
3781         }
3782
3783         return &new_state->base;
3784 }
3785
3786 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
3787                                     struct drm_private_state *state)
3788 {
3789         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3790
3791         if (dm_state && dm_state->context)
3792                 dc_release_state(dm_state->context);
3793
3794         kfree(dm_state);
3795 }
3796
3797 static struct drm_private_state_funcs dm_atomic_state_funcs = {
3798         .atomic_duplicate_state = dm_atomic_duplicate_state,
3799         .atomic_destroy_state = dm_atomic_destroy_state,
3800 };
3801
3802 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
3803 {
3804         struct dm_atomic_state *state;
3805         int r;
3806
3807         adev->mode_info.mode_config_initialized = true;
3808
3809         adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
3810         adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
3811
3812         adev_to_drm(adev)->mode_config.max_width = 16384;
3813         adev_to_drm(adev)->mode_config.max_height = 16384;
3814
3815         adev_to_drm(adev)->mode_config.preferred_depth = 24;
3816         if (adev->asic_type == CHIP_HAWAII)
3817                 /* disable prefer shadow for now due to hibernation issues */
3818                 adev_to_drm(adev)->mode_config.prefer_shadow = 0;
3819         else
3820                 adev_to_drm(adev)->mode_config.prefer_shadow = 1;
3821         /* indicates support for immediate flip */
3822         adev_to_drm(adev)->mode_config.async_page_flip = true;
3823
3824         state = kzalloc(sizeof(*state), GFP_KERNEL);
3825         if (!state)
3826                 return -ENOMEM;
3827
3828         state->context = dc_create_state(adev->dm.dc);
3829         if (!state->context) {
3830                 kfree(state);
3831                 return -ENOMEM;
3832         }
3833
3834         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
3835
3836         drm_atomic_private_obj_init(adev_to_drm(adev),
3837                                     &adev->dm.atomic_obj,
3838                                     &state->base,
3839                                     &dm_atomic_state_funcs);
3840
3841         r = amdgpu_display_modeset_create_props(adev);
3842         if (r) {
3843                 dc_release_state(state->context);
3844                 kfree(state);
3845                 return r;
3846         }
3847
3848         r = amdgpu_dm_audio_init(adev);
3849         if (r) {
3850                 dc_release_state(state->context);
3851                 kfree(state);
3852                 return r;
3853         }
3854
3855         return 0;
3856 }
3857
3858 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
3859 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
3860 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
3861
3862 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
3863                                             int bl_idx)
3864 {
3865 #if defined(CONFIG_ACPI)
3866         struct amdgpu_dm_backlight_caps caps;
3867
3868         memset(&caps, 0, sizeof(caps));
3869
3870         if (dm->backlight_caps[bl_idx].caps_valid)
3871                 return;
3872
3873         amdgpu_acpi_get_backlight_caps(&caps);
3874         if (caps.caps_valid) {
3875                 dm->backlight_caps[bl_idx].caps_valid = true;
3876                 if (caps.aux_support)
3877                         return;
3878                 dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
3879                 dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
3880         } else {
3881                 dm->backlight_caps[bl_idx].min_input_signal =
3882                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3883                 dm->backlight_caps[bl_idx].max_input_signal =
3884                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3885         }
3886 #else
3887         if (dm->backlight_caps[bl_idx].aux_support)
3888                 return;
3889
3890         dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3891         dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3892 #endif
3893 }
3894
3895 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
3896                                 unsigned *min, unsigned *max)
3897 {
3898         if (!caps)
3899                 return 0;
3900
3901         if (caps->aux_support) {
3902                 // Firmware limits are in nits, DC API wants millinits.
3903                 *max = 1000 * caps->aux_max_input_signal;
3904                 *min = 1000 * caps->aux_min_input_signal;
3905         } else {
3906                 // Firmware limits are 8-bit, PWM control is 16-bit.
3907                 *max = 0x101 * caps->max_input_signal;
3908                 *min = 0x101 * caps->min_input_signal;
3909         }
3910         return 1;
3911 }
3912
3913 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
3914                                         uint32_t brightness)
3915 {
3916         unsigned min, max;
3917
3918         if (!get_brightness_range(caps, &min, &max))
3919                 return brightness;
3920
3921         // Rescale 0..255 to min..max
3922         return min + DIV_ROUND_CLOSEST((max - min) * brightness,
3923                                        AMDGPU_MAX_BL_LEVEL);
3924 }
3925
3926 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
3927                                       uint32_t brightness)
3928 {
3929         unsigned min, max;
3930
3931         if (!get_brightness_range(caps, &min, &max))
3932                 return brightness;
3933
3934         if (brightness < min)
3935                 return 0;
3936         // Rescale min..max to 0..255
3937         return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
3938                                  max - min);
3939 }
3940
3941 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
3942                                          int bl_idx,
3943                                          u32 user_brightness)
3944 {
3945         struct amdgpu_dm_backlight_caps caps;
3946         struct dc_link *link;
3947         u32 brightness;
3948         bool rc;
3949
3950         amdgpu_dm_update_backlight_caps(dm, bl_idx);
3951         caps = dm->backlight_caps[bl_idx];
3952
3953         dm->brightness[bl_idx] = user_brightness;
3954         /* update scratch register */
3955         if (bl_idx == 0)
3956                 amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
3957         brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
3958         link = (struct dc_link *)dm->backlight_link[bl_idx];
3959
3960         /* Change brightness based on AUX property */
3961         if (caps.aux_support) {
3962                 rc = dc_link_set_backlight_level_nits(link, true, brightness,
3963                                                       AUX_BL_DEFAULT_TRANSITION_TIME_MS);
3964                 if (!rc)
3965                         DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
3966         } else {
3967                 rc = dc_link_set_backlight_level(link, brightness, 0);
3968                 if (!rc)
3969                         DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
3970         }
3971
3972         if (rc)
3973                 dm->actual_brightness[bl_idx] = user_brightness;
3974 }
3975
3976 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
3977 {
3978         struct amdgpu_display_manager *dm = bl_get_data(bd);
3979         int i;
3980
3981         for (i = 0; i < dm->num_of_edps; i++) {
3982                 if (bd == dm->backlight_dev[i])
3983                         break;
3984         }
3985         if (i >= AMDGPU_DM_MAX_NUM_EDP)
3986                 i = 0;
3987         amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
3988
3989         return 0;
3990 }
3991
3992 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
3993                                          int bl_idx)
3994 {
3995         struct amdgpu_dm_backlight_caps caps;
3996         struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
3997
3998         amdgpu_dm_update_backlight_caps(dm, bl_idx);
3999         caps = dm->backlight_caps[bl_idx];
4000
4001         if (caps.aux_support) {
4002                 u32 avg, peak;
4003                 bool rc;
4004
4005                 rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
4006                 if (!rc)
4007                         return dm->brightness[bl_idx];
4008                 return convert_brightness_to_user(&caps, avg);
4009         } else {
4010                 int ret = dc_link_get_backlight_level(link);
4011
4012                 if (ret == DC_ERROR_UNEXPECTED)
4013                         return dm->brightness[bl_idx];
4014                 return convert_brightness_to_user(&caps, ret);
4015         }
4016 }
4017
4018 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
4019 {
4020         struct amdgpu_display_manager *dm = bl_get_data(bd);
4021         int i;
4022
4023         for (i = 0; i < dm->num_of_edps; i++) {
4024                 if (bd == dm->backlight_dev[i])
4025                         break;
4026         }
4027         if (i >= AMDGPU_DM_MAX_NUM_EDP)
4028                 i = 0;
4029         return amdgpu_dm_backlight_get_level(dm, i);
4030 }
4031
4032 static const struct backlight_ops amdgpu_dm_backlight_ops = {
4033         .options = BL_CORE_SUSPENDRESUME,
4034         .get_brightness = amdgpu_dm_backlight_get_brightness,
4035         .update_status  = amdgpu_dm_backlight_update_status,
4036 };
4037
4038 static void
4039 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
4040 {
4041         char bl_name[16];
4042         struct backlight_properties props = { 0 };
4043
4044         amdgpu_dm_update_backlight_caps(dm, dm->num_of_edps);
4045         dm->brightness[dm->num_of_edps] = AMDGPU_MAX_BL_LEVEL;
4046
4047         if (!acpi_video_backlight_use_native()) {
4048                 drm_info(adev_to_drm(dm->adev), "Skipping amdgpu DM backlight registration\n");
4049                 /* Try registering an ACPI video backlight device instead. */
4050                 acpi_video_register_backlight();
4051                 return;
4052         }
4053
4054         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
4055         props.brightness = AMDGPU_MAX_BL_LEVEL;
4056         props.type = BACKLIGHT_RAW;
4057
4058         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
4059                  adev_to_drm(dm->adev)->primary->index + dm->num_of_edps);
4060
4061         dm->backlight_dev[dm->num_of_edps] = backlight_device_register(bl_name,
4062                                                                        adev_to_drm(dm->adev)->dev,
4063                                                                        dm,
4064                                                                        &amdgpu_dm_backlight_ops,
4065                                                                        &props);
4066
4067         if (IS_ERR(dm->backlight_dev[dm->num_of_edps]))
4068                 DRM_ERROR("DM: Backlight registration failed!\n");
4069         else
4070                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
4071 }
4072
4073 static int initialize_plane(struct amdgpu_display_manager *dm,
4074                             struct amdgpu_mode_info *mode_info, int plane_id,
4075                             enum drm_plane_type plane_type,
4076                             const struct dc_plane_cap *plane_cap)
4077 {
4078         struct drm_plane *plane;
4079         unsigned long possible_crtcs;
4080         int ret = 0;
4081
4082         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
4083         if (!plane) {
4084                 DRM_ERROR("KMS: Failed to allocate plane\n");
4085                 return -ENOMEM;
4086         }
4087         plane->type = plane_type;
4088
4089         /*
4090          * HACK: IGT tests expect that the primary plane for a CRTC
4091          * can only have one possible CRTC. Only expose support for
4092          * any CRTC if they're not going to be used as a primary plane
4093          * for a CRTC - like overlay or underlay planes.
4094          */
4095         possible_crtcs = 1 << plane_id;
4096         if (plane_id >= dm->dc->caps.max_streams)
4097                 possible_crtcs = 0xff;
4098
4099         ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
4100
4101         if (ret) {
4102                 DRM_ERROR("KMS: Failed to initialize plane\n");
4103                 kfree(plane);
4104                 return ret;
4105         }
4106
4107         if (mode_info)
4108                 mode_info->planes[plane_id] = plane;
4109
4110         return ret;
4111 }
4112
4113
4114 static void register_backlight_device(struct amdgpu_display_manager *dm,
4115                                       struct dc_link *link)
4116 {
4117         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4118             link->type != dc_connection_none) {
4119                 /*
4120                  * Event if registration failed, we should continue with
4121                  * DM initialization because not having a backlight control
4122                  * is better then a black screen.
4123                  */
4124                 if (!dm->backlight_dev[dm->num_of_edps])
4125                         amdgpu_dm_register_backlight_device(dm);
4126
4127                 if (dm->backlight_dev[dm->num_of_edps]) {
4128                         dm->backlight_link[dm->num_of_edps] = link;
4129                         dm->num_of_edps++;
4130                 }
4131         }
4132 }
4133
4134 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
4135
4136 /*
4137  * In this architecture, the association
4138  * connector -> encoder -> crtc
4139  * id not really requried. The crtc and connector will hold the
4140  * display_index as an abstraction to use with DAL component
4141  *
4142  * Returns 0 on success
4143  */
4144 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
4145 {
4146         struct amdgpu_display_manager *dm = &adev->dm;
4147         s32 i;
4148         struct amdgpu_dm_connector *aconnector = NULL;
4149         struct amdgpu_encoder *aencoder = NULL;
4150         struct amdgpu_mode_info *mode_info = &adev->mode_info;
4151         u32 link_cnt;
4152         s32 primary_planes;
4153         enum dc_connection_type new_connection_type = dc_connection_none;
4154         const struct dc_plane_cap *plane;
4155         bool psr_feature_enabled = false;
4156
4157         dm->display_indexes_num = dm->dc->caps.max_streams;
4158         /* Update the actual used number of crtc */
4159         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
4160
4161         link_cnt = dm->dc->caps.max_links;
4162         if (amdgpu_dm_mode_config_init(dm->adev)) {
4163                 DRM_ERROR("DM: Failed to initialize mode config\n");
4164                 return -EINVAL;
4165         }
4166
4167         /* There is one primary plane per CRTC */
4168         primary_planes = dm->dc->caps.max_streams;
4169         ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
4170
4171         /*
4172          * Initialize primary planes, implicit planes for legacy IOCTLS.
4173          * Order is reversed to match iteration order in atomic check.
4174          */
4175         for (i = (primary_planes - 1); i >= 0; i--) {
4176                 plane = &dm->dc->caps.planes[i];
4177
4178                 if (initialize_plane(dm, mode_info, i,
4179                                      DRM_PLANE_TYPE_PRIMARY, plane)) {
4180                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
4181                         goto fail;
4182                 }
4183         }
4184
4185         /*
4186          * Initialize overlay planes, index starting after primary planes.
4187          * These planes have a higher DRM index than the primary planes since
4188          * they should be considered as having a higher z-order.
4189          * Order is reversed to match iteration order in atomic check.
4190          *
4191          * Only support DCN for now, and only expose one so we don't encourage
4192          * userspace to use up all the pipes.
4193          */
4194         for (i = 0; i < dm->dc->caps.max_planes; ++i) {
4195                 struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
4196
4197                 /* Do not create overlay if MPO disabled */
4198                 if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
4199                         break;
4200
4201                 if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
4202                         continue;
4203
4204                 if (!plane->blends_with_above || !plane->blends_with_below)
4205                         continue;
4206
4207                 if (!plane->pixel_format_support.argb8888)
4208                         continue;
4209
4210                 if (initialize_plane(dm, NULL, primary_planes + i,
4211                                      DRM_PLANE_TYPE_OVERLAY, plane)) {
4212                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
4213                         goto fail;
4214                 }
4215
4216                 /* Only create one overlay plane. */
4217                 break;
4218         }
4219
4220         for (i = 0; i < dm->dc->caps.max_streams; i++)
4221                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
4222                         DRM_ERROR("KMS: Failed to initialize crtc\n");
4223                         goto fail;
4224                 }
4225
4226         /* Use Outbox interrupt */
4227         switch (adev->ip_versions[DCE_HWIP][0]) {
4228         case IP_VERSION(3, 0, 0):
4229         case IP_VERSION(3, 1, 2):
4230         case IP_VERSION(3, 1, 3):
4231         case IP_VERSION(3, 1, 4):
4232         case IP_VERSION(3, 1, 5):
4233         case IP_VERSION(3, 1, 6):
4234         case IP_VERSION(3, 2, 0):
4235         case IP_VERSION(3, 2, 1):
4236         case IP_VERSION(2, 1, 0):
4237                 if (register_outbox_irq_handlers(dm->adev)) {
4238                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4239                         goto fail;
4240                 }
4241                 break;
4242         default:
4243                 DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
4244                               adev->ip_versions[DCE_HWIP][0]);
4245         }
4246
4247         /* Determine whether to enable PSR support by default. */
4248         if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
4249                 switch (adev->ip_versions[DCE_HWIP][0]) {
4250                 case IP_VERSION(3, 1, 2):
4251                 case IP_VERSION(3, 1, 3):
4252                 case IP_VERSION(3, 1, 4):
4253                 case IP_VERSION(3, 1, 5):
4254                 case IP_VERSION(3, 1, 6):
4255                 case IP_VERSION(3, 2, 0):
4256                 case IP_VERSION(3, 2, 1):
4257                         psr_feature_enabled = true;
4258                         break;
4259                 default:
4260                         psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
4261                         break;
4262                 }
4263         }
4264
4265         /* loops over all connectors on the board */
4266         for (i = 0; i < link_cnt; i++) {
4267                 struct dc_link *link = NULL;
4268
4269                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
4270                         DRM_ERROR(
4271                                 "KMS: Cannot support more than %d display indexes\n",
4272                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
4273                         continue;
4274                 }
4275
4276                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
4277                 if (!aconnector)
4278                         goto fail;
4279
4280                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
4281                 if (!aencoder)
4282                         goto fail;
4283
4284                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
4285                         DRM_ERROR("KMS: Failed to initialize encoder\n");
4286                         goto fail;
4287                 }
4288
4289                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
4290                         DRM_ERROR("KMS: Failed to initialize connector\n");
4291                         goto fail;
4292                 }
4293
4294                 link = dc_get_link_at_index(dm->dc, i);
4295
4296                 if (!dc_link_detect_sink(link, &new_connection_type))
4297                         DRM_ERROR("KMS: Failed to detect connector\n");
4298
4299                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
4300                         emulated_link_detect(link);
4301                         amdgpu_dm_update_connector_after_detect(aconnector);
4302                 } else {
4303                         bool ret = false;
4304
4305                         mutex_lock(&dm->dc_lock);
4306                         ret = dc_link_detect(link, DETECT_REASON_BOOT);
4307                         mutex_unlock(&dm->dc_lock);
4308
4309                         if (ret) {
4310                                 amdgpu_dm_update_connector_after_detect(aconnector);
4311                                 register_backlight_device(dm, link);
4312
4313                                 if (dm->num_of_edps)
4314                                         update_connector_ext_caps(aconnector);
4315
4316                                 if (psr_feature_enabled)
4317                                         amdgpu_dm_set_psr_caps(link);
4318
4319                                 /* TODO: Fix vblank control helpers to delay PSR entry to allow this when
4320                                  * PSR is also supported.
4321                                  */
4322                                 if (link->psr_settings.psr_feature_enabled)
4323                                         adev_to_drm(adev)->vblank_disable_immediate = false;
4324                         }
4325                 }
4326                 amdgpu_set_panel_orientation(&aconnector->base);
4327         }
4328
4329         /* Software is initialized. Now we can register interrupt handlers. */
4330         switch (adev->asic_type) {
4331 #if defined(CONFIG_DRM_AMD_DC_SI)
4332         case CHIP_TAHITI:
4333         case CHIP_PITCAIRN:
4334         case CHIP_VERDE:
4335         case CHIP_OLAND:
4336                 if (dce60_register_irq_handlers(dm->adev)) {
4337                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4338                         goto fail;
4339                 }
4340                 break;
4341 #endif
4342         case CHIP_BONAIRE:
4343         case CHIP_HAWAII:
4344         case CHIP_KAVERI:
4345         case CHIP_KABINI:
4346         case CHIP_MULLINS:
4347         case CHIP_TONGA:
4348         case CHIP_FIJI:
4349         case CHIP_CARRIZO:
4350         case CHIP_STONEY:
4351         case CHIP_POLARIS11:
4352         case CHIP_POLARIS10:
4353         case CHIP_POLARIS12:
4354         case CHIP_VEGAM:
4355         case CHIP_VEGA10:
4356         case CHIP_VEGA12:
4357         case CHIP_VEGA20:
4358                 if (dce110_register_irq_handlers(dm->adev)) {
4359                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4360                         goto fail;
4361                 }
4362                 break;
4363         default:
4364                 switch (adev->ip_versions[DCE_HWIP][0]) {
4365                 case IP_VERSION(1, 0, 0):
4366                 case IP_VERSION(1, 0, 1):
4367                 case IP_VERSION(2, 0, 2):
4368                 case IP_VERSION(2, 0, 3):
4369                 case IP_VERSION(2, 0, 0):
4370                 case IP_VERSION(2, 1, 0):
4371                 case IP_VERSION(3, 0, 0):
4372                 case IP_VERSION(3, 0, 2):
4373                 case IP_VERSION(3, 0, 3):
4374                 case IP_VERSION(3, 0, 1):
4375                 case IP_VERSION(3, 1, 2):
4376                 case IP_VERSION(3, 1, 3):
4377                 case IP_VERSION(3, 1, 4):
4378                 case IP_VERSION(3, 1, 5):
4379                 case IP_VERSION(3, 1, 6):
4380                 case IP_VERSION(3, 2, 0):
4381                 case IP_VERSION(3, 2, 1):
4382                         if (dcn10_register_irq_handlers(dm->adev)) {
4383                                 DRM_ERROR("DM: Failed to initialize IRQ\n");
4384                                 goto fail;
4385                         }
4386                         break;
4387                 default:
4388                         DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4389                                         adev->ip_versions[DCE_HWIP][0]);
4390                         goto fail;
4391                 }
4392                 break;
4393         }
4394
4395         return 0;
4396 fail:
4397         kfree(aencoder);
4398         kfree(aconnector);
4399
4400         return -EINVAL;
4401 }
4402
4403 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4404 {
4405         drm_atomic_private_obj_fini(&dm->atomic_obj);
4406         return;
4407 }
4408
4409 /******************************************************************************
4410  * amdgpu_display_funcs functions
4411  *****************************************************************************/
4412
4413 /*
4414  * dm_bandwidth_update - program display watermarks
4415  *
4416  * @adev: amdgpu_device pointer
4417  *
4418  * Calculate and program the display watermarks and line buffer allocation.
4419  */
4420 static void dm_bandwidth_update(struct amdgpu_device *adev)
4421 {
4422         /* TODO: implement later */
4423 }
4424
4425 static const struct amdgpu_display_funcs dm_display_funcs = {
4426         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4427         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4428         .backlight_set_level = NULL, /* never called for DC */
4429         .backlight_get_level = NULL, /* never called for DC */
4430         .hpd_sense = NULL,/* called unconditionally */
4431         .hpd_set_polarity = NULL, /* called unconditionally */
4432         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4433         .page_flip_get_scanoutpos =
4434                 dm_crtc_get_scanoutpos,/* called unconditionally */
4435         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4436         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
4437 };
4438
4439 #if defined(CONFIG_DEBUG_KERNEL_DC)
4440
4441 static ssize_t s3_debug_store(struct device *device,
4442                               struct device_attribute *attr,
4443                               const char *buf,
4444                               size_t count)
4445 {
4446         int ret;
4447         int s3_state;
4448         struct drm_device *drm_dev = dev_get_drvdata(device);
4449         struct amdgpu_device *adev = drm_to_adev(drm_dev);
4450
4451         ret = kstrtoint(buf, 0, &s3_state);
4452
4453         if (ret == 0) {
4454                 if (s3_state) {
4455                         dm_resume(adev);
4456                         drm_kms_helper_hotplug_event(adev_to_drm(adev));
4457                 } else
4458                         dm_suspend(adev);
4459         }
4460
4461         return ret == 0 ? count : 0;
4462 }
4463
4464 DEVICE_ATTR_WO(s3_debug);
4465
4466 #endif
4467
4468 static int dm_init_microcode(struct amdgpu_device *adev)
4469 {
4470         char *fw_name_dmub;
4471         int r;
4472
4473         switch (adev->ip_versions[DCE_HWIP][0]) {
4474         case IP_VERSION(2, 1, 0):
4475                 fw_name_dmub = FIRMWARE_RENOIR_DMUB;
4476                 if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
4477                         fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
4478                 break;
4479         case IP_VERSION(3, 0, 0):
4480                 if (adev->ip_versions[GC_HWIP][0] == IP_VERSION(10, 3, 0))
4481                         fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
4482                 else
4483                         fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
4484                 break;
4485         case IP_VERSION(3, 0, 1):
4486                 fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
4487                 break;
4488         case IP_VERSION(3, 0, 2):
4489                 fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
4490                 break;
4491         case IP_VERSION(3, 0, 3):
4492                 fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
4493                 break;
4494         case IP_VERSION(3, 1, 2):
4495         case IP_VERSION(3, 1, 3):
4496                 fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
4497                 break;
4498         case IP_VERSION(3, 1, 4):
4499                 fw_name_dmub = FIRMWARE_DCN_314_DMUB;
4500                 break;
4501         case IP_VERSION(3, 1, 5):
4502                 fw_name_dmub = FIRMWARE_DCN_315_DMUB;
4503                 break;
4504         case IP_VERSION(3, 1, 6):
4505                 fw_name_dmub = FIRMWARE_DCN316_DMUB;
4506                 break;
4507         case IP_VERSION(3, 2, 0):
4508                 fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
4509                 break;
4510         case IP_VERSION(3, 2, 1):
4511                 fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
4512                 break;
4513         default:
4514                 /* ASIC doesn't support DMUB. */
4515                 return 0;
4516         }
4517         r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, fw_name_dmub);
4518         if (r)
4519                 DRM_ERROR("DMUB firmware loading failed: %d\n", r);
4520         return r;
4521 }
4522
4523 static int dm_early_init(void *handle)
4524 {
4525         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4526
4527         switch (adev->asic_type) {
4528 #if defined(CONFIG_DRM_AMD_DC_SI)
4529         case CHIP_TAHITI:
4530         case CHIP_PITCAIRN:
4531         case CHIP_VERDE:
4532                 adev->mode_info.num_crtc = 6;
4533                 adev->mode_info.num_hpd = 6;
4534                 adev->mode_info.num_dig = 6;
4535                 break;
4536         case CHIP_OLAND:
4537                 adev->mode_info.num_crtc = 2;
4538                 adev->mode_info.num_hpd = 2;
4539                 adev->mode_info.num_dig = 2;
4540                 break;
4541 #endif
4542         case CHIP_BONAIRE:
4543         case CHIP_HAWAII:
4544                 adev->mode_info.num_crtc = 6;
4545                 adev->mode_info.num_hpd = 6;
4546                 adev->mode_info.num_dig = 6;
4547                 break;
4548         case CHIP_KAVERI:
4549                 adev->mode_info.num_crtc = 4;
4550                 adev->mode_info.num_hpd = 6;
4551                 adev->mode_info.num_dig = 7;
4552                 break;
4553         case CHIP_KABINI:
4554         case CHIP_MULLINS:
4555                 adev->mode_info.num_crtc = 2;
4556                 adev->mode_info.num_hpd = 6;
4557                 adev->mode_info.num_dig = 6;
4558                 break;
4559         case CHIP_FIJI:
4560         case CHIP_TONGA:
4561                 adev->mode_info.num_crtc = 6;
4562                 adev->mode_info.num_hpd = 6;
4563                 adev->mode_info.num_dig = 7;
4564                 break;
4565         case CHIP_CARRIZO:
4566                 adev->mode_info.num_crtc = 3;
4567                 adev->mode_info.num_hpd = 6;
4568                 adev->mode_info.num_dig = 9;
4569                 break;
4570         case CHIP_STONEY:
4571                 adev->mode_info.num_crtc = 2;
4572                 adev->mode_info.num_hpd = 6;
4573                 adev->mode_info.num_dig = 9;
4574                 break;
4575         case CHIP_POLARIS11:
4576         case CHIP_POLARIS12:
4577                 adev->mode_info.num_crtc = 5;
4578                 adev->mode_info.num_hpd = 5;
4579                 adev->mode_info.num_dig = 5;
4580                 break;
4581         case CHIP_POLARIS10:
4582         case CHIP_VEGAM:
4583                 adev->mode_info.num_crtc = 6;
4584                 adev->mode_info.num_hpd = 6;
4585                 adev->mode_info.num_dig = 6;
4586                 break;
4587         case CHIP_VEGA10:
4588         case CHIP_VEGA12:
4589         case CHIP_VEGA20:
4590                 adev->mode_info.num_crtc = 6;
4591                 adev->mode_info.num_hpd = 6;
4592                 adev->mode_info.num_dig = 6;
4593                 break;
4594         default:
4595
4596                 switch (adev->ip_versions[DCE_HWIP][0]) {
4597                 case IP_VERSION(2, 0, 2):
4598                 case IP_VERSION(3, 0, 0):
4599                         adev->mode_info.num_crtc = 6;
4600                         adev->mode_info.num_hpd = 6;
4601                         adev->mode_info.num_dig = 6;
4602                         break;
4603                 case IP_VERSION(2, 0, 0):
4604                 case IP_VERSION(3, 0, 2):
4605                         adev->mode_info.num_crtc = 5;
4606                         adev->mode_info.num_hpd = 5;
4607                         adev->mode_info.num_dig = 5;
4608                         break;
4609                 case IP_VERSION(2, 0, 3):
4610                 case IP_VERSION(3, 0, 3):
4611                         adev->mode_info.num_crtc = 2;
4612                         adev->mode_info.num_hpd = 2;
4613                         adev->mode_info.num_dig = 2;
4614                         break;
4615                 case IP_VERSION(1, 0, 0):
4616                 case IP_VERSION(1, 0, 1):
4617                 case IP_VERSION(3, 0, 1):
4618                 case IP_VERSION(2, 1, 0):
4619                 case IP_VERSION(3, 1, 2):
4620                 case IP_VERSION(3, 1, 3):
4621                 case IP_VERSION(3, 1, 4):
4622                 case IP_VERSION(3, 1, 5):
4623                 case IP_VERSION(3, 1, 6):
4624                 case IP_VERSION(3, 2, 0):
4625                 case IP_VERSION(3, 2, 1):
4626                         adev->mode_info.num_crtc = 4;
4627                         adev->mode_info.num_hpd = 4;
4628                         adev->mode_info.num_dig = 4;
4629                         break;
4630                 default:
4631                         DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4632                                         adev->ip_versions[DCE_HWIP][0]);
4633                         return -EINVAL;
4634                 }
4635                 break;
4636         }
4637
4638         amdgpu_dm_set_irq_funcs(adev);
4639
4640         if (adev->mode_info.funcs == NULL)
4641                 adev->mode_info.funcs = &dm_display_funcs;
4642
4643         /*
4644          * Note: Do NOT change adev->audio_endpt_rreg and
4645          * adev->audio_endpt_wreg because they are initialised in
4646          * amdgpu_device_init()
4647          */
4648 #if defined(CONFIG_DEBUG_KERNEL_DC)
4649         device_create_file(
4650                 adev_to_drm(adev)->dev,
4651                 &dev_attr_s3_debug);
4652 #endif
4653         adev->dc_enabled = true;
4654
4655         return dm_init_microcode(adev);
4656 }
4657
4658 static bool modereset_required(struct drm_crtc_state *crtc_state)
4659 {
4660         return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4661 }
4662
4663 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4664 {
4665         drm_encoder_cleanup(encoder);
4666         kfree(encoder);
4667 }
4668
4669 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4670         .destroy = amdgpu_dm_encoder_destroy,
4671 };
4672
4673 static int
4674 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4675                             const enum surface_pixel_format format,
4676                             enum dc_color_space *color_space)
4677 {
4678         bool full_range;
4679
4680         *color_space = COLOR_SPACE_SRGB;
4681
4682         /* DRM color properties only affect non-RGB formats. */
4683         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4684                 return 0;
4685
4686         full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4687
4688         switch (plane_state->color_encoding) {
4689         case DRM_COLOR_YCBCR_BT601:
4690                 if (full_range)
4691                         *color_space = COLOR_SPACE_YCBCR601;
4692                 else
4693                         *color_space = COLOR_SPACE_YCBCR601_LIMITED;
4694                 break;
4695
4696         case DRM_COLOR_YCBCR_BT709:
4697                 if (full_range)
4698                         *color_space = COLOR_SPACE_YCBCR709;
4699                 else
4700                         *color_space = COLOR_SPACE_YCBCR709_LIMITED;
4701                 break;
4702
4703         case DRM_COLOR_YCBCR_BT2020:
4704                 if (full_range)
4705                         *color_space = COLOR_SPACE_2020_YCBCR;
4706                 else
4707                         return -EINVAL;
4708                 break;
4709
4710         default:
4711                 return -EINVAL;
4712         }
4713
4714         return 0;
4715 }
4716
4717 static int
4718 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4719                             const struct drm_plane_state *plane_state,
4720                             const u64 tiling_flags,
4721                             struct dc_plane_info *plane_info,
4722                             struct dc_plane_address *address,
4723                             bool tmz_surface,
4724                             bool force_disable_dcc)
4725 {
4726         const struct drm_framebuffer *fb = plane_state->fb;
4727         const struct amdgpu_framebuffer *afb =
4728                 to_amdgpu_framebuffer(plane_state->fb);
4729         int ret;
4730
4731         memset(plane_info, 0, sizeof(*plane_info));
4732
4733         switch (fb->format->format) {
4734         case DRM_FORMAT_C8:
4735                 plane_info->format =
4736                         SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4737                 break;
4738         case DRM_FORMAT_RGB565:
4739                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4740                 break;
4741         case DRM_FORMAT_XRGB8888:
4742         case DRM_FORMAT_ARGB8888:
4743                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4744                 break;
4745         case DRM_FORMAT_XRGB2101010:
4746         case DRM_FORMAT_ARGB2101010:
4747                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4748                 break;
4749         case DRM_FORMAT_XBGR2101010:
4750         case DRM_FORMAT_ABGR2101010:
4751                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4752                 break;
4753         case DRM_FORMAT_XBGR8888:
4754         case DRM_FORMAT_ABGR8888:
4755                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4756                 break;
4757         case DRM_FORMAT_NV21:
4758                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4759                 break;
4760         case DRM_FORMAT_NV12:
4761                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4762                 break;
4763         case DRM_FORMAT_P010:
4764                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4765                 break;
4766         case DRM_FORMAT_XRGB16161616F:
4767         case DRM_FORMAT_ARGB16161616F:
4768                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4769                 break;
4770         case DRM_FORMAT_XBGR16161616F:
4771         case DRM_FORMAT_ABGR16161616F:
4772                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4773                 break;
4774         case DRM_FORMAT_XRGB16161616:
4775         case DRM_FORMAT_ARGB16161616:
4776                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4777                 break;
4778         case DRM_FORMAT_XBGR16161616:
4779         case DRM_FORMAT_ABGR16161616:
4780                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4781                 break;
4782         default:
4783                 DRM_ERROR(
4784                         "Unsupported screen format %p4cc\n",
4785                         &fb->format->format);
4786                 return -EINVAL;
4787         }
4788
4789         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4790         case DRM_MODE_ROTATE_0:
4791                 plane_info->rotation = ROTATION_ANGLE_0;
4792                 break;
4793         case DRM_MODE_ROTATE_90:
4794                 plane_info->rotation = ROTATION_ANGLE_90;
4795                 break;
4796         case DRM_MODE_ROTATE_180:
4797                 plane_info->rotation = ROTATION_ANGLE_180;
4798                 break;
4799         case DRM_MODE_ROTATE_270:
4800                 plane_info->rotation = ROTATION_ANGLE_270;
4801                 break;
4802         default:
4803                 plane_info->rotation = ROTATION_ANGLE_0;
4804                 break;
4805         }
4806
4807
4808         plane_info->visible = true;
4809         plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4810
4811         plane_info->layer_index = plane_state->normalized_zpos;
4812
4813         ret = fill_plane_color_attributes(plane_state, plane_info->format,
4814                                           &plane_info->color_space);
4815         if (ret)
4816                 return ret;
4817
4818         ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4819                                            plane_info->rotation, tiling_flags,
4820                                            &plane_info->tiling_info,
4821                                            &plane_info->plane_size,
4822                                            &plane_info->dcc, address,
4823                                            tmz_surface, force_disable_dcc);
4824         if (ret)
4825                 return ret;
4826
4827         fill_blending_from_plane_state(
4828                 plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4829                 &plane_info->global_alpha, &plane_info->global_alpha_value);
4830
4831         return 0;
4832 }
4833
4834 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4835                                     struct dc_plane_state *dc_plane_state,
4836                                     struct drm_plane_state *plane_state,
4837                                     struct drm_crtc_state *crtc_state)
4838 {
4839         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4840         struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4841         struct dc_scaling_info scaling_info;
4842         struct dc_plane_info plane_info;
4843         int ret;
4844         bool force_disable_dcc = false;
4845
4846         ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4847         if (ret)
4848                 return ret;
4849
4850         dc_plane_state->src_rect = scaling_info.src_rect;
4851         dc_plane_state->dst_rect = scaling_info.dst_rect;
4852         dc_plane_state->clip_rect = scaling_info.clip_rect;
4853         dc_plane_state->scaling_quality = scaling_info.scaling_quality;
4854
4855         force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
4856         ret = fill_dc_plane_info_and_addr(adev, plane_state,
4857                                           afb->tiling_flags,
4858                                           &plane_info,
4859                                           &dc_plane_state->address,
4860                                           afb->tmz_surface,
4861                                           force_disable_dcc);
4862         if (ret)
4863                 return ret;
4864
4865         dc_plane_state->format = plane_info.format;
4866         dc_plane_state->color_space = plane_info.color_space;
4867         dc_plane_state->format = plane_info.format;
4868         dc_plane_state->plane_size = plane_info.plane_size;
4869         dc_plane_state->rotation = plane_info.rotation;
4870         dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
4871         dc_plane_state->stereo_format = plane_info.stereo_format;
4872         dc_plane_state->tiling_info = plane_info.tiling_info;
4873         dc_plane_state->visible = plane_info.visible;
4874         dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
4875         dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
4876         dc_plane_state->global_alpha = plane_info.global_alpha;
4877         dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
4878         dc_plane_state->dcc = plane_info.dcc;
4879         dc_plane_state->layer_index = plane_info.layer_index;
4880         dc_plane_state->flip_int_enabled = true;
4881
4882         /*
4883          * Always set input transfer function, since plane state is refreshed
4884          * every time.
4885          */
4886         ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
4887         if (ret)
4888                 return ret;
4889
4890         return 0;
4891 }
4892
4893 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
4894                                       struct rect *dirty_rect, int32_t x,
4895                                       s32 y, s32 width, s32 height,
4896                                       int *i, bool ffu)
4897 {
4898         if (*i > DC_MAX_DIRTY_RECTS)
4899                 return;
4900
4901         if (*i == DC_MAX_DIRTY_RECTS)
4902                 goto out;
4903
4904         dirty_rect->x = x;
4905         dirty_rect->y = y;
4906         dirty_rect->width = width;
4907         dirty_rect->height = height;
4908
4909         if (ffu)
4910                 drm_dbg(plane->dev,
4911                         "[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
4912                         plane->base.id, width, height);
4913         else
4914                 drm_dbg(plane->dev,
4915                         "[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
4916                         plane->base.id, x, y, width, height);
4917
4918 out:
4919         (*i)++;
4920 }
4921
4922 /**
4923  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
4924  *
4925  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
4926  *         remote fb
4927  * @old_plane_state: Old state of @plane
4928  * @new_plane_state: New state of @plane
4929  * @crtc_state: New state of CRTC connected to the @plane
4930  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
4931  *
4932  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
4933  * (referred to as "damage clips" in DRM nomenclature) that require updating on
4934  * the eDP remote buffer. The responsibility of specifying the dirty regions is
4935  * amdgpu_dm's.
4936  *
4937  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
4938  * plane with regions that require flushing to the eDP remote buffer. In
4939  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
4940  * implicitly provide damage clips without any client support via the plane
4941  * bounds.
4942  */
4943 static void fill_dc_dirty_rects(struct drm_plane *plane,
4944                                 struct drm_plane_state *old_plane_state,
4945                                 struct drm_plane_state *new_plane_state,
4946                                 struct drm_crtc_state *crtc_state,
4947                                 struct dc_flip_addrs *flip_addrs)
4948 {
4949         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4950         struct rect *dirty_rects = flip_addrs->dirty_rects;
4951         u32 num_clips;
4952         struct drm_mode_rect *clips;
4953         bool bb_changed;
4954         bool fb_changed;
4955         u32 i = 0;
4956
4957         /*
4958          * Cursor plane has it's own dirty rect update interface. See
4959          * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
4960          */
4961         if (plane->type == DRM_PLANE_TYPE_CURSOR)
4962                 return;
4963
4964         num_clips = drm_plane_get_damage_clips_count(new_plane_state);
4965         clips = drm_plane_get_damage_clips(new_plane_state);
4966
4967         if (!dm_crtc_state->mpo_requested) {
4968                 if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
4969                         goto ffu;
4970
4971                 for (; flip_addrs->dirty_rect_count < num_clips; clips++)
4972                         fill_dc_dirty_rect(new_plane_state->plane,
4973                                            &dirty_rects[i], clips->x1,
4974                                            clips->y1, clips->x2 - clips->x1,
4975                                            clips->y2 - clips->y1,
4976                                            &flip_addrs->dirty_rect_count,
4977                                            false);
4978                 return;
4979         }
4980
4981         /*
4982          * MPO is requested. Add entire plane bounding box to dirty rects if
4983          * flipped to or damaged.
4984          *
4985          * If plane is moved or resized, also add old bounding box to dirty
4986          * rects.
4987          */
4988         fb_changed = old_plane_state->fb->base.id !=
4989                      new_plane_state->fb->base.id;
4990         bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
4991                       old_plane_state->crtc_y != new_plane_state->crtc_y ||
4992                       old_plane_state->crtc_w != new_plane_state->crtc_w ||
4993                       old_plane_state->crtc_h != new_plane_state->crtc_h);
4994
4995         drm_dbg(plane->dev,
4996                 "[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
4997                 new_plane_state->plane->base.id,
4998                 bb_changed, fb_changed, num_clips);
4999
5000         if (bb_changed) {
5001                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5002                                    new_plane_state->crtc_x,
5003                                    new_plane_state->crtc_y,
5004                                    new_plane_state->crtc_w,
5005                                    new_plane_state->crtc_h, &i, false);
5006
5007                 /* Add old plane bounding-box if plane is moved or resized */
5008                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5009                                    old_plane_state->crtc_x,
5010                                    old_plane_state->crtc_y,
5011                                    old_plane_state->crtc_w,
5012                                    old_plane_state->crtc_h, &i, false);
5013         }
5014
5015         if (num_clips) {
5016                 for (; i < num_clips; clips++)
5017                         fill_dc_dirty_rect(new_plane_state->plane,
5018                                            &dirty_rects[i], clips->x1,
5019                                            clips->y1, clips->x2 - clips->x1,
5020                                            clips->y2 - clips->y1, &i, false);
5021         } else if (fb_changed && !bb_changed) {
5022                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5023                                    new_plane_state->crtc_x,
5024                                    new_plane_state->crtc_y,
5025                                    new_plane_state->crtc_w,
5026                                    new_plane_state->crtc_h, &i, false);
5027         }
5028
5029         if (i > DC_MAX_DIRTY_RECTS)
5030                 goto ffu;
5031
5032         flip_addrs->dirty_rect_count = i;
5033         return;
5034
5035 ffu:
5036         fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
5037                            dm_crtc_state->base.mode.crtc_hdisplay,
5038                            dm_crtc_state->base.mode.crtc_vdisplay,
5039                            &flip_addrs->dirty_rect_count, true);
5040 }
5041
5042 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
5043                                            const struct dm_connector_state *dm_state,
5044                                            struct dc_stream_state *stream)
5045 {
5046         enum amdgpu_rmx_type rmx_type;
5047
5048         struct rect src = { 0 }; /* viewport in composition space*/
5049         struct rect dst = { 0 }; /* stream addressable area */
5050
5051         /* no mode. nothing to be done */
5052         if (!mode)
5053                 return;
5054
5055         /* Full screen scaling by default */
5056         src.width = mode->hdisplay;
5057         src.height = mode->vdisplay;
5058         dst.width = stream->timing.h_addressable;
5059         dst.height = stream->timing.v_addressable;
5060
5061         if (dm_state) {
5062                 rmx_type = dm_state->scaling;
5063                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5064                         if (src.width * dst.height <
5065                                         src.height * dst.width) {
5066                                 /* height needs less upscaling/more downscaling */
5067                                 dst.width = src.width *
5068                                                 dst.height / src.height;
5069                         } else {
5070                                 /* width needs less upscaling/more downscaling */
5071                                 dst.height = src.height *
5072                                                 dst.width / src.width;
5073                         }
5074                 } else if (rmx_type == RMX_CENTER) {
5075                         dst = src;
5076                 }
5077
5078                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
5079                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
5080
5081                 if (dm_state->underscan_enable) {
5082                         dst.x += dm_state->underscan_hborder / 2;
5083                         dst.y += dm_state->underscan_vborder / 2;
5084                         dst.width -= dm_state->underscan_hborder;
5085                         dst.height -= dm_state->underscan_vborder;
5086                 }
5087         }
5088
5089         stream->src = src;
5090         stream->dst = dst;
5091
5092         DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5093                       dst.x, dst.y, dst.width, dst.height);
5094
5095 }
5096
5097 static enum dc_color_depth
5098 convert_color_depth_from_display_info(const struct drm_connector *connector,
5099                                       bool is_y420, int requested_bpc)
5100 {
5101         u8 bpc;
5102
5103         if (is_y420) {
5104                 bpc = 8;
5105
5106                 /* Cap display bpc based on HDMI 2.0 HF-VSDB */
5107                 if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5108                         bpc = 16;
5109                 else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5110                         bpc = 12;
5111                 else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5112                         bpc = 10;
5113         } else {
5114                 bpc = (uint8_t)connector->display_info.bpc;
5115                 /* Assume 8 bpc by default if no bpc is specified. */
5116                 bpc = bpc ? bpc : 8;
5117         }
5118
5119         if (requested_bpc > 0) {
5120                 /*
5121                  * Cap display bpc based on the user requested value.
5122                  *
5123                  * The value for state->max_bpc may not correctly updated
5124                  * depending on when the connector gets added to the state
5125                  * or if this was called outside of atomic check, so it
5126                  * can't be used directly.
5127                  */
5128                 bpc = min_t(u8, bpc, requested_bpc);
5129
5130                 /* Round down to the nearest even number. */
5131                 bpc = bpc - (bpc & 1);
5132         }
5133
5134         switch (bpc) {
5135         case 0:
5136                 /*
5137                  * Temporary Work around, DRM doesn't parse color depth for
5138                  * EDID revision before 1.4
5139                  * TODO: Fix edid parsing
5140                  */
5141                 return COLOR_DEPTH_888;
5142         case 6:
5143                 return COLOR_DEPTH_666;
5144         case 8:
5145                 return COLOR_DEPTH_888;
5146         case 10:
5147                 return COLOR_DEPTH_101010;
5148         case 12:
5149                 return COLOR_DEPTH_121212;
5150         case 14:
5151                 return COLOR_DEPTH_141414;
5152         case 16:
5153                 return COLOR_DEPTH_161616;
5154         default:
5155                 return COLOR_DEPTH_UNDEFINED;
5156         }
5157 }
5158
5159 static enum dc_aspect_ratio
5160 get_aspect_ratio(const struct drm_display_mode *mode_in)
5161 {
5162         /* 1-1 mapping, since both enums follow the HDMI spec. */
5163         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5164 }
5165
5166 static enum dc_color_space
5167 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5168 {
5169         enum dc_color_space color_space = COLOR_SPACE_SRGB;
5170
5171         switch (dc_crtc_timing->pixel_encoding) {
5172         case PIXEL_ENCODING_YCBCR422:
5173         case PIXEL_ENCODING_YCBCR444:
5174         case PIXEL_ENCODING_YCBCR420:
5175         {
5176                 /*
5177                  * 27030khz is the separation point between HDTV and SDTV
5178                  * according to HDMI spec, we use YCbCr709 and YCbCr601
5179                  * respectively
5180                  */
5181                 if (dc_crtc_timing->pix_clk_100hz > 270300) {
5182                         if (dc_crtc_timing->flags.Y_ONLY)
5183                                 color_space =
5184                                         COLOR_SPACE_YCBCR709_LIMITED;
5185                         else
5186                                 color_space = COLOR_SPACE_YCBCR709;
5187                 } else {
5188                         if (dc_crtc_timing->flags.Y_ONLY)
5189                                 color_space =
5190                                         COLOR_SPACE_YCBCR601_LIMITED;
5191                         else
5192                                 color_space = COLOR_SPACE_YCBCR601;
5193                 }
5194
5195         }
5196         break;
5197         case PIXEL_ENCODING_RGB:
5198                 color_space = COLOR_SPACE_SRGB;
5199                 break;
5200
5201         default:
5202                 WARN_ON(1);
5203                 break;
5204         }
5205
5206         return color_space;
5207 }
5208
5209 static bool adjust_colour_depth_from_display_info(
5210         struct dc_crtc_timing *timing_out,
5211         const struct drm_display_info *info)
5212 {
5213         enum dc_color_depth depth = timing_out->display_color_depth;
5214         int normalized_clk;
5215         do {
5216                 normalized_clk = timing_out->pix_clk_100hz / 10;
5217                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5218                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5219                         normalized_clk /= 2;
5220                 /* Adjusting pix clock following on HDMI spec based on colour depth */
5221                 switch (depth) {
5222                 case COLOR_DEPTH_888:
5223                         break;
5224                 case COLOR_DEPTH_101010:
5225                         normalized_clk = (normalized_clk * 30) / 24;
5226                         break;
5227                 case COLOR_DEPTH_121212:
5228                         normalized_clk = (normalized_clk * 36) / 24;
5229                         break;
5230                 case COLOR_DEPTH_161616:
5231                         normalized_clk = (normalized_clk * 48) / 24;
5232                         break;
5233                 default:
5234                         /* The above depths are the only ones valid for HDMI. */
5235                         return false;
5236                 }
5237                 if (normalized_clk <= info->max_tmds_clock) {
5238                         timing_out->display_color_depth = depth;
5239                         return true;
5240                 }
5241         } while (--depth > COLOR_DEPTH_666);
5242         return false;
5243 }
5244
5245 static void fill_stream_properties_from_drm_display_mode(
5246         struct dc_stream_state *stream,
5247         const struct drm_display_mode *mode_in,
5248         const struct drm_connector *connector,
5249         const struct drm_connector_state *connector_state,
5250         const struct dc_stream_state *old_stream,
5251         int requested_bpc)
5252 {
5253         struct dc_crtc_timing *timing_out = &stream->timing;
5254         const struct drm_display_info *info = &connector->display_info;
5255         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5256         struct hdmi_vendor_infoframe hv_frame;
5257         struct hdmi_avi_infoframe avi_frame;
5258
5259         memset(&hv_frame, 0, sizeof(hv_frame));
5260         memset(&avi_frame, 0, sizeof(avi_frame));
5261
5262         timing_out->h_border_left = 0;
5263         timing_out->h_border_right = 0;
5264         timing_out->v_border_top = 0;
5265         timing_out->v_border_bottom = 0;
5266         /* TODO: un-hardcode */
5267         if (drm_mode_is_420_only(info, mode_in)
5268                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5269                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5270         else if (drm_mode_is_420_also(info, mode_in)
5271                         && aconnector->force_yuv420_output)
5272                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5273         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5274                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5275                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5276         else
5277                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5278
5279         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5280         timing_out->display_color_depth = convert_color_depth_from_display_info(
5281                 connector,
5282                 (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5283                 requested_bpc);
5284         timing_out->scan_type = SCANNING_TYPE_NODATA;
5285         timing_out->hdmi_vic = 0;
5286
5287         if (old_stream) {
5288                 timing_out->vic = old_stream->timing.vic;
5289                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5290                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5291         } else {
5292                 timing_out->vic = drm_match_cea_mode(mode_in);
5293                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5294                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5295                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5296                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5297         }
5298
5299         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5300                 drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5301                 timing_out->vic = avi_frame.video_code;
5302                 drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5303                 timing_out->hdmi_vic = hv_frame.vic;
5304         }
5305
5306         if (is_freesync_video_mode(mode_in, aconnector)) {
5307                 timing_out->h_addressable = mode_in->hdisplay;
5308                 timing_out->h_total = mode_in->htotal;
5309                 timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5310                 timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5311                 timing_out->v_total = mode_in->vtotal;
5312                 timing_out->v_addressable = mode_in->vdisplay;
5313                 timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5314                 timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5315                 timing_out->pix_clk_100hz = mode_in->clock * 10;
5316         } else {
5317                 timing_out->h_addressable = mode_in->crtc_hdisplay;
5318                 timing_out->h_total = mode_in->crtc_htotal;
5319                 timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5320                 timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5321                 timing_out->v_total = mode_in->crtc_vtotal;
5322                 timing_out->v_addressable = mode_in->crtc_vdisplay;
5323                 timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5324                 timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5325                 timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5326         }
5327
5328         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5329
5330         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5331         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5332         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5333                 if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5334                     drm_mode_is_420_also(info, mode_in) &&
5335                     timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5336                         timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5337                         adjust_colour_depth_from_display_info(timing_out, info);
5338                 }
5339         }
5340
5341         stream->output_color_space = get_output_color_space(timing_out);
5342 }
5343
5344 static void fill_audio_info(struct audio_info *audio_info,
5345                             const struct drm_connector *drm_connector,
5346                             const struct dc_sink *dc_sink)
5347 {
5348         int i = 0;
5349         int cea_revision = 0;
5350         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5351
5352         audio_info->manufacture_id = edid_caps->manufacturer_id;
5353         audio_info->product_id = edid_caps->product_id;
5354
5355         cea_revision = drm_connector->display_info.cea_rev;
5356
5357         strscpy(audio_info->display_name,
5358                 edid_caps->display_name,
5359                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5360
5361         if (cea_revision >= 3) {
5362                 audio_info->mode_count = edid_caps->audio_mode_count;
5363
5364                 for (i = 0; i < audio_info->mode_count; ++i) {
5365                         audio_info->modes[i].format_code =
5366                                         (enum audio_format_code)
5367                                         (edid_caps->audio_modes[i].format_code);
5368                         audio_info->modes[i].channel_count =
5369                                         edid_caps->audio_modes[i].channel_count;
5370                         audio_info->modes[i].sample_rates.all =
5371                                         edid_caps->audio_modes[i].sample_rate;
5372                         audio_info->modes[i].sample_size =
5373                                         edid_caps->audio_modes[i].sample_size;
5374                 }
5375         }
5376
5377         audio_info->flags.all = edid_caps->speaker_flags;
5378
5379         /* TODO: We only check for the progressive mode, check for interlace mode too */
5380         if (drm_connector->latency_present[0]) {
5381                 audio_info->video_latency = drm_connector->video_latency[0];
5382                 audio_info->audio_latency = drm_connector->audio_latency[0];
5383         }
5384
5385         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5386
5387 }
5388
5389 static void
5390 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5391                                       struct drm_display_mode *dst_mode)
5392 {
5393         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5394         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5395         dst_mode->crtc_clock = src_mode->crtc_clock;
5396         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5397         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5398         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5399         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5400         dst_mode->crtc_htotal = src_mode->crtc_htotal;
5401         dst_mode->crtc_hskew = src_mode->crtc_hskew;
5402         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5403         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5404         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5405         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5406         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5407 }
5408
5409 static void
5410 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5411                                         const struct drm_display_mode *native_mode,
5412                                         bool scale_enabled)
5413 {
5414         if (scale_enabled) {
5415                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5416         } else if (native_mode->clock == drm_mode->clock &&
5417                         native_mode->htotal == drm_mode->htotal &&
5418                         native_mode->vtotal == drm_mode->vtotal) {
5419                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5420         } else {
5421                 /* no scaling nor amdgpu inserted, no need to patch */
5422         }
5423 }
5424
5425 static struct dc_sink *
5426 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5427 {
5428         struct dc_sink_init_data sink_init_data = { 0 };
5429         struct dc_sink *sink = NULL;
5430         sink_init_data.link = aconnector->dc_link;
5431         sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5432
5433         sink = dc_sink_create(&sink_init_data);
5434         if (!sink) {
5435                 DRM_ERROR("Failed to create sink!\n");
5436                 return NULL;
5437         }
5438         sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5439
5440         return sink;
5441 }
5442
5443 static void set_multisync_trigger_params(
5444                 struct dc_stream_state *stream)
5445 {
5446         struct dc_stream_state *master = NULL;
5447
5448         if (stream->triggered_crtc_reset.enabled) {
5449                 master = stream->triggered_crtc_reset.event_source;
5450                 stream->triggered_crtc_reset.event =
5451                         master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5452                         CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5453                 stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5454         }
5455 }
5456
5457 static void set_master_stream(struct dc_stream_state *stream_set[],
5458                               int stream_count)
5459 {
5460         int j, highest_rfr = 0, master_stream = 0;
5461
5462         for (j = 0;  j < stream_count; j++) {
5463                 if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5464                         int refresh_rate = 0;
5465
5466                         refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5467                                 (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5468                         if (refresh_rate > highest_rfr) {
5469                                 highest_rfr = refresh_rate;
5470                                 master_stream = j;
5471                         }
5472                 }
5473         }
5474         for (j = 0;  j < stream_count; j++) {
5475                 if (stream_set[j])
5476                         stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5477         }
5478 }
5479
5480 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5481 {
5482         int i = 0;
5483         struct dc_stream_state *stream;
5484
5485         if (context->stream_count < 2)
5486                 return;
5487         for (i = 0; i < context->stream_count ; i++) {
5488                 if (!context->streams[i])
5489                         continue;
5490                 /*
5491                  * TODO: add a function to read AMD VSDB bits and set
5492                  * crtc_sync_master.multi_sync_enabled flag
5493                  * For now it's set to false
5494                  */
5495         }
5496
5497         set_master_stream(context->streams, context->stream_count);
5498
5499         for (i = 0; i < context->stream_count ; i++) {
5500                 stream = context->streams[i];
5501
5502                 if (!stream)
5503                         continue;
5504
5505                 set_multisync_trigger_params(stream);
5506         }
5507 }
5508
5509 /**
5510  * DOC: FreeSync Video
5511  *
5512  * When a userspace application wants to play a video, the content follows a
5513  * standard format definition that usually specifies the FPS for that format.
5514  * The below list illustrates some video format and the expected FPS,
5515  * respectively:
5516  *
5517  * - TV/NTSC (23.976 FPS)
5518  * - Cinema (24 FPS)
5519  * - TV/PAL (25 FPS)
5520  * - TV/NTSC (29.97 FPS)
5521  * - TV/NTSC (30 FPS)
5522  * - Cinema HFR (48 FPS)
5523  * - TV/PAL (50 FPS)
5524  * - Commonly used (60 FPS)
5525  * - Multiples of 24 (48,72,96 FPS)
5526  *
5527  * The list of standards video format is not huge and can be added to the
5528  * connector modeset list beforehand. With that, userspace can leverage
5529  * FreeSync to extends the front porch in order to attain the target refresh
5530  * rate. Such a switch will happen seamlessly, without screen blanking or
5531  * reprogramming of the output in any other way. If the userspace requests a
5532  * modesetting change compatible with FreeSync modes that only differ in the
5533  * refresh rate, DC will skip the full update and avoid blink during the
5534  * transition. For example, the video player can change the modesetting from
5535  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5536  * causing any display blink. This same concept can be applied to a mode
5537  * setting change.
5538  */
5539 static struct drm_display_mode *
5540 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5541                 bool use_probed_modes)
5542 {
5543         struct drm_display_mode *m, *m_pref = NULL;
5544         u16 current_refresh, highest_refresh;
5545         struct list_head *list_head = use_probed_modes ?
5546                 &aconnector->base.probed_modes :
5547                 &aconnector->base.modes;
5548
5549         if (aconnector->freesync_vid_base.clock != 0)
5550                 return &aconnector->freesync_vid_base;
5551
5552         /* Find the preferred mode */
5553         list_for_each_entry (m, list_head, head) {
5554                 if (m->type & DRM_MODE_TYPE_PREFERRED) {
5555                         m_pref = m;
5556                         break;
5557                 }
5558         }
5559
5560         if (!m_pref) {
5561                 /* Probably an EDID with no preferred mode. Fallback to first entry */
5562                 m_pref = list_first_entry_or_null(
5563                                 &aconnector->base.modes, struct drm_display_mode, head);
5564                 if (!m_pref) {
5565                         DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5566                         return NULL;
5567                 }
5568         }
5569
5570         highest_refresh = drm_mode_vrefresh(m_pref);
5571
5572         /*
5573          * Find the mode with highest refresh rate with same resolution.
5574          * For some monitors, preferred mode is not the mode with highest
5575          * supported refresh rate.
5576          */
5577         list_for_each_entry (m, list_head, head) {
5578                 current_refresh  = drm_mode_vrefresh(m);
5579
5580                 if (m->hdisplay == m_pref->hdisplay &&
5581                     m->vdisplay == m_pref->vdisplay &&
5582                     highest_refresh < current_refresh) {
5583                         highest_refresh = current_refresh;
5584                         m_pref = m;
5585                 }
5586         }
5587
5588         drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5589         return m_pref;
5590 }
5591
5592 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5593                 struct amdgpu_dm_connector *aconnector)
5594 {
5595         struct drm_display_mode *high_mode;
5596         int timing_diff;
5597
5598         high_mode = get_highest_refresh_rate_mode(aconnector, false);
5599         if (!high_mode || !mode)
5600                 return false;
5601
5602         timing_diff = high_mode->vtotal - mode->vtotal;
5603
5604         if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5605             high_mode->hdisplay != mode->hdisplay ||
5606             high_mode->vdisplay != mode->vdisplay ||
5607             high_mode->hsync_start != mode->hsync_start ||
5608             high_mode->hsync_end != mode->hsync_end ||
5609             high_mode->htotal != mode->htotal ||
5610             high_mode->hskew != mode->hskew ||
5611             high_mode->vscan != mode->vscan ||
5612             high_mode->vsync_start - mode->vsync_start != timing_diff ||
5613             high_mode->vsync_end - mode->vsync_end != timing_diff)
5614                 return false;
5615         else
5616                 return true;
5617 }
5618
5619 #if defined(CONFIG_DRM_AMD_DC_DCN)
5620 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5621                             struct dc_sink *sink, struct dc_stream_state *stream,
5622                             struct dsc_dec_dpcd_caps *dsc_caps)
5623 {
5624         stream->timing.flags.DSC = 0;
5625         dsc_caps->is_dsc_supported = false;
5626
5627         if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5628             sink->sink_signal == SIGNAL_TYPE_EDP)) {
5629                 if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5630                         sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5631                         dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5632                                 aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5633                                 aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5634                                 dsc_caps);
5635         }
5636 }
5637
5638
5639 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5640                                     struct dc_sink *sink, struct dc_stream_state *stream,
5641                                     struct dsc_dec_dpcd_caps *dsc_caps,
5642                                     uint32_t max_dsc_target_bpp_limit_override)
5643 {
5644         const struct dc_link_settings *verified_link_cap = NULL;
5645         u32 link_bw_in_kbps;
5646         u32 edp_min_bpp_x16, edp_max_bpp_x16;
5647         struct dc *dc = sink->ctx->dc;
5648         struct dc_dsc_bw_range bw_range = {0};
5649         struct dc_dsc_config dsc_cfg = {0};
5650
5651         verified_link_cap = dc_link_get_link_cap(stream->link);
5652         link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5653         edp_min_bpp_x16 = 8 * 16;
5654         edp_max_bpp_x16 = 8 * 16;
5655
5656         if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5657                 edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5658
5659         if (edp_max_bpp_x16 < edp_min_bpp_x16)
5660                 edp_min_bpp_x16 = edp_max_bpp_x16;
5661
5662         if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5663                                 dc->debug.dsc_min_slice_height_override,
5664                                 edp_min_bpp_x16, edp_max_bpp_x16,
5665                                 dsc_caps,
5666                                 &stream->timing,
5667                                 &bw_range)) {
5668
5669                 if (bw_range.max_kbps < link_bw_in_kbps) {
5670                         if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5671                                         dsc_caps,
5672                                         dc->debug.dsc_min_slice_height_override,
5673                                         max_dsc_target_bpp_limit_override,
5674                                         0,
5675                                         &stream->timing,
5676                                         &dsc_cfg)) {
5677                                 stream->timing.dsc_cfg = dsc_cfg;
5678                                 stream->timing.flags.DSC = 1;
5679                                 stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5680                         }
5681                         return;
5682                 }
5683         }
5684
5685         if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5686                                 dsc_caps,
5687                                 dc->debug.dsc_min_slice_height_override,
5688                                 max_dsc_target_bpp_limit_override,
5689                                 link_bw_in_kbps,
5690                                 &stream->timing,
5691                                 &dsc_cfg)) {
5692                 stream->timing.dsc_cfg = dsc_cfg;
5693                 stream->timing.flags.DSC = 1;
5694         }
5695 }
5696
5697
5698 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5699                                         struct dc_sink *sink, struct dc_stream_state *stream,
5700                                         struct dsc_dec_dpcd_caps *dsc_caps)
5701 {
5702         struct drm_connector *drm_connector = &aconnector->base;
5703         u32 link_bandwidth_kbps;
5704         struct dc *dc = sink->ctx->dc;
5705         u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
5706         u32 dsc_max_supported_bw_in_kbps;
5707         u32 max_dsc_target_bpp_limit_override =
5708                 drm_connector->display_info.max_dsc_bpp;
5709
5710         link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5711                                                         dc_link_get_link_cap(aconnector->dc_link));
5712
5713         /* Set DSC policy according to dsc_clock_en */
5714         dc_dsc_policy_set_enable_dsc_when_not_needed(
5715                 aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5716
5717         if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5718             !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5719             dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5720
5721                 apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5722
5723         } else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5724                 if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5725                         if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5726                                                 dsc_caps,
5727                                                 aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5728                                                 max_dsc_target_bpp_limit_override,
5729                                                 link_bandwidth_kbps,
5730                                                 &stream->timing,
5731                                                 &stream->timing.dsc_cfg)) {
5732                                 stream->timing.flags.DSC = 1;
5733                                 DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5734                         }
5735                 } else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5736                         timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5737                         max_supported_bw_in_kbps = link_bandwidth_kbps;
5738                         dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5739
5740                         if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5741                                         max_supported_bw_in_kbps > 0 &&
5742                                         dsc_max_supported_bw_in_kbps > 0)
5743                                 if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5744                                                 dsc_caps,
5745                                                 aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5746                                                 max_dsc_target_bpp_limit_override,
5747                                                 dsc_max_supported_bw_in_kbps,
5748                                                 &stream->timing,
5749                                                 &stream->timing.dsc_cfg)) {
5750                                         stream->timing.flags.DSC = 1;
5751                                         DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5752                                                                          __func__, drm_connector->name);
5753                                 }
5754                 }
5755         }
5756
5757         /* Overwrite the stream flag if DSC is enabled through debugfs */
5758         if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5759                 stream->timing.flags.DSC = 1;
5760
5761         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5762                 stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5763
5764         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5765                 stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5766
5767         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5768                 stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5769 }
5770 #endif /* CONFIG_DRM_AMD_DC_DCN */
5771
5772 static struct dc_stream_state *
5773 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5774                        const struct drm_display_mode *drm_mode,
5775                        const struct dm_connector_state *dm_state,
5776                        const struct dc_stream_state *old_stream,
5777                        int requested_bpc)
5778 {
5779         struct drm_display_mode *preferred_mode = NULL;
5780         struct drm_connector *drm_connector;
5781         const struct drm_connector_state *con_state =
5782                 dm_state ? &dm_state->base : NULL;
5783         struct dc_stream_state *stream = NULL;
5784         struct drm_display_mode mode;
5785         struct drm_display_mode saved_mode;
5786         struct drm_display_mode *freesync_mode = NULL;
5787         bool native_mode_found = false;
5788         bool recalculate_timing = false;
5789         bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5790         int mode_refresh;
5791         int preferred_refresh = 0;
5792         enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
5793 #if defined(CONFIG_DRM_AMD_DC_DCN)
5794         struct dsc_dec_dpcd_caps dsc_caps;
5795 #endif
5796
5797         struct dc_sink *sink = NULL;
5798
5799         drm_mode_init(&mode, drm_mode);
5800         memset(&saved_mode, 0, sizeof(saved_mode));
5801
5802         if (aconnector == NULL) {
5803                 DRM_ERROR("aconnector is NULL!\n");
5804                 return stream;
5805         }
5806
5807         drm_connector = &aconnector->base;
5808
5809         if (!aconnector->dc_sink) {
5810                 sink = create_fake_sink(aconnector);
5811                 if (!sink)
5812                         return stream;
5813         } else {
5814                 sink = aconnector->dc_sink;
5815                 dc_sink_retain(sink);
5816         }
5817
5818         stream = dc_create_stream_for_sink(sink);
5819
5820         if (stream == NULL) {
5821                 DRM_ERROR("Failed to create stream for sink!\n");
5822                 goto finish;
5823         }
5824
5825         stream->dm_stream_context = aconnector;
5826
5827         stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5828                 drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5829
5830         list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5831                 /* Search for preferred mode */
5832                 if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5833                         native_mode_found = true;
5834                         break;
5835                 }
5836         }
5837         if (!native_mode_found)
5838                 preferred_mode = list_first_entry_or_null(
5839                                 &aconnector->base.modes,
5840                                 struct drm_display_mode,
5841                                 head);
5842
5843         mode_refresh = drm_mode_vrefresh(&mode);
5844
5845         if (preferred_mode == NULL) {
5846                 /*
5847                  * This may not be an error, the use case is when we have no
5848                  * usermode calls to reset and set mode upon hotplug. In this
5849                  * case, we call set mode ourselves to restore the previous mode
5850                  * and the modelist may not be filled in in time.
5851                  */
5852                 DRM_DEBUG_DRIVER("No preferred mode found\n");
5853         } else {
5854                 recalculate_timing = amdgpu_freesync_vid_mode &&
5855                                  is_freesync_video_mode(&mode, aconnector);
5856                 if (recalculate_timing) {
5857                         freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5858                         drm_mode_copy(&saved_mode, &mode);
5859                         drm_mode_copy(&mode, freesync_mode);
5860                 } else {
5861                         decide_crtc_timing_for_drm_display_mode(
5862                                         &mode, preferred_mode, scale);
5863
5864                         preferred_refresh = drm_mode_vrefresh(preferred_mode);
5865                 }
5866         }
5867
5868         if (recalculate_timing)
5869                 drm_mode_set_crtcinfo(&saved_mode, 0);
5870         else if (!dm_state)
5871                 drm_mode_set_crtcinfo(&mode, 0);
5872
5873         /*
5874         * If scaling is enabled and refresh rate didn't change
5875         * we copy the vic and polarities of the old timings
5876         */
5877         if (!scale || mode_refresh != preferred_refresh)
5878                 fill_stream_properties_from_drm_display_mode(
5879                         stream, &mode, &aconnector->base, con_state, NULL,
5880                         requested_bpc);
5881         else
5882                 fill_stream_properties_from_drm_display_mode(
5883                         stream, &mode, &aconnector->base, con_state, old_stream,
5884                         requested_bpc);
5885
5886 #if defined(CONFIG_DRM_AMD_DC_DCN)
5887         /* SST DSC determination policy */
5888         update_dsc_caps(aconnector, sink, stream, &dsc_caps);
5889         if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
5890                 apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
5891 #endif
5892
5893         update_stream_scaling_settings(&mode, dm_state, stream);
5894
5895         fill_audio_info(
5896                 &stream->audio_info,
5897                 drm_connector,
5898                 sink);
5899
5900         update_stream_signal(stream, sink);
5901
5902         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5903                 mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
5904
5905         if (stream->link->psr_settings.psr_feature_enabled) {
5906                 //
5907                 // should decide stream support vsc sdp colorimetry capability
5908                 // before building vsc info packet
5909                 //
5910                 stream->use_vsc_sdp_for_colorimetry = false;
5911                 if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
5912                         stream->use_vsc_sdp_for_colorimetry =
5913                                 aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
5914                 } else {
5915                         if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
5916                                 stream->use_vsc_sdp_for_colorimetry = true;
5917                 }
5918                 if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
5919                         tf = TRANSFER_FUNC_GAMMA_22;
5920                 mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
5921                 aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
5922
5923         }
5924 finish:
5925         dc_sink_release(sink);
5926
5927         return stream;
5928 }
5929
5930 static enum drm_connector_status
5931 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
5932 {
5933         bool connected;
5934         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5935
5936         /*
5937          * Notes:
5938          * 1. This interface is NOT called in context of HPD irq.
5939          * 2. This interface *is called* in context of user-mode ioctl. Which
5940          * makes it a bad place for *any* MST-related activity.
5941          */
5942
5943         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
5944             !aconnector->fake_enable)
5945                 connected = (aconnector->dc_sink != NULL);
5946         else
5947                 connected = (aconnector->base.force == DRM_FORCE_ON ||
5948                                 aconnector->base.force == DRM_FORCE_ON_DIGITAL);
5949
5950         update_subconnector_property(aconnector);
5951
5952         return (connected ? connector_status_connected :
5953                         connector_status_disconnected);
5954 }
5955
5956 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
5957                                             struct drm_connector_state *connector_state,
5958                                             struct drm_property *property,
5959                                             uint64_t val)
5960 {
5961         struct drm_device *dev = connector->dev;
5962         struct amdgpu_device *adev = drm_to_adev(dev);
5963         struct dm_connector_state *dm_old_state =
5964                 to_dm_connector_state(connector->state);
5965         struct dm_connector_state *dm_new_state =
5966                 to_dm_connector_state(connector_state);
5967
5968         int ret = -EINVAL;
5969
5970         if (property == dev->mode_config.scaling_mode_property) {
5971                 enum amdgpu_rmx_type rmx_type;
5972
5973                 switch (val) {
5974                 case DRM_MODE_SCALE_CENTER:
5975                         rmx_type = RMX_CENTER;
5976                         break;
5977                 case DRM_MODE_SCALE_ASPECT:
5978                         rmx_type = RMX_ASPECT;
5979                         break;
5980                 case DRM_MODE_SCALE_FULLSCREEN:
5981                         rmx_type = RMX_FULL;
5982                         break;
5983                 case DRM_MODE_SCALE_NONE:
5984                 default:
5985                         rmx_type = RMX_OFF;
5986                         break;
5987                 }
5988
5989                 if (dm_old_state->scaling == rmx_type)
5990                         return 0;
5991
5992                 dm_new_state->scaling = rmx_type;
5993                 ret = 0;
5994         } else if (property == adev->mode_info.underscan_hborder_property) {
5995                 dm_new_state->underscan_hborder = val;
5996                 ret = 0;
5997         } else if (property == adev->mode_info.underscan_vborder_property) {
5998                 dm_new_state->underscan_vborder = val;
5999                 ret = 0;
6000         } else if (property == adev->mode_info.underscan_property) {
6001                 dm_new_state->underscan_enable = val;
6002                 ret = 0;
6003         } else if (property == adev->mode_info.abm_level_property) {
6004                 dm_new_state->abm_level = val;
6005                 ret = 0;
6006         }
6007
6008         return ret;
6009 }
6010
6011 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
6012                                             const struct drm_connector_state *state,
6013                                             struct drm_property *property,
6014                                             uint64_t *val)
6015 {
6016         struct drm_device *dev = connector->dev;
6017         struct amdgpu_device *adev = drm_to_adev(dev);
6018         struct dm_connector_state *dm_state =
6019                 to_dm_connector_state(state);
6020         int ret = -EINVAL;
6021
6022         if (property == dev->mode_config.scaling_mode_property) {
6023                 switch (dm_state->scaling) {
6024                 case RMX_CENTER:
6025                         *val = DRM_MODE_SCALE_CENTER;
6026                         break;
6027                 case RMX_ASPECT:
6028                         *val = DRM_MODE_SCALE_ASPECT;
6029                         break;
6030                 case RMX_FULL:
6031                         *val = DRM_MODE_SCALE_FULLSCREEN;
6032                         break;
6033                 case RMX_OFF:
6034                 default:
6035                         *val = DRM_MODE_SCALE_NONE;
6036                         break;
6037                 }
6038                 ret = 0;
6039         } else if (property == adev->mode_info.underscan_hborder_property) {
6040                 *val = dm_state->underscan_hborder;
6041                 ret = 0;
6042         } else if (property == adev->mode_info.underscan_vborder_property) {
6043                 *val = dm_state->underscan_vborder;
6044                 ret = 0;
6045         } else if (property == adev->mode_info.underscan_property) {
6046                 *val = dm_state->underscan_enable;
6047                 ret = 0;
6048         } else if (property == adev->mode_info.abm_level_property) {
6049                 *val = dm_state->abm_level;
6050                 ret = 0;
6051         }
6052
6053         return ret;
6054 }
6055
6056 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6057 {
6058         struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6059
6060         drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6061 }
6062
6063 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6064 {
6065         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6066         const struct dc_link *link = aconnector->dc_link;
6067         struct amdgpu_device *adev = drm_to_adev(connector->dev);
6068         struct amdgpu_display_manager *dm = &adev->dm;
6069         int i;
6070
6071         /*
6072          * Call only if mst_mgr was initialized before since it's not done
6073          * for all connector types.
6074          */
6075         if (aconnector->mst_mgr.dev)
6076                 drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6077
6078 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
6079         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
6080         for (i = 0; i < dm->num_of_edps; i++) {
6081                 if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6082                         backlight_device_unregister(dm->backlight_dev[i]);
6083                         dm->backlight_dev[i] = NULL;
6084                 }
6085         }
6086 #endif
6087
6088         if (aconnector->dc_em_sink)
6089                 dc_sink_release(aconnector->dc_em_sink);
6090         aconnector->dc_em_sink = NULL;
6091         if (aconnector->dc_sink)
6092                 dc_sink_release(aconnector->dc_sink);
6093         aconnector->dc_sink = NULL;
6094
6095         drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6096         drm_connector_unregister(connector);
6097         drm_connector_cleanup(connector);
6098         if (aconnector->i2c) {
6099                 i2c_del_adapter(&aconnector->i2c->base);
6100                 kfree(aconnector->i2c);
6101         }
6102         kfree(aconnector->dm_dp_aux.aux.name);
6103
6104         kfree(connector);
6105 }
6106
6107 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6108 {
6109         struct dm_connector_state *state =
6110                 to_dm_connector_state(connector->state);
6111
6112         if (connector->state)
6113                 __drm_atomic_helper_connector_destroy_state(connector->state);
6114
6115         kfree(state);
6116
6117         state = kzalloc(sizeof(*state), GFP_KERNEL);
6118
6119         if (state) {
6120                 state->scaling = RMX_OFF;
6121                 state->underscan_enable = false;
6122                 state->underscan_hborder = 0;
6123                 state->underscan_vborder = 0;
6124                 state->base.max_requested_bpc = 8;
6125                 state->vcpi_slots = 0;
6126                 state->pbn = 0;
6127
6128                 if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6129                         state->abm_level = amdgpu_dm_abm_level;
6130
6131                 __drm_atomic_helper_connector_reset(connector, &state->base);
6132         }
6133 }
6134
6135 struct drm_connector_state *
6136 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6137 {
6138         struct dm_connector_state *state =
6139                 to_dm_connector_state(connector->state);
6140
6141         struct dm_connector_state *new_state =
6142                         kmemdup(state, sizeof(*state), GFP_KERNEL);
6143
6144         if (!new_state)
6145                 return NULL;
6146
6147         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6148
6149         new_state->freesync_capable = state->freesync_capable;
6150         new_state->abm_level = state->abm_level;
6151         new_state->scaling = state->scaling;
6152         new_state->underscan_enable = state->underscan_enable;
6153         new_state->underscan_hborder = state->underscan_hborder;
6154         new_state->underscan_vborder = state->underscan_vborder;
6155         new_state->vcpi_slots = state->vcpi_slots;
6156         new_state->pbn = state->pbn;
6157         return &new_state->base;
6158 }
6159
6160 static int
6161 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6162 {
6163         struct amdgpu_dm_connector *amdgpu_dm_connector =
6164                 to_amdgpu_dm_connector(connector);
6165         int r;
6166
6167         if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6168             (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6169                 amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6170                 r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6171                 if (r)
6172                         return r;
6173         }
6174
6175 #if defined(CONFIG_DEBUG_FS)
6176         connector_debugfs_init(amdgpu_dm_connector);
6177 #endif
6178
6179         return 0;
6180 }
6181
6182 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6183         .reset = amdgpu_dm_connector_funcs_reset,
6184         .detect = amdgpu_dm_connector_detect,
6185         .fill_modes = drm_helper_probe_single_connector_modes,
6186         .destroy = amdgpu_dm_connector_destroy,
6187         .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6188         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6189         .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6190         .atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6191         .late_register = amdgpu_dm_connector_late_register,
6192         .early_unregister = amdgpu_dm_connector_unregister
6193 };
6194
6195 static int get_modes(struct drm_connector *connector)
6196 {
6197         return amdgpu_dm_connector_get_modes(connector);
6198 }
6199
6200 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6201 {
6202         struct dc_sink_init_data init_params = {
6203                         .link = aconnector->dc_link,
6204                         .sink_signal = SIGNAL_TYPE_VIRTUAL
6205         };
6206         struct edid *edid;
6207
6208         if (!aconnector->base.edid_blob_ptr) {
6209                 DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6210                                 aconnector->base.name);
6211
6212                 aconnector->base.force = DRM_FORCE_OFF;
6213                 return;
6214         }
6215
6216         edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6217
6218         aconnector->edid = edid;
6219
6220         aconnector->dc_em_sink = dc_link_add_remote_sink(
6221                 aconnector->dc_link,
6222                 (uint8_t *)edid,
6223                 (edid->extensions + 1) * EDID_LENGTH,
6224                 &init_params);
6225
6226         if (aconnector->base.force == DRM_FORCE_ON) {
6227                 aconnector->dc_sink = aconnector->dc_link->local_sink ?
6228                 aconnector->dc_link->local_sink :
6229                 aconnector->dc_em_sink;
6230                 dc_sink_retain(aconnector->dc_sink);
6231         }
6232 }
6233
6234 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6235 {
6236         struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6237
6238         /*
6239          * In case of headless boot with force on for DP managed connector
6240          * Those settings have to be != 0 to get initial modeset
6241          */
6242         if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6243                 link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6244                 link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6245         }
6246
6247         create_eml_sink(aconnector);
6248 }
6249
6250 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
6251                                                 struct dc_stream_state *stream)
6252 {
6253         enum dc_status dc_result = DC_ERROR_UNEXPECTED;
6254         struct dc_plane_state *dc_plane_state = NULL;
6255         struct dc_state *dc_state = NULL;
6256
6257         if (!stream)
6258                 goto cleanup;
6259
6260         dc_plane_state = dc_create_plane_state(dc);
6261         if (!dc_plane_state)
6262                 goto cleanup;
6263
6264         dc_state = dc_create_state(dc);
6265         if (!dc_state)
6266                 goto cleanup;
6267
6268         /* populate stream to plane */
6269         dc_plane_state->src_rect.height  = stream->src.height;
6270         dc_plane_state->src_rect.width   = stream->src.width;
6271         dc_plane_state->dst_rect.height  = stream->src.height;
6272         dc_plane_state->dst_rect.width   = stream->src.width;
6273         dc_plane_state->clip_rect.height = stream->src.height;
6274         dc_plane_state->clip_rect.width  = stream->src.width;
6275         dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
6276         dc_plane_state->plane_size.surface_size.height = stream->src.height;
6277         dc_plane_state->plane_size.surface_size.width  = stream->src.width;
6278         dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
6279         dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
6280         dc_plane_state->tiling_info.gfx9.swizzle =  DC_SW_UNKNOWN;
6281         dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6282         dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
6283         dc_plane_state->rotation = ROTATION_ANGLE_0;
6284         dc_plane_state->is_tiling_rotated = false;
6285         dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
6286
6287         dc_result = dc_validate_stream(dc, stream);
6288         if (dc_result == DC_OK)
6289                 dc_result = dc_validate_plane(dc, dc_plane_state);
6290
6291         if (dc_result == DC_OK)
6292                 dc_result = dc_add_stream_to_ctx(dc, dc_state, stream);
6293
6294         if (dc_result == DC_OK && !dc_add_plane_to_context(
6295                                                 dc,
6296                                                 stream,
6297                                                 dc_plane_state,
6298                                                 dc_state))
6299                 dc_result = DC_FAIL_ATTACH_SURFACES;
6300
6301         if (dc_result == DC_OK)
6302                 dc_result = dc_validate_global_state(dc, dc_state, true);
6303
6304 cleanup:
6305         if (dc_state)
6306                 dc_release_state(dc_state);
6307
6308         if (dc_plane_state)
6309                 dc_plane_state_release(dc_plane_state);
6310
6311         return dc_result;
6312 }
6313
6314 struct dc_stream_state *
6315 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6316                                 const struct drm_display_mode *drm_mode,
6317                                 const struct dm_connector_state *dm_state,
6318                                 const struct dc_stream_state *old_stream)
6319 {
6320         struct drm_connector *connector = &aconnector->base;
6321         struct amdgpu_device *adev = drm_to_adev(connector->dev);
6322         struct dc_stream_state *stream;
6323         const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6324         int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6325         enum dc_status dc_result = DC_OK;
6326
6327         do {
6328                 stream = create_stream_for_sink(aconnector, drm_mode,
6329                                                 dm_state, old_stream,
6330                                                 requested_bpc);
6331                 if (stream == NULL) {
6332                         DRM_ERROR("Failed to create stream for sink!\n");
6333                         break;
6334                 }
6335
6336                 dc_result = dc_validate_stream(adev->dm.dc, stream);
6337                 if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6338                         dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6339
6340                 if (dc_result == DC_OK)
6341                         dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
6342
6343                 if (dc_result != DC_OK) {
6344                         DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6345                                       drm_mode->hdisplay,
6346                                       drm_mode->vdisplay,
6347                                       drm_mode->clock,
6348                                       dc_result,
6349                                       dc_status_to_str(dc_result));
6350
6351                         dc_stream_release(stream);
6352                         stream = NULL;
6353                         requested_bpc -= 2; /* lower bpc to retry validation */
6354                 }
6355
6356         } while (stream == NULL && requested_bpc >= 6);
6357
6358         if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6359                 DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6360
6361                 aconnector->force_yuv420_output = true;
6362                 stream = create_validate_stream_for_sink(aconnector, drm_mode,
6363                                                 dm_state, old_stream);
6364                 aconnector->force_yuv420_output = false;
6365         }
6366
6367         return stream;
6368 }
6369
6370 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6371                                    struct drm_display_mode *mode)
6372 {
6373         int result = MODE_ERROR;
6374         struct dc_sink *dc_sink;
6375         /* TODO: Unhardcode stream count */
6376         struct dc_stream_state *stream;
6377         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6378
6379         if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6380                         (mode->flags & DRM_MODE_FLAG_DBLSCAN))
6381                 return result;
6382
6383         /*
6384          * Only run this the first time mode_valid is called to initilialize
6385          * EDID mgmt
6386          */
6387         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6388                 !aconnector->dc_em_sink)
6389                 handle_edid_mgmt(aconnector);
6390
6391         dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6392
6393         if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6394                                 aconnector->base.force != DRM_FORCE_ON) {
6395                 DRM_ERROR("dc_sink is NULL!\n");
6396                 goto fail;
6397         }
6398
6399         stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6400         if (stream) {
6401                 dc_stream_release(stream);
6402                 result = MODE_OK;
6403         }
6404
6405 fail:
6406         /* TODO: error handling*/
6407         return result;
6408 }
6409
6410 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6411                                 struct dc_info_packet *out)
6412 {
6413         struct hdmi_drm_infoframe frame;
6414         unsigned char buf[30]; /* 26 + 4 */
6415         ssize_t len;
6416         int ret, i;
6417
6418         memset(out, 0, sizeof(*out));
6419
6420         if (!state->hdr_output_metadata)
6421                 return 0;
6422
6423         ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6424         if (ret)
6425                 return ret;
6426
6427         len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6428         if (len < 0)
6429                 return (int)len;
6430
6431         /* Static metadata is a fixed 26 bytes + 4 byte header. */
6432         if (len != 30)
6433                 return -EINVAL;
6434
6435         /* Prepare the infopacket for DC. */
6436         switch (state->connector->connector_type) {
6437         case DRM_MODE_CONNECTOR_HDMIA:
6438                 out->hb0 = 0x87; /* type */
6439                 out->hb1 = 0x01; /* version */
6440                 out->hb2 = 0x1A; /* length */
6441                 out->sb[0] = buf[3]; /* checksum */
6442                 i = 1;
6443                 break;
6444
6445         case DRM_MODE_CONNECTOR_DisplayPort:
6446         case DRM_MODE_CONNECTOR_eDP:
6447                 out->hb0 = 0x00; /* sdp id, zero */
6448                 out->hb1 = 0x87; /* type */
6449                 out->hb2 = 0x1D; /* payload len - 1 */
6450                 out->hb3 = (0x13 << 2); /* sdp version */
6451                 out->sb[0] = 0x01; /* version */
6452                 out->sb[1] = 0x1A; /* length */
6453                 i = 2;
6454                 break;
6455
6456         default:
6457                 return -EINVAL;
6458         }
6459
6460         memcpy(&out->sb[i], &buf[4], 26);
6461         out->valid = true;
6462
6463         print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6464                        sizeof(out->sb), false);
6465
6466         return 0;
6467 }
6468
6469 static int
6470 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6471                                  struct drm_atomic_state *state)
6472 {
6473         struct drm_connector_state *new_con_state =
6474                 drm_atomic_get_new_connector_state(state, conn);
6475         struct drm_connector_state *old_con_state =
6476                 drm_atomic_get_old_connector_state(state, conn);
6477         struct drm_crtc *crtc = new_con_state->crtc;
6478         struct drm_crtc_state *new_crtc_state;
6479         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6480         int ret;
6481
6482         trace_amdgpu_dm_connector_atomic_check(new_con_state);
6483
6484         if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6485                 ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6486                 if (ret < 0)
6487                         return ret;
6488         }
6489
6490         if (!crtc)
6491                 return 0;
6492
6493         if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6494                 struct dc_info_packet hdr_infopacket;
6495
6496                 ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6497                 if (ret)
6498                         return ret;
6499
6500                 new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6501                 if (IS_ERR(new_crtc_state))
6502                         return PTR_ERR(new_crtc_state);
6503
6504                 /*
6505                  * DC considers the stream backends changed if the
6506                  * static metadata changes. Forcing the modeset also
6507                  * gives a simple way for userspace to switch from
6508                  * 8bpc to 10bpc when setting the metadata to enter
6509                  * or exit HDR.
6510                  *
6511                  * Changing the static metadata after it's been
6512                  * set is permissible, however. So only force a
6513                  * modeset if we're entering or exiting HDR.
6514                  */
6515                 new_crtc_state->mode_changed =
6516                         !old_con_state->hdr_output_metadata ||
6517                         !new_con_state->hdr_output_metadata;
6518         }
6519
6520         return 0;
6521 }
6522
6523 static const struct drm_connector_helper_funcs
6524 amdgpu_dm_connector_helper_funcs = {
6525         /*
6526          * If hotplugging a second bigger display in FB Con mode, bigger resolution
6527          * modes will be filtered by drm_mode_validate_size(), and those modes
6528          * are missing after user start lightdm. So we need to renew modes list.
6529          * in get_modes call back, not just return the modes count
6530          */
6531         .get_modes = get_modes,
6532         .mode_valid = amdgpu_dm_connector_mode_valid,
6533         .atomic_check = amdgpu_dm_connector_atomic_check,
6534 };
6535
6536 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6537 {
6538
6539 }
6540
6541 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6542 {
6543         switch (display_color_depth) {
6544         case COLOR_DEPTH_666:
6545                 return 6;
6546         case COLOR_DEPTH_888:
6547                 return 8;
6548         case COLOR_DEPTH_101010:
6549                 return 10;
6550         case COLOR_DEPTH_121212:
6551                 return 12;
6552         case COLOR_DEPTH_141414:
6553                 return 14;
6554         case COLOR_DEPTH_161616:
6555                 return 16;
6556         default:
6557                 break;
6558         }
6559         return 0;
6560 }
6561
6562 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6563                                           struct drm_crtc_state *crtc_state,
6564                                           struct drm_connector_state *conn_state)
6565 {
6566         struct drm_atomic_state *state = crtc_state->state;
6567         struct drm_connector *connector = conn_state->connector;
6568         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6569         struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6570         const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6571         struct drm_dp_mst_topology_mgr *mst_mgr;
6572         struct drm_dp_mst_port *mst_port;
6573         struct drm_dp_mst_topology_state *mst_state;
6574         enum dc_color_depth color_depth;
6575         int clock, bpp = 0;
6576         bool is_y420 = false;
6577
6578         if (!aconnector->port || !aconnector->dc_sink)
6579                 return 0;
6580
6581         mst_port = aconnector->port;
6582         mst_mgr = &aconnector->mst_port->mst_mgr;
6583
6584         if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6585                 return 0;
6586
6587         mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6588         if (IS_ERR(mst_state))
6589                 return PTR_ERR(mst_state);
6590
6591         if (!mst_state->pbn_div)
6592                 mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_port->dc_link);
6593
6594         if (!state->duplicated) {
6595                 int max_bpc = conn_state->max_requested_bpc;
6596                 is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6597                           aconnector->force_yuv420_output;
6598                 color_depth = convert_color_depth_from_display_info(connector,
6599                                                                     is_y420,
6600                                                                     max_bpc);
6601                 bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6602                 clock = adjusted_mode->clock;
6603                 dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6604         }
6605
6606         dm_new_connector_state->vcpi_slots =
6607                 drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6608                                               dm_new_connector_state->pbn);
6609         if (dm_new_connector_state->vcpi_slots < 0) {
6610                 DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6611                 return dm_new_connector_state->vcpi_slots;
6612         }
6613         return 0;
6614 }
6615
6616 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6617         .disable = dm_encoder_helper_disable,
6618         .atomic_check = dm_encoder_helper_atomic_check
6619 };
6620
6621 #if defined(CONFIG_DRM_AMD_DC_DCN)
6622 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6623                                             struct dc_state *dc_state,
6624                                             struct dsc_mst_fairness_vars *vars)
6625 {
6626         struct dc_stream_state *stream = NULL;
6627         struct drm_connector *connector;
6628         struct drm_connector_state *new_con_state;
6629         struct amdgpu_dm_connector *aconnector;
6630         struct dm_connector_state *dm_conn_state;
6631         int i, j, ret;
6632         int vcpi, pbn_div, pbn, slot_num = 0;
6633
6634         for_each_new_connector_in_state(state, connector, new_con_state, i) {
6635
6636                 aconnector = to_amdgpu_dm_connector(connector);
6637
6638                 if (!aconnector->port)
6639                         continue;
6640
6641                 if (!new_con_state || !new_con_state->crtc)
6642                         continue;
6643
6644                 dm_conn_state = to_dm_connector_state(new_con_state);
6645
6646                 for (j = 0; j < dc_state->stream_count; j++) {
6647                         stream = dc_state->streams[j];
6648                         if (!stream)
6649                                 continue;
6650
6651                         if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6652                                 break;
6653
6654                         stream = NULL;
6655                 }
6656
6657                 if (!stream)
6658                         continue;
6659
6660                 pbn_div = dm_mst_get_pbn_divider(stream->link);
6661                 /* pbn is calculated by compute_mst_dsc_configs_for_state*/
6662                 for (j = 0; j < dc_state->stream_count; j++) {
6663                         if (vars[j].aconnector == aconnector) {
6664                                 pbn = vars[j].pbn;
6665                                 break;
6666                         }
6667                 }
6668
6669                 if (j == dc_state->stream_count)
6670                         continue;
6671
6672                 slot_num = DIV_ROUND_UP(pbn, pbn_div);
6673
6674                 if (stream->timing.flags.DSC != 1) {
6675                         dm_conn_state->pbn = pbn;
6676                         dm_conn_state->vcpi_slots = slot_num;
6677
6678                         ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->port,
6679                                                            dm_conn_state->pbn, false);
6680                         if (ret < 0)
6681                                 return ret;
6682
6683                         continue;
6684                 }
6685
6686                 vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->port, pbn, true);
6687                 if (vcpi < 0)
6688                         return vcpi;
6689
6690                 dm_conn_state->pbn = pbn;
6691                 dm_conn_state->vcpi_slots = vcpi;
6692         }
6693         return 0;
6694 }
6695 #endif
6696
6697 static int to_drm_connector_type(enum signal_type st)
6698 {
6699         switch (st) {
6700         case SIGNAL_TYPE_HDMI_TYPE_A:
6701                 return DRM_MODE_CONNECTOR_HDMIA;
6702         case SIGNAL_TYPE_EDP:
6703                 return DRM_MODE_CONNECTOR_eDP;
6704         case SIGNAL_TYPE_LVDS:
6705                 return DRM_MODE_CONNECTOR_LVDS;
6706         case SIGNAL_TYPE_RGB:
6707                 return DRM_MODE_CONNECTOR_VGA;
6708         case SIGNAL_TYPE_DISPLAY_PORT:
6709         case SIGNAL_TYPE_DISPLAY_PORT_MST:
6710                 return DRM_MODE_CONNECTOR_DisplayPort;
6711         case SIGNAL_TYPE_DVI_DUAL_LINK:
6712         case SIGNAL_TYPE_DVI_SINGLE_LINK:
6713                 return DRM_MODE_CONNECTOR_DVID;
6714         case SIGNAL_TYPE_VIRTUAL:
6715                 return DRM_MODE_CONNECTOR_VIRTUAL;
6716
6717         default:
6718                 return DRM_MODE_CONNECTOR_Unknown;
6719         }
6720 }
6721
6722 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6723 {
6724         struct drm_encoder *encoder;
6725
6726         /* There is only one encoder per connector */
6727         drm_connector_for_each_possible_encoder(connector, encoder)
6728                 return encoder;
6729
6730         return NULL;
6731 }
6732
6733 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6734 {
6735         struct drm_encoder *encoder;
6736         struct amdgpu_encoder *amdgpu_encoder;
6737
6738         encoder = amdgpu_dm_connector_to_encoder(connector);
6739
6740         if (encoder == NULL)
6741                 return;
6742
6743         amdgpu_encoder = to_amdgpu_encoder(encoder);
6744
6745         amdgpu_encoder->native_mode.clock = 0;
6746
6747         if (!list_empty(&connector->probed_modes)) {
6748                 struct drm_display_mode *preferred_mode = NULL;
6749
6750                 list_for_each_entry(preferred_mode,
6751                                     &connector->probed_modes,
6752                                     head) {
6753                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6754                                 amdgpu_encoder->native_mode = *preferred_mode;
6755
6756                         break;
6757                 }
6758
6759         }
6760 }
6761
6762 static struct drm_display_mode *
6763 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6764                              char *name,
6765                              int hdisplay, int vdisplay)
6766 {
6767         struct drm_device *dev = encoder->dev;
6768         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6769         struct drm_display_mode *mode = NULL;
6770         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6771
6772         mode = drm_mode_duplicate(dev, native_mode);
6773
6774         if (mode == NULL)
6775                 return NULL;
6776
6777         mode->hdisplay = hdisplay;
6778         mode->vdisplay = vdisplay;
6779         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6780         strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6781
6782         return mode;
6783
6784 }
6785
6786 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6787                                                  struct drm_connector *connector)
6788 {
6789         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6790         struct drm_display_mode *mode = NULL;
6791         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6792         struct amdgpu_dm_connector *amdgpu_dm_connector =
6793                                 to_amdgpu_dm_connector(connector);
6794         int i;
6795         int n;
6796         struct mode_size {
6797                 char name[DRM_DISPLAY_MODE_LEN];
6798                 int w;
6799                 int h;
6800         } common_modes[] = {
6801                 {  "640x480",  640,  480},
6802                 {  "800x600",  800,  600},
6803                 { "1024x768", 1024,  768},
6804                 { "1280x720", 1280,  720},
6805                 { "1280x800", 1280,  800},
6806                 {"1280x1024", 1280, 1024},
6807                 { "1440x900", 1440,  900},
6808                 {"1680x1050", 1680, 1050},
6809                 {"1600x1200", 1600, 1200},
6810                 {"1920x1080", 1920, 1080},
6811                 {"1920x1200", 1920, 1200}
6812         };
6813
6814         n = ARRAY_SIZE(common_modes);
6815
6816         for (i = 0; i < n; i++) {
6817                 struct drm_display_mode *curmode = NULL;
6818                 bool mode_existed = false;
6819
6820                 if (common_modes[i].w > native_mode->hdisplay ||
6821                     common_modes[i].h > native_mode->vdisplay ||
6822                    (common_modes[i].w == native_mode->hdisplay &&
6823                     common_modes[i].h == native_mode->vdisplay))
6824                         continue;
6825
6826                 list_for_each_entry(curmode, &connector->probed_modes, head) {
6827                         if (common_modes[i].w == curmode->hdisplay &&
6828                             common_modes[i].h == curmode->vdisplay) {
6829                                 mode_existed = true;
6830                                 break;
6831                         }
6832                 }
6833
6834                 if (mode_existed)
6835                         continue;
6836
6837                 mode = amdgpu_dm_create_common_mode(encoder,
6838                                 common_modes[i].name, common_modes[i].w,
6839                                 common_modes[i].h);
6840                 if (!mode)
6841                         continue;
6842
6843                 drm_mode_probed_add(connector, mode);
6844                 amdgpu_dm_connector->num_modes++;
6845         }
6846 }
6847
6848 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6849 {
6850         struct drm_encoder *encoder;
6851         struct amdgpu_encoder *amdgpu_encoder;
6852         const struct drm_display_mode *native_mode;
6853
6854         if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6855             connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6856                 return;
6857
6858         mutex_lock(&connector->dev->mode_config.mutex);
6859         amdgpu_dm_connector_get_modes(connector);
6860         mutex_unlock(&connector->dev->mode_config.mutex);
6861
6862         encoder = amdgpu_dm_connector_to_encoder(connector);
6863         if (!encoder)
6864                 return;
6865
6866         amdgpu_encoder = to_amdgpu_encoder(encoder);
6867
6868         native_mode = &amdgpu_encoder->native_mode;
6869         if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6870                 return;
6871
6872         drm_connector_set_panel_orientation_with_quirk(connector,
6873                                                        DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6874                                                        native_mode->hdisplay,
6875                                                        native_mode->vdisplay);
6876 }
6877
6878 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6879                                               struct edid *edid)
6880 {
6881         struct amdgpu_dm_connector *amdgpu_dm_connector =
6882                         to_amdgpu_dm_connector(connector);
6883
6884         if (edid) {
6885                 /* empty probed_modes */
6886                 INIT_LIST_HEAD(&connector->probed_modes);
6887                 amdgpu_dm_connector->num_modes =
6888                                 drm_add_edid_modes(connector, edid);
6889
6890                 /* sorting the probed modes before calling function
6891                  * amdgpu_dm_get_native_mode() since EDID can have
6892                  * more than one preferred mode. The modes that are
6893                  * later in the probed mode list could be of higher
6894                  * and preferred resolution. For example, 3840x2160
6895                  * resolution in base EDID preferred timing and 4096x2160
6896                  * preferred resolution in DID extension block later.
6897                  */
6898                 drm_mode_sort(&connector->probed_modes);
6899                 amdgpu_dm_get_native_mode(connector);
6900
6901                 /* Freesync capabilities are reset by calling
6902                  * drm_add_edid_modes() and need to be
6903                  * restored here.
6904                  */
6905                 amdgpu_dm_update_freesync_caps(connector, edid);
6906         } else {
6907                 amdgpu_dm_connector->num_modes = 0;
6908         }
6909 }
6910
6911 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
6912                               struct drm_display_mode *mode)
6913 {
6914         struct drm_display_mode *m;
6915
6916         list_for_each_entry (m, &aconnector->base.probed_modes, head) {
6917                 if (drm_mode_equal(m, mode))
6918                         return true;
6919         }
6920
6921         return false;
6922 }
6923
6924 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
6925 {
6926         const struct drm_display_mode *m;
6927         struct drm_display_mode *new_mode;
6928         uint i;
6929         u32 new_modes_count = 0;
6930
6931         /* Standard FPS values
6932          *
6933          * 23.976       - TV/NTSC
6934          * 24           - Cinema
6935          * 25           - TV/PAL
6936          * 29.97        - TV/NTSC
6937          * 30           - TV/NTSC
6938          * 48           - Cinema HFR
6939          * 50           - TV/PAL
6940          * 60           - Commonly used
6941          * 48,72,96,120 - Multiples of 24
6942          */
6943         static const u32 common_rates[] = {
6944                 23976, 24000, 25000, 29970, 30000,
6945                 48000, 50000, 60000, 72000, 96000, 120000
6946         };
6947
6948         /*
6949          * Find mode with highest refresh rate with the same resolution
6950          * as the preferred mode. Some monitors report a preferred mode
6951          * with lower resolution than the highest refresh rate supported.
6952          */
6953
6954         m = get_highest_refresh_rate_mode(aconnector, true);
6955         if (!m)
6956                 return 0;
6957
6958         for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
6959                 u64 target_vtotal, target_vtotal_diff;
6960                 u64 num, den;
6961
6962                 if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
6963                         continue;
6964
6965                 if (common_rates[i] < aconnector->min_vfreq * 1000 ||
6966                     common_rates[i] > aconnector->max_vfreq * 1000)
6967                         continue;
6968
6969                 num = (unsigned long long)m->clock * 1000 * 1000;
6970                 den = common_rates[i] * (unsigned long long)m->htotal;
6971                 target_vtotal = div_u64(num, den);
6972                 target_vtotal_diff = target_vtotal - m->vtotal;
6973
6974                 /* Check for illegal modes */
6975                 if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
6976                     m->vsync_end + target_vtotal_diff < m->vsync_start ||
6977                     m->vtotal + target_vtotal_diff < m->vsync_end)
6978                         continue;
6979
6980                 new_mode = drm_mode_duplicate(aconnector->base.dev, m);
6981                 if (!new_mode)
6982                         goto out;
6983
6984                 new_mode->vtotal += (u16)target_vtotal_diff;
6985                 new_mode->vsync_start += (u16)target_vtotal_diff;
6986                 new_mode->vsync_end += (u16)target_vtotal_diff;
6987                 new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6988                 new_mode->type |= DRM_MODE_TYPE_DRIVER;
6989
6990                 if (!is_duplicate_mode(aconnector, new_mode)) {
6991                         drm_mode_probed_add(&aconnector->base, new_mode);
6992                         new_modes_count += 1;
6993                 } else
6994                         drm_mode_destroy(aconnector->base.dev, new_mode);
6995         }
6996  out:
6997         return new_modes_count;
6998 }
6999
7000 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
7001                                                    struct edid *edid)
7002 {
7003         struct amdgpu_dm_connector *amdgpu_dm_connector =
7004                 to_amdgpu_dm_connector(connector);
7005
7006         if (!(amdgpu_freesync_vid_mode && edid))
7007                 return;
7008
7009         if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
7010                 amdgpu_dm_connector->num_modes +=
7011                         add_fs_modes(amdgpu_dm_connector);
7012 }
7013
7014 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
7015 {
7016         struct amdgpu_dm_connector *amdgpu_dm_connector =
7017                         to_amdgpu_dm_connector(connector);
7018         struct drm_encoder *encoder;
7019         struct edid *edid = amdgpu_dm_connector->edid;
7020
7021         encoder = amdgpu_dm_connector_to_encoder(connector);
7022
7023         if (!drm_edid_is_valid(edid)) {
7024                 amdgpu_dm_connector->num_modes =
7025                                 drm_add_modes_noedid(connector, 640, 480);
7026         } else {
7027                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
7028                 amdgpu_dm_connector_add_common_modes(encoder, connector);
7029                 amdgpu_dm_connector_add_freesync_modes(connector, edid);
7030         }
7031         amdgpu_dm_fbc_init(connector);
7032
7033         return amdgpu_dm_connector->num_modes;
7034 }
7035
7036 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
7037                                      struct amdgpu_dm_connector *aconnector,
7038                                      int connector_type,
7039                                      struct dc_link *link,
7040                                      int link_index)
7041 {
7042         struct amdgpu_device *adev = drm_to_adev(dm->ddev);
7043
7044         /*
7045          * Some of the properties below require access to state, like bpc.
7046          * Allocate some default initial connector state with our reset helper.
7047          */
7048         if (aconnector->base.funcs->reset)
7049                 aconnector->base.funcs->reset(&aconnector->base);
7050
7051         aconnector->connector_id = link_index;
7052         aconnector->dc_link = link;
7053         aconnector->base.interlace_allowed = false;
7054         aconnector->base.doublescan_allowed = false;
7055         aconnector->base.stereo_allowed = false;
7056         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
7057         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
7058         aconnector->audio_inst = -1;
7059         mutex_init(&aconnector->hpd_lock);
7060
7061         /*
7062          * configure support HPD hot plug connector_>polled default value is 0
7063          * which means HPD hot plug not supported
7064          */
7065         switch (connector_type) {
7066         case DRM_MODE_CONNECTOR_HDMIA:
7067                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7068                 aconnector->base.ycbcr_420_allowed =
7069                         link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
7070                 break;
7071         case DRM_MODE_CONNECTOR_DisplayPort:
7072                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7073                 link->link_enc = link_enc_cfg_get_link_enc(link);
7074                 ASSERT(link->link_enc);
7075                 if (link->link_enc)
7076                         aconnector->base.ycbcr_420_allowed =
7077                         link->link_enc->features.dp_ycbcr420_supported ? true : false;
7078                 break;
7079         case DRM_MODE_CONNECTOR_DVID:
7080                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7081                 break;
7082         default:
7083                 break;
7084         }
7085
7086         drm_object_attach_property(&aconnector->base.base,
7087                                 dm->ddev->mode_config.scaling_mode_property,
7088                                 DRM_MODE_SCALE_NONE);
7089
7090         drm_object_attach_property(&aconnector->base.base,
7091                                 adev->mode_info.underscan_property,
7092                                 UNDERSCAN_OFF);
7093         drm_object_attach_property(&aconnector->base.base,
7094                                 adev->mode_info.underscan_hborder_property,
7095                                 0);
7096         drm_object_attach_property(&aconnector->base.base,
7097                                 adev->mode_info.underscan_vborder_property,
7098                                 0);
7099
7100         if (!aconnector->mst_port)
7101                 drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7102
7103         /* This defaults to the max in the range, but we want 8bpc for non-edp. */
7104         aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7105         aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7106
7107         if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7108             (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7109                 drm_object_attach_property(&aconnector->base.base,
7110                                 adev->mode_info.abm_level_property, 0);
7111         }
7112
7113         if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7114             connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7115             connector_type == DRM_MODE_CONNECTOR_eDP) {
7116                 drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7117
7118                 if (!aconnector->mst_port)
7119                         drm_connector_attach_vrr_capable_property(&aconnector->base);
7120
7121 #ifdef CONFIG_DRM_AMD_DC_HDCP
7122                 if (adev->dm.hdcp_workqueue)
7123                         drm_connector_attach_content_protection_property(&aconnector->base, true);
7124 #endif
7125         }
7126 }
7127
7128 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7129                               struct i2c_msg *msgs, int num)
7130 {
7131         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7132         struct ddc_service *ddc_service = i2c->ddc_service;
7133         struct i2c_command cmd;
7134         int i;
7135         int result = -EIO;
7136
7137         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7138
7139         if (!cmd.payloads)
7140                 return result;
7141
7142         cmd.number_of_payloads = num;
7143         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7144         cmd.speed = 100;
7145
7146         for (i = 0; i < num; i++) {
7147                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7148                 cmd.payloads[i].address = msgs[i].addr;
7149                 cmd.payloads[i].length = msgs[i].len;
7150                 cmd.payloads[i].data = msgs[i].buf;
7151         }
7152
7153         if (dc_submit_i2c(
7154                         ddc_service->ctx->dc,
7155                         ddc_service->link->link_index,
7156                         &cmd))
7157                 result = num;
7158
7159         kfree(cmd.payloads);
7160         return result;
7161 }
7162
7163 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7164 {
7165         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7166 }
7167
7168 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7169         .master_xfer = amdgpu_dm_i2c_xfer,
7170         .functionality = amdgpu_dm_i2c_func,
7171 };
7172
7173 static struct amdgpu_i2c_adapter *
7174 create_i2c(struct ddc_service *ddc_service,
7175            int link_index,
7176            int *res)
7177 {
7178         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7179         struct amdgpu_i2c_adapter *i2c;
7180
7181         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7182         if (!i2c)
7183                 return NULL;
7184         i2c->base.owner = THIS_MODULE;
7185         i2c->base.class = I2C_CLASS_DDC;
7186         i2c->base.dev.parent = &adev->pdev->dev;
7187         i2c->base.algo = &amdgpu_dm_i2c_algo;
7188         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7189         i2c_set_adapdata(&i2c->base, i2c);
7190         i2c->ddc_service = ddc_service;
7191
7192         return i2c;
7193 }
7194
7195
7196 /*
7197  * Note: this function assumes that dc_link_detect() was called for the
7198  * dc_link which will be represented by this aconnector.
7199  */
7200 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7201                                     struct amdgpu_dm_connector *aconnector,
7202                                     u32 link_index,
7203                                     struct amdgpu_encoder *aencoder)
7204 {
7205         int res = 0;
7206         int connector_type;
7207         struct dc *dc = dm->dc;
7208         struct dc_link *link = dc_get_link_at_index(dc, link_index);
7209         struct amdgpu_i2c_adapter *i2c;
7210
7211         link->priv = aconnector;
7212
7213         DRM_DEBUG_DRIVER("%s()\n", __func__);
7214
7215         i2c = create_i2c(link->ddc, link->link_index, &res);
7216         if (!i2c) {
7217                 DRM_ERROR("Failed to create i2c adapter data\n");
7218                 return -ENOMEM;
7219         }
7220
7221         aconnector->i2c = i2c;
7222         res = i2c_add_adapter(&i2c->base);
7223
7224         if (res) {
7225                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7226                 goto out_free;
7227         }
7228
7229         connector_type = to_drm_connector_type(link->connector_signal);
7230
7231         res = drm_connector_init_with_ddc(
7232                         dm->ddev,
7233                         &aconnector->base,
7234                         &amdgpu_dm_connector_funcs,
7235                         connector_type,
7236                         &i2c->base);
7237
7238         if (res) {
7239                 DRM_ERROR("connector_init failed\n");
7240                 aconnector->connector_id = -1;
7241                 goto out_free;
7242         }
7243
7244         drm_connector_helper_add(
7245                         &aconnector->base,
7246                         &amdgpu_dm_connector_helper_funcs);
7247
7248         amdgpu_dm_connector_init_helper(
7249                 dm,
7250                 aconnector,
7251                 connector_type,
7252                 link,
7253                 link_index);
7254
7255         drm_connector_attach_encoder(
7256                 &aconnector->base, &aencoder->base);
7257
7258         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7259                 || connector_type == DRM_MODE_CONNECTOR_eDP)
7260                 amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7261
7262 out_free:
7263         if (res) {
7264                 kfree(i2c);
7265                 aconnector->i2c = NULL;
7266         }
7267         return res;
7268 }
7269
7270 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7271 {
7272         switch (adev->mode_info.num_crtc) {
7273         case 1:
7274                 return 0x1;
7275         case 2:
7276                 return 0x3;
7277         case 3:
7278                 return 0x7;
7279         case 4:
7280                 return 0xf;
7281         case 5:
7282                 return 0x1f;
7283         case 6:
7284         default:
7285                 return 0x3f;
7286         }
7287 }
7288
7289 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7290                                   struct amdgpu_encoder *aencoder,
7291                                   uint32_t link_index)
7292 {
7293         struct amdgpu_device *adev = drm_to_adev(dev);
7294
7295         int res = drm_encoder_init(dev,
7296                                    &aencoder->base,
7297                                    &amdgpu_dm_encoder_funcs,
7298                                    DRM_MODE_ENCODER_TMDS,
7299                                    NULL);
7300
7301         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7302
7303         if (!res)
7304                 aencoder->encoder_id = link_index;
7305         else
7306                 aencoder->encoder_id = -1;
7307
7308         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7309
7310         return res;
7311 }
7312
7313 static void manage_dm_interrupts(struct amdgpu_device *adev,
7314                                  struct amdgpu_crtc *acrtc,
7315                                  bool enable)
7316 {
7317         /*
7318          * We have no guarantee that the frontend index maps to the same
7319          * backend index - some even map to more than one.
7320          *
7321          * TODO: Use a different interrupt or check DC itself for the mapping.
7322          */
7323         int irq_type =
7324                 amdgpu_display_crtc_idx_to_irq_type(
7325                         adev,
7326                         acrtc->crtc_id);
7327
7328         if (enable) {
7329                 drm_crtc_vblank_on(&acrtc->base);
7330                 amdgpu_irq_get(
7331                         adev,
7332                         &adev->pageflip_irq,
7333                         irq_type);
7334 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7335                 amdgpu_irq_get(
7336                         adev,
7337                         &adev->vline0_irq,
7338                         irq_type);
7339 #endif
7340         } else {
7341 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7342                 amdgpu_irq_put(
7343                         adev,
7344                         &adev->vline0_irq,
7345                         irq_type);
7346 #endif
7347                 amdgpu_irq_put(
7348                         adev,
7349                         &adev->pageflip_irq,
7350                         irq_type);
7351                 drm_crtc_vblank_off(&acrtc->base);
7352         }
7353 }
7354
7355 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7356                                       struct amdgpu_crtc *acrtc)
7357 {
7358         int irq_type =
7359                 amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7360
7361         /**
7362          * This reads the current state for the IRQ and force reapplies
7363          * the setting to hardware.
7364          */
7365         amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7366 }
7367
7368 static bool
7369 is_scaling_state_different(const struct dm_connector_state *dm_state,
7370                            const struct dm_connector_state *old_dm_state)
7371 {
7372         if (dm_state->scaling != old_dm_state->scaling)
7373                 return true;
7374         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7375                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7376                         return true;
7377         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7378                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7379                         return true;
7380         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7381                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7382                 return true;
7383         return false;
7384 }
7385
7386 #ifdef CONFIG_DRM_AMD_DC_HDCP
7387 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
7388                                             struct drm_crtc_state *old_crtc_state,
7389                                             struct drm_connector_state *new_conn_state,
7390                                             struct drm_connector_state *old_conn_state,
7391                                             const struct drm_connector *connector,
7392                                             struct hdcp_workqueue *hdcp_w)
7393 {
7394         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7395         struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7396
7397         pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
7398                 connector->index, connector->status, connector->dpms);
7399         pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
7400                 old_conn_state->content_protection, new_conn_state->content_protection);
7401
7402         if (old_crtc_state)
7403                 pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7404                 old_crtc_state->enable,
7405                 old_crtc_state->active,
7406                 old_crtc_state->mode_changed,
7407                 old_crtc_state->active_changed,
7408                 old_crtc_state->connectors_changed);
7409
7410         if (new_crtc_state)
7411                 pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7412                 new_crtc_state->enable,
7413                 new_crtc_state->active,
7414                 new_crtc_state->mode_changed,
7415                 new_crtc_state->active_changed,
7416                 new_crtc_state->connectors_changed);
7417
7418         /* hdcp content type change */
7419         if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
7420             new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7421                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7422                 pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
7423                 return true;
7424         }
7425
7426         /* CP is being re enabled, ignore this */
7427         if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7428             new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7429                 if (new_crtc_state && new_crtc_state->mode_changed) {
7430                         new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7431                         pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
7432                         return true;
7433                 }
7434                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7435                 pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
7436                 return false;
7437         }
7438
7439         /* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7440          *
7441          * Handles:     UNDESIRED -> ENABLED
7442          */
7443         if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7444             new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7445                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7446
7447         /* Stream removed and re-enabled
7448          *
7449          * Can sometimes overlap with the HPD case,
7450          * thus set update_hdcp to false to avoid
7451          * setting HDCP multiple times.
7452          *
7453          * Handles:     DESIRED -> DESIRED (Special case)
7454          */
7455         if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
7456                 new_conn_state->crtc && new_conn_state->crtc->enabled &&
7457                 connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7458                 dm_con_state->update_hdcp = false;
7459                 pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
7460                         __func__);
7461                 return true;
7462         }
7463
7464         /* Hot-plug, headless s3, dpms
7465          *
7466          * Only start HDCP if the display is connected/enabled.
7467          * update_hdcp flag will be set to false until the next
7468          * HPD comes in.
7469          *
7470          * Handles:     DESIRED -> DESIRED (Special case)
7471          */
7472         if (dm_con_state->update_hdcp &&
7473         new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7474         connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7475                 dm_con_state->update_hdcp = false;
7476                 pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
7477                         __func__);
7478                 return true;
7479         }
7480
7481         if (old_conn_state->content_protection == new_conn_state->content_protection) {
7482                 if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7483                         if (new_crtc_state && new_crtc_state->mode_changed) {
7484                                 pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
7485                                         __func__);
7486                                 return true;
7487                         }
7488                         pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
7489                                 __func__);
7490                         return false;
7491                 }
7492
7493                 pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
7494                 return false;
7495         }
7496
7497         if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
7498                 pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
7499                         __func__);
7500                 return true;
7501         }
7502
7503         pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
7504         return false;
7505 }
7506 #endif
7507
7508 static void remove_stream(struct amdgpu_device *adev,
7509                           struct amdgpu_crtc *acrtc,
7510                           struct dc_stream_state *stream)
7511 {
7512         /* this is the update mode case */
7513
7514         acrtc->otg_inst = -1;
7515         acrtc->enabled = false;
7516 }
7517
7518 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7519 {
7520
7521         assert_spin_locked(&acrtc->base.dev->event_lock);
7522         WARN_ON(acrtc->event);
7523
7524         acrtc->event = acrtc->base.state->event;
7525
7526         /* Set the flip status */
7527         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7528
7529         /* Mark this event as consumed */
7530         acrtc->base.state->event = NULL;
7531
7532         DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7533                      acrtc->crtc_id);
7534 }
7535
7536 static void update_freesync_state_on_stream(
7537         struct amdgpu_display_manager *dm,
7538         struct dm_crtc_state *new_crtc_state,
7539         struct dc_stream_state *new_stream,
7540         struct dc_plane_state *surface,
7541         u32 flip_timestamp_in_us)
7542 {
7543         struct mod_vrr_params vrr_params;
7544         struct dc_info_packet vrr_infopacket = {0};
7545         struct amdgpu_device *adev = dm->adev;
7546         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7547         unsigned long flags;
7548         bool pack_sdp_v1_3 = false;
7549
7550         if (!new_stream)
7551                 return;
7552
7553         /*
7554          * TODO: Determine why min/max totals and vrefresh can be 0 here.
7555          * For now it's sufficient to just guard against these conditions.
7556          */
7557
7558         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7559                 return;
7560
7561         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7562         vrr_params = acrtc->dm_irq_params.vrr_params;
7563
7564         if (surface) {
7565                 mod_freesync_handle_preflip(
7566                         dm->freesync_module,
7567                         surface,
7568                         new_stream,
7569                         flip_timestamp_in_us,
7570                         &vrr_params);
7571
7572                 if (adev->family < AMDGPU_FAMILY_AI &&
7573                     amdgpu_dm_vrr_active(new_crtc_state)) {
7574                         mod_freesync_handle_v_update(dm->freesync_module,
7575                                                      new_stream, &vrr_params);
7576
7577                         /* Need to call this before the frame ends. */
7578                         dc_stream_adjust_vmin_vmax(dm->dc,
7579                                                    new_crtc_state->stream,
7580                                                    &vrr_params.adjust);
7581                 }
7582         }
7583
7584         mod_freesync_build_vrr_infopacket(
7585                 dm->freesync_module,
7586                 new_stream,
7587                 &vrr_params,
7588                 PACKET_TYPE_VRR,
7589                 TRANSFER_FUNC_UNKNOWN,
7590                 &vrr_infopacket,
7591                 pack_sdp_v1_3);
7592
7593         new_crtc_state->freesync_vrr_info_changed |=
7594                 (memcmp(&new_crtc_state->vrr_infopacket,
7595                         &vrr_infopacket,
7596                         sizeof(vrr_infopacket)) != 0);
7597
7598         acrtc->dm_irq_params.vrr_params = vrr_params;
7599         new_crtc_state->vrr_infopacket = vrr_infopacket;
7600
7601         new_stream->vrr_infopacket = vrr_infopacket;
7602
7603         if (new_crtc_state->freesync_vrr_info_changed)
7604                 DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7605                               new_crtc_state->base.crtc->base.id,
7606                               (int)new_crtc_state->base.vrr_enabled,
7607                               (int)vrr_params.state);
7608
7609         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7610 }
7611
7612 static void update_stream_irq_parameters(
7613         struct amdgpu_display_manager *dm,
7614         struct dm_crtc_state *new_crtc_state)
7615 {
7616         struct dc_stream_state *new_stream = new_crtc_state->stream;
7617         struct mod_vrr_params vrr_params;
7618         struct mod_freesync_config config = new_crtc_state->freesync_config;
7619         struct amdgpu_device *adev = dm->adev;
7620         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7621         unsigned long flags;
7622
7623         if (!new_stream)
7624                 return;
7625
7626         /*
7627          * TODO: Determine why min/max totals and vrefresh can be 0 here.
7628          * For now it's sufficient to just guard against these conditions.
7629          */
7630         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7631                 return;
7632
7633         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7634         vrr_params = acrtc->dm_irq_params.vrr_params;
7635
7636         if (new_crtc_state->vrr_supported &&
7637             config.min_refresh_in_uhz &&
7638             config.max_refresh_in_uhz) {
7639                 /*
7640                  * if freesync compatible mode was set, config.state will be set
7641                  * in atomic check
7642                  */
7643                 if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7644                     (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7645                      new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7646                         vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7647                         vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7648                         vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7649                         vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7650                 } else {
7651                         config.state = new_crtc_state->base.vrr_enabled ?
7652                                                      VRR_STATE_ACTIVE_VARIABLE :
7653                                                      VRR_STATE_INACTIVE;
7654                 }
7655         } else {
7656                 config.state = VRR_STATE_UNSUPPORTED;
7657         }
7658
7659         mod_freesync_build_vrr_params(dm->freesync_module,
7660                                       new_stream,
7661                                       &config, &vrr_params);
7662
7663         new_crtc_state->freesync_config = config;
7664         /* Copy state for access from DM IRQ handler */
7665         acrtc->dm_irq_params.freesync_config = config;
7666         acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7667         acrtc->dm_irq_params.vrr_params = vrr_params;
7668         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7669 }
7670
7671 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7672                                             struct dm_crtc_state *new_state)
7673 {
7674         bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7675         bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7676
7677         if (!old_vrr_active && new_vrr_active) {
7678                 /* Transition VRR inactive -> active:
7679                  * While VRR is active, we must not disable vblank irq, as a
7680                  * reenable after disable would compute bogus vblank/pflip
7681                  * timestamps if it likely happened inside display front-porch.
7682                  *
7683                  * We also need vupdate irq for the actual core vblank handling
7684                  * at end of vblank.
7685                  */
7686                 WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7687                 WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7688                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7689                                  __func__, new_state->base.crtc->base.id);
7690         } else if (old_vrr_active && !new_vrr_active) {
7691                 /* Transition VRR active -> inactive:
7692                  * Allow vblank irq disable again for fixed refresh rate.
7693                  */
7694                 WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7695                 drm_crtc_vblank_put(new_state->base.crtc);
7696                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7697                                  __func__, new_state->base.crtc->base.id);
7698         }
7699 }
7700
7701 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7702 {
7703         struct drm_plane *plane;
7704         struct drm_plane_state *old_plane_state;
7705         int i;
7706
7707         /*
7708          * TODO: Make this per-stream so we don't issue redundant updates for
7709          * commits with multiple streams.
7710          */
7711         for_each_old_plane_in_state(state, plane, old_plane_state, i)
7712                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
7713                         handle_cursor_update(plane, old_plane_state);
7714 }
7715
7716 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7717                                     struct dc_state *dc_state,
7718                                     struct drm_device *dev,
7719                                     struct amdgpu_display_manager *dm,
7720                                     struct drm_crtc *pcrtc,
7721                                     bool wait_for_vblank)
7722 {
7723         u32 i;
7724         u64 timestamp_ns;
7725         struct drm_plane *plane;
7726         struct drm_plane_state *old_plane_state, *new_plane_state;
7727         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7728         struct drm_crtc_state *new_pcrtc_state =
7729                         drm_atomic_get_new_crtc_state(state, pcrtc);
7730         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7731         struct dm_crtc_state *dm_old_crtc_state =
7732                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7733         int planes_count = 0, vpos, hpos;
7734         unsigned long flags;
7735         u32 target_vblank, last_flip_vblank;
7736         bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7737         bool cursor_update = false;
7738         bool pflip_present = false;
7739         struct {
7740                 struct dc_surface_update surface_updates[MAX_SURFACES];
7741                 struct dc_plane_info plane_infos[MAX_SURFACES];
7742                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
7743                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7744                 struct dc_stream_update stream_update;
7745         } *bundle;
7746
7747         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7748
7749         if (!bundle) {
7750                 dm_error("Failed to allocate update bundle\n");
7751                 goto cleanup;
7752         }
7753
7754         /*
7755          * Disable the cursor first if we're disabling all the planes.
7756          * It'll remain on the screen after the planes are re-enabled
7757          * if we don't.
7758          */
7759         if (acrtc_state->active_planes == 0)
7760                 amdgpu_dm_commit_cursors(state);
7761
7762         /* update planes when needed */
7763         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7764                 struct drm_crtc *crtc = new_plane_state->crtc;
7765                 struct drm_crtc_state *new_crtc_state;
7766                 struct drm_framebuffer *fb = new_plane_state->fb;
7767                 struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7768                 bool plane_needs_flip;
7769                 struct dc_plane_state *dc_plane;
7770                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7771
7772                 /* Cursor plane is handled after stream updates */
7773                 if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7774                         if ((fb && crtc == pcrtc) ||
7775                             (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7776                                 cursor_update = true;
7777
7778                         continue;
7779                 }
7780
7781                 if (!fb || !crtc || pcrtc != crtc)
7782                         continue;
7783
7784                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7785                 if (!new_crtc_state->active)
7786                         continue;
7787
7788                 dc_plane = dm_new_plane_state->dc_state;
7789
7790                 bundle->surface_updates[planes_count].surface = dc_plane;
7791                 if (new_pcrtc_state->color_mgmt_changed) {
7792                         bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7793                         bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7794                         bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7795                 }
7796
7797                 fill_dc_scaling_info(dm->adev, new_plane_state,
7798                                      &bundle->scaling_infos[planes_count]);
7799
7800                 bundle->surface_updates[planes_count].scaling_info =
7801                         &bundle->scaling_infos[planes_count];
7802
7803                 plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7804
7805                 pflip_present = pflip_present || plane_needs_flip;
7806
7807                 if (!plane_needs_flip) {
7808                         planes_count += 1;
7809                         continue;
7810                 }
7811
7812                 fill_dc_plane_info_and_addr(
7813                         dm->adev, new_plane_state,
7814                         afb->tiling_flags,
7815                         &bundle->plane_infos[planes_count],
7816                         &bundle->flip_addrs[planes_count].address,
7817                         afb->tmz_surface, false);
7818
7819                 drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7820                                  new_plane_state->plane->index,
7821                                  bundle->plane_infos[planes_count].dcc.enable);
7822
7823                 bundle->surface_updates[planes_count].plane_info =
7824                         &bundle->plane_infos[planes_count];
7825
7826                 if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7827                         fill_dc_dirty_rects(plane, old_plane_state,
7828                                             new_plane_state, new_crtc_state,
7829                                             &bundle->flip_addrs[planes_count]);
7830
7831                 /*
7832                  * Only allow immediate flips for fast updates that don't
7833                  * change FB pitch, DCC state, rotation or mirroing.
7834                  */
7835                 bundle->flip_addrs[planes_count].flip_immediate =
7836                         crtc->state->async_flip &&
7837                         acrtc_state->update_type == UPDATE_TYPE_FAST;
7838
7839                 timestamp_ns = ktime_get_ns();
7840                 bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7841                 bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7842                 bundle->surface_updates[planes_count].surface = dc_plane;
7843
7844                 if (!bundle->surface_updates[planes_count].surface) {
7845                         DRM_ERROR("No surface for CRTC: id=%d\n",
7846                                         acrtc_attach->crtc_id);
7847                         continue;
7848                 }
7849
7850                 if (plane == pcrtc->primary)
7851                         update_freesync_state_on_stream(
7852                                 dm,
7853                                 acrtc_state,
7854                                 acrtc_state->stream,
7855                                 dc_plane,
7856                                 bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7857
7858                 drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7859                                  __func__,
7860                                  bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7861                                  bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7862
7863                 planes_count += 1;
7864
7865         }
7866
7867         if (pflip_present) {
7868                 if (!vrr_active) {
7869                         /* Use old throttling in non-vrr fixed refresh rate mode
7870                          * to keep flip scheduling based on target vblank counts
7871                          * working in a backwards compatible way, e.g., for
7872                          * clients using the GLX_OML_sync_control extension or
7873                          * DRI3/Present extension with defined target_msc.
7874                          */
7875                         last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7876                 }
7877                 else {
7878                         /* For variable refresh rate mode only:
7879                          * Get vblank of last completed flip to avoid > 1 vrr
7880                          * flips per video frame by use of throttling, but allow
7881                          * flip programming anywhere in the possibly large
7882                          * variable vrr vblank interval for fine-grained flip
7883                          * timing control and more opportunity to avoid stutter
7884                          * on late submission of flips.
7885                          */
7886                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7887                         last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
7888                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7889                 }
7890
7891                 target_vblank = last_flip_vblank + wait_for_vblank;
7892
7893                 /*
7894                  * Wait until we're out of the vertical blank period before the one
7895                  * targeted by the flip
7896                  */
7897                 while ((acrtc_attach->enabled &&
7898                         (amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
7899                                                             0, &vpos, &hpos, NULL,
7900                                                             NULL, &pcrtc->hwmode)
7901                          & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
7902                         (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
7903                         (int)(target_vblank -
7904                           amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
7905                         usleep_range(1000, 1100);
7906                 }
7907
7908                 /**
7909                  * Prepare the flip event for the pageflip interrupt to handle.
7910                  *
7911                  * This only works in the case where we've already turned on the
7912                  * appropriate hardware blocks (eg. HUBP) so in the transition case
7913                  * from 0 -> n planes we have to skip a hardware generated event
7914                  * and rely on sending it from software.
7915                  */
7916                 if (acrtc_attach->base.state->event &&
7917                     acrtc_state->active_planes > 0) {
7918                         drm_crtc_vblank_get(pcrtc);
7919
7920                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7921
7922                         WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
7923                         prepare_flip_isr(acrtc_attach);
7924
7925                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7926                 }
7927
7928                 if (acrtc_state->stream) {
7929                         if (acrtc_state->freesync_vrr_info_changed)
7930                                 bundle->stream_update.vrr_infopacket =
7931                                         &acrtc_state->stream->vrr_infopacket;
7932                 }
7933         } else if (cursor_update && acrtc_state->active_planes > 0 &&
7934                    acrtc_attach->base.state->event) {
7935                 drm_crtc_vblank_get(pcrtc);
7936
7937                 spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7938
7939                 acrtc_attach->event = acrtc_attach->base.state->event;
7940                 acrtc_attach->base.state->event = NULL;
7941
7942                 spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7943         }
7944
7945         /* Update the planes if changed or disable if we don't have any. */
7946         if ((planes_count || acrtc_state->active_planes == 0) &&
7947                 acrtc_state->stream) {
7948                 /*
7949                  * If PSR or idle optimizations are enabled then flush out
7950                  * any pending work before hardware programming.
7951                  */
7952                 if (dm->vblank_control_workqueue)
7953                         flush_workqueue(dm->vblank_control_workqueue);
7954
7955                 bundle->stream_update.stream = acrtc_state->stream;
7956                 if (new_pcrtc_state->mode_changed) {
7957                         bundle->stream_update.src = acrtc_state->stream->src;
7958                         bundle->stream_update.dst = acrtc_state->stream->dst;
7959                 }
7960
7961                 if (new_pcrtc_state->color_mgmt_changed) {
7962                         /*
7963                          * TODO: This isn't fully correct since we've actually
7964                          * already modified the stream in place.
7965                          */
7966                         bundle->stream_update.gamut_remap =
7967                                 &acrtc_state->stream->gamut_remap_matrix;
7968                         bundle->stream_update.output_csc_transform =
7969                                 &acrtc_state->stream->csc_color_matrix;
7970                         bundle->stream_update.out_transfer_func =
7971                                 acrtc_state->stream->out_transfer_func;
7972                 }
7973
7974                 acrtc_state->stream->abm_level = acrtc_state->abm_level;
7975                 if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
7976                         bundle->stream_update.abm_level = &acrtc_state->abm_level;
7977
7978                 /*
7979                  * If FreeSync state on the stream has changed then we need to
7980                  * re-adjust the min/max bounds now that DC doesn't handle this
7981                  * as part of commit.
7982                  */
7983                 if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
7984                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7985                         dc_stream_adjust_vmin_vmax(
7986                                 dm->dc, acrtc_state->stream,
7987                                 &acrtc_attach->dm_irq_params.vrr_params.adjust);
7988                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7989                 }
7990                 mutex_lock(&dm->dc_lock);
7991                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7992                                 acrtc_state->stream->link->psr_settings.psr_allow_active)
7993                         amdgpu_dm_psr_disable(acrtc_state->stream);
7994
7995                 dc_commit_updates_for_stream(dm->dc,
7996                                                      bundle->surface_updates,
7997                                                      planes_count,
7998                                                      acrtc_state->stream,
7999                                                      &bundle->stream_update,
8000                                                      dc_state);
8001
8002                 /**
8003                  * Enable or disable the interrupts on the backend.
8004                  *
8005                  * Most pipes are put into power gating when unused.
8006                  *
8007                  * When power gating is enabled on a pipe we lose the
8008                  * interrupt enablement state when power gating is disabled.
8009                  *
8010                  * So we need to update the IRQ control state in hardware
8011                  * whenever the pipe turns on (since it could be previously
8012                  * power gated) or off (since some pipes can't be power gated
8013                  * on some ASICs).
8014                  */
8015                 if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
8016                         dm_update_pflip_irq_state(drm_to_adev(dev),
8017                                                   acrtc_attach);
8018
8019                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8020                                 acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
8021                                 !acrtc_state->stream->link->psr_settings.psr_feature_enabled)
8022                         amdgpu_dm_link_setup_psr(acrtc_state->stream);
8023
8024                 /* Decrement skip count when PSR is enabled and we're doing fast updates. */
8025                 if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
8026                     acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
8027                         struct amdgpu_dm_connector *aconn =
8028                                 (struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8029
8030                         if (aconn->psr_skip_count > 0)
8031                                 aconn->psr_skip_count--;
8032
8033                         /* Allow PSR when skip count is 0. */
8034                         acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
8035
8036                         /*
8037                          * If sink supports PSR SU, there is no need to rely on
8038                          * a vblank event disable request to enable PSR. PSR SU
8039                          * can be enabled immediately once OS demonstrates an
8040                          * adequate number of fast atomic commits to notify KMD
8041                          * of update events. See `vblank_control_worker()`.
8042                          */
8043                         if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
8044                             acrtc_attach->dm_irq_params.allow_psr_entry &&
8045 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
8046                             !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
8047 #endif
8048                             !acrtc_state->stream->link->psr_settings.psr_allow_active)
8049                                 amdgpu_dm_psr_enable(acrtc_state->stream);
8050                 } else {
8051                         acrtc_attach->dm_irq_params.allow_psr_entry = false;
8052                 }
8053
8054                 mutex_unlock(&dm->dc_lock);
8055         }
8056
8057         /*
8058          * Update cursor state *after* programming all the planes.
8059          * This avoids redundant programming in the case where we're going
8060          * to be disabling a single plane - those pipes are being disabled.
8061          */
8062         if (acrtc_state->active_planes)
8063                 amdgpu_dm_commit_cursors(state);
8064
8065 cleanup:
8066         kfree(bundle);
8067 }
8068
8069 static void amdgpu_dm_commit_audio(struct drm_device *dev,
8070                                    struct drm_atomic_state *state)
8071 {
8072         struct amdgpu_device *adev = drm_to_adev(dev);
8073         struct amdgpu_dm_connector *aconnector;
8074         struct drm_connector *connector;
8075         struct drm_connector_state *old_con_state, *new_con_state;
8076         struct drm_crtc_state *new_crtc_state;
8077         struct dm_crtc_state *new_dm_crtc_state;
8078         const struct dc_stream_status *status;
8079         int i, inst;
8080
8081         /* Notify device removals. */
8082         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8083                 if (old_con_state->crtc != new_con_state->crtc) {
8084                         /* CRTC changes require notification. */
8085                         goto notify;
8086                 }
8087
8088                 if (!new_con_state->crtc)
8089                         continue;
8090
8091                 new_crtc_state = drm_atomic_get_new_crtc_state(
8092                         state, new_con_state->crtc);
8093
8094                 if (!new_crtc_state)
8095                         continue;
8096
8097                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8098                         continue;
8099
8100         notify:
8101                 aconnector = to_amdgpu_dm_connector(connector);
8102
8103                 mutex_lock(&adev->dm.audio_lock);
8104                 inst = aconnector->audio_inst;
8105                 aconnector->audio_inst = -1;
8106                 mutex_unlock(&adev->dm.audio_lock);
8107
8108                 amdgpu_dm_audio_eld_notify(adev, inst);
8109         }
8110
8111         /* Notify audio device additions. */
8112         for_each_new_connector_in_state(state, connector, new_con_state, i) {
8113                 if (!new_con_state->crtc)
8114                         continue;
8115
8116                 new_crtc_state = drm_atomic_get_new_crtc_state(
8117                         state, new_con_state->crtc);
8118
8119                 if (!new_crtc_state)
8120                         continue;
8121
8122                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8123                         continue;
8124
8125                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
8126                 if (!new_dm_crtc_state->stream)
8127                         continue;
8128
8129                 status = dc_stream_get_status(new_dm_crtc_state->stream);
8130                 if (!status)
8131                         continue;
8132
8133                 aconnector = to_amdgpu_dm_connector(connector);
8134
8135                 mutex_lock(&adev->dm.audio_lock);
8136                 inst = status->audio_inst;
8137                 aconnector->audio_inst = inst;
8138                 mutex_unlock(&adev->dm.audio_lock);
8139
8140                 amdgpu_dm_audio_eld_notify(adev, inst);
8141         }
8142 }
8143
8144 /*
8145  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8146  * @crtc_state: the DRM CRTC state
8147  * @stream_state: the DC stream state.
8148  *
8149  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8150  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8151  */
8152 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8153                                                 struct dc_stream_state *stream_state)
8154 {
8155         stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8156 }
8157
8158 /**
8159  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8160  * @state: The atomic state to commit
8161  *
8162  * This will tell DC to commit the constructed DC state from atomic_check,
8163  * programming the hardware. Any failures here implies a hardware failure, since
8164  * atomic check should have filtered anything non-kosher.
8165  */
8166 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8167 {
8168         struct drm_device *dev = state->dev;
8169         struct amdgpu_device *adev = drm_to_adev(dev);
8170         struct amdgpu_display_manager *dm = &adev->dm;
8171         struct dm_atomic_state *dm_state;
8172         struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8173         u32 i, j;
8174         struct drm_crtc *crtc;
8175         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8176         unsigned long flags;
8177         bool wait_for_vblank = true;
8178         struct drm_connector *connector;
8179         struct drm_connector_state *old_con_state, *new_con_state;
8180         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8181         int crtc_disable_count = 0;
8182         bool mode_set_reset_required = false;
8183         int r;
8184
8185         trace_amdgpu_dm_atomic_commit_tail_begin(state);
8186
8187         r = drm_atomic_helper_wait_for_fences(dev, state, false);
8188         if (unlikely(r))
8189                 DRM_ERROR("Waiting for fences timed out!");
8190
8191         drm_atomic_helper_update_legacy_modeset_state(dev, state);
8192         drm_dp_mst_atomic_wait_for_dependencies(state);
8193
8194         dm_state = dm_atomic_get_new_state(state);
8195         if (dm_state && dm_state->context) {
8196                 dc_state = dm_state->context;
8197         } else {
8198                 /* No state changes, retain current state. */
8199                 dc_state_temp = dc_create_state(dm->dc);
8200                 ASSERT(dc_state_temp);
8201                 dc_state = dc_state_temp;
8202                 dc_resource_state_copy_construct_current(dm->dc, dc_state);
8203         }
8204
8205         for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8206                                        new_crtc_state, i) {
8207                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8208
8209                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8210
8211                 if (old_crtc_state->active &&
8212                     (!new_crtc_state->active ||
8213                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8214                         manage_dm_interrupts(adev, acrtc, false);
8215                         dc_stream_release(dm_old_crtc_state->stream);
8216                 }
8217         }
8218
8219         drm_atomic_helper_calc_timestamping_constants(state);
8220
8221         /* update changed items */
8222         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8223                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8224
8225                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8226                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8227
8228                 drm_dbg_state(state->dev,
8229                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8230                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
8231                         "connectors_changed:%d\n",
8232                         acrtc->crtc_id,
8233                         new_crtc_state->enable,
8234                         new_crtc_state->active,
8235                         new_crtc_state->planes_changed,
8236                         new_crtc_state->mode_changed,
8237                         new_crtc_state->active_changed,
8238                         new_crtc_state->connectors_changed);
8239
8240                 /* Disable cursor if disabling crtc */
8241                 if (old_crtc_state->active && !new_crtc_state->active) {
8242                         struct dc_cursor_position position;
8243
8244                         memset(&position, 0, sizeof(position));
8245                         mutex_lock(&dm->dc_lock);
8246                         dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8247                         mutex_unlock(&dm->dc_lock);
8248                 }
8249
8250                 /* Copy all transient state flags into dc state */
8251                 if (dm_new_crtc_state->stream) {
8252                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8253                                                             dm_new_crtc_state->stream);
8254                 }
8255
8256                 /* handles headless hotplug case, updating new_state and
8257                  * aconnector as needed
8258                  */
8259
8260                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8261
8262                         DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8263
8264                         if (!dm_new_crtc_state->stream) {
8265                                 /*
8266                                  * this could happen because of issues with
8267                                  * userspace notifications delivery.
8268                                  * In this case userspace tries to set mode on
8269                                  * display which is disconnected in fact.
8270                                  * dc_sink is NULL in this case on aconnector.
8271                                  * We expect reset mode will come soon.
8272                                  *
8273                                  * This can also happen when unplug is done
8274                                  * during resume sequence ended
8275                                  *
8276                                  * In this case, we want to pretend we still
8277                                  * have a sink to keep the pipe running so that
8278                                  * hw state is consistent with the sw state
8279                                  */
8280                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8281                                                 __func__, acrtc->base.base.id);
8282                                 continue;
8283                         }
8284
8285                         if (dm_old_crtc_state->stream)
8286                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8287
8288                         pm_runtime_get_noresume(dev->dev);
8289
8290                         acrtc->enabled = true;
8291                         acrtc->hw_mode = new_crtc_state->mode;
8292                         crtc->hwmode = new_crtc_state->mode;
8293                         mode_set_reset_required = true;
8294                 } else if (modereset_required(new_crtc_state)) {
8295                         DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8296                         /* i.e. reset mode */
8297                         if (dm_old_crtc_state->stream)
8298                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8299
8300                         mode_set_reset_required = true;
8301                 }
8302         } /* for_each_crtc_in_state() */
8303
8304         if (dc_state) {
8305                 /* if there mode set or reset, disable eDP PSR */
8306                 if (mode_set_reset_required) {
8307                         if (dm->vblank_control_workqueue)
8308                                 flush_workqueue(dm->vblank_control_workqueue);
8309
8310                         amdgpu_dm_psr_disable_all(dm);
8311                 }
8312
8313                 dm_enable_per_frame_crtc_master_sync(dc_state);
8314                 mutex_lock(&dm->dc_lock);
8315                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
8316
8317                 /* Allow idle optimization when vblank count is 0 for display off */
8318                 if (dm->active_vblank_irq_count == 0)
8319                         dc_allow_idle_optimizations(dm->dc, true);
8320                 mutex_unlock(&dm->dc_lock);
8321         }
8322
8323         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8324                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8325
8326                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8327
8328                 if (dm_new_crtc_state->stream != NULL) {
8329                         const struct dc_stream_status *status =
8330                                         dc_stream_get_status(dm_new_crtc_state->stream);
8331
8332                         if (!status)
8333                                 status = dc_stream_get_status_from_state(dc_state,
8334                                                                          dm_new_crtc_state->stream);
8335                         if (!status)
8336                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8337                         else
8338                                 acrtc->otg_inst = status->primary_otg_inst;
8339                 }
8340         }
8341 #ifdef CONFIG_DRM_AMD_DC_HDCP
8342         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8343                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8344                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8345                 struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8346
8347                 pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
8348
8349                 if (!connector)
8350                         continue;
8351
8352                 pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8353                         connector->index, connector->status, connector->dpms);
8354                 pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8355                         old_con_state->content_protection, new_con_state->content_protection);
8356
8357                 if (aconnector->dc_sink) {
8358                         if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
8359                                 aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
8360                                 pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
8361                                 aconnector->dc_sink->edid_caps.display_name);
8362                         }
8363                 }
8364
8365                 new_crtc_state = NULL;
8366                 old_crtc_state = NULL;
8367
8368                 if (acrtc) {
8369                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8370                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8371                 }
8372
8373                 if (old_crtc_state)
8374                         pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8375                         old_crtc_state->enable,
8376                         old_crtc_state->active,
8377                         old_crtc_state->mode_changed,
8378                         old_crtc_state->active_changed,
8379                         old_crtc_state->connectors_changed);
8380
8381                 if (new_crtc_state)
8382                         pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8383                         new_crtc_state->enable,
8384                         new_crtc_state->active,
8385                         new_crtc_state->mode_changed,
8386                         new_crtc_state->active_changed,
8387                         new_crtc_state->connectors_changed);
8388         }
8389
8390         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8391                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8392                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8393                 struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8394
8395                 new_crtc_state = NULL;
8396                 old_crtc_state = NULL;
8397
8398                 if (acrtc) {
8399                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8400                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8401                 }
8402
8403                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8404
8405                 if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8406                     connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8407                         hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8408                         new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8409                         dm_new_con_state->update_hdcp = true;
8410                         continue;
8411                 }
8412
8413                 if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
8414                                                                                         old_con_state, connector, adev->dm.hdcp_workqueue)) {
8415                         /* when display is unplugged from mst hub, connctor will
8416                          * be destroyed within dm_dp_mst_connector_destroy. connector
8417                          * hdcp perperties, like type, undesired, desired, enabled,
8418                          * will be lost. So, save hdcp properties into hdcp_work within
8419                          * amdgpu_dm_atomic_commit_tail. if the same display is
8420                          * plugged back with same display index, its hdcp properties
8421                          * will be retrieved from hdcp_work within dm_dp_mst_get_modes
8422                          */
8423
8424                         bool enable_encryption = false;
8425
8426                         if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
8427                                 enable_encryption = true;
8428
8429                         if (aconnector->dc_link && aconnector->dc_sink &&
8430                                 aconnector->dc_link->type == dc_connection_mst_branch) {
8431                                 struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
8432                                 struct hdcp_workqueue *hdcp_w =
8433                                         &hdcp_work[aconnector->dc_link->link_index];
8434
8435                                 hdcp_w->hdcp_content_type[connector->index] =
8436                                         new_con_state->hdcp_content_type;
8437                                 hdcp_w->content_protection[connector->index] =
8438                                         new_con_state->content_protection;
8439                         }
8440
8441                         if (new_crtc_state && new_crtc_state->mode_changed &&
8442                                 new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
8443                                 enable_encryption = true;
8444
8445                         DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
8446
8447                         hdcp_update_display(
8448                                 adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8449                                 new_con_state->hdcp_content_type, enable_encryption);
8450                 }
8451         }
8452 #endif
8453
8454         /* Handle connector state changes */
8455         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8456                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8457                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8458                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8459                 struct dc_surface_update dummy_updates[MAX_SURFACES];
8460                 struct dc_stream_update stream_update;
8461                 struct dc_info_packet hdr_packet;
8462                 struct dc_stream_status *status = NULL;
8463                 bool abm_changed, hdr_changed, scaling_changed;
8464
8465                 memset(&dummy_updates, 0, sizeof(dummy_updates));
8466                 memset(&stream_update, 0, sizeof(stream_update));
8467
8468                 if (acrtc) {
8469                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8470                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8471                 }
8472
8473                 /* Skip any modesets/resets */
8474                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8475                         continue;
8476
8477                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8478                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8479
8480                 scaling_changed = is_scaling_state_different(dm_new_con_state,
8481                                                              dm_old_con_state);
8482
8483                 abm_changed = dm_new_crtc_state->abm_level !=
8484                               dm_old_crtc_state->abm_level;
8485
8486                 hdr_changed =
8487                         !drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8488
8489                 if (!scaling_changed && !abm_changed && !hdr_changed)
8490                         continue;
8491
8492                 stream_update.stream = dm_new_crtc_state->stream;
8493                 if (scaling_changed) {
8494                         update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8495                                         dm_new_con_state, dm_new_crtc_state->stream);
8496
8497                         stream_update.src = dm_new_crtc_state->stream->src;
8498                         stream_update.dst = dm_new_crtc_state->stream->dst;
8499                 }
8500
8501                 if (abm_changed) {
8502                         dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8503
8504                         stream_update.abm_level = &dm_new_crtc_state->abm_level;
8505                 }
8506
8507                 if (hdr_changed) {
8508                         fill_hdr_info_packet(new_con_state, &hdr_packet);
8509                         stream_update.hdr_static_metadata = &hdr_packet;
8510                 }
8511
8512                 status = dc_stream_get_status(dm_new_crtc_state->stream);
8513
8514                 if (WARN_ON(!status))
8515                         continue;
8516
8517                 WARN_ON(!status->plane_count);
8518
8519                 /*
8520                  * TODO: DC refuses to perform stream updates without a dc_surface_update.
8521                  * Here we create an empty update on each plane.
8522                  * To fix this, DC should permit updating only stream properties.
8523                  */
8524                 for (j = 0; j < status->plane_count; j++)
8525                         dummy_updates[j].surface = status->plane_states[0];
8526
8527
8528                 mutex_lock(&dm->dc_lock);
8529                 dc_commit_updates_for_stream(dm->dc,
8530                                                      dummy_updates,
8531                                                      status->plane_count,
8532                                                      dm_new_crtc_state->stream,
8533                                                      &stream_update,
8534                                                      dc_state);
8535                 mutex_unlock(&dm->dc_lock);
8536         }
8537
8538         /**
8539          * Enable interrupts for CRTCs that are newly enabled or went through
8540          * a modeset. It was intentionally deferred until after the front end
8541          * state was modified to wait until the OTG was on and so the IRQ
8542          * handlers didn't access stale or invalid state.
8543          */
8544         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8545                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8546 #ifdef CONFIG_DEBUG_FS
8547                 enum amdgpu_dm_pipe_crc_source cur_crc_src;
8548 #endif
8549                 /* Count number of newly disabled CRTCs for dropping PM refs later. */
8550                 if (old_crtc_state->active && !new_crtc_state->active)
8551                         crtc_disable_count++;
8552
8553                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8554                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8555
8556                 /* For freesync config update on crtc state and params for irq */
8557                 update_stream_irq_parameters(dm, dm_new_crtc_state);
8558
8559 #ifdef CONFIG_DEBUG_FS
8560                 spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8561                 cur_crc_src = acrtc->dm_irq_params.crc_src;
8562                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8563 #endif
8564
8565                 if (new_crtc_state->active &&
8566                     (!old_crtc_state->active ||
8567                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8568                         dc_stream_retain(dm_new_crtc_state->stream);
8569                         acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8570                         manage_dm_interrupts(adev, acrtc, true);
8571                 }
8572                 /* Handle vrr on->off / off->on transitions */
8573                 amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8574
8575 #ifdef CONFIG_DEBUG_FS
8576                 if (new_crtc_state->active &&
8577                     (!old_crtc_state->active ||
8578                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8579                         /**
8580                          * Frontend may have changed so reapply the CRC capture
8581                          * settings for the stream.
8582                          */
8583                         if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8584 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8585                                 if (amdgpu_dm_crc_window_is_activated(crtc)) {
8586                                         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8587                                         acrtc->dm_irq_params.window_param.update_win = true;
8588
8589                                         /**
8590                                          * It takes 2 frames for HW to stably generate CRC when
8591                                          * resuming from suspend, so we set skip_frame_cnt 2.
8592                                          */
8593                                         acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
8594                                         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8595                                 }
8596 #endif
8597                                 if (amdgpu_dm_crtc_configure_crc_source(
8598                                         crtc, dm_new_crtc_state, cur_crc_src))
8599                                         DRM_DEBUG_DRIVER("Failed to configure crc source");
8600                         }
8601                 }
8602 #endif
8603         }
8604
8605         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8606                 if (new_crtc_state->async_flip)
8607                         wait_for_vblank = false;
8608
8609         /* update planes when needed per crtc*/
8610         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8611                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8612
8613                 if (dm_new_crtc_state->stream)
8614                         amdgpu_dm_commit_planes(state, dc_state, dev,
8615                                                 dm, crtc, wait_for_vblank);
8616         }
8617
8618         /* Update audio instances for each connector. */
8619         amdgpu_dm_commit_audio(dev, state);
8620
8621         /* restore the backlight level */
8622         for (i = 0; i < dm->num_of_edps; i++) {
8623                 if (dm->backlight_dev[i] &&
8624                     (dm->actual_brightness[i] != dm->brightness[i]))
8625                         amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8626         }
8627
8628         /*
8629          * send vblank event on all events not handled in flip and
8630          * mark consumed event for drm_atomic_helper_commit_hw_done
8631          */
8632         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8633         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8634
8635                 if (new_crtc_state->event)
8636                         drm_send_event_locked(dev, &new_crtc_state->event->base);
8637
8638                 new_crtc_state->event = NULL;
8639         }
8640         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8641
8642         /* Signal HW programming completion */
8643         drm_atomic_helper_commit_hw_done(state);
8644
8645         if (wait_for_vblank)
8646                 drm_atomic_helper_wait_for_flip_done(dev, state);
8647
8648         drm_atomic_helper_cleanup_planes(dev, state);
8649
8650         /* return the stolen vga memory back to VRAM */
8651         if (!adev->mman.keep_stolen_vga_memory)
8652                 amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8653         amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8654
8655         /*
8656          * Finally, drop a runtime PM reference for each newly disabled CRTC,
8657          * so we can put the GPU into runtime suspend if we're not driving any
8658          * displays anymore
8659          */
8660         for (i = 0; i < crtc_disable_count; i++)
8661                 pm_runtime_put_autosuspend(dev->dev);
8662         pm_runtime_mark_last_busy(dev->dev);
8663
8664         if (dc_state_temp)
8665                 dc_release_state(dc_state_temp);
8666 }
8667
8668 static int dm_force_atomic_commit(struct drm_connector *connector)
8669 {
8670         int ret = 0;
8671         struct drm_device *ddev = connector->dev;
8672         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8673         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8674         struct drm_plane *plane = disconnected_acrtc->base.primary;
8675         struct drm_connector_state *conn_state;
8676         struct drm_crtc_state *crtc_state;
8677         struct drm_plane_state *plane_state;
8678
8679         if (!state)
8680                 return -ENOMEM;
8681
8682         state->acquire_ctx = ddev->mode_config.acquire_ctx;
8683
8684         /* Construct an atomic state to restore previous display setting */
8685
8686         /*
8687          * Attach connectors to drm_atomic_state
8688          */
8689         conn_state = drm_atomic_get_connector_state(state, connector);
8690
8691         ret = PTR_ERR_OR_ZERO(conn_state);
8692         if (ret)
8693                 goto out;
8694
8695         /* Attach crtc to drm_atomic_state*/
8696         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8697
8698         ret = PTR_ERR_OR_ZERO(crtc_state);
8699         if (ret)
8700                 goto out;
8701
8702         /* force a restore */
8703         crtc_state->mode_changed = true;
8704
8705         /* Attach plane to drm_atomic_state */
8706         plane_state = drm_atomic_get_plane_state(state, plane);
8707
8708         ret = PTR_ERR_OR_ZERO(plane_state);
8709         if (ret)
8710                 goto out;
8711
8712         /* Call commit internally with the state we just constructed */
8713         ret = drm_atomic_commit(state);
8714
8715 out:
8716         drm_atomic_state_put(state);
8717         if (ret)
8718                 DRM_ERROR("Restoring old state failed with %i\n", ret);
8719
8720         return ret;
8721 }
8722
8723 /*
8724  * This function handles all cases when set mode does not come upon hotplug.
8725  * This includes when a display is unplugged then plugged back into the
8726  * same port and when running without usermode desktop manager supprot
8727  */
8728 void dm_restore_drm_connector_state(struct drm_device *dev,
8729                                     struct drm_connector *connector)
8730 {
8731         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8732         struct amdgpu_crtc *disconnected_acrtc;
8733         struct dm_crtc_state *acrtc_state;
8734
8735         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8736                 return;
8737
8738         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8739         if (!disconnected_acrtc)
8740                 return;
8741
8742         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8743         if (!acrtc_state->stream)
8744                 return;
8745
8746         /*
8747          * If the previous sink is not released and different from the current,
8748          * we deduce we are in a state where we can not rely on usermode call
8749          * to turn on the display, so we do it here
8750          */
8751         if (acrtc_state->stream->sink != aconnector->dc_sink)
8752                 dm_force_atomic_commit(&aconnector->base);
8753 }
8754
8755 /*
8756  * Grabs all modesetting locks to serialize against any blocking commits,
8757  * Waits for completion of all non blocking commits.
8758  */
8759 static int do_aquire_global_lock(struct drm_device *dev,
8760                                  struct drm_atomic_state *state)
8761 {
8762         struct drm_crtc *crtc;
8763         struct drm_crtc_commit *commit;
8764         long ret;
8765
8766         /*
8767          * Adding all modeset locks to aquire_ctx will
8768          * ensure that when the framework release it the
8769          * extra locks we are locking here will get released to
8770          */
8771         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8772         if (ret)
8773                 return ret;
8774
8775         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8776                 spin_lock(&crtc->commit_lock);
8777                 commit = list_first_entry_or_null(&crtc->commit_list,
8778                                 struct drm_crtc_commit, commit_entry);
8779                 if (commit)
8780                         drm_crtc_commit_get(commit);
8781                 spin_unlock(&crtc->commit_lock);
8782
8783                 if (!commit)
8784                         continue;
8785
8786                 /*
8787                  * Make sure all pending HW programming completed and
8788                  * page flips done
8789                  */
8790                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8791
8792                 if (ret > 0)
8793                         ret = wait_for_completion_interruptible_timeout(
8794                                         &commit->flip_done, 10*HZ);
8795
8796                 if (ret == 0)
8797                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8798                                   "timed out\n", crtc->base.id, crtc->name);
8799
8800                 drm_crtc_commit_put(commit);
8801         }
8802
8803         return ret < 0 ? ret : 0;
8804 }
8805
8806 static void get_freesync_config_for_crtc(
8807         struct dm_crtc_state *new_crtc_state,
8808         struct dm_connector_state *new_con_state)
8809 {
8810         struct mod_freesync_config config = {0};
8811         struct amdgpu_dm_connector *aconnector =
8812                         to_amdgpu_dm_connector(new_con_state->base.connector);
8813         struct drm_display_mode *mode = &new_crtc_state->base.mode;
8814         int vrefresh = drm_mode_vrefresh(mode);
8815         bool fs_vid_mode = false;
8816         bool drr_active = false;
8817
8818         new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8819                                         vrefresh >= aconnector->min_vfreq &&
8820                                         vrefresh <= aconnector->max_vfreq;
8821
8822         drr_active = new_crtc_state->vrr_supported &&
8823                 new_crtc_state->freesync_config.state != VRR_STATE_DISABLED &&
8824                 new_crtc_state->freesync_config.state != VRR_STATE_INACTIVE &&
8825                 new_crtc_state->freesync_config.state != VRR_STATE_UNSUPPORTED;
8826
8827         if (drr_active)
8828                 new_crtc_state->stream->ignore_msa_timing_param = true;
8829
8830         if (new_crtc_state->vrr_supported) {
8831                 fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8832                 config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8833                 config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8834                 config.vsif_supported = true;
8835                 config.btr = true;
8836
8837                 if (fs_vid_mode) {
8838                         config.state = VRR_STATE_ACTIVE_FIXED;
8839                         config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8840                         goto out;
8841                 } else if (new_crtc_state->base.vrr_enabled) {
8842                         config.state = VRR_STATE_ACTIVE_VARIABLE;
8843                 } else {
8844                         config.state = VRR_STATE_INACTIVE;
8845                 }
8846         }
8847 out:
8848         new_crtc_state->freesync_config = config;
8849 }
8850
8851 static void reset_freesync_config_for_crtc(
8852         struct dm_crtc_state *new_crtc_state)
8853 {
8854         new_crtc_state->vrr_supported = false;
8855
8856         memset(&new_crtc_state->vrr_infopacket, 0,
8857                sizeof(new_crtc_state->vrr_infopacket));
8858 }
8859
8860 static bool
8861 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8862                                  struct drm_crtc_state *new_crtc_state)
8863 {
8864         const struct drm_display_mode *old_mode, *new_mode;
8865
8866         if (!old_crtc_state || !new_crtc_state)
8867                 return false;
8868
8869         old_mode = &old_crtc_state->mode;
8870         new_mode = &new_crtc_state->mode;
8871
8872         if (old_mode->clock       == new_mode->clock &&
8873             old_mode->hdisplay    == new_mode->hdisplay &&
8874             old_mode->vdisplay    == new_mode->vdisplay &&
8875             old_mode->htotal      == new_mode->htotal &&
8876             old_mode->vtotal      != new_mode->vtotal &&
8877             old_mode->hsync_start == new_mode->hsync_start &&
8878             old_mode->vsync_start != new_mode->vsync_start &&
8879             old_mode->hsync_end   == new_mode->hsync_end &&
8880             old_mode->vsync_end   != new_mode->vsync_end &&
8881             old_mode->hskew       == new_mode->hskew &&
8882             old_mode->vscan       == new_mode->vscan &&
8883             (old_mode->vsync_end - old_mode->vsync_start) ==
8884             (new_mode->vsync_end - new_mode->vsync_start))
8885                 return true;
8886
8887         return false;
8888 }
8889
8890 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
8891         u64 num, den, res;
8892         struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
8893
8894         dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
8895
8896         num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
8897         den = (unsigned long long)new_crtc_state->mode.htotal *
8898               (unsigned long long)new_crtc_state->mode.vtotal;
8899
8900         res = div_u64(num, den);
8901         dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
8902 }
8903
8904 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
8905                          struct drm_atomic_state *state,
8906                          struct drm_crtc *crtc,
8907                          struct drm_crtc_state *old_crtc_state,
8908                          struct drm_crtc_state *new_crtc_state,
8909                          bool enable,
8910                          bool *lock_and_validation_needed)
8911 {
8912         struct dm_atomic_state *dm_state = NULL;
8913         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8914         struct dc_stream_state *new_stream;
8915         int ret = 0;
8916
8917         /*
8918          * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
8919          * update changed items
8920          */
8921         struct amdgpu_crtc *acrtc = NULL;
8922         struct amdgpu_dm_connector *aconnector = NULL;
8923         struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
8924         struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
8925
8926         new_stream = NULL;
8927
8928         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8929         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8930         acrtc = to_amdgpu_crtc(crtc);
8931         aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
8932
8933         /* TODO This hack should go away */
8934         if (aconnector && enable) {
8935                 /* Make sure fake sink is created in plug-in scenario */
8936                 drm_new_conn_state = drm_atomic_get_new_connector_state(state,
8937                                                             &aconnector->base);
8938                 drm_old_conn_state = drm_atomic_get_old_connector_state(state,
8939                                                             &aconnector->base);
8940
8941                 if (IS_ERR(drm_new_conn_state)) {
8942                         ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
8943                         goto fail;
8944                 }
8945
8946                 dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
8947                 dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
8948
8949                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8950                         goto skip_modeset;
8951
8952                 new_stream = create_validate_stream_for_sink(aconnector,
8953                                                              &new_crtc_state->mode,
8954                                                              dm_new_conn_state,
8955                                                              dm_old_crtc_state->stream);
8956
8957                 /*
8958                  * we can have no stream on ACTION_SET if a display
8959                  * was disconnected during S3, in this case it is not an
8960                  * error, the OS will be updated after detection, and
8961                  * will do the right thing on next atomic commit
8962                  */
8963
8964                 if (!new_stream) {
8965                         DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8966                                         __func__, acrtc->base.base.id);
8967                         ret = -ENOMEM;
8968                         goto fail;
8969                 }
8970
8971                 /*
8972                  * TODO: Check VSDB bits to decide whether this should
8973                  * be enabled or not.
8974                  */
8975                 new_stream->triggered_crtc_reset.enabled =
8976                         dm->force_timing_sync;
8977
8978                 dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8979
8980                 ret = fill_hdr_info_packet(drm_new_conn_state,
8981                                            &new_stream->hdr_static_metadata);
8982                 if (ret)
8983                         goto fail;
8984
8985                 /*
8986                  * If we already removed the old stream from the context
8987                  * (and set the new stream to NULL) then we can't reuse
8988                  * the old stream even if the stream and scaling are unchanged.
8989                  * We'll hit the BUG_ON and black screen.
8990                  *
8991                  * TODO: Refactor this function to allow this check to work
8992                  * in all conditions.
8993                  */
8994                 if (amdgpu_freesync_vid_mode &&
8995                     dm_new_crtc_state->stream &&
8996                     is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
8997                         goto skip_modeset;
8998
8999                 if (dm_new_crtc_state->stream &&
9000                     dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9001                     dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
9002                         new_crtc_state->mode_changed = false;
9003                         DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
9004                                          new_crtc_state->mode_changed);
9005                 }
9006         }
9007
9008         /* mode_changed flag may get updated above, need to check again */
9009         if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9010                 goto skip_modeset;
9011
9012         drm_dbg_state(state->dev,
9013                 "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
9014                 "planes_changed:%d, mode_changed:%d,active_changed:%d,"
9015                 "connectors_changed:%d\n",
9016                 acrtc->crtc_id,
9017                 new_crtc_state->enable,
9018                 new_crtc_state->active,
9019                 new_crtc_state->planes_changed,
9020                 new_crtc_state->mode_changed,
9021                 new_crtc_state->active_changed,
9022                 new_crtc_state->connectors_changed);
9023
9024         /* Remove stream for any changed/disabled CRTC */
9025         if (!enable) {
9026
9027                 if (!dm_old_crtc_state->stream)
9028                         goto skip_modeset;
9029
9030                 if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
9031                     is_timing_unchanged_for_freesync(new_crtc_state,
9032                                                      old_crtc_state)) {
9033                         new_crtc_state->mode_changed = false;
9034                         DRM_DEBUG_DRIVER(
9035                                 "Mode change not required for front porch change, "
9036                                 "setting mode_changed to %d",
9037                                 new_crtc_state->mode_changed);
9038
9039                         set_freesync_fixed_config(dm_new_crtc_state);
9040
9041                         goto skip_modeset;
9042                 } else if (amdgpu_freesync_vid_mode && aconnector &&
9043                            is_freesync_video_mode(&new_crtc_state->mode,
9044                                                   aconnector)) {
9045                         struct drm_display_mode *high_mode;
9046
9047                         high_mode = get_highest_refresh_rate_mode(aconnector, false);
9048                         if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
9049                                 set_freesync_fixed_config(dm_new_crtc_state);
9050                         }
9051                 }
9052
9053                 ret = dm_atomic_get_state(state, &dm_state);
9054                 if (ret)
9055                         goto fail;
9056
9057                 DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
9058                                 crtc->base.id);
9059
9060                 /* i.e. reset mode */
9061                 if (dc_remove_stream_from_ctx(
9062                                 dm->dc,
9063                                 dm_state->context,
9064                                 dm_old_crtc_state->stream) != DC_OK) {
9065                         ret = -EINVAL;
9066                         goto fail;
9067                 }
9068
9069                 dc_stream_release(dm_old_crtc_state->stream);
9070                 dm_new_crtc_state->stream = NULL;
9071
9072                 reset_freesync_config_for_crtc(dm_new_crtc_state);
9073
9074                 *lock_and_validation_needed = true;
9075
9076         } else {/* Add stream for any updated/enabled CRTC */
9077                 /*
9078                  * Quick fix to prevent NULL pointer on new_stream when
9079                  * added MST connectors not found in existing crtc_state in the chained mode
9080                  * TODO: need to dig out the root cause of that
9081                  */
9082                 if (!aconnector)
9083                         goto skip_modeset;
9084
9085                 if (modereset_required(new_crtc_state))
9086                         goto skip_modeset;
9087
9088                 if (modeset_required(new_crtc_state, new_stream,
9089                                      dm_old_crtc_state->stream)) {
9090
9091                         WARN_ON(dm_new_crtc_state->stream);
9092
9093                         ret = dm_atomic_get_state(state, &dm_state);
9094                         if (ret)
9095                                 goto fail;
9096
9097                         dm_new_crtc_state->stream = new_stream;
9098
9099                         dc_stream_retain(new_stream);
9100
9101                         DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
9102                                          crtc->base.id);
9103
9104                         if (dc_add_stream_to_ctx(
9105                                         dm->dc,
9106                                         dm_state->context,
9107                                         dm_new_crtc_state->stream) != DC_OK) {
9108                                 ret = -EINVAL;
9109                                 goto fail;
9110                         }
9111
9112                         *lock_and_validation_needed = true;
9113                 }
9114         }
9115
9116 skip_modeset:
9117         /* Release extra reference */
9118         if (new_stream)
9119                  dc_stream_release(new_stream);
9120
9121         /*
9122          * We want to do dc stream updates that do not require a
9123          * full modeset below.
9124          */
9125         if (!(enable && aconnector && new_crtc_state->active))
9126                 return 0;
9127         /*
9128          * Given above conditions, the dc state cannot be NULL because:
9129          * 1. We're in the process of enabling CRTCs (just been added
9130          *    to the dc context, or already is on the context)
9131          * 2. Has a valid connector attached, and
9132          * 3. Is currently active and enabled.
9133          * => The dc stream state currently exists.
9134          */
9135         BUG_ON(dm_new_crtc_state->stream == NULL);
9136
9137         /* Scaling or underscan settings */
9138         if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
9139                                 drm_atomic_crtc_needs_modeset(new_crtc_state))
9140                 update_stream_scaling_settings(
9141                         &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
9142
9143         /* ABM settings */
9144         dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9145
9146         /*
9147          * Color management settings. We also update color properties
9148          * when a modeset is needed, to ensure it gets reprogrammed.
9149          */
9150         if (dm_new_crtc_state->base.color_mgmt_changed ||
9151             drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9152                 ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
9153                 if (ret)
9154                         goto fail;
9155         }
9156
9157         /* Update Freesync settings. */
9158         get_freesync_config_for_crtc(dm_new_crtc_state,
9159                                      dm_new_conn_state);
9160
9161         return ret;
9162
9163 fail:
9164         if (new_stream)
9165                 dc_stream_release(new_stream);
9166         return ret;
9167 }
9168
9169 static bool should_reset_plane(struct drm_atomic_state *state,
9170                                struct drm_plane *plane,
9171                                struct drm_plane_state *old_plane_state,
9172                                struct drm_plane_state *new_plane_state)
9173 {
9174         struct drm_plane *other;
9175         struct drm_plane_state *old_other_state, *new_other_state;
9176         struct drm_crtc_state *new_crtc_state;
9177         int i;
9178
9179         /*
9180          * TODO: Remove this hack once the checks below are sufficient
9181          * enough to determine when we need to reset all the planes on
9182          * the stream.
9183          */
9184         if (state->allow_modeset)
9185                 return true;
9186
9187         /* Exit early if we know that we're adding or removing the plane. */
9188         if (old_plane_state->crtc != new_plane_state->crtc)
9189                 return true;
9190
9191         /* old crtc == new_crtc == NULL, plane not in context. */
9192         if (!new_plane_state->crtc)
9193                 return false;
9194
9195         new_crtc_state =
9196                 drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
9197
9198         if (!new_crtc_state)
9199                 return true;
9200
9201         /* CRTC Degamma changes currently require us to recreate planes. */
9202         if (new_crtc_state->color_mgmt_changed)
9203                 return true;
9204
9205         if (drm_atomic_crtc_needs_modeset(new_crtc_state))
9206                 return true;
9207
9208         /*
9209          * If there are any new primary or overlay planes being added or
9210          * removed then the z-order can potentially change. To ensure
9211          * correct z-order and pipe acquisition the current DC architecture
9212          * requires us to remove and recreate all existing planes.
9213          *
9214          * TODO: Come up with a more elegant solution for this.
9215          */
9216         for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9217                 struct amdgpu_framebuffer *old_afb, *new_afb;
9218                 if (other->type == DRM_PLANE_TYPE_CURSOR)
9219                         continue;
9220
9221                 if (old_other_state->crtc != new_plane_state->crtc &&
9222                     new_other_state->crtc != new_plane_state->crtc)
9223                         continue;
9224
9225                 if (old_other_state->crtc != new_other_state->crtc)
9226                         return true;
9227
9228                 /* Src/dst size and scaling updates. */
9229                 if (old_other_state->src_w != new_other_state->src_w ||
9230                     old_other_state->src_h != new_other_state->src_h ||
9231                     old_other_state->crtc_w != new_other_state->crtc_w ||
9232                     old_other_state->crtc_h != new_other_state->crtc_h)
9233                         return true;
9234
9235                 /* Rotation / mirroring updates. */
9236                 if (old_other_state->rotation != new_other_state->rotation)
9237                         return true;
9238
9239                 /* Blending updates. */
9240                 if (old_other_state->pixel_blend_mode !=
9241                     new_other_state->pixel_blend_mode)
9242                         return true;
9243
9244                 /* Alpha updates. */
9245                 if (old_other_state->alpha != new_other_state->alpha)
9246                         return true;
9247
9248                 /* Colorspace changes. */
9249                 if (old_other_state->color_range != new_other_state->color_range ||
9250                     old_other_state->color_encoding != new_other_state->color_encoding)
9251                         return true;
9252
9253                 /* Framebuffer checks fall at the end. */
9254                 if (!old_other_state->fb || !new_other_state->fb)
9255                         continue;
9256
9257                 /* Pixel format changes can require bandwidth updates. */
9258                 if (old_other_state->fb->format != new_other_state->fb->format)
9259                         return true;
9260
9261                 old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9262                 new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9263
9264                 /* Tiling and DCC changes also require bandwidth updates. */
9265                 if (old_afb->tiling_flags != new_afb->tiling_flags ||
9266                     old_afb->base.modifier != new_afb->base.modifier)
9267                         return true;
9268         }
9269
9270         return false;
9271 }
9272
9273 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9274                               struct drm_plane_state *new_plane_state,
9275                               struct drm_framebuffer *fb)
9276 {
9277         struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9278         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9279         unsigned int pitch;
9280         bool linear;
9281
9282         if (fb->width > new_acrtc->max_cursor_width ||
9283             fb->height > new_acrtc->max_cursor_height) {
9284                 DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9285                                  new_plane_state->fb->width,
9286                                  new_plane_state->fb->height);
9287                 return -EINVAL;
9288         }
9289         if (new_plane_state->src_w != fb->width << 16 ||
9290             new_plane_state->src_h != fb->height << 16) {
9291                 DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9292                 return -EINVAL;
9293         }
9294
9295         /* Pitch in pixels */
9296         pitch = fb->pitches[0] / fb->format->cpp[0];
9297
9298         if (fb->width != pitch) {
9299                 DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9300                                  fb->width, pitch);
9301                 return -EINVAL;
9302         }
9303
9304         switch (pitch) {
9305         case 64:
9306         case 128:
9307         case 256:
9308                 /* FB pitch is supported by cursor plane */
9309                 break;
9310         default:
9311                 DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9312                 return -EINVAL;
9313         }
9314
9315         /* Core DRM takes care of checking FB modifiers, so we only need to
9316          * check tiling flags when the FB doesn't have a modifier. */
9317         if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9318                 if (adev->family < AMDGPU_FAMILY_AI) {
9319                         linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9320                                  AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9321                                  AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9322                 } else {
9323                         linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9324                 }
9325                 if (!linear) {
9326                         DRM_DEBUG_ATOMIC("Cursor FB not linear");
9327                         return -EINVAL;
9328                 }
9329         }
9330
9331         return 0;
9332 }
9333
9334 static int dm_update_plane_state(struct dc *dc,
9335                                  struct drm_atomic_state *state,
9336                                  struct drm_plane *plane,
9337                                  struct drm_plane_state *old_plane_state,
9338                                  struct drm_plane_state *new_plane_state,
9339                                  bool enable,
9340                                  bool *lock_and_validation_needed)
9341 {
9342
9343         struct dm_atomic_state *dm_state = NULL;
9344         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9345         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9346         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9347         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9348         struct amdgpu_crtc *new_acrtc;
9349         bool needs_reset;
9350         int ret = 0;
9351
9352
9353         new_plane_crtc = new_plane_state->crtc;
9354         old_plane_crtc = old_plane_state->crtc;
9355         dm_new_plane_state = to_dm_plane_state(new_plane_state);
9356         dm_old_plane_state = to_dm_plane_state(old_plane_state);
9357
9358         if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9359                 if (!enable || !new_plane_crtc ||
9360                         drm_atomic_plane_disabling(plane->state, new_plane_state))
9361                         return 0;
9362
9363                 new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9364
9365                 if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9366                         DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9367                         return -EINVAL;
9368                 }
9369
9370                 if (new_plane_state->fb) {
9371                         ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9372                                                  new_plane_state->fb);
9373                         if (ret)
9374                                 return ret;
9375                 }
9376
9377                 return 0;
9378         }
9379
9380         needs_reset = should_reset_plane(state, plane, old_plane_state,
9381                                          new_plane_state);
9382
9383         /* Remove any changed/removed planes */
9384         if (!enable) {
9385                 if (!needs_reset)
9386                         return 0;
9387
9388                 if (!old_plane_crtc)
9389                         return 0;
9390
9391                 old_crtc_state = drm_atomic_get_old_crtc_state(
9392                                 state, old_plane_crtc);
9393                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9394
9395                 if (!dm_old_crtc_state->stream)
9396                         return 0;
9397
9398                 DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9399                                 plane->base.id, old_plane_crtc->base.id);
9400
9401                 ret = dm_atomic_get_state(state, &dm_state);
9402                 if (ret)
9403                         return ret;
9404
9405                 if (!dc_remove_plane_from_context(
9406                                 dc,
9407                                 dm_old_crtc_state->stream,
9408                                 dm_old_plane_state->dc_state,
9409                                 dm_state->context)) {
9410
9411                         return -EINVAL;
9412                 }
9413
9414
9415                 dc_plane_state_release(dm_old_plane_state->dc_state);
9416                 dm_new_plane_state->dc_state = NULL;
9417
9418                 *lock_and_validation_needed = true;
9419
9420         } else { /* Add new planes */
9421                 struct dc_plane_state *dc_new_plane_state;
9422
9423                 if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9424                         return 0;
9425
9426                 if (!new_plane_crtc)
9427                         return 0;
9428
9429                 new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9430                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9431
9432                 if (!dm_new_crtc_state->stream)
9433                         return 0;
9434
9435                 if (!needs_reset)
9436                         return 0;
9437
9438                 ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9439                 if (ret)
9440                         return ret;
9441
9442                 WARN_ON(dm_new_plane_state->dc_state);
9443
9444                 dc_new_plane_state = dc_create_plane_state(dc);
9445                 if (!dc_new_plane_state)
9446                         return -ENOMEM;
9447
9448                 DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9449                                  plane->base.id, new_plane_crtc->base.id);
9450
9451                 ret = fill_dc_plane_attributes(
9452                         drm_to_adev(new_plane_crtc->dev),
9453                         dc_new_plane_state,
9454                         new_plane_state,
9455                         new_crtc_state);
9456                 if (ret) {
9457                         dc_plane_state_release(dc_new_plane_state);
9458                         return ret;
9459                 }
9460
9461                 ret = dm_atomic_get_state(state, &dm_state);
9462                 if (ret) {
9463                         dc_plane_state_release(dc_new_plane_state);
9464                         return ret;
9465                 }
9466
9467                 /*
9468                  * Any atomic check errors that occur after this will
9469                  * not need a release. The plane state will be attached
9470                  * to the stream, and therefore part of the atomic
9471                  * state. It'll be released when the atomic state is
9472                  * cleaned.
9473                  */
9474                 if (!dc_add_plane_to_context(
9475                                 dc,
9476                                 dm_new_crtc_state->stream,
9477                                 dc_new_plane_state,
9478                                 dm_state->context)) {
9479
9480                         dc_plane_state_release(dc_new_plane_state);
9481                         return -EINVAL;
9482                 }
9483
9484                 dm_new_plane_state->dc_state = dc_new_plane_state;
9485
9486                 dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9487
9488                 /* Tell DC to do a full surface update every time there
9489                  * is a plane change. Inefficient, but works for now.
9490                  */
9491                 dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9492
9493                 *lock_and_validation_needed = true;
9494         }
9495
9496
9497         return ret;
9498 }
9499
9500 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9501                                        int *src_w, int *src_h)
9502 {
9503         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9504         case DRM_MODE_ROTATE_90:
9505         case DRM_MODE_ROTATE_270:
9506                 *src_w = plane_state->src_h >> 16;
9507                 *src_h = plane_state->src_w >> 16;
9508                 break;
9509         case DRM_MODE_ROTATE_0:
9510         case DRM_MODE_ROTATE_180:
9511         default:
9512                 *src_w = plane_state->src_w >> 16;
9513                 *src_h = plane_state->src_h >> 16;
9514                 break;
9515         }
9516 }
9517
9518 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9519                                 struct drm_crtc *crtc,
9520                                 struct drm_crtc_state *new_crtc_state)
9521 {
9522         struct drm_plane *cursor = crtc->cursor, *underlying;
9523         struct drm_plane_state *new_cursor_state, *new_underlying_state;
9524         int i;
9525         int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9526         int cursor_src_w, cursor_src_h;
9527         int underlying_src_w, underlying_src_h;
9528
9529         /* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9530          * cursor per pipe but it's going to inherit the scaling and
9531          * positioning from the underlying pipe. Check the cursor plane's
9532          * blending properties match the underlying planes'. */
9533
9534         new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9535         if (!new_cursor_state || !new_cursor_state->fb) {
9536                 return 0;
9537         }
9538
9539         dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9540         cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9541         cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9542
9543         for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9544                 /* Narrow down to non-cursor planes on the same CRTC as the cursor */
9545                 if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9546                         continue;
9547
9548                 /* Ignore disabled planes */
9549                 if (!new_underlying_state->fb)
9550                         continue;
9551
9552                 dm_get_oriented_plane_size(new_underlying_state,
9553                                            &underlying_src_w, &underlying_src_h);
9554                 underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9555                 underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9556
9557                 if (cursor_scale_w != underlying_scale_w ||
9558                     cursor_scale_h != underlying_scale_h) {
9559                         drm_dbg_atomic(crtc->dev,
9560                                        "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9561                                        cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9562                         return -EINVAL;
9563                 }
9564
9565                 /* If this plane covers the whole CRTC, no need to check planes underneath */
9566                 if (new_underlying_state->crtc_x <= 0 &&
9567                     new_underlying_state->crtc_y <= 0 &&
9568                     new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9569                     new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9570                         break;
9571         }
9572
9573         return 0;
9574 }
9575
9576 #if defined(CONFIG_DRM_AMD_DC_DCN)
9577 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9578 {
9579         struct drm_connector *connector;
9580         struct drm_connector_state *conn_state, *old_conn_state;
9581         struct amdgpu_dm_connector *aconnector = NULL;
9582         int i;
9583         for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9584                 if (!conn_state->crtc)
9585                         conn_state = old_conn_state;
9586
9587                 if (conn_state->crtc != crtc)
9588                         continue;
9589
9590                 aconnector = to_amdgpu_dm_connector(connector);
9591                 if (!aconnector->port || !aconnector->mst_port)
9592                         aconnector = NULL;
9593                 else
9594                         break;
9595         }
9596
9597         if (!aconnector)
9598                 return 0;
9599
9600         return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_port->mst_mgr);
9601 }
9602 #endif
9603
9604 /**
9605  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9606  *
9607  * @dev: The DRM device
9608  * @state: The atomic state to commit
9609  *
9610  * Validate that the given atomic state is programmable by DC into hardware.
9611  * This involves constructing a &struct dc_state reflecting the new hardware
9612  * state we wish to commit, then querying DC to see if it is programmable. It's
9613  * important not to modify the existing DC state. Otherwise, atomic_check
9614  * may unexpectedly commit hardware changes.
9615  *
9616  * When validating the DC state, it's important that the right locks are
9617  * acquired. For full updates case which removes/adds/updates streams on one
9618  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9619  * that any such full update commit will wait for completion of any outstanding
9620  * flip using DRMs synchronization events.
9621  *
9622  * Note that DM adds the affected connectors for all CRTCs in state, when that
9623  * might not seem necessary. This is because DC stream creation requires the
9624  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9625  * be possible but non-trivial - a possible TODO item.
9626  *
9627  * Return: -Error code if validation failed.
9628  */
9629 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9630                                   struct drm_atomic_state *state)
9631 {
9632         struct amdgpu_device *adev = drm_to_adev(dev);
9633         struct dm_atomic_state *dm_state = NULL;
9634         struct dc *dc = adev->dm.dc;
9635         struct drm_connector *connector;
9636         struct drm_connector_state *old_con_state, *new_con_state;
9637         struct drm_crtc *crtc;
9638         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9639         struct drm_plane *plane;
9640         struct drm_plane_state *old_plane_state, *new_plane_state;
9641         enum dc_status status;
9642         int ret, i;
9643         bool lock_and_validation_needed = false;
9644         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9645 #if defined(CONFIG_DRM_AMD_DC_DCN)
9646         struct dsc_mst_fairness_vars vars[MAX_PIPES];
9647 #endif
9648
9649         trace_amdgpu_dm_atomic_check_begin(state);
9650
9651         ret = drm_atomic_helper_check_modeset(dev, state);
9652         if (ret) {
9653                 DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9654                 goto fail;
9655         }
9656
9657         /* Check connector changes */
9658         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9659                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9660                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9661
9662                 /* Skip connectors that are disabled or part of modeset already. */
9663                 if (!new_con_state->crtc)
9664                         continue;
9665
9666                 new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9667                 if (IS_ERR(new_crtc_state)) {
9668                         DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9669                         ret = PTR_ERR(new_crtc_state);
9670                         goto fail;
9671                 }
9672
9673                 if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
9674                     dm_old_con_state->scaling != dm_new_con_state->scaling)
9675                         new_crtc_state->connectors_changed = true;
9676         }
9677
9678 #if defined(CONFIG_DRM_AMD_DC_DCN)
9679         if (dc_resource_is_dsc_encoding_supported(dc)) {
9680                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9681                         if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9682                                 ret = add_affected_mst_dsc_crtcs(state, crtc);
9683                                 if (ret) {
9684                                         DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9685                                         goto fail;
9686                                 }
9687                         }
9688                 }
9689         }
9690 #endif
9691         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9692                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9693
9694                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9695                     !new_crtc_state->color_mgmt_changed &&
9696                     old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9697                         dm_old_crtc_state->dsc_force_changed == false)
9698                         continue;
9699
9700                 ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9701                 if (ret) {
9702                         DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9703                         goto fail;
9704                 }
9705
9706                 if (!new_crtc_state->enable)
9707                         continue;
9708
9709                 ret = drm_atomic_add_affected_connectors(state, crtc);
9710                 if (ret) {
9711                         DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9712                         goto fail;
9713                 }
9714
9715                 ret = drm_atomic_add_affected_planes(state, crtc);
9716                 if (ret) {
9717                         DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9718                         goto fail;
9719                 }
9720
9721                 if (dm_old_crtc_state->dsc_force_changed)
9722                         new_crtc_state->mode_changed = true;
9723         }
9724
9725         /*
9726          * Add all primary and overlay planes on the CRTC to the state
9727          * whenever a plane is enabled to maintain correct z-ordering
9728          * and to enable fast surface updates.
9729          */
9730         drm_for_each_crtc(crtc, dev) {
9731                 bool modified = false;
9732
9733                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9734                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
9735                                 continue;
9736
9737                         if (new_plane_state->crtc == crtc ||
9738                             old_plane_state->crtc == crtc) {
9739                                 modified = true;
9740                                 break;
9741                         }
9742                 }
9743
9744                 if (!modified)
9745                         continue;
9746
9747                 drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9748                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
9749                                 continue;
9750
9751                         new_plane_state =
9752                                 drm_atomic_get_plane_state(state, plane);
9753
9754                         if (IS_ERR(new_plane_state)) {
9755                                 ret = PTR_ERR(new_plane_state);
9756                                 DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9757                                 goto fail;
9758                         }
9759                 }
9760         }
9761
9762         /*
9763          * DC consults the zpos (layer_index in DC terminology) to determine the
9764          * hw plane on which to enable the hw cursor (see
9765          * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9766          * atomic state, so call drm helper to normalize zpos.
9767          */
9768         drm_atomic_normalize_zpos(dev, state);
9769
9770         /* Remove exiting planes if they are modified */
9771         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9772                 ret = dm_update_plane_state(dc, state, plane,
9773                                             old_plane_state,
9774                                             new_plane_state,
9775                                             false,
9776                                             &lock_and_validation_needed);
9777                 if (ret) {
9778                         DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9779                         goto fail;
9780                 }
9781         }
9782
9783         /* Disable all crtcs which require disable */
9784         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9785                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
9786                                            old_crtc_state,
9787                                            new_crtc_state,
9788                                            false,
9789                                            &lock_and_validation_needed);
9790                 if (ret) {
9791                         DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9792                         goto fail;
9793                 }
9794         }
9795
9796         /* Enable all crtcs which require enable */
9797         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9798                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
9799                                            old_crtc_state,
9800                                            new_crtc_state,
9801                                            true,
9802                                            &lock_and_validation_needed);
9803                 if (ret) {
9804                         DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9805                         goto fail;
9806                 }
9807         }
9808
9809         /* Add new/modified planes */
9810         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9811                 ret = dm_update_plane_state(dc, state, plane,
9812                                             old_plane_state,
9813                                             new_plane_state,
9814                                             true,
9815                                             &lock_and_validation_needed);
9816                 if (ret) {
9817                         DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9818                         goto fail;
9819                 }
9820         }
9821
9822 #if defined(CONFIG_DRM_AMD_DC_DCN)
9823         if (dc_resource_is_dsc_encoding_supported(dc)) {
9824                 ret = pre_validate_dsc(state, &dm_state, vars);
9825                 if (ret != 0)
9826                         goto fail;
9827         }
9828 #endif
9829
9830         /* Run this here since we want to validate the streams we created */
9831         ret = drm_atomic_helper_check_planes(dev, state);
9832         if (ret) {
9833                 DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
9834                 goto fail;
9835         }
9836
9837         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9838                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9839                 if (dm_new_crtc_state->mpo_requested)
9840                         DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
9841         }
9842
9843         /* Check cursor planes scaling */
9844         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9845                 ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
9846                 if (ret) {
9847                         DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
9848                         goto fail;
9849                 }
9850         }
9851
9852         if (state->legacy_cursor_update) {
9853                 /*
9854                  * This is a fast cursor update coming from the plane update
9855                  * helper, check if it can be done asynchronously for better
9856                  * performance.
9857                  */
9858                 state->async_update =
9859                         !drm_atomic_helper_async_check(dev, state);
9860
9861                 /*
9862                  * Skip the remaining global validation if this is an async
9863                  * update. Cursor updates can be done without affecting
9864                  * state or bandwidth calcs and this avoids the performance
9865                  * penalty of locking the private state object and
9866                  * allocating a new dc_state.
9867                  */
9868                 if (state->async_update)
9869                         return 0;
9870         }
9871
9872         /* Check scaling and underscan changes*/
9873         /* TODO Removed scaling changes validation due to inability to commit
9874          * new stream into context w\o causing full reset. Need to
9875          * decide how to handle.
9876          */
9877         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9878                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9879                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9880                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9881
9882                 /* Skip any modesets/resets */
9883                 if (!acrtc || drm_atomic_crtc_needs_modeset(
9884                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
9885                         continue;
9886
9887                 /* Skip any thing not scale or underscan changes */
9888                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
9889                         continue;
9890
9891                 lock_and_validation_needed = true;
9892         }
9893
9894         /**
9895          * Streams and planes are reset when there are changes that affect
9896          * bandwidth. Anything that affects bandwidth needs to go through
9897          * DC global validation to ensure that the configuration can be applied
9898          * to hardware.
9899          *
9900          * We have to currently stall out here in atomic_check for outstanding
9901          * commits to finish in this case because our IRQ handlers reference
9902          * DRM state directly - we can end up disabling interrupts too early
9903          * if we don't.
9904          *
9905          * TODO: Remove this stall and drop DM state private objects.
9906          */
9907         if (lock_and_validation_needed) {
9908                 ret = dm_atomic_get_state(state, &dm_state);
9909                 if (ret) {
9910                         DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
9911                         goto fail;
9912                 }
9913
9914                 ret = do_aquire_global_lock(dev, state);
9915                 if (ret) {
9916                         DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
9917                         goto fail;
9918                 }
9919
9920 #if defined(CONFIG_DRM_AMD_DC_DCN)
9921                 ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
9922                 if (ret) {
9923                         DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
9924                         goto fail;
9925                 }
9926
9927                 ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
9928                 if (ret) {
9929                         DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
9930                         goto fail;
9931                 }
9932 #endif
9933
9934                 /*
9935                  * Perform validation of MST topology in the state:
9936                  * We need to perform MST atomic check before calling
9937                  * dc_validate_global_state(), or there is a chance
9938                  * to get stuck in an infinite loop and hang eventually.
9939                  */
9940                 ret = drm_dp_mst_atomic_check(state);
9941                 if (ret) {
9942                         DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
9943                         goto fail;
9944                 }
9945                 status = dc_validate_global_state(dc, dm_state->context, true);
9946                 if (status != DC_OK) {
9947                         DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
9948                                        dc_status_to_str(status), status);
9949                         ret = -EINVAL;
9950                         goto fail;
9951                 }
9952         } else {
9953                 /*
9954                  * The commit is a fast update. Fast updates shouldn't change
9955                  * the DC context, affect global validation, and can have their
9956                  * commit work done in parallel with other commits not touching
9957                  * the same resource. If we have a new DC context as part of
9958                  * the DM atomic state from validation we need to free it and
9959                  * retain the existing one instead.
9960                  *
9961                  * Furthermore, since the DM atomic state only contains the DC
9962                  * context and can safely be annulled, we can free the state
9963                  * and clear the associated private object now to free
9964                  * some memory and avoid a possible use-after-free later.
9965                  */
9966
9967                 for (i = 0; i < state->num_private_objs; i++) {
9968                         struct drm_private_obj *obj = state->private_objs[i].ptr;
9969
9970                         if (obj->funcs == adev->dm.atomic_obj.funcs) {
9971                                 int j = state->num_private_objs-1;
9972
9973                                 dm_atomic_destroy_state(obj,
9974                                                 state->private_objs[i].state);
9975
9976                                 /* If i is not at the end of the array then the
9977                                  * last element needs to be moved to where i was
9978                                  * before the array can safely be truncated.
9979                                  */
9980                                 if (i != j)
9981                                         state->private_objs[i] =
9982                                                 state->private_objs[j];
9983
9984                                 state->private_objs[j].ptr = NULL;
9985                                 state->private_objs[j].state = NULL;
9986                                 state->private_objs[j].old_state = NULL;
9987                                 state->private_objs[j].new_state = NULL;
9988
9989                                 state->num_private_objs = j;
9990                                 break;
9991                         }
9992                 }
9993         }
9994
9995         /* Store the overall update type for use later in atomic check. */
9996         for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
9997                 struct dm_crtc_state *dm_new_crtc_state =
9998                         to_dm_crtc_state(new_crtc_state);
9999
10000                 dm_new_crtc_state->update_type = lock_and_validation_needed ?
10001                                                          UPDATE_TYPE_FULL :
10002                                                          UPDATE_TYPE_FAST;
10003         }
10004
10005         /* Must be success */
10006         WARN_ON(ret);
10007
10008         trace_amdgpu_dm_atomic_check_finish(state, ret);
10009
10010         return ret;
10011
10012 fail:
10013         if (ret == -EDEADLK)
10014                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10015         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10016                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10017         else
10018                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
10019
10020         trace_amdgpu_dm_atomic_check_finish(state, ret);
10021
10022         return ret;
10023 }
10024
10025 static bool is_dp_capable_without_timing_msa(struct dc *dc,
10026                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
10027 {
10028         u8 dpcd_data;
10029         bool capable = false;
10030
10031         if (amdgpu_dm_connector->dc_link &&
10032                 dm_helpers_dp_read_dpcd(
10033                                 NULL,
10034                                 amdgpu_dm_connector->dc_link,
10035                                 DP_DOWN_STREAM_PORT_COUNT,
10036                                 &dpcd_data,
10037                                 sizeof(dpcd_data))) {
10038                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10039         }
10040
10041         return capable;
10042 }
10043
10044 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10045                 unsigned int offset,
10046                 unsigned int total_length,
10047                 u8 *data,
10048                 unsigned int length,
10049                 struct amdgpu_hdmi_vsdb_info *vsdb)
10050 {
10051         bool res;
10052         union dmub_rb_cmd cmd;
10053         struct dmub_cmd_send_edid_cea *input;
10054         struct dmub_cmd_edid_cea_output *output;
10055
10056         if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10057                 return false;
10058
10059         memset(&cmd, 0, sizeof(cmd));
10060
10061         input = &cmd.edid_cea.data.input;
10062
10063         cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10064         cmd.edid_cea.header.sub_type = 0;
10065         cmd.edid_cea.header.payload_bytes =
10066                 sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10067         input->offset = offset;
10068         input->length = length;
10069         input->cea_total_length = total_length;
10070         memcpy(input->payload, data, length);
10071
10072         res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
10073         if (!res) {
10074                 DRM_ERROR("EDID CEA parser failed\n");
10075                 return false;
10076         }
10077
10078         output = &cmd.edid_cea.data.output;
10079
10080         if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10081                 if (!output->ack.success) {
10082                         DRM_ERROR("EDID CEA ack failed at offset %d\n",
10083                                         output->ack.offset);
10084                 }
10085         } else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10086                 if (!output->amd_vsdb.vsdb_found)
10087                         return false;
10088
10089                 vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10090                 vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10091                 vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10092                 vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10093         } else {
10094                 DRM_WARN("Unknown EDID CEA parser results\n");
10095                 return false;
10096         }
10097
10098         return true;
10099 }
10100
10101 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10102                 u8 *edid_ext, int len,
10103                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10104 {
10105         int i;
10106
10107         /* send extension block to DMCU for parsing */
10108         for (i = 0; i < len; i += 8) {
10109                 bool res;
10110                 int offset;
10111
10112                 /* send 8 bytes a time */
10113                 if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10114                         return false;
10115
10116                 if (i+8 == len) {
10117                         /* EDID block sent completed, expect result */
10118                         int version, min_rate, max_rate;
10119
10120                         res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10121                         if (res) {
10122                                 /* amd vsdb found */
10123                                 vsdb_info->freesync_supported = 1;
10124                                 vsdb_info->amd_vsdb_version = version;
10125                                 vsdb_info->min_refresh_rate_hz = min_rate;
10126                                 vsdb_info->max_refresh_rate_hz = max_rate;
10127                                 return true;
10128                         }
10129                         /* not amd vsdb */
10130                         return false;
10131                 }
10132
10133                 /* check for ack*/
10134                 res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10135                 if (!res)
10136                         return false;
10137         }
10138
10139         return false;
10140 }
10141
10142 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10143                 u8 *edid_ext, int len,
10144                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10145 {
10146         int i;
10147
10148         /* send extension block to DMCU for parsing */
10149         for (i = 0; i < len; i += 8) {
10150                 /* send 8 bytes a time */
10151                 if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10152                         return false;
10153         }
10154
10155         return vsdb_info->freesync_supported;
10156 }
10157
10158 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
10159                 u8 *edid_ext, int len,
10160                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10161 {
10162         struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
10163
10164         if (adev->dm.dmub_srv)
10165                 return parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
10166         else
10167                 return parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
10168 }
10169
10170 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
10171                 struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
10172 {
10173         u8 *edid_ext = NULL;
10174         int i;
10175         bool valid_vsdb_found = false;
10176
10177         /*----- drm_find_cea_extension() -----*/
10178         /* No EDID or EDID extensions */
10179         if (edid == NULL || edid->extensions == 0)
10180                 return -ENODEV;
10181
10182         /* Find CEA extension */
10183         for (i = 0; i < edid->extensions; i++) {
10184                 edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
10185                 if (edid_ext[0] == CEA_EXT)
10186                         break;
10187         }
10188
10189         if (i == edid->extensions)
10190                 return -ENODEV;
10191
10192         /*----- cea_db_offsets() -----*/
10193         if (edid_ext[0] != CEA_EXT)
10194                 return -ENODEV;
10195
10196         valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
10197
10198         return valid_vsdb_found ? i : -ENODEV;
10199 }
10200
10201 /**
10202  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
10203  *
10204  * @connector: Connector to query.
10205  * @edid: EDID from monitor
10206  *
10207  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
10208  * track of some of the display information in the internal data struct used by
10209  * amdgpu_dm. This function checks which type of connector we need to set the
10210  * FreeSync parameters.
10211  */
10212 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
10213                                     struct edid *edid)
10214 {
10215         int i = 0;
10216         struct detailed_timing *timing;
10217         struct detailed_non_pixel *data;
10218         struct detailed_data_monitor_range *range;
10219         struct amdgpu_dm_connector *amdgpu_dm_connector =
10220                         to_amdgpu_dm_connector(connector);
10221         struct dm_connector_state *dm_con_state = NULL;
10222         struct dc_sink *sink;
10223
10224         struct drm_device *dev = connector->dev;
10225         struct amdgpu_device *adev = drm_to_adev(dev);
10226         struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10227         bool freesync_capable = false;
10228
10229         if (!connector->state) {
10230                 DRM_ERROR("%s - Connector has no state", __func__);
10231                 goto update;
10232         }
10233
10234         sink = amdgpu_dm_connector->dc_sink ?
10235                 amdgpu_dm_connector->dc_sink :
10236                 amdgpu_dm_connector->dc_em_sink;
10237
10238         if (!edid || !sink) {
10239                 dm_con_state = to_dm_connector_state(connector->state);
10240
10241                 amdgpu_dm_connector->min_vfreq = 0;
10242                 amdgpu_dm_connector->max_vfreq = 0;
10243                 amdgpu_dm_connector->pixel_clock_mhz = 0;
10244                 connector->display_info.monitor_range.min_vfreq = 0;
10245                 connector->display_info.monitor_range.max_vfreq = 0;
10246                 freesync_capable = false;
10247
10248                 goto update;
10249         }
10250
10251         dm_con_state = to_dm_connector_state(connector->state);
10252
10253         if (!adev->dm.freesync_module)
10254                 goto update;
10255
10256         if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10257                 || sink->sink_signal == SIGNAL_TYPE_EDP) {
10258                 bool edid_check_required = false;
10259
10260                 if (edid) {
10261                         edid_check_required = is_dp_capable_without_timing_msa(
10262                                                 adev->dm.dc,
10263                                                 amdgpu_dm_connector);
10264                 }
10265
10266                 if (edid_check_required == true && (edid->version > 1 ||
10267                    (edid->version == 1 && edid->revision > 1))) {
10268                         for (i = 0; i < 4; i++) {
10269
10270                                 timing  = &edid->detailed_timings[i];
10271                                 data    = &timing->data.other_data;
10272                                 range   = &data->data.range;
10273                                 /*
10274                                  * Check if monitor has continuous frequency mode
10275                                  */
10276                                 if (data->type != EDID_DETAIL_MONITOR_RANGE)
10277                                         continue;
10278                                 /*
10279                                  * Check for flag range limits only. If flag == 1 then
10280                                  * no additional timing information provided.
10281                                  * Default GTF, GTF Secondary curve and CVT are not
10282                                  * supported
10283                                  */
10284                                 if (range->flags != 1)
10285                                         continue;
10286
10287                                 amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10288                                 amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10289                                 amdgpu_dm_connector->pixel_clock_mhz =
10290                                         range->pixel_clock_mhz * 10;
10291
10292                                 connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10293                                 connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10294
10295                                 break;
10296                         }
10297
10298                         if (amdgpu_dm_connector->max_vfreq -
10299                             amdgpu_dm_connector->min_vfreq > 10) {
10300
10301                                 freesync_capable = true;
10302                         }
10303                 }
10304         } else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10305                 i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10306                 if (i >= 0 && vsdb_info.freesync_supported) {
10307                         timing  = &edid->detailed_timings[i];
10308                         data    = &timing->data.other_data;
10309
10310                         amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10311                         amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10312                         if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10313                                 freesync_capable = true;
10314
10315                         connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10316                         connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10317                 }
10318         }
10319
10320 update:
10321         if (dm_con_state)
10322                 dm_con_state->freesync_capable = freesync_capable;
10323
10324         if (connector->vrr_capable_property)
10325                 drm_connector_set_vrr_capable_property(connector,
10326                                                        freesync_capable);
10327 }
10328
10329 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10330 {
10331         struct amdgpu_device *adev = drm_to_adev(dev);
10332         struct dc *dc = adev->dm.dc;
10333         int i;
10334
10335         mutex_lock(&adev->dm.dc_lock);
10336         if (dc->current_state) {
10337                 for (i = 0; i < dc->current_state->stream_count; ++i)
10338                         dc->current_state->streams[i]
10339                                 ->triggered_crtc_reset.enabled =
10340                                 adev->dm.force_timing_sync;
10341
10342                 dm_enable_per_frame_crtc_master_sync(dc->current_state);
10343                 dc_trigger_sync(dc, dc->current_state);
10344         }
10345         mutex_unlock(&adev->dm.dc_lock);
10346 }
10347
10348 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10349                        u32 value, const char *func_name)
10350 {
10351 #ifdef DM_CHECK_ADDR_0
10352         if (address == 0) {
10353                 DC_ERR("invalid register write. address = 0");
10354                 return;
10355         }
10356 #endif
10357         cgs_write_register(ctx->cgs_device, address, value);
10358         trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10359 }
10360
10361 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10362                           const char *func_name)
10363 {
10364         u32 value;
10365 #ifdef DM_CHECK_ADDR_0
10366         if (address == 0) {
10367                 DC_ERR("invalid register read; address = 0\n");
10368                 return 0;
10369         }
10370 #endif
10371
10372         if (ctx->dmub_srv &&
10373             ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10374             !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10375                 ASSERT(false);
10376                 return 0;
10377         }
10378
10379         value = cgs_read_register(ctx->cgs_device, address);
10380
10381         trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10382
10383         return value;
10384 }
10385
10386 int amdgpu_dm_process_dmub_aux_transfer_sync(
10387                 struct dc_context *ctx,
10388                 unsigned int link_index,
10389                 struct aux_payload *payload,
10390                 enum aux_return_code_type *operation_result)
10391 {
10392         struct amdgpu_device *adev = ctx->driver_context;
10393         struct dmub_notification *p_notify = adev->dm.dmub_notify;
10394         int ret = -1;
10395
10396         mutex_lock(&adev->dm.dpia_aux_lock);
10397         if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
10398                 *operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10399                 goto out;
10400         }
10401
10402         if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10403                 DRM_ERROR("wait_for_completion_timeout timeout!");
10404                 *operation_result = AUX_RET_ERROR_TIMEOUT;
10405                 goto out;
10406         }
10407
10408         if (p_notify->result != AUX_RET_SUCCESS) {
10409                 /*
10410                  * Transient states before tunneling is enabled could
10411                  * lead to this error. We can ignore this for now.
10412                  */
10413                 if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
10414                         DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
10415                                         payload->address, payload->length,
10416                                         p_notify->result);
10417                 }
10418                 *operation_result = AUX_RET_ERROR_INVALID_REPLY;
10419                 goto out;
10420         }
10421
10422
10423         payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10424         if (!payload->write && p_notify->aux_reply.length &&
10425                         (payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
10426
10427                 if (payload->length != p_notify->aux_reply.length) {
10428                         DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
10429                                 p_notify->aux_reply.length,
10430                                         payload->address, payload->length);
10431                         *operation_result = AUX_RET_ERROR_INVALID_REPLY;
10432                         goto out;
10433                 }
10434
10435                 memcpy(payload->data, p_notify->aux_reply.data,
10436                                 p_notify->aux_reply.length);
10437         }
10438
10439         /* success */
10440         ret = p_notify->aux_reply.length;
10441         *operation_result = p_notify->result;
10442 out:
10443         mutex_unlock(&adev->dm.dpia_aux_lock);
10444         return ret;
10445 }
10446
10447 int amdgpu_dm_process_dmub_set_config_sync(
10448                 struct dc_context *ctx,
10449                 unsigned int link_index,
10450                 struct set_config_cmd_payload *payload,
10451                 enum set_config_status *operation_result)
10452 {
10453         struct amdgpu_device *adev = ctx->driver_context;
10454         bool is_cmd_complete;
10455         int ret;
10456
10457         mutex_lock(&adev->dm.dpia_aux_lock);
10458         is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
10459                         link_index, payload, adev->dm.dmub_notify);
10460
10461         if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10462                 ret = 0;
10463                 *operation_result = adev->dm.dmub_notify->sc_status;
10464         } else {
10465                 DRM_ERROR("wait_for_completion_timeout timeout!");
10466                 ret = -1;
10467                 *operation_result = SET_CONFIG_UNKNOWN_ERROR;
10468         }
10469
10470         mutex_unlock(&adev->dm.dpia_aux_lock);
10471         return ret;
10472 }
10473
10474 /*
10475  * Check whether seamless boot is supported.
10476  *
10477  * So far we only support seamless boot on CHIP_VANGOGH.
10478  * If everything goes well, we may consider expanding
10479  * seamless boot to other ASICs.
10480  */
10481 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10482 {
10483         switch (adev->ip_versions[DCE_HWIP][0]) {
10484         case IP_VERSION(3, 0, 1):
10485                 if (!adev->mman.keep_stolen_vga_memory)
10486                         return true;
10487                 break;
10488         default:
10489                 break;
10490         }
10491
10492         return false;
10493 }
This page took 0.702256 seconds and 4 git commands to generate.