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