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