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