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