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