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