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