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