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