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