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