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