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