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