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