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