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  * @dirty_regions_changed: dirty regions changed
5048  *
5049  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
5050  * (referred to as "damage clips" in DRM nomenclature) that require updating on
5051  * the eDP remote buffer. The responsibility of specifying the dirty regions is
5052  * amdgpu_dm's.
5053  *
5054  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
5055  * plane with regions that require flushing to the eDP remote buffer. In
5056  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
5057  * implicitly provide damage clips without any client support via the plane
5058  * bounds.
5059  */
5060 static void fill_dc_dirty_rects(struct drm_plane *plane,
5061 				struct drm_plane_state *old_plane_state,
5062 				struct drm_plane_state *new_plane_state,
5063 				struct drm_crtc_state *crtc_state,
5064 				struct dc_flip_addrs *flip_addrs,
5065 				bool *dirty_regions_changed)
5066 {
5067 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
5068 	struct rect *dirty_rects = flip_addrs->dirty_rects;
5069 	u32 num_clips;
5070 	struct drm_mode_rect *clips;
5071 	bool bb_changed;
5072 	bool fb_changed;
5073 	u32 i = 0;
5074 	*dirty_regions_changed = false;
5075 
5076 	/*
5077 	 * Cursor plane has it's own dirty rect update interface. See
5078 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
5079 	 */
5080 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
5081 		return;
5082 
5083 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
5084 	clips = drm_plane_get_damage_clips(new_plane_state);
5085 
5086 	if (!dm_crtc_state->mpo_requested) {
5087 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
5088 			goto ffu;
5089 
5090 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
5091 			fill_dc_dirty_rect(new_plane_state->plane,
5092 					   &dirty_rects[i], clips->x1,
5093 					   clips->y1, clips->x2 - clips->x1,
5094 					   clips->y2 - clips->y1,
5095 					   &flip_addrs->dirty_rect_count,
5096 					   false);
5097 		return;
5098 	}
5099 
5100 	/*
5101 	 * MPO is requested. Add entire plane bounding box to dirty rects if
5102 	 * flipped to or damaged.
5103 	 *
5104 	 * If plane is moved or resized, also add old bounding box to dirty
5105 	 * rects.
5106 	 */
5107 	fb_changed = old_plane_state->fb->base.id !=
5108 		     new_plane_state->fb->base.id;
5109 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
5110 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
5111 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
5112 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
5113 
5114 	drm_dbg(plane->dev,
5115 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
5116 		new_plane_state->plane->base.id,
5117 		bb_changed, fb_changed, num_clips);
5118 
5119 	*dirty_regions_changed = bb_changed;
5120 
5121 	if (bb_changed) {
5122 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5123 				   new_plane_state->crtc_x,
5124 				   new_plane_state->crtc_y,
5125 				   new_plane_state->crtc_w,
5126 				   new_plane_state->crtc_h, &i, false);
5127 
5128 		/* Add old plane bounding-box if plane is moved or resized */
5129 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5130 				   old_plane_state->crtc_x,
5131 				   old_plane_state->crtc_y,
5132 				   old_plane_state->crtc_w,
5133 				   old_plane_state->crtc_h, &i, false);
5134 	}
5135 
5136 	if (num_clips) {
5137 		for (; i < num_clips; clips++)
5138 			fill_dc_dirty_rect(new_plane_state->plane,
5139 					   &dirty_rects[i], clips->x1,
5140 					   clips->y1, clips->x2 - clips->x1,
5141 					   clips->y2 - clips->y1, &i, false);
5142 	} else if (fb_changed && !bb_changed) {
5143 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5144 				   new_plane_state->crtc_x,
5145 				   new_plane_state->crtc_y,
5146 				   new_plane_state->crtc_w,
5147 				   new_plane_state->crtc_h, &i, false);
5148 	}
5149 
5150 	if (i > DC_MAX_DIRTY_RECTS)
5151 		goto ffu;
5152 
5153 	flip_addrs->dirty_rect_count = i;
5154 	return;
5155 
5156 ffu:
5157 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
5158 			   dm_crtc_state->base.mode.crtc_hdisplay,
5159 			   dm_crtc_state->base.mode.crtc_vdisplay,
5160 			   &flip_addrs->dirty_rect_count, true);
5161 }
5162 
5163 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
5164 					   const struct dm_connector_state *dm_state,
5165 					   struct dc_stream_state *stream)
5166 {
5167 	enum amdgpu_rmx_type rmx_type;
5168 
5169 	struct rect src = { 0 }; /* viewport in composition space*/
5170 	struct rect dst = { 0 }; /* stream addressable area */
5171 
5172 	/* no mode. nothing to be done */
5173 	if (!mode)
5174 		return;
5175 
5176 	/* Full screen scaling by default */
5177 	src.width = mode->hdisplay;
5178 	src.height = mode->vdisplay;
5179 	dst.width = stream->timing.h_addressable;
5180 	dst.height = stream->timing.v_addressable;
5181 
5182 	if (dm_state) {
5183 		rmx_type = dm_state->scaling;
5184 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5185 			if (src.width * dst.height <
5186 					src.height * dst.width) {
5187 				/* height needs less upscaling/more downscaling */
5188 				dst.width = src.width *
5189 						dst.height / src.height;
5190 			} else {
5191 				/* width needs less upscaling/more downscaling */
5192 				dst.height = src.height *
5193 						dst.width / src.width;
5194 			}
5195 		} else if (rmx_type == RMX_CENTER) {
5196 			dst = src;
5197 		}
5198 
5199 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
5200 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
5201 
5202 		if (dm_state->underscan_enable) {
5203 			dst.x += dm_state->underscan_hborder / 2;
5204 			dst.y += dm_state->underscan_vborder / 2;
5205 			dst.width -= dm_state->underscan_hborder;
5206 			dst.height -= dm_state->underscan_vborder;
5207 		}
5208 	}
5209 
5210 	stream->src = src;
5211 	stream->dst = dst;
5212 
5213 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5214 		      dst.x, dst.y, dst.width, dst.height);
5215 
5216 }
5217 
5218 static enum dc_color_depth
5219 convert_color_depth_from_display_info(const struct drm_connector *connector,
5220 				      bool is_y420, int requested_bpc)
5221 {
5222 	u8 bpc;
5223 
5224 	if (is_y420) {
5225 		bpc = 8;
5226 
5227 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
5228 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5229 			bpc = 16;
5230 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5231 			bpc = 12;
5232 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5233 			bpc = 10;
5234 	} else {
5235 		bpc = (uint8_t)connector->display_info.bpc;
5236 		/* Assume 8 bpc by default if no bpc is specified. */
5237 		bpc = bpc ? bpc : 8;
5238 	}
5239 
5240 	if (requested_bpc > 0) {
5241 		/*
5242 		 * Cap display bpc based on the user requested value.
5243 		 *
5244 		 * The value for state->max_bpc may not correctly updated
5245 		 * depending on when the connector gets added to the state
5246 		 * or if this was called outside of atomic check, so it
5247 		 * can't be used directly.
5248 		 */
5249 		bpc = min_t(u8, bpc, requested_bpc);
5250 
5251 		/* Round down to the nearest even number. */
5252 		bpc = bpc - (bpc & 1);
5253 	}
5254 
5255 	switch (bpc) {
5256 	case 0:
5257 		/*
5258 		 * Temporary Work around, DRM doesn't parse color depth for
5259 		 * EDID revision before 1.4
5260 		 * TODO: Fix edid parsing
5261 		 */
5262 		return COLOR_DEPTH_888;
5263 	case 6:
5264 		return COLOR_DEPTH_666;
5265 	case 8:
5266 		return COLOR_DEPTH_888;
5267 	case 10:
5268 		return COLOR_DEPTH_101010;
5269 	case 12:
5270 		return COLOR_DEPTH_121212;
5271 	case 14:
5272 		return COLOR_DEPTH_141414;
5273 	case 16:
5274 		return COLOR_DEPTH_161616;
5275 	default:
5276 		return COLOR_DEPTH_UNDEFINED;
5277 	}
5278 }
5279 
5280 static enum dc_aspect_ratio
5281 get_aspect_ratio(const struct drm_display_mode *mode_in)
5282 {
5283 	/* 1-1 mapping, since both enums follow the HDMI spec. */
5284 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5285 }
5286 
5287 static enum dc_color_space
5288 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5289 {
5290 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
5291 
5292 	switch (dc_crtc_timing->pixel_encoding)	{
5293 	case PIXEL_ENCODING_YCBCR422:
5294 	case PIXEL_ENCODING_YCBCR444:
5295 	case PIXEL_ENCODING_YCBCR420:
5296 	{
5297 		/*
5298 		 * 27030khz is the separation point between HDTV and SDTV
5299 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
5300 		 * respectively
5301 		 */
5302 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
5303 			if (dc_crtc_timing->flags.Y_ONLY)
5304 				color_space =
5305 					COLOR_SPACE_YCBCR709_LIMITED;
5306 			else
5307 				color_space = COLOR_SPACE_YCBCR709;
5308 		} else {
5309 			if (dc_crtc_timing->flags.Y_ONLY)
5310 				color_space =
5311 					COLOR_SPACE_YCBCR601_LIMITED;
5312 			else
5313 				color_space = COLOR_SPACE_YCBCR601;
5314 		}
5315 
5316 	}
5317 	break;
5318 	case PIXEL_ENCODING_RGB:
5319 		color_space = COLOR_SPACE_SRGB;
5320 		break;
5321 
5322 	default:
5323 		WARN_ON(1);
5324 		break;
5325 	}
5326 
5327 	return color_space;
5328 }
5329 
5330 static bool adjust_colour_depth_from_display_info(
5331 	struct dc_crtc_timing *timing_out,
5332 	const struct drm_display_info *info)
5333 {
5334 	enum dc_color_depth depth = timing_out->display_color_depth;
5335 	int normalized_clk;
5336 	do {
5337 		normalized_clk = timing_out->pix_clk_100hz / 10;
5338 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5339 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5340 			normalized_clk /= 2;
5341 		/* Adjusting pix clock following on HDMI spec based on colour depth */
5342 		switch (depth) {
5343 		case COLOR_DEPTH_888:
5344 			break;
5345 		case COLOR_DEPTH_101010:
5346 			normalized_clk = (normalized_clk * 30) / 24;
5347 			break;
5348 		case COLOR_DEPTH_121212:
5349 			normalized_clk = (normalized_clk * 36) / 24;
5350 			break;
5351 		case COLOR_DEPTH_161616:
5352 			normalized_clk = (normalized_clk * 48) / 24;
5353 			break;
5354 		default:
5355 			/* The above depths are the only ones valid for HDMI. */
5356 			return false;
5357 		}
5358 		if (normalized_clk <= info->max_tmds_clock) {
5359 			timing_out->display_color_depth = depth;
5360 			return true;
5361 		}
5362 	} while (--depth > COLOR_DEPTH_666);
5363 	return false;
5364 }
5365 
5366 static void fill_stream_properties_from_drm_display_mode(
5367 	struct dc_stream_state *stream,
5368 	const struct drm_display_mode *mode_in,
5369 	const struct drm_connector *connector,
5370 	const struct drm_connector_state *connector_state,
5371 	const struct dc_stream_state *old_stream,
5372 	int requested_bpc)
5373 {
5374 	struct dc_crtc_timing *timing_out = &stream->timing;
5375 	const struct drm_display_info *info = &connector->display_info;
5376 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5377 	struct hdmi_vendor_infoframe hv_frame;
5378 	struct hdmi_avi_infoframe avi_frame;
5379 
5380 	memset(&hv_frame, 0, sizeof(hv_frame));
5381 	memset(&avi_frame, 0, sizeof(avi_frame));
5382 
5383 	timing_out->h_border_left = 0;
5384 	timing_out->h_border_right = 0;
5385 	timing_out->v_border_top = 0;
5386 	timing_out->v_border_bottom = 0;
5387 	/* TODO: un-hardcode */
5388 	if (drm_mode_is_420_only(info, mode_in)
5389 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5390 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5391 	else if (drm_mode_is_420_also(info, mode_in)
5392 			&& aconnector->force_yuv420_output)
5393 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5394 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5395 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5396 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5397 	else
5398 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5399 
5400 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5401 	timing_out->display_color_depth = convert_color_depth_from_display_info(
5402 		connector,
5403 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5404 		requested_bpc);
5405 	timing_out->scan_type = SCANNING_TYPE_NODATA;
5406 	timing_out->hdmi_vic = 0;
5407 
5408 	if (old_stream) {
5409 		timing_out->vic = old_stream->timing.vic;
5410 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5411 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5412 	} else {
5413 		timing_out->vic = drm_match_cea_mode(mode_in);
5414 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5415 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5416 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5417 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5418 	}
5419 
5420 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5421 		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5422 		timing_out->vic = avi_frame.video_code;
5423 		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5424 		timing_out->hdmi_vic = hv_frame.vic;
5425 	}
5426 
5427 	if (is_freesync_video_mode(mode_in, aconnector)) {
5428 		timing_out->h_addressable = mode_in->hdisplay;
5429 		timing_out->h_total = mode_in->htotal;
5430 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5431 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5432 		timing_out->v_total = mode_in->vtotal;
5433 		timing_out->v_addressable = mode_in->vdisplay;
5434 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5435 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5436 		timing_out->pix_clk_100hz = mode_in->clock * 10;
5437 	} else {
5438 		timing_out->h_addressable = mode_in->crtc_hdisplay;
5439 		timing_out->h_total = mode_in->crtc_htotal;
5440 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5441 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5442 		timing_out->v_total = mode_in->crtc_vtotal;
5443 		timing_out->v_addressable = mode_in->crtc_vdisplay;
5444 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5445 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5446 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5447 	}
5448 
5449 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5450 
5451 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5452 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5453 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5454 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5455 		    drm_mode_is_420_also(info, mode_in) &&
5456 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5457 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5458 			adjust_colour_depth_from_display_info(timing_out, info);
5459 		}
5460 	}
5461 
5462 	stream->output_color_space = get_output_color_space(timing_out);
5463 }
5464 
5465 static void fill_audio_info(struct audio_info *audio_info,
5466 			    const struct drm_connector *drm_connector,
5467 			    const struct dc_sink *dc_sink)
5468 {
5469 	int i = 0;
5470 	int cea_revision = 0;
5471 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5472 
5473 	audio_info->manufacture_id = edid_caps->manufacturer_id;
5474 	audio_info->product_id = edid_caps->product_id;
5475 
5476 	cea_revision = drm_connector->display_info.cea_rev;
5477 
5478 	strscpy(audio_info->display_name,
5479 		edid_caps->display_name,
5480 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5481 
5482 	if (cea_revision >= 3) {
5483 		audio_info->mode_count = edid_caps->audio_mode_count;
5484 
5485 		for (i = 0; i < audio_info->mode_count; ++i) {
5486 			audio_info->modes[i].format_code =
5487 					(enum audio_format_code)
5488 					(edid_caps->audio_modes[i].format_code);
5489 			audio_info->modes[i].channel_count =
5490 					edid_caps->audio_modes[i].channel_count;
5491 			audio_info->modes[i].sample_rates.all =
5492 					edid_caps->audio_modes[i].sample_rate;
5493 			audio_info->modes[i].sample_size =
5494 					edid_caps->audio_modes[i].sample_size;
5495 		}
5496 	}
5497 
5498 	audio_info->flags.all = edid_caps->speaker_flags;
5499 
5500 	/* TODO: We only check for the progressive mode, check for interlace mode too */
5501 	if (drm_connector->latency_present[0]) {
5502 		audio_info->video_latency = drm_connector->video_latency[0];
5503 		audio_info->audio_latency = drm_connector->audio_latency[0];
5504 	}
5505 
5506 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5507 
5508 }
5509 
5510 static void
5511 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5512 				      struct drm_display_mode *dst_mode)
5513 {
5514 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5515 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5516 	dst_mode->crtc_clock = src_mode->crtc_clock;
5517 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5518 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5519 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5520 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5521 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
5522 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
5523 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5524 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5525 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5526 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5527 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5528 }
5529 
5530 static void
5531 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5532 					const struct drm_display_mode *native_mode,
5533 					bool scale_enabled)
5534 {
5535 	if (scale_enabled) {
5536 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5537 	} else if (native_mode->clock == drm_mode->clock &&
5538 			native_mode->htotal == drm_mode->htotal &&
5539 			native_mode->vtotal == drm_mode->vtotal) {
5540 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5541 	} else {
5542 		/* no scaling nor amdgpu inserted, no need to patch */
5543 	}
5544 }
5545 
5546 static struct dc_sink *
5547 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5548 {
5549 	struct dc_sink_init_data sink_init_data = { 0 };
5550 	struct dc_sink *sink = NULL;
5551 	sink_init_data.link = aconnector->dc_link;
5552 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5553 
5554 	sink = dc_sink_create(&sink_init_data);
5555 	if (!sink) {
5556 		DRM_ERROR("Failed to create sink!\n");
5557 		return NULL;
5558 	}
5559 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5560 
5561 	return sink;
5562 }
5563 
5564 static void set_multisync_trigger_params(
5565 		struct dc_stream_state *stream)
5566 {
5567 	struct dc_stream_state *master = NULL;
5568 
5569 	if (stream->triggered_crtc_reset.enabled) {
5570 		master = stream->triggered_crtc_reset.event_source;
5571 		stream->triggered_crtc_reset.event =
5572 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5573 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5574 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5575 	}
5576 }
5577 
5578 static void set_master_stream(struct dc_stream_state *stream_set[],
5579 			      int stream_count)
5580 {
5581 	int j, highest_rfr = 0, master_stream = 0;
5582 
5583 	for (j = 0;  j < stream_count; j++) {
5584 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5585 			int refresh_rate = 0;
5586 
5587 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5588 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5589 			if (refresh_rate > highest_rfr) {
5590 				highest_rfr = refresh_rate;
5591 				master_stream = j;
5592 			}
5593 		}
5594 	}
5595 	for (j = 0;  j < stream_count; j++) {
5596 		if (stream_set[j])
5597 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5598 	}
5599 }
5600 
5601 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5602 {
5603 	int i = 0;
5604 	struct dc_stream_state *stream;
5605 
5606 	if (context->stream_count < 2)
5607 		return;
5608 	for (i = 0; i < context->stream_count ; i++) {
5609 		if (!context->streams[i])
5610 			continue;
5611 		/*
5612 		 * TODO: add a function to read AMD VSDB bits and set
5613 		 * crtc_sync_master.multi_sync_enabled flag
5614 		 * For now it's set to false
5615 		 */
5616 	}
5617 
5618 	set_master_stream(context->streams, context->stream_count);
5619 
5620 	for (i = 0; i < context->stream_count ; i++) {
5621 		stream = context->streams[i];
5622 
5623 		if (!stream)
5624 			continue;
5625 
5626 		set_multisync_trigger_params(stream);
5627 	}
5628 }
5629 
5630 /**
5631  * DOC: FreeSync Video
5632  *
5633  * When a userspace application wants to play a video, the content follows a
5634  * standard format definition that usually specifies the FPS for that format.
5635  * The below list illustrates some video format and the expected FPS,
5636  * respectively:
5637  *
5638  * - TV/NTSC (23.976 FPS)
5639  * - Cinema (24 FPS)
5640  * - TV/PAL (25 FPS)
5641  * - TV/NTSC (29.97 FPS)
5642  * - TV/NTSC (30 FPS)
5643  * - Cinema HFR (48 FPS)
5644  * - TV/PAL (50 FPS)
5645  * - Commonly used (60 FPS)
5646  * - Multiples of 24 (48,72,96 FPS)
5647  *
5648  * The list of standards video format is not huge and can be added to the
5649  * connector modeset list beforehand. With that, userspace can leverage
5650  * FreeSync to extends the front porch in order to attain the target refresh
5651  * rate. Such a switch will happen seamlessly, without screen blanking or
5652  * reprogramming of the output in any other way. If the userspace requests a
5653  * modesetting change compatible with FreeSync modes that only differ in the
5654  * refresh rate, DC will skip the full update and avoid blink during the
5655  * transition. For example, the video player can change the modesetting from
5656  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5657  * causing any display blink. This same concept can be applied to a mode
5658  * setting change.
5659  */
5660 static struct drm_display_mode *
5661 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5662 		bool use_probed_modes)
5663 {
5664 	struct drm_display_mode *m, *m_pref = NULL;
5665 	u16 current_refresh, highest_refresh;
5666 	struct list_head *list_head = use_probed_modes ?
5667 		&aconnector->base.probed_modes :
5668 		&aconnector->base.modes;
5669 
5670 	if (aconnector->freesync_vid_base.clock != 0)
5671 		return &aconnector->freesync_vid_base;
5672 
5673 	/* Find the preferred mode */
5674 	list_for_each_entry (m, list_head, head) {
5675 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
5676 			m_pref = m;
5677 			break;
5678 		}
5679 	}
5680 
5681 	if (!m_pref) {
5682 		/* Probably an EDID with no preferred mode. Fallback to first entry */
5683 		m_pref = list_first_entry_or_null(
5684 				&aconnector->base.modes, struct drm_display_mode, head);
5685 		if (!m_pref) {
5686 			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5687 			return NULL;
5688 		}
5689 	}
5690 
5691 	highest_refresh = drm_mode_vrefresh(m_pref);
5692 
5693 	/*
5694 	 * Find the mode with highest refresh rate with same resolution.
5695 	 * For some monitors, preferred mode is not the mode with highest
5696 	 * supported refresh rate.
5697 	 */
5698 	list_for_each_entry (m, list_head, head) {
5699 		current_refresh  = drm_mode_vrefresh(m);
5700 
5701 		if (m->hdisplay == m_pref->hdisplay &&
5702 		    m->vdisplay == m_pref->vdisplay &&
5703 		    highest_refresh < current_refresh) {
5704 			highest_refresh = current_refresh;
5705 			m_pref = m;
5706 		}
5707 	}
5708 
5709 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5710 	return m_pref;
5711 }
5712 
5713 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5714 		struct amdgpu_dm_connector *aconnector)
5715 {
5716 	struct drm_display_mode *high_mode;
5717 	int timing_diff;
5718 
5719 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
5720 	if (!high_mode || !mode)
5721 		return false;
5722 
5723 	timing_diff = high_mode->vtotal - mode->vtotal;
5724 
5725 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5726 	    high_mode->hdisplay != mode->hdisplay ||
5727 	    high_mode->vdisplay != mode->vdisplay ||
5728 	    high_mode->hsync_start != mode->hsync_start ||
5729 	    high_mode->hsync_end != mode->hsync_end ||
5730 	    high_mode->htotal != mode->htotal ||
5731 	    high_mode->hskew != mode->hskew ||
5732 	    high_mode->vscan != mode->vscan ||
5733 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
5734 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
5735 		return false;
5736 	else
5737 		return true;
5738 }
5739 
5740 #if defined(CONFIG_DRM_AMD_DC_DCN)
5741 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5742 			    struct dc_sink *sink, struct dc_stream_state *stream,
5743 			    struct dsc_dec_dpcd_caps *dsc_caps)
5744 {
5745 	stream->timing.flags.DSC = 0;
5746 	dsc_caps->is_dsc_supported = false;
5747 
5748 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5749 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
5750 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5751 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5752 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5753 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5754 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5755 				dsc_caps);
5756 	}
5757 }
5758 
5759 
5760 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5761 				    struct dc_sink *sink, struct dc_stream_state *stream,
5762 				    struct dsc_dec_dpcd_caps *dsc_caps,
5763 				    uint32_t max_dsc_target_bpp_limit_override)
5764 {
5765 	const struct dc_link_settings *verified_link_cap = NULL;
5766 	u32 link_bw_in_kbps;
5767 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
5768 	struct dc *dc = sink->ctx->dc;
5769 	struct dc_dsc_bw_range bw_range = {0};
5770 	struct dc_dsc_config dsc_cfg = {0};
5771 
5772 	verified_link_cap = dc_link_get_link_cap(stream->link);
5773 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5774 	edp_min_bpp_x16 = 8 * 16;
5775 	edp_max_bpp_x16 = 8 * 16;
5776 
5777 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5778 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5779 
5780 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
5781 		edp_min_bpp_x16 = edp_max_bpp_x16;
5782 
5783 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5784 				dc->debug.dsc_min_slice_height_override,
5785 				edp_min_bpp_x16, edp_max_bpp_x16,
5786 				dsc_caps,
5787 				&stream->timing,
5788 				&bw_range)) {
5789 
5790 		if (bw_range.max_kbps < link_bw_in_kbps) {
5791 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5792 					dsc_caps,
5793 					dc->debug.dsc_min_slice_height_override,
5794 					max_dsc_target_bpp_limit_override,
5795 					0,
5796 					&stream->timing,
5797 					&dsc_cfg)) {
5798 				stream->timing.dsc_cfg = dsc_cfg;
5799 				stream->timing.flags.DSC = 1;
5800 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5801 			}
5802 			return;
5803 		}
5804 	}
5805 
5806 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5807 				dsc_caps,
5808 				dc->debug.dsc_min_slice_height_override,
5809 				max_dsc_target_bpp_limit_override,
5810 				link_bw_in_kbps,
5811 				&stream->timing,
5812 				&dsc_cfg)) {
5813 		stream->timing.dsc_cfg = dsc_cfg;
5814 		stream->timing.flags.DSC = 1;
5815 	}
5816 }
5817 
5818 
5819 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5820 					struct dc_sink *sink, struct dc_stream_state *stream,
5821 					struct dsc_dec_dpcd_caps *dsc_caps)
5822 {
5823 	struct drm_connector *drm_connector = &aconnector->base;
5824 	u32 link_bandwidth_kbps;
5825 	struct dc *dc = sink->ctx->dc;
5826 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
5827 	u32 dsc_max_supported_bw_in_kbps;
5828 	u32 max_dsc_target_bpp_limit_override =
5829 		drm_connector->display_info.max_dsc_bpp;
5830 
5831 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5832 							dc_link_get_link_cap(aconnector->dc_link));
5833 
5834 	/* Set DSC policy according to dsc_clock_en */
5835 	dc_dsc_policy_set_enable_dsc_when_not_needed(
5836 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5837 
5838 	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5839 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5840 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5841 
5842 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5843 
5844 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5845 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5846 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5847 						dsc_caps,
5848 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5849 						max_dsc_target_bpp_limit_override,
5850 						link_bandwidth_kbps,
5851 						&stream->timing,
5852 						&stream->timing.dsc_cfg)) {
5853 				stream->timing.flags.DSC = 1;
5854 				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5855 			}
5856 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5857 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5858 			max_supported_bw_in_kbps = link_bandwidth_kbps;
5859 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5860 
5861 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5862 					max_supported_bw_in_kbps > 0 &&
5863 					dsc_max_supported_bw_in_kbps > 0)
5864 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5865 						dsc_caps,
5866 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5867 						max_dsc_target_bpp_limit_override,
5868 						dsc_max_supported_bw_in_kbps,
5869 						&stream->timing,
5870 						&stream->timing.dsc_cfg)) {
5871 					stream->timing.flags.DSC = 1;
5872 					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5873 									 __func__, drm_connector->name);
5874 				}
5875 		}
5876 	}
5877 
5878 	/* Overwrite the stream flag if DSC is enabled through debugfs */
5879 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5880 		stream->timing.flags.DSC = 1;
5881 
5882 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5883 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5884 
5885 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5886 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5887 
5888 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5889 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5890 }
5891 #endif /* CONFIG_DRM_AMD_DC_DCN */
5892 
5893 static struct dc_stream_state *
5894 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5895 		       const struct drm_display_mode *drm_mode,
5896 		       const struct dm_connector_state *dm_state,
5897 		       const struct dc_stream_state *old_stream,
5898 		       int requested_bpc)
5899 {
5900 	struct drm_display_mode *preferred_mode = NULL;
5901 	struct drm_connector *drm_connector;
5902 	const struct drm_connector_state *con_state =
5903 		dm_state ? &dm_state->base : NULL;
5904 	struct dc_stream_state *stream = NULL;
5905 	struct drm_display_mode mode;
5906 	struct drm_display_mode saved_mode;
5907 	struct drm_display_mode *freesync_mode = NULL;
5908 	bool native_mode_found = false;
5909 	bool recalculate_timing = false;
5910 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5911 	int mode_refresh;
5912 	int preferred_refresh = 0;
5913 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
5914 #if defined(CONFIG_DRM_AMD_DC_DCN)
5915 	struct dsc_dec_dpcd_caps dsc_caps;
5916 #endif
5917 
5918 	struct dc_sink *sink = NULL;
5919 
5920 	drm_mode_init(&mode, drm_mode);
5921 	memset(&saved_mode, 0, sizeof(saved_mode));
5922 
5923 	if (aconnector == NULL) {
5924 		DRM_ERROR("aconnector is NULL!\n");
5925 		return stream;
5926 	}
5927 
5928 	drm_connector = &aconnector->base;
5929 
5930 	if (!aconnector->dc_sink) {
5931 		sink = create_fake_sink(aconnector);
5932 		if (!sink)
5933 			return stream;
5934 	} else {
5935 		sink = aconnector->dc_sink;
5936 		dc_sink_retain(sink);
5937 	}
5938 
5939 	stream = dc_create_stream_for_sink(sink);
5940 
5941 	if (stream == NULL) {
5942 		DRM_ERROR("Failed to create stream for sink!\n");
5943 		goto finish;
5944 	}
5945 
5946 	stream->dm_stream_context = aconnector;
5947 
5948 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5949 		drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5950 
5951 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5952 		/* Search for preferred mode */
5953 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5954 			native_mode_found = true;
5955 			break;
5956 		}
5957 	}
5958 	if (!native_mode_found)
5959 		preferred_mode = list_first_entry_or_null(
5960 				&aconnector->base.modes,
5961 				struct drm_display_mode,
5962 				head);
5963 
5964 	mode_refresh = drm_mode_vrefresh(&mode);
5965 
5966 	if (preferred_mode == NULL) {
5967 		/*
5968 		 * This may not be an error, the use case is when we have no
5969 		 * usermode calls to reset and set mode upon hotplug. In this
5970 		 * case, we call set mode ourselves to restore the previous mode
5971 		 * and the modelist may not be filled in in time.
5972 		 */
5973 		DRM_DEBUG_DRIVER("No preferred mode found\n");
5974 	} else {
5975 		recalculate_timing = amdgpu_freesync_vid_mode &&
5976 				 is_freesync_video_mode(&mode, aconnector);
5977 		if (recalculate_timing) {
5978 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5979 			drm_mode_copy(&saved_mode, &mode);
5980 			drm_mode_copy(&mode, freesync_mode);
5981 		} else {
5982 			decide_crtc_timing_for_drm_display_mode(
5983 					&mode, preferred_mode, scale);
5984 
5985 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
5986 		}
5987 	}
5988 
5989 	if (recalculate_timing)
5990 		drm_mode_set_crtcinfo(&saved_mode, 0);
5991 	else if (!dm_state)
5992 		drm_mode_set_crtcinfo(&mode, 0);
5993 
5994 	/*
5995 	* If scaling is enabled and refresh rate didn't change
5996 	* we copy the vic and polarities of the old timings
5997 	*/
5998 	if (!scale || mode_refresh != preferred_refresh)
5999 		fill_stream_properties_from_drm_display_mode(
6000 			stream, &mode, &aconnector->base, con_state, NULL,
6001 			requested_bpc);
6002 	else
6003 		fill_stream_properties_from_drm_display_mode(
6004 			stream, &mode, &aconnector->base, con_state, old_stream,
6005 			requested_bpc);
6006 
6007 	if (aconnector->timing_changed) {
6008 		DC_LOG_DEBUG("%s: overriding timing for automated test, bpc %d, changing to %d\n",
6009 				__func__,
6010 				stream->timing.display_color_depth,
6011 				aconnector->timing_requested->display_color_depth);
6012 		stream->timing = *aconnector->timing_requested;
6013 	}
6014 
6015 #if defined(CONFIG_DRM_AMD_DC_DCN)
6016 	/* SST DSC determination policy */
6017 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
6018 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
6019 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
6020 #endif
6021 
6022 	update_stream_scaling_settings(&mode, dm_state, stream);
6023 
6024 	fill_audio_info(
6025 		&stream->audio_info,
6026 		drm_connector,
6027 		sink);
6028 
6029 	update_stream_signal(stream, sink);
6030 
6031 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6032 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
6033 
6034 	if (stream->link->psr_settings.psr_feature_enabled) {
6035 		//
6036 		// should decide stream support vsc sdp colorimetry capability
6037 		// before building vsc info packet
6038 		//
6039 		stream->use_vsc_sdp_for_colorimetry = false;
6040 		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
6041 			stream->use_vsc_sdp_for_colorimetry =
6042 				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
6043 		} else {
6044 			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
6045 				stream->use_vsc_sdp_for_colorimetry = true;
6046 		}
6047 		if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
6048 			tf = TRANSFER_FUNC_GAMMA_22;
6049 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
6050 		aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
6051 
6052 	}
6053 finish:
6054 	dc_sink_release(sink);
6055 
6056 	return stream;
6057 }
6058 
6059 static enum drm_connector_status
6060 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
6061 {
6062 	bool connected;
6063 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6064 
6065 	/*
6066 	 * Notes:
6067 	 * 1. This interface is NOT called in context of HPD irq.
6068 	 * 2. This interface *is called* in context of user-mode ioctl. Which
6069 	 * makes it a bad place for *any* MST-related activity.
6070 	 */
6071 
6072 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
6073 	    !aconnector->fake_enable)
6074 		connected = (aconnector->dc_sink != NULL);
6075 	else
6076 		connected = (aconnector->base.force == DRM_FORCE_ON ||
6077 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
6078 
6079 	update_subconnector_property(aconnector);
6080 
6081 	return (connected ? connector_status_connected :
6082 			connector_status_disconnected);
6083 }
6084 
6085 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
6086 					    struct drm_connector_state *connector_state,
6087 					    struct drm_property *property,
6088 					    uint64_t val)
6089 {
6090 	struct drm_device *dev = connector->dev;
6091 	struct amdgpu_device *adev = drm_to_adev(dev);
6092 	struct dm_connector_state *dm_old_state =
6093 		to_dm_connector_state(connector->state);
6094 	struct dm_connector_state *dm_new_state =
6095 		to_dm_connector_state(connector_state);
6096 
6097 	int ret = -EINVAL;
6098 
6099 	if (property == dev->mode_config.scaling_mode_property) {
6100 		enum amdgpu_rmx_type rmx_type;
6101 
6102 		switch (val) {
6103 		case DRM_MODE_SCALE_CENTER:
6104 			rmx_type = RMX_CENTER;
6105 			break;
6106 		case DRM_MODE_SCALE_ASPECT:
6107 			rmx_type = RMX_ASPECT;
6108 			break;
6109 		case DRM_MODE_SCALE_FULLSCREEN:
6110 			rmx_type = RMX_FULL;
6111 			break;
6112 		case DRM_MODE_SCALE_NONE:
6113 		default:
6114 			rmx_type = RMX_OFF;
6115 			break;
6116 		}
6117 
6118 		if (dm_old_state->scaling == rmx_type)
6119 			return 0;
6120 
6121 		dm_new_state->scaling = rmx_type;
6122 		ret = 0;
6123 	} else if (property == adev->mode_info.underscan_hborder_property) {
6124 		dm_new_state->underscan_hborder = val;
6125 		ret = 0;
6126 	} else if (property == adev->mode_info.underscan_vborder_property) {
6127 		dm_new_state->underscan_vborder = val;
6128 		ret = 0;
6129 	} else if (property == adev->mode_info.underscan_property) {
6130 		dm_new_state->underscan_enable = val;
6131 		ret = 0;
6132 	} else if (property == adev->mode_info.abm_level_property) {
6133 		dm_new_state->abm_level = val;
6134 		ret = 0;
6135 	}
6136 
6137 	return ret;
6138 }
6139 
6140 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
6141 					    const struct drm_connector_state *state,
6142 					    struct drm_property *property,
6143 					    uint64_t *val)
6144 {
6145 	struct drm_device *dev = connector->dev;
6146 	struct amdgpu_device *adev = drm_to_adev(dev);
6147 	struct dm_connector_state *dm_state =
6148 		to_dm_connector_state(state);
6149 	int ret = -EINVAL;
6150 
6151 	if (property == dev->mode_config.scaling_mode_property) {
6152 		switch (dm_state->scaling) {
6153 		case RMX_CENTER:
6154 			*val = DRM_MODE_SCALE_CENTER;
6155 			break;
6156 		case RMX_ASPECT:
6157 			*val = DRM_MODE_SCALE_ASPECT;
6158 			break;
6159 		case RMX_FULL:
6160 			*val = DRM_MODE_SCALE_FULLSCREEN;
6161 			break;
6162 		case RMX_OFF:
6163 		default:
6164 			*val = DRM_MODE_SCALE_NONE;
6165 			break;
6166 		}
6167 		ret = 0;
6168 	} else if (property == adev->mode_info.underscan_hborder_property) {
6169 		*val = dm_state->underscan_hborder;
6170 		ret = 0;
6171 	} else if (property == adev->mode_info.underscan_vborder_property) {
6172 		*val = dm_state->underscan_vborder;
6173 		ret = 0;
6174 	} else if (property == adev->mode_info.underscan_property) {
6175 		*val = dm_state->underscan_enable;
6176 		ret = 0;
6177 	} else if (property == adev->mode_info.abm_level_property) {
6178 		*val = dm_state->abm_level;
6179 		ret = 0;
6180 	}
6181 
6182 	return ret;
6183 }
6184 
6185 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6186 {
6187 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6188 
6189 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6190 }
6191 
6192 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6193 {
6194 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6195 	const struct dc_link *link = aconnector->dc_link;
6196 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6197 	struct amdgpu_display_manager *dm = &adev->dm;
6198 	int i;
6199 
6200 	/*
6201 	 * Call only if mst_mgr was initialized before since it's not done
6202 	 * for all connector types.
6203 	 */
6204 	if (aconnector->mst_mgr.dev)
6205 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6206 
6207 	for (i = 0; i < dm->num_of_edps; i++) {
6208 		if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6209 			backlight_device_unregister(dm->backlight_dev[i]);
6210 			dm->backlight_dev[i] = NULL;
6211 		}
6212 	}
6213 
6214 	if (aconnector->dc_em_sink)
6215 		dc_sink_release(aconnector->dc_em_sink);
6216 	aconnector->dc_em_sink = NULL;
6217 	if (aconnector->dc_sink)
6218 		dc_sink_release(aconnector->dc_sink);
6219 	aconnector->dc_sink = NULL;
6220 
6221 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6222 	drm_connector_unregister(connector);
6223 	drm_connector_cleanup(connector);
6224 	if (aconnector->i2c) {
6225 		i2c_del_adapter(&aconnector->i2c->base);
6226 		kfree(aconnector->i2c);
6227 	}
6228 	kfree(aconnector->dm_dp_aux.aux.name);
6229 
6230 	kfree(connector);
6231 }
6232 
6233 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6234 {
6235 	struct dm_connector_state *state =
6236 		to_dm_connector_state(connector->state);
6237 
6238 	if (connector->state)
6239 		__drm_atomic_helper_connector_destroy_state(connector->state);
6240 
6241 	kfree(state);
6242 
6243 	state = kzalloc(sizeof(*state), GFP_KERNEL);
6244 
6245 	if (state) {
6246 		state->scaling = RMX_OFF;
6247 		state->underscan_enable = false;
6248 		state->underscan_hborder = 0;
6249 		state->underscan_vborder = 0;
6250 		state->base.max_requested_bpc = 8;
6251 		state->vcpi_slots = 0;
6252 		state->pbn = 0;
6253 
6254 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6255 			state->abm_level = amdgpu_dm_abm_level;
6256 
6257 		__drm_atomic_helper_connector_reset(connector, &state->base);
6258 	}
6259 }
6260 
6261 struct drm_connector_state *
6262 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6263 {
6264 	struct dm_connector_state *state =
6265 		to_dm_connector_state(connector->state);
6266 
6267 	struct dm_connector_state *new_state =
6268 			kmemdup(state, sizeof(*state), GFP_KERNEL);
6269 
6270 	if (!new_state)
6271 		return NULL;
6272 
6273 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6274 
6275 	new_state->freesync_capable = state->freesync_capable;
6276 	new_state->abm_level = state->abm_level;
6277 	new_state->scaling = state->scaling;
6278 	new_state->underscan_enable = state->underscan_enable;
6279 	new_state->underscan_hborder = state->underscan_hborder;
6280 	new_state->underscan_vborder = state->underscan_vborder;
6281 	new_state->vcpi_slots = state->vcpi_slots;
6282 	new_state->pbn = state->pbn;
6283 	return &new_state->base;
6284 }
6285 
6286 static int
6287 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6288 {
6289 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6290 		to_amdgpu_dm_connector(connector);
6291 	int r;
6292 
6293 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6294 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6295 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6296 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6297 		if (r)
6298 			return r;
6299 	}
6300 
6301 #if defined(CONFIG_DEBUG_FS)
6302 	connector_debugfs_init(amdgpu_dm_connector);
6303 #endif
6304 
6305 	return 0;
6306 }
6307 
6308 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6309 	.reset = amdgpu_dm_connector_funcs_reset,
6310 	.detect = amdgpu_dm_connector_detect,
6311 	.fill_modes = drm_helper_probe_single_connector_modes,
6312 	.destroy = amdgpu_dm_connector_destroy,
6313 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6314 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6315 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6316 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6317 	.late_register = amdgpu_dm_connector_late_register,
6318 	.early_unregister = amdgpu_dm_connector_unregister
6319 };
6320 
6321 static int get_modes(struct drm_connector *connector)
6322 {
6323 	return amdgpu_dm_connector_get_modes(connector);
6324 }
6325 
6326 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6327 {
6328 	struct dc_sink_init_data init_params = {
6329 			.link = aconnector->dc_link,
6330 			.sink_signal = SIGNAL_TYPE_VIRTUAL
6331 	};
6332 	struct edid *edid;
6333 
6334 	if (!aconnector->base.edid_blob_ptr) {
6335 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6336 				aconnector->base.name);
6337 
6338 		aconnector->base.force = DRM_FORCE_OFF;
6339 		return;
6340 	}
6341 
6342 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6343 
6344 	aconnector->edid = edid;
6345 
6346 	aconnector->dc_em_sink = dc_link_add_remote_sink(
6347 		aconnector->dc_link,
6348 		(uint8_t *)edid,
6349 		(edid->extensions + 1) * EDID_LENGTH,
6350 		&init_params);
6351 
6352 	if (aconnector->base.force == DRM_FORCE_ON) {
6353 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
6354 		aconnector->dc_link->local_sink :
6355 		aconnector->dc_em_sink;
6356 		dc_sink_retain(aconnector->dc_sink);
6357 	}
6358 }
6359 
6360 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6361 {
6362 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6363 
6364 	/*
6365 	 * In case of headless boot with force on for DP managed connector
6366 	 * Those settings have to be != 0 to get initial modeset
6367 	 */
6368 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6369 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6370 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6371 	}
6372 
6373 	create_eml_sink(aconnector);
6374 }
6375 
6376 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
6377 						struct dc_stream_state *stream)
6378 {
6379 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
6380 	struct dc_plane_state *dc_plane_state = NULL;
6381 	struct dc_state *dc_state = NULL;
6382 
6383 	if (!stream)
6384 		goto cleanup;
6385 
6386 	dc_plane_state = dc_create_plane_state(dc);
6387 	if (!dc_plane_state)
6388 		goto cleanup;
6389 
6390 	dc_state = dc_create_state(dc);
6391 	if (!dc_state)
6392 		goto cleanup;
6393 
6394 	/* populate stream to plane */
6395 	dc_plane_state->src_rect.height  = stream->src.height;
6396 	dc_plane_state->src_rect.width   = stream->src.width;
6397 	dc_plane_state->dst_rect.height  = stream->src.height;
6398 	dc_plane_state->dst_rect.width   = stream->src.width;
6399 	dc_plane_state->clip_rect.height = stream->src.height;
6400 	dc_plane_state->clip_rect.width  = stream->src.width;
6401 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
6402 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
6403 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
6404 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
6405 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
6406 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6407 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
6408 	dc_plane_state->rotation = ROTATION_ANGLE_0;
6409 	dc_plane_state->is_tiling_rotated = false;
6410 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
6411 
6412 	dc_result = dc_validate_stream(dc, stream);
6413 	if (dc_result == DC_OK)
6414 		dc_result = dc_validate_plane(dc, dc_plane_state);
6415 
6416 	if (dc_result == DC_OK)
6417 		dc_result = dc_add_stream_to_ctx(dc, dc_state, stream);
6418 
6419 	if (dc_result == DC_OK && !dc_add_plane_to_context(
6420 						dc,
6421 						stream,
6422 						dc_plane_state,
6423 						dc_state))
6424 		dc_result = DC_FAIL_ATTACH_SURFACES;
6425 
6426 	if (dc_result == DC_OK)
6427 		dc_result = dc_validate_global_state(dc, dc_state, true);
6428 
6429 cleanup:
6430 	if (dc_state)
6431 		dc_release_state(dc_state);
6432 
6433 	if (dc_plane_state)
6434 		dc_plane_state_release(dc_plane_state);
6435 
6436 	return dc_result;
6437 }
6438 
6439 struct dc_stream_state *
6440 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6441 				const struct drm_display_mode *drm_mode,
6442 				const struct dm_connector_state *dm_state,
6443 				const struct dc_stream_state *old_stream)
6444 {
6445 	struct drm_connector *connector = &aconnector->base;
6446 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6447 	struct dc_stream_state *stream;
6448 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6449 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6450 	enum dc_status dc_result = DC_OK;
6451 
6452 	do {
6453 		stream = create_stream_for_sink(aconnector, drm_mode,
6454 						dm_state, old_stream,
6455 						requested_bpc);
6456 		if (stream == NULL) {
6457 			DRM_ERROR("Failed to create stream for sink!\n");
6458 			break;
6459 		}
6460 
6461 		dc_result = dc_validate_stream(adev->dm.dc, stream);
6462 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6463 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6464 
6465 		if (dc_result == DC_OK)
6466 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
6467 
6468 		if (dc_result != DC_OK) {
6469 			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6470 				      drm_mode->hdisplay,
6471 				      drm_mode->vdisplay,
6472 				      drm_mode->clock,
6473 				      dc_result,
6474 				      dc_status_to_str(dc_result));
6475 
6476 			dc_stream_release(stream);
6477 			stream = NULL;
6478 			requested_bpc -= 2; /* lower bpc to retry validation */
6479 		}
6480 
6481 	} while (stream == NULL && requested_bpc >= 6);
6482 
6483 	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6484 		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6485 
6486 		aconnector->force_yuv420_output = true;
6487 		stream = create_validate_stream_for_sink(aconnector, drm_mode,
6488 						dm_state, old_stream);
6489 		aconnector->force_yuv420_output = false;
6490 	}
6491 
6492 	return stream;
6493 }
6494 
6495 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6496 				   struct drm_display_mode *mode)
6497 {
6498 	int result = MODE_ERROR;
6499 	struct dc_sink *dc_sink;
6500 	/* TODO: Unhardcode stream count */
6501 	struct dc_stream_state *stream;
6502 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6503 
6504 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6505 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
6506 		return result;
6507 
6508 	/*
6509 	 * Only run this the first time mode_valid is called to initilialize
6510 	 * EDID mgmt
6511 	 */
6512 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6513 		!aconnector->dc_em_sink)
6514 		handle_edid_mgmt(aconnector);
6515 
6516 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6517 
6518 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6519 				aconnector->base.force != DRM_FORCE_ON) {
6520 		DRM_ERROR("dc_sink is NULL!\n");
6521 		goto fail;
6522 	}
6523 
6524 	stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6525 	if (stream) {
6526 		dc_stream_release(stream);
6527 		result = MODE_OK;
6528 	}
6529 
6530 fail:
6531 	/* TODO: error handling*/
6532 	return result;
6533 }
6534 
6535 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6536 				struct dc_info_packet *out)
6537 {
6538 	struct hdmi_drm_infoframe frame;
6539 	unsigned char buf[30]; /* 26 + 4 */
6540 	ssize_t len;
6541 	int ret, i;
6542 
6543 	memset(out, 0, sizeof(*out));
6544 
6545 	if (!state->hdr_output_metadata)
6546 		return 0;
6547 
6548 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6549 	if (ret)
6550 		return ret;
6551 
6552 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6553 	if (len < 0)
6554 		return (int)len;
6555 
6556 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
6557 	if (len != 30)
6558 		return -EINVAL;
6559 
6560 	/* Prepare the infopacket for DC. */
6561 	switch (state->connector->connector_type) {
6562 	case DRM_MODE_CONNECTOR_HDMIA:
6563 		out->hb0 = 0x87; /* type */
6564 		out->hb1 = 0x01; /* version */
6565 		out->hb2 = 0x1A; /* length */
6566 		out->sb[0] = buf[3]; /* checksum */
6567 		i = 1;
6568 		break;
6569 
6570 	case DRM_MODE_CONNECTOR_DisplayPort:
6571 	case DRM_MODE_CONNECTOR_eDP:
6572 		out->hb0 = 0x00; /* sdp id, zero */
6573 		out->hb1 = 0x87; /* type */
6574 		out->hb2 = 0x1D; /* payload len - 1 */
6575 		out->hb3 = (0x13 << 2); /* sdp version */
6576 		out->sb[0] = 0x01; /* version */
6577 		out->sb[1] = 0x1A; /* length */
6578 		i = 2;
6579 		break;
6580 
6581 	default:
6582 		return -EINVAL;
6583 	}
6584 
6585 	memcpy(&out->sb[i], &buf[4], 26);
6586 	out->valid = true;
6587 
6588 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6589 		       sizeof(out->sb), false);
6590 
6591 	return 0;
6592 }
6593 
6594 static int
6595 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6596 				 struct drm_atomic_state *state)
6597 {
6598 	struct drm_connector_state *new_con_state =
6599 		drm_atomic_get_new_connector_state(state, conn);
6600 	struct drm_connector_state *old_con_state =
6601 		drm_atomic_get_old_connector_state(state, conn);
6602 	struct drm_crtc *crtc = new_con_state->crtc;
6603 	struct drm_crtc_state *new_crtc_state;
6604 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6605 	int ret;
6606 
6607 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
6608 
6609 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6610 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6611 		if (ret < 0)
6612 			return ret;
6613 	}
6614 
6615 	if (!crtc)
6616 		return 0;
6617 
6618 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6619 		struct dc_info_packet hdr_infopacket;
6620 
6621 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6622 		if (ret)
6623 			return ret;
6624 
6625 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6626 		if (IS_ERR(new_crtc_state))
6627 			return PTR_ERR(new_crtc_state);
6628 
6629 		/*
6630 		 * DC considers the stream backends changed if the
6631 		 * static metadata changes. Forcing the modeset also
6632 		 * gives a simple way for userspace to switch from
6633 		 * 8bpc to 10bpc when setting the metadata to enter
6634 		 * or exit HDR.
6635 		 *
6636 		 * Changing the static metadata after it's been
6637 		 * set is permissible, however. So only force a
6638 		 * modeset if we're entering or exiting HDR.
6639 		 */
6640 		new_crtc_state->mode_changed =
6641 			!old_con_state->hdr_output_metadata ||
6642 			!new_con_state->hdr_output_metadata;
6643 	}
6644 
6645 	return 0;
6646 }
6647 
6648 static const struct drm_connector_helper_funcs
6649 amdgpu_dm_connector_helper_funcs = {
6650 	/*
6651 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
6652 	 * modes will be filtered by drm_mode_validate_size(), and those modes
6653 	 * are missing after user start lightdm. So we need to renew modes list.
6654 	 * in get_modes call back, not just return the modes count
6655 	 */
6656 	.get_modes = get_modes,
6657 	.mode_valid = amdgpu_dm_connector_mode_valid,
6658 	.atomic_check = amdgpu_dm_connector_atomic_check,
6659 };
6660 
6661 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6662 {
6663 
6664 }
6665 
6666 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6667 {
6668 	switch (display_color_depth) {
6669 	case COLOR_DEPTH_666:
6670 		return 6;
6671 	case COLOR_DEPTH_888:
6672 		return 8;
6673 	case COLOR_DEPTH_101010:
6674 		return 10;
6675 	case COLOR_DEPTH_121212:
6676 		return 12;
6677 	case COLOR_DEPTH_141414:
6678 		return 14;
6679 	case COLOR_DEPTH_161616:
6680 		return 16;
6681 	default:
6682 		break;
6683 	}
6684 	return 0;
6685 }
6686 
6687 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6688 					  struct drm_crtc_state *crtc_state,
6689 					  struct drm_connector_state *conn_state)
6690 {
6691 	struct drm_atomic_state *state = crtc_state->state;
6692 	struct drm_connector *connector = conn_state->connector;
6693 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6694 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6695 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6696 	struct drm_dp_mst_topology_mgr *mst_mgr;
6697 	struct drm_dp_mst_port *mst_port;
6698 	struct drm_dp_mst_topology_state *mst_state;
6699 	enum dc_color_depth color_depth;
6700 	int clock, bpp = 0;
6701 	bool is_y420 = false;
6702 
6703 	if (!aconnector->mst_output_port || !aconnector->dc_sink)
6704 		return 0;
6705 
6706 	mst_port = aconnector->mst_output_port;
6707 	mst_mgr = &aconnector->mst_root->mst_mgr;
6708 
6709 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6710 		return 0;
6711 
6712 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6713 	if (IS_ERR(mst_state))
6714 		return PTR_ERR(mst_state);
6715 
6716 	if (!mst_state->pbn_div)
6717 		mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
6718 
6719 	if (!state->duplicated) {
6720 		int max_bpc = conn_state->max_requested_bpc;
6721 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6722 			  aconnector->force_yuv420_output;
6723 		color_depth = convert_color_depth_from_display_info(connector,
6724 								    is_y420,
6725 								    max_bpc);
6726 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6727 		clock = adjusted_mode->clock;
6728 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6729 	}
6730 
6731 	dm_new_connector_state->vcpi_slots =
6732 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6733 					      dm_new_connector_state->pbn);
6734 	if (dm_new_connector_state->vcpi_slots < 0) {
6735 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6736 		return dm_new_connector_state->vcpi_slots;
6737 	}
6738 	return 0;
6739 }
6740 
6741 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6742 	.disable = dm_encoder_helper_disable,
6743 	.atomic_check = dm_encoder_helper_atomic_check
6744 };
6745 
6746 #if defined(CONFIG_DRM_AMD_DC_DCN)
6747 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6748 					    struct dc_state *dc_state,
6749 					    struct dsc_mst_fairness_vars *vars)
6750 {
6751 	struct dc_stream_state *stream = NULL;
6752 	struct drm_connector *connector;
6753 	struct drm_connector_state *new_con_state;
6754 	struct amdgpu_dm_connector *aconnector;
6755 	struct dm_connector_state *dm_conn_state;
6756 	int i, j, ret;
6757 	int vcpi, pbn_div, pbn, slot_num = 0;
6758 
6759 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
6760 
6761 		aconnector = to_amdgpu_dm_connector(connector);
6762 
6763 		if (!aconnector->mst_output_port)
6764 			continue;
6765 
6766 		if (!new_con_state || !new_con_state->crtc)
6767 			continue;
6768 
6769 		dm_conn_state = to_dm_connector_state(new_con_state);
6770 
6771 		for (j = 0; j < dc_state->stream_count; j++) {
6772 			stream = dc_state->streams[j];
6773 			if (!stream)
6774 				continue;
6775 
6776 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6777 				break;
6778 
6779 			stream = NULL;
6780 		}
6781 
6782 		if (!stream)
6783 			continue;
6784 
6785 		pbn_div = dm_mst_get_pbn_divider(stream->link);
6786 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
6787 		for (j = 0; j < dc_state->stream_count; j++) {
6788 			if (vars[j].aconnector == aconnector) {
6789 				pbn = vars[j].pbn;
6790 				break;
6791 			}
6792 		}
6793 
6794 		if (j == dc_state->stream_count)
6795 			continue;
6796 
6797 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
6798 
6799 		if (stream->timing.flags.DSC != 1) {
6800 			dm_conn_state->pbn = pbn;
6801 			dm_conn_state->vcpi_slots = slot_num;
6802 
6803 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
6804 							   dm_conn_state->pbn, false);
6805 			if (ret < 0)
6806 				return ret;
6807 
6808 			continue;
6809 		}
6810 
6811 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
6812 		if (vcpi < 0)
6813 			return vcpi;
6814 
6815 		dm_conn_state->pbn = pbn;
6816 		dm_conn_state->vcpi_slots = vcpi;
6817 	}
6818 	return 0;
6819 }
6820 #endif
6821 
6822 static int to_drm_connector_type(enum signal_type st)
6823 {
6824 	switch (st) {
6825 	case SIGNAL_TYPE_HDMI_TYPE_A:
6826 		return DRM_MODE_CONNECTOR_HDMIA;
6827 	case SIGNAL_TYPE_EDP:
6828 		return DRM_MODE_CONNECTOR_eDP;
6829 	case SIGNAL_TYPE_LVDS:
6830 		return DRM_MODE_CONNECTOR_LVDS;
6831 	case SIGNAL_TYPE_RGB:
6832 		return DRM_MODE_CONNECTOR_VGA;
6833 	case SIGNAL_TYPE_DISPLAY_PORT:
6834 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
6835 		return DRM_MODE_CONNECTOR_DisplayPort;
6836 	case SIGNAL_TYPE_DVI_DUAL_LINK:
6837 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
6838 		return DRM_MODE_CONNECTOR_DVID;
6839 	case SIGNAL_TYPE_VIRTUAL:
6840 		return DRM_MODE_CONNECTOR_VIRTUAL;
6841 
6842 	default:
6843 		return DRM_MODE_CONNECTOR_Unknown;
6844 	}
6845 }
6846 
6847 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6848 {
6849 	struct drm_encoder *encoder;
6850 
6851 	/* There is only one encoder per connector */
6852 	drm_connector_for_each_possible_encoder(connector, encoder)
6853 		return encoder;
6854 
6855 	return NULL;
6856 }
6857 
6858 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6859 {
6860 	struct drm_encoder *encoder;
6861 	struct amdgpu_encoder *amdgpu_encoder;
6862 
6863 	encoder = amdgpu_dm_connector_to_encoder(connector);
6864 
6865 	if (encoder == NULL)
6866 		return;
6867 
6868 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6869 
6870 	amdgpu_encoder->native_mode.clock = 0;
6871 
6872 	if (!list_empty(&connector->probed_modes)) {
6873 		struct drm_display_mode *preferred_mode = NULL;
6874 
6875 		list_for_each_entry(preferred_mode,
6876 				    &connector->probed_modes,
6877 				    head) {
6878 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6879 				amdgpu_encoder->native_mode = *preferred_mode;
6880 
6881 			break;
6882 		}
6883 
6884 	}
6885 }
6886 
6887 static struct drm_display_mode *
6888 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6889 			     char *name,
6890 			     int hdisplay, int vdisplay)
6891 {
6892 	struct drm_device *dev = encoder->dev;
6893 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6894 	struct drm_display_mode *mode = NULL;
6895 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6896 
6897 	mode = drm_mode_duplicate(dev, native_mode);
6898 
6899 	if (mode == NULL)
6900 		return NULL;
6901 
6902 	mode->hdisplay = hdisplay;
6903 	mode->vdisplay = vdisplay;
6904 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6905 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6906 
6907 	return mode;
6908 
6909 }
6910 
6911 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6912 						 struct drm_connector *connector)
6913 {
6914 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6915 	struct drm_display_mode *mode = NULL;
6916 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6917 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6918 				to_amdgpu_dm_connector(connector);
6919 	int i;
6920 	int n;
6921 	struct mode_size {
6922 		char name[DRM_DISPLAY_MODE_LEN];
6923 		int w;
6924 		int h;
6925 	} common_modes[] = {
6926 		{  "640x480",  640,  480},
6927 		{  "800x600",  800,  600},
6928 		{ "1024x768", 1024,  768},
6929 		{ "1280x720", 1280,  720},
6930 		{ "1280x800", 1280,  800},
6931 		{"1280x1024", 1280, 1024},
6932 		{ "1440x900", 1440,  900},
6933 		{"1680x1050", 1680, 1050},
6934 		{"1600x1200", 1600, 1200},
6935 		{"1920x1080", 1920, 1080},
6936 		{"1920x1200", 1920, 1200}
6937 	};
6938 
6939 	n = ARRAY_SIZE(common_modes);
6940 
6941 	for (i = 0; i < n; i++) {
6942 		struct drm_display_mode *curmode = NULL;
6943 		bool mode_existed = false;
6944 
6945 		if (common_modes[i].w > native_mode->hdisplay ||
6946 		    common_modes[i].h > native_mode->vdisplay ||
6947 		   (common_modes[i].w == native_mode->hdisplay &&
6948 		    common_modes[i].h == native_mode->vdisplay))
6949 			continue;
6950 
6951 		list_for_each_entry(curmode, &connector->probed_modes, head) {
6952 			if (common_modes[i].w == curmode->hdisplay &&
6953 			    common_modes[i].h == curmode->vdisplay) {
6954 				mode_existed = true;
6955 				break;
6956 			}
6957 		}
6958 
6959 		if (mode_existed)
6960 			continue;
6961 
6962 		mode = amdgpu_dm_create_common_mode(encoder,
6963 				common_modes[i].name, common_modes[i].w,
6964 				common_modes[i].h);
6965 		if (!mode)
6966 			continue;
6967 
6968 		drm_mode_probed_add(connector, mode);
6969 		amdgpu_dm_connector->num_modes++;
6970 	}
6971 }
6972 
6973 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6974 {
6975 	struct drm_encoder *encoder;
6976 	struct amdgpu_encoder *amdgpu_encoder;
6977 	const struct drm_display_mode *native_mode;
6978 
6979 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6980 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6981 		return;
6982 
6983 	mutex_lock(&connector->dev->mode_config.mutex);
6984 	amdgpu_dm_connector_get_modes(connector);
6985 	mutex_unlock(&connector->dev->mode_config.mutex);
6986 
6987 	encoder = amdgpu_dm_connector_to_encoder(connector);
6988 	if (!encoder)
6989 		return;
6990 
6991 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6992 
6993 	native_mode = &amdgpu_encoder->native_mode;
6994 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6995 		return;
6996 
6997 	drm_connector_set_panel_orientation_with_quirk(connector,
6998 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6999 						       native_mode->hdisplay,
7000 						       native_mode->vdisplay);
7001 }
7002 
7003 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
7004 					      struct edid *edid)
7005 {
7006 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7007 			to_amdgpu_dm_connector(connector);
7008 
7009 	if (edid) {
7010 		/* empty probed_modes */
7011 		INIT_LIST_HEAD(&connector->probed_modes);
7012 		amdgpu_dm_connector->num_modes =
7013 				drm_add_edid_modes(connector, edid);
7014 
7015 		/* sorting the probed modes before calling function
7016 		 * amdgpu_dm_get_native_mode() since EDID can have
7017 		 * more than one preferred mode. The modes that are
7018 		 * later in the probed mode list could be of higher
7019 		 * and preferred resolution. For example, 3840x2160
7020 		 * resolution in base EDID preferred timing and 4096x2160
7021 		 * preferred resolution in DID extension block later.
7022 		 */
7023 		drm_mode_sort(&connector->probed_modes);
7024 		amdgpu_dm_get_native_mode(connector);
7025 
7026 		/* Freesync capabilities are reset by calling
7027 		 * drm_add_edid_modes() and need to be
7028 		 * restored here.
7029 		 */
7030 		amdgpu_dm_update_freesync_caps(connector, edid);
7031 	} else {
7032 		amdgpu_dm_connector->num_modes = 0;
7033 	}
7034 }
7035 
7036 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
7037 			      struct drm_display_mode *mode)
7038 {
7039 	struct drm_display_mode *m;
7040 
7041 	list_for_each_entry (m, &aconnector->base.probed_modes, head) {
7042 		if (drm_mode_equal(m, mode))
7043 			return true;
7044 	}
7045 
7046 	return false;
7047 }
7048 
7049 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
7050 {
7051 	const struct drm_display_mode *m;
7052 	struct drm_display_mode *new_mode;
7053 	uint i;
7054 	u32 new_modes_count = 0;
7055 
7056 	/* Standard FPS values
7057 	 *
7058 	 * 23.976       - TV/NTSC
7059 	 * 24 	        - Cinema
7060 	 * 25 	        - TV/PAL
7061 	 * 29.97        - TV/NTSC
7062 	 * 30 	        - TV/NTSC
7063 	 * 48 	        - Cinema HFR
7064 	 * 50 	        - TV/PAL
7065 	 * 60 	        - Commonly used
7066 	 * 48,72,96,120 - Multiples of 24
7067 	 */
7068 	static const u32 common_rates[] = {
7069 		23976, 24000, 25000, 29970, 30000,
7070 		48000, 50000, 60000, 72000, 96000, 120000
7071 	};
7072 
7073 	/*
7074 	 * Find mode with highest refresh rate with the same resolution
7075 	 * as the preferred mode. Some monitors report a preferred mode
7076 	 * with lower resolution than the highest refresh rate supported.
7077 	 */
7078 
7079 	m = get_highest_refresh_rate_mode(aconnector, true);
7080 	if (!m)
7081 		return 0;
7082 
7083 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
7084 		u64 target_vtotal, target_vtotal_diff;
7085 		u64 num, den;
7086 
7087 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
7088 			continue;
7089 
7090 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
7091 		    common_rates[i] > aconnector->max_vfreq * 1000)
7092 			continue;
7093 
7094 		num = (unsigned long long)m->clock * 1000 * 1000;
7095 		den = common_rates[i] * (unsigned long long)m->htotal;
7096 		target_vtotal = div_u64(num, den);
7097 		target_vtotal_diff = target_vtotal - m->vtotal;
7098 
7099 		/* Check for illegal modes */
7100 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
7101 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
7102 		    m->vtotal + target_vtotal_diff < m->vsync_end)
7103 			continue;
7104 
7105 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
7106 		if (!new_mode)
7107 			goto out;
7108 
7109 		new_mode->vtotal += (u16)target_vtotal_diff;
7110 		new_mode->vsync_start += (u16)target_vtotal_diff;
7111 		new_mode->vsync_end += (u16)target_vtotal_diff;
7112 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
7113 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
7114 
7115 		if (!is_duplicate_mode(aconnector, new_mode)) {
7116 			drm_mode_probed_add(&aconnector->base, new_mode);
7117 			new_modes_count += 1;
7118 		} else
7119 			drm_mode_destroy(aconnector->base.dev, new_mode);
7120 	}
7121  out:
7122 	return new_modes_count;
7123 }
7124 
7125 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
7126 						   struct edid *edid)
7127 {
7128 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7129 		to_amdgpu_dm_connector(connector);
7130 
7131 	if (!(amdgpu_freesync_vid_mode && edid))
7132 		return;
7133 
7134 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
7135 		amdgpu_dm_connector->num_modes +=
7136 			add_fs_modes(amdgpu_dm_connector);
7137 }
7138 
7139 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
7140 {
7141 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7142 			to_amdgpu_dm_connector(connector);
7143 	struct drm_encoder *encoder;
7144 	struct edid *edid = amdgpu_dm_connector->edid;
7145 
7146 	encoder = amdgpu_dm_connector_to_encoder(connector);
7147 
7148 	if (!drm_edid_is_valid(edid)) {
7149 		amdgpu_dm_connector->num_modes =
7150 				drm_add_modes_noedid(connector, 640, 480);
7151 	} else {
7152 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
7153 		amdgpu_dm_connector_add_common_modes(encoder, connector);
7154 		amdgpu_dm_connector_add_freesync_modes(connector, edid);
7155 	}
7156 	amdgpu_dm_fbc_init(connector);
7157 
7158 	return amdgpu_dm_connector->num_modes;
7159 }
7160 
7161 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
7162 				     struct amdgpu_dm_connector *aconnector,
7163 				     int connector_type,
7164 				     struct dc_link *link,
7165 				     int link_index)
7166 {
7167 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
7168 
7169 	/*
7170 	 * Some of the properties below require access to state, like bpc.
7171 	 * Allocate some default initial connector state with our reset helper.
7172 	 */
7173 	if (aconnector->base.funcs->reset)
7174 		aconnector->base.funcs->reset(&aconnector->base);
7175 
7176 	aconnector->connector_id = link_index;
7177 	aconnector->dc_link = link;
7178 	aconnector->base.interlace_allowed = false;
7179 	aconnector->base.doublescan_allowed = false;
7180 	aconnector->base.stereo_allowed = false;
7181 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
7182 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
7183 	aconnector->audio_inst = -1;
7184 	aconnector->pack_sdp_v1_3 = false;
7185 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
7186 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
7187 	mutex_init(&aconnector->hpd_lock);
7188 
7189 	/*
7190 	 * configure support HPD hot plug connector_>polled default value is 0
7191 	 * which means HPD hot plug not supported
7192 	 */
7193 	switch (connector_type) {
7194 	case DRM_MODE_CONNECTOR_HDMIA:
7195 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7196 		aconnector->base.ycbcr_420_allowed =
7197 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
7198 		break;
7199 	case DRM_MODE_CONNECTOR_DisplayPort:
7200 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7201 		link->link_enc = link_enc_cfg_get_link_enc(link);
7202 		ASSERT(link->link_enc);
7203 		if (link->link_enc)
7204 			aconnector->base.ycbcr_420_allowed =
7205 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
7206 		break;
7207 	case DRM_MODE_CONNECTOR_DVID:
7208 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7209 		break;
7210 	default:
7211 		break;
7212 	}
7213 
7214 	drm_object_attach_property(&aconnector->base.base,
7215 				dm->ddev->mode_config.scaling_mode_property,
7216 				DRM_MODE_SCALE_NONE);
7217 
7218 	drm_object_attach_property(&aconnector->base.base,
7219 				adev->mode_info.underscan_property,
7220 				UNDERSCAN_OFF);
7221 	drm_object_attach_property(&aconnector->base.base,
7222 				adev->mode_info.underscan_hborder_property,
7223 				0);
7224 	drm_object_attach_property(&aconnector->base.base,
7225 				adev->mode_info.underscan_vborder_property,
7226 				0);
7227 
7228 	if (!aconnector->mst_root)
7229 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7230 
7231 	/* This defaults to the max in the range, but we want 8bpc for non-edp. */
7232 	aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7233 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7234 
7235 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7236 	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7237 		drm_object_attach_property(&aconnector->base.base,
7238 				adev->mode_info.abm_level_property, 0);
7239 	}
7240 
7241 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7242 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7243 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
7244 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7245 
7246 		if (!aconnector->mst_root)
7247 			drm_connector_attach_vrr_capable_property(&aconnector->base);
7248 
7249 #ifdef CONFIG_DRM_AMD_DC_HDCP
7250 		if (adev->dm.hdcp_workqueue)
7251 			drm_connector_attach_content_protection_property(&aconnector->base, true);
7252 #endif
7253 	}
7254 }
7255 
7256 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7257 			      struct i2c_msg *msgs, int num)
7258 {
7259 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7260 	struct ddc_service *ddc_service = i2c->ddc_service;
7261 	struct i2c_command cmd;
7262 	int i;
7263 	int result = -EIO;
7264 
7265 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7266 
7267 	if (!cmd.payloads)
7268 		return result;
7269 
7270 	cmd.number_of_payloads = num;
7271 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7272 	cmd.speed = 100;
7273 
7274 	for (i = 0; i < num; i++) {
7275 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7276 		cmd.payloads[i].address = msgs[i].addr;
7277 		cmd.payloads[i].length = msgs[i].len;
7278 		cmd.payloads[i].data = msgs[i].buf;
7279 	}
7280 
7281 	if (dc_submit_i2c(
7282 			ddc_service->ctx->dc,
7283 			ddc_service->link->link_index,
7284 			&cmd))
7285 		result = num;
7286 
7287 	kfree(cmd.payloads);
7288 	return result;
7289 }
7290 
7291 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7292 {
7293 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7294 }
7295 
7296 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7297 	.master_xfer = amdgpu_dm_i2c_xfer,
7298 	.functionality = amdgpu_dm_i2c_func,
7299 };
7300 
7301 static struct amdgpu_i2c_adapter *
7302 create_i2c(struct ddc_service *ddc_service,
7303 	   int link_index,
7304 	   int *res)
7305 {
7306 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7307 	struct amdgpu_i2c_adapter *i2c;
7308 
7309 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7310 	if (!i2c)
7311 		return NULL;
7312 	i2c->base.owner = THIS_MODULE;
7313 	i2c->base.class = I2C_CLASS_DDC;
7314 	i2c->base.dev.parent = &adev->pdev->dev;
7315 	i2c->base.algo = &amdgpu_dm_i2c_algo;
7316 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7317 	i2c_set_adapdata(&i2c->base, i2c);
7318 	i2c->ddc_service = ddc_service;
7319 
7320 	return i2c;
7321 }
7322 
7323 
7324 /*
7325  * Note: this function assumes that dc_link_detect() was called for the
7326  * dc_link which will be represented by this aconnector.
7327  */
7328 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7329 				    struct amdgpu_dm_connector *aconnector,
7330 				    u32 link_index,
7331 				    struct amdgpu_encoder *aencoder)
7332 {
7333 	int res = 0;
7334 	int connector_type;
7335 	struct dc *dc = dm->dc;
7336 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
7337 	struct amdgpu_i2c_adapter *i2c;
7338 
7339 	link->priv = aconnector;
7340 
7341 	DRM_DEBUG_DRIVER("%s()\n", __func__);
7342 
7343 	i2c = create_i2c(link->ddc, link->link_index, &res);
7344 	if (!i2c) {
7345 		DRM_ERROR("Failed to create i2c adapter data\n");
7346 		return -ENOMEM;
7347 	}
7348 
7349 	aconnector->i2c = i2c;
7350 	res = i2c_add_adapter(&i2c->base);
7351 
7352 	if (res) {
7353 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7354 		goto out_free;
7355 	}
7356 
7357 	connector_type = to_drm_connector_type(link->connector_signal);
7358 
7359 	res = drm_connector_init_with_ddc(
7360 			dm->ddev,
7361 			&aconnector->base,
7362 			&amdgpu_dm_connector_funcs,
7363 			connector_type,
7364 			&i2c->base);
7365 
7366 	if (res) {
7367 		DRM_ERROR("connector_init failed\n");
7368 		aconnector->connector_id = -1;
7369 		goto out_free;
7370 	}
7371 
7372 	drm_connector_helper_add(
7373 			&aconnector->base,
7374 			&amdgpu_dm_connector_helper_funcs);
7375 
7376 	amdgpu_dm_connector_init_helper(
7377 		dm,
7378 		aconnector,
7379 		connector_type,
7380 		link,
7381 		link_index);
7382 
7383 	drm_connector_attach_encoder(
7384 		&aconnector->base, &aencoder->base);
7385 
7386 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7387 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
7388 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7389 
7390 out_free:
7391 	if (res) {
7392 		kfree(i2c);
7393 		aconnector->i2c = NULL;
7394 	}
7395 	return res;
7396 }
7397 
7398 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7399 {
7400 	switch (adev->mode_info.num_crtc) {
7401 	case 1:
7402 		return 0x1;
7403 	case 2:
7404 		return 0x3;
7405 	case 3:
7406 		return 0x7;
7407 	case 4:
7408 		return 0xf;
7409 	case 5:
7410 		return 0x1f;
7411 	case 6:
7412 	default:
7413 		return 0x3f;
7414 	}
7415 }
7416 
7417 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7418 				  struct amdgpu_encoder *aencoder,
7419 				  uint32_t link_index)
7420 {
7421 	struct amdgpu_device *adev = drm_to_adev(dev);
7422 
7423 	int res = drm_encoder_init(dev,
7424 				   &aencoder->base,
7425 				   &amdgpu_dm_encoder_funcs,
7426 				   DRM_MODE_ENCODER_TMDS,
7427 				   NULL);
7428 
7429 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7430 
7431 	if (!res)
7432 		aencoder->encoder_id = link_index;
7433 	else
7434 		aencoder->encoder_id = -1;
7435 
7436 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7437 
7438 	return res;
7439 }
7440 
7441 static void manage_dm_interrupts(struct amdgpu_device *adev,
7442 				 struct amdgpu_crtc *acrtc,
7443 				 bool enable)
7444 {
7445 	/*
7446 	 * We have no guarantee that the frontend index maps to the same
7447 	 * backend index - some even map to more than one.
7448 	 *
7449 	 * TODO: Use a different interrupt or check DC itself for the mapping.
7450 	 */
7451 	int irq_type =
7452 		amdgpu_display_crtc_idx_to_irq_type(
7453 			adev,
7454 			acrtc->crtc_id);
7455 
7456 	if (enable) {
7457 		drm_crtc_vblank_on(&acrtc->base);
7458 		amdgpu_irq_get(
7459 			adev,
7460 			&adev->pageflip_irq,
7461 			irq_type);
7462 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7463 		amdgpu_irq_get(
7464 			adev,
7465 			&adev->vline0_irq,
7466 			irq_type);
7467 #endif
7468 	} else {
7469 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7470 		amdgpu_irq_put(
7471 			adev,
7472 			&adev->vline0_irq,
7473 			irq_type);
7474 #endif
7475 		amdgpu_irq_put(
7476 			adev,
7477 			&adev->pageflip_irq,
7478 			irq_type);
7479 		drm_crtc_vblank_off(&acrtc->base);
7480 	}
7481 }
7482 
7483 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7484 				      struct amdgpu_crtc *acrtc)
7485 {
7486 	int irq_type =
7487 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7488 
7489 	/**
7490 	 * This reads the current state for the IRQ and force reapplies
7491 	 * the setting to hardware.
7492 	 */
7493 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7494 }
7495 
7496 static bool
7497 is_scaling_state_different(const struct dm_connector_state *dm_state,
7498 			   const struct dm_connector_state *old_dm_state)
7499 {
7500 	if (dm_state->scaling != old_dm_state->scaling)
7501 		return true;
7502 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7503 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7504 			return true;
7505 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7506 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7507 			return true;
7508 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7509 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7510 		return true;
7511 	return false;
7512 }
7513 
7514 #ifdef CONFIG_DRM_AMD_DC_HDCP
7515 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
7516 					    struct drm_crtc_state *old_crtc_state,
7517 					    struct drm_connector_state *new_conn_state,
7518 					    struct drm_connector_state *old_conn_state,
7519 					    const struct drm_connector *connector,
7520 					    struct hdcp_workqueue *hdcp_w)
7521 {
7522 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7523 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7524 
7525 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
7526 		connector->index, connector->status, connector->dpms);
7527 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
7528 		old_conn_state->content_protection, new_conn_state->content_protection);
7529 
7530 	if (old_crtc_state)
7531 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7532 		old_crtc_state->enable,
7533 		old_crtc_state->active,
7534 		old_crtc_state->mode_changed,
7535 		old_crtc_state->active_changed,
7536 		old_crtc_state->connectors_changed);
7537 
7538 	if (new_crtc_state)
7539 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7540 		new_crtc_state->enable,
7541 		new_crtc_state->active,
7542 		new_crtc_state->mode_changed,
7543 		new_crtc_state->active_changed,
7544 		new_crtc_state->connectors_changed);
7545 
7546 	/* hdcp content type change */
7547 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
7548 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7549 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7550 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
7551 		return true;
7552 	}
7553 
7554 	/* CP is being re enabled, ignore this */
7555 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7556 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7557 		if (new_crtc_state && new_crtc_state->mode_changed) {
7558 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7559 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
7560 			return true;
7561 		}
7562 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7563 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
7564 		return false;
7565 	}
7566 
7567 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7568 	 *
7569 	 * Handles:	UNDESIRED -> ENABLED
7570 	 */
7571 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7572 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7573 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7574 
7575 	/* Stream removed and re-enabled
7576 	 *
7577 	 * Can sometimes overlap with the HPD case,
7578 	 * thus set update_hdcp to false to avoid
7579 	 * setting HDCP multiple times.
7580 	 *
7581 	 * Handles:	DESIRED -> DESIRED (Special case)
7582 	 */
7583 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
7584 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
7585 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7586 		dm_con_state->update_hdcp = false;
7587 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
7588 			__func__);
7589 		return true;
7590 	}
7591 
7592 	/* Hot-plug, headless s3, dpms
7593 	 *
7594 	 * Only start HDCP if the display is connected/enabled.
7595 	 * update_hdcp flag will be set to false until the next
7596 	 * HPD comes in.
7597 	 *
7598 	 * Handles:	DESIRED -> DESIRED (Special case)
7599 	 */
7600 	if (dm_con_state->update_hdcp &&
7601 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7602 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7603 		dm_con_state->update_hdcp = false;
7604 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
7605 			__func__);
7606 		return true;
7607 	}
7608 
7609 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
7610 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7611 			if (new_crtc_state && new_crtc_state->mode_changed) {
7612 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
7613 					__func__);
7614 				return true;
7615 			}
7616 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
7617 				__func__);
7618 			return false;
7619 		}
7620 
7621 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
7622 		return false;
7623 	}
7624 
7625 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
7626 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
7627 			__func__);
7628 		return true;
7629 	}
7630 
7631 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
7632 	return false;
7633 }
7634 #endif
7635 
7636 static void remove_stream(struct amdgpu_device *adev,
7637 			  struct amdgpu_crtc *acrtc,
7638 			  struct dc_stream_state *stream)
7639 {
7640 	/* this is the update mode case */
7641 
7642 	acrtc->otg_inst = -1;
7643 	acrtc->enabled = false;
7644 }
7645 
7646 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7647 {
7648 
7649 	assert_spin_locked(&acrtc->base.dev->event_lock);
7650 	WARN_ON(acrtc->event);
7651 
7652 	acrtc->event = acrtc->base.state->event;
7653 
7654 	/* Set the flip status */
7655 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7656 
7657 	/* Mark this event as consumed */
7658 	acrtc->base.state->event = NULL;
7659 
7660 	DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7661 		     acrtc->crtc_id);
7662 }
7663 
7664 static void update_freesync_state_on_stream(
7665 	struct amdgpu_display_manager *dm,
7666 	struct dm_crtc_state *new_crtc_state,
7667 	struct dc_stream_state *new_stream,
7668 	struct dc_plane_state *surface,
7669 	u32 flip_timestamp_in_us)
7670 {
7671 	struct mod_vrr_params vrr_params;
7672 	struct dc_info_packet vrr_infopacket = {0};
7673 	struct amdgpu_device *adev = dm->adev;
7674 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7675 	unsigned long flags;
7676 	bool pack_sdp_v1_3 = false;
7677 	struct amdgpu_dm_connector *aconn;
7678 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
7679 
7680 	if (!new_stream)
7681 		return;
7682 
7683 	/*
7684 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7685 	 * For now it's sufficient to just guard against these conditions.
7686 	 */
7687 
7688 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7689 		return;
7690 
7691 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7692         vrr_params = acrtc->dm_irq_params.vrr_params;
7693 
7694 	if (surface) {
7695 		mod_freesync_handle_preflip(
7696 			dm->freesync_module,
7697 			surface,
7698 			new_stream,
7699 			flip_timestamp_in_us,
7700 			&vrr_params);
7701 
7702 		if (adev->family < AMDGPU_FAMILY_AI &&
7703 		    amdgpu_dm_vrr_active(new_crtc_state)) {
7704 			mod_freesync_handle_v_update(dm->freesync_module,
7705 						     new_stream, &vrr_params);
7706 
7707 			/* Need to call this before the frame ends. */
7708 			dc_stream_adjust_vmin_vmax(dm->dc,
7709 						   new_crtc_state->stream,
7710 						   &vrr_params.adjust);
7711 		}
7712 	}
7713 
7714 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
7715 
7716 	if (aconn && aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
7717 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
7718 
7719 		if (aconn->vsdb_info.amd_vsdb_version == 1)
7720 			packet_type = PACKET_TYPE_FS_V1;
7721 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
7722 			packet_type = PACKET_TYPE_FS_V2;
7723 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
7724 			packet_type = PACKET_TYPE_FS_V3;
7725 
7726 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
7727 					&new_stream->adaptive_sync_infopacket);
7728 	}
7729 
7730 	mod_freesync_build_vrr_infopacket(
7731 		dm->freesync_module,
7732 		new_stream,
7733 		&vrr_params,
7734 		packet_type,
7735 		TRANSFER_FUNC_UNKNOWN,
7736 		&vrr_infopacket,
7737 		pack_sdp_v1_3);
7738 
7739 	new_crtc_state->freesync_vrr_info_changed |=
7740 		(memcmp(&new_crtc_state->vrr_infopacket,
7741 			&vrr_infopacket,
7742 			sizeof(vrr_infopacket)) != 0);
7743 
7744 	acrtc->dm_irq_params.vrr_params = vrr_params;
7745 	new_crtc_state->vrr_infopacket = vrr_infopacket;
7746 
7747 	new_stream->vrr_infopacket = vrr_infopacket;
7748 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
7749 
7750 	if (new_crtc_state->freesync_vrr_info_changed)
7751 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7752 			      new_crtc_state->base.crtc->base.id,
7753 			      (int)new_crtc_state->base.vrr_enabled,
7754 			      (int)vrr_params.state);
7755 
7756 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7757 }
7758 
7759 static void update_stream_irq_parameters(
7760 	struct amdgpu_display_manager *dm,
7761 	struct dm_crtc_state *new_crtc_state)
7762 {
7763 	struct dc_stream_state *new_stream = new_crtc_state->stream;
7764 	struct mod_vrr_params vrr_params;
7765 	struct mod_freesync_config config = new_crtc_state->freesync_config;
7766 	struct amdgpu_device *adev = dm->adev;
7767 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7768 	unsigned long flags;
7769 
7770 	if (!new_stream)
7771 		return;
7772 
7773 	/*
7774 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7775 	 * For now it's sufficient to just guard against these conditions.
7776 	 */
7777 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7778 		return;
7779 
7780 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7781 	vrr_params = acrtc->dm_irq_params.vrr_params;
7782 
7783 	if (new_crtc_state->vrr_supported &&
7784 	    config.min_refresh_in_uhz &&
7785 	    config.max_refresh_in_uhz) {
7786 		/*
7787 		 * if freesync compatible mode was set, config.state will be set
7788 		 * in atomic check
7789 		 */
7790 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7791 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7792 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7793 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7794 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7795 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7796 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7797 		} else {
7798 			config.state = new_crtc_state->base.vrr_enabled ?
7799 						     VRR_STATE_ACTIVE_VARIABLE :
7800 						     VRR_STATE_INACTIVE;
7801 		}
7802 	} else {
7803 		config.state = VRR_STATE_UNSUPPORTED;
7804 	}
7805 
7806 	mod_freesync_build_vrr_params(dm->freesync_module,
7807 				      new_stream,
7808 				      &config, &vrr_params);
7809 
7810 	new_crtc_state->freesync_config = config;
7811 	/* Copy state for access from DM IRQ handler */
7812 	acrtc->dm_irq_params.freesync_config = config;
7813 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7814 	acrtc->dm_irq_params.vrr_params = vrr_params;
7815 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7816 }
7817 
7818 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7819 					    struct dm_crtc_state *new_state)
7820 {
7821 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7822 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7823 
7824 	if (!old_vrr_active && new_vrr_active) {
7825 		/* Transition VRR inactive -> active:
7826 		 * While VRR is active, we must not disable vblank irq, as a
7827 		 * reenable after disable would compute bogus vblank/pflip
7828 		 * timestamps if it likely happened inside display front-porch.
7829 		 *
7830 		 * We also need vupdate irq for the actual core vblank handling
7831 		 * at end of vblank.
7832 		 */
7833 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7834 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7835 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7836 				 __func__, new_state->base.crtc->base.id);
7837 	} else if (old_vrr_active && !new_vrr_active) {
7838 		/* Transition VRR active -> inactive:
7839 		 * Allow vblank irq disable again for fixed refresh rate.
7840 		 */
7841 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7842 		drm_crtc_vblank_put(new_state->base.crtc);
7843 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7844 				 __func__, new_state->base.crtc->base.id);
7845 	}
7846 }
7847 
7848 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7849 {
7850 	struct drm_plane *plane;
7851 	struct drm_plane_state *old_plane_state;
7852 	int i;
7853 
7854 	/*
7855 	 * TODO: Make this per-stream so we don't issue redundant updates for
7856 	 * commits with multiple streams.
7857 	 */
7858 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
7859 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
7860 			handle_cursor_update(plane, old_plane_state);
7861 }
7862 
7863 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7864 				    struct dc_state *dc_state,
7865 				    struct drm_device *dev,
7866 				    struct amdgpu_display_manager *dm,
7867 				    struct drm_crtc *pcrtc,
7868 				    bool wait_for_vblank)
7869 {
7870 	u32 i;
7871 	u64 timestamp_ns = ktime_get_ns();
7872 	struct drm_plane *plane;
7873 	struct drm_plane_state *old_plane_state, *new_plane_state;
7874 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7875 	struct drm_crtc_state *new_pcrtc_state =
7876 			drm_atomic_get_new_crtc_state(state, pcrtc);
7877 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7878 	struct dm_crtc_state *dm_old_crtc_state =
7879 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7880 	int planes_count = 0, vpos, hpos;
7881 	unsigned long flags;
7882 	u32 target_vblank, last_flip_vblank;
7883 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7884 	bool cursor_update = false;
7885 	bool pflip_present = false;
7886 	bool dirty_rects_changed = false;
7887 	struct {
7888 		struct dc_surface_update surface_updates[MAX_SURFACES];
7889 		struct dc_plane_info plane_infos[MAX_SURFACES];
7890 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
7891 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7892 		struct dc_stream_update stream_update;
7893 	} *bundle;
7894 
7895 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7896 
7897 	if (!bundle) {
7898 		dm_error("Failed to allocate update bundle\n");
7899 		goto cleanup;
7900 	}
7901 
7902 	/*
7903 	 * Disable the cursor first if we're disabling all the planes.
7904 	 * It'll remain on the screen after the planes are re-enabled
7905 	 * if we don't.
7906 	 */
7907 	if (acrtc_state->active_planes == 0)
7908 		amdgpu_dm_commit_cursors(state);
7909 
7910 	/* update planes when needed */
7911 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7912 		struct drm_crtc *crtc = new_plane_state->crtc;
7913 		struct drm_crtc_state *new_crtc_state;
7914 		struct drm_framebuffer *fb = new_plane_state->fb;
7915 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7916 		bool plane_needs_flip;
7917 		struct dc_plane_state *dc_plane;
7918 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7919 
7920 		/* Cursor plane is handled after stream updates */
7921 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7922 			if ((fb && crtc == pcrtc) ||
7923 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7924 				cursor_update = true;
7925 
7926 			continue;
7927 		}
7928 
7929 		if (!fb || !crtc || pcrtc != crtc)
7930 			continue;
7931 
7932 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7933 		if (!new_crtc_state->active)
7934 			continue;
7935 
7936 		dc_plane = dm_new_plane_state->dc_state;
7937 
7938 		bundle->surface_updates[planes_count].surface = dc_plane;
7939 		if (new_pcrtc_state->color_mgmt_changed) {
7940 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7941 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7942 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7943 		}
7944 
7945 		fill_dc_scaling_info(dm->adev, new_plane_state,
7946 				     &bundle->scaling_infos[planes_count]);
7947 
7948 		bundle->surface_updates[planes_count].scaling_info =
7949 			&bundle->scaling_infos[planes_count];
7950 
7951 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7952 
7953 		pflip_present = pflip_present || plane_needs_flip;
7954 
7955 		if (!plane_needs_flip) {
7956 			planes_count += 1;
7957 			continue;
7958 		}
7959 
7960 		fill_dc_plane_info_and_addr(
7961 			dm->adev, new_plane_state,
7962 			afb->tiling_flags,
7963 			&bundle->plane_infos[planes_count],
7964 			&bundle->flip_addrs[planes_count].address,
7965 			afb->tmz_surface, false);
7966 
7967 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7968 				 new_plane_state->plane->index,
7969 				 bundle->plane_infos[planes_count].dcc.enable);
7970 
7971 		bundle->surface_updates[planes_count].plane_info =
7972 			&bundle->plane_infos[planes_count];
7973 
7974 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
7975 			fill_dc_dirty_rects(plane, old_plane_state,
7976 					    new_plane_state, new_crtc_state,
7977 					    &bundle->flip_addrs[planes_count],
7978 					    &dirty_rects_changed);
7979 
7980 			/*
7981 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
7982 			 * and enabled it again after dirty regions are stable to avoid video glitch.
7983 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
7984 			 * during the PSR-SU was disabled.
7985 			 */
7986 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
7987 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
7988 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
7989 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
7990 #endif
7991 			    dirty_rects_changed) {
7992 				mutex_lock(&dm->dc_lock);
7993 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
7994 				timestamp_ns;
7995 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
7996 					amdgpu_dm_psr_disable(acrtc_state->stream);
7997 				mutex_unlock(&dm->dc_lock);
7998 			}
7999 		}
8000 
8001 		/*
8002 		 * Only allow immediate flips for fast updates that don't
8003 		 * change FB pitch, DCC state, rotation or mirroing.
8004 		 */
8005 		bundle->flip_addrs[planes_count].flip_immediate =
8006 			crtc->state->async_flip &&
8007 			acrtc_state->update_type == UPDATE_TYPE_FAST;
8008 
8009 		timestamp_ns = ktime_get_ns();
8010 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
8011 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
8012 		bundle->surface_updates[planes_count].surface = dc_plane;
8013 
8014 		if (!bundle->surface_updates[planes_count].surface) {
8015 			DRM_ERROR("No surface for CRTC: id=%d\n",
8016 					acrtc_attach->crtc_id);
8017 			continue;
8018 		}
8019 
8020 		if (plane == pcrtc->primary)
8021 			update_freesync_state_on_stream(
8022 				dm,
8023 				acrtc_state,
8024 				acrtc_state->stream,
8025 				dc_plane,
8026 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
8027 
8028 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
8029 				 __func__,
8030 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
8031 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
8032 
8033 		planes_count += 1;
8034 
8035 	}
8036 
8037 	if (pflip_present) {
8038 		if (!vrr_active) {
8039 			/* Use old throttling in non-vrr fixed refresh rate mode
8040 			 * to keep flip scheduling based on target vblank counts
8041 			 * working in a backwards compatible way, e.g., for
8042 			 * clients using the GLX_OML_sync_control extension or
8043 			 * DRI3/Present extension with defined target_msc.
8044 			 */
8045 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
8046 		}
8047 		else {
8048 			/* For variable refresh rate mode only:
8049 			 * Get vblank of last completed flip to avoid > 1 vrr
8050 			 * flips per video frame by use of throttling, but allow
8051 			 * flip programming anywhere in the possibly large
8052 			 * variable vrr vblank interval for fine-grained flip
8053 			 * timing control and more opportunity to avoid stutter
8054 			 * on late submission of flips.
8055 			 */
8056 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8057 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
8058 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8059 		}
8060 
8061 		target_vblank = last_flip_vblank + wait_for_vblank;
8062 
8063 		/*
8064 		 * Wait until we're out of the vertical blank period before the one
8065 		 * targeted by the flip
8066 		 */
8067 		while ((acrtc_attach->enabled &&
8068 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
8069 							    0, &vpos, &hpos, NULL,
8070 							    NULL, &pcrtc->hwmode)
8071 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
8072 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
8073 			(int)(target_vblank -
8074 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
8075 			usleep_range(1000, 1100);
8076 		}
8077 
8078 		/**
8079 		 * Prepare the flip event for the pageflip interrupt to handle.
8080 		 *
8081 		 * This only works in the case where we've already turned on the
8082 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
8083 		 * from 0 -> n planes we have to skip a hardware generated event
8084 		 * and rely on sending it from software.
8085 		 */
8086 		if (acrtc_attach->base.state->event &&
8087 		    acrtc_state->active_planes > 0) {
8088 			drm_crtc_vblank_get(pcrtc);
8089 
8090 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8091 
8092 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
8093 			prepare_flip_isr(acrtc_attach);
8094 
8095 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8096 		}
8097 
8098 		if (acrtc_state->stream) {
8099 			if (acrtc_state->freesync_vrr_info_changed)
8100 				bundle->stream_update.vrr_infopacket =
8101 					&acrtc_state->stream->vrr_infopacket;
8102 		}
8103 	} else if (cursor_update && acrtc_state->active_planes > 0 &&
8104 		   acrtc_attach->base.state->event) {
8105 		drm_crtc_vblank_get(pcrtc);
8106 
8107 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8108 
8109 		acrtc_attach->event = acrtc_attach->base.state->event;
8110 		acrtc_attach->base.state->event = NULL;
8111 
8112 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8113 	}
8114 
8115 	/* Update the planes if changed or disable if we don't have any. */
8116 	if ((planes_count || acrtc_state->active_planes == 0) &&
8117 		acrtc_state->stream) {
8118 		/*
8119 		 * If PSR or idle optimizations are enabled then flush out
8120 		 * any pending work before hardware programming.
8121 		 */
8122 		if (dm->vblank_control_workqueue)
8123 			flush_workqueue(dm->vblank_control_workqueue);
8124 
8125 		bundle->stream_update.stream = acrtc_state->stream;
8126 		if (new_pcrtc_state->mode_changed) {
8127 			bundle->stream_update.src = acrtc_state->stream->src;
8128 			bundle->stream_update.dst = acrtc_state->stream->dst;
8129 		}
8130 
8131 		if (new_pcrtc_state->color_mgmt_changed) {
8132 			/*
8133 			 * TODO: This isn't fully correct since we've actually
8134 			 * already modified the stream in place.
8135 			 */
8136 			bundle->stream_update.gamut_remap =
8137 				&acrtc_state->stream->gamut_remap_matrix;
8138 			bundle->stream_update.output_csc_transform =
8139 				&acrtc_state->stream->csc_color_matrix;
8140 			bundle->stream_update.out_transfer_func =
8141 				acrtc_state->stream->out_transfer_func;
8142 		}
8143 
8144 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
8145 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
8146 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
8147 
8148 		/*
8149 		 * If FreeSync state on the stream has changed then we need to
8150 		 * re-adjust the min/max bounds now that DC doesn't handle this
8151 		 * as part of commit.
8152 		 */
8153 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
8154 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8155 			dc_stream_adjust_vmin_vmax(
8156 				dm->dc, acrtc_state->stream,
8157 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
8158 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8159 		}
8160 		mutex_lock(&dm->dc_lock);
8161 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8162 				acrtc_state->stream->link->psr_settings.psr_allow_active)
8163 			amdgpu_dm_psr_disable(acrtc_state->stream);
8164 
8165 		dc_commit_updates_for_stream(dm->dc,
8166 						     bundle->surface_updates,
8167 						     planes_count,
8168 						     acrtc_state->stream,
8169 						     &bundle->stream_update,
8170 						     dc_state);
8171 
8172 		/**
8173 		 * Enable or disable the interrupts on the backend.
8174 		 *
8175 		 * Most pipes are put into power gating when unused.
8176 		 *
8177 		 * When power gating is enabled on a pipe we lose the
8178 		 * interrupt enablement state when power gating is disabled.
8179 		 *
8180 		 * So we need to update the IRQ control state in hardware
8181 		 * whenever the pipe turns on (since it could be previously
8182 		 * power gated) or off (since some pipes can't be power gated
8183 		 * on some ASICs).
8184 		 */
8185 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
8186 			dm_update_pflip_irq_state(drm_to_adev(dev),
8187 						  acrtc_attach);
8188 
8189 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8190 				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
8191 				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
8192 			amdgpu_dm_link_setup_psr(acrtc_state->stream);
8193 
8194 		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
8195 		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
8196 		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
8197 			struct amdgpu_dm_connector *aconn =
8198 				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8199 
8200 			if (aconn->psr_skip_count > 0)
8201 				aconn->psr_skip_count--;
8202 
8203 			/* Allow PSR when skip count is 0. */
8204 			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
8205 
8206 			/*
8207 			 * If sink supports PSR SU, there is no need to rely on
8208 			 * a vblank event disable request to enable PSR. PSR SU
8209 			 * can be enabled immediately once OS demonstrates an
8210 			 * adequate number of fast atomic commits to notify KMD
8211 			 * of update events. See `vblank_control_worker()`.
8212 			 */
8213 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
8214 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
8215 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
8216 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
8217 #endif
8218 			    !acrtc_state->stream->link->psr_settings.psr_allow_active &&
8219 			    (timestamp_ns -
8220 			    acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns) >
8221 			    500000000)
8222 				amdgpu_dm_psr_enable(acrtc_state->stream);
8223 		} else {
8224 			acrtc_attach->dm_irq_params.allow_psr_entry = false;
8225 		}
8226 
8227 		mutex_unlock(&dm->dc_lock);
8228 	}
8229 
8230 	/*
8231 	 * Update cursor state *after* programming all the planes.
8232 	 * This avoids redundant programming in the case where we're going
8233 	 * to be disabling a single plane - those pipes are being disabled.
8234 	 */
8235 	if (acrtc_state->active_planes)
8236 		amdgpu_dm_commit_cursors(state);
8237 
8238 cleanup:
8239 	kfree(bundle);
8240 }
8241 
8242 static void amdgpu_dm_commit_audio(struct drm_device *dev,
8243 				   struct drm_atomic_state *state)
8244 {
8245 	struct amdgpu_device *adev = drm_to_adev(dev);
8246 	struct amdgpu_dm_connector *aconnector;
8247 	struct drm_connector *connector;
8248 	struct drm_connector_state *old_con_state, *new_con_state;
8249 	struct drm_crtc_state *new_crtc_state;
8250 	struct dm_crtc_state *new_dm_crtc_state;
8251 	const struct dc_stream_status *status;
8252 	int i, inst;
8253 
8254 	/* Notify device removals. */
8255 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8256 		if (old_con_state->crtc != new_con_state->crtc) {
8257 			/* CRTC changes require notification. */
8258 			goto notify;
8259 		}
8260 
8261 		if (!new_con_state->crtc)
8262 			continue;
8263 
8264 		new_crtc_state = drm_atomic_get_new_crtc_state(
8265 			state, new_con_state->crtc);
8266 
8267 		if (!new_crtc_state)
8268 			continue;
8269 
8270 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8271 			continue;
8272 
8273 	notify:
8274 		aconnector = to_amdgpu_dm_connector(connector);
8275 
8276 		mutex_lock(&adev->dm.audio_lock);
8277 		inst = aconnector->audio_inst;
8278 		aconnector->audio_inst = -1;
8279 		mutex_unlock(&adev->dm.audio_lock);
8280 
8281 		amdgpu_dm_audio_eld_notify(adev, inst);
8282 	}
8283 
8284 	/* Notify audio device additions. */
8285 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8286 		if (!new_con_state->crtc)
8287 			continue;
8288 
8289 		new_crtc_state = drm_atomic_get_new_crtc_state(
8290 			state, new_con_state->crtc);
8291 
8292 		if (!new_crtc_state)
8293 			continue;
8294 
8295 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8296 			continue;
8297 
8298 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
8299 		if (!new_dm_crtc_state->stream)
8300 			continue;
8301 
8302 		status = dc_stream_get_status(new_dm_crtc_state->stream);
8303 		if (!status)
8304 			continue;
8305 
8306 		aconnector = to_amdgpu_dm_connector(connector);
8307 
8308 		mutex_lock(&adev->dm.audio_lock);
8309 		inst = status->audio_inst;
8310 		aconnector->audio_inst = inst;
8311 		mutex_unlock(&adev->dm.audio_lock);
8312 
8313 		amdgpu_dm_audio_eld_notify(adev, inst);
8314 	}
8315 }
8316 
8317 /*
8318  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8319  * @crtc_state: the DRM CRTC state
8320  * @stream_state: the DC stream state.
8321  *
8322  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8323  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8324  */
8325 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8326 						struct dc_stream_state *stream_state)
8327 {
8328 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8329 }
8330 
8331 /**
8332  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8333  * @state: The atomic state to commit
8334  *
8335  * This will tell DC to commit the constructed DC state from atomic_check,
8336  * programming the hardware. Any failures here implies a hardware failure, since
8337  * atomic check should have filtered anything non-kosher.
8338  */
8339 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8340 {
8341 	struct drm_device *dev = state->dev;
8342 	struct amdgpu_device *adev = drm_to_adev(dev);
8343 	struct amdgpu_display_manager *dm = &adev->dm;
8344 	struct dm_atomic_state *dm_state;
8345 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8346 	u32 i, j;
8347 	struct drm_crtc *crtc;
8348 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8349 	unsigned long flags;
8350 	bool wait_for_vblank = true;
8351 	struct drm_connector *connector;
8352 	struct drm_connector_state *old_con_state, *new_con_state;
8353 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8354 	int crtc_disable_count = 0;
8355 	bool mode_set_reset_required = false;
8356 	int r;
8357 
8358 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
8359 
8360 	r = drm_atomic_helper_wait_for_fences(dev, state, false);
8361 	if (unlikely(r))
8362 		DRM_ERROR("Waiting for fences timed out!");
8363 
8364 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
8365 	drm_dp_mst_atomic_wait_for_dependencies(state);
8366 
8367 	dm_state = dm_atomic_get_new_state(state);
8368 	if (dm_state && dm_state->context) {
8369 		dc_state = dm_state->context;
8370 	} else {
8371 		/* No state changes, retain current state. */
8372 		dc_state_temp = dc_create_state(dm->dc);
8373 		ASSERT(dc_state_temp);
8374 		dc_state = dc_state_temp;
8375 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
8376 	}
8377 
8378 	for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8379 				       new_crtc_state, i) {
8380 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8381 
8382 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8383 
8384 		if (old_crtc_state->active &&
8385 		    (!new_crtc_state->active ||
8386 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8387 			manage_dm_interrupts(adev, acrtc, false);
8388 			dc_stream_release(dm_old_crtc_state->stream);
8389 		}
8390 	}
8391 
8392 	drm_atomic_helper_calc_timestamping_constants(state);
8393 
8394 	/* update changed items */
8395 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8396 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8397 
8398 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8399 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8400 
8401 		drm_dbg_state(state->dev,
8402 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8403 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8404 			"connectors_changed:%d\n",
8405 			acrtc->crtc_id,
8406 			new_crtc_state->enable,
8407 			new_crtc_state->active,
8408 			new_crtc_state->planes_changed,
8409 			new_crtc_state->mode_changed,
8410 			new_crtc_state->active_changed,
8411 			new_crtc_state->connectors_changed);
8412 
8413 		/* Disable cursor if disabling crtc */
8414 		if (old_crtc_state->active && !new_crtc_state->active) {
8415 			struct dc_cursor_position position;
8416 
8417 			memset(&position, 0, sizeof(position));
8418 			mutex_lock(&dm->dc_lock);
8419 			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8420 			mutex_unlock(&dm->dc_lock);
8421 		}
8422 
8423 		/* Copy all transient state flags into dc state */
8424 		if (dm_new_crtc_state->stream) {
8425 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8426 							    dm_new_crtc_state->stream);
8427 		}
8428 
8429 		/* handles headless hotplug case, updating new_state and
8430 		 * aconnector as needed
8431 		 */
8432 
8433 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8434 
8435 			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8436 
8437 			if (!dm_new_crtc_state->stream) {
8438 				/*
8439 				 * this could happen because of issues with
8440 				 * userspace notifications delivery.
8441 				 * In this case userspace tries to set mode on
8442 				 * display which is disconnected in fact.
8443 				 * dc_sink is NULL in this case on aconnector.
8444 				 * We expect reset mode will come soon.
8445 				 *
8446 				 * This can also happen when unplug is done
8447 				 * during resume sequence ended
8448 				 *
8449 				 * In this case, we want to pretend we still
8450 				 * have a sink to keep the pipe running so that
8451 				 * hw state is consistent with the sw state
8452 				 */
8453 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8454 						__func__, acrtc->base.base.id);
8455 				continue;
8456 			}
8457 
8458 			if (dm_old_crtc_state->stream)
8459 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8460 
8461 			pm_runtime_get_noresume(dev->dev);
8462 
8463 			acrtc->enabled = true;
8464 			acrtc->hw_mode = new_crtc_state->mode;
8465 			crtc->hwmode = new_crtc_state->mode;
8466 			mode_set_reset_required = true;
8467 		} else if (modereset_required(new_crtc_state)) {
8468 			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8469 			/* i.e. reset mode */
8470 			if (dm_old_crtc_state->stream)
8471 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8472 
8473 			mode_set_reset_required = true;
8474 		}
8475 	} /* for_each_crtc_in_state() */
8476 
8477 	if (dc_state) {
8478 		/* if there mode set or reset, disable eDP PSR */
8479 		if (mode_set_reset_required) {
8480 			if (dm->vblank_control_workqueue)
8481 				flush_workqueue(dm->vblank_control_workqueue);
8482 
8483 			amdgpu_dm_psr_disable_all(dm);
8484 		}
8485 
8486 		dm_enable_per_frame_crtc_master_sync(dc_state);
8487 		mutex_lock(&dm->dc_lock);
8488 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
8489 
8490 		/* Allow idle optimization when vblank count is 0 for display off */
8491 		if (dm->active_vblank_irq_count == 0)
8492 			dc_allow_idle_optimizations(dm->dc, true);
8493 		mutex_unlock(&dm->dc_lock);
8494 	}
8495 
8496 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8497 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8498 
8499 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8500 
8501 		if (dm_new_crtc_state->stream != NULL) {
8502 			const struct dc_stream_status *status =
8503 					dc_stream_get_status(dm_new_crtc_state->stream);
8504 
8505 			if (!status)
8506 				status = dc_stream_get_status_from_state(dc_state,
8507 									 dm_new_crtc_state->stream);
8508 			if (!status)
8509 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8510 			else
8511 				acrtc->otg_inst = status->primary_otg_inst;
8512 		}
8513 	}
8514 #ifdef CONFIG_DRM_AMD_DC_HDCP
8515 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8516 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8517 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8518 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8519 
8520 		pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
8521 
8522 		if (!connector)
8523 			continue;
8524 
8525 		pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8526 			connector->index, connector->status, connector->dpms);
8527 		pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8528 			old_con_state->content_protection, new_con_state->content_protection);
8529 
8530 		if (aconnector->dc_sink) {
8531 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
8532 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
8533 				pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
8534 				aconnector->dc_sink->edid_caps.display_name);
8535 			}
8536 		}
8537 
8538 		new_crtc_state = NULL;
8539 		old_crtc_state = NULL;
8540 
8541 		if (acrtc) {
8542 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8543 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8544 		}
8545 
8546 		if (old_crtc_state)
8547 			pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8548 			old_crtc_state->enable,
8549 			old_crtc_state->active,
8550 			old_crtc_state->mode_changed,
8551 			old_crtc_state->active_changed,
8552 			old_crtc_state->connectors_changed);
8553 
8554 		if (new_crtc_state)
8555 			pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8556 			new_crtc_state->enable,
8557 			new_crtc_state->active,
8558 			new_crtc_state->mode_changed,
8559 			new_crtc_state->active_changed,
8560 			new_crtc_state->connectors_changed);
8561 	}
8562 
8563 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8564 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8565 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8566 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8567 
8568 		new_crtc_state = NULL;
8569 		old_crtc_state = NULL;
8570 
8571 		if (acrtc) {
8572 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8573 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8574 		}
8575 
8576 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8577 
8578 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8579 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8580 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8581 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8582 			dm_new_con_state->update_hdcp = true;
8583 			continue;
8584 		}
8585 
8586 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
8587 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
8588 			/* when display is unplugged from mst hub, connctor will
8589 			 * be destroyed within dm_dp_mst_connector_destroy. connector
8590 			 * hdcp perperties, like type, undesired, desired, enabled,
8591 			 * will be lost. So, save hdcp properties into hdcp_work within
8592 			 * amdgpu_dm_atomic_commit_tail. if the same display is
8593 			 * plugged back with same display index, its hdcp properties
8594 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
8595 			 */
8596 
8597 			bool enable_encryption = false;
8598 
8599 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
8600 				enable_encryption = true;
8601 
8602 			if (aconnector->dc_link && aconnector->dc_sink &&
8603 				aconnector->dc_link->type == dc_connection_mst_branch) {
8604 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
8605 				struct hdcp_workqueue *hdcp_w =
8606 					&hdcp_work[aconnector->dc_link->link_index];
8607 
8608 				hdcp_w->hdcp_content_type[connector->index] =
8609 					new_con_state->hdcp_content_type;
8610 				hdcp_w->content_protection[connector->index] =
8611 					new_con_state->content_protection;
8612 			}
8613 
8614 			if (new_crtc_state && new_crtc_state->mode_changed &&
8615 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
8616 				enable_encryption = true;
8617 
8618 			DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
8619 
8620 			hdcp_update_display(
8621 				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8622 				new_con_state->hdcp_content_type, enable_encryption);
8623 		}
8624 	}
8625 #endif
8626 
8627 	/* Handle connector state changes */
8628 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8629 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8630 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8631 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8632 		struct dc_surface_update dummy_updates[MAX_SURFACES];
8633 		struct dc_stream_update stream_update;
8634 		struct dc_info_packet hdr_packet;
8635 		struct dc_stream_status *status = NULL;
8636 		bool abm_changed, hdr_changed, scaling_changed;
8637 
8638 		memset(&dummy_updates, 0, sizeof(dummy_updates));
8639 		memset(&stream_update, 0, sizeof(stream_update));
8640 
8641 		if (acrtc) {
8642 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8643 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8644 		}
8645 
8646 		/* Skip any modesets/resets */
8647 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8648 			continue;
8649 
8650 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8651 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8652 
8653 		scaling_changed = is_scaling_state_different(dm_new_con_state,
8654 							     dm_old_con_state);
8655 
8656 		abm_changed = dm_new_crtc_state->abm_level !=
8657 			      dm_old_crtc_state->abm_level;
8658 
8659 		hdr_changed =
8660 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8661 
8662 		if (!scaling_changed && !abm_changed && !hdr_changed)
8663 			continue;
8664 
8665 		stream_update.stream = dm_new_crtc_state->stream;
8666 		if (scaling_changed) {
8667 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8668 					dm_new_con_state, dm_new_crtc_state->stream);
8669 
8670 			stream_update.src = dm_new_crtc_state->stream->src;
8671 			stream_update.dst = dm_new_crtc_state->stream->dst;
8672 		}
8673 
8674 		if (abm_changed) {
8675 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8676 
8677 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
8678 		}
8679 
8680 		if (hdr_changed) {
8681 			fill_hdr_info_packet(new_con_state, &hdr_packet);
8682 			stream_update.hdr_static_metadata = &hdr_packet;
8683 		}
8684 
8685 		status = dc_stream_get_status(dm_new_crtc_state->stream);
8686 
8687 		if (WARN_ON(!status))
8688 			continue;
8689 
8690 		WARN_ON(!status->plane_count);
8691 
8692 		/*
8693 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
8694 		 * Here we create an empty update on each plane.
8695 		 * To fix this, DC should permit updating only stream properties.
8696 		 */
8697 		for (j = 0; j < status->plane_count; j++)
8698 			dummy_updates[j].surface = status->plane_states[0];
8699 
8700 
8701 		mutex_lock(&dm->dc_lock);
8702 		dc_commit_updates_for_stream(dm->dc,
8703 						     dummy_updates,
8704 						     status->plane_count,
8705 						     dm_new_crtc_state->stream,
8706 						     &stream_update,
8707 						     dc_state);
8708 		mutex_unlock(&dm->dc_lock);
8709 	}
8710 
8711 	/**
8712 	 * Enable interrupts for CRTCs that are newly enabled or went through
8713 	 * a modeset. It was intentionally deferred until after the front end
8714 	 * state was modified to wait until the OTG was on and so the IRQ
8715 	 * handlers didn't access stale or invalid state.
8716 	 */
8717 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8718 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8719 #ifdef CONFIG_DEBUG_FS
8720 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
8721 #endif
8722 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
8723 		if (old_crtc_state->active && !new_crtc_state->active)
8724 			crtc_disable_count++;
8725 
8726 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8727 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8728 
8729 		/* For freesync config update on crtc state and params for irq */
8730 		update_stream_irq_parameters(dm, dm_new_crtc_state);
8731 
8732 #ifdef CONFIG_DEBUG_FS
8733 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8734 		cur_crc_src = acrtc->dm_irq_params.crc_src;
8735 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8736 #endif
8737 
8738 		if (new_crtc_state->active &&
8739 		    (!old_crtc_state->active ||
8740 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8741 			dc_stream_retain(dm_new_crtc_state->stream);
8742 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8743 			manage_dm_interrupts(adev, acrtc, true);
8744 		}
8745 		/* Handle vrr on->off / off->on transitions */
8746 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8747 
8748 #ifdef CONFIG_DEBUG_FS
8749 		if (new_crtc_state->active &&
8750 		    (!old_crtc_state->active ||
8751 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8752 			/**
8753 			 * Frontend may have changed so reapply the CRC capture
8754 			 * settings for the stream.
8755 			 */
8756 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8757 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8758 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
8759 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8760 					acrtc->dm_irq_params.window_param.update_win = true;
8761 
8762 					/**
8763 					 * It takes 2 frames for HW to stably generate CRC when
8764 					 * resuming from suspend, so we set skip_frame_cnt 2.
8765 					 */
8766 					acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
8767 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8768 				}
8769 #endif
8770 				if (amdgpu_dm_crtc_configure_crc_source(
8771 					crtc, dm_new_crtc_state, cur_crc_src))
8772 					DRM_DEBUG_DRIVER("Failed to configure crc source");
8773 			}
8774 		}
8775 #endif
8776 	}
8777 
8778 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8779 		if (new_crtc_state->async_flip)
8780 			wait_for_vblank = false;
8781 
8782 	/* update planes when needed per crtc*/
8783 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8784 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8785 
8786 		if (dm_new_crtc_state->stream)
8787 			amdgpu_dm_commit_planes(state, dc_state, dev,
8788 						dm, crtc, wait_for_vblank);
8789 	}
8790 
8791 	/* Update audio instances for each connector. */
8792 	amdgpu_dm_commit_audio(dev, state);
8793 
8794 	/* restore the backlight level */
8795 	for (i = 0; i < dm->num_of_edps; i++) {
8796 		if (dm->backlight_dev[i] &&
8797 		    (dm->actual_brightness[i] != dm->brightness[i]))
8798 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8799 	}
8800 
8801 	/*
8802 	 * send vblank event on all events not handled in flip and
8803 	 * mark consumed event for drm_atomic_helper_commit_hw_done
8804 	 */
8805 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8806 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8807 
8808 		if (new_crtc_state->event)
8809 			drm_send_event_locked(dev, &new_crtc_state->event->base);
8810 
8811 		new_crtc_state->event = NULL;
8812 	}
8813 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8814 
8815 	/* Signal HW programming completion */
8816 	drm_atomic_helper_commit_hw_done(state);
8817 
8818 	if (wait_for_vblank)
8819 		drm_atomic_helper_wait_for_flip_done(dev, state);
8820 
8821 	drm_atomic_helper_cleanup_planes(dev, state);
8822 
8823 	/* return the stolen vga memory back to VRAM */
8824 	if (!adev->mman.keep_stolen_vga_memory)
8825 		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8826 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8827 
8828 	/*
8829 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
8830 	 * so we can put the GPU into runtime suspend if we're not driving any
8831 	 * displays anymore
8832 	 */
8833 	for (i = 0; i < crtc_disable_count; i++)
8834 		pm_runtime_put_autosuspend(dev->dev);
8835 	pm_runtime_mark_last_busy(dev->dev);
8836 
8837 	if (dc_state_temp)
8838 		dc_release_state(dc_state_temp);
8839 }
8840 
8841 static int dm_force_atomic_commit(struct drm_connector *connector)
8842 {
8843 	int ret = 0;
8844 	struct drm_device *ddev = connector->dev;
8845 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8846 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8847 	struct drm_plane *plane = disconnected_acrtc->base.primary;
8848 	struct drm_connector_state *conn_state;
8849 	struct drm_crtc_state *crtc_state;
8850 	struct drm_plane_state *plane_state;
8851 
8852 	if (!state)
8853 		return -ENOMEM;
8854 
8855 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
8856 
8857 	/* Construct an atomic state to restore previous display setting */
8858 
8859 	/*
8860 	 * Attach connectors to drm_atomic_state
8861 	 */
8862 	conn_state = drm_atomic_get_connector_state(state, connector);
8863 
8864 	ret = PTR_ERR_OR_ZERO(conn_state);
8865 	if (ret)
8866 		goto out;
8867 
8868 	/* Attach crtc to drm_atomic_state*/
8869 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8870 
8871 	ret = PTR_ERR_OR_ZERO(crtc_state);
8872 	if (ret)
8873 		goto out;
8874 
8875 	/* force a restore */
8876 	crtc_state->mode_changed = true;
8877 
8878 	/* Attach plane to drm_atomic_state */
8879 	plane_state = drm_atomic_get_plane_state(state, plane);
8880 
8881 	ret = PTR_ERR_OR_ZERO(plane_state);
8882 	if (ret)
8883 		goto out;
8884 
8885 	/* Call commit internally with the state we just constructed */
8886 	ret = drm_atomic_commit(state);
8887 
8888 out:
8889 	drm_atomic_state_put(state);
8890 	if (ret)
8891 		DRM_ERROR("Restoring old state failed with %i\n", ret);
8892 
8893 	return ret;
8894 }
8895 
8896 /*
8897  * This function handles all cases when set mode does not come upon hotplug.
8898  * This includes when a display is unplugged then plugged back into the
8899  * same port and when running without usermode desktop manager supprot
8900  */
8901 void dm_restore_drm_connector_state(struct drm_device *dev,
8902 				    struct drm_connector *connector)
8903 {
8904 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8905 	struct amdgpu_crtc *disconnected_acrtc;
8906 	struct dm_crtc_state *acrtc_state;
8907 
8908 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8909 		return;
8910 
8911 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8912 	if (!disconnected_acrtc)
8913 		return;
8914 
8915 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8916 	if (!acrtc_state->stream)
8917 		return;
8918 
8919 	/*
8920 	 * If the previous sink is not released and different from the current,
8921 	 * we deduce we are in a state where we can not rely on usermode call
8922 	 * to turn on the display, so we do it here
8923 	 */
8924 	if (acrtc_state->stream->sink != aconnector->dc_sink)
8925 		dm_force_atomic_commit(&aconnector->base);
8926 }
8927 
8928 /*
8929  * Grabs all modesetting locks to serialize against any blocking commits,
8930  * Waits for completion of all non blocking commits.
8931  */
8932 static int do_aquire_global_lock(struct drm_device *dev,
8933 				 struct drm_atomic_state *state)
8934 {
8935 	struct drm_crtc *crtc;
8936 	struct drm_crtc_commit *commit;
8937 	long ret;
8938 
8939 	/*
8940 	 * Adding all modeset locks to aquire_ctx will
8941 	 * ensure that when the framework release it the
8942 	 * extra locks we are locking here will get released to
8943 	 */
8944 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8945 	if (ret)
8946 		return ret;
8947 
8948 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8949 		spin_lock(&crtc->commit_lock);
8950 		commit = list_first_entry_or_null(&crtc->commit_list,
8951 				struct drm_crtc_commit, commit_entry);
8952 		if (commit)
8953 			drm_crtc_commit_get(commit);
8954 		spin_unlock(&crtc->commit_lock);
8955 
8956 		if (!commit)
8957 			continue;
8958 
8959 		/*
8960 		 * Make sure all pending HW programming completed and
8961 		 * page flips done
8962 		 */
8963 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8964 
8965 		if (ret > 0)
8966 			ret = wait_for_completion_interruptible_timeout(
8967 					&commit->flip_done, 10*HZ);
8968 
8969 		if (ret == 0)
8970 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8971 				  "timed out\n", crtc->base.id, crtc->name);
8972 
8973 		drm_crtc_commit_put(commit);
8974 	}
8975 
8976 	return ret < 0 ? ret : 0;
8977 }
8978 
8979 static void get_freesync_config_for_crtc(
8980 	struct dm_crtc_state *new_crtc_state,
8981 	struct dm_connector_state *new_con_state)
8982 {
8983 	struct mod_freesync_config config = {0};
8984 	struct amdgpu_dm_connector *aconnector =
8985 			to_amdgpu_dm_connector(new_con_state->base.connector);
8986 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
8987 	int vrefresh = drm_mode_vrefresh(mode);
8988 	bool fs_vid_mode = false;
8989 
8990 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8991 					vrefresh >= aconnector->min_vfreq &&
8992 					vrefresh <= aconnector->max_vfreq;
8993 
8994 	if (new_crtc_state->vrr_supported) {
8995 		new_crtc_state->stream->ignore_msa_timing_param = true;
8996 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8997 
8998 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8999 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
9000 		config.vsif_supported = true;
9001 		config.btr = true;
9002 
9003 		if (fs_vid_mode) {
9004 			config.state = VRR_STATE_ACTIVE_FIXED;
9005 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
9006 			goto out;
9007 		} else if (new_crtc_state->base.vrr_enabled) {
9008 			config.state = VRR_STATE_ACTIVE_VARIABLE;
9009 		} else {
9010 			config.state = VRR_STATE_INACTIVE;
9011 		}
9012 	}
9013 out:
9014 	new_crtc_state->freesync_config = config;
9015 }
9016 
9017 static void reset_freesync_config_for_crtc(
9018 	struct dm_crtc_state *new_crtc_state)
9019 {
9020 	new_crtc_state->vrr_supported = false;
9021 
9022 	memset(&new_crtc_state->vrr_infopacket, 0,
9023 	       sizeof(new_crtc_state->vrr_infopacket));
9024 }
9025 
9026 static bool
9027 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
9028 				 struct drm_crtc_state *new_crtc_state)
9029 {
9030 	const struct drm_display_mode *old_mode, *new_mode;
9031 
9032 	if (!old_crtc_state || !new_crtc_state)
9033 		return false;
9034 
9035 	old_mode = &old_crtc_state->mode;
9036 	new_mode = &new_crtc_state->mode;
9037 
9038 	if (old_mode->clock       == new_mode->clock &&
9039 	    old_mode->hdisplay    == new_mode->hdisplay &&
9040 	    old_mode->vdisplay    == new_mode->vdisplay &&
9041 	    old_mode->htotal      == new_mode->htotal &&
9042 	    old_mode->vtotal      != new_mode->vtotal &&
9043 	    old_mode->hsync_start == new_mode->hsync_start &&
9044 	    old_mode->vsync_start != new_mode->vsync_start &&
9045 	    old_mode->hsync_end   == new_mode->hsync_end &&
9046 	    old_mode->vsync_end   != new_mode->vsync_end &&
9047 	    old_mode->hskew       == new_mode->hskew &&
9048 	    old_mode->vscan       == new_mode->vscan &&
9049 	    (old_mode->vsync_end - old_mode->vsync_start) ==
9050 	    (new_mode->vsync_end - new_mode->vsync_start))
9051 		return true;
9052 
9053 	return false;
9054 }
9055 
9056 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
9057 	u64 num, den, res;
9058 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
9059 
9060 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
9061 
9062 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
9063 	den = (unsigned long long)new_crtc_state->mode.htotal *
9064 	      (unsigned long long)new_crtc_state->mode.vtotal;
9065 
9066 	res = div_u64(num, den);
9067 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
9068 }
9069 
9070 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
9071 			 struct drm_atomic_state *state,
9072 			 struct drm_crtc *crtc,
9073 			 struct drm_crtc_state *old_crtc_state,
9074 			 struct drm_crtc_state *new_crtc_state,
9075 			 bool enable,
9076 			 bool *lock_and_validation_needed)
9077 {
9078 	struct dm_atomic_state *dm_state = NULL;
9079 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9080 	struct dc_stream_state *new_stream;
9081 	int ret = 0;
9082 
9083 	/*
9084 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
9085 	 * update changed items
9086 	 */
9087 	struct amdgpu_crtc *acrtc = NULL;
9088 	struct amdgpu_dm_connector *aconnector = NULL;
9089 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
9090 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
9091 
9092 	new_stream = NULL;
9093 
9094 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9095 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9096 	acrtc = to_amdgpu_crtc(crtc);
9097 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
9098 
9099 	/* TODO This hack should go away */
9100 	if (aconnector && enable) {
9101 		/* Make sure fake sink is created in plug-in scenario */
9102 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
9103 							    &aconnector->base);
9104 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
9105 							    &aconnector->base);
9106 
9107 		if (IS_ERR(drm_new_conn_state)) {
9108 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
9109 			goto fail;
9110 		}
9111 
9112 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
9113 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
9114 
9115 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9116 			goto skip_modeset;
9117 
9118 		new_stream = create_validate_stream_for_sink(aconnector,
9119 							     &new_crtc_state->mode,
9120 							     dm_new_conn_state,
9121 							     dm_old_crtc_state->stream);
9122 
9123 		/*
9124 		 * we can have no stream on ACTION_SET if a display
9125 		 * was disconnected during S3, in this case it is not an
9126 		 * error, the OS will be updated after detection, and
9127 		 * will do the right thing on next atomic commit
9128 		 */
9129 
9130 		if (!new_stream) {
9131 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
9132 					__func__, acrtc->base.base.id);
9133 			ret = -ENOMEM;
9134 			goto fail;
9135 		}
9136 
9137 		/*
9138 		 * TODO: Check VSDB bits to decide whether this should
9139 		 * be enabled or not.
9140 		 */
9141 		new_stream->triggered_crtc_reset.enabled =
9142 			dm->force_timing_sync;
9143 
9144 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9145 
9146 		ret = fill_hdr_info_packet(drm_new_conn_state,
9147 					   &new_stream->hdr_static_metadata);
9148 		if (ret)
9149 			goto fail;
9150 
9151 		/*
9152 		 * If we already removed the old stream from the context
9153 		 * (and set the new stream to NULL) then we can't reuse
9154 		 * the old stream even if the stream and scaling are unchanged.
9155 		 * We'll hit the BUG_ON and black screen.
9156 		 *
9157 		 * TODO: Refactor this function to allow this check to work
9158 		 * in all conditions.
9159 		 */
9160 		if (amdgpu_freesync_vid_mode &&
9161 		    dm_new_crtc_state->stream &&
9162 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
9163 			goto skip_modeset;
9164 
9165 		if (dm_new_crtc_state->stream &&
9166 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9167 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
9168 			new_crtc_state->mode_changed = false;
9169 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
9170 					 new_crtc_state->mode_changed);
9171 		}
9172 	}
9173 
9174 	/* mode_changed flag may get updated above, need to check again */
9175 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9176 		goto skip_modeset;
9177 
9178 	drm_dbg_state(state->dev,
9179 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
9180 		"planes_changed:%d, mode_changed:%d,active_changed:%d,"
9181 		"connectors_changed:%d\n",
9182 		acrtc->crtc_id,
9183 		new_crtc_state->enable,
9184 		new_crtc_state->active,
9185 		new_crtc_state->planes_changed,
9186 		new_crtc_state->mode_changed,
9187 		new_crtc_state->active_changed,
9188 		new_crtc_state->connectors_changed);
9189 
9190 	/* Remove stream for any changed/disabled CRTC */
9191 	if (!enable) {
9192 
9193 		if (!dm_old_crtc_state->stream)
9194 			goto skip_modeset;
9195 
9196 		/* Unset freesync video if it was active before */
9197 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
9198 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
9199 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
9200 		}
9201 
9202 		/* Now check if we should set freesync video mode */
9203 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
9204 		    is_timing_unchanged_for_freesync(new_crtc_state,
9205 						     old_crtc_state)) {
9206 			new_crtc_state->mode_changed = false;
9207 			DRM_DEBUG_DRIVER(
9208 				"Mode change not required for front porch change, "
9209 				"setting mode_changed to %d",
9210 				new_crtc_state->mode_changed);
9211 
9212 			set_freesync_fixed_config(dm_new_crtc_state);
9213 
9214 			goto skip_modeset;
9215 		} else if (amdgpu_freesync_vid_mode && aconnector &&
9216 			   is_freesync_video_mode(&new_crtc_state->mode,
9217 						  aconnector)) {
9218 			struct drm_display_mode *high_mode;
9219 
9220 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
9221 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
9222 				set_freesync_fixed_config(dm_new_crtc_state);
9223 			}
9224 		}
9225 
9226 		ret = dm_atomic_get_state(state, &dm_state);
9227 		if (ret)
9228 			goto fail;
9229 
9230 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
9231 				crtc->base.id);
9232 
9233 		/* i.e. reset mode */
9234 		if (dc_remove_stream_from_ctx(
9235 				dm->dc,
9236 				dm_state->context,
9237 				dm_old_crtc_state->stream) != DC_OK) {
9238 			ret = -EINVAL;
9239 			goto fail;
9240 		}
9241 
9242 		dc_stream_release(dm_old_crtc_state->stream);
9243 		dm_new_crtc_state->stream = NULL;
9244 
9245 		reset_freesync_config_for_crtc(dm_new_crtc_state);
9246 
9247 		*lock_and_validation_needed = true;
9248 
9249 	} else {/* Add stream for any updated/enabled CRTC */
9250 		/*
9251 		 * Quick fix to prevent NULL pointer on new_stream when
9252 		 * added MST connectors not found in existing crtc_state in the chained mode
9253 		 * TODO: need to dig out the root cause of that
9254 		 */
9255 		if (!aconnector)
9256 			goto skip_modeset;
9257 
9258 		if (modereset_required(new_crtc_state))
9259 			goto skip_modeset;
9260 
9261 		if (modeset_required(new_crtc_state, new_stream,
9262 				     dm_old_crtc_state->stream)) {
9263 
9264 			WARN_ON(dm_new_crtc_state->stream);
9265 
9266 			ret = dm_atomic_get_state(state, &dm_state);
9267 			if (ret)
9268 				goto fail;
9269 
9270 			dm_new_crtc_state->stream = new_stream;
9271 
9272 			dc_stream_retain(new_stream);
9273 
9274 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
9275 					 crtc->base.id);
9276 
9277 			if (dc_add_stream_to_ctx(
9278 					dm->dc,
9279 					dm_state->context,
9280 					dm_new_crtc_state->stream) != DC_OK) {
9281 				ret = -EINVAL;
9282 				goto fail;
9283 			}
9284 
9285 			*lock_and_validation_needed = true;
9286 		}
9287 	}
9288 
9289 skip_modeset:
9290 	/* Release extra reference */
9291 	if (new_stream)
9292 		 dc_stream_release(new_stream);
9293 
9294 	/*
9295 	 * We want to do dc stream updates that do not require a
9296 	 * full modeset below.
9297 	 */
9298 	if (!(enable && aconnector && new_crtc_state->active))
9299 		return 0;
9300 	/*
9301 	 * Given above conditions, the dc state cannot be NULL because:
9302 	 * 1. We're in the process of enabling CRTCs (just been added
9303 	 *    to the dc context, or already is on the context)
9304 	 * 2. Has a valid connector attached, and
9305 	 * 3. Is currently active and enabled.
9306 	 * => The dc stream state currently exists.
9307 	 */
9308 	BUG_ON(dm_new_crtc_state->stream == NULL);
9309 
9310 	/* Scaling or underscan settings */
9311 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
9312 				drm_atomic_crtc_needs_modeset(new_crtc_state))
9313 		update_stream_scaling_settings(
9314 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
9315 
9316 	/* ABM settings */
9317 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9318 
9319 	/*
9320 	 * Color management settings. We also update color properties
9321 	 * when a modeset is needed, to ensure it gets reprogrammed.
9322 	 */
9323 	if (dm_new_crtc_state->base.color_mgmt_changed ||
9324 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9325 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
9326 		if (ret)
9327 			goto fail;
9328 	}
9329 
9330 	/* Update Freesync settings. */
9331 	get_freesync_config_for_crtc(dm_new_crtc_state,
9332 				     dm_new_conn_state);
9333 
9334 	return ret;
9335 
9336 fail:
9337 	if (new_stream)
9338 		dc_stream_release(new_stream);
9339 	return ret;
9340 }
9341 
9342 static bool should_reset_plane(struct drm_atomic_state *state,
9343 			       struct drm_plane *plane,
9344 			       struct drm_plane_state *old_plane_state,
9345 			       struct drm_plane_state *new_plane_state)
9346 {
9347 	struct drm_plane *other;
9348 	struct drm_plane_state *old_other_state, *new_other_state;
9349 	struct drm_crtc_state *new_crtc_state;
9350 	int i;
9351 
9352 	/*
9353 	 * TODO: Remove this hack once the checks below are sufficient
9354 	 * enough to determine when we need to reset all the planes on
9355 	 * the stream.
9356 	 */
9357 	if (state->allow_modeset)
9358 		return true;
9359 
9360 	/* Exit early if we know that we're adding or removing the plane. */
9361 	if (old_plane_state->crtc != new_plane_state->crtc)
9362 		return true;
9363 
9364 	/* old crtc == new_crtc == NULL, plane not in context. */
9365 	if (!new_plane_state->crtc)
9366 		return false;
9367 
9368 	new_crtc_state =
9369 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
9370 
9371 	if (!new_crtc_state)
9372 		return true;
9373 
9374 	/* CRTC Degamma changes currently require us to recreate planes. */
9375 	if (new_crtc_state->color_mgmt_changed)
9376 		return true;
9377 
9378 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
9379 		return true;
9380 
9381 	/*
9382 	 * If there are any new primary or overlay planes being added or
9383 	 * removed then the z-order can potentially change. To ensure
9384 	 * correct z-order and pipe acquisition the current DC architecture
9385 	 * requires us to remove and recreate all existing planes.
9386 	 *
9387 	 * TODO: Come up with a more elegant solution for this.
9388 	 */
9389 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9390 		struct amdgpu_framebuffer *old_afb, *new_afb;
9391 		if (other->type == DRM_PLANE_TYPE_CURSOR)
9392 			continue;
9393 
9394 		if (old_other_state->crtc != new_plane_state->crtc &&
9395 		    new_other_state->crtc != new_plane_state->crtc)
9396 			continue;
9397 
9398 		if (old_other_state->crtc != new_other_state->crtc)
9399 			return true;
9400 
9401 		/* Src/dst size and scaling updates. */
9402 		if (old_other_state->src_w != new_other_state->src_w ||
9403 		    old_other_state->src_h != new_other_state->src_h ||
9404 		    old_other_state->crtc_w != new_other_state->crtc_w ||
9405 		    old_other_state->crtc_h != new_other_state->crtc_h)
9406 			return true;
9407 
9408 		/* Rotation / mirroring updates. */
9409 		if (old_other_state->rotation != new_other_state->rotation)
9410 			return true;
9411 
9412 		/* Blending updates. */
9413 		if (old_other_state->pixel_blend_mode !=
9414 		    new_other_state->pixel_blend_mode)
9415 			return true;
9416 
9417 		/* Alpha updates. */
9418 		if (old_other_state->alpha != new_other_state->alpha)
9419 			return true;
9420 
9421 		/* Colorspace changes. */
9422 		if (old_other_state->color_range != new_other_state->color_range ||
9423 		    old_other_state->color_encoding != new_other_state->color_encoding)
9424 			return true;
9425 
9426 		/* Framebuffer checks fall at the end. */
9427 		if (!old_other_state->fb || !new_other_state->fb)
9428 			continue;
9429 
9430 		/* Pixel format changes can require bandwidth updates. */
9431 		if (old_other_state->fb->format != new_other_state->fb->format)
9432 			return true;
9433 
9434 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9435 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9436 
9437 		/* Tiling and DCC changes also require bandwidth updates. */
9438 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
9439 		    old_afb->base.modifier != new_afb->base.modifier)
9440 			return true;
9441 	}
9442 
9443 	return false;
9444 }
9445 
9446 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9447 			      struct drm_plane_state *new_plane_state,
9448 			      struct drm_framebuffer *fb)
9449 {
9450 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9451 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9452 	unsigned int pitch;
9453 	bool linear;
9454 
9455 	if (fb->width > new_acrtc->max_cursor_width ||
9456 	    fb->height > new_acrtc->max_cursor_height) {
9457 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9458 				 new_plane_state->fb->width,
9459 				 new_plane_state->fb->height);
9460 		return -EINVAL;
9461 	}
9462 	if (new_plane_state->src_w != fb->width << 16 ||
9463 	    new_plane_state->src_h != fb->height << 16) {
9464 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9465 		return -EINVAL;
9466 	}
9467 
9468 	/* Pitch in pixels */
9469 	pitch = fb->pitches[0] / fb->format->cpp[0];
9470 
9471 	if (fb->width != pitch) {
9472 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9473 				 fb->width, pitch);
9474 		return -EINVAL;
9475 	}
9476 
9477 	switch (pitch) {
9478 	case 64:
9479 	case 128:
9480 	case 256:
9481 		/* FB pitch is supported by cursor plane */
9482 		break;
9483 	default:
9484 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9485 		return -EINVAL;
9486 	}
9487 
9488 	/* Core DRM takes care of checking FB modifiers, so we only need to
9489 	 * check tiling flags when the FB doesn't have a modifier. */
9490 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9491 		if (adev->family < AMDGPU_FAMILY_AI) {
9492 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9493 			         AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9494 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9495 		} else {
9496 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9497 		}
9498 		if (!linear) {
9499 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
9500 			return -EINVAL;
9501 		}
9502 	}
9503 
9504 	return 0;
9505 }
9506 
9507 static int dm_update_plane_state(struct dc *dc,
9508 				 struct drm_atomic_state *state,
9509 				 struct drm_plane *plane,
9510 				 struct drm_plane_state *old_plane_state,
9511 				 struct drm_plane_state *new_plane_state,
9512 				 bool enable,
9513 				 bool *lock_and_validation_needed)
9514 {
9515 
9516 	struct dm_atomic_state *dm_state = NULL;
9517 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9518 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9519 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9520 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9521 	struct amdgpu_crtc *new_acrtc;
9522 	bool needs_reset;
9523 	int ret = 0;
9524 
9525 
9526 	new_plane_crtc = new_plane_state->crtc;
9527 	old_plane_crtc = old_plane_state->crtc;
9528 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
9529 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
9530 
9531 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9532 		if (!enable || !new_plane_crtc ||
9533 			drm_atomic_plane_disabling(plane->state, new_plane_state))
9534 			return 0;
9535 
9536 		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9537 
9538 		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9539 			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9540 			return -EINVAL;
9541 		}
9542 
9543 		if (new_plane_state->fb) {
9544 			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9545 						 new_plane_state->fb);
9546 			if (ret)
9547 				return ret;
9548 		}
9549 
9550 		return 0;
9551 	}
9552 
9553 	needs_reset = should_reset_plane(state, plane, old_plane_state,
9554 					 new_plane_state);
9555 
9556 	/* Remove any changed/removed planes */
9557 	if (!enable) {
9558 		if (!needs_reset)
9559 			return 0;
9560 
9561 		if (!old_plane_crtc)
9562 			return 0;
9563 
9564 		old_crtc_state = drm_atomic_get_old_crtc_state(
9565 				state, old_plane_crtc);
9566 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9567 
9568 		if (!dm_old_crtc_state->stream)
9569 			return 0;
9570 
9571 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9572 				plane->base.id, old_plane_crtc->base.id);
9573 
9574 		ret = dm_atomic_get_state(state, &dm_state);
9575 		if (ret)
9576 			return ret;
9577 
9578 		if (!dc_remove_plane_from_context(
9579 				dc,
9580 				dm_old_crtc_state->stream,
9581 				dm_old_plane_state->dc_state,
9582 				dm_state->context)) {
9583 
9584 			return -EINVAL;
9585 		}
9586 
9587 
9588 		dc_plane_state_release(dm_old_plane_state->dc_state);
9589 		dm_new_plane_state->dc_state = NULL;
9590 
9591 		*lock_and_validation_needed = true;
9592 
9593 	} else { /* Add new planes */
9594 		struct dc_plane_state *dc_new_plane_state;
9595 
9596 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9597 			return 0;
9598 
9599 		if (!new_plane_crtc)
9600 			return 0;
9601 
9602 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9603 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9604 
9605 		if (!dm_new_crtc_state->stream)
9606 			return 0;
9607 
9608 		if (!needs_reset)
9609 			return 0;
9610 
9611 		ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9612 		if (ret)
9613 			return ret;
9614 
9615 		WARN_ON(dm_new_plane_state->dc_state);
9616 
9617 		dc_new_plane_state = dc_create_plane_state(dc);
9618 		if (!dc_new_plane_state)
9619 			return -ENOMEM;
9620 
9621 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9622 				 plane->base.id, new_plane_crtc->base.id);
9623 
9624 		ret = fill_dc_plane_attributes(
9625 			drm_to_adev(new_plane_crtc->dev),
9626 			dc_new_plane_state,
9627 			new_plane_state,
9628 			new_crtc_state);
9629 		if (ret) {
9630 			dc_plane_state_release(dc_new_plane_state);
9631 			return ret;
9632 		}
9633 
9634 		ret = dm_atomic_get_state(state, &dm_state);
9635 		if (ret) {
9636 			dc_plane_state_release(dc_new_plane_state);
9637 			return ret;
9638 		}
9639 
9640 		/*
9641 		 * Any atomic check errors that occur after this will
9642 		 * not need a release. The plane state will be attached
9643 		 * to the stream, and therefore part of the atomic
9644 		 * state. It'll be released when the atomic state is
9645 		 * cleaned.
9646 		 */
9647 		if (!dc_add_plane_to_context(
9648 				dc,
9649 				dm_new_crtc_state->stream,
9650 				dc_new_plane_state,
9651 				dm_state->context)) {
9652 
9653 			dc_plane_state_release(dc_new_plane_state);
9654 			return -EINVAL;
9655 		}
9656 
9657 		dm_new_plane_state->dc_state = dc_new_plane_state;
9658 
9659 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9660 
9661 		/* Tell DC to do a full surface update every time there
9662 		 * is a plane change. Inefficient, but works for now.
9663 		 */
9664 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9665 
9666 		*lock_and_validation_needed = true;
9667 	}
9668 
9669 
9670 	return ret;
9671 }
9672 
9673 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9674 				       int *src_w, int *src_h)
9675 {
9676 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9677 	case DRM_MODE_ROTATE_90:
9678 	case DRM_MODE_ROTATE_270:
9679 		*src_w = plane_state->src_h >> 16;
9680 		*src_h = plane_state->src_w >> 16;
9681 		break;
9682 	case DRM_MODE_ROTATE_0:
9683 	case DRM_MODE_ROTATE_180:
9684 	default:
9685 		*src_w = plane_state->src_w >> 16;
9686 		*src_h = plane_state->src_h >> 16;
9687 		break;
9688 	}
9689 }
9690 
9691 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9692 				struct drm_crtc *crtc,
9693 				struct drm_crtc_state *new_crtc_state)
9694 {
9695 	struct drm_plane *cursor = crtc->cursor, *underlying;
9696 	struct drm_plane_state *new_cursor_state, *new_underlying_state;
9697 	int i;
9698 	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9699 	int cursor_src_w, cursor_src_h;
9700 	int underlying_src_w, underlying_src_h;
9701 
9702 	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9703 	 * cursor per pipe but it's going to inherit the scaling and
9704 	 * positioning from the underlying pipe. Check the cursor plane's
9705 	 * blending properties match the underlying planes'. */
9706 
9707 	new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9708 	if (!new_cursor_state || !new_cursor_state->fb) {
9709 		return 0;
9710 	}
9711 
9712 	dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9713 	cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9714 	cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9715 
9716 	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9717 		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
9718 		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9719 			continue;
9720 
9721 		/* Ignore disabled planes */
9722 		if (!new_underlying_state->fb)
9723 			continue;
9724 
9725 		dm_get_oriented_plane_size(new_underlying_state,
9726 					   &underlying_src_w, &underlying_src_h);
9727 		underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9728 		underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9729 
9730 		if (cursor_scale_w != underlying_scale_w ||
9731 		    cursor_scale_h != underlying_scale_h) {
9732 			drm_dbg_atomic(crtc->dev,
9733 				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9734 				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9735 			return -EINVAL;
9736 		}
9737 
9738 		/* If this plane covers the whole CRTC, no need to check planes underneath */
9739 		if (new_underlying_state->crtc_x <= 0 &&
9740 		    new_underlying_state->crtc_y <= 0 &&
9741 		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9742 		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9743 			break;
9744 	}
9745 
9746 	return 0;
9747 }
9748 
9749 #if defined(CONFIG_DRM_AMD_DC_DCN)
9750 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9751 {
9752 	struct drm_connector *connector;
9753 	struct drm_connector_state *conn_state, *old_conn_state;
9754 	struct amdgpu_dm_connector *aconnector = NULL;
9755 	int i;
9756 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9757 		if (!conn_state->crtc)
9758 			conn_state = old_conn_state;
9759 
9760 		if (conn_state->crtc != crtc)
9761 			continue;
9762 
9763 		aconnector = to_amdgpu_dm_connector(connector);
9764 		if (!aconnector->mst_output_port || !aconnector->mst_root)
9765 			aconnector = NULL;
9766 		else
9767 			break;
9768 	}
9769 
9770 	if (!aconnector)
9771 		return 0;
9772 
9773 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
9774 }
9775 #endif
9776 
9777 /**
9778  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9779  *
9780  * @dev: The DRM device
9781  * @state: The atomic state to commit
9782  *
9783  * Validate that the given atomic state is programmable by DC into hardware.
9784  * This involves constructing a &struct dc_state reflecting the new hardware
9785  * state we wish to commit, then querying DC to see if it is programmable. It's
9786  * important not to modify the existing DC state. Otherwise, atomic_check
9787  * may unexpectedly commit hardware changes.
9788  *
9789  * When validating the DC state, it's important that the right locks are
9790  * acquired. For full updates case which removes/adds/updates streams on one
9791  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9792  * that any such full update commit will wait for completion of any outstanding
9793  * flip using DRMs synchronization events.
9794  *
9795  * Note that DM adds the affected connectors for all CRTCs in state, when that
9796  * might not seem necessary. This is because DC stream creation requires the
9797  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9798  * be possible but non-trivial - a possible TODO item.
9799  *
9800  * Return: -Error code if validation failed.
9801  */
9802 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9803 				  struct drm_atomic_state *state)
9804 {
9805 	struct amdgpu_device *adev = drm_to_adev(dev);
9806 	struct dm_atomic_state *dm_state = NULL;
9807 	struct dc *dc = adev->dm.dc;
9808 	struct drm_connector *connector;
9809 	struct drm_connector_state *old_con_state, *new_con_state;
9810 	struct drm_crtc *crtc;
9811 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9812 	struct drm_plane *plane;
9813 	struct drm_plane_state *old_plane_state, *new_plane_state;
9814 	enum dc_status status;
9815 	int ret, i;
9816 	bool lock_and_validation_needed = false;
9817 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9818 #if defined(CONFIG_DRM_AMD_DC_DCN)
9819 	struct drm_dp_mst_topology_mgr *mgr;
9820 	struct drm_dp_mst_topology_state *mst_state;
9821 	struct dsc_mst_fairness_vars vars[MAX_PIPES];
9822 #endif
9823 
9824 	trace_amdgpu_dm_atomic_check_begin(state);
9825 
9826 	ret = drm_atomic_helper_check_modeset(dev, state);
9827 	if (ret) {
9828 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9829 		goto fail;
9830 	}
9831 
9832 	/* Check connector changes */
9833 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9834 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9835 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9836 
9837 		/* Skip connectors that are disabled or part of modeset already. */
9838 		if (!new_con_state->crtc)
9839 			continue;
9840 
9841 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9842 		if (IS_ERR(new_crtc_state)) {
9843 			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9844 			ret = PTR_ERR(new_crtc_state);
9845 			goto fail;
9846 		}
9847 
9848 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
9849 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
9850 			new_crtc_state->connectors_changed = true;
9851 	}
9852 
9853 #if defined(CONFIG_DRM_AMD_DC_DCN)
9854 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9855 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9856 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9857 				ret = add_affected_mst_dsc_crtcs(state, crtc);
9858 				if (ret) {
9859 					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9860 					goto fail;
9861 				}
9862 			}
9863 		}
9864 	}
9865 #endif
9866 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9867 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9868 
9869 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9870 		    !new_crtc_state->color_mgmt_changed &&
9871 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9872 			dm_old_crtc_state->dsc_force_changed == false)
9873 			continue;
9874 
9875 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9876 		if (ret) {
9877 			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9878 			goto fail;
9879 		}
9880 
9881 		if (!new_crtc_state->enable)
9882 			continue;
9883 
9884 		ret = drm_atomic_add_affected_connectors(state, crtc);
9885 		if (ret) {
9886 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9887 			goto fail;
9888 		}
9889 
9890 		ret = drm_atomic_add_affected_planes(state, crtc);
9891 		if (ret) {
9892 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9893 			goto fail;
9894 		}
9895 
9896 		if (dm_old_crtc_state->dsc_force_changed)
9897 			new_crtc_state->mode_changed = true;
9898 	}
9899 
9900 	/*
9901 	 * Add all primary and overlay planes on the CRTC to the state
9902 	 * whenever a plane is enabled to maintain correct z-ordering
9903 	 * and to enable fast surface updates.
9904 	 */
9905 	drm_for_each_crtc(crtc, dev) {
9906 		bool modified = false;
9907 
9908 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9909 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9910 				continue;
9911 
9912 			if (new_plane_state->crtc == crtc ||
9913 			    old_plane_state->crtc == crtc) {
9914 				modified = true;
9915 				break;
9916 			}
9917 		}
9918 
9919 		if (!modified)
9920 			continue;
9921 
9922 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9923 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9924 				continue;
9925 
9926 			new_plane_state =
9927 				drm_atomic_get_plane_state(state, plane);
9928 
9929 			if (IS_ERR(new_plane_state)) {
9930 				ret = PTR_ERR(new_plane_state);
9931 				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9932 				goto fail;
9933 			}
9934 		}
9935 	}
9936 
9937 	/*
9938 	 * DC consults the zpos (layer_index in DC terminology) to determine the
9939 	 * hw plane on which to enable the hw cursor (see
9940 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9941 	 * atomic state, so call drm helper to normalize zpos.
9942 	 */
9943 	drm_atomic_normalize_zpos(dev, state);
9944 
9945 	/* Remove exiting planes if they are modified */
9946 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9947 		ret = dm_update_plane_state(dc, state, plane,
9948 					    old_plane_state,
9949 					    new_plane_state,
9950 					    false,
9951 					    &lock_and_validation_needed);
9952 		if (ret) {
9953 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9954 			goto fail;
9955 		}
9956 	}
9957 
9958 	/* Disable all crtcs which require disable */
9959 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9960 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9961 					   old_crtc_state,
9962 					   new_crtc_state,
9963 					   false,
9964 					   &lock_and_validation_needed);
9965 		if (ret) {
9966 			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9967 			goto fail;
9968 		}
9969 	}
9970 
9971 	/* Enable all crtcs which require enable */
9972 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9973 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9974 					   old_crtc_state,
9975 					   new_crtc_state,
9976 					   true,
9977 					   &lock_and_validation_needed);
9978 		if (ret) {
9979 			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9980 			goto fail;
9981 		}
9982 	}
9983 
9984 	/* Add new/modified planes */
9985 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9986 		ret = dm_update_plane_state(dc, state, plane,
9987 					    old_plane_state,
9988 					    new_plane_state,
9989 					    true,
9990 					    &lock_and_validation_needed);
9991 		if (ret) {
9992 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9993 			goto fail;
9994 		}
9995 	}
9996 
9997 #if defined(CONFIG_DRM_AMD_DC_DCN)
9998 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9999 		ret = pre_validate_dsc(state, &dm_state, vars);
10000 		if (ret != 0)
10001 			goto fail;
10002 	}
10003 #endif
10004 
10005 	/* Run this here since we want to validate the streams we created */
10006 	ret = drm_atomic_helper_check_planes(dev, state);
10007 	if (ret) {
10008 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
10009 		goto fail;
10010 	}
10011 
10012 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10013 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10014 		if (dm_new_crtc_state->mpo_requested)
10015 			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
10016 	}
10017 
10018 	/* Check cursor planes scaling */
10019 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10020 		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
10021 		if (ret) {
10022 			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
10023 			goto fail;
10024 		}
10025 	}
10026 
10027 	if (state->legacy_cursor_update) {
10028 		/*
10029 		 * This is a fast cursor update coming from the plane update
10030 		 * helper, check if it can be done asynchronously for better
10031 		 * performance.
10032 		 */
10033 		state->async_update =
10034 			!drm_atomic_helper_async_check(dev, state);
10035 
10036 		/*
10037 		 * Skip the remaining global validation if this is an async
10038 		 * update. Cursor updates can be done without affecting
10039 		 * state or bandwidth calcs and this avoids the performance
10040 		 * penalty of locking the private state object and
10041 		 * allocating a new dc_state.
10042 		 */
10043 		if (state->async_update)
10044 			return 0;
10045 	}
10046 
10047 	/* Check scaling and underscan changes*/
10048 	/* TODO Removed scaling changes validation due to inability to commit
10049 	 * new stream into context w\o causing full reset. Need to
10050 	 * decide how to handle.
10051 	 */
10052 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10053 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10054 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10055 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10056 
10057 		/* Skip any modesets/resets */
10058 		if (!acrtc || drm_atomic_crtc_needs_modeset(
10059 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
10060 			continue;
10061 
10062 		/* Skip any thing not scale or underscan changes */
10063 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
10064 			continue;
10065 
10066 		lock_and_validation_needed = true;
10067 	}
10068 
10069 #if defined(CONFIG_DRM_AMD_DC_DCN)
10070 	/* set the slot info for each mst_state based on the link encoding format */
10071 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
10072 		struct amdgpu_dm_connector *aconnector;
10073 		struct drm_connector *connector;
10074 		struct drm_connector_list_iter iter;
10075 		u8 link_coding_cap;
10076 
10077 		drm_connector_list_iter_begin(dev, &iter);
10078 		drm_for_each_connector_iter(connector, &iter) {
10079 			if (connector->index == mst_state->mgr->conn_base_id) {
10080 				aconnector = to_amdgpu_dm_connector(connector);
10081 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
10082 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
10083 
10084 				break;
10085 			}
10086 		}
10087 		drm_connector_list_iter_end(&iter);
10088 	}
10089 #endif
10090 
10091 	/**
10092 	 * Streams and planes are reset when there are changes that affect
10093 	 * bandwidth. Anything that affects bandwidth needs to go through
10094 	 * DC global validation to ensure that the configuration can be applied
10095 	 * to hardware.
10096 	 *
10097 	 * We have to currently stall out here in atomic_check for outstanding
10098 	 * commits to finish in this case because our IRQ handlers reference
10099 	 * DRM state directly - we can end up disabling interrupts too early
10100 	 * if we don't.
10101 	 *
10102 	 * TODO: Remove this stall and drop DM state private objects.
10103 	 */
10104 	if (lock_and_validation_needed) {
10105 		ret = dm_atomic_get_state(state, &dm_state);
10106 		if (ret) {
10107 			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
10108 			goto fail;
10109 		}
10110 
10111 		ret = do_aquire_global_lock(dev, state);
10112 		if (ret) {
10113 			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
10114 			goto fail;
10115 		}
10116 
10117 #if defined(CONFIG_DRM_AMD_DC_DCN)
10118 		ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
10119 		if (ret) {
10120 			DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
10121 			goto fail;
10122 		}
10123 
10124 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
10125 		if (ret) {
10126 			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
10127 			goto fail;
10128 		}
10129 #endif
10130 
10131 		/*
10132 		 * Perform validation of MST topology in the state:
10133 		 * We need to perform MST atomic check before calling
10134 		 * dc_validate_global_state(), or there is a chance
10135 		 * to get stuck in an infinite loop and hang eventually.
10136 		 */
10137 		ret = drm_dp_mst_atomic_check(state);
10138 		if (ret) {
10139 			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
10140 			goto fail;
10141 		}
10142 		status = dc_validate_global_state(dc, dm_state->context, true);
10143 		if (status != DC_OK) {
10144 			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
10145 				       dc_status_to_str(status), status);
10146 			ret = -EINVAL;
10147 			goto fail;
10148 		}
10149 	} else {
10150 		/*
10151 		 * The commit is a fast update. Fast updates shouldn't change
10152 		 * the DC context, affect global validation, and can have their
10153 		 * commit work done in parallel with other commits not touching
10154 		 * the same resource. If we have a new DC context as part of
10155 		 * the DM atomic state from validation we need to free it and
10156 		 * retain the existing one instead.
10157 		 *
10158 		 * Furthermore, since the DM atomic state only contains the DC
10159 		 * context and can safely be annulled, we can free the state
10160 		 * and clear the associated private object now to free
10161 		 * some memory and avoid a possible use-after-free later.
10162 		 */
10163 
10164 		for (i = 0; i < state->num_private_objs; i++) {
10165 			struct drm_private_obj *obj = state->private_objs[i].ptr;
10166 
10167 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
10168 				int j = state->num_private_objs-1;
10169 
10170 				dm_atomic_destroy_state(obj,
10171 						state->private_objs[i].state);
10172 
10173 				/* If i is not at the end of the array then the
10174 				 * last element needs to be moved to where i was
10175 				 * before the array can safely be truncated.
10176 				 */
10177 				if (i != j)
10178 					state->private_objs[i] =
10179 						state->private_objs[j];
10180 
10181 				state->private_objs[j].ptr = NULL;
10182 				state->private_objs[j].state = NULL;
10183 				state->private_objs[j].old_state = NULL;
10184 				state->private_objs[j].new_state = NULL;
10185 
10186 				state->num_private_objs = j;
10187 				break;
10188 			}
10189 		}
10190 	}
10191 
10192 	/* Store the overall update type for use later in atomic check. */
10193 	for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
10194 		struct dm_crtc_state *dm_new_crtc_state =
10195 			to_dm_crtc_state(new_crtc_state);
10196 
10197 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
10198 							 UPDATE_TYPE_FULL :
10199 							 UPDATE_TYPE_FAST;
10200 	}
10201 
10202 	/* Must be success */
10203 	WARN_ON(ret);
10204 
10205 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10206 
10207 	return ret;
10208 
10209 fail:
10210 	if (ret == -EDEADLK)
10211 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10212 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10213 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10214 	else
10215 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
10216 
10217 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10218 
10219 	return ret;
10220 }
10221 
10222 static bool is_dp_capable_without_timing_msa(struct dc *dc,
10223 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
10224 {
10225 	u8 dpcd_data;
10226 	bool capable = false;
10227 
10228 	if (amdgpu_dm_connector->dc_link &&
10229 		dm_helpers_dp_read_dpcd(
10230 				NULL,
10231 				amdgpu_dm_connector->dc_link,
10232 				DP_DOWN_STREAM_PORT_COUNT,
10233 				&dpcd_data,
10234 				sizeof(dpcd_data))) {
10235 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10236 	}
10237 
10238 	return capable;
10239 }
10240 
10241 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10242 		unsigned int offset,
10243 		unsigned int total_length,
10244 		u8 *data,
10245 		unsigned int length,
10246 		struct amdgpu_hdmi_vsdb_info *vsdb)
10247 {
10248 	bool res;
10249 	union dmub_rb_cmd cmd;
10250 	struct dmub_cmd_send_edid_cea *input;
10251 	struct dmub_cmd_edid_cea_output *output;
10252 
10253 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10254 		return false;
10255 
10256 	memset(&cmd, 0, sizeof(cmd));
10257 
10258 	input = &cmd.edid_cea.data.input;
10259 
10260 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10261 	cmd.edid_cea.header.sub_type = 0;
10262 	cmd.edid_cea.header.payload_bytes =
10263 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10264 	input->offset = offset;
10265 	input->length = length;
10266 	input->cea_total_length = total_length;
10267 	memcpy(input->payload, data, length);
10268 
10269 	res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
10270 	if (!res) {
10271 		DRM_ERROR("EDID CEA parser failed\n");
10272 		return false;
10273 	}
10274 
10275 	output = &cmd.edid_cea.data.output;
10276 
10277 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10278 		if (!output->ack.success) {
10279 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
10280 					output->ack.offset);
10281 		}
10282 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10283 		if (!output->amd_vsdb.vsdb_found)
10284 			return false;
10285 
10286 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10287 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10288 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10289 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10290 	} else {
10291 		DRM_WARN("Unknown EDID CEA parser results\n");
10292 		return false;
10293 	}
10294 
10295 	return true;
10296 }
10297 
10298 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10299 		u8 *edid_ext, int len,
10300 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10301 {
10302 	int i;
10303 
10304 	/* send extension block to DMCU for parsing */
10305 	for (i = 0; i < len; i += 8) {
10306 		bool res;
10307 		int offset;
10308 
10309 		/* send 8 bytes a time */
10310 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10311 			return false;
10312 
10313 		if (i+8 == len) {
10314 			/* EDID block sent completed, expect result */
10315 			int version, min_rate, max_rate;
10316 
10317 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10318 			if (res) {
10319 				/* amd vsdb found */
10320 				vsdb_info->freesync_supported = 1;
10321 				vsdb_info->amd_vsdb_version = version;
10322 				vsdb_info->min_refresh_rate_hz = min_rate;
10323 				vsdb_info->max_refresh_rate_hz = max_rate;
10324 				return true;
10325 			}
10326 			/* not amd vsdb */
10327 			return false;
10328 		}
10329 
10330 		/* check for ack*/
10331 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10332 		if (!res)
10333 			return false;
10334 	}
10335 
10336 	return false;
10337 }
10338 
10339 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10340 		u8 *edid_ext, int len,
10341 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10342 {
10343 	int i;
10344 
10345 	/* send extension block to DMCU for parsing */
10346 	for (i = 0; i < len; i += 8) {
10347 		/* send 8 bytes a time */
10348 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10349 			return false;
10350 	}
10351 
10352 	return vsdb_info->freesync_supported;
10353 }
10354 
10355 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
10356 		u8 *edid_ext, int len,
10357 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10358 {
10359 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
10360 	bool ret;
10361 
10362 	mutex_lock(&adev->dm.dc_lock);
10363 	if (adev->dm.dmub_srv)
10364 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
10365 	else
10366 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
10367 	mutex_unlock(&adev->dm.dc_lock);
10368 	return ret;
10369 }
10370 
10371 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
10372 		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
10373 {
10374 	u8 *edid_ext = NULL;
10375 	int i;
10376 	bool valid_vsdb_found = false;
10377 
10378 	/*----- drm_find_cea_extension() -----*/
10379 	/* No EDID or EDID extensions */
10380 	if (edid == NULL || edid->extensions == 0)
10381 		return -ENODEV;
10382 
10383 	/* Find CEA extension */
10384 	for (i = 0; i < edid->extensions; i++) {
10385 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
10386 		if (edid_ext[0] == CEA_EXT)
10387 			break;
10388 	}
10389 
10390 	if (i == edid->extensions)
10391 		return -ENODEV;
10392 
10393 	/*----- cea_db_offsets() -----*/
10394 	if (edid_ext[0] != CEA_EXT)
10395 		return -ENODEV;
10396 
10397 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
10398 
10399 	return valid_vsdb_found ? i : -ENODEV;
10400 }
10401 
10402 /**
10403  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
10404  *
10405  * @connector: Connector to query.
10406  * @edid: EDID from monitor
10407  *
10408  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
10409  * track of some of the display information in the internal data struct used by
10410  * amdgpu_dm. This function checks which type of connector we need to set the
10411  * FreeSync parameters.
10412  */
10413 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
10414 				    struct edid *edid)
10415 {
10416 	int i = 0;
10417 	struct detailed_timing *timing;
10418 	struct detailed_non_pixel *data;
10419 	struct detailed_data_monitor_range *range;
10420 	struct amdgpu_dm_connector *amdgpu_dm_connector =
10421 			to_amdgpu_dm_connector(connector);
10422 	struct dm_connector_state *dm_con_state = NULL;
10423 	struct dc_sink *sink;
10424 
10425 	struct drm_device *dev = connector->dev;
10426 	struct amdgpu_device *adev = drm_to_adev(dev);
10427 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10428 	bool freesync_capable = false;
10429 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
10430 
10431 	if (!connector->state) {
10432 		DRM_ERROR("%s - Connector has no state", __func__);
10433 		goto update;
10434 	}
10435 
10436 	sink = amdgpu_dm_connector->dc_sink ?
10437 		amdgpu_dm_connector->dc_sink :
10438 		amdgpu_dm_connector->dc_em_sink;
10439 
10440 	if (!edid || !sink) {
10441 		dm_con_state = to_dm_connector_state(connector->state);
10442 
10443 		amdgpu_dm_connector->min_vfreq = 0;
10444 		amdgpu_dm_connector->max_vfreq = 0;
10445 		amdgpu_dm_connector->pixel_clock_mhz = 0;
10446 		connector->display_info.monitor_range.min_vfreq = 0;
10447 		connector->display_info.monitor_range.max_vfreq = 0;
10448 		freesync_capable = false;
10449 
10450 		goto update;
10451 	}
10452 
10453 	dm_con_state = to_dm_connector_state(connector->state);
10454 
10455 	if (!adev->dm.freesync_module)
10456 		goto update;
10457 
10458 	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10459 		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
10460 		bool edid_check_required = false;
10461 
10462 		if (edid) {
10463 			edid_check_required = is_dp_capable_without_timing_msa(
10464 						adev->dm.dc,
10465 						amdgpu_dm_connector);
10466 		}
10467 
10468 		if (edid_check_required == true && (edid->version > 1 ||
10469 		   (edid->version == 1 && edid->revision > 1))) {
10470 			for (i = 0; i < 4; i++) {
10471 
10472 				timing	= &edid->detailed_timings[i];
10473 				data	= &timing->data.other_data;
10474 				range	= &data->data.range;
10475 				/*
10476 				 * Check if monitor has continuous frequency mode
10477 				 */
10478 				if (data->type != EDID_DETAIL_MONITOR_RANGE)
10479 					continue;
10480 				/*
10481 				 * Check for flag range limits only. If flag == 1 then
10482 				 * no additional timing information provided.
10483 				 * Default GTF, GTF Secondary curve and CVT are not
10484 				 * supported
10485 				 */
10486 				if (range->flags != 1)
10487 					continue;
10488 
10489 				amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10490 				amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10491 				amdgpu_dm_connector->pixel_clock_mhz =
10492 					range->pixel_clock_mhz * 10;
10493 
10494 				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10495 				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10496 
10497 				break;
10498 			}
10499 
10500 			if (amdgpu_dm_connector->max_vfreq -
10501 			    amdgpu_dm_connector->min_vfreq > 10) {
10502 
10503 				freesync_capable = true;
10504 			}
10505 		}
10506 	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10507 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10508 		if (i >= 0 && vsdb_info.freesync_supported) {
10509 			timing  = &edid->detailed_timings[i];
10510 			data    = &timing->data.other_data;
10511 
10512 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10513 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10514 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10515 				freesync_capable = true;
10516 
10517 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10518 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10519 		}
10520 	}
10521 
10522 	as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
10523 
10524 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
10525 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10526 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
10527 
10528 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
10529 			amdgpu_dm_connector->as_type = as_type;
10530 			amdgpu_dm_connector->vsdb_info = vsdb_info;
10531 
10532 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10533 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10534 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10535 				freesync_capable = true;
10536 
10537 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10538 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10539 		}
10540 	}
10541 
10542 update:
10543 	if (dm_con_state)
10544 		dm_con_state->freesync_capable = freesync_capable;
10545 
10546 	if (connector->vrr_capable_property)
10547 		drm_connector_set_vrr_capable_property(connector,
10548 						       freesync_capable);
10549 }
10550 
10551 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10552 {
10553 	struct amdgpu_device *adev = drm_to_adev(dev);
10554 	struct dc *dc = adev->dm.dc;
10555 	int i;
10556 
10557 	mutex_lock(&adev->dm.dc_lock);
10558 	if (dc->current_state) {
10559 		for (i = 0; i < dc->current_state->stream_count; ++i)
10560 			dc->current_state->streams[i]
10561 				->triggered_crtc_reset.enabled =
10562 				adev->dm.force_timing_sync;
10563 
10564 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
10565 		dc_trigger_sync(dc, dc->current_state);
10566 	}
10567 	mutex_unlock(&adev->dm.dc_lock);
10568 }
10569 
10570 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10571 		       u32 value, const char *func_name)
10572 {
10573 #ifdef DM_CHECK_ADDR_0
10574 	if (address == 0) {
10575 		DC_ERR("invalid register write. address = 0");
10576 		return;
10577 	}
10578 #endif
10579 	cgs_write_register(ctx->cgs_device, address, value);
10580 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10581 }
10582 
10583 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10584 			  const char *func_name)
10585 {
10586 	u32 value;
10587 #ifdef DM_CHECK_ADDR_0
10588 	if (address == 0) {
10589 		DC_ERR("invalid register read; address = 0\n");
10590 		return 0;
10591 	}
10592 #endif
10593 
10594 	if (ctx->dmub_srv &&
10595 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10596 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10597 		ASSERT(false);
10598 		return 0;
10599 	}
10600 
10601 	value = cgs_read_register(ctx->cgs_device, address);
10602 
10603 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10604 
10605 	return value;
10606 }
10607 
10608 int amdgpu_dm_process_dmub_aux_transfer_sync(
10609 		struct dc_context *ctx,
10610 		unsigned int link_index,
10611 		struct aux_payload *payload,
10612 		enum aux_return_code_type *operation_result)
10613 {
10614 	struct amdgpu_device *adev = ctx->driver_context;
10615 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
10616 	int ret = -1;
10617 
10618 	mutex_lock(&adev->dm.dpia_aux_lock);
10619 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
10620 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10621 		goto out;
10622  	}
10623 
10624 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10625 		DRM_ERROR("wait_for_completion_timeout timeout!");
10626 		*operation_result = AUX_RET_ERROR_TIMEOUT;
10627 		goto out;
10628 	}
10629 
10630 	if (p_notify->result != AUX_RET_SUCCESS) {
10631 		/*
10632 		 * Transient states before tunneling is enabled could
10633 		 * lead to this error. We can ignore this for now.
10634 		 */
10635 		if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
10636 			DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
10637 					payload->address, payload->length,
10638 					p_notify->result);
10639 		}
10640 		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10641 		goto out;
10642 	}
10643 
10644 
10645 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10646 	if (!payload->write && p_notify->aux_reply.length &&
10647 			(payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
10648 
10649 		if (payload->length != p_notify->aux_reply.length) {
10650 			DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
10651 				p_notify->aux_reply.length,
10652 					payload->address, payload->length);
10653 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10654 			goto out;
10655 		}
10656 
10657 		memcpy(payload->data, p_notify->aux_reply.data,
10658 				p_notify->aux_reply.length);
10659 	}
10660 
10661 	/* success */
10662 	ret = p_notify->aux_reply.length;
10663 	*operation_result = p_notify->result;
10664 out:
10665 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
10666 	mutex_unlock(&adev->dm.dpia_aux_lock);
10667 	return ret;
10668 }
10669 
10670 int amdgpu_dm_process_dmub_set_config_sync(
10671 		struct dc_context *ctx,
10672 		unsigned int link_index,
10673 		struct set_config_cmd_payload *payload,
10674 		enum set_config_status *operation_result)
10675 {
10676 	struct amdgpu_device *adev = ctx->driver_context;
10677 	bool is_cmd_complete;
10678 	int ret;
10679 
10680 	mutex_lock(&adev->dm.dpia_aux_lock);
10681 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
10682 			link_index, payload, adev->dm.dmub_notify);
10683 
10684 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10685 		ret = 0;
10686 		*operation_result = adev->dm.dmub_notify->sc_status;
10687 	} else {
10688 		DRM_ERROR("wait_for_completion_timeout timeout!");
10689 		ret = -1;
10690 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
10691 	}
10692 
10693 	if (!is_cmd_complete)
10694 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
10695 	mutex_unlock(&adev->dm.dpia_aux_lock);
10696 	return ret;
10697 }
10698 
10699 /*
10700  * Check whether seamless boot is supported.
10701  *
10702  * So far we only support seamless boot on CHIP_VANGOGH.
10703  * If everything goes well, we may consider expanding
10704  * seamless boot to other ASICs.
10705  */
10706 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10707 {
10708 	switch (adev->ip_versions[DCE_HWIP][0]) {
10709 	case IP_VERSION(3, 0, 1):
10710 		if (!adev->mman.keep_stolen_vga_memory)
10711 			return true;
10712 		break;
10713 	default:
10714 		break;
10715 	}
10716 
10717 	return false;
10718 }
10719