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