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