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