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