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