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