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