xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision e825f56c4ed166fc7be8a70531ea6edda8a665fc)
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/backlight.h>
71 #include <linux/module.h>
72 #include <linux/moduleparam.h>
73 #include <linux/types.h>
74 #include <linux/pm_runtime.h>
75 #include <linux/pci.h>
76 #include <linux/firmware.h>
77 #include <linux/component.h>
78 #include <linux/dmi.h>
79 
80 #include <drm/display/drm_dp_mst_helper.h>
81 #include <drm/display/drm_hdmi_helper.h>
82 #include <drm/drm_atomic.h>
83 #include <drm/drm_atomic_uapi.h>
84 #include <drm/drm_atomic_helper.h>
85 #include <drm/drm_blend.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 	.atomic_check = amdgpu_dm_atomic_check,
2824 	.atomic_commit = drm_atomic_helper_commit,
2825 };
2826 
2827 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2828 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2829 	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
2830 };
2831 
2832 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
2833 {
2834 	struct amdgpu_dm_backlight_caps *caps;
2835 	struct amdgpu_display_manager *dm;
2836 	struct drm_connector *conn_base;
2837 	struct amdgpu_device *adev;
2838 	struct dc_link *link = NULL;
2839 	struct drm_luminance_range_info *luminance_range;
2840 	int i;
2841 
2842 	if (!aconnector || !aconnector->dc_link)
2843 		return;
2844 
2845 	link = aconnector->dc_link;
2846 	if (link->connector_signal != SIGNAL_TYPE_EDP)
2847 		return;
2848 
2849 	conn_base = &aconnector->base;
2850 	adev = drm_to_adev(conn_base->dev);
2851 	dm = &adev->dm;
2852 	for (i = 0; i < dm->num_of_edps; i++) {
2853 		if (link == dm->backlight_link[i])
2854 			break;
2855 	}
2856 	if (i >= dm->num_of_edps)
2857 		return;
2858 	caps = &dm->backlight_caps[i];
2859 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
2860 	caps->aux_support = false;
2861 
2862 	if (caps->ext_caps->bits.oled == 1 /*||
2863 	    caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
2864 	    caps->ext_caps->bits.hdr_aux_backlight_control == 1*/)
2865 		caps->aux_support = true;
2866 
2867 	if (amdgpu_backlight == 0)
2868 		caps->aux_support = false;
2869 	else if (amdgpu_backlight == 1)
2870 		caps->aux_support = true;
2871 
2872 	luminance_range = &conn_base->display_info.luminance_range;
2873 	caps->aux_min_input_signal = luminance_range->min_luminance;
2874 	caps->aux_max_input_signal = luminance_range->max_luminance;
2875 }
2876 
2877 void amdgpu_dm_update_connector_after_detect(
2878 		struct amdgpu_dm_connector *aconnector)
2879 {
2880 	struct drm_connector *connector = &aconnector->base;
2881 	struct drm_device *dev = connector->dev;
2882 	struct dc_sink *sink;
2883 
2884 	/* MST handled by drm_mst framework */
2885 	if (aconnector->mst_mgr.mst_state == true)
2886 		return;
2887 
2888 	sink = aconnector->dc_link->local_sink;
2889 	if (sink)
2890 		dc_sink_retain(sink);
2891 
2892 	/*
2893 	 * Edid mgmt connector gets first update only in mode_valid hook and then
2894 	 * the connector sink is set to either fake or physical sink depends on link status.
2895 	 * Skip if already done during boot.
2896 	 */
2897 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
2898 			&& aconnector->dc_em_sink) {
2899 
2900 		/*
2901 		 * For S3 resume with headless use eml_sink to fake stream
2902 		 * because on resume connector->sink is set to NULL
2903 		 */
2904 		mutex_lock(&dev->mode_config.mutex);
2905 
2906 		if (sink) {
2907 			if (aconnector->dc_sink) {
2908 				amdgpu_dm_update_freesync_caps(connector, NULL);
2909 				/*
2910 				 * retain and release below are used to
2911 				 * bump up refcount for sink because the link doesn't point
2912 				 * to it anymore after disconnect, so on next crtc to connector
2913 				 * reshuffle by UMD we will get into unwanted dc_sink release
2914 				 */
2915 				dc_sink_release(aconnector->dc_sink);
2916 			}
2917 			aconnector->dc_sink = sink;
2918 			dc_sink_retain(aconnector->dc_sink);
2919 			amdgpu_dm_update_freesync_caps(connector,
2920 					aconnector->edid);
2921 		} else {
2922 			amdgpu_dm_update_freesync_caps(connector, NULL);
2923 			if (!aconnector->dc_sink) {
2924 				aconnector->dc_sink = aconnector->dc_em_sink;
2925 				dc_sink_retain(aconnector->dc_sink);
2926 			}
2927 		}
2928 
2929 		mutex_unlock(&dev->mode_config.mutex);
2930 
2931 		if (sink)
2932 			dc_sink_release(sink);
2933 		return;
2934 	}
2935 
2936 	/*
2937 	 * TODO: temporary guard to look for proper fix
2938 	 * if this sink is MST sink, we should not do anything
2939 	 */
2940 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
2941 		dc_sink_release(sink);
2942 		return;
2943 	}
2944 
2945 	if (aconnector->dc_sink == sink) {
2946 		/*
2947 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
2948 		 * Do nothing!!
2949 		 */
2950 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
2951 				aconnector->connector_id);
2952 		if (sink)
2953 			dc_sink_release(sink);
2954 		return;
2955 	}
2956 
2957 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
2958 		aconnector->connector_id, aconnector->dc_sink, sink);
2959 
2960 	mutex_lock(&dev->mode_config.mutex);
2961 
2962 	/*
2963 	 * 1. Update status of the drm connector
2964 	 * 2. Send an event and let userspace tell us what to do
2965 	 */
2966 	if (sink) {
2967 		/*
2968 		 * TODO: check if we still need the S3 mode update workaround.
2969 		 * If yes, put it here.
2970 		 */
2971 		if (aconnector->dc_sink) {
2972 			amdgpu_dm_update_freesync_caps(connector, NULL);
2973 			dc_sink_release(aconnector->dc_sink);
2974 		}
2975 
2976 		aconnector->dc_sink = sink;
2977 		dc_sink_retain(aconnector->dc_sink);
2978 		if (sink->dc_edid.length == 0) {
2979 			aconnector->edid = NULL;
2980 			if (aconnector->dc_link->aux_mode) {
2981 				drm_dp_cec_unset_edid(
2982 					&aconnector->dm_dp_aux.aux);
2983 			}
2984 		} else {
2985 			aconnector->edid =
2986 				(struct edid *)sink->dc_edid.raw_edid;
2987 
2988 			if (aconnector->dc_link->aux_mode)
2989 				drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
2990 						    aconnector->edid);
2991 		}
2992 
2993 		drm_connector_update_edid_property(connector, aconnector->edid);
2994 		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
2995 		update_connector_ext_caps(aconnector);
2996 	} else {
2997 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
2998 		amdgpu_dm_update_freesync_caps(connector, NULL);
2999 		drm_connector_update_edid_property(connector, NULL);
3000 		aconnector->num_modes = 0;
3001 		dc_sink_release(aconnector->dc_sink);
3002 		aconnector->dc_sink = NULL;
3003 		aconnector->edid = NULL;
3004 #ifdef CONFIG_DRM_AMD_DC_HDCP
3005 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3006 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3007 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3008 #endif
3009 	}
3010 
3011 	mutex_unlock(&dev->mode_config.mutex);
3012 
3013 	update_subconnector_property(aconnector);
3014 
3015 	if (sink)
3016 		dc_sink_release(sink);
3017 }
3018 
3019 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3020 {
3021 	struct drm_connector *connector = &aconnector->base;
3022 	struct drm_device *dev = connector->dev;
3023 	enum dc_connection_type new_connection_type = dc_connection_none;
3024 	struct amdgpu_device *adev = drm_to_adev(dev);
3025 #ifdef CONFIG_DRM_AMD_DC_HDCP
3026 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3027 #endif
3028 	bool ret = false;
3029 
3030 	if (adev->dm.disable_hpd_irq)
3031 		return;
3032 
3033 	/*
3034 	 * In case of failure or MST no need to update connector status or notify the OS
3035 	 * since (for MST case) MST does this in its own context.
3036 	 */
3037 	mutex_lock(&aconnector->hpd_lock);
3038 
3039 #ifdef CONFIG_DRM_AMD_DC_HDCP
3040 	if (adev->dm.hdcp_workqueue) {
3041 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3042 		dm_con_state->update_hdcp = true;
3043 	}
3044 #endif
3045 	if (aconnector->fake_enable)
3046 		aconnector->fake_enable = false;
3047 
3048 	if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
3049 		DRM_ERROR("KMS: Failed to detect connector\n");
3050 
3051 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
3052 		emulated_link_detect(aconnector->dc_link);
3053 
3054 		drm_modeset_lock_all(dev);
3055 		dm_restore_drm_connector_state(dev, connector);
3056 		drm_modeset_unlock_all(dev);
3057 
3058 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3059 			drm_kms_helper_connector_hotplug_event(connector);
3060 	} else {
3061 		mutex_lock(&adev->dm.dc_lock);
3062 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3063 		mutex_unlock(&adev->dm.dc_lock);
3064 		if (ret) {
3065 			amdgpu_dm_update_connector_after_detect(aconnector);
3066 
3067 			drm_modeset_lock_all(dev);
3068 			dm_restore_drm_connector_state(dev, connector);
3069 			drm_modeset_unlock_all(dev);
3070 
3071 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3072 				drm_kms_helper_connector_hotplug_event(connector);
3073 		}
3074 	}
3075 	mutex_unlock(&aconnector->hpd_lock);
3076 
3077 }
3078 
3079 static void handle_hpd_irq(void *param)
3080 {
3081 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3082 
3083 	handle_hpd_irq_helper(aconnector);
3084 
3085 }
3086 
3087 static void dm_handle_mst_sideband_msg(struct amdgpu_dm_connector *aconnector)
3088 {
3089 	uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
3090 	uint8_t dret;
3091 	bool new_irq_handled = false;
3092 	int dpcd_addr;
3093 	int dpcd_bytes_to_read;
3094 
3095 	const int max_process_count = 30;
3096 	int process_count = 0;
3097 
3098 	const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
3099 
3100 	if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
3101 		dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
3102 		/* DPCD 0x200 - 0x201 for downstream IRQ */
3103 		dpcd_addr = DP_SINK_COUNT;
3104 	} else {
3105 		dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
3106 		/* DPCD 0x2002 - 0x2005 for downstream IRQ */
3107 		dpcd_addr = DP_SINK_COUNT_ESI;
3108 	}
3109 
3110 	dret = drm_dp_dpcd_read(
3111 		&aconnector->dm_dp_aux.aux,
3112 		dpcd_addr,
3113 		esi,
3114 		dpcd_bytes_to_read);
3115 
3116 	while (dret == dpcd_bytes_to_read &&
3117 		process_count < max_process_count) {
3118 		uint8_t retry;
3119 		dret = 0;
3120 
3121 		process_count++;
3122 
3123 		DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
3124 		/* handle HPD short pulse irq */
3125 		if (aconnector->mst_mgr.mst_state)
3126 			drm_dp_mst_hpd_irq(
3127 				&aconnector->mst_mgr,
3128 				esi,
3129 				&new_irq_handled);
3130 
3131 		if (new_irq_handled) {
3132 			/* ACK at DPCD to notify down stream */
3133 			const int ack_dpcd_bytes_to_write =
3134 				dpcd_bytes_to_read - 1;
3135 
3136 			for (retry = 0; retry < 3; retry++) {
3137 				uint8_t wret;
3138 
3139 				wret = drm_dp_dpcd_write(
3140 					&aconnector->dm_dp_aux.aux,
3141 					dpcd_addr + 1,
3142 					&esi[1],
3143 					ack_dpcd_bytes_to_write);
3144 				if (wret == ack_dpcd_bytes_to_write)
3145 					break;
3146 			}
3147 
3148 			/* check if there is new irq to be handled */
3149 			dret = drm_dp_dpcd_read(
3150 				&aconnector->dm_dp_aux.aux,
3151 				dpcd_addr,
3152 				esi,
3153 				dpcd_bytes_to_read);
3154 
3155 			new_irq_handled = false;
3156 		} else {
3157 			break;
3158 		}
3159 	}
3160 
3161 	if (process_count == max_process_count)
3162 		DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
3163 }
3164 
3165 static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
3166 							union hpd_irq_data hpd_irq_data)
3167 {
3168 	struct hpd_rx_irq_offload_work *offload_work =
3169 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
3170 
3171 	if (!offload_work) {
3172 		DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
3173 		return;
3174 	}
3175 
3176 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3177 	offload_work->data = hpd_irq_data;
3178 	offload_work->offload_wq = offload_wq;
3179 
3180 	queue_work(offload_wq->wq, &offload_work->work);
3181 	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3182 }
3183 
3184 static void handle_hpd_rx_irq(void *param)
3185 {
3186 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3187 	struct drm_connector *connector = &aconnector->base;
3188 	struct drm_device *dev = connector->dev;
3189 	struct dc_link *dc_link = aconnector->dc_link;
3190 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3191 	bool result = false;
3192 	enum dc_connection_type new_connection_type = dc_connection_none;
3193 	struct amdgpu_device *adev = drm_to_adev(dev);
3194 	union hpd_irq_data hpd_irq_data;
3195 	bool link_loss = false;
3196 	bool has_left_work = false;
3197 	int idx = aconnector->base.index;
3198 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3199 
3200 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3201 
3202 	if (adev->dm.disable_hpd_irq)
3203 		return;
3204 
3205 	/*
3206 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3207 	 * conflict, after implement i2c helper, this mutex should be
3208 	 * retired.
3209 	 */
3210 	mutex_lock(&aconnector->hpd_lock);
3211 
3212 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3213 						&link_loss, true, &has_left_work);
3214 
3215 	if (!has_left_work)
3216 		goto out;
3217 
3218 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3219 		schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3220 		goto out;
3221 	}
3222 
3223 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3224 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3225 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3226 			dm_handle_mst_sideband_msg(aconnector);
3227 			goto out;
3228 		}
3229 
3230 		if (link_loss) {
3231 			bool skip = false;
3232 
3233 			spin_lock(&offload_wq->offload_lock);
3234 			skip = offload_wq->is_handling_link_loss;
3235 
3236 			if (!skip)
3237 				offload_wq->is_handling_link_loss = true;
3238 
3239 			spin_unlock(&offload_wq->offload_lock);
3240 
3241 			if (!skip)
3242 				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3243 
3244 			goto out;
3245 		}
3246 	}
3247 
3248 out:
3249 	if (result && !is_mst_root_connector) {
3250 		/* Downstream Port status changed. */
3251 		if (!dc_link_detect_sink(dc_link, &new_connection_type))
3252 			DRM_ERROR("KMS: Failed to detect connector\n");
3253 
3254 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3255 			emulated_link_detect(dc_link);
3256 
3257 			if (aconnector->fake_enable)
3258 				aconnector->fake_enable = false;
3259 
3260 			amdgpu_dm_update_connector_after_detect(aconnector);
3261 
3262 
3263 			drm_modeset_lock_all(dev);
3264 			dm_restore_drm_connector_state(dev, connector);
3265 			drm_modeset_unlock_all(dev);
3266 
3267 			drm_kms_helper_connector_hotplug_event(connector);
3268 		} else {
3269 			bool ret = false;
3270 
3271 			mutex_lock(&adev->dm.dc_lock);
3272 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
3273 			mutex_unlock(&adev->dm.dc_lock);
3274 
3275 			if (ret) {
3276 				if (aconnector->fake_enable)
3277 					aconnector->fake_enable = false;
3278 
3279 				amdgpu_dm_update_connector_after_detect(aconnector);
3280 
3281 				drm_modeset_lock_all(dev);
3282 				dm_restore_drm_connector_state(dev, connector);
3283 				drm_modeset_unlock_all(dev);
3284 
3285 				drm_kms_helper_connector_hotplug_event(connector);
3286 			}
3287 		}
3288 	}
3289 #ifdef CONFIG_DRM_AMD_DC_HDCP
3290 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
3291 		if (adev->dm.hdcp_workqueue)
3292 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
3293 	}
3294 #endif
3295 
3296 	if (dc_link->type != dc_connection_mst_branch)
3297 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
3298 
3299 	mutex_unlock(&aconnector->hpd_lock);
3300 }
3301 
3302 static void register_hpd_handlers(struct amdgpu_device *adev)
3303 {
3304 	struct drm_device *dev = adev_to_drm(adev);
3305 	struct drm_connector *connector;
3306 	struct amdgpu_dm_connector *aconnector;
3307 	const struct dc_link *dc_link;
3308 	struct dc_interrupt_params int_params = {0};
3309 
3310 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3311 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3312 
3313 	list_for_each_entry(connector,
3314 			&dev->mode_config.connector_list, head)	{
3315 
3316 		aconnector = to_amdgpu_dm_connector(connector);
3317 		dc_link = aconnector->dc_link;
3318 
3319 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
3320 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3321 			int_params.irq_source = dc_link->irq_source_hpd;
3322 
3323 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3324 					handle_hpd_irq,
3325 					(void *) aconnector);
3326 		}
3327 
3328 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
3329 
3330 			/* Also register for DP short pulse (hpd_rx). */
3331 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3332 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
3333 
3334 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3335 					handle_hpd_rx_irq,
3336 					(void *) aconnector);
3337 
3338 			if (adev->dm.hpd_rx_offload_wq)
3339 				adev->dm.hpd_rx_offload_wq[connector->index].aconnector =
3340 					aconnector;
3341 		}
3342 	}
3343 }
3344 
3345 #if defined(CONFIG_DRM_AMD_DC_SI)
3346 /* Register IRQ sources and initialize IRQ callbacks */
3347 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
3348 {
3349 	struct dc *dc = adev->dm.dc;
3350 	struct common_irq_params *c_irq_params;
3351 	struct dc_interrupt_params int_params = {0};
3352 	int r;
3353 	int i;
3354 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3355 
3356 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3357 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3358 
3359 	/*
3360 	 * Actions of amdgpu_irq_add_id():
3361 	 * 1. Register a set() function with base driver.
3362 	 *    Base driver will call set() function to enable/disable an
3363 	 *    interrupt in DC hardware.
3364 	 * 2. Register amdgpu_dm_irq_handler().
3365 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3366 	 *    coming from DC hardware.
3367 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3368 	 *    for acknowledging and handling. */
3369 
3370 	/* Use VBLANK interrupt */
3371 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
3372 		r = amdgpu_irq_add_id(adev, client_id, i+1 , &adev->crtc_irq);
3373 		if (r) {
3374 			DRM_ERROR("Failed to add crtc irq id!\n");
3375 			return r;
3376 		}
3377 
3378 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3379 		int_params.irq_source =
3380 			dc_interrupt_to_irq_source(dc, i+1 , 0);
3381 
3382 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3383 
3384 		c_irq_params->adev = adev;
3385 		c_irq_params->irq_src = int_params.irq_source;
3386 
3387 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3388 				dm_crtc_high_irq, c_irq_params);
3389 	}
3390 
3391 	/* Use GRPH_PFLIP interrupt */
3392 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3393 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3394 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3395 		if (r) {
3396 			DRM_ERROR("Failed to add page flip irq id!\n");
3397 			return r;
3398 		}
3399 
3400 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3401 		int_params.irq_source =
3402 			dc_interrupt_to_irq_source(dc, i, 0);
3403 
3404 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3405 
3406 		c_irq_params->adev = adev;
3407 		c_irq_params->irq_src = int_params.irq_source;
3408 
3409 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3410 				dm_pflip_high_irq, c_irq_params);
3411 
3412 	}
3413 
3414 	/* HPD */
3415 	r = amdgpu_irq_add_id(adev, client_id,
3416 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3417 	if (r) {
3418 		DRM_ERROR("Failed to add hpd irq id!\n");
3419 		return r;
3420 	}
3421 
3422 	register_hpd_handlers(adev);
3423 
3424 	return 0;
3425 }
3426 #endif
3427 
3428 /* Register IRQ sources and initialize IRQ callbacks */
3429 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
3430 {
3431 	struct dc *dc = adev->dm.dc;
3432 	struct common_irq_params *c_irq_params;
3433 	struct dc_interrupt_params int_params = {0};
3434 	int r;
3435 	int i;
3436 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3437 
3438 	if (adev->family >= AMDGPU_FAMILY_AI)
3439 		client_id = SOC15_IH_CLIENTID_DCE;
3440 
3441 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3442 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3443 
3444 	/*
3445 	 * Actions of amdgpu_irq_add_id():
3446 	 * 1. Register a set() function with base driver.
3447 	 *    Base driver will call set() function to enable/disable an
3448 	 *    interrupt in DC hardware.
3449 	 * 2. Register amdgpu_dm_irq_handler().
3450 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3451 	 *    coming from DC hardware.
3452 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3453 	 *    for acknowledging and handling. */
3454 
3455 	/* Use VBLANK interrupt */
3456 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
3457 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
3458 		if (r) {
3459 			DRM_ERROR("Failed to add crtc irq id!\n");
3460 			return r;
3461 		}
3462 
3463 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3464 		int_params.irq_source =
3465 			dc_interrupt_to_irq_source(dc, i, 0);
3466 
3467 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3468 
3469 		c_irq_params->adev = adev;
3470 		c_irq_params->irq_src = int_params.irq_source;
3471 
3472 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3473 				dm_crtc_high_irq, c_irq_params);
3474 	}
3475 
3476 	/* Use VUPDATE interrupt */
3477 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
3478 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
3479 		if (r) {
3480 			DRM_ERROR("Failed to add vupdate irq id!\n");
3481 			return r;
3482 		}
3483 
3484 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3485 		int_params.irq_source =
3486 			dc_interrupt_to_irq_source(dc, i, 0);
3487 
3488 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3489 
3490 		c_irq_params->adev = adev;
3491 		c_irq_params->irq_src = int_params.irq_source;
3492 
3493 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3494 				dm_vupdate_high_irq, c_irq_params);
3495 	}
3496 
3497 	/* Use GRPH_PFLIP interrupt */
3498 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3499 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3500 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3501 		if (r) {
3502 			DRM_ERROR("Failed to add page flip irq id!\n");
3503 			return r;
3504 		}
3505 
3506 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3507 		int_params.irq_source =
3508 			dc_interrupt_to_irq_source(dc, i, 0);
3509 
3510 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3511 
3512 		c_irq_params->adev = adev;
3513 		c_irq_params->irq_src = int_params.irq_source;
3514 
3515 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3516 				dm_pflip_high_irq, c_irq_params);
3517 
3518 	}
3519 
3520 	/* HPD */
3521 	r = amdgpu_irq_add_id(adev, client_id,
3522 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3523 	if (r) {
3524 		DRM_ERROR("Failed to add hpd irq id!\n");
3525 		return r;
3526 	}
3527 
3528 	register_hpd_handlers(adev);
3529 
3530 	return 0;
3531 }
3532 
3533 /* Register IRQ sources and initialize IRQ callbacks */
3534 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
3535 {
3536 	struct dc *dc = adev->dm.dc;
3537 	struct common_irq_params *c_irq_params;
3538 	struct dc_interrupt_params int_params = {0};
3539 	int r;
3540 	int i;
3541 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3542 	static const unsigned int vrtl_int_srcid[] = {
3543 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
3544 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
3545 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
3546 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
3547 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
3548 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
3549 	};
3550 #endif
3551 
3552 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3553 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3554 
3555 	/*
3556 	 * Actions of amdgpu_irq_add_id():
3557 	 * 1. Register a set() function with base driver.
3558 	 *    Base driver will call set() function to enable/disable an
3559 	 *    interrupt in DC hardware.
3560 	 * 2. Register amdgpu_dm_irq_handler().
3561 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3562 	 *    coming from DC hardware.
3563 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3564 	 *    for acknowledging and handling.
3565 	 */
3566 
3567 	/* Use VSTARTUP interrupt */
3568 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
3569 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
3570 			i++) {
3571 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
3572 
3573 		if (r) {
3574 			DRM_ERROR("Failed to add crtc irq id!\n");
3575 			return r;
3576 		}
3577 
3578 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3579 		int_params.irq_source =
3580 			dc_interrupt_to_irq_source(dc, i, 0);
3581 
3582 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3583 
3584 		c_irq_params->adev = adev;
3585 		c_irq_params->irq_src = int_params.irq_source;
3586 
3587 		amdgpu_dm_irq_register_interrupt(
3588 			adev, &int_params, dm_crtc_high_irq, c_irq_params);
3589 	}
3590 
3591 	/* Use otg vertical line interrupt */
3592 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3593 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
3594 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
3595 				vrtl_int_srcid[i], &adev->vline0_irq);
3596 
3597 		if (r) {
3598 			DRM_ERROR("Failed to add vline0 irq id!\n");
3599 			return r;
3600 		}
3601 
3602 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3603 		int_params.irq_source =
3604 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
3605 
3606 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
3607 			DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
3608 			break;
3609 		}
3610 
3611 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
3612 					- DC_IRQ_SOURCE_DC1_VLINE0];
3613 
3614 		c_irq_params->adev = adev;
3615 		c_irq_params->irq_src = int_params.irq_source;
3616 
3617 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3618 				dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
3619 	}
3620 #endif
3621 
3622 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
3623 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
3624 	 * to trigger at end of each vblank, regardless of state of the lock,
3625 	 * matching DCE behaviour.
3626 	 */
3627 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
3628 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
3629 	     i++) {
3630 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
3631 
3632 		if (r) {
3633 			DRM_ERROR("Failed to add vupdate irq id!\n");
3634 			return r;
3635 		}
3636 
3637 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3638 		int_params.irq_source =
3639 			dc_interrupt_to_irq_source(dc, i, 0);
3640 
3641 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3642 
3643 		c_irq_params->adev = adev;
3644 		c_irq_params->irq_src = int_params.irq_source;
3645 
3646 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3647 				dm_vupdate_high_irq, c_irq_params);
3648 	}
3649 
3650 	/* Use GRPH_PFLIP interrupt */
3651 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
3652 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
3653 			i++) {
3654 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
3655 		if (r) {
3656 			DRM_ERROR("Failed to add page flip irq id!\n");
3657 			return r;
3658 		}
3659 
3660 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3661 		int_params.irq_source =
3662 			dc_interrupt_to_irq_source(dc, i, 0);
3663 
3664 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3665 
3666 		c_irq_params->adev = adev;
3667 		c_irq_params->irq_src = int_params.irq_source;
3668 
3669 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3670 				dm_pflip_high_irq, c_irq_params);
3671 
3672 	}
3673 
3674 	/* HPD */
3675 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
3676 			&adev->hpd_irq);
3677 	if (r) {
3678 		DRM_ERROR("Failed to add hpd irq id!\n");
3679 		return r;
3680 	}
3681 
3682 	register_hpd_handlers(adev);
3683 
3684 	return 0;
3685 }
3686 /* Register Outbox IRQ sources and initialize IRQ callbacks */
3687 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
3688 {
3689 	struct dc *dc = adev->dm.dc;
3690 	struct common_irq_params *c_irq_params;
3691 	struct dc_interrupt_params int_params = {0};
3692 	int r, i;
3693 
3694 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3695 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3696 
3697 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
3698 			&adev->dmub_outbox_irq);
3699 	if (r) {
3700 		DRM_ERROR("Failed to add outbox irq id!\n");
3701 		return r;
3702 	}
3703 
3704 	if (dc->ctx->dmub_srv) {
3705 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
3706 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3707 		int_params.irq_source =
3708 		dc_interrupt_to_irq_source(dc, i, 0);
3709 
3710 		c_irq_params = &adev->dm.dmub_outbox_params[0];
3711 
3712 		c_irq_params->adev = adev;
3713 		c_irq_params->irq_src = int_params.irq_source;
3714 
3715 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3716 				dm_dmub_outbox1_low_irq, c_irq_params);
3717 	}
3718 
3719 	return 0;
3720 }
3721 
3722 /*
3723  * Acquires the lock for the atomic state object and returns
3724  * the new atomic state.
3725  *
3726  * This should only be called during atomic check.
3727  */
3728 int dm_atomic_get_state(struct drm_atomic_state *state,
3729 			struct dm_atomic_state **dm_state)
3730 {
3731 	struct drm_device *dev = state->dev;
3732 	struct amdgpu_device *adev = drm_to_adev(dev);
3733 	struct amdgpu_display_manager *dm = &adev->dm;
3734 	struct drm_private_state *priv_state;
3735 
3736 	if (*dm_state)
3737 		return 0;
3738 
3739 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
3740 	if (IS_ERR(priv_state))
3741 		return PTR_ERR(priv_state);
3742 
3743 	*dm_state = to_dm_atomic_state(priv_state);
3744 
3745 	return 0;
3746 }
3747 
3748 static struct dm_atomic_state *
3749 dm_atomic_get_new_state(struct drm_atomic_state *state)
3750 {
3751 	struct drm_device *dev = state->dev;
3752 	struct amdgpu_device *adev = drm_to_adev(dev);
3753 	struct amdgpu_display_manager *dm = &adev->dm;
3754 	struct drm_private_obj *obj;
3755 	struct drm_private_state *new_obj_state;
3756 	int i;
3757 
3758 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
3759 		if (obj->funcs == dm->atomic_obj.funcs)
3760 			return to_dm_atomic_state(new_obj_state);
3761 	}
3762 
3763 	return NULL;
3764 }
3765 
3766 static struct drm_private_state *
3767 dm_atomic_duplicate_state(struct drm_private_obj *obj)
3768 {
3769 	struct dm_atomic_state *old_state, *new_state;
3770 
3771 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
3772 	if (!new_state)
3773 		return NULL;
3774 
3775 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
3776 
3777 	old_state = to_dm_atomic_state(obj->state);
3778 
3779 	if (old_state && old_state->context)
3780 		new_state->context = dc_copy_state(old_state->context);
3781 
3782 	if (!new_state->context) {
3783 		kfree(new_state);
3784 		return NULL;
3785 	}
3786 
3787 	return &new_state->base;
3788 }
3789 
3790 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
3791 				    struct drm_private_state *state)
3792 {
3793 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3794 
3795 	if (dm_state && dm_state->context)
3796 		dc_release_state(dm_state->context);
3797 
3798 	kfree(dm_state);
3799 }
3800 
3801 static struct drm_private_state_funcs dm_atomic_state_funcs = {
3802 	.atomic_duplicate_state = dm_atomic_duplicate_state,
3803 	.atomic_destroy_state = dm_atomic_destroy_state,
3804 };
3805 
3806 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
3807 {
3808 	struct dm_atomic_state *state;
3809 	int r;
3810 
3811 	adev->mode_info.mode_config_initialized = true;
3812 
3813 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
3814 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
3815 
3816 	adev_to_drm(adev)->mode_config.max_width = 16384;
3817 	adev_to_drm(adev)->mode_config.max_height = 16384;
3818 
3819 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
3820 	if (adev->asic_type == CHIP_HAWAII)
3821 		/* disable prefer shadow for now due to hibernation issues */
3822 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
3823 	else
3824 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
3825 	/* indicates support for immediate flip */
3826 	adev_to_drm(adev)->mode_config.async_page_flip = true;
3827 
3828 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3829 	if (!state)
3830 		return -ENOMEM;
3831 
3832 	state->context = dc_create_state(adev->dm.dc);
3833 	if (!state->context) {
3834 		kfree(state);
3835 		return -ENOMEM;
3836 	}
3837 
3838 	dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
3839 
3840 	drm_atomic_private_obj_init(adev_to_drm(adev),
3841 				    &adev->dm.atomic_obj,
3842 				    &state->base,
3843 				    &dm_atomic_state_funcs);
3844 
3845 	r = amdgpu_display_modeset_create_props(adev);
3846 	if (r) {
3847 		dc_release_state(state->context);
3848 		kfree(state);
3849 		return r;
3850 	}
3851 
3852 	r = amdgpu_dm_audio_init(adev);
3853 	if (r) {
3854 		dc_release_state(state->context);
3855 		kfree(state);
3856 		return r;
3857 	}
3858 
3859 	return 0;
3860 }
3861 
3862 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
3863 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
3864 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
3865 
3866 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
3867 					    int bl_idx)
3868 {
3869 #if defined(CONFIG_ACPI)
3870 	struct amdgpu_dm_backlight_caps caps;
3871 
3872 	memset(&caps, 0, sizeof(caps));
3873 
3874 	if (dm->backlight_caps[bl_idx].caps_valid)
3875 		return;
3876 
3877 	amdgpu_acpi_get_backlight_caps(&caps);
3878 	if (caps.caps_valid) {
3879 		dm->backlight_caps[bl_idx].caps_valid = true;
3880 		if (caps.aux_support)
3881 			return;
3882 		dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
3883 		dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
3884 	} else {
3885 		dm->backlight_caps[bl_idx].min_input_signal =
3886 				AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3887 		dm->backlight_caps[bl_idx].max_input_signal =
3888 				AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3889 	}
3890 #else
3891 	if (dm->backlight_caps[bl_idx].aux_support)
3892 		return;
3893 
3894 	dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3895 	dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3896 #endif
3897 }
3898 
3899 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
3900 				unsigned *min, unsigned *max)
3901 {
3902 	if (!caps)
3903 		return 0;
3904 
3905 	if (caps->aux_support) {
3906 		// Firmware limits are in nits, DC API wants millinits.
3907 		*max = 1000 * caps->aux_max_input_signal;
3908 		*min = 1000 * caps->aux_min_input_signal;
3909 	} else {
3910 		// Firmware limits are 8-bit, PWM control is 16-bit.
3911 		*max = 0x101 * caps->max_input_signal;
3912 		*min = 0x101 * caps->min_input_signal;
3913 	}
3914 	return 1;
3915 }
3916 
3917 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
3918 					uint32_t brightness)
3919 {
3920 	unsigned min, max;
3921 
3922 	if (!get_brightness_range(caps, &min, &max))
3923 		return brightness;
3924 
3925 	// Rescale 0..255 to min..max
3926 	return min + DIV_ROUND_CLOSEST((max - min) * brightness,
3927 				       AMDGPU_MAX_BL_LEVEL);
3928 }
3929 
3930 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
3931 				      uint32_t brightness)
3932 {
3933 	unsigned min, max;
3934 
3935 	if (!get_brightness_range(caps, &min, &max))
3936 		return brightness;
3937 
3938 	if (brightness < min)
3939 		return 0;
3940 	// Rescale min..max to 0..255
3941 	return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
3942 				 max - min);
3943 }
3944 
3945 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
3946 					 int bl_idx,
3947 					 u32 user_brightness)
3948 {
3949 	struct amdgpu_dm_backlight_caps caps;
3950 	struct dc_link *link;
3951 	u32 brightness;
3952 	bool rc;
3953 
3954 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
3955 	caps = dm->backlight_caps[bl_idx];
3956 
3957 	dm->brightness[bl_idx] = user_brightness;
3958 	/* update scratch register */
3959 	if (bl_idx == 0)
3960 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
3961 	brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
3962 	link = (struct dc_link *)dm->backlight_link[bl_idx];
3963 
3964 	/* Change brightness based on AUX property */
3965 	if (caps.aux_support) {
3966 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
3967 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
3968 		if (!rc)
3969 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
3970 	} else {
3971 		rc = dc_link_set_backlight_level(link, brightness, 0);
3972 		if (!rc)
3973 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
3974 	}
3975 
3976 	if (rc)
3977 		dm->actual_brightness[bl_idx] = user_brightness;
3978 }
3979 
3980 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
3981 {
3982 	struct amdgpu_display_manager *dm = bl_get_data(bd);
3983 	int i;
3984 
3985 	for (i = 0; i < dm->num_of_edps; i++) {
3986 		if (bd == dm->backlight_dev[i])
3987 			break;
3988 	}
3989 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
3990 		i = 0;
3991 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
3992 
3993 	return 0;
3994 }
3995 
3996 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
3997 					 int bl_idx)
3998 {
3999 	struct amdgpu_dm_backlight_caps caps;
4000 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
4001 
4002 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4003 	caps = dm->backlight_caps[bl_idx];
4004 
4005 	if (caps.aux_support) {
4006 		u32 avg, peak;
4007 		bool rc;
4008 
4009 		rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
4010 		if (!rc)
4011 			return dm->brightness[bl_idx];
4012 		return convert_brightness_to_user(&caps, avg);
4013 	} else {
4014 		int ret = dc_link_get_backlight_level(link);
4015 
4016 		if (ret == DC_ERROR_UNEXPECTED)
4017 			return dm->brightness[bl_idx];
4018 		return convert_brightness_to_user(&caps, ret);
4019 	}
4020 }
4021 
4022 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
4023 {
4024 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4025 	int i;
4026 
4027 	for (i = 0; i < dm->num_of_edps; i++) {
4028 		if (bd == dm->backlight_dev[i])
4029 			break;
4030 	}
4031 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4032 		i = 0;
4033 	return amdgpu_dm_backlight_get_level(dm, i);
4034 }
4035 
4036 static const struct backlight_ops amdgpu_dm_backlight_ops = {
4037 	.options = BL_CORE_SUSPENDRESUME,
4038 	.get_brightness = amdgpu_dm_backlight_get_brightness,
4039 	.update_status	= amdgpu_dm_backlight_update_status,
4040 };
4041 
4042 static void
4043 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
4044 {
4045 	char bl_name[16];
4046 	struct backlight_properties props = { 0 };
4047 
4048 	amdgpu_dm_update_backlight_caps(dm, dm->num_of_edps);
4049 	dm->brightness[dm->num_of_edps] = AMDGPU_MAX_BL_LEVEL;
4050 
4051 	if (!acpi_video_backlight_use_native()) {
4052 		drm_info(adev_to_drm(dm->adev), "Skipping amdgpu DM backlight registration\n");
4053 		/* Try registering an ACPI video backlight device instead. */
4054 		acpi_video_register_backlight();
4055 		return;
4056 	}
4057 
4058 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
4059 	props.brightness = AMDGPU_MAX_BL_LEVEL;
4060 	props.type = BACKLIGHT_RAW;
4061 
4062 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
4063 		 adev_to_drm(dm->adev)->primary->index + dm->num_of_edps);
4064 
4065 	dm->backlight_dev[dm->num_of_edps] = backlight_device_register(bl_name,
4066 								       adev_to_drm(dm->adev)->dev,
4067 								       dm,
4068 								       &amdgpu_dm_backlight_ops,
4069 								       &props);
4070 
4071 	if (IS_ERR(dm->backlight_dev[dm->num_of_edps]))
4072 		DRM_ERROR("DM: Backlight registration failed!\n");
4073 	else
4074 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
4075 }
4076 
4077 static int initialize_plane(struct amdgpu_display_manager *dm,
4078 			    struct amdgpu_mode_info *mode_info, int plane_id,
4079 			    enum drm_plane_type plane_type,
4080 			    const struct dc_plane_cap *plane_cap)
4081 {
4082 	struct drm_plane *plane;
4083 	unsigned long possible_crtcs;
4084 	int ret = 0;
4085 
4086 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
4087 	if (!plane) {
4088 		DRM_ERROR("KMS: Failed to allocate plane\n");
4089 		return -ENOMEM;
4090 	}
4091 	plane->type = plane_type;
4092 
4093 	/*
4094 	 * HACK: IGT tests expect that the primary plane for a CRTC
4095 	 * can only have one possible CRTC. Only expose support for
4096 	 * any CRTC if they're not going to be used as a primary plane
4097 	 * for a CRTC - like overlay or underlay planes.
4098 	 */
4099 	possible_crtcs = 1 << plane_id;
4100 	if (plane_id >= dm->dc->caps.max_streams)
4101 		possible_crtcs = 0xff;
4102 
4103 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
4104 
4105 	if (ret) {
4106 		DRM_ERROR("KMS: Failed to initialize plane\n");
4107 		kfree(plane);
4108 		return ret;
4109 	}
4110 
4111 	if (mode_info)
4112 		mode_info->planes[plane_id] = plane;
4113 
4114 	return ret;
4115 }
4116 
4117 
4118 static void register_backlight_device(struct amdgpu_display_manager *dm,
4119 				      struct dc_link *link)
4120 {
4121 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4122 	    link->type != dc_connection_none) {
4123 		/*
4124 		 * Event if registration failed, we should continue with
4125 		 * DM initialization because not having a backlight control
4126 		 * is better then a black screen.
4127 		 */
4128 		if (!dm->backlight_dev[dm->num_of_edps])
4129 			amdgpu_dm_register_backlight_device(dm);
4130 
4131 		if (dm->backlight_dev[dm->num_of_edps]) {
4132 			dm->backlight_link[dm->num_of_edps] = link;
4133 			dm->num_of_edps++;
4134 		}
4135 	}
4136 }
4137 
4138 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
4139 
4140 /*
4141  * In this architecture, the association
4142  * connector -> encoder -> crtc
4143  * id not really requried. The crtc and connector will hold the
4144  * display_index as an abstraction to use with DAL component
4145  *
4146  * Returns 0 on success
4147  */
4148 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
4149 {
4150 	struct amdgpu_display_manager *dm = &adev->dm;
4151 	int32_t i;
4152 	struct amdgpu_dm_connector *aconnector = NULL;
4153 	struct amdgpu_encoder *aencoder = NULL;
4154 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
4155 	uint32_t link_cnt;
4156 	int32_t primary_planes;
4157 	enum dc_connection_type new_connection_type = dc_connection_none;
4158 	const struct dc_plane_cap *plane;
4159 	bool psr_feature_enabled = false;
4160 
4161 	dm->display_indexes_num = dm->dc->caps.max_streams;
4162 	/* Update the actual used number of crtc */
4163 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
4164 
4165 	link_cnt = dm->dc->caps.max_links;
4166 	if (amdgpu_dm_mode_config_init(dm->adev)) {
4167 		DRM_ERROR("DM: Failed to initialize mode config\n");
4168 		return -EINVAL;
4169 	}
4170 
4171 	/* There is one primary plane per CRTC */
4172 	primary_planes = dm->dc->caps.max_streams;
4173 	ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
4174 
4175 	/*
4176 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
4177 	 * Order is reversed to match iteration order in atomic check.
4178 	 */
4179 	for (i = (primary_planes - 1); i >= 0; i--) {
4180 		plane = &dm->dc->caps.planes[i];
4181 
4182 		if (initialize_plane(dm, mode_info, i,
4183 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
4184 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
4185 			goto fail;
4186 		}
4187 	}
4188 
4189 	/*
4190 	 * Initialize overlay planes, index starting after primary planes.
4191 	 * These planes have a higher DRM index than the primary planes since
4192 	 * they should be considered as having a higher z-order.
4193 	 * Order is reversed to match iteration order in atomic check.
4194 	 *
4195 	 * Only support DCN for now, and only expose one so we don't encourage
4196 	 * userspace to use up all the pipes.
4197 	 */
4198 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
4199 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
4200 
4201 		/* Do not create overlay if MPO disabled */
4202 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
4203 			break;
4204 
4205 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
4206 			continue;
4207 
4208 		if (!plane->blends_with_above || !plane->blends_with_below)
4209 			continue;
4210 
4211 		if (!plane->pixel_format_support.argb8888)
4212 			continue;
4213 
4214 		if (initialize_plane(dm, NULL, primary_planes + i,
4215 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
4216 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
4217 			goto fail;
4218 		}
4219 
4220 		/* Only create one overlay plane. */
4221 		break;
4222 	}
4223 
4224 	for (i = 0; i < dm->dc->caps.max_streams; i++)
4225 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
4226 			DRM_ERROR("KMS: Failed to initialize crtc\n");
4227 			goto fail;
4228 		}
4229 
4230 	/* Use Outbox interrupt */
4231 	switch (adev->ip_versions[DCE_HWIP][0]) {
4232 	case IP_VERSION(3, 0, 0):
4233 	case IP_VERSION(3, 1, 2):
4234 	case IP_VERSION(3, 1, 3):
4235 	case IP_VERSION(3, 1, 4):
4236 	case IP_VERSION(3, 1, 5):
4237 	case IP_VERSION(3, 1, 6):
4238 	case IP_VERSION(3, 2, 0):
4239 	case IP_VERSION(3, 2, 1):
4240 	case IP_VERSION(2, 1, 0):
4241 		if (register_outbox_irq_handlers(dm->adev)) {
4242 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4243 			goto fail;
4244 		}
4245 		break;
4246 	default:
4247 		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
4248 			      adev->ip_versions[DCE_HWIP][0]);
4249 	}
4250 
4251 	/* Determine whether to enable PSR support by default. */
4252 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
4253 		switch (adev->ip_versions[DCE_HWIP][0]) {
4254 		case IP_VERSION(3, 1, 2):
4255 		case IP_VERSION(3, 1, 3):
4256 		case IP_VERSION(3, 1, 4):
4257 		case IP_VERSION(3, 1, 5):
4258 		case IP_VERSION(3, 1, 6):
4259 		case IP_VERSION(3, 2, 0):
4260 		case IP_VERSION(3, 2, 1):
4261 			psr_feature_enabled = true;
4262 			break;
4263 		default:
4264 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
4265 			break;
4266 		}
4267 	}
4268 
4269 	/* loops over all connectors on the board */
4270 	for (i = 0; i < link_cnt; i++) {
4271 		struct dc_link *link = NULL;
4272 
4273 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
4274 			DRM_ERROR(
4275 				"KMS: Cannot support more than %d display indexes\n",
4276 					AMDGPU_DM_MAX_DISPLAY_INDEX);
4277 			continue;
4278 		}
4279 
4280 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
4281 		if (!aconnector)
4282 			goto fail;
4283 
4284 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
4285 		if (!aencoder)
4286 			goto fail;
4287 
4288 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
4289 			DRM_ERROR("KMS: Failed to initialize encoder\n");
4290 			goto fail;
4291 		}
4292 
4293 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
4294 			DRM_ERROR("KMS: Failed to initialize connector\n");
4295 			goto fail;
4296 		}
4297 
4298 		link = dc_get_link_at_index(dm->dc, i);
4299 
4300 		if (!dc_link_detect_sink(link, &new_connection_type))
4301 			DRM_ERROR("KMS: Failed to detect connector\n");
4302 
4303 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4304 			emulated_link_detect(link);
4305 			amdgpu_dm_update_connector_after_detect(aconnector);
4306 		} else {
4307 			bool ret = false;
4308 
4309 			mutex_lock(&dm->dc_lock);
4310 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
4311 			mutex_unlock(&dm->dc_lock);
4312 
4313 			if (ret) {
4314 				amdgpu_dm_update_connector_after_detect(aconnector);
4315 				register_backlight_device(dm, link);
4316 
4317 				if (dm->num_of_edps)
4318 					update_connector_ext_caps(aconnector);
4319 
4320 				if (psr_feature_enabled)
4321 					amdgpu_dm_set_psr_caps(link);
4322 
4323 				/* TODO: Fix vblank control helpers to delay PSR entry to allow this when
4324 				 * PSR is also supported.
4325 				 */
4326 				if (link->psr_settings.psr_feature_enabled)
4327 					adev_to_drm(adev)->vblank_disable_immediate = false;
4328 			}
4329 		}
4330 		amdgpu_set_panel_orientation(&aconnector->base);
4331 	}
4332 
4333 	/* Software is initialized. Now we can register interrupt handlers. */
4334 	switch (adev->asic_type) {
4335 #if defined(CONFIG_DRM_AMD_DC_SI)
4336 	case CHIP_TAHITI:
4337 	case CHIP_PITCAIRN:
4338 	case CHIP_VERDE:
4339 	case CHIP_OLAND:
4340 		if (dce60_register_irq_handlers(dm->adev)) {
4341 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4342 			goto fail;
4343 		}
4344 		break;
4345 #endif
4346 	case CHIP_BONAIRE:
4347 	case CHIP_HAWAII:
4348 	case CHIP_KAVERI:
4349 	case CHIP_KABINI:
4350 	case CHIP_MULLINS:
4351 	case CHIP_TONGA:
4352 	case CHIP_FIJI:
4353 	case CHIP_CARRIZO:
4354 	case CHIP_STONEY:
4355 	case CHIP_POLARIS11:
4356 	case CHIP_POLARIS10:
4357 	case CHIP_POLARIS12:
4358 	case CHIP_VEGAM:
4359 	case CHIP_VEGA10:
4360 	case CHIP_VEGA12:
4361 	case CHIP_VEGA20:
4362 		if (dce110_register_irq_handlers(dm->adev)) {
4363 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4364 			goto fail;
4365 		}
4366 		break;
4367 	default:
4368 		switch (adev->ip_versions[DCE_HWIP][0]) {
4369 		case IP_VERSION(1, 0, 0):
4370 		case IP_VERSION(1, 0, 1):
4371 		case IP_VERSION(2, 0, 2):
4372 		case IP_VERSION(2, 0, 3):
4373 		case IP_VERSION(2, 0, 0):
4374 		case IP_VERSION(2, 1, 0):
4375 		case IP_VERSION(3, 0, 0):
4376 		case IP_VERSION(3, 0, 2):
4377 		case IP_VERSION(3, 0, 3):
4378 		case IP_VERSION(3, 0, 1):
4379 		case IP_VERSION(3, 1, 2):
4380 		case IP_VERSION(3, 1, 3):
4381 		case IP_VERSION(3, 1, 4):
4382 		case IP_VERSION(3, 1, 5):
4383 		case IP_VERSION(3, 1, 6):
4384 		case IP_VERSION(3, 2, 0):
4385 		case IP_VERSION(3, 2, 1):
4386 			if (dcn10_register_irq_handlers(dm->adev)) {
4387 				DRM_ERROR("DM: Failed to initialize IRQ\n");
4388 				goto fail;
4389 			}
4390 			break;
4391 		default:
4392 			DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4393 					adev->ip_versions[DCE_HWIP][0]);
4394 			goto fail;
4395 		}
4396 		break;
4397 	}
4398 
4399 	return 0;
4400 fail:
4401 	kfree(aencoder);
4402 	kfree(aconnector);
4403 
4404 	return -EINVAL;
4405 }
4406 
4407 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4408 {
4409 	drm_atomic_private_obj_fini(&dm->atomic_obj);
4410 	return;
4411 }
4412 
4413 /******************************************************************************
4414  * amdgpu_display_funcs functions
4415  *****************************************************************************/
4416 
4417 /*
4418  * dm_bandwidth_update - program display watermarks
4419  *
4420  * @adev: amdgpu_device pointer
4421  *
4422  * Calculate and program the display watermarks and line buffer allocation.
4423  */
4424 static void dm_bandwidth_update(struct amdgpu_device *adev)
4425 {
4426 	/* TODO: implement later */
4427 }
4428 
4429 static const struct amdgpu_display_funcs dm_display_funcs = {
4430 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4431 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4432 	.backlight_set_level = NULL, /* never called for DC */
4433 	.backlight_get_level = NULL, /* never called for DC */
4434 	.hpd_sense = NULL,/* called unconditionally */
4435 	.hpd_set_polarity = NULL, /* called unconditionally */
4436 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4437 	.page_flip_get_scanoutpos =
4438 		dm_crtc_get_scanoutpos,/* called unconditionally */
4439 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4440 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
4441 };
4442 
4443 #if defined(CONFIG_DEBUG_KERNEL_DC)
4444 
4445 static ssize_t s3_debug_store(struct device *device,
4446 			      struct device_attribute *attr,
4447 			      const char *buf,
4448 			      size_t count)
4449 {
4450 	int ret;
4451 	int s3_state;
4452 	struct drm_device *drm_dev = dev_get_drvdata(device);
4453 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
4454 
4455 	ret = kstrtoint(buf, 0, &s3_state);
4456 
4457 	if (ret == 0) {
4458 		if (s3_state) {
4459 			dm_resume(adev);
4460 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
4461 		} else
4462 			dm_suspend(adev);
4463 	}
4464 
4465 	return ret == 0 ? count : 0;
4466 }
4467 
4468 DEVICE_ATTR_WO(s3_debug);
4469 
4470 #endif
4471 
4472 static int dm_early_init(void *handle)
4473 {
4474 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4475 
4476 	switch (adev->asic_type) {
4477 #if defined(CONFIG_DRM_AMD_DC_SI)
4478 	case CHIP_TAHITI:
4479 	case CHIP_PITCAIRN:
4480 	case CHIP_VERDE:
4481 		adev->mode_info.num_crtc = 6;
4482 		adev->mode_info.num_hpd = 6;
4483 		adev->mode_info.num_dig = 6;
4484 		break;
4485 	case CHIP_OLAND:
4486 		adev->mode_info.num_crtc = 2;
4487 		adev->mode_info.num_hpd = 2;
4488 		adev->mode_info.num_dig = 2;
4489 		break;
4490 #endif
4491 	case CHIP_BONAIRE:
4492 	case CHIP_HAWAII:
4493 		adev->mode_info.num_crtc = 6;
4494 		adev->mode_info.num_hpd = 6;
4495 		adev->mode_info.num_dig = 6;
4496 		break;
4497 	case CHIP_KAVERI:
4498 		adev->mode_info.num_crtc = 4;
4499 		adev->mode_info.num_hpd = 6;
4500 		adev->mode_info.num_dig = 7;
4501 		break;
4502 	case CHIP_KABINI:
4503 	case CHIP_MULLINS:
4504 		adev->mode_info.num_crtc = 2;
4505 		adev->mode_info.num_hpd = 6;
4506 		adev->mode_info.num_dig = 6;
4507 		break;
4508 	case CHIP_FIJI:
4509 	case CHIP_TONGA:
4510 		adev->mode_info.num_crtc = 6;
4511 		adev->mode_info.num_hpd = 6;
4512 		adev->mode_info.num_dig = 7;
4513 		break;
4514 	case CHIP_CARRIZO:
4515 		adev->mode_info.num_crtc = 3;
4516 		adev->mode_info.num_hpd = 6;
4517 		adev->mode_info.num_dig = 9;
4518 		break;
4519 	case CHIP_STONEY:
4520 		adev->mode_info.num_crtc = 2;
4521 		adev->mode_info.num_hpd = 6;
4522 		adev->mode_info.num_dig = 9;
4523 		break;
4524 	case CHIP_POLARIS11:
4525 	case CHIP_POLARIS12:
4526 		adev->mode_info.num_crtc = 5;
4527 		adev->mode_info.num_hpd = 5;
4528 		adev->mode_info.num_dig = 5;
4529 		break;
4530 	case CHIP_POLARIS10:
4531 	case CHIP_VEGAM:
4532 		adev->mode_info.num_crtc = 6;
4533 		adev->mode_info.num_hpd = 6;
4534 		adev->mode_info.num_dig = 6;
4535 		break;
4536 	case CHIP_VEGA10:
4537 	case CHIP_VEGA12:
4538 	case CHIP_VEGA20:
4539 		adev->mode_info.num_crtc = 6;
4540 		adev->mode_info.num_hpd = 6;
4541 		adev->mode_info.num_dig = 6;
4542 		break;
4543 	default:
4544 
4545 		switch (adev->ip_versions[DCE_HWIP][0]) {
4546 		case IP_VERSION(2, 0, 2):
4547 		case IP_VERSION(3, 0, 0):
4548 			adev->mode_info.num_crtc = 6;
4549 			adev->mode_info.num_hpd = 6;
4550 			adev->mode_info.num_dig = 6;
4551 			break;
4552 		case IP_VERSION(2, 0, 0):
4553 		case IP_VERSION(3, 0, 2):
4554 			adev->mode_info.num_crtc = 5;
4555 			adev->mode_info.num_hpd = 5;
4556 			adev->mode_info.num_dig = 5;
4557 			break;
4558 		case IP_VERSION(2, 0, 3):
4559 		case IP_VERSION(3, 0, 3):
4560 			adev->mode_info.num_crtc = 2;
4561 			adev->mode_info.num_hpd = 2;
4562 			adev->mode_info.num_dig = 2;
4563 			break;
4564 		case IP_VERSION(1, 0, 0):
4565 		case IP_VERSION(1, 0, 1):
4566 		case IP_VERSION(3, 0, 1):
4567 		case IP_VERSION(2, 1, 0):
4568 		case IP_VERSION(3, 1, 2):
4569 		case IP_VERSION(3, 1, 3):
4570 		case IP_VERSION(3, 1, 4):
4571 		case IP_VERSION(3, 1, 5):
4572 		case IP_VERSION(3, 1, 6):
4573 		case IP_VERSION(3, 2, 0):
4574 		case IP_VERSION(3, 2, 1):
4575 			adev->mode_info.num_crtc = 4;
4576 			adev->mode_info.num_hpd = 4;
4577 			adev->mode_info.num_dig = 4;
4578 			break;
4579 		default:
4580 			DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4581 					adev->ip_versions[DCE_HWIP][0]);
4582 			return -EINVAL;
4583 		}
4584 		break;
4585 	}
4586 
4587 	amdgpu_dm_set_irq_funcs(adev);
4588 
4589 	if (adev->mode_info.funcs == NULL)
4590 		adev->mode_info.funcs = &dm_display_funcs;
4591 
4592 	/*
4593 	 * Note: Do NOT change adev->audio_endpt_rreg and
4594 	 * adev->audio_endpt_wreg because they are initialised in
4595 	 * amdgpu_device_init()
4596 	 */
4597 #if defined(CONFIG_DEBUG_KERNEL_DC)
4598 	device_create_file(
4599 		adev_to_drm(adev)->dev,
4600 		&dev_attr_s3_debug);
4601 #endif
4602 	adev->dc_enabled = true;
4603 
4604 	return 0;
4605 }
4606 
4607 static bool modereset_required(struct drm_crtc_state *crtc_state)
4608 {
4609 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4610 }
4611 
4612 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4613 {
4614 	drm_encoder_cleanup(encoder);
4615 	kfree(encoder);
4616 }
4617 
4618 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4619 	.destroy = amdgpu_dm_encoder_destroy,
4620 };
4621 
4622 static int
4623 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4624 			    const enum surface_pixel_format format,
4625 			    enum dc_color_space *color_space)
4626 {
4627 	bool full_range;
4628 
4629 	*color_space = COLOR_SPACE_SRGB;
4630 
4631 	/* DRM color properties only affect non-RGB formats. */
4632 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4633 		return 0;
4634 
4635 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4636 
4637 	switch (plane_state->color_encoding) {
4638 	case DRM_COLOR_YCBCR_BT601:
4639 		if (full_range)
4640 			*color_space = COLOR_SPACE_YCBCR601;
4641 		else
4642 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
4643 		break;
4644 
4645 	case DRM_COLOR_YCBCR_BT709:
4646 		if (full_range)
4647 			*color_space = COLOR_SPACE_YCBCR709;
4648 		else
4649 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
4650 		break;
4651 
4652 	case DRM_COLOR_YCBCR_BT2020:
4653 		if (full_range)
4654 			*color_space = COLOR_SPACE_2020_YCBCR;
4655 		else
4656 			return -EINVAL;
4657 		break;
4658 
4659 	default:
4660 		return -EINVAL;
4661 	}
4662 
4663 	return 0;
4664 }
4665 
4666 static int
4667 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4668 			    const struct drm_plane_state *plane_state,
4669 			    const uint64_t tiling_flags,
4670 			    struct dc_plane_info *plane_info,
4671 			    struct dc_plane_address *address,
4672 			    bool tmz_surface,
4673 			    bool force_disable_dcc)
4674 {
4675 	const struct drm_framebuffer *fb = plane_state->fb;
4676 	const struct amdgpu_framebuffer *afb =
4677 		to_amdgpu_framebuffer(plane_state->fb);
4678 	int ret;
4679 
4680 	memset(plane_info, 0, sizeof(*plane_info));
4681 
4682 	switch (fb->format->format) {
4683 	case DRM_FORMAT_C8:
4684 		plane_info->format =
4685 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4686 		break;
4687 	case DRM_FORMAT_RGB565:
4688 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4689 		break;
4690 	case DRM_FORMAT_XRGB8888:
4691 	case DRM_FORMAT_ARGB8888:
4692 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4693 		break;
4694 	case DRM_FORMAT_XRGB2101010:
4695 	case DRM_FORMAT_ARGB2101010:
4696 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4697 		break;
4698 	case DRM_FORMAT_XBGR2101010:
4699 	case DRM_FORMAT_ABGR2101010:
4700 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4701 		break;
4702 	case DRM_FORMAT_XBGR8888:
4703 	case DRM_FORMAT_ABGR8888:
4704 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4705 		break;
4706 	case DRM_FORMAT_NV21:
4707 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4708 		break;
4709 	case DRM_FORMAT_NV12:
4710 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4711 		break;
4712 	case DRM_FORMAT_P010:
4713 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4714 		break;
4715 	case DRM_FORMAT_XRGB16161616F:
4716 	case DRM_FORMAT_ARGB16161616F:
4717 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4718 		break;
4719 	case DRM_FORMAT_XBGR16161616F:
4720 	case DRM_FORMAT_ABGR16161616F:
4721 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4722 		break;
4723 	case DRM_FORMAT_XRGB16161616:
4724 	case DRM_FORMAT_ARGB16161616:
4725 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4726 		break;
4727 	case DRM_FORMAT_XBGR16161616:
4728 	case DRM_FORMAT_ABGR16161616:
4729 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4730 		break;
4731 	default:
4732 		DRM_ERROR(
4733 			"Unsupported screen format %p4cc\n",
4734 			&fb->format->format);
4735 		return -EINVAL;
4736 	}
4737 
4738 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4739 	case DRM_MODE_ROTATE_0:
4740 		plane_info->rotation = ROTATION_ANGLE_0;
4741 		break;
4742 	case DRM_MODE_ROTATE_90:
4743 		plane_info->rotation = ROTATION_ANGLE_90;
4744 		break;
4745 	case DRM_MODE_ROTATE_180:
4746 		plane_info->rotation = ROTATION_ANGLE_180;
4747 		break;
4748 	case DRM_MODE_ROTATE_270:
4749 		plane_info->rotation = ROTATION_ANGLE_270;
4750 		break;
4751 	default:
4752 		plane_info->rotation = ROTATION_ANGLE_0;
4753 		break;
4754 	}
4755 
4756 
4757 	plane_info->visible = true;
4758 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4759 
4760 	plane_info->layer_index = plane_state->normalized_zpos;
4761 
4762 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
4763 					  &plane_info->color_space);
4764 	if (ret)
4765 		return ret;
4766 
4767 	ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4768 					   plane_info->rotation, tiling_flags,
4769 					   &plane_info->tiling_info,
4770 					   &plane_info->plane_size,
4771 					   &plane_info->dcc, address,
4772 					   tmz_surface, force_disable_dcc);
4773 	if (ret)
4774 		return ret;
4775 
4776 	fill_blending_from_plane_state(
4777 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4778 		&plane_info->global_alpha, &plane_info->global_alpha_value);
4779 
4780 	return 0;
4781 }
4782 
4783 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4784 				    struct dc_plane_state *dc_plane_state,
4785 				    struct drm_plane_state *plane_state,
4786 				    struct drm_crtc_state *crtc_state)
4787 {
4788 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4789 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4790 	struct dc_scaling_info scaling_info;
4791 	struct dc_plane_info plane_info;
4792 	int ret;
4793 	bool force_disable_dcc = false;
4794 
4795 	ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4796 	if (ret)
4797 		return ret;
4798 
4799 	dc_plane_state->src_rect = scaling_info.src_rect;
4800 	dc_plane_state->dst_rect = scaling_info.dst_rect;
4801 	dc_plane_state->clip_rect = scaling_info.clip_rect;
4802 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
4803 
4804 	force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
4805 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
4806 					  afb->tiling_flags,
4807 					  &plane_info,
4808 					  &dc_plane_state->address,
4809 					  afb->tmz_surface,
4810 					  force_disable_dcc);
4811 	if (ret)
4812 		return ret;
4813 
4814 	dc_plane_state->format = plane_info.format;
4815 	dc_plane_state->color_space = plane_info.color_space;
4816 	dc_plane_state->format = plane_info.format;
4817 	dc_plane_state->plane_size = plane_info.plane_size;
4818 	dc_plane_state->rotation = plane_info.rotation;
4819 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
4820 	dc_plane_state->stereo_format = plane_info.stereo_format;
4821 	dc_plane_state->tiling_info = plane_info.tiling_info;
4822 	dc_plane_state->visible = plane_info.visible;
4823 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
4824 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
4825 	dc_plane_state->global_alpha = plane_info.global_alpha;
4826 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
4827 	dc_plane_state->dcc = plane_info.dcc;
4828 	dc_plane_state->layer_index = plane_info.layer_index;
4829 	dc_plane_state->flip_int_enabled = true;
4830 
4831 	/*
4832 	 * Always set input transfer function, since plane state is refreshed
4833 	 * every time.
4834 	 */
4835 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
4836 	if (ret)
4837 		return ret;
4838 
4839 	return 0;
4840 }
4841 
4842 /**
4843  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
4844  *
4845  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
4846  *         remote fb
4847  * @old_plane_state: Old state of @plane
4848  * @new_plane_state: New state of @plane
4849  * @crtc_state: New state of CRTC connected to the @plane
4850  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
4851  *
4852  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
4853  * (referred to as "damage clips" in DRM nomenclature) that require updating on
4854  * the eDP remote buffer. The responsibility of specifying the dirty regions is
4855  * amdgpu_dm's.
4856  *
4857  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
4858  * plane with regions that require flushing to the eDP remote buffer. In
4859  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
4860  * implicitly provide damage clips without any client support via the plane
4861  * bounds.
4862  *
4863  * Today, amdgpu_dm only supports the MPO and cursor usecase.
4864  *
4865  * TODO: Also enable for FB_DAMAGE_CLIPS
4866  */
4867 static void fill_dc_dirty_rects(struct drm_plane *plane,
4868 				struct drm_plane_state *old_plane_state,
4869 				struct drm_plane_state *new_plane_state,
4870 				struct drm_crtc_state *crtc_state,
4871 				struct dc_flip_addrs *flip_addrs)
4872 {
4873 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4874 	struct rect *dirty_rects = flip_addrs->dirty_rects;
4875 	uint32_t num_clips;
4876 	bool bb_changed;
4877 	bool fb_changed;
4878 	uint32_t i = 0;
4879 
4880 	flip_addrs->dirty_rect_count = 0;
4881 
4882 	/*
4883 	 * Cursor plane has it's own dirty rect update interface. See
4884 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
4885 	 */
4886 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
4887 		return;
4888 
4889 	/*
4890 	 * Today, we only consider MPO use-case for PSR SU. If MPO not
4891 	 * requested, and there is a plane update, do FFU.
4892 	 */
4893 	if (!dm_crtc_state->mpo_requested) {
4894 		dirty_rects[0].x = 0;
4895 		dirty_rects[0].y = 0;
4896 		dirty_rects[0].width = dm_crtc_state->base.mode.crtc_hdisplay;
4897 		dirty_rects[0].height = dm_crtc_state->base.mode.crtc_vdisplay;
4898 		flip_addrs->dirty_rect_count = 1;
4899 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
4900 				 new_plane_state->plane->base.id,
4901 				 dm_crtc_state->base.mode.crtc_hdisplay,
4902 				 dm_crtc_state->base.mode.crtc_vdisplay);
4903 		return;
4904 	}
4905 
4906 	/*
4907 	 * MPO is requested. Add entire plane bounding box to dirty rects if
4908 	 * flipped to or damaged.
4909 	 *
4910 	 * If plane is moved or resized, also add old bounding box to dirty
4911 	 * rects.
4912 	 */
4913 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
4914 	fb_changed = old_plane_state->fb->base.id !=
4915 		     new_plane_state->fb->base.id;
4916 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
4917 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
4918 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
4919 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
4920 
4921 	DRM_DEBUG_DRIVER("[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
4922 			 new_plane_state->plane->base.id,
4923 			 bb_changed, fb_changed, num_clips);
4924 
4925 	if (num_clips || fb_changed || bb_changed) {
4926 		dirty_rects[i].x = new_plane_state->crtc_x;
4927 		dirty_rects[i].y = new_plane_state->crtc_y;
4928 		dirty_rects[i].width = new_plane_state->crtc_w;
4929 		dirty_rects[i].height = new_plane_state->crtc_h;
4930 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)\n",
4931 				 new_plane_state->plane->base.id,
4932 				 dirty_rects[i].x, dirty_rects[i].y,
4933 				 dirty_rects[i].width, dirty_rects[i].height);
4934 		i += 1;
4935 	}
4936 
4937 	/* Add old plane bounding-box if plane is moved or resized */
4938 	if (bb_changed) {
4939 		dirty_rects[i].x = old_plane_state->crtc_x;
4940 		dirty_rects[i].y = old_plane_state->crtc_y;
4941 		dirty_rects[i].width = old_plane_state->crtc_w;
4942 		dirty_rects[i].height = old_plane_state->crtc_h;
4943 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)\n",
4944 				old_plane_state->plane->base.id,
4945 				dirty_rects[i].x, dirty_rects[i].y,
4946 				dirty_rects[i].width, dirty_rects[i].height);
4947 		i += 1;
4948 	}
4949 
4950 	flip_addrs->dirty_rect_count = i;
4951 }
4952 
4953 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
4954 					   const struct dm_connector_state *dm_state,
4955 					   struct dc_stream_state *stream)
4956 {
4957 	enum amdgpu_rmx_type rmx_type;
4958 
4959 	struct rect src = { 0 }; /* viewport in composition space*/
4960 	struct rect dst = { 0 }; /* stream addressable area */
4961 
4962 	/* no mode. nothing to be done */
4963 	if (!mode)
4964 		return;
4965 
4966 	/* Full screen scaling by default */
4967 	src.width = mode->hdisplay;
4968 	src.height = mode->vdisplay;
4969 	dst.width = stream->timing.h_addressable;
4970 	dst.height = stream->timing.v_addressable;
4971 
4972 	if (dm_state) {
4973 		rmx_type = dm_state->scaling;
4974 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
4975 			if (src.width * dst.height <
4976 					src.height * dst.width) {
4977 				/* height needs less upscaling/more downscaling */
4978 				dst.width = src.width *
4979 						dst.height / src.height;
4980 			} else {
4981 				/* width needs less upscaling/more downscaling */
4982 				dst.height = src.height *
4983 						dst.width / src.width;
4984 			}
4985 		} else if (rmx_type == RMX_CENTER) {
4986 			dst = src;
4987 		}
4988 
4989 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
4990 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
4991 
4992 		if (dm_state->underscan_enable) {
4993 			dst.x += dm_state->underscan_hborder / 2;
4994 			dst.y += dm_state->underscan_vborder / 2;
4995 			dst.width -= dm_state->underscan_hborder;
4996 			dst.height -= dm_state->underscan_vborder;
4997 		}
4998 	}
4999 
5000 	stream->src = src;
5001 	stream->dst = dst;
5002 
5003 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5004 		      dst.x, dst.y, dst.width, dst.height);
5005 
5006 }
5007 
5008 static enum dc_color_depth
5009 convert_color_depth_from_display_info(const struct drm_connector *connector,
5010 				      bool is_y420, int requested_bpc)
5011 {
5012 	uint8_t bpc;
5013 
5014 	if (is_y420) {
5015 		bpc = 8;
5016 
5017 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
5018 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5019 			bpc = 16;
5020 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5021 			bpc = 12;
5022 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5023 			bpc = 10;
5024 	} else {
5025 		bpc = (uint8_t)connector->display_info.bpc;
5026 		/* Assume 8 bpc by default if no bpc is specified. */
5027 		bpc = bpc ? bpc : 8;
5028 	}
5029 
5030 	if (requested_bpc > 0) {
5031 		/*
5032 		 * Cap display bpc based on the user requested value.
5033 		 *
5034 		 * The value for state->max_bpc may not correctly updated
5035 		 * depending on when the connector gets added to the state
5036 		 * or if this was called outside of atomic check, so it
5037 		 * can't be used directly.
5038 		 */
5039 		bpc = min_t(u8, bpc, requested_bpc);
5040 
5041 		/* Round down to the nearest even number. */
5042 		bpc = bpc - (bpc & 1);
5043 	}
5044 
5045 	switch (bpc) {
5046 	case 0:
5047 		/*
5048 		 * Temporary Work around, DRM doesn't parse color depth for
5049 		 * EDID revision before 1.4
5050 		 * TODO: Fix edid parsing
5051 		 */
5052 		return COLOR_DEPTH_888;
5053 	case 6:
5054 		return COLOR_DEPTH_666;
5055 	case 8:
5056 		return COLOR_DEPTH_888;
5057 	case 10:
5058 		return COLOR_DEPTH_101010;
5059 	case 12:
5060 		return COLOR_DEPTH_121212;
5061 	case 14:
5062 		return COLOR_DEPTH_141414;
5063 	case 16:
5064 		return COLOR_DEPTH_161616;
5065 	default:
5066 		return COLOR_DEPTH_UNDEFINED;
5067 	}
5068 }
5069 
5070 static enum dc_aspect_ratio
5071 get_aspect_ratio(const struct drm_display_mode *mode_in)
5072 {
5073 	/* 1-1 mapping, since both enums follow the HDMI spec. */
5074 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5075 }
5076 
5077 static enum dc_color_space
5078 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5079 {
5080 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
5081 
5082 	switch (dc_crtc_timing->pixel_encoding)	{
5083 	case PIXEL_ENCODING_YCBCR422:
5084 	case PIXEL_ENCODING_YCBCR444:
5085 	case PIXEL_ENCODING_YCBCR420:
5086 	{
5087 		/*
5088 		 * 27030khz is the separation point between HDTV and SDTV
5089 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
5090 		 * respectively
5091 		 */
5092 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
5093 			if (dc_crtc_timing->flags.Y_ONLY)
5094 				color_space =
5095 					COLOR_SPACE_YCBCR709_LIMITED;
5096 			else
5097 				color_space = COLOR_SPACE_YCBCR709;
5098 		} else {
5099 			if (dc_crtc_timing->flags.Y_ONLY)
5100 				color_space =
5101 					COLOR_SPACE_YCBCR601_LIMITED;
5102 			else
5103 				color_space = COLOR_SPACE_YCBCR601;
5104 		}
5105 
5106 	}
5107 	break;
5108 	case PIXEL_ENCODING_RGB:
5109 		color_space = COLOR_SPACE_SRGB;
5110 		break;
5111 
5112 	default:
5113 		WARN_ON(1);
5114 		break;
5115 	}
5116 
5117 	return color_space;
5118 }
5119 
5120 static bool adjust_colour_depth_from_display_info(
5121 	struct dc_crtc_timing *timing_out,
5122 	const struct drm_display_info *info)
5123 {
5124 	enum dc_color_depth depth = timing_out->display_color_depth;
5125 	int normalized_clk;
5126 	do {
5127 		normalized_clk = timing_out->pix_clk_100hz / 10;
5128 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5129 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5130 			normalized_clk /= 2;
5131 		/* Adjusting pix clock following on HDMI spec based on colour depth */
5132 		switch (depth) {
5133 		case COLOR_DEPTH_888:
5134 			break;
5135 		case COLOR_DEPTH_101010:
5136 			normalized_clk = (normalized_clk * 30) / 24;
5137 			break;
5138 		case COLOR_DEPTH_121212:
5139 			normalized_clk = (normalized_clk * 36) / 24;
5140 			break;
5141 		case COLOR_DEPTH_161616:
5142 			normalized_clk = (normalized_clk * 48) / 24;
5143 			break;
5144 		default:
5145 			/* The above depths are the only ones valid for HDMI. */
5146 			return false;
5147 		}
5148 		if (normalized_clk <= info->max_tmds_clock) {
5149 			timing_out->display_color_depth = depth;
5150 			return true;
5151 		}
5152 	} while (--depth > COLOR_DEPTH_666);
5153 	return false;
5154 }
5155 
5156 static void fill_stream_properties_from_drm_display_mode(
5157 	struct dc_stream_state *stream,
5158 	const struct drm_display_mode *mode_in,
5159 	const struct drm_connector *connector,
5160 	const struct drm_connector_state *connector_state,
5161 	const struct dc_stream_state *old_stream,
5162 	int requested_bpc)
5163 {
5164 	struct dc_crtc_timing *timing_out = &stream->timing;
5165 	const struct drm_display_info *info = &connector->display_info;
5166 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5167 	struct hdmi_vendor_infoframe hv_frame;
5168 	struct hdmi_avi_infoframe avi_frame;
5169 
5170 	memset(&hv_frame, 0, sizeof(hv_frame));
5171 	memset(&avi_frame, 0, sizeof(avi_frame));
5172 
5173 	timing_out->h_border_left = 0;
5174 	timing_out->h_border_right = 0;
5175 	timing_out->v_border_top = 0;
5176 	timing_out->v_border_bottom = 0;
5177 	/* TODO: un-hardcode */
5178 	if (drm_mode_is_420_only(info, mode_in)
5179 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5180 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5181 	else if (drm_mode_is_420_also(info, mode_in)
5182 			&& aconnector->force_yuv420_output)
5183 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5184 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5185 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5186 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5187 	else
5188 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5189 
5190 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5191 	timing_out->display_color_depth = convert_color_depth_from_display_info(
5192 		connector,
5193 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5194 		requested_bpc);
5195 	timing_out->scan_type = SCANNING_TYPE_NODATA;
5196 	timing_out->hdmi_vic = 0;
5197 
5198 	if (old_stream) {
5199 		timing_out->vic = old_stream->timing.vic;
5200 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5201 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5202 	} else {
5203 		timing_out->vic = drm_match_cea_mode(mode_in);
5204 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5205 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5206 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5207 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5208 	}
5209 
5210 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5211 		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5212 		timing_out->vic = avi_frame.video_code;
5213 		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5214 		timing_out->hdmi_vic = hv_frame.vic;
5215 	}
5216 
5217 	if (is_freesync_video_mode(mode_in, aconnector)) {
5218 		timing_out->h_addressable = mode_in->hdisplay;
5219 		timing_out->h_total = mode_in->htotal;
5220 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5221 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5222 		timing_out->v_total = mode_in->vtotal;
5223 		timing_out->v_addressable = mode_in->vdisplay;
5224 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5225 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5226 		timing_out->pix_clk_100hz = mode_in->clock * 10;
5227 	} else {
5228 		timing_out->h_addressable = mode_in->crtc_hdisplay;
5229 		timing_out->h_total = mode_in->crtc_htotal;
5230 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5231 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5232 		timing_out->v_total = mode_in->crtc_vtotal;
5233 		timing_out->v_addressable = mode_in->crtc_vdisplay;
5234 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5235 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5236 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5237 	}
5238 
5239 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5240 
5241 	stream->output_color_space = get_output_color_space(timing_out);
5242 
5243 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5244 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5245 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5246 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5247 		    drm_mode_is_420_also(info, mode_in) &&
5248 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5249 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5250 			adjust_colour_depth_from_display_info(timing_out, info);
5251 		}
5252 	}
5253 }
5254 
5255 static void fill_audio_info(struct audio_info *audio_info,
5256 			    const struct drm_connector *drm_connector,
5257 			    const struct dc_sink *dc_sink)
5258 {
5259 	int i = 0;
5260 	int cea_revision = 0;
5261 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5262 
5263 	audio_info->manufacture_id = edid_caps->manufacturer_id;
5264 	audio_info->product_id = edid_caps->product_id;
5265 
5266 	cea_revision = drm_connector->display_info.cea_rev;
5267 
5268 	strscpy(audio_info->display_name,
5269 		edid_caps->display_name,
5270 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5271 
5272 	if (cea_revision >= 3) {
5273 		audio_info->mode_count = edid_caps->audio_mode_count;
5274 
5275 		for (i = 0; i < audio_info->mode_count; ++i) {
5276 			audio_info->modes[i].format_code =
5277 					(enum audio_format_code)
5278 					(edid_caps->audio_modes[i].format_code);
5279 			audio_info->modes[i].channel_count =
5280 					edid_caps->audio_modes[i].channel_count;
5281 			audio_info->modes[i].sample_rates.all =
5282 					edid_caps->audio_modes[i].sample_rate;
5283 			audio_info->modes[i].sample_size =
5284 					edid_caps->audio_modes[i].sample_size;
5285 		}
5286 	}
5287 
5288 	audio_info->flags.all = edid_caps->speaker_flags;
5289 
5290 	/* TODO: We only check for the progressive mode, check for interlace mode too */
5291 	if (drm_connector->latency_present[0]) {
5292 		audio_info->video_latency = drm_connector->video_latency[0];
5293 		audio_info->audio_latency = drm_connector->audio_latency[0];
5294 	}
5295 
5296 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5297 
5298 }
5299 
5300 static void
5301 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5302 				      struct drm_display_mode *dst_mode)
5303 {
5304 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5305 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5306 	dst_mode->crtc_clock = src_mode->crtc_clock;
5307 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5308 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5309 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5310 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5311 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
5312 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
5313 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5314 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5315 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5316 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5317 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5318 }
5319 
5320 static void
5321 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5322 					const struct drm_display_mode *native_mode,
5323 					bool scale_enabled)
5324 {
5325 	if (scale_enabled) {
5326 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5327 	} else if (native_mode->clock == drm_mode->clock &&
5328 			native_mode->htotal == drm_mode->htotal &&
5329 			native_mode->vtotal == drm_mode->vtotal) {
5330 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5331 	} else {
5332 		/* no scaling nor amdgpu inserted, no need to patch */
5333 	}
5334 }
5335 
5336 static struct dc_sink *
5337 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5338 {
5339 	struct dc_sink_init_data sink_init_data = { 0 };
5340 	struct dc_sink *sink = NULL;
5341 	sink_init_data.link = aconnector->dc_link;
5342 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5343 
5344 	sink = dc_sink_create(&sink_init_data);
5345 	if (!sink) {
5346 		DRM_ERROR("Failed to create sink!\n");
5347 		return NULL;
5348 	}
5349 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5350 
5351 	return sink;
5352 }
5353 
5354 static void set_multisync_trigger_params(
5355 		struct dc_stream_state *stream)
5356 {
5357 	struct dc_stream_state *master = NULL;
5358 
5359 	if (stream->triggered_crtc_reset.enabled) {
5360 		master = stream->triggered_crtc_reset.event_source;
5361 		stream->triggered_crtc_reset.event =
5362 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5363 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5364 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5365 	}
5366 }
5367 
5368 static void set_master_stream(struct dc_stream_state *stream_set[],
5369 			      int stream_count)
5370 {
5371 	int j, highest_rfr = 0, master_stream = 0;
5372 
5373 	for (j = 0;  j < stream_count; j++) {
5374 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5375 			int refresh_rate = 0;
5376 
5377 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5378 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5379 			if (refresh_rate > highest_rfr) {
5380 				highest_rfr = refresh_rate;
5381 				master_stream = j;
5382 			}
5383 		}
5384 	}
5385 	for (j = 0;  j < stream_count; j++) {
5386 		if (stream_set[j])
5387 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5388 	}
5389 }
5390 
5391 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5392 {
5393 	int i = 0;
5394 	struct dc_stream_state *stream;
5395 
5396 	if (context->stream_count < 2)
5397 		return;
5398 	for (i = 0; i < context->stream_count ; i++) {
5399 		if (!context->streams[i])
5400 			continue;
5401 		/*
5402 		 * TODO: add a function to read AMD VSDB bits and set
5403 		 * crtc_sync_master.multi_sync_enabled flag
5404 		 * For now it's set to false
5405 		 */
5406 	}
5407 
5408 	set_master_stream(context->streams, context->stream_count);
5409 
5410 	for (i = 0; i < context->stream_count ; i++) {
5411 		stream = context->streams[i];
5412 
5413 		if (!stream)
5414 			continue;
5415 
5416 		set_multisync_trigger_params(stream);
5417 	}
5418 }
5419 
5420 /**
5421  * DOC: FreeSync Video
5422  *
5423  * When a userspace application wants to play a video, the content follows a
5424  * standard format definition that usually specifies the FPS for that format.
5425  * The below list illustrates some video format and the expected FPS,
5426  * respectively:
5427  *
5428  * - TV/NTSC (23.976 FPS)
5429  * - Cinema (24 FPS)
5430  * - TV/PAL (25 FPS)
5431  * - TV/NTSC (29.97 FPS)
5432  * - TV/NTSC (30 FPS)
5433  * - Cinema HFR (48 FPS)
5434  * - TV/PAL (50 FPS)
5435  * - Commonly used (60 FPS)
5436  * - Multiples of 24 (48,72,96 FPS)
5437  *
5438  * The list of standards video format is not huge and can be added to the
5439  * connector modeset list beforehand. With that, userspace can leverage
5440  * FreeSync to extends the front porch in order to attain the target refresh
5441  * rate. Such a switch will happen seamlessly, without screen blanking or
5442  * reprogramming of the output in any other way. If the userspace requests a
5443  * modesetting change compatible with FreeSync modes that only differ in the
5444  * refresh rate, DC will skip the full update and avoid blink during the
5445  * transition. For example, the video player can change the modesetting from
5446  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5447  * causing any display blink. This same concept can be applied to a mode
5448  * setting change.
5449  */
5450 static struct drm_display_mode *
5451 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5452 		bool use_probed_modes)
5453 {
5454 	struct drm_display_mode *m, *m_pref = NULL;
5455 	u16 current_refresh, highest_refresh;
5456 	struct list_head *list_head = use_probed_modes ?
5457 		&aconnector->base.probed_modes :
5458 		&aconnector->base.modes;
5459 
5460 	if (aconnector->freesync_vid_base.clock != 0)
5461 		return &aconnector->freesync_vid_base;
5462 
5463 	/* Find the preferred mode */
5464 	list_for_each_entry (m, list_head, head) {
5465 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
5466 			m_pref = m;
5467 			break;
5468 		}
5469 	}
5470 
5471 	if (!m_pref) {
5472 		/* Probably an EDID with no preferred mode. Fallback to first entry */
5473 		m_pref = list_first_entry_or_null(
5474 				&aconnector->base.modes, struct drm_display_mode, head);
5475 		if (!m_pref) {
5476 			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5477 			return NULL;
5478 		}
5479 	}
5480 
5481 	highest_refresh = drm_mode_vrefresh(m_pref);
5482 
5483 	/*
5484 	 * Find the mode with highest refresh rate with same resolution.
5485 	 * For some monitors, preferred mode is not the mode with highest
5486 	 * supported refresh rate.
5487 	 */
5488 	list_for_each_entry (m, list_head, head) {
5489 		current_refresh  = drm_mode_vrefresh(m);
5490 
5491 		if (m->hdisplay == m_pref->hdisplay &&
5492 		    m->vdisplay == m_pref->vdisplay &&
5493 		    highest_refresh < current_refresh) {
5494 			highest_refresh = current_refresh;
5495 			m_pref = m;
5496 		}
5497 	}
5498 
5499 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5500 	return m_pref;
5501 }
5502 
5503 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5504 		struct amdgpu_dm_connector *aconnector)
5505 {
5506 	struct drm_display_mode *high_mode;
5507 	int timing_diff;
5508 
5509 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
5510 	if (!high_mode || !mode)
5511 		return false;
5512 
5513 	timing_diff = high_mode->vtotal - mode->vtotal;
5514 
5515 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5516 	    high_mode->hdisplay != mode->hdisplay ||
5517 	    high_mode->vdisplay != mode->vdisplay ||
5518 	    high_mode->hsync_start != mode->hsync_start ||
5519 	    high_mode->hsync_end != mode->hsync_end ||
5520 	    high_mode->htotal != mode->htotal ||
5521 	    high_mode->hskew != mode->hskew ||
5522 	    high_mode->vscan != mode->vscan ||
5523 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
5524 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
5525 		return false;
5526 	else
5527 		return true;
5528 }
5529 
5530 #if defined(CONFIG_DRM_AMD_DC_DCN)
5531 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5532 			    struct dc_sink *sink, struct dc_stream_state *stream,
5533 			    struct dsc_dec_dpcd_caps *dsc_caps)
5534 {
5535 	stream->timing.flags.DSC = 0;
5536 	dsc_caps->is_dsc_supported = false;
5537 
5538 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5539 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
5540 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5541 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5542 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5543 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5544 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5545 				dsc_caps);
5546 	}
5547 }
5548 
5549 
5550 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5551 				    struct dc_sink *sink, struct dc_stream_state *stream,
5552 				    struct dsc_dec_dpcd_caps *dsc_caps,
5553 				    uint32_t max_dsc_target_bpp_limit_override)
5554 {
5555 	const struct dc_link_settings *verified_link_cap = NULL;
5556 	uint32_t link_bw_in_kbps;
5557 	uint32_t edp_min_bpp_x16, edp_max_bpp_x16;
5558 	struct dc *dc = sink->ctx->dc;
5559 	struct dc_dsc_bw_range bw_range = {0};
5560 	struct dc_dsc_config dsc_cfg = {0};
5561 
5562 	verified_link_cap = dc_link_get_link_cap(stream->link);
5563 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5564 	edp_min_bpp_x16 = 8 * 16;
5565 	edp_max_bpp_x16 = 8 * 16;
5566 
5567 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5568 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5569 
5570 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
5571 		edp_min_bpp_x16 = edp_max_bpp_x16;
5572 
5573 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5574 				dc->debug.dsc_min_slice_height_override,
5575 				edp_min_bpp_x16, edp_max_bpp_x16,
5576 				dsc_caps,
5577 				&stream->timing,
5578 				&bw_range)) {
5579 
5580 		if (bw_range.max_kbps < link_bw_in_kbps) {
5581 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5582 					dsc_caps,
5583 					dc->debug.dsc_min_slice_height_override,
5584 					max_dsc_target_bpp_limit_override,
5585 					0,
5586 					&stream->timing,
5587 					&dsc_cfg)) {
5588 				stream->timing.dsc_cfg = dsc_cfg;
5589 				stream->timing.flags.DSC = 1;
5590 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5591 			}
5592 			return;
5593 		}
5594 	}
5595 
5596 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5597 				dsc_caps,
5598 				dc->debug.dsc_min_slice_height_override,
5599 				max_dsc_target_bpp_limit_override,
5600 				link_bw_in_kbps,
5601 				&stream->timing,
5602 				&dsc_cfg)) {
5603 		stream->timing.dsc_cfg = dsc_cfg;
5604 		stream->timing.flags.DSC = 1;
5605 	}
5606 }
5607 
5608 
5609 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5610 					struct dc_sink *sink, struct dc_stream_state *stream,
5611 					struct dsc_dec_dpcd_caps *dsc_caps)
5612 {
5613 	struct drm_connector *drm_connector = &aconnector->base;
5614 	uint32_t link_bandwidth_kbps;
5615 	struct dc *dc = sink->ctx->dc;
5616 	uint32_t max_supported_bw_in_kbps, timing_bw_in_kbps;
5617 	uint32_t dsc_max_supported_bw_in_kbps;
5618 	uint32_t max_dsc_target_bpp_limit_override =
5619 		drm_connector->display_info.max_dsc_bpp;
5620 
5621 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5622 							dc_link_get_link_cap(aconnector->dc_link));
5623 
5624 	/* Set DSC policy according to dsc_clock_en */
5625 	dc_dsc_policy_set_enable_dsc_when_not_needed(
5626 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5627 
5628 	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5629 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5630 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5631 
5632 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5633 
5634 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5635 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5636 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5637 						dsc_caps,
5638 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5639 						max_dsc_target_bpp_limit_override,
5640 						link_bandwidth_kbps,
5641 						&stream->timing,
5642 						&stream->timing.dsc_cfg)) {
5643 				stream->timing.flags.DSC = 1;
5644 				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5645 			}
5646 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5647 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5648 			max_supported_bw_in_kbps = link_bandwidth_kbps;
5649 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5650 
5651 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5652 					max_supported_bw_in_kbps > 0 &&
5653 					dsc_max_supported_bw_in_kbps > 0)
5654 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5655 						dsc_caps,
5656 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5657 						max_dsc_target_bpp_limit_override,
5658 						dsc_max_supported_bw_in_kbps,
5659 						&stream->timing,
5660 						&stream->timing.dsc_cfg)) {
5661 					stream->timing.flags.DSC = 1;
5662 					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5663 									 __func__, drm_connector->name);
5664 				}
5665 		}
5666 	}
5667 
5668 	/* Overwrite the stream flag if DSC is enabled through debugfs */
5669 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5670 		stream->timing.flags.DSC = 1;
5671 
5672 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5673 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5674 
5675 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5676 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5677 
5678 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5679 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5680 }
5681 #endif /* CONFIG_DRM_AMD_DC_DCN */
5682 
5683 static struct dc_stream_state *
5684 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5685 		       const struct drm_display_mode *drm_mode,
5686 		       const struct dm_connector_state *dm_state,
5687 		       const struct dc_stream_state *old_stream,
5688 		       int requested_bpc)
5689 {
5690 	struct drm_display_mode *preferred_mode = NULL;
5691 	struct drm_connector *drm_connector;
5692 	const struct drm_connector_state *con_state =
5693 		dm_state ? &dm_state->base : NULL;
5694 	struct dc_stream_state *stream = NULL;
5695 	struct drm_display_mode mode;
5696 	struct drm_display_mode saved_mode;
5697 	struct drm_display_mode *freesync_mode = NULL;
5698 	bool native_mode_found = false;
5699 	bool recalculate_timing = false;
5700 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5701 	int mode_refresh;
5702 	int preferred_refresh = 0;
5703 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
5704 #if defined(CONFIG_DRM_AMD_DC_DCN)
5705 	struct dsc_dec_dpcd_caps dsc_caps;
5706 #endif
5707 
5708 	struct dc_sink *sink = NULL;
5709 
5710 	drm_mode_init(&mode, drm_mode);
5711 	memset(&saved_mode, 0, sizeof(saved_mode));
5712 
5713 	if (aconnector == NULL) {
5714 		DRM_ERROR("aconnector is NULL!\n");
5715 		return stream;
5716 	}
5717 
5718 	drm_connector = &aconnector->base;
5719 
5720 	if (!aconnector->dc_sink) {
5721 		sink = create_fake_sink(aconnector);
5722 		if (!sink)
5723 			return stream;
5724 	} else {
5725 		sink = aconnector->dc_sink;
5726 		dc_sink_retain(sink);
5727 	}
5728 
5729 	stream = dc_create_stream_for_sink(sink);
5730 
5731 	if (stream == NULL) {
5732 		DRM_ERROR("Failed to create stream for sink!\n");
5733 		goto finish;
5734 	}
5735 
5736 	stream->dm_stream_context = aconnector;
5737 
5738 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5739 		drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5740 
5741 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5742 		/* Search for preferred mode */
5743 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5744 			native_mode_found = true;
5745 			break;
5746 		}
5747 	}
5748 	if (!native_mode_found)
5749 		preferred_mode = list_first_entry_or_null(
5750 				&aconnector->base.modes,
5751 				struct drm_display_mode,
5752 				head);
5753 
5754 	mode_refresh = drm_mode_vrefresh(&mode);
5755 
5756 	if (preferred_mode == NULL) {
5757 		/*
5758 		 * This may not be an error, the use case is when we have no
5759 		 * usermode calls to reset and set mode upon hotplug. In this
5760 		 * case, we call set mode ourselves to restore the previous mode
5761 		 * and the modelist may not be filled in in time.
5762 		 */
5763 		DRM_DEBUG_DRIVER("No preferred mode found\n");
5764 	} else {
5765 		recalculate_timing = is_freesync_video_mode(&mode, aconnector);
5766 		if (recalculate_timing) {
5767 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5768 			drm_mode_copy(&saved_mode, &mode);
5769 			drm_mode_copy(&mode, freesync_mode);
5770 		} else {
5771 			decide_crtc_timing_for_drm_display_mode(
5772 					&mode, preferred_mode, scale);
5773 
5774 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
5775 		}
5776 	}
5777 
5778 	if (recalculate_timing)
5779 		drm_mode_set_crtcinfo(&saved_mode, 0);
5780 	else if (!dm_state)
5781 		drm_mode_set_crtcinfo(&mode, 0);
5782 
5783 	/*
5784 	* If scaling is enabled and refresh rate didn't change
5785 	* we copy the vic and polarities of the old timings
5786 	*/
5787 	if (!scale || mode_refresh != preferred_refresh)
5788 		fill_stream_properties_from_drm_display_mode(
5789 			stream, &mode, &aconnector->base, con_state, NULL,
5790 			requested_bpc);
5791 	else
5792 		fill_stream_properties_from_drm_display_mode(
5793 			stream, &mode, &aconnector->base, con_state, old_stream,
5794 			requested_bpc);
5795 
5796 #if defined(CONFIG_DRM_AMD_DC_DCN)
5797 	/* SST DSC determination policy */
5798 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
5799 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
5800 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
5801 #endif
5802 
5803 	update_stream_scaling_settings(&mode, dm_state, stream);
5804 
5805 	fill_audio_info(
5806 		&stream->audio_info,
5807 		drm_connector,
5808 		sink);
5809 
5810 	update_stream_signal(stream, sink);
5811 
5812 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5813 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
5814 
5815 	if (stream->link->psr_settings.psr_feature_enabled) {
5816 		//
5817 		// should decide stream support vsc sdp colorimetry capability
5818 		// before building vsc info packet
5819 		//
5820 		stream->use_vsc_sdp_for_colorimetry = false;
5821 		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
5822 			stream->use_vsc_sdp_for_colorimetry =
5823 				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
5824 		} else {
5825 			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
5826 				stream->use_vsc_sdp_for_colorimetry = true;
5827 		}
5828 		if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
5829 			tf = TRANSFER_FUNC_GAMMA_22;
5830 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
5831 		aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
5832 
5833 	}
5834 finish:
5835 	dc_sink_release(sink);
5836 
5837 	return stream;
5838 }
5839 
5840 static enum drm_connector_status
5841 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
5842 {
5843 	bool connected;
5844 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5845 
5846 	/*
5847 	 * Notes:
5848 	 * 1. This interface is NOT called in context of HPD irq.
5849 	 * 2. This interface *is called* in context of user-mode ioctl. Which
5850 	 * makes it a bad place for *any* MST-related activity.
5851 	 */
5852 
5853 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
5854 	    !aconnector->fake_enable)
5855 		connected = (aconnector->dc_sink != NULL);
5856 	else
5857 		connected = (aconnector->base.force == DRM_FORCE_ON ||
5858 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
5859 
5860 	update_subconnector_property(aconnector);
5861 
5862 	return (connected ? connector_status_connected :
5863 			connector_status_disconnected);
5864 }
5865 
5866 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
5867 					    struct drm_connector_state *connector_state,
5868 					    struct drm_property *property,
5869 					    uint64_t val)
5870 {
5871 	struct drm_device *dev = connector->dev;
5872 	struct amdgpu_device *adev = drm_to_adev(dev);
5873 	struct dm_connector_state *dm_old_state =
5874 		to_dm_connector_state(connector->state);
5875 	struct dm_connector_state *dm_new_state =
5876 		to_dm_connector_state(connector_state);
5877 
5878 	int ret = -EINVAL;
5879 
5880 	if (property == dev->mode_config.scaling_mode_property) {
5881 		enum amdgpu_rmx_type rmx_type;
5882 
5883 		switch (val) {
5884 		case DRM_MODE_SCALE_CENTER:
5885 			rmx_type = RMX_CENTER;
5886 			break;
5887 		case DRM_MODE_SCALE_ASPECT:
5888 			rmx_type = RMX_ASPECT;
5889 			break;
5890 		case DRM_MODE_SCALE_FULLSCREEN:
5891 			rmx_type = RMX_FULL;
5892 			break;
5893 		case DRM_MODE_SCALE_NONE:
5894 		default:
5895 			rmx_type = RMX_OFF;
5896 			break;
5897 		}
5898 
5899 		if (dm_old_state->scaling == rmx_type)
5900 			return 0;
5901 
5902 		dm_new_state->scaling = rmx_type;
5903 		ret = 0;
5904 	} else if (property == adev->mode_info.underscan_hborder_property) {
5905 		dm_new_state->underscan_hborder = val;
5906 		ret = 0;
5907 	} else if (property == adev->mode_info.underscan_vborder_property) {
5908 		dm_new_state->underscan_vborder = val;
5909 		ret = 0;
5910 	} else if (property == adev->mode_info.underscan_property) {
5911 		dm_new_state->underscan_enable = val;
5912 		ret = 0;
5913 	} else if (property == adev->mode_info.abm_level_property) {
5914 		dm_new_state->abm_level = val;
5915 		ret = 0;
5916 	}
5917 
5918 	return ret;
5919 }
5920 
5921 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
5922 					    const struct drm_connector_state *state,
5923 					    struct drm_property *property,
5924 					    uint64_t *val)
5925 {
5926 	struct drm_device *dev = connector->dev;
5927 	struct amdgpu_device *adev = drm_to_adev(dev);
5928 	struct dm_connector_state *dm_state =
5929 		to_dm_connector_state(state);
5930 	int ret = -EINVAL;
5931 
5932 	if (property == dev->mode_config.scaling_mode_property) {
5933 		switch (dm_state->scaling) {
5934 		case RMX_CENTER:
5935 			*val = DRM_MODE_SCALE_CENTER;
5936 			break;
5937 		case RMX_ASPECT:
5938 			*val = DRM_MODE_SCALE_ASPECT;
5939 			break;
5940 		case RMX_FULL:
5941 			*val = DRM_MODE_SCALE_FULLSCREEN;
5942 			break;
5943 		case RMX_OFF:
5944 		default:
5945 			*val = DRM_MODE_SCALE_NONE;
5946 			break;
5947 		}
5948 		ret = 0;
5949 	} else if (property == adev->mode_info.underscan_hborder_property) {
5950 		*val = dm_state->underscan_hborder;
5951 		ret = 0;
5952 	} else if (property == adev->mode_info.underscan_vborder_property) {
5953 		*val = dm_state->underscan_vborder;
5954 		ret = 0;
5955 	} else if (property == adev->mode_info.underscan_property) {
5956 		*val = dm_state->underscan_enable;
5957 		ret = 0;
5958 	} else if (property == adev->mode_info.abm_level_property) {
5959 		*val = dm_state->abm_level;
5960 		ret = 0;
5961 	}
5962 
5963 	return ret;
5964 }
5965 
5966 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
5967 {
5968 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
5969 
5970 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
5971 }
5972 
5973 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
5974 {
5975 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5976 	const struct dc_link *link = aconnector->dc_link;
5977 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
5978 	struct amdgpu_display_manager *dm = &adev->dm;
5979 	int i;
5980 
5981 	/*
5982 	 * Call only if mst_mgr was initialized before since it's not done
5983 	 * for all connector types.
5984 	 */
5985 	if (aconnector->mst_mgr.dev)
5986 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
5987 
5988 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
5989 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
5990 	for (i = 0; i < dm->num_of_edps; i++) {
5991 		if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
5992 			backlight_device_unregister(dm->backlight_dev[i]);
5993 			dm->backlight_dev[i] = NULL;
5994 		}
5995 	}
5996 #endif
5997 
5998 	if (aconnector->dc_em_sink)
5999 		dc_sink_release(aconnector->dc_em_sink);
6000 	aconnector->dc_em_sink = NULL;
6001 	if (aconnector->dc_sink)
6002 		dc_sink_release(aconnector->dc_sink);
6003 	aconnector->dc_sink = NULL;
6004 
6005 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6006 	drm_connector_unregister(connector);
6007 	drm_connector_cleanup(connector);
6008 	if (aconnector->i2c) {
6009 		i2c_del_adapter(&aconnector->i2c->base);
6010 		kfree(aconnector->i2c);
6011 	}
6012 	kfree(aconnector->dm_dp_aux.aux.name);
6013 
6014 	kfree(connector);
6015 }
6016 
6017 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6018 {
6019 	struct dm_connector_state *state =
6020 		to_dm_connector_state(connector->state);
6021 
6022 	if (connector->state)
6023 		__drm_atomic_helper_connector_destroy_state(connector->state);
6024 
6025 	kfree(state);
6026 
6027 	state = kzalloc(sizeof(*state), GFP_KERNEL);
6028 
6029 	if (state) {
6030 		state->scaling = RMX_OFF;
6031 		state->underscan_enable = false;
6032 		state->underscan_hborder = 0;
6033 		state->underscan_vborder = 0;
6034 		state->base.max_requested_bpc = 8;
6035 		state->vcpi_slots = 0;
6036 		state->pbn = 0;
6037 
6038 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6039 			state->abm_level = amdgpu_dm_abm_level;
6040 
6041 		__drm_atomic_helper_connector_reset(connector, &state->base);
6042 	}
6043 }
6044 
6045 struct drm_connector_state *
6046 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6047 {
6048 	struct dm_connector_state *state =
6049 		to_dm_connector_state(connector->state);
6050 
6051 	struct dm_connector_state *new_state =
6052 			kmemdup(state, sizeof(*state), GFP_KERNEL);
6053 
6054 	if (!new_state)
6055 		return NULL;
6056 
6057 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6058 
6059 	new_state->freesync_capable = state->freesync_capable;
6060 	new_state->abm_level = state->abm_level;
6061 	new_state->scaling = state->scaling;
6062 	new_state->underscan_enable = state->underscan_enable;
6063 	new_state->underscan_hborder = state->underscan_hborder;
6064 	new_state->underscan_vborder = state->underscan_vborder;
6065 	new_state->vcpi_slots = state->vcpi_slots;
6066 	new_state->pbn = state->pbn;
6067 	return &new_state->base;
6068 }
6069 
6070 static int
6071 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6072 {
6073 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6074 		to_amdgpu_dm_connector(connector);
6075 	int r;
6076 
6077 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6078 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6079 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6080 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6081 		if (r)
6082 			return r;
6083 	}
6084 
6085 #if defined(CONFIG_DEBUG_FS)
6086 	connector_debugfs_init(amdgpu_dm_connector);
6087 #endif
6088 
6089 	return 0;
6090 }
6091 
6092 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6093 	.reset = amdgpu_dm_connector_funcs_reset,
6094 	.detect = amdgpu_dm_connector_detect,
6095 	.fill_modes = drm_helper_probe_single_connector_modes,
6096 	.destroy = amdgpu_dm_connector_destroy,
6097 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6098 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6099 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6100 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6101 	.late_register = amdgpu_dm_connector_late_register,
6102 	.early_unregister = amdgpu_dm_connector_unregister
6103 };
6104 
6105 static int get_modes(struct drm_connector *connector)
6106 {
6107 	return amdgpu_dm_connector_get_modes(connector);
6108 }
6109 
6110 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6111 {
6112 	struct dc_sink_init_data init_params = {
6113 			.link = aconnector->dc_link,
6114 			.sink_signal = SIGNAL_TYPE_VIRTUAL
6115 	};
6116 	struct edid *edid;
6117 
6118 	if (!aconnector->base.edid_blob_ptr) {
6119 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6120 				aconnector->base.name);
6121 
6122 		aconnector->base.force = DRM_FORCE_OFF;
6123 		return;
6124 	}
6125 
6126 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6127 
6128 	aconnector->edid = edid;
6129 
6130 	aconnector->dc_em_sink = dc_link_add_remote_sink(
6131 		aconnector->dc_link,
6132 		(uint8_t *)edid,
6133 		(edid->extensions + 1) * EDID_LENGTH,
6134 		&init_params);
6135 
6136 	if (aconnector->base.force == DRM_FORCE_ON) {
6137 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
6138 		aconnector->dc_link->local_sink :
6139 		aconnector->dc_em_sink;
6140 		dc_sink_retain(aconnector->dc_sink);
6141 	}
6142 }
6143 
6144 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6145 {
6146 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6147 
6148 	/*
6149 	 * In case of headless boot with force on for DP managed connector
6150 	 * Those settings have to be != 0 to get initial modeset
6151 	 */
6152 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6153 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6154 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6155 	}
6156 
6157 	create_eml_sink(aconnector);
6158 }
6159 
6160 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
6161 						struct dc_stream_state *stream)
6162 {
6163 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
6164 	struct dc_plane_state *dc_plane_state = NULL;
6165 	struct dc_state *dc_state = NULL;
6166 
6167 	if (!stream)
6168 		goto cleanup;
6169 
6170 	dc_plane_state = dc_create_plane_state(dc);
6171 	if (!dc_plane_state)
6172 		goto cleanup;
6173 
6174 	dc_state = dc_create_state(dc);
6175 	if (!dc_state)
6176 		goto cleanup;
6177 
6178 	/* populate stream to plane */
6179 	dc_plane_state->src_rect.height  = stream->src.height;
6180 	dc_plane_state->src_rect.width   = stream->src.width;
6181 	dc_plane_state->dst_rect.height  = stream->src.height;
6182 	dc_plane_state->dst_rect.width   = stream->src.width;
6183 	dc_plane_state->clip_rect.height = stream->src.height;
6184 	dc_plane_state->clip_rect.width  = stream->src.width;
6185 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
6186 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
6187 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
6188 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
6189 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
6190 	dc_plane_state->tiling_info.gfx9.swizzle =  DC_SW_UNKNOWN;
6191 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6192 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
6193 	dc_plane_state->rotation = ROTATION_ANGLE_0;
6194 	dc_plane_state->is_tiling_rotated = false;
6195 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
6196 
6197 	dc_result = dc_validate_stream(dc, stream);
6198 	if (dc_result == DC_OK)
6199 		dc_result = dc_validate_plane(dc, dc_plane_state);
6200 
6201 	if (dc_result == DC_OK)
6202 		dc_result = dc_add_stream_to_ctx(dc, dc_state, stream);
6203 
6204 	if (dc_result == DC_OK && !dc_add_plane_to_context(
6205 						dc,
6206 						stream,
6207 						dc_plane_state,
6208 						dc_state))
6209 		dc_result = DC_FAIL_ATTACH_SURFACES;
6210 
6211 	if (dc_result == DC_OK)
6212 		dc_result = dc_validate_global_state(dc, dc_state, true);
6213 
6214 cleanup:
6215 	if (dc_state)
6216 		dc_release_state(dc_state);
6217 
6218 	if (dc_plane_state)
6219 		dc_plane_state_release(dc_plane_state);
6220 
6221 	return dc_result;
6222 }
6223 
6224 struct dc_stream_state *
6225 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6226 				const struct drm_display_mode *drm_mode,
6227 				const struct dm_connector_state *dm_state,
6228 				const struct dc_stream_state *old_stream)
6229 {
6230 	struct drm_connector *connector = &aconnector->base;
6231 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6232 	struct dc_stream_state *stream;
6233 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6234 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6235 	enum dc_status dc_result = DC_OK;
6236 
6237 	do {
6238 		stream = create_stream_for_sink(aconnector, drm_mode,
6239 						dm_state, old_stream,
6240 						requested_bpc);
6241 		if (stream == NULL) {
6242 			DRM_ERROR("Failed to create stream for sink!\n");
6243 			break;
6244 		}
6245 
6246 		dc_result = dc_validate_stream(adev->dm.dc, stream);
6247 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6248 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6249 
6250 		if (dc_result == DC_OK)
6251 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
6252 
6253 		if (dc_result != DC_OK) {
6254 			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6255 				      drm_mode->hdisplay,
6256 				      drm_mode->vdisplay,
6257 				      drm_mode->clock,
6258 				      dc_result,
6259 				      dc_status_to_str(dc_result));
6260 
6261 			dc_stream_release(stream);
6262 			stream = NULL;
6263 			requested_bpc -= 2; /* lower bpc to retry validation */
6264 		}
6265 
6266 	} while (stream == NULL && requested_bpc >= 6);
6267 
6268 	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6269 		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6270 
6271 		aconnector->force_yuv420_output = true;
6272 		stream = create_validate_stream_for_sink(aconnector, drm_mode,
6273 						dm_state, old_stream);
6274 		aconnector->force_yuv420_output = false;
6275 	}
6276 
6277 	return stream;
6278 }
6279 
6280 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6281 				   struct drm_display_mode *mode)
6282 {
6283 	int result = MODE_ERROR;
6284 	struct dc_sink *dc_sink;
6285 	/* TODO: Unhardcode stream count */
6286 	struct dc_stream_state *stream;
6287 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6288 
6289 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6290 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
6291 		return result;
6292 
6293 	/*
6294 	 * Only run this the first time mode_valid is called to initilialize
6295 	 * EDID mgmt
6296 	 */
6297 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6298 		!aconnector->dc_em_sink)
6299 		handle_edid_mgmt(aconnector);
6300 
6301 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6302 
6303 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6304 				aconnector->base.force != DRM_FORCE_ON) {
6305 		DRM_ERROR("dc_sink is NULL!\n");
6306 		goto fail;
6307 	}
6308 
6309 	stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6310 	if (stream) {
6311 		dc_stream_release(stream);
6312 		result = MODE_OK;
6313 	}
6314 
6315 fail:
6316 	/* TODO: error handling*/
6317 	return result;
6318 }
6319 
6320 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6321 				struct dc_info_packet *out)
6322 {
6323 	struct hdmi_drm_infoframe frame;
6324 	unsigned char buf[30]; /* 26 + 4 */
6325 	ssize_t len;
6326 	int ret, i;
6327 
6328 	memset(out, 0, sizeof(*out));
6329 
6330 	if (!state->hdr_output_metadata)
6331 		return 0;
6332 
6333 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6334 	if (ret)
6335 		return ret;
6336 
6337 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6338 	if (len < 0)
6339 		return (int)len;
6340 
6341 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
6342 	if (len != 30)
6343 		return -EINVAL;
6344 
6345 	/* Prepare the infopacket for DC. */
6346 	switch (state->connector->connector_type) {
6347 	case DRM_MODE_CONNECTOR_HDMIA:
6348 		out->hb0 = 0x87; /* type */
6349 		out->hb1 = 0x01; /* version */
6350 		out->hb2 = 0x1A; /* length */
6351 		out->sb[0] = buf[3]; /* checksum */
6352 		i = 1;
6353 		break;
6354 
6355 	case DRM_MODE_CONNECTOR_DisplayPort:
6356 	case DRM_MODE_CONNECTOR_eDP:
6357 		out->hb0 = 0x00; /* sdp id, zero */
6358 		out->hb1 = 0x87; /* type */
6359 		out->hb2 = 0x1D; /* payload len - 1 */
6360 		out->hb3 = (0x13 << 2); /* sdp version */
6361 		out->sb[0] = 0x01; /* version */
6362 		out->sb[1] = 0x1A; /* length */
6363 		i = 2;
6364 		break;
6365 
6366 	default:
6367 		return -EINVAL;
6368 	}
6369 
6370 	memcpy(&out->sb[i], &buf[4], 26);
6371 	out->valid = true;
6372 
6373 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6374 		       sizeof(out->sb), false);
6375 
6376 	return 0;
6377 }
6378 
6379 static int
6380 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6381 				 struct drm_atomic_state *state)
6382 {
6383 	struct drm_connector_state *new_con_state =
6384 		drm_atomic_get_new_connector_state(state, conn);
6385 	struct drm_connector_state *old_con_state =
6386 		drm_atomic_get_old_connector_state(state, conn);
6387 	struct drm_crtc *crtc = new_con_state->crtc;
6388 	struct drm_crtc_state *new_crtc_state;
6389 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6390 	int ret;
6391 
6392 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
6393 
6394 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6395 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6396 		if (ret < 0)
6397 			return ret;
6398 	}
6399 
6400 	if (!crtc)
6401 		return 0;
6402 
6403 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6404 		struct dc_info_packet hdr_infopacket;
6405 
6406 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6407 		if (ret)
6408 			return ret;
6409 
6410 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6411 		if (IS_ERR(new_crtc_state))
6412 			return PTR_ERR(new_crtc_state);
6413 
6414 		/*
6415 		 * DC considers the stream backends changed if the
6416 		 * static metadata changes. Forcing the modeset also
6417 		 * gives a simple way for userspace to switch from
6418 		 * 8bpc to 10bpc when setting the metadata to enter
6419 		 * or exit HDR.
6420 		 *
6421 		 * Changing the static metadata after it's been
6422 		 * set is permissible, however. So only force a
6423 		 * modeset if we're entering or exiting HDR.
6424 		 */
6425 		new_crtc_state->mode_changed =
6426 			!old_con_state->hdr_output_metadata ||
6427 			!new_con_state->hdr_output_metadata;
6428 	}
6429 
6430 	return 0;
6431 }
6432 
6433 static const struct drm_connector_helper_funcs
6434 amdgpu_dm_connector_helper_funcs = {
6435 	/*
6436 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
6437 	 * modes will be filtered by drm_mode_validate_size(), and those modes
6438 	 * are missing after user start lightdm. So we need to renew modes list.
6439 	 * in get_modes call back, not just return the modes count
6440 	 */
6441 	.get_modes = get_modes,
6442 	.mode_valid = amdgpu_dm_connector_mode_valid,
6443 	.atomic_check = amdgpu_dm_connector_atomic_check,
6444 };
6445 
6446 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6447 {
6448 
6449 }
6450 
6451 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6452 {
6453 	switch (display_color_depth) {
6454 	case COLOR_DEPTH_666:
6455 		return 6;
6456 	case COLOR_DEPTH_888:
6457 		return 8;
6458 	case COLOR_DEPTH_101010:
6459 		return 10;
6460 	case COLOR_DEPTH_121212:
6461 		return 12;
6462 	case COLOR_DEPTH_141414:
6463 		return 14;
6464 	case COLOR_DEPTH_161616:
6465 		return 16;
6466 	default:
6467 		break;
6468 	}
6469 	return 0;
6470 }
6471 
6472 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6473 					  struct drm_crtc_state *crtc_state,
6474 					  struct drm_connector_state *conn_state)
6475 {
6476 	struct drm_atomic_state *state = crtc_state->state;
6477 	struct drm_connector *connector = conn_state->connector;
6478 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6479 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6480 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6481 	struct drm_dp_mst_topology_mgr *mst_mgr;
6482 	struct drm_dp_mst_port *mst_port;
6483 	struct drm_dp_mst_topology_state *mst_state;
6484 	enum dc_color_depth color_depth;
6485 	int clock, bpp = 0;
6486 	bool is_y420 = false;
6487 
6488 	if (!aconnector->port || !aconnector->dc_sink)
6489 		return 0;
6490 
6491 	mst_port = aconnector->port;
6492 	mst_mgr = &aconnector->mst_port->mst_mgr;
6493 
6494 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6495 		return 0;
6496 
6497 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6498 	if (IS_ERR(mst_state))
6499 		return PTR_ERR(mst_state);
6500 
6501 	if (!mst_state->pbn_div)
6502 		mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_port->dc_link);
6503 
6504 	if (!state->duplicated) {
6505 		int max_bpc = conn_state->max_requested_bpc;
6506 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6507 			  aconnector->force_yuv420_output;
6508 		color_depth = convert_color_depth_from_display_info(connector,
6509 								    is_y420,
6510 								    max_bpc);
6511 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6512 		clock = adjusted_mode->clock;
6513 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6514 	}
6515 
6516 	dm_new_connector_state->vcpi_slots =
6517 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6518 					      dm_new_connector_state->pbn);
6519 	if (dm_new_connector_state->vcpi_slots < 0) {
6520 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6521 		return dm_new_connector_state->vcpi_slots;
6522 	}
6523 	return 0;
6524 }
6525 
6526 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6527 	.disable = dm_encoder_helper_disable,
6528 	.atomic_check = dm_encoder_helper_atomic_check
6529 };
6530 
6531 #if defined(CONFIG_DRM_AMD_DC_DCN)
6532 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6533 					    struct dc_state *dc_state,
6534 					    struct dsc_mst_fairness_vars *vars)
6535 {
6536 	struct dc_stream_state *stream = NULL;
6537 	struct drm_connector *connector;
6538 	struct drm_connector_state *new_con_state;
6539 	struct amdgpu_dm_connector *aconnector;
6540 	struct dm_connector_state *dm_conn_state;
6541 	int i, j, ret;
6542 	int vcpi, pbn_div, pbn, slot_num = 0;
6543 
6544 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
6545 
6546 		aconnector = to_amdgpu_dm_connector(connector);
6547 
6548 		if (!aconnector->port)
6549 			continue;
6550 
6551 		if (!new_con_state || !new_con_state->crtc)
6552 			continue;
6553 
6554 		dm_conn_state = to_dm_connector_state(new_con_state);
6555 
6556 		for (j = 0; j < dc_state->stream_count; j++) {
6557 			stream = dc_state->streams[j];
6558 			if (!stream)
6559 				continue;
6560 
6561 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6562 				break;
6563 
6564 			stream = NULL;
6565 		}
6566 
6567 		if (!stream)
6568 			continue;
6569 
6570 		pbn_div = dm_mst_get_pbn_divider(stream->link);
6571 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
6572 		for (j = 0; j < dc_state->stream_count; j++) {
6573 			if (vars[j].aconnector == aconnector) {
6574 				pbn = vars[j].pbn;
6575 				break;
6576 			}
6577 		}
6578 
6579 		if (j == dc_state->stream_count)
6580 			continue;
6581 
6582 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
6583 
6584 		if (stream->timing.flags.DSC != 1) {
6585 			dm_conn_state->pbn = pbn;
6586 			dm_conn_state->vcpi_slots = slot_num;
6587 
6588 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->port,
6589 							   dm_conn_state->pbn, false);
6590 			if (ret < 0)
6591 				return ret;
6592 
6593 			continue;
6594 		}
6595 
6596 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->port, pbn, true);
6597 		if (vcpi < 0)
6598 			return vcpi;
6599 
6600 		dm_conn_state->pbn = pbn;
6601 		dm_conn_state->vcpi_slots = vcpi;
6602 	}
6603 	return 0;
6604 }
6605 #endif
6606 
6607 static int to_drm_connector_type(enum signal_type st)
6608 {
6609 	switch (st) {
6610 	case SIGNAL_TYPE_HDMI_TYPE_A:
6611 		return DRM_MODE_CONNECTOR_HDMIA;
6612 	case SIGNAL_TYPE_EDP:
6613 		return DRM_MODE_CONNECTOR_eDP;
6614 	case SIGNAL_TYPE_LVDS:
6615 		return DRM_MODE_CONNECTOR_LVDS;
6616 	case SIGNAL_TYPE_RGB:
6617 		return DRM_MODE_CONNECTOR_VGA;
6618 	case SIGNAL_TYPE_DISPLAY_PORT:
6619 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
6620 		return DRM_MODE_CONNECTOR_DisplayPort;
6621 	case SIGNAL_TYPE_DVI_DUAL_LINK:
6622 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
6623 		return DRM_MODE_CONNECTOR_DVID;
6624 	case SIGNAL_TYPE_VIRTUAL:
6625 		return DRM_MODE_CONNECTOR_VIRTUAL;
6626 
6627 	default:
6628 		return DRM_MODE_CONNECTOR_Unknown;
6629 	}
6630 }
6631 
6632 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6633 {
6634 	struct drm_encoder *encoder;
6635 
6636 	/* There is only one encoder per connector */
6637 	drm_connector_for_each_possible_encoder(connector, encoder)
6638 		return encoder;
6639 
6640 	return NULL;
6641 }
6642 
6643 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6644 {
6645 	struct drm_encoder *encoder;
6646 	struct amdgpu_encoder *amdgpu_encoder;
6647 
6648 	encoder = amdgpu_dm_connector_to_encoder(connector);
6649 
6650 	if (encoder == NULL)
6651 		return;
6652 
6653 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6654 
6655 	amdgpu_encoder->native_mode.clock = 0;
6656 
6657 	if (!list_empty(&connector->probed_modes)) {
6658 		struct drm_display_mode *preferred_mode = NULL;
6659 
6660 		list_for_each_entry(preferred_mode,
6661 				    &connector->probed_modes,
6662 				    head) {
6663 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6664 				amdgpu_encoder->native_mode = *preferred_mode;
6665 
6666 			break;
6667 		}
6668 
6669 	}
6670 }
6671 
6672 static struct drm_display_mode *
6673 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6674 			     char *name,
6675 			     int hdisplay, int vdisplay)
6676 {
6677 	struct drm_device *dev = encoder->dev;
6678 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6679 	struct drm_display_mode *mode = NULL;
6680 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6681 
6682 	mode = drm_mode_duplicate(dev, native_mode);
6683 
6684 	if (mode == NULL)
6685 		return NULL;
6686 
6687 	mode->hdisplay = hdisplay;
6688 	mode->vdisplay = vdisplay;
6689 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6690 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6691 
6692 	return mode;
6693 
6694 }
6695 
6696 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6697 						 struct drm_connector *connector)
6698 {
6699 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6700 	struct drm_display_mode *mode = NULL;
6701 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6702 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6703 				to_amdgpu_dm_connector(connector);
6704 	int i;
6705 	int n;
6706 	struct mode_size {
6707 		char name[DRM_DISPLAY_MODE_LEN];
6708 		int w;
6709 		int h;
6710 	} common_modes[] = {
6711 		{  "640x480",  640,  480},
6712 		{  "800x600",  800,  600},
6713 		{ "1024x768", 1024,  768},
6714 		{ "1280x720", 1280,  720},
6715 		{ "1280x800", 1280,  800},
6716 		{"1280x1024", 1280, 1024},
6717 		{ "1440x900", 1440,  900},
6718 		{"1680x1050", 1680, 1050},
6719 		{"1600x1200", 1600, 1200},
6720 		{"1920x1080", 1920, 1080},
6721 		{"1920x1200", 1920, 1200}
6722 	};
6723 
6724 	n = ARRAY_SIZE(common_modes);
6725 
6726 	for (i = 0; i < n; i++) {
6727 		struct drm_display_mode *curmode = NULL;
6728 		bool mode_existed = false;
6729 
6730 		if (common_modes[i].w > native_mode->hdisplay ||
6731 		    common_modes[i].h > native_mode->vdisplay ||
6732 		   (common_modes[i].w == native_mode->hdisplay &&
6733 		    common_modes[i].h == native_mode->vdisplay))
6734 			continue;
6735 
6736 		list_for_each_entry(curmode, &connector->probed_modes, head) {
6737 			if (common_modes[i].w == curmode->hdisplay &&
6738 			    common_modes[i].h == curmode->vdisplay) {
6739 				mode_existed = true;
6740 				break;
6741 			}
6742 		}
6743 
6744 		if (mode_existed)
6745 			continue;
6746 
6747 		mode = amdgpu_dm_create_common_mode(encoder,
6748 				common_modes[i].name, common_modes[i].w,
6749 				common_modes[i].h);
6750 		if (!mode)
6751 			continue;
6752 
6753 		drm_mode_probed_add(connector, mode);
6754 		amdgpu_dm_connector->num_modes++;
6755 	}
6756 }
6757 
6758 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6759 {
6760 	struct drm_encoder *encoder;
6761 	struct amdgpu_encoder *amdgpu_encoder;
6762 	const struct drm_display_mode *native_mode;
6763 
6764 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6765 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6766 		return;
6767 
6768 	mutex_lock(&connector->dev->mode_config.mutex);
6769 	amdgpu_dm_connector_get_modes(connector);
6770 	mutex_unlock(&connector->dev->mode_config.mutex);
6771 
6772 	encoder = amdgpu_dm_connector_to_encoder(connector);
6773 	if (!encoder)
6774 		return;
6775 
6776 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6777 
6778 	native_mode = &amdgpu_encoder->native_mode;
6779 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6780 		return;
6781 
6782 	drm_connector_set_panel_orientation_with_quirk(connector,
6783 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6784 						       native_mode->hdisplay,
6785 						       native_mode->vdisplay);
6786 }
6787 
6788 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6789 					      struct edid *edid)
6790 {
6791 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6792 			to_amdgpu_dm_connector(connector);
6793 
6794 	if (edid) {
6795 		/* empty probed_modes */
6796 		INIT_LIST_HEAD(&connector->probed_modes);
6797 		amdgpu_dm_connector->num_modes =
6798 				drm_add_edid_modes(connector, edid);
6799 
6800 		/* sorting the probed modes before calling function
6801 		 * amdgpu_dm_get_native_mode() since EDID can have
6802 		 * more than one preferred mode. The modes that are
6803 		 * later in the probed mode list could be of higher
6804 		 * and preferred resolution. For example, 3840x2160
6805 		 * resolution in base EDID preferred timing and 4096x2160
6806 		 * preferred resolution in DID extension block later.
6807 		 */
6808 		drm_mode_sort(&connector->probed_modes);
6809 		amdgpu_dm_get_native_mode(connector);
6810 
6811 		/* Freesync capabilities are reset by calling
6812 		 * drm_add_edid_modes() and need to be
6813 		 * restored here.
6814 		 */
6815 		amdgpu_dm_update_freesync_caps(connector, edid);
6816 	} else {
6817 		amdgpu_dm_connector->num_modes = 0;
6818 	}
6819 }
6820 
6821 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
6822 			      struct drm_display_mode *mode)
6823 {
6824 	struct drm_display_mode *m;
6825 
6826 	list_for_each_entry (m, &aconnector->base.probed_modes, head) {
6827 		if (drm_mode_equal(m, mode))
6828 			return true;
6829 	}
6830 
6831 	return false;
6832 }
6833 
6834 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
6835 {
6836 	const struct drm_display_mode *m;
6837 	struct drm_display_mode *new_mode;
6838 	uint i;
6839 	uint32_t new_modes_count = 0;
6840 
6841 	/* Standard FPS values
6842 	 *
6843 	 * 23.976       - TV/NTSC
6844 	 * 24 	        - Cinema
6845 	 * 25 	        - TV/PAL
6846 	 * 29.97        - TV/NTSC
6847 	 * 30 	        - TV/NTSC
6848 	 * 48 	        - Cinema HFR
6849 	 * 50 	        - TV/PAL
6850 	 * 60 	        - Commonly used
6851 	 * 48,72,96,120 - Multiples of 24
6852 	 */
6853 	static const uint32_t common_rates[] = {
6854 		23976, 24000, 25000, 29970, 30000,
6855 		48000, 50000, 60000, 72000, 96000, 120000
6856 	};
6857 
6858 	/*
6859 	 * Find mode with highest refresh rate with the same resolution
6860 	 * as the preferred mode. Some monitors report a preferred mode
6861 	 * with lower resolution than the highest refresh rate supported.
6862 	 */
6863 
6864 	m = get_highest_refresh_rate_mode(aconnector, true);
6865 	if (!m)
6866 		return 0;
6867 
6868 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
6869 		uint64_t target_vtotal, target_vtotal_diff;
6870 		uint64_t num, den;
6871 
6872 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
6873 			continue;
6874 
6875 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
6876 		    common_rates[i] > aconnector->max_vfreq * 1000)
6877 			continue;
6878 
6879 		num = (unsigned long long)m->clock * 1000 * 1000;
6880 		den = common_rates[i] * (unsigned long long)m->htotal;
6881 		target_vtotal = div_u64(num, den);
6882 		target_vtotal_diff = target_vtotal - m->vtotal;
6883 
6884 		/* Check for illegal modes */
6885 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
6886 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
6887 		    m->vtotal + target_vtotal_diff < m->vsync_end)
6888 			continue;
6889 
6890 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
6891 		if (!new_mode)
6892 			goto out;
6893 
6894 		new_mode->vtotal += (u16)target_vtotal_diff;
6895 		new_mode->vsync_start += (u16)target_vtotal_diff;
6896 		new_mode->vsync_end += (u16)target_vtotal_diff;
6897 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6898 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
6899 
6900 		if (!is_duplicate_mode(aconnector, new_mode)) {
6901 			drm_mode_probed_add(&aconnector->base, new_mode);
6902 			new_modes_count += 1;
6903 		} else
6904 			drm_mode_destroy(aconnector->base.dev, new_mode);
6905 	}
6906  out:
6907 	return new_modes_count;
6908 }
6909 
6910 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
6911 						   struct edid *edid)
6912 {
6913 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6914 		to_amdgpu_dm_connector(connector);
6915 
6916 	if (!edid)
6917 		return;
6918 
6919 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
6920 		amdgpu_dm_connector->num_modes +=
6921 			add_fs_modes(amdgpu_dm_connector);
6922 }
6923 
6924 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
6925 {
6926 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6927 			to_amdgpu_dm_connector(connector);
6928 	struct drm_encoder *encoder;
6929 	struct edid *edid = amdgpu_dm_connector->edid;
6930 
6931 	encoder = amdgpu_dm_connector_to_encoder(connector);
6932 
6933 	if (!drm_edid_is_valid(edid)) {
6934 		amdgpu_dm_connector->num_modes =
6935 				drm_add_modes_noedid(connector, 640, 480);
6936 	} else {
6937 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
6938 		amdgpu_dm_connector_add_common_modes(encoder, connector);
6939 		amdgpu_dm_connector_add_freesync_modes(connector, edid);
6940 	}
6941 	amdgpu_dm_fbc_init(connector);
6942 
6943 	return amdgpu_dm_connector->num_modes;
6944 }
6945 
6946 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
6947 				     struct amdgpu_dm_connector *aconnector,
6948 				     int connector_type,
6949 				     struct dc_link *link,
6950 				     int link_index)
6951 {
6952 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
6953 
6954 	/*
6955 	 * Some of the properties below require access to state, like bpc.
6956 	 * Allocate some default initial connector state with our reset helper.
6957 	 */
6958 	if (aconnector->base.funcs->reset)
6959 		aconnector->base.funcs->reset(&aconnector->base);
6960 
6961 	aconnector->connector_id = link_index;
6962 	aconnector->dc_link = link;
6963 	aconnector->base.interlace_allowed = false;
6964 	aconnector->base.doublescan_allowed = false;
6965 	aconnector->base.stereo_allowed = false;
6966 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
6967 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
6968 	aconnector->audio_inst = -1;
6969 	mutex_init(&aconnector->hpd_lock);
6970 
6971 	/*
6972 	 * configure support HPD hot plug connector_>polled default value is 0
6973 	 * which means HPD hot plug not supported
6974 	 */
6975 	switch (connector_type) {
6976 	case DRM_MODE_CONNECTOR_HDMIA:
6977 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6978 		aconnector->base.ycbcr_420_allowed =
6979 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
6980 		break;
6981 	case DRM_MODE_CONNECTOR_DisplayPort:
6982 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6983 		link->link_enc = link_enc_cfg_get_link_enc(link);
6984 		ASSERT(link->link_enc);
6985 		if (link->link_enc)
6986 			aconnector->base.ycbcr_420_allowed =
6987 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
6988 		break;
6989 	case DRM_MODE_CONNECTOR_DVID:
6990 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6991 		break;
6992 	default:
6993 		break;
6994 	}
6995 
6996 	drm_object_attach_property(&aconnector->base.base,
6997 				dm->ddev->mode_config.scaling_mode_property,
6998 				DRM_MODE_SCALE_NONE);
6999 
7000 	drm_object_attach_property(&aconnector->base.base,
7001 				adev->mode_info.underscan_property,
7002 				UNDERSCAN_OFF);
7003 	drm_object_attach_property(&aconnector->base.base,
7004 				adev->mode_info.underscan_hborder_property,
7005 				0);
7006 	drm_object_attach_property(&aconnector->base.base,
7007 				adev->mode_info.underscan_vborder_property,
7008 				0);
7009 
7010 	if (!aconnector->mst_port)
7011 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7012 
7013 	/* This defaults to the max in the range, but we want 8bpc for non-edp. */
7014 	aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7015 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7016 
7017 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7018 	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7019 		drm_object_attach_property(&aconnector->base.base,
7020 				adev->mode_info.abm_level_property, 0);
7021 	}
7022 
7023 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7024 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7025 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
7026 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7027 
7028 		if (!aconnector->mst_port)
7029 			drm_connector_attach_vrr_capable_property(&aconnector->base);
7030 
7031 #ifdef CONFIG_DRM_AMD_DC_HDCP
7032 		if (adev->dm.hdcp_workqueue)
7033 			drm_connector_attach_content_protection_property(&aconnector->base, true);
7034 #endif
7035 	}
7036 }
7037 
7038 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7039 			      struct i2c_msg *msgs, int num)
7040 {
7041 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7042 	struct ddc_service *ddc_service = i2c->ddc_service;
7043 	struct i2c_command cmd;
7044 	int i;
7045 	int result = -EIO;
7046 
7047 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7048 
7049 	if (!cmd.payloads)
7050 		return result;
7051 
7052 	cmd.number_of_payloads = num;
7053 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7054 	cmd.speed = 100;
7055 
7056 	for (i = 0; i < num; i++) {
7057 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7058 		cmd.payloads[i].address = msgs[i].addr;
7059 		cmd.payloads[i].length = msgs[i].len;
7060 		cmd.payloads[i].data = msgs[i].buf;
7061 	}
7062 
7063 	if (dc_submit_i2c(
7064 			ddc_service->ctx->dc,
7065 			ddc_service->link->link_index,
7066 			&cmd))
7067 		result = num;
7068 
7069 	kfree(cmd.payloads);
7070 	return result;
7071 }
7072 
7073 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7074 {
7075 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7076 }
7077 
7078 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7079 	.master_xfer = amdgpu_dm_i2c_xfer,
7080 	.functionality = amdgpu_dm_i2c_func,
7081 };
7082 
7083 static struct amdgpu_i2c_adapter *
7084 create_i2c(struct ddc_service *ddc_service,
7085 	   int link_index,
7086 	   int *res)
7087 {
7088 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7089 	struct amdgpu_i2c_adapter *i2c;
7090 
7091 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7092 	if (!i2c)
7093 		return NULL;
7094 	i2c->base.owner = THIS_MODULE;
7095 	i2c->base.class = I2C_CLASS_DDC;
7096 	i2c->base.dev.parent = &adev->pdev->dev;
7097 	i2c->base.algo = &amdgpu_dm_i2c_algo;
7098 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7099 	i2c_set_adapdata(&i2c->base, i2c);
7100 	i2c->ddc_service = ddc_service;
7101 
7102 	return i2c;
7103 }
7104 
7105 
7106 /*
7107  * Note: this function assumes that dc_link_detect() was called for the
7108  * dc_link which will be represented by this aconnector.
7109  */
7110 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7111 				    struct amdgpu_dm_connector *aconnector,
7112 				    uint32_t link_index,
7113 				    struct amdgpu_encoder *aencoder)
7114 {
7115 	int res = 0;
7116 	int connector_type;
7117 	struct dc *dc = dm->dc;
7118 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
7119 	struct amdgpu_i2c_adapter *i2c;
7120 
7121 	link->priv = aconnector;
7122 
7123 	DRM_DEBUG_DRIVER("%s()\n", __func__);
7124 
7125 	i2c = create_i2c(link->ddc, link->link_index, &res);
7126 	if (!i2c) {
7127 		DRM_ERROR("Failed to create i2c adapter data\n");
7128 		return -ENOMEM;
7129 	}
7130 
7131 	aconnector->i2c = i2c;
7132 	res = i2c_add_adapter(&i2c->base);
7133 
7134 	if (res) {
7135 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7136 		goto out_free;
7137 	}
7138 
7139 	connector_type = to_drm_connector_type(link->connector_signal);
7140 
7141 	res = drm_connector_init_with_ddc(
7142 			dm->ddev,
7143 			&aconnector->base,
7144 			&amdgpu_dm_connector_funcs,
7145 			connector_type,
7146 			&i2c->base);
7147 
7148 	if (res) {
7149 		DRM_ERROR("connector_init failed\n");
7150 		aconnector->connector_id = -1;
7151 		goto out_free;
7152 	}
7153 
7154 	drm_connector_helper_add(
7155 			&aconnector->base,
7156 			&amdgpu_dm_connector_helper_funcs);
7157 
7158 	amdgpu_dm_connector_init_helper(
7159 		dm,
7160 		aconnector,
7161 		connector_type,
7162 		link,
7163 		link_index);
7164 
7165 	drm_connector_attach_encoder(
7166 		&aconnector->base, &aencoder->base);
7167 
7168 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7169 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
7170 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7171 
7172 out_free:
7173 	if (res) {
7174 		kfree(i2c);
7175 		aconnector->i2c = NULL;
7176 	}
7177 	return res;
7178 }
7179 
7180 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7181 {
7182 	switch (adev->mode_info.num_crtc) {
7183 	case 1:
7184 		return 0x1;
7185 	case 2:
7186 		return 0x3;
7187 	case 3:
7188 		return 0x7;
7189 	case 4:
7190 		return 0xf;
7191 	case 5:
7192 		return 0x1f;
7193 	case 6:
7194 	default:
7195 		return 0x3f;
7196 	}
7197 }
7198 
7199 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7200 				  struct amdgpu_encoder *aencoder,
7201 				  uint32_t link_index)
7202 {
7203 	struct amdgpu_device *adev = drm_to_adev(dev);
7204 
7205 	int res = drm_encoder_init(dev,
7206 				   &aencoder->base,
7207 				   &amdgpu_dm_encoder_funcs,
7208 				   DRM_MODE_ENCODER_TMDS,
7209 				   NULL);
7210 
7211 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7212 
7213 	if (!res)
7214 		aencoder->encoder_id = link_index;
7215 	else
7216 		aencoder->encoder_id = -1;
7217 
7218 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7219 
7220 	return res;
7221 }
7222 
7223 static void manage_dm_interrupts(struct amdgpu_device *adev,
7224 				 struct amdgpu_crtc *acrtc,
7225 				 bool enable)
7226 {
7227 	/*
7228 	 * We have no guarantee that the frontend index maps to the same
7229 	 * backend index - some even map to more than one.
7230 	 *
7231 	 * TODO: Use a different interrupt or check DC itself for the mapping.
7232 	 */
7233 	int irq_type =
7234 		amdgpu_display_crtc_idx_to_irq_type(
7235 			adev,
7236 			acrtc->crtc_id);
7237 
7238 	if (enable) {
7239 		drm_crtc_vblank_on(&acrtc->base);
7240 		amdgpu_irq_get(
7241 			adev,
7242 			&adev->pageflip_irq,
7243 			irq_type);
7244 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7245 		amdgpu_irq_get(
7246 			adev,
7247 			&adev->vline0_irq,
7248 			irq_type);
7249 #endif
7250 	} else {
7251 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7252 		amdgpu_irq_put(
7253 			adev,
7254 			&adev->vline0_irq,
7255 			irq_type);
7256 #endif
7257 		amdgpu_irq_put(
7258 			adev,
7259 			&adev->pageflip_irq,
7260 			irq_type);
7261 		drm_crtc_vblank_off(&acrtc->base);
7262 	}
7263 }
7264 
7265 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7266 				      struct amdgpu_crtc *acrtc)
7267 {
7268 	int irq_type =
7269 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7270 
7271 	/**
7272 	 * This reads the current state for the IRQ and force reapplies
7273 	 * the setting to hardware.
7274 	 */
7275 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7276 }
7277 
7278 static bool
7279 is_scaling_state_different(const struct dm_connector_state *dm_state,
7280 			   const struct dm_connector_state *old_dm_state)
7281 {
7282 	if (dm_state->scaling != old_dm_state->scaling)
7283 		return true;
7284 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7285 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7286 			return true;
7287 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7288 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7289 			return true;
7290 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7291 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7292 		return true;
7293 	return false;
7294 }
7295 
7296 #ifdef CONFIG_DRM_AMD_DC_HDCP
7297 static bool is_content_protection_different(struct drm_connector_state *state,
7298 					    const struct drm_connector_state *old_state,
7299 					    const struct drm_connector *connector, struct hdcp_workqueue *hdcp_w)
7300 {
7301 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7302 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7303 
7304 	/* Handle: Type0/1 change */
7305 	if (old_state->hdcp_content_type != state->hdcp_content_type &&
7306 	    state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7307 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7308 		return true;
7309 	}
7310 
7311 	/* CP is being re enabled, ignore this
7312 	 *
7313 	 * Handles:	ENABLED -> DESIRED
7314 	 */
7315 	if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7316 	    state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7317 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7318 		return false;
7319 	}
7320 
7321 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7322 	 *
7323 	 * Handles:	UNDESIRED -> ENABLED
7324 	 */
7325 	if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7326 	    state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7327 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7328 
7329 	/* Stream removed and re-enabled
7330 	 *
7331 	 * Can sometimes overlap with the HPD case,
7332 	 * thus set update_hdcp to false to avoid
7333 	 * setting HDCP multiple times.
7334 	 *
7335 	 * Handles:	DESIRED -> DESIRED (Special case)
7336 	 */
7337 	if (!(old_state->crtc && old_state->crtc->enabled) &&
7338 		state->crtc && state->crtc->enabled &&
7339 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7340 		dm_con_state->update_hdcp = false;
7341 		return true;
7342 	}
7343 
7344 	/* Hot-plug, headless s3, dpms
7345 	 *
7346 	 * Only start HDCP if the display is connected/enabled.
7347 	 * update_hdcp flag will be set to false until the next
7348 	 * HPD comes in.
7349 	 *
7350 	 * Handles:	DESIRED -> DESIRED (Special case)
7351 	 */
7352 	if (dm_con_state->update_hdcp && state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7353 	    connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7354 		dm_con_state->update_hdcp = false;
7355 		return true;
7356 	}
7357 
7358 	/*
7359 	 * Handles:	UNDESIRED -> UNDESIRED
7360 	 *		DESIRED -> DESIRED
7361 	 *		ENABLED -> ENABLED
7362 	 */
7363 	if (old_state->content_protection == state->content_protection)
7364 		return false;
7365 
7366 	/*
7367 	 * Handles:	UNDESIRED -> DESIRED
7368 	 *		DESIRED -> UNDESIRED
7369 	 *		ENABLED -> UNDESIRED
7370 	 */
7371 	if (state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED)
7372 		return true;
7373 
7374 	/*
7375 	 * Handles:	DESIRED -> ENABLED
7376 	 */
7377 	return false;
7378 }
7379 
7380 #endif
7381 static void remove_stream(struct amdgpu_device *adev,
7382 			  struct amdgpu_crtc *acrtc,
7383 			  struct dc_stream_state *stream)
7384 {
7385 	/* this is the update mode case */
7386 
7387 	acrtc->otg_inst = -1;
7388 	acrtc->enabled = false;
7389 }
7390 
7391 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7392 {
7393 
7394 	assert_spin_locked(&acrtc->base.dev->event_lock);
7395 	WARN_ON(acrtc->event);
7396 
7397 	acrtc->event = acrtc->base.state->event;
7398 
7399 	/* Set the flip status */
7400 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7401 
7402 	/* Mark this event as consumed */
7403 	acrtc->base.state->event = NULL;
7404 
7405 	DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7406 		     acrtc->crtc_id);
7407 }
7408 
7409 static void update_freesync_state_on_stream(
7410 	struct amdgpu_display_manager *dm,
7411 	struct dm_crtc_state *new_crtc_state,
7412 	struct dc_stream_state *new_stream,
7413 	struct dc_plane_state *surface,
7414 	u32 flip_timestamp_in_us)
7415 {
7416 	struct mod_vrr_params vrr_params;
7417 	struct dc_info_packet vrr_infopacket = {0};
7418 	struct amdgpu_device *adev = dm->adev;
7419 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7420 	unsigned long flags;
7421 	bool pack_sdp_v1_3 = false;
7422 
7423 	if (!new_stream)
7424 		return;
7425 
7426 	/*
7427 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7428 	 * For now it's sufficient to just guard against these conditions.
7429 	 */
7430 
7431 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7432 		return;
7433 
7434 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7435         vrr_params = acrtc->dm_irq_params.vrr_params;
7436 
7437 	if (surface) {
7438 		mod_freesync_handle_preflip(
7439 			dm->freesync_module,
7440 			surface,
7441 			new_stream,
7442 			flip_timestamp_in_us,
7443 			&vrr_params);
7444 
7445 		if (adev->family < AMDGPU_FAMILY_AI &&
7446 		    amdgpu_dm_vrr_active(new_crtc_state)) {
7447 			mod_freesync_handle_v_update(dm->freesync_module,
7448 						     new_stream, &vrr_params);
7449 
7450 			/* Need to call this before the frame ends. */
7451 			dc_stream_adjust_vmin_vmax(dm->dc,
7452 						   new_crtc_state->stream,
7453 						   &vrr_params.adjust);
7454 		}
7455 	}
7456 
7457 	mod_freesync_build_vrr_infopacket(
7458 		dm->freesync_module,
7459 		new_stream,
7460 		&vrr_params,
7461 		PACKET_TYPE_VRR,
7462 		TRANSFER_FUNC_UNKNOWN,
7463 		&vrr_infopacket,
7464 		pack_sdp_v1_3);
7465 
7466 	new_crtc_state->freesync_vrr_info_changed |=
7467 		(memcmp(&new_crtc_state->vrr_infopacket,
7468 			&vrr_infopacket,
7469 			sizeof(vrr_infopacket)) != 0);
7470 
7471 	acrtc->dm_irq_params.vrr_params = vrr_params;
7472 	new_crtc_state->vrr_infopacket = vrr_infopacket;
7473 
7474 	new_stream->vrr_infopacket = vrr_infopacket;
7475 
7476 	if (new_crtc_state->freesync_vrr_info_changed)
7477 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7478 			      new_crtc_state->base.crtc->base.id,
7479 			      (int)new_crtc_state->base.vrr_enabled,
7480 			      (int)vrr_params.state);
7481 
7482 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7483 }
7484 
7485 static void update_stream_irq_parameters(
7486 	struct amdgpu_display_manager *dm,
7487 	struct dm_crtc_state *new_crtc_state)
7488 {
7489 	struct dc_stream_state *new_stream = new_crtc_state->stream;
7490 	struct mod_vrr_params vrr_params;
7491 	struct mod_freesync_config config = new_crtc_state->freesync_config;
7492 	struct amdgpu_device *adev = dm->adev;
7493 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7494 	unsigned long flags;
7495 
7496 	if (!new_stream)
7497 		return;
7498 
7499 	/*
7500 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7501 	 * For now it's sufficient to just guard against these conditions.
7502 	 */
7503 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7504 		return;
7505 
7506 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7507 	vrr_params = acrtc->dm_irq_params.vrr_params;
7508 
7509 	if (new_crtc_state->vrr_supported &&
7510 	    config.min_refresh_in_uhz &&
7511 	    config.max_refresh_in_uhz) {
7512 		/*
7513 		 * if freesync compatible mode was set, config.state will be set
7514 		 * in atomic check
7515 		 */
7516 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7517 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7518 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7519 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7520 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7521 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7522 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7523 		} else {
7524 			config.state = new_crtc_state->base.vrr_enabled ?
7525 						     VRR_STATE_ACTIVE_VARIABLE :
7526 						     VRR_STATE_INACTIVE;
7527 		}
7528 	} else {
7529 		config.state = VRR_STATE_UNSUPPORTED;
7530 	}
7531 
7532 	mod_freesync_build_vrr_params(dm->freesync_module,
7533 				      new_stream,
7534 				      &config, &vrr_params);
7535 
7536 	new_crtc_state->freesync_config = config;
7537 	/* Copy state for access from DM IRQ handler */
7538 	acrtc->dm_irq_params.freesync_config = config;
7539 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7540 	acrtc->dm_irq_params.vrr_params = vrr_params;
7541 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7542 }
7543 
7544 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7545 					    struct dm_crtc_state *new_state)
7546 {
7547 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7548 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7549 
7550 	if (!old_vrr_active && new_vrr_active) {
7551 		/* Transition VRR inactive -> active:
7552 		 * While VRR is active, we must not disable vblank irq, as a
7553 		 * reenable after disable would compute bogus vblank/pflip
7554 		 * timestamps if it likely happened inside display front-porch.
7555 		 *
7556 		 * We also need vupdate irq for the actual core vblank handling
7557 		 * at end of vblank.
7558 		 */
7559 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7560 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7561 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7562 				 __func__, new_state->base.crtc->base.id);
7563 	} else if (old_vrr_active && !new_vrr_active) {
7564 		/* Transition VRR active -> inactive:
7565 		 * Allow vblank irq disable again for fixed refresh rate.
7566 		 */
7567 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7568 		drm_crtc_vblank_put(new_state->base.crtc);
7569 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7570 				 __func__, new_state->base.crtc->base.id);
7571 	}
7572 }
7573 
7574 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7575 {
7576 	struct drm_plane *plane;
7577 	struct drm_plane_state *old_plane_state;
7578 	int i;
7579 
7580 	/*
7581 	 * TODO: Make this per-stream so we don't issue redundant updates for
7582 	 * commits with multiple streams.
7583 	 */
7584 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
7585 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
7586 			handle_cursor_update(plane, old_plane_state);
7587 }
7588 
7589 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7590 				    struct dc_state *dc_state,
7591 				    struct drm_device *dev,
7592 				    struct amdgpu_display_manager *dm,
7593 				    struct drm_crtc *pcrtc,
7594 				    bool wait_for_vblank)
7595 {
7596 	uint32_t i;
7597 	uint64_t timestamp_ns;
7598 	struct drm_plane *plane;
7599 	struct drm_plane_state *old_plane_state, *new_plane_state;
7600 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7601 	struct drm_crtc_state *new_pcrtc_state =
7602 			drm_atomic_get_new_crtc_state(state, pcrtc);
7603 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7604 	struct dm_crtc_state *dm_old_crtc_state =
7605 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7606 	int planes_count = 0, vpos, hpos;
7607 	unsigned long flags;
7608 	uint32_t target_vblank, last_flip_vblank;
7609 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7610 	bool cursor_update = false;
7611 	bool pflip_present = false;
7612 	struct {
7613 		struct dc_surface_update surface_updates[MAX_SURFACES];
7614 		struct dc_plane_info plane_infos[MAX_SURFACES];
7615 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
7616 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7617 		struct dc_stream_update stream_update;
7618 	} *bundle;
7619 
7620 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7621 
7622 	if (!bundle) {
7623 		dm_error("Failed to allocate update bundle\n");
7624 		goto cleanup;
7625 	}
7626 
7627 	/*
7628 	 * Disable the cursor first if we're disabling all the planes.
7629 	 * It'll remain on the screen after the planes are re-enabled
7630 	 * if we don't.
7631 	 */
7632 	if (acrtc_state->active_planes == 0)
7633 		amdgpu_dm_commit_cursors(state);
7634 
7635 	/* update planes when needed */
7636 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7637 		struct drm_crtc *crtc = new_plane_state->crtc;
7638 		struct drm_crtc_state *new_crtc_state;
7639 		struct drm_framebuffer *fb = new_plane_state->fb;
7640 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7641 		bool plane_needs_flip;
7642 		struct dc_plane_state *dc_plane;
7643 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7644 
7645 		/* Cursor plane is handled after stream updates */
7646 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7647 			if ((fb && crtc == pcrtc) ||
7648 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7649 				cursor_update = true;
7650 
7651 			continue;
7652 		}
7653 
7654 		if (!fb || !crtc || pcrtc != crtc)
7655 			continue;
7656 
7657 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7658 		if (!new_crtc_state->active)
7659 			continue;
7660 
7661 		dc_plane = dm_new_plane_state->dc_state;
7662 
7663 		bundle->surface_updates[planes_count].surface = dc_plane;
7664 		if (new_pcrtc_state->color_mgmt_changed) {
7665 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7666 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7667 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7668 		}
7669 
7670 		fill_dc_scaling_info(dm->adev, new_plane_state,
7671 				     &bundle->scaling_infos[planes_count]);
7672 
7673 		bundle->surface_updates[planes_count].scaling_info =
7674 			&bundle->scaling_infos[planes_count];
7675 
7676 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7677 
7678 		pflip_present = pflip_present || plane_needs_flip;
7679 
7680 		if (!plane_needs_flip) {
7681 			planes_count += 1;
7682 			continue;
7683 		}
7684 
7685 		fill_dc_plane_info_and_addr(
7686 			dm->adev, new_plane_state,
7687 			afb->tiling_flags,
7688 			&bundle->plane_infos[planes_count],
7689 			&bundle->flip_addrs[planes_count].address,
7690 			afb->tmz_surface, false);
7691 
7692 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7693 				 new_plane_state->plane->index,
7694 				 bundle->plane_infos[planes_count].dcc.enable);
7695 
7696 		bundle->surface_updates[planes_count].plane_info =
7697 			&bundle->plane_infos[planes_count];
7698 
7699 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7700 			fill_dc_dirty_rects(plane, old_plane_state,
7701 					    new_plane_state, new_crtc_state,
7702 					    &bundle->flip_addrs[planes_count]);
7703 
7704 		/*
7705 		 * Only allow immediate flips for fast updates that don't
7706 		 * change FB pitch, DCC state, rotation or mirroing.
7707 		 */
7708 		bundle->flip_addrs[planes_count].flip_immediate =
7709 			crtc->state->async_flip &&
7710 			acrtc_state->update_type == UPDATE_TYPE_FAST;
7711 
7712 		timestamp_ns = ktime_get_ns();
7713 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7714 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7715 		bundle->surface_updates[planes_count].surface = dc_plane;
7716 
7717 		if (!bundle->surface_updates[planes_count].surface) {
7718 			DRM_ERROR("No surface for CRTC: id=%d\n",
7719 					acrtc_attach->crtc_id);
7720 			continue;
7721 		}
7722 
7723 		if (plane == pcrtc->primary)
7724 			update_freesync_state_on_stream(
7725 				dm,
7726 				acrtc_state,
7727 				acrtc_state->stream,
7728 				dc_plane,
7729 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7730 
7731 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7732 				 __func__,
7733 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7734 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7735 
7736 		planes_count += 1;
7737 
7738 	}
7739 
7740 	if (pflip_present) {
7741 		if (!vrr_active) {
7742 			/* Use old throttling in non-vrr fixed refresh rate mode
7743 			 * to keep flip scheduling based on target vblank counts
7744 			 * working in a backwards compatible way, e.g., for
7745 			 * clients using the GLX_OML_sync_control extension or
7746 			 * DRI3/Present extension with defined target_msc.
7747 			 */
7748 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7749 		}
7750 		else {
7751 			/* For variable refresh rate mode only:
7752 			 * Get vblank of last completed flip to avoid > 1 vrr
7753 			 * flips per video frame by use of throttling, but allow
7754 			 * flip programming anywhere in the possibly large
7755 			 * variable vrr vblank interval for fine-grained flip
7756 			 * timing control and more opportunity to avoid stutter
7757 			 * on late submission of flips.
7758 			 */
7759 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7760 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
7761 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7762 		}
7763 
7764 		target_vblank = last_flip_vblank + wait_for_vblank;
7765 
7766 		/*
7767 		 * Wait until we're out of the vertical blank period before the one
7768 		 * targeted by the flip
7769 		 */
7770 		while ((acrtc_attach->enabled &&
7771 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
7772 							    0, &vpos, &hpos, NULL,
7773 							    NULL, &pcrtc->hwmode)
7774 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
7775 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
7776 			(int)(target_vblank -
7777 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
7778 			usleep_range(1000, 1100);
7779 		}
7780 
7781 		/**
7782 		 * Prepare the flip event for the pageflip interrupt to handle.
7783 		 *
7784 		 * This only works in the case where we've already turned on the
7785 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
7786 		 * from 0 -> n planes we have to skip a hardware generated event
7787 		 * and rely on sending it from software.
7788 		 */
7789 		if (acrtc_attach->base.state->event &&
7790 		    acrtc_state->active_planes > 0) {
7791 			drm_crtc_vblank_get(pcrtc);
7792 
7793 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7794 
7795 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
7796 			prepare_flip_isr(acrtc_attach);
7797 
7798 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7799 		}
7800 
7801 		if (acrtc_state->stream) {
7802 			if (acrtc_state->freesync_vrr_info_changed)
7803 				bundle->stream_update.vrr_infopacket =
7804 					&acrtc_state->stream->vrr_infopacket;
7805 		}
7806 	} else if (cursor_update && acrtc_state->active_planes > 0 &&
7807 		   acrtc_attach->base.state->event) {
7808 		drm_crtc_vblank_get(pcrtc);
7809 
7810 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7811 
7812 		acrtc_attach->event = acrtc_attach->base.state->event;
7813 		acrtc_attach->base.state->event = NULL;
7814 
7815 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7816 	}
7817 
7818 	/* Update the planes if changed or disable if we don't have any. */
7819 	if ((planes_count || acrtc_state->active_planes == 0) &&
7820 		acrtc_state->stream) {
7821 		/*
7822 		 * If PSR or idle optimizations are enabled then flush out
7823 		 * any pending work before hardware programming.
7824 		 */
7825 		if (dm->vblank_control_workqueue)
7826 			flush_workqueue(dm->vblank_control_workqueue);
7827 
7828 		bundle->stream_update.stream = acrtc_state->stream;
7829 		if (new_pcrtc_state->mode_changed) {
7830 			bundle->stream_update.src = acrtc_state->stream->src;
7831 			bundle->stream_update.dst = acrtc_state->stream->dst;
7832 		}
7833 
7834 		if (new_pcrtc_state->color_mgmt_changed) {
7835 			/*
7836 			 * TODO: This isn't fully correct since we've actually
7837 			 * already modified the stream in place.
7838 			 */
7839 			bundle->stream_update.gamut_remap =
7840 				&acrtc_state->stream->gamut_remap_matrix;
7841 			bundle->stream_update.output_csc_transform =
7842 				&acrtc_state->stream->csc_color_matrix;
7843 			bundle->stream_update.out_transfer_func =
7844 				acrtc_state->stream->out_transfer_func;
7845 		}
7846 
7847 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
7848 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
7849 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
7850 
7851 		/*
7852 		 * If FreeSync state on the stream has changed then we need to
7853 		 * re-adjust the min/max bounds now that DC doesn't handle this
7854 		 * as part of commit.
7855 		 */
7856 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
7857 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7858 			dc_stream_adjust_vmin_vmax(
7859 				dm->dc, acrtc_state->stream,
7860 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
7861 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7862 		}
7863 		mutex_lock(&dm->dc_lock);
7864 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7865 				acrtc_state->stream->link->psr_settings.psr_allow_active)
7866 			amdgpu_dm_psr_disable(acrtc_state->stream);
7867 
7868 		dc_commit_updates_for_stream(dm->dc,
7869 						     bundle->surface_updates,
7870 						     planes_count,
7871 						     acrtc_state->stream,
7872 						     &bundle->stream_update,
7873 						     dc_state);
7874 
7875 		/**
7876 		 * Enable or disable the interrupts on the backend.
7877 		 *
7878 		 * Most pipes are put into power gating when unused.
7879 		 *
7880 		 * When power gating is enabled on a pipe we lose the
7881 		 * interrupt enablement state when power gating is disabled.
7882 		 *
7883 		 * So we need to update the IRQ control state in hardware
7884 		 * whenever the pipe turns on (since it could be previously
7885 		 * power gated) or off (since some pipes can't be power gated
7886 		 * on some ASICs).
7887 		 */
7888 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
7889 			dm_update_pflip_irq_state(drm_to_adev(dev),
7890 						  acrtc_attach);
7891 
7892 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7893 				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
7894 				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7895 			amdgpu_dm_link_setup_psr(acrtc_state->stream);
7896 
7897 		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
7898 		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
7899 		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
7900 			struct amdgpu_dm_connector *aconn =
7901 				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
7902 
7903 			if (aconn->psr_skip_count > 0)
7904 				aconn->psr_skip_count--;
7905 
7906 			/* Allow PSR when skip count is 0. */
7907 			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
7908 
7909 			/*
7910 			 * If sink supports PSR SU, there is no need to rely on
7911 			 * a vblank event disable request to enable PSR. PSR SU
7912 			 * can be enabled immediately once OS demonstrates an
7913 			 * adequate number of fast atomic commits to notify KMD
7914 			 * of update events. See `vblank_control_worker()`.
7915 			 */
7916 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
7917 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
7918 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
7919 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
7920 #endif
7921 			    !acrtc_state->stream->link->psr_settings.psr_allow_active)
7922 				amdgpu_dm_psr_enable(acrtc_state->stream);
7923 		} else {
7924 			acrtc_attach->dm_irq_params.allow_psr_entry = false;
7925 		}
7926 
7927 		mutex_unlock(&dm->dc_lock);
7928 	}
7929 
7930 	/*
7931 	 * Update cursor state *after* programming all the planes.
7932 	 * This avoids redundant programming in the case where we're going
7933 	 * to be disabling a single plane - those pipes are being disabled.
7934 	 */
7935 	if (acrtc_state->active_planes)
7936 		amdgpu_dm_commit_cursors(state);
7937 
7938 cleanup:
7939 	kfree(bundle);
7940 }
7941 
7942 static void amdgpu_dm_commit_audio(struct drm_device *dev,
7943 				   struct drm_atomic_state *state)
7944 {
7945 	struct amdgpu_device *adev = drm_to_adev(dev);
7946 	struct amdgpu_dm_connector *aconnector;
7947 	struct drm_connector *connector;
7948 	struct drm_connector_state *old_con_state, *new_con_state;
7949 	struct drm_crtc_state *new_crtc_state;
7950 	struct dm_crtc_state *new_dm_crtc_state;
7951 	const struct dc_stream_status *status;
7952 	int i, inst;
7953 
7954 	/* Notify device removals. */
7955 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
7956 		if (old_con_state->crtc != new_con_state->crtc) {
7957 			/* CRTC changes require notification. */
7958 			goto notify;
7959 		}
7960 
7961 		if (!new_con_state->crtc)
7962 			continue;
7963 
7964 		new_crtc_state = drm_atomic_get_new_crtc_state(
7965 			state, new_con_state->crtc);
7966 
7967 		if (!new_crtc_state)
7968 			continue;
7969 
7970 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
7971 			continue;
7972 
7973 	notify:
7974 		aconnector = to_amdgpu_dm_connector(connector);
7975 
7976 		mutex_lock(&adev->dm.audio_lock);
7977 		inst = aconnector->audio_inst;
7978 		aconnector->audio_inst = -1;
7979 		mutex_unlock(&adev->dm.audio_lock);
7980 
7981 		amdgpu_dm_audio_eld_notify(adev, inst);
7982 	}
7983 
7984 	/* Notify audio device additions. */
7985 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
7986 		if (!new_con_state->crtc)
7987 			continue;
7988 
7989 		new_crtc_state = drm_atomic_get_new_crtc_state(
7990 			state, new_con_state->crtc);
7991 
7992 		if (!new_crtc_state)
7993 			continue;
7994 
7995 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
7996 			continue;
7997 
7998 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
7999 		if (!new_dm_crtc_state->stream)
8000 			continue;
8001 
8002 		status = dc_stream_get_status(new_dm_crtc_state->stream);
8003 		if (!status)
8004 			continue;
8005 
8006 		aconnector = to_amdgpu_dm_connector(connector);
8007 
8008 		mutex_lock(&adev->dm.audio_lock);
8009 		inst = status->audio_inst;
8010 		aconnector->audio_inst = inst;
8011 		mutex_unlock(&adev->dm.audio_lock);
8012 
8013 		amdgpu_dm_audio_eld_notify(adev, inst);
8014 	}
8015 }
8016 
8017 /*
8018  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8019  * @crtc_state: the DRM CRTC state
8020  * @stream_state: the DC stream state.
8021  *
8022  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8023  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8024  */
8025 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8026 						struct dc_stream_state *stream_state)
8027 {
8028 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8029 }
8030 
8031 /**
8032  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8033  * @state: The atomic state to commit
8034  *
8035  * This will tell DC to commit the constructed DC state from atomic_check,
8036  * programming the hardware. Any failures here implies a hardware failure, since
8037  * atomic check should have filtered anything non-kosher.
8038  */
8039 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8040 {
8041 	struct drm_device *dev = state->dev;
8042 	struct amdgpu_device *adev = drm_to_adev(dev);
8043 	struct amdgpu_display_manager *dm = &adev->dm;
8044 	struct dm_atomic_state *dm_state;
8045 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8046 	uint32_t i, j;
8047 	struct drm_crtc *crtc;
8048 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8049 	unsigned long flags;
8050 	bool wait_for_vblank = true;
8051 	struct drm_connector *connector;
8052 	struct drm_connector_state *old_con_state, *new_con_state;
8053 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8054 	int crtc_disable_count = 0;
8055 	bool mode_set_reset_required = false;
8056 	int r;
8057 
8058 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
8059 
8060 	r = drm_atomic_helper_wait_for_fences(dev, state, false);
8061 	if (unlikely(r))
8062 		DRM_ERROR("Waiting for fences timed out!");
8063 
8064 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
8065 	drm_dp_mst_atomic_wait_for_dependencies(state);
8066 
8067 	dm_state = dm_atomic_get_new_state(state);
8068 	if (dm_state && dm_state->context) {
8069 		dc_state = dm_state->context;
8070 	} else {
8071 		/* No state changes, retain current state. */
8072 		dc_state_temp = dc_create_state(dm->dc);
8073 		ASSERT(dc_state_temp);
8074 		dc_state = dc_state_temp;
8075 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
8076 	}
8077 
8078 	for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8079 				       new_crtc_state, i) {
8080 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8081 
8082 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8083 
8084 		if (old_crtc_state->active &&
8085 		    (!new_crtc_state->active ||
8086 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8087 			manage_dm_interrupts(adev, acrtc, false);
8088 			dc_stream_release(dm_old_crtc_state->stream);
8089 		}
8090 	}
8091 
8092 	drm_atomic_helper_calc_timestamping_constants(state);
8093 
8094 	/* update changed items */
8095 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8096 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8097 
8098 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8099 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8100 
8101 		drm_dbg_state(state->dev,
8102 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8103 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8104 			"connectors_changed:%d\n",
8105 			acrtc->crtc_id,
8106 			new_crtc_state->enable,
8107 			new_crtc_state->active,
8108 			new_crtc_state->planes_changed,
8109 			new_crtc_state->mode_changed,
8110 			new_crtc_state->active_changed,
8111 			new_crtc_state->connectors_changed);
8112 
8113 		/* Disable cursor if disabling crtc */
8114 		if (old_crtc_state->active && !new_crtc_state->active) {
8115 			struct dc_cursor_position position;
8116 
8117 			memset(&position, 0, sizeof(position));
8118 			mutex_lock(&dm->dc_lock);
8119 			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8120 			mutex_unlock(&dm->dc_lock);
8121 		}
8122 
8123 		/* Copy all transient state flags into dc state */
8124 		if (dm_new_crtc_state->stream) {
8125 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8126 							    dm_new_crtc_state->stream);
8127 		}
8128 
8129 		/* handles headless hotplug case, updating new_state and
8130 		 * aconnector as needed
8131 		 */
8132 
8133 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8134 
8135 			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8136 
8137 			if (!dm_new_crtc_state->stream) {
8138 				/*
8139 				 * this could happen because of issues with
8140 				 * userspace notifications delivery.
8141 				 * In this case userspace tries to set mode on
8142 				 * display which is disconnected in fact.
8143 				 * dc_sink is NULL in this case on aconnector.
8144 				 * We expect reset mode will come soon.
8145 				 *
8146 				 * This can also happen when unplug is done
8147 				 * during resume sequence ended
8148 				 *
8149 				 * In this case, we want to pretend we still
8150 				 * have a sink to keep the pipe running so that
8151 				 * hw state is consistent with the sw state
8152 				 */
8153 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8154 						__func__, acrtc->base.base.id);
8155 				continue;
8156 			}
8157 
8158 			if (dm_old_crtc_state->stream)
8159 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8160 
8161 			pm_runtime_get_noresume(dev->dev);
8162 
8163 			acrtc->enabled = true;
8164 			acrtc->hw_mode = new_crtc_state->mode;
8165 			crtc->hwmode = new_crtc_state->mode;
8166 			mode_set_reset_required = true;
8167 		} else if (modereset_required(new_crtc_state)) {
8168 			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8169 			/* i.e. reset mode */
8170 			if (dm_old_crtc_state->stream)
8171 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8172 
8173 			mode_set_reset_required = true;
8174 		}
8175 	} /* for_each_crtc_in_state() */
8176 
8177 	if (dc_state) {
8178 		/* if there mode set or reset, disable eDP PSR */
8179 		if (mode_set_reset_required) {
8180 			if (dm->vblank_control_workqueue)
8181 				flush_workqueue(dm->vblank_control_workqueue);
8182 
8183 			amdgpu_dm_psr_disable_all(dm);
8184 		}
8185 
8186 		dm_enable_per_frame_crtc_master_sync(dc_state);
8187 		mutex_lock(&dm->dc_lock);
8188 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
8189 
8190 		/* Allow idle optimization when vblank count is 0 for display off */
8191 		if (dm->active_vblank_irq_count == 0)
8192 			dc_allow_idle_optimizations(dm->dc, true);
8193 		mutex_unlock(&dm->dc_lock);
8194 	}
8195 
8196 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8197 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8198 
8199 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8200 
8201 		if (dm_new_crtc_state->stream != NULL) {
8202 			const struct dc_stream_status *status =
8203 					dc_stream_get_status(dm_new_crtc_state->stream);
8204 
8205 			if (!status)
8206 				status = dc_stream_get_status_from_state(dc_state,
8207 									 dm_new_crtc_state->stream);
8208 			if (!status)
8209 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8210 			else
8211 				acrtc->otg_inst = status->primary_otg_inst;
8212 		}
8213 	}
8214 #ifdef CONFIG_DRM_AMD_DC_HDCP
8215 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8216 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8217 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8218 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8219 
8220 		new_crtc_state = NULL;
8221 
8222 		if (acrtc)
8223 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8224 
8225 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8226 
8227 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8228 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8229 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8230 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8231 			dm_new_con_state->update_hdcp = true;
8232 			continue;
8233 		}
8234 
8235 		if (is_content_protection_different(new_con_state, old_con_state, connector, adev->dm.hdcp_workqueue))
8236 			hdcp_update_display(
8237 				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8238 				new_con_state->hdcp_content_type,
8239 				new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED);
8240 	}
8241 #endif
8242 
8243 	/* Handle connector state changes */
8244 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8245 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8246 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8247 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8248 		struct dc_surface_update dummy_updates[MAX_SURFACES];
8249 		struct dc_stream_update stream_update;
8250 		struct dc_info_packet hdr_packet;
8251 		struct dc_stream_status *status = NULL;
8252 		bool abm_changed, hdr_changed, scaling_changed;
8253 
8254 		memset(&dummy_updates, 0, sizeof(dummy_updates));
8255 		memset(&stream_update, 0, sizeof(stream_update));
8256 
8257 		if (acrtc) {
8258 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8259 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8260 		}
8261 
8262 		/* Skip any modesets/resets */
8263 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8264 			continue;
8265 
8266 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8267 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8268 
8269 		scaling_changed = is_scaling_state_different(dm_new_con_state,
8270 							     dm_old_con_state);
8271 
8272 		abm_changed = dm_new_crtc_state->abm_level !=
8273 			      dm_old_crtc_state->abm_level;
8274 
8275 		hdr_changed =
8276 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8277 
8278 		if (!scaling_changed && !abm_changed && !hdr_changed)
8279 			continue;
8280 
8281 		stream_update.stream = dm_new_crtc_state->stream;
8282 		if (scaling_changed) {
8283 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8284 					dm_new_con_state, dm_new_crtc_state->stream);
8285 
8286 			stream_update.src = dm_new_crtc_state->stream->src;
8287 			stream_update.dst = dm_new_crtc_state->stream->dst;
8288 		}
8289 
8290 		if (abm_changed) {
8291 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8292 
8293 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
8294 		}
8295 
8296 		if (hdr_changed) {
8297 			fill_hdr_info_packet(new_con_state, &hdr_packet);
8298 			stream_update.hdr_static_metadata = &hdr_packet;
8299 		}
8300 
8301 		status = dc_stream_get_status(dm_new_crtc_state->stream);
8302 
8303 		if (WARN_ON(!status))
8304 			continue;
8305 
8306 		WARN_ON(!status->plane_count);
8307 
8308 		/*
8309 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
8310 		 * Here we create an empty update on each plane.
8311 		 * To fix this, DC should permit updating only stream properties.
8312 		 */
8313 		for (j = 0; j < status->plane_count; j++)
8314 			dummy_updates[j].surface = status->plane_states[0];
8315 
8316 
8317 		mutex_lock(&dm->dc_lock);
8318 		dc_commit_updates_for_stream(dm->dc,
8319 						     dummy_updates,
8320 						     status->plane_count,
8321 						     dm_new_crtc_state->stream,
8322 						     &stream_update,
8323 						     dc_state);
8324 		mutex_unlock(&dm->dc_lock);
8325 	}
8326 
8327 	/**
8328 	 * Enable interrupts for CRTCs that are newly enabled or went through
8329 	 * a modeset. It was intentionally deferred until after the front end
8330 	 * state was modified to wait until the OTG was on and so the IRQ
8331 	 * handlers didn't access stale or invalid state.
8332 	 */
8333 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8334 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8335 #ifdef CONFIG_DEBUG_FS
8336 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
8337 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8338 		struct crc_rd_work *crc_rd_wrk;
8339 #endif
8340 #endif
8341 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
8342 		if (old_crtc_state->active && !new_crtc_state->active)
8343 			crtc_disable_count++;
8344 
8345 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8346 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8347 
8348 		/* For freesync config update on crtc state and params for irq */
8349 		update_stream_irq_parameters(dm, dm_new_crtc_state);
8350 
8351 #ifdef CONFIG_DEBUG_FS
8352 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8353 		crc_rd_wrk = dm->crc_rd_wrk;
8354 #endif
8355 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8356 		cur_crc_src = acrtc->dm_irq_params.crc_src;
8357 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8358 #endif
8359 
8360 		if (new_crtc_state->active &&
8361 		    (!old_crtc_state->active ||
8362 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8363 			dc_stream_retain(dm_new_crtc_state->stream);
8364 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8365 			manage_dm_interrupts(adev, acrtc, true);
8366 		}
8367 		/* Handle vrr on->off / off->on transitions */
8368 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8369 
8370 #ifdef CONFIG_DEBUG_FS
8371 		if (new_crtc_state->active &&
8372 		    (!old_crtc_state->active ||
8373 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8374 			/**
8375 			 * Frontend may have changed so reapply the CRC capture
8376 			 * settings for the stream.
8377 			 */
8378 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8379 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8380 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
8381 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8382 					acrtc->dm_irq_params.window_param.update_win = true;
8383 					acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
8384 					spin_lock_irq(&crc_rd_wrk->crc_rd_work_lock);
8385 					crc_rd_wrk->crtc = crtc;
8386 					spin_unlock_irq(&crc_rd_wrk->crc_rd_work_lock);
8387 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8388 				}
8389 #endif
8390 				if (amdgpu_dm_crtc_configure_crc_source(
8391 					crtc, dm_new_crtc_state, cur_crc_src))
8392 					DRM_DEBUG_DRIVER("Failed to configure crc source");
8393 			}
8394 		}
8395 #endif
8396 	}
8397 
8398 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8399 		if (new_crtc_state->async_flip)
8400 			wait_for_vblank = false;
8401 
8402 	/* update planes when needed per crtc*/
8403 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8404 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8405 
8406 		if (dm_new_crtc_state->stream)
8407 			amdgpu_dm_commit_planes(state, dc_state, dev,
8408 						dm, crtc, wait_for_vblank);
8409 	}
8410 
8411 	/* Update audio instances for each connector. */
8412 	amdgpu_dm_commit_audio(dev, state);
8413 
8414 	/* restore the backlight level */
8415 	for (i = 0; i < dm->num_of_edps; i++) {
8416 		if (dm->backlight_dev[i] &&
8417 		    (dm->actual_brightness[i] != dm->brightness[i]))
8418 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8419 	}
8420 
8421 	/*
8422 	 * send vblank event on all events not handled in flip and
8423 	 * mark consumed event for drm_atomic_helper_commit_hw_done
8424 	 */
8425 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8426 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8427 
8428 		if (new_crtc_state->event)
8429 			drm_send_event_locked(dev, &new_crtc_state->event->base);
8430 
8431 		new_crtc_state->event = NULL;
8432 	}
8433 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8434 
8435 	/* Signal HW programming completion */
8436 	drm_atomic_helper_commit_hw_done(state);
8437 
8438 	if (wait_for_vblank)
8439 		drm_atomic_helper_wait_for_flip_done(dev, state);
8440 
8441 	drm_atomic_helper_cleanup_planes(dev, state);
8442 
8443 	/* return the stolen vga memory back to VRAM */
8444 	if (!adev->mman.keep_stolen_vga_memory)
8445 		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8446 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8447 
8448 	/*
8449 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
8450 	 * so we can put the GPU into runtime suspend if we're not driving any
8451 	 * displays anymore
8452 	 */
8453 	for (i = 0; i < crtc_disable_count; i++)
8454 		pm_runtime_put_autosuspend(dev->dev);
8455 	pm_runtime_mark_last_busy(dev->dev);
8456 
8457 	if (dc_state_temp)
8458 		dc_release_state(dc_state_temp);
8459 }
8460 
8461 static int dm_force_atomic_commit(struct drm_connector *connector)
8462 {
8463 	int ret = 0;
8464 	struct drm_device *ddev = connector->dev;
8465 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8466 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8467 	struct drm_plane *plane = disconnected_acrtc->base.primary;
8468 	struct drm_connector_state *conn_state;
8469 	struct drm_crtc_state *crtc_state;
8470 	struct drm_plane_state *plane_state;
8471 
8472 	if (!state)
8473 		return -ENOMEM;
8474 
8475 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
8476 
8477 	/* Construct an atomic state to restore previous display setting */
8478 
8479 	/*
8480 	 * Attach connectors to drm_atomic_state
8481 	 */
8482 	conn_state = drm_atomic_get_connector_state(state, connector);
8483 
8484 	ret = PTR_ERR_OR_ZERO(conn_state);
8485 	if (ret)
8486 		goto out;
8487 
8488 	/* Attach crtc to drm_atomic_state*/
8489 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8490 
8491 	ret = PTR_ERR_OR_ZERO(crtc_state);
8492 	if (ret)
8493 		goto out;
8494 
8495 	/* force a restore */
8496 	crtc_state->mode_changed = true;
8497 
8498 	/* Attach plane to drm_atomic_state */
8499 	plane_state = drm_atomic_get_plane_state(state, plane);
8500 
8501 	ret = PTR_ERR_OR_ZERO(plane_state);
8502 	if (ret)
8503 		goto out;
8504 
8505 	/* Call commit internally with the state we just constructed */
8506 	ret = drm_atomic_commit(state);
8507 
8508 out:
8509 	drm_atomic_state_put(state);
8510 	if (ret)
8511 		DRM_ERROR("Restoring old state failed with %i\n", ret);
8512 
8513 	return ret;
8514 }
8515 
8516 /*
8517  * This function handles all cases when set mode does not come upon hotplug.
8518  * This includes when a display is unplugged then plugged back into the
8519  * same port and when running without usermode desktop manager supprot
8520  */
8521 void dm_restore_drm_connector_state(struct drm_device *dev,
8522 				    struct drm_connector *connector)
8523 {
8524 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8525 	struct amdgpu_crtc *disconnected_acrtc;
8526 	struct dm_crtc_state *acrtc_state;
8527 
8528 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8529 		return;
8530 
8531 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8532 	if (!disconnected_acrtc)
8533 		return;
8534 
8535 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8536 	if (!acrtc_state->stream)
8537 		return;
8538 
8539 	/*
8540 	 * If the previous sink is not released and different from the current,
8541 	 * we deduce we are in a state where we can not rely on usermode call
8542 	 * to turn on the display, so we do it here
8543 	 */
8544 	if (acrtc_state->stream->sink != aconnector->dc_sink)
8545 		dm_force_atomic_commit(&aconnector->base);
8546 }
8547 
8548 /*
8549  * Grabs all modesetting locks to serialize against any blocking commits,
8550  * Waits for completion of all non blocking commits.
8551  */
8552 static int do_aquire_global_lock(struct drm_device *dev,
8553 				 struct drm_atomic_state *state)
8554 {
8555 	struct drm_crtc *crtc;
8556 	struct drm_crtc_commit *commit;
8557 	long ret;
8558 
8559 	/*
8560 	 * Adding all modeset locks to aquire_ctx will
8561 	 * ensure that when the framework release it the
8562 	 * extra locks we are locking here will get released to
8563 	 */
8564 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8565 	if (ret)
8566 		return ret;
8567 
8568 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8569 		spin_lock(&crtc->commit_lock);
8570 		commit = list_first_entry_or_null(&crtc->commit_list,
8571 				struct drm_crtc_commit, commit_entry);
8572 		if (commit)
8573 			drm_crtc_commit_get(commit);
8574 		spin_unlock(&crtc->commit_lock);
8575 
8576 		if (!commit)
8577 			continue;
8578 
8579 		/*
8580 		 * Make sure all pending HW programming completed and
8581 		 * page flips done
8582 		 */
8583 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8584 
8585 		if (ret > 0)
8586 			ret = wait_for_completion_interruptible_timeout(
8587 					&commit->flip_done, 10*HZ);
8588 
8589 		if (ret == 0)
8590 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8591 				  "timed out\n", crtc->base.id, crtc->name);
8592 
8593 		drm_crtc_commit_put(commit);
8594 	}
8595 
8596 	return ret < 0 ? ret : 0;
8597 }
8598 
8599 static void get_freesync_config_for_crtc(
8600 	struct dm_crtc_state *new_crtc_state,
8601 	struct dm_connector_state *new_con_state)
8602 {
8603 	struct mod_freesync_config config = {0};
8604 	struct amdgpu_dm_connector *aconnector =
8605 			to_amdgpu_dm_connector(new_con_state->base.connector);
8606 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
8607 	int vrefresh = drm_mode_vrefresh(mode);
8608 	bool fs_vid_mode = false;
8609 
8610 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8611 					vrefresh >= aconnector->min_vfreq &&
8612 					vrefresh <= aconnector->max_vfreq;
8613 
8614 	if (new_crtc_state->vrr_supported) {
8615 		new_crtc_state->stream->ignore_msa_timing_param = true;
8616 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8617 
8618 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8619 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8620 		config.vsif_supported = true;
8621 		config.btr = true;
8622 
8623 		if (fs_vid_mode) {
8624 			config.state = VRR_STATE_ACTIVE_FIXED;
8625 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8626 			goto out;
8627 		} else if (new_crtc_state->base.vrr_enabled) {
8628 			config.state = VRR_STATE_ACTIVE_VARIABLE;
8629 		} else {
8630 			config.state = VRR_STATE_INACTIVE;
8631 		}
8632 	}
8633 out:
8634 	new_crtc_state->freesync_config = config;
8635 }
8636 
8637 static void reset_freesync_config_for_crtc(
8638 	struct dm_crtc_state *new_crtc_state)
8639 {
8640 	new_crtc_state->vrr_supported = false;
8641 
8642 	memset(&new_crtc_state->vrr_infopacket, 0,
8643 	       sizeof(new_crtc_state->vrr_infopacket));
8644 }
8645 
8646 static bool
8647 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8648 				 struct drm_crtc_state *new_crtc_state)
8649 {
8650 	const struct drm_display_mode *old_mode, *new_mode;
8651 
8652 	if (!old_crtc_state || !new_crtc_state)
8653 		return false;
8654 
8655 	old_mode = &old_crtc_state->mode;
8656 	new_mode = &new_crtc_state->mode;
8657 
8658 	if (old_mode->clock       == new_mode->clock &&
8659 	    old_mode->hdisplay    == new_mode->hdisplay &&
8660 	    old_mode->vdisplay    == new_mode->vdisplay &&
8661 	    old_mode->htotal      == new_mode->htotal &&
8662 	    old_mode->vtotal      != new_mode->vtotal &&
8663 	    old_mode->hsync_start == new_mode->hsync_start &&
8664 	    old_mode->vsync_start != new_mode->vsync_start &&
8665 	    old_mode->hsync_end   == new_mode->hsync_end &&
8666 	    old_mode->vsync_end   != new_mode->vsync_end &&
8667 	    old_mode->hskew       == new_mode->hskew &&
8668 	    old_mode->vscan       == new_mode->vscan &&
8669 	    (old_mode->vsync_end - old_mode->vsync_start) ==
8670 	    (new_mode->vsync_end - new_mode->vsync_start))
8671 		return true;
8672 
8673 	return false;
8674 }
8675 
8676 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
8677 	uint64_t num, den, res;
8678 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
8679 
8680 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
8681 
8682 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
8683 	den = (unsigned long long)new_crtc_state->mode.htotal *
8684 	      (unsigned long long)new_crtc_state->mode.vtotal;
8685 
8686 	res = div_u64(num, den);
8687 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
8688 }
8689 
8690 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
8691 			 struct drm_atomic_state *state,
8692 			 struct drm_crtc *crtc,
8693 			 struct drm_crtc_state *old_crtc_state,
8694 			 struct drm_crtc_state *new_crtc_state,
8695 			 bool enable,
8696 			 bool *lock_and_validation_needed)
8697 {
8698 	struct dm_atomic_state *dm_state = NULL;
8699 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8700 	struct dc_stream_state *new_stream;
8701 	int ret = 0;
8702 
8703 	/*
8704 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
8705 	 * update changed items
8706 	 */
8707 	struct amdgpu_crtc *acrtc = NULL;
8708 	struct amdgpu_dm_connector *aconnector = NULL;
8709 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
8710 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
8711 
8712 	new_stream = NULL;
8713 
8714 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8715 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8716 	acrtc = to_amdgpu_crtc(crtc);
8717 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
8718 
8719 	/* TODO This hack should go away */
8720 	if (aconnector && enable) {
8721 		/* Make sure fake sink is created in plug-in scenario */
8722 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
8723 							    &aconnector->base);
8724 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
8725 							    &aconnector->base);
8726 
8727 		if (IS_ERR(drm_new_conn_state)) {
8728 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
8729 			goto fail;
8730 		}
8731 
8732 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
8733 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
8734 
8735 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8736 			goto skip_modeset;
8737 
8738 		new_stream = create_validate_stream_for_sink(aconnector,
8739 							     &new_crtc_state->mode,
8740 							     dm_new_conn_state,
8741 							     dm_old_crtc_state->stream);
8742 
8743 		/*
8744 		 * we can have no stream on ACTION_SET if a display
8745 		 * was disconnected during S3, in this case it is not an
8746 		 * error, the OS will be updated after detection, and
8747 		 * will do the right thing on next atomic commit
8748 		 */
8749 
8750 		if (!new_stream) {
8751 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8752 					__func__, acrtc->base.base.id);
8753 			ret = -ENOMEM;
8754 			goto fail;
8755 		}
8756 
8757 		/*
8758 		 * TODO: Check VSDB bits to decide whether this should
8759 		 * be enabled or not.
8760 		 */
8761 		new_stream->triggered_crtc_reset.enabled =
8762 			dm->force_timing_sync;
8763 
8764 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8765 
8766 		ret = fill_hdr_info_packet(drm_new_conn_state,
8767 					   &new_stream->hdr_static_metadata);
8768 		if (ret)
8769 			goto fail;
8770 
8771 		/*
8772 		 * If we already removed the old stream from the context
8773 		 * (and set the new stream to NULL) then we can't reuse
8774 		 * the old stream even if the stream and scaling are unchanged.
8775 		 * We'll hit the BUG_ON and black screen.
8776 		 *
8777 		 * TODO: Refactor this function to allow this check to work
8778 		 * in all conditions.
8779 		 */
8780 		if (dm_new_crtc_state->stream &&
8781 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
8782 			goto skip_modeset;
8783 
8784 		if (dm_new_crtc_state->stream &&
8785 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
8786 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
8787 			new_crtc_state->mode_changed = false;
8788 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
8789 					 new_crtc_state->mode_changed);
8790 		}
8791 	}
8792 
8793 	/* mode_changed flag may get updated above, need to check again */
8794 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8795 		goto skip_modeset;
8796 
8797 	drm_dbg_state(state->dev,
8798 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8799 		"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8800 		"connectors_changed:%d\n",
8801 		acrtc->crtc_id,
8802 		new_crtc_state->enable,
8803 		new_crtc_state->active,
8804 		new_crtc_state->planes_changed,
8805 		new_crtc_state->mode_changed,
8806 		new_crtc_state->active_changed,
8807 		new_crtc_state->connectors_changed);
8808 
8809 	/* Remove stream for any changed/disabled CRTC */
8810 	if (!enable) {
8811 
8812 		if (!dm_old_crtc_state->stream)
8813 			goto skip_modeset;
8814 
8815 		if (dm_new_crtc_state->stream &&
8816 		    is_timing_unchanged_for_freesync(new_crtc_state,
8817 						     old_crtc_state)) {
8818 			new_crtc_state->mode_changed = false;
8819 			DRM_DEBUG_DRIVER(
8820 				"Mode change not required for front porch change, "
8821 				"setting mode_changed to %d",
8822 				new_crtc_state->mode_changed);
8823 
8824 			set_freesync_fixed_config(dm_new_crtc_state);
8825 
8826 			goto skip_modeset;
8827 		} else if (aconnector &&
8828 			   is_freesync_video_mode(&new_crtc_state->mode,
8829 						  aconnector)) {
8830 			struct drm_display_mode *high_mode;
8831 
8832 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
8833 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
8834 				set_freesync_fixed_config(dm_new_crtc_state);
8835 			}
8836 		}
8837 
8838 		ret = dm_atomic_get_state(state, &dm_state);
8839 		if (ret)
8840 			goto fail;
8841 
8842 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
8843 				crtc->base.id);
8844 
8845 		/* i.e. reset mode */
8846 		if (dc_remove_stream_from_ctx(
8847 				dm->dc,
8848 				dm_state->context,
8849 				dm_old_crtc_state->stream) != DC_OK) {
8850 			ret = -EINVAL;
8851 			goto fail;
8852 		}
8853 
8854 		dc_stream_release(dm_old_crtc_state->stream);
8855 		dm_new_crtc_state->stream = NULL;
8856 
8857 		reset_freesync_config_for_crtc(dm_new_crtc_state);
8858 
8859 		*lock_and_validation_needed = true;
8860 
8861 	} else {/* Add stream for any updated/enabled CRTC */
8862 		/*
8863 		 * Quick fix to prevent NULL pointer on new_stream when
8864 		 * added MST connectors not found in existing crtc_state in the chained mode
8865 		 * TODO: need to dig out the root cause of that
8866 		 */
8867 		if (!aconnector)
8868 			goto skip_modeset;
8869 
8870 		if (modereset_required(new_crtc_state))
8871 			goto skip_modeset;
8872 
8873 		if (modeset_required(new_crtc_state, new_stream,
8874 				     dm_old_crtc_state->stream)) {
8875 
8876 			WARN_ON(dm_new_crtc_state->stream);
8877 
8878 			ret = dm_atomic_get_state(state, &dm_state);
8879 			if (ret)
8880 				goto fail;
8881 
8882 			dm_new_crtc_state->stream = new_stream;
8883 
8884 			dc_stream_retain(new_stream);
8885 
8886 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
8887 					 crtc->base.id);
8888 
8889 			if (dc_add_stream_to_ctx(
8890 					dm->dc,
8891 					dm_state->context,
8892 					dm_new_crtc_state->stream) != DC_OK) {
8893 				ret = -EINVAL;
8894 				goto fail;
8895 			}
8896 
8897 			*lock_and_validation_needed = true;
8898 		}
8899 	}
8900 
8901 skip_modeset:
8902 	/* Release extra reference */
8903 	if (new_stream)
8904 		 dc_stream_release(new_stream);
8905 
8906 	/*
8907 	 * We want to do dc stream updates that do not require a
8908 	 * full modeset below.
8909 	 */
8910 	if (!(enable && aconnector && new_crtc_state->active))
8911 		return 0;
8912 	/*
8913 	 * Given above conditions, the dc state cannot be NULL because:
8914 	 * 1. We're in the process of enabling CRTCs (just been added
8915 	 *    to the dc context, or already is on the context)
8916 	 * 2. Has a valid connector attached, and
8917 	 * 3. Is currently active and enabled.
8918 	 * => The dc stream state currently exists.
8919 	 */
8920 	BUG_ON(dm_new_crtc_state->stream == NULL);
8921 
8922 	/* Scaling or underscan settings */
8923 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
8924 				drm_atomic_crtc_needs_modeset(new_crtc_state))
8925 		update_stream_scaling_settings(
8926 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
8927 
8928 	/* ABM settings */
8929 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8930 
8931 	/*
8932 	 * Color management settings. We also update color properties
8933 	 * when a modeset is needed, to ensure it gets reprogrammed.
8934 	 */
8935 	if (dm_new_crtc_state->base.color_mgmt_changed ||
8936 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
8937 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
8938 		if (ret)
8939 			goto fail;
8940 	}
8941 
8942 	/* Update Freesync settings. */
8943 	get_freesync_config_for_crtc(dm_new_crtc_state,
8944 				     dm_new_conn_state);
8945 
8946 	return ret;
8947 
8948 fail:
8949 	if (new_stream)
8950 		dc_stream_release(new_stream);
8951 	return ret;
8952 }
8953 
8954 static bool should_reset_plane(struct drm_atomic_state *state,
8955 			       struct drm_plane *plane,
8956 			       struct drm_plane_state *old_plane_state,
8957 			       struct drm_plane_state *new_plane_state)
8958 {
8959 	struct drm_plane *other;
8960 	struct drm_plane_state *old_other_state, *new_other_state;
8961 	struct drm_crtc_state *new_crtc_state;
8962 	int i;
8963 
8964 	/*
8965 	 * TODO: Remove this hack once the checks below are sufficient
8966 	 * enough to determine when we need to reset all the planes on
8967 	 * the stream.
8968 	 */
8969 	if (state->allow_modeset)
8970 		return true;
8971 
8972 	/* Exit early if we know that we're adding or removing the plane. */
8973 	if (old_plane_state->crtc != new_plane_state->crtc)
8974 		return true;
8975 
8976 	/* old crtc == new_crtc == NULL, plane not in context. */
8977 	if (!new_plane_state->crtc)
8978 		return false;
8979 
8980 	new_crtc_state =
8981 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
8982 
8983 	if (!new_crtc_state)
8984 		return true;
8985 
8986 	/* CRTC Degamma changes currently require us to recreate planes. */
8987 	if (new_crtc_state->color_mgmt_changed)
8988 		return true;
8989 
8990 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
8991 		return true;
8992 
8993 	/*
8994 	 * If there are any new primary or overlay planes being added or
8995 	 * removed then the z-order can potentially change. To ensure
8996 	 * correct z-order and pipe acquisition the current DC architecture
8997 	 * requires us to remove and recreate all existing planes.
8998 	 *
8999 	 * TODO: Come up with a more elegant solution for this.
9000 	 */
9001 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9002 		struct amdgpu_framebuffer *old_afb, *new_afb;
9003 		if (other->type == DRM_PLANE_TYPE_CURSOR)
9004 			continue;
9005 
9006 		if (old_other_state->crtc != new_plane_state->crtc &&
9007 		    new_other_state->crtc != new_plane_state->crtc)
9008 			continue;
9009 
9010 		if (old_other_state->crtc != new_other_state->crtc)
9011 			return true;
9012 
9013 		/* Src/dst size and scaling updates. */
9014 		if (old_other_state->src_w != new_other_state->src_w ||
9015 		    old_other_state->src_h != new_other_state->src_h ||
9016 		    old_other_state->crtc_w != new_other_state->crtc_w ||
9017 		    old_other_state->crtc_h != new_other_state->crtc_h)
9018 			return true;
9019 
9020 		/* Rotation / mirroring updates. */
9021 		if (old_other_state->rotation != new_other_state->rotation)
9022 			return true;
9023 
9024 		/* Blending updates. */
9025 		if (old_other_state->pixel_blend_mode !=
9026 		    new_other_state->pixel_blend_mode)
9027 			return true;
9028 
9029 		/* Alpha updates. */
9030 		if (old_other_state->alpha != new_other_state->alpha)
9031 			return true;
9032 
9033 		/* Colorspace changes. */
9034 		if (old_other_state->color_range != new_other_state->color_range ||
9035 		    old_other_state->color_encoding != new_other_state->color_encoding)
9036 			return true;
9037 
9038 		/* Framebuffer checks fall at the end. */
9039 		if (!old_other_state->fb || !new_other_state->fb)
9040 			continue;
9041 
9042 		/* Pixel format changes can require bandwidth updates. */
9043 		if (old_other_state->fb->format != new_other_state->fb->format)
9044 			return true;
9045 
9046 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9047 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9048 
9049 		/* Tiling and DCC changes also require bandwidth updates. */
9050 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
9051 		    old_afb->base.modifier != new_afb->base.modifier)
9052 			return true;
9053 	}
9054 
9055 	return false;
9056 }
9057 
9058 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9059 			      struct drm_plane_state *new_plane_state,
9060 			      struct drm_framebuffer *fb)
9061 {
9062 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9063 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9064 	unsigned int pitch;
9065 	bool linear;
9066 
9067 	if (fb->width > new_acrtc->max_cursor_width ||
9068 	    fb->height > new_acrtc->max_cursor_height) {
9069 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9070 				 new_plane_state->fb->width,
9071 				 new_plane_state->fb->height);
9072 		return -EINVAL;
9073 	}
9074 	if (new_plane_state->src_w != fb->width << 16 ||
9075 	    new_plane_state->src_h != fb->height << 16) {
9076 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9077 		return -EINVAL;
9078 	}
9079 
9080 	/* Pitch in pixels */
9081 	pitch = fb->pitches[0] / fb->format->cpp[0];
9082 
9083 	if (fb->width != pitch) {
9084 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9085 				 fb->width, pitch);
9086 		return -EINVAL;
9087 	}
9088 
9089 	switch (pitch) {
9090 	case 64:
9091 	case 128:
9092 	case 256:
9093 		/* FB pitch is supported by cursor plane */
9094 		break;
9095 	default:
9096 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9097 		return -EINVAL;
9098 	}
9099 
9100 	/* Core DRM takes care of checking FB modifiers, so we only need to
9101 	 * check tiling flags when the FB doesn't have a modifier. */
9102 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9103 		if (adev->family < AMDGPU_FAMILY_AI) {
9104 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9105 			         AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9106 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9107 		} else {
9108 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9109 		}
9110 		if (!linear) {
9111 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
9112 			return -EINVAL;
9113 		}
9114 	}
9115 
9116 	return 0;
9117 }
9118 
9119 static int dm_update_plane_state(struct dc *dc,
9120 				 struct drm_atomic_state *state,
9121 				 struct drm_plane *plane,
9122 				 struct drm_plane_state *old_plane_state,
9123 				 struct drm_plane_state *new_plane_state,
9124 				 bool enable,
9125 				 bool *lock_and_validation_needed)
9126 {
9127 
9128 	struct dm_atomic_state *dm_state = NULL;
9129 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9130 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9131 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9132 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9133 	struct amdgpu_crtc *new_acrtc;
9134 	bool needs_reset;
9135 	int ret = 0;
9136 
9137 
9138 	new_plane_crtc = new_plane_state->crtc;
9139 	old_plane_crtc = old_plane_state->crtc;
9140 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
9141 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
9142 
9143 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9144 		if (!enable || !new_plane_crtc ||
9145 			drm_atomic_plane_disabling(plane->state, new_plane_state))
9146 			return 0;
9147 
9148 		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9149 
9150 		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9151 			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9152 			return -EINVAL;
9153 		}
9154 
9155 		if (new_plane_state->fb) {
9156 			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9157 						 new_plane_state->fb);
9158 			if (ret)
9159 				return ret;
9160 		}
9161 
9162 		return 0;
9163 	}
9164 
9165 	needs_reset = should_reset_plane(state, plane, old_plane_state,
9166 					 new_plane_state);
9167 
9168 	/* Remove any changed/removed planes */
9169 	if (!enable) {
9170 		if (!needs_reset)
9171 			return 0;
9172 
9173 		if (!old_plane_crtc)
9174 			return 0;
9175 
9176 		old_crtc_state = drm_atomic_get_old_crtc_state(
9177 				state, old_plane_crtc);
9178 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9179 
9180 		if (!dm_old_crtc_state->stream)
9181 			return 0;
9182 
9183 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9184 				plane->base.id, old_plane_crtc->base.id);
9185 
9186 		ret = dm_atomic_get_state(state, &dm_state);
9187 		if (ret)
9188 			return ret;
9189 
9190 		if (!dc_remove_plane_from_context(
9191 				dc,
9192 				dm_old_crtc_state->stream,
9193 				dm_old_plane_state->dc_state,
9194 				dm_state->context)) {
9195 
9196 			return -EINVAL;
9197 		}
9198 
9199 
9200 		dc_plane_state_release(dm_old_plane_state->dc_state);
9201 		dm_new_plane_state->dc_state = NULL;
9202 
9203 		*lock_and_validation_needed = true;
9204 
9205 	} else { /* Add new planes */
9206 		struct dc_plane_state *dc_new_plane_state;
9207 
9208 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9209 			return 0;
9210 
9211 		if (!new_plane_crtc)
9212 			return 0;
9213 
9214 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9215 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9216 
9217 		if (!dm_new_crtc_state->stream)
9218 			return 0;
9219 
9220 		if (!needs_reset)
9221 			return 0;
9222 
9223 		ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9224 		if (ret)
9225 			return ret;
9226 
9227 		WARN_ON(dm_new_plane_state->dc_state);
9228 
9229 		dc_new_plane_state = dc_create_plane_state(dc);
9230 		if (!dc_new_plane_state)
9231 			return -ENOMEM;
9232 
9233 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9234 				 plane->base.id, new_plane_crtc->base.id);
9235 
9236 		ret = fill_dc_plane_attributes(
9237 			drm_to_adev(new_plane_crtc->dev),
9238 			dc_new_plane_state,
9239 			new_plane_state,
9240 			new_crtc_state);
9241 		if (ret) {
9242 			dc_plane_state_release(dc_new_plane_state);
9243 			return ret;
9244 		}
9245 
9246 		ret = dm_atomic_get_state(state, &dm_state);
9247 		if (ret) {
9248 			dc_plane_state_release(dc_new_plane_state);
9249 			return ret;
9250 		}
9251 
9252 		/*
9253 		 * Any atomic check errors that occur after this will
9254 		 * not need a release. The plane state will be attached
9255 		 * to the stream, and therefore part of the atomic
9256 		 * state. It'll be released when the atomic state is
9257 		 * cleaned.
9258 		 */
9259 		if (!dc_add_plane_to_context(
9260 				dc,
9261 				dm_new_crtc_state->stream,
9262 				dc_new_plane_state,
9263 				dm_state->context)) {
9264 
9265 			dc_plane_state_release(dc_new_plane_state);
9266 			return -EINVAL;
9267 		}
9268 
9269 		dm_new_plane_state->dc_state = dc_new_plane_state;
9270 
9271 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9272 
9273 		/* Tell DC to do a full surface update every time there
9274 		 * is a plane change. Inefficient, but works for now.
9275 		 */
9276 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9277 
9278 		*lock_and_validation_needed = true;
9279 	}
9280 
9281 
9282 	return ret;
9283 }
9284 
9285 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9286 				       int *src_w, int *src_h)
9287 {
9288 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9289 	case DRM_MODE_ROTATE_90:
9290 	case DRM_MODE_ROTATE_270:
9291 		*src_w = plane_state->src_h >> 16;
9292 		*src_h = plane_state->src_w >> 16;
9293 		break;
9294 	case DRM_MODE_ROTATE_0:
9295 	case DRM_MODE_ROTATE_180:
9296 	default:
9297 		*src_w = plane_state->src_w >> 16;
9298 		*src_h = plane_state->src_h >> 16;
9299 		break;
9300 	}
9301 }
9302 
9303 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9304 				struct drm_crtc *crtc,
9305 				struct drm_crtc_state *new_crtc_state)
9306 {
9307 	struct drm_plane *cursor = crtc->cursor, *underlying;
9308 	struct drm_plane_state *new_cursor_state, *new_underlying_state;
9309 	int i;
9310 	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9311 	int cursor_src_w, cursor_src_h;
9312 	int underlying_src_w, underlying_src_h;
9313 
9314 	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9315 	 * cursor per pipe but it's going to inherit the scaling and
9316 	 * positioning from the underlying pipe. Check the cursor plane's
9317 	 * blending properties match the underlying planes'. */
9318 
9319 	new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9320 	if (!new_cursor_state || !new_cursor_state->fb) {
9321 		return 0;
9322 	}
9323 
9324 	dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9325 	cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9326 	cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9327 
9328 	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9329 		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
9330 		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9331 			continue;
9332 
9333 		/* Ignore disabled planes */
9334 		if (!new_underlying_state->fb)
9335 			continue;
9336 
9337 		dm_get_oriented_plane_size(new_underlying_state,
9338 					   &underlying_src_w, &underlying_src_h);
9339 		underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9340 		underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9341 
9342 		if (cursor_scale_w != underlying_scale_w ||
9343 		    cursor_scale_h != underlying_scale_h) {
9344 			drm_dbg_atomic(crtc->dev,
9345 				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9346 				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9347 			return -EINVAL;
9348 		}
9349 
9350 		/* If this plane covers the whole CRTC, no need to check planes underneath */
9351 		if (new_underlying_state->crtc_x <= 0 &&
9352 		    new_underlying_state->crtc_y <= 0 &&
9353 		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9354 		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9355 			break;
9356 	}
9357 
9358 	return 0;
9359 }
9360 
9361 #if defined(CONFIG_DRM_AMD_DC_DCN)
9362 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9363 {
9364 	struct drm_connector *connector;
9365 	struct drm_connector_state *conn_state, *old_conn_state;
9366 	struct amdgpu_dm_connector *aconnector = NULL;
9367 	int i;
9368 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9369 		if (!conn_state->crtc)
9370 			conn_state = old_conn_state;
9371 
9372 		if (conn_state->crtc != crtc)
9373 			continue;
9374 
9375 		aconnector = to_amdgpu_dm_connector(connector);
9376 		if (!aconnector->port || !aconnector->mst_port)
9377 			aconnector = NULL;
9378 		else
9379 			break;
9380 	}
9381 
9382 	if (!aconnector)
9383 		return 0;
9384 
9385 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_port->mst_mgr);
9386 }
9387 #endif
9388 
9389 /**
9390  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9391  *
9392  * @dev: The DRM device
9393  * @state: The atomic state to commit
9394  *
9395  * Validate that the given atomic state is programmable by DC into hardware.
9396  * This involves constructing a &struct dc_state reflecting the new hardware
9397  * state we wish to commit, then querying DC to see if it is programmable. It's
9398  * important not to modify the existing DC state. Otherwise, atomic_check
9399  * may unexpectedly commit hardware changes.
9400  *
9401  * When validating the DC state, it's important that the right locks are
9402  * acquired. For full updates case which removes/adds/updates streams on one
9403  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9404  * that any such full update commit will wait for completion of any outstanding
9405  * flip using DRMs synchronization events.
9406  *
9407  * Note that DM adds the affected connectors for all CRTCs in state, when that
9408  * might not seem necessary. This is because DC stream creation requires the
9409  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9410  * be possible but non-trivial - a possible TODO item.
9411  *
9412  * Return: -Error code if validation failed.
9413  */
9414 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9415 				  struct drm_atomic_state *state)
9416 {
9417 	struct amdgpu_device *adev = drm_to_adev(dev);
9418 	struct dm_atomic_state *dm_state = NULL;
9419 	struct dc *dc = adev->dm.dc;
9420 	struct drm_connector *connector;
9421 	struct drm_connector_state *old_con_state, *new_con_state;
9422 	struct drm_crtc *crtc;
9423 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9424 	struct drm_plane *plane;
9425 	struct drm_plane_state *old_plane_state, *new_plane_state;
9426 	enum dc_status status;
9427 	int ret, i;
9428 	bool lock_and_validation_needed = false;
9429 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9430 #if defined(CONFIG_DRM_AMD_DC_DCN)
9431 	struct dsc_mst_fairness_vars vars[MAX_PIPES];
9432 #endif
9433 
9434 	trace_amdgpu_dm_atomic_check_begin(state);
9435 
9436 	ret = drm_atomic_helper_check_modeset(dev, state);
9437 	if (ret) {
9438 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9439 		goto fail;
9440 	}
9441 
9442 	/* Check connector changes */
9443 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9444 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9445 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9446 
9447 		/* Skip connectors that are disabled or part of modeset already. */
9448 		if (!new_con_state->crtc)
9449 			continue;
9450 
9451 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9452 		if (IS_ERR(new_crtc_state)) {
9453 			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9454 			ret = PTR_ERR(new_crtc_state);
9455 			goto fail;
9456 		}
9457 
9458 		if (dm_old_con_state->abm_level !=
9459 		    dm_new_con_state->abm_level)
9460 			new_crtc_state->connectors_changed = true;
9461 	}
9462 
9463 #if defined(CONFIG_DRM_AMD_DC_DCN)
9464 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9465 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9466 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9467 				ret = add_affected_mst_dsc_crtcs(state, crtc);
9468 				if (ret) {
9469 					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9470 					goto fail;
9471 				}
9472 			}
9473 		}
9474 	}
9475 #endif
9476 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9477 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9478 
9479 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9480 		    !new_crtc_state->color_mgmt_changed &&
9481 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9482 			dm_old_crtc_state->dsc_force_changed == false)
9483 			continue;
9484 
9485 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9486 		if (ret) {
9487 			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9488 			goto fail;
9489 		}
9490 
9491 		if (!new_crtc_state->enable)
9492 			continue;
9493 
9494 		ret = drm_atomic_add_affected_connectors(state, crtc);
9495 		if (ret) {
9496 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9497 			goto fail;
9498 		}
9499 
9500 		ret = drm_atomic_add_affected_planes(state, crtc);
9501 		if (ret) {
9502 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9503 			goto fail;
9504 		}
9505 
9506 		if (dm_old_crtc_state->dsc_force_changed)
9507 			new_crtc_state->mode_changed = true;
9508 	}
9509 
9510 	/*
9511 	 * Add all primary and overlay planes on the CRTC to the state
9512 	 * whenever a plane is enabled to maintain correct z-ordering
9513 	 * and to enable fast surface updates.
9514 	 */
9515 	drm_for_each_crtc(crtc, dev) {
9516 		bool modified = false;
9517 
9518 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9519 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9520 				continue;
9521 
9522 			if (new_plane_state->crtc == crtc ||
9523 			    old_plane_state->crtc == crtc) {
9524 				modified = true;
9525 				break;
9526 			}
9527 		}
9528 
9529 		if (!modified)
9530 			continue;
9531 
9532 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9533 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9534 				continue;
9535 
9536 			new_plane_state =
9537 				drm_atomic_get_plane_state(state, plane);
9538 
9539 			if (IS_ERR(new_plane_state)) {
9540 				ret = PTR_ERR(new_plane_state);
9541 				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9542 				goto fail;
9543 			}
9544 		}
9545 	}
9546 
9547 	/*
9548 	 * DC consults the zpos (layer_index in DC terminology) to determine the
9549 	 * hw plane on which to enable the hw cursor (see
9550 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9551 	 * atomic state, so call drm helper to normalize zpos.
9552 	 */
9553 	drm_atomic_normalize_zpos(dev, state);
9554 
9555 	/* Remove exiting planes if they are modified */
9556 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9557 		ret = dm_update_plane_state(dc, state, plane,
9558 					    old_plane_state,
9559 					    new_plane_state,
9560 					    false,
9561 					    &lock_and_validation_needed);
9562 		if (ret) {
9563 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9564 			goto fail;
9565 		}
9566 	}
9567 
9568 	/* Disable all crtcs which require disable */
9569 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9570 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9571 					   old_crtc_state,
9572 					   new_crtc_state,
9573 					   false,
9574 					   &lock_and_validation_needed);
9575 		if (ret) {
9576 			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9577 			goto fail;
9578 		}
9579 	}
9580 
9581 	/* Enable all crtcs which require enable */
9582 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9583 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9584 					   old_crtc_state,
9585 					   new_crtc_state,
9586 					   true,
9587 					   &lock_and_validation_needed);
9588 		if (ret) {
9589 			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9590 			goto fail;
9591 		}
9592 	}
9593 
9594 	/* Add new/modified planes */
9595 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9596 		ret = dm_update_plane_state(dc, state, plane,
9597 					    old_plane_state,
9598 					    new_plane_state,
9599 					    true,
9600 					    &lock_and_validation_needed);
9601 		if (ret) {
9602 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9603 			goto fail;
9604 		}
9605 	}
9606 
9607 #if defined(CONFIG_DRM_AMD_DC_DCN)
9608 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9609 		ret = pre_validate_dsc(state, &dm_state, vars);
9610 		if (ret != 0)
9611 			goto fail;
9612 	}
9613 #endif
9614 
9615 	/* Run this here since we want to validate the streams we created */
9616 	ret = drm_atomic_helper_check_planes(dev, state);
9617 	if (ret) {
9618 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
9619 		goto fail;
9620 	}
9621 
9622 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9623 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9624 		if (dm_new_crtc_state->mpo_requested)
9625 			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
9626 	}
9627 
9628 	/* Check cursor planes scaling */
9629 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9630 		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
9631 		if (ret) {
9632 			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
9633 			goto fail;
9634 		}
9635 	}
9636 
9637 	if (state->legacy_cursor_update) {
9638 		/*
9639 		 * This is a fast cursor update coming from the plane update
9640 		 * helper, check if it can be done asynchronously for better
9641 		 * performance.
9642 		 */
9643 		state->async_update =
9644 			!drm_atomic_helper_async_check(dev, state);
9645 
9646 		/*
9647 		 * Skip the remaining global validation if this is an async
9648 		 * update. Cursor updates can be done without affecting
9649 		 * state or bandwidth calcs and this avoids the performance
9650 		 * penalty of locking the private state object and
9651 		 * allocating a new dc_state.
9652 		 */
9653 		if (state->async_update)
9654 			return 0;
9655 	}
9656 
9657 	/* Check scaling and underscan changes*/
9658 	/* TODO Removed scaling changes validation due to inability to commit
9659 	 * new stream into context w\o causing full reset. Need to
9660 	 * decide how to handle.
9661 	 */
9662 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9663 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9664 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9665 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9666 
9667 		/* Skip any modesets/resets */
9668 		if (!acrtc || drm_atomic_crtc_needs_modeset(
9669 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
9670 			continue;
9671 
9672 		/* Skip any thing not scale or underscan changes */
9673 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
9674 			continue;
9675 
9676 		lock_and_validation_needed = true;
9677 	}
9678 
9679 	/**
9680 	 * Streams and planes are reset when there are changes that affect
9681 	 * bandwidth. Anything that affects bandwidth needs to go through
9682 	 * DC global validation to ensure that the configuration can be applied
9683 	 * to hardware.
9684 	 *
9685 	 * We have to currently stall out here in atomic_check for outstanding
9686 	 * commits to finish in this case because our IRQ handlers reference
9687 	 * DRM state directly - we can end up disabling interrupts too early
9688 	 * if we don't.
9689 	 *
9690 	 * TODO: Remove this stall and drop DM state private objects.
9691 	 */
9692 	if (lock_and_validation_needed) {
9693 		ret = dm_atomic_get_state(state, &dm_state);
9694 		if (ret) {
9695 			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
9696 			goto fail;
9697 		}
9698 
9699 		ret = do_aquire_global_lock(dev, state);
9700 		if (ret) {
9701 			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
9702 			goto fail;
9703 		}
9704 
9705 #if defined(CONFIG_DRM_AMD_DC_DCN)
9706 		ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
9707 		if (ret) {
9708 			DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
9709 			goto fail;
9710 		}
9711 
9712 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
9713 		if (ret) {
9714 			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
9715 			goto fail;
9716 		}
9717 #endif
9718 
9719 		/*
9720 		 * Perform validation of MST topology in the state:
9721 		 * We need to perform MST atomic check before calling
9722 		 * dc_validate_global_state(), or there is a chance
9723 		 * to get stuck in an infinite loop and hang eventually.
9724 		 */
9725 		ret = drm_dp_mst_atomic_check(state);
9726 		if (ret) {
9727 			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
9728 			goto fail;
9729 		}
9730 		status = dc_validate_global_state(dc, dm_state->context, true);
9731 		if (status != DC_OK) {
9732 			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
9733 				       dc_status_to_str(status), status);
9734 			ret = -EINVAL;
9735 			goto fail;
9736 		}
9737 	} else {
9738 		/*
9739 		 * The commit is a fast update. Fast updates shouldn't change
9740 		 * the DC context, affect global validation, and can have their
9741 		 * commit work done in parallel with other commits not touching
9742 		 * the same resource. If we have a new DC context as part of
9743 		 * the DM atomic state from validation we need to free it and
9744 		 * retain the existing one instead.
9745 		 *
9746 		 * Furthermore, since the DM atomic state only contains the DC
9747 		 * context and can safely be annulled, we can free the state
9748 		 * and clear the associated private object now to free
9749 		 * some memory and avoid a possible use-after-free later.
9750 		 */
9751 
9752 		for (i = 0; i < state->num_private_objs; i++) {
9753 			struct drm_private_obj *obj = state->private_objs[i].ptr;
9754 
9755 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
9756 				int j = state->num_private_objs-1;
9757 
9758 				dm_atomic_destroy_state(obj,
9759 						state->private_objs[i].state);
9760 
9761 				/* If i is not at the end of the array then the
9762 				 * last element needs to be moved to where i was
9763 				 * before the array can safely be truncated.
9764 				 */
9765 				if (i != j)
9766 					state->private_objs[i] =
9767 						state->private_objs[j];
9768 
9769 				state->private_objs[j].ptr = NULL;
9770 				state->private_objs[j].state = NULL;
9771 				state->private_objs[j].old_state = NULL;
9772 				state->private_objs[j].new_state = NULL;
9773 
9774 				state->num_private_objs = j;
9775 				break;
9776 			}
9777 		}
9778 	}
9779 
9780 	/* Store the overall update type for use later in atomic check. */
9781 	for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
9782 		struct dm_crtc_state *dm_new_crtc_state =
9783 			to_dm_crtc_state(new_crtc_state);
9784 
9785 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
9786 							 UPDATE_TYPE_FULL :
9787 							 UPDATE_TYPE_FAST;
9788 	}
9789 
9790 	/* Must be success */
9791 	WARN_ON(ret);
9792 
9793 	trace_amdgpu_dm_atomic_check_finish(state, ret);
9794 
9795 	return ret;
9796 
9797 fail:
9798 	if (ret == -EDEADLK)
9799 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
9800 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
9801 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
9802 	else
9803 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
9804 
9805 	trace_amdgpu_dm_atomic_check_finish(state, ret);
9806 
9807 	return ret;
9808 }
9809 
9810 static bool is_dp_capable_without_timing_msa(struct dc *dc,
9811 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
9812 {
9813 	uint8_t dpcd_data;
9814 	bool capable = false;
9815 
9816 	if (amdgpu_dm_connector->dc_link &&
9817 		dm_helpers_dp_read_dpcd(
9818 				NULL,
9819 				amdgpu_dm_connector->dc_link,
9820 				DP_DOWN_STREAM_PORT_COUNT,
9821 				&dpcd_data,
9822 				sizeof(dpcd_data))) {
9823 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
9824 	}
9825 
9826 	return capable;
9827 }
9828 
9829 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
9830 		unsigned int offset,
9831 		unsigned int total_length,
9832 		uint8_t *data,
9833 		unsigned int length,
9834 		struct amdgpu_hdmi_vsdb_info *vsdb)
9835 {
9836 	bool res;
9837 	union dmub_rb_cmd cmd;
9838 	struct dmub_cmd_send_edid_cea *input;
9839 	struct dmub_cmd_edid_cea_output *output;
9840 
9841 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
9842 		return false;
9843 
9844 	memset(&cmd, 0, sizeof(cmd));
9845 
9846 	input = &cmd.edid_cea.data.input;
9847 
9848 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
9849 	cmd.edid_cea.header.sub_type = 0;
9850 	cmd.edid_cea.header.payload_bytes =
9851 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
9852 	input->offset = offset;
9853 	input->length = length;
9854 	input->cea_total_length = total_length;
9855 	memcpy(input->payload, data, length);
9856 
9857 	res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
9858 	if (!res) {
9859 		DRM_ERROR("EDID CEA parser failed\n");
9860 		return false;
9861 	}
9862 
9863 	output = &cmd.edid_cea.data.output;
9864 
9865 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
9866 		if (!output->ack.success) {
9867 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
9868 					output->ack.offset);
9869 		}
9870 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
9871 		if (!output->amd_vsdb.vsdb_found)
9872 			return false;
9873 
9874 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
9875 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
9876 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
9877 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
9878 	} else {
9879 		DRM_WARN("Unknown EDID CEA parser results\n");
9880 		return false;
9881 	}
9882 
9883 	return true;
9884 }
9885 
9886 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
9887 		uint8_t *edid_ext, int len,
9888 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9889 {
9890 	int i;
9891 
9892 	/* send extension block to DMCU for parsing */
9893 	for (i = 0; i < len; i += 8) {
9894 		bool res;
9895 		int offset;
9896 
9897 		/* send 8 bytes a time */
9898 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
9899 			return false;
9900 
9901 		if (i+8 == len) {
9902 			/* EDID block sent completed, expect result */
9903 			int version, min_rate, max_rate;
9904 
9905 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
9906 			if (res) {
9907 				/* amd vsdb found */
9908 				vsdb_info->freesync_supported = 1;
9909 				vsdb_info->amd_vsdb_version = version;
9910 				vsdb_info->min_refresh_rate_hz = min_rate;
9911 				vsdb_info->max_refresh_rate_hz = max_rate;
9912 				return true;
9913 			}
9914 			/* not amd vsdb */
9915 			return false;
9916 		}
9917 
9918 		/* check for ack*/
9919 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
9920 		if (!res)
9921 			return false;
9922 	}
9923 
9924 	return false;
9925 }
9926 
9927 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
9928 		uint8_t *edid_ext, int len,
9929 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9930 {
9931 	int i;
9932 
9933 	/* send extension block to DMCU for parsing */
9934 	for (i = 0; i < len; i += 8) {
9935 		/* send 8 bytes a time */
9936 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
9937 			return false;
9938 	}
9939 
9940 	return vsdb_info->freesync_supported;
9941 }
9942 
9943 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
9944 		uint8_t *edid_ext, int len,
9945 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9946 {
9947 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
9948 
9949 	if (adev->dm.dmub_srv)
9950 		return parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
9951 	else
9952 		return parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
9953 }
9954 
9955 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
9956 		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
9957 {
9958 	uint8_t *edid_ext = NULL;
9959 	int i;
9960 	bool valid_vsdb_found = false;
9961 
9962 	/*----- drm_find_cea_extension() -----*/
9963 	/* No EDID or EDID extensions */
9964 	if (edid == NULL || edid->extensions == 0)
9965 		return -ENODEV;
9966 
9967 	/* Find CEA extension */
9968 	for (i = 0; i < edid->extensions; i++) {
9969 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
9970 		if (edid_ext[0] == CEA_EXT)
9971 			break;
9972 	}
9973 
9974 	if (i == edid->extensions)
9975 		return -ENODEV;
9976 
9977 	/*----- cea_db_offsets() -----*/
9978 	if (edid_ext[0] != CEA_EXT)
9979 		return -ENODEV;
9980 
9981 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
9982 
9983 	return valid_vsdb_found ? i : -ENODEV;
9984 }
9985 
9986 /**
9987  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
9988  *
9989  * @connector: Connector to query.
9990  * @edid: EDID from monitor
9991  *
9992  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
9993  * track of some of the display information in the internal data struct used by
9994  * amdgpu_dm. This function checks which type of connector we need to set the
9995  * FreeSync parameters.
9996  */
9997 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
9998 				    struct edid *edid)
9999 {
10000 	int i = 0;
10001 	struct detailed_timing *timing;
10002 	struct detailed_non_pixel *data;
10003 	struct detailed_data_monitor_range *range;
10004 	struct amdgpu_dm_connector *amdgpu_dm_connector =
10005 			to_amdgpu_dm_connector(connector);
10006 	struct dm_connector_state *dm_con_state = NULL;
10007 	struct dc_sink *sink;
10008 
10009 	struct drm_device *dev = connector->dev;
10010 	struct amdgpu_device *adev = drm_to_adev(dev);
10011 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10012 	bool freesync_capable = false;
10013 
10014 	if (!connector->state) {
10015 		DRM_ERROR("%s - Connector has no state", __func__);
10016 		goto update;
10017 	}
10018 
10019 	sink = amdgpu_dm_connector->dc_sink ?
10020 		amdgpu_dm_connector->dc_sink :
10021 		amdgpu_dm_connector->dc_em_sink;
10022 
10023 	if (!edid || !sink) {
10024 		dm_con_state = to_dm_connector_state(connector->state);
10025 
10026 		amdgpu_dm_connector->min_vfreq = 0;
10027 		amdgpu_dm_connector->max_vfreq = 0;
10028 		amdgpu_dm_connector->pixel_clock_mhz = 0;
10029 		connector->display_info.monitor_range.min_vfreq = 0;
10030 		connector->display_info.monitor_range.max_vfreq = 0;
10031 		freesync_capable = false;
10032 
10033 		goto update;
10034 	}
10035 
10036 	dm_con_state = to_dm_connector_state(connector->state);
10037 
10038 	if (!adev->dm.freesync_module)
10039 		goto update;
10040 
10041 	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10042 		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
10043 		bool edid_check_required = false;
10044 
10045 		if (edid) {
10046 			edid_check_required = is_dp_capable_without_timing_msa(
10047 						adev->dm.dc,
10048 						amdgpu_dm_connector);
10049 		}
10050 
10051 		if (edid_check_required == true && (edid->version > 1 ||
10052 		   (edid->version == 1 && edid->revision > 1))) {
10053 			for (i = 0; i < 4; i++) {
10054 
10055 				timing	= &edid->detailed_timings[i];
10056 				data	= &timing->data.other_data;
10057 				range	= &data->data.range;
10058 				/*
10059 				 * Check if monitor has continuous frequency mode
10060 				 */
10061 				if (data->type != EDID_DETAIL_MONITOR_RANGE)
10062 					continue;
10063 				/*
10064 				 * Check for flag range limits only. If flag == 1 then
10065 				 * no additional timing information provided.
10066 				 * Default GTF, GTF Secondary curve and CVT are not
10067 				 * supported
10068 				 */
10069 				if (range->flags != 1)
10070 					continue;
10071 
10072 				amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10073 				amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10074 				amdgpu_dm_connector->pixel_clock_mhz =
10075 					range->pixel_clock_mhz * 10;
10076 
10077 				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10078 				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10079 
10080 				break;
10081 			}
10082 
10083 			if (amdgpu_dm_connector->max_vfreq -
10084 			    amdgpu_dm_connector->min_vfreq > 10) {
10085 
10086 				freesync_capable = true;
10087 			}
10088 		}
10089 	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10090 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10091 		if (i >= 0 && vsdb_info.freesync_supported) {
10092 			timing  = &edid->detailed_timings[i];
10093 			data    = &timing->data.other_data;
10094 
10095 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10096 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10097 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10098 				freesync_capable = true;
10099 
10100 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10101 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10102 		}
10103 	}
10104 
10105 update:
10106 	if (dm_con_state)
10107 		dm_con_state->freesync_capable = freesync_capable;
10108 
10109 	if (connector->vrr_capable_property)
10110 		drm_connector_set_vrr_capable_property(connector,
10111 						       freesync_capable);
10112 }
10113 
10114 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10115 {
10116 	struct amdgpu_device *adev = drm_to_adev(dev);
10117 	struct dc *dc = adev->dm.dc;
10118 	int i;
10119 
10120 	mutex_lock(&adev->dm.dc_lock);
10121 	if (dc->current_state) {
10122 		for (i = 0; i < dc->current_state->stream_count; ++i)
10123 			dc->current_state->streams[i]
10124 				->triggered_crtc_reset.enabled =
10125 				adev->dm.force_timing_sync;
10126 
10127 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
10128 		dc_trigger_sync(dc, dc->current_state);
10129 	}
10130 	mutex_unlock(&adev->dm.dc_lock);
10131 }
10132 
10133 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10134 		       uint32_t value, const char *func_name)
10135 {
10136 #ifdef DM_CHECK_ADDR_0
10137 	if (address == 0) {
10138 		DC_ERR("invalid register write. address = 0");
10139 		return;
10140 	}
10141 #endif
10142 	cgs_write_register(ctx->cgs_device, address, value);
10143 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10144 }
10145 
10146 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10147 			  const char *func_name)
10148 {
10149 	uint32_t value;
10150 #ifdef DM_CHECK_ADDR_0
10151 	if (address == 0) {
10152 		DC_ERR("invalid register read; address = 0\n");
10153 		return 0;
10154 	}
10155 #endif
10156 
10157 	if (ctx->dmub_srv &&
10158 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10159 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10160 		ASSERT(false);
10161 		return 0;
10162 	}
10163 
10164 	value = cgs_read_register(ctx->cgs_device, address);
10165 
10166 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10167 
10168 	return value;
10169 }
10170 
10171 static int amdgpu_dm_set_dmub_async_sync_status(bool is_cmd_aux,
10172 						struct dc_context *ctx,
10173 						uint8_t status_type,
10174 						uint32_t *operation_result)
10175 {
10176 	struct amdgpu_device *adev = ctx->driver_context;
10177 	int return_status = -1;
10178 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
10179 
10180 	if (is_cmd_aux) {
10181 		if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS) {
10182 			return_status = p_notify->aux_reply.length;
10183 			*operation_result = p_notify->result;
10184 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_TIMEOUT) {
10185 			*operation_result = AUX_RET_ERROR_TIMEOUT;
10186 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_FAIL) {
10187 			*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10188 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_INVALID) {
10189 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10190 		} else {
10191 			*operation_result = AUX_RET_ERROR_UNKNOWN;
10192 		}
10193 	} else {
10194 		if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS) {
10195 			return_status = 0;
10196 			*operation_result = p_notify->sc_status;
10197 		} else {
10198 			*operation_result = SET_CONFIG_UNKNOWN_ERROR;
10199 		}
10200 	}
10201 
10202 	return return_status;
10203 }
10204 
10205 int amdgpu_dm_process_dmub_aux_transfer_sync(bool is_cmd_aux, struct dc_context *ctx,
10206 	unsigned int link_index, void *cmd_payload, void *operation_result)
10207 {
10208 	struct amdgpu_device *adev = ctx->driver_context;
10209 	int ret = 0;
10210 
10211 	if (is_cmd_aux) {
10212 		dc_process_dmub_aux_transfer_async(ctx->dc,
10213 			link_index, (struct aux_payload *)cmd_payload);
10214 	} else if (dc_process_dmub_set_config_async(ctx->dc, link_index,
10215 					(struct set_config_cmd_payload *)cmd_payload,
10216 					adev->dm.dmub_notify)) {
10217 		return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10218 					ctx, DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS,
10219 					(uint32_t *)operation_result);
10220 	}
10221 
10222 	ret = wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ);
10223 	if (ret == 0) {
10224 		DRM_ERROR("wait_for_completion_timeout timeout!");
10225 		return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10226 				ctx, DMUB_ASYNC_TO_SYNC_ACCESS_TIMEOUT,
10227 				(uint32_t *)operation_result);
10228 	}
10229 
10230 	if (is_cmd_aux) {
10231 		if (adev->dm.dmub_notify->result == AUX_RET_SUCCESS) {
10232 			struct aux_payload *payload = (struct aux_payload *)cmd_payload;
10233 
10234 			payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10235 			if (!payload->write && adev->dm.dmub_notify->aux_reply.length &&
10236 			    payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK) {
10237 
10238 				if (payload->length != adev->dm.dmub_notify->aux_reply.length) {
10239 					DRM_WARN("invalid read from DPIA AUX %x(%d) got length %d!\n",
10240 							payload->address, payload->length,
10241 							adev->dm.dmub_notify->aux_reply.length);
10242 					return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux, ctx,
10243 							DMUB_ASYNC_TO_SYNC_ACCESS_INVALID,
10244 							(uint32_t *)operation_result);
10245 				}
10246 
10247 				memcpy(payload->data, adev->dm.dmub_notify->aux_reply.data,
10248 				       adev->dm.dmub_notify->aux_reply.length);
10249 			}
10250 		}
10251 	}
10252 
10253 	return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10254 			ctx, DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS,
10255 			(uint32_t *)operation_result);
10256 }
10257 
10258 /*
10259  * Check whether seamless boot is supported.
10260  *
10261  * So far we only support seamless boot on CHIP_VANGOGH.
10262  * If everything goes well, we may consider expanding
10263  * seamless boot to other ASICs.
10264  */
10265 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10266 {
10267 	switch (adev->ip_versions[DCE_HWIP][0]) {
10268 	case IP_VERSION(3, 0, 1):
10269 		if (!adev->mman.keep_stolen_vga_memory)
10270 			return true;
10271 		break;
10272 	default:
10273 		break;
10274 	}
10275 
10276 	return false;
10277 }
10278