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