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