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