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