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