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