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