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