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