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