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