xref: /openbsd-src/sys/dev/pci/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 8dfe214903ce3625c937d5fad2469e8a0d1d4d71)
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_memory_params memory_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 	region_params.is_mailbox_in_inbox = false;
2194 
2195 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2196 					   &region_info);
2197 
2198 	if (status != DMUB_STATUS_OK) {
2199 		DRM_ERROR("Error calculating DMUB region info: %d\n", status);
2200 		return -EINVAL;
2201 	}
2202 
2203 	/*
2204 	 * Allocate a framebuffer based on the total size of all the regions.
2205 	 * TODO: Move this into GART.
2206 	 */
2207 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2208 				    AMDGPU_GEM_DOMAIN_VRAM, &adev->dm.dmub_bo,
2209 				    &adev->dm.dmub_bo_gpu_addr,
2210 				    &adev->dm.dmub_bo_cpu_addr);
2211 	if (r)
2212 		return r;
2213 
2214 	/* Rebase the regions on the framebuffer address. */
2215 	memset(&memory_params, 0, sizeof(memory_params));
2216 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2217 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2218 	memory_params.region_info = &region_info;
2219 
2220 	adev->dm.dmub_fb_info =
2221 		kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2222 	fb_info = adev->dm.dmub_fb_info;
2223 
2224 	if (!fb_info) {
2225 		DRM_ERROR(
2226 			"Failed to allocate framebuffer info for DMUB service!\n");
2227 		return -ENOMEM;
2228 	}
2229 
2230 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2231 	if (status != DMUB_STATUS_OK) {
2232 		DRM_ERROR("Error calculating DMUB FB info: %d\n", status);
2233 		return -EINVAL;
2234 	}
2235 
2236 	return 0;
2237 }
2238 
2239 static int dm_sw_init(void *handle)
2240 {
2241 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2242 	int r;
2243 
2244 	r = dm_dmub_sw_init(adev);
2245 	if (r)
2246 		return r;
2247 
2248 	return load_dmcu_fw(adev);
2249 }
2250 
2251 static int dm_sw_fini(void *handle)
2252 {
2253 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2254 
2255 	kfree(adev->dm.dmub_fb_info);
2256 	adev->dm.dmub_fb_info = NULL;
2257 
2258 	if (adev->dm.dmub_srv) {
2259 		dmub_srv_destroy(adev->dm.dmub_srv);
2260 		adev->dm.dmub_srv = NULL;
2261 	}
2262 
2263 	release_firmware(adev->dm.dmub_fw);
2264 	adev->dm.dmub_fw = NULL;
2265 
2266 	release_firmware(adev->dm.fw_dmcu);
2267 	adev->dm.fw_dmcu = NULL;
2268 
2269 	return 0;
2270 }
2271 
2272 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2273 {
2274 	struct amdgpu_dm_connector *aconnector;
2275 	struct drm_connector *connector;
2276 	struct drm_connector_list_iter iter;
2277 	int ret = 0;
2278 
2279 	drm_connector_list_iter_begin(dev, &iter);
2280 	drm_for_each_connector_iter(connector, &iter) {
2281 		aconnector = to_amdgpu_dm_connector(connector);
2282 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2283 		    aconnector->mst_mgr.aux) {
2284 			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
2285 					 aconnector,
2286 					 aconnector->base.base.id);
2287 
2288 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2289 			if (ret < 0) {
2290 				DRM_ERROR("DM_MST: Failed to start MST\n");
2291 				aconnector->dc_link->type =
2292 					dc_connection_single;
2293 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2294 								     aconnector->dc_link);
2295 				break;
2296 			}
2297 		}
2298 	}
2299 	drm_connector_list_iter_end(&iter);
2300 
2301 	return ret;
2302 }
2303 
2304 static int dm_late_init(void *handle)
2305 {
2306 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2307 
2308 	struct dmcu_iram_parameters params;
2309 	unsigned int linear_lut[16];
2310 	int i;
2311 	struct dmcu *dmcu = NULL;
2312 
2313 	dmcu = adev->dm.dc->res_pool->dmcu;
2314 
2315 	for (i = 0; i < 16; i++)
2316 		linear_lut[i] = 0xFFFF * i / 15;
2317 
2318 	params.set = 0;
2319 	params.backlight_ramping_override = false;
2320 	params.backlight_ramping_start = 0xCCCC;
2321 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2322 	params.backlight_lut_array_size = 16;
2323 	params.backlight_lut_array = linear_lut;
2324 
2325 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2326 	 * 0xFFFF x 0.01 = 0x28F
2327 	 */
2328 	params.min_abm_backlight = 0x28F;
2329 	/* In the case where abm is implemented on dmcub,
2330 	* dmcu object will be null.
2331 	* ABM 2.4 and up are implemented on dmcub.
2332 	*/
2333 	if (dmcu) {
2334 		if (!dmcu_load_iram(dmcu, params))
2335 			return -EINVAL;
2336 	} else if (adev->dm.dc->ctx->dmub_srv) {
2337 		struct dc_link *edp_links[MAX_NUM_EDP];
2338 		int edp_num;
2339 
2340 		get_edp_links(adev->dm.dc, edp_links, &edp_num);
2341 		for (i = 0; i < edp_num; i++) {
2342 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2343 				return -EINVAL;
2344 		}
2345 	}
2346 
2347 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2348 }
2349 
2350 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2351 {
2352 	int ret;
2353 	u8 guid[16];
2354 	u64 tmp64;
2355 
2356 	mutex_lock(&mgr->lock);
2357 	if (!mgr->mst_primary)
2358 		goto out_fail;
2359 
2360 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2361 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2362 		goto out_fail;
2363 	}
2364 
2365 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2366 				 DP_MST_EN |
2367 				 DP_UP_REQ_EN |
2368 				 DP_UPSTREAM_IS_SRC);
2369 	if (ret < 0) {
2370 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2371 		goto out_fail;
2372 	}
2373 
2374 	/* Some hubs forget their guids after they resume */
2375 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, guid, 16);
2376 	if (ret != 16) {
2377 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2378 		goto out_fail;
2379 	}
2380 
2381 	if (memchr_inv(guid, 0, 16) == NULL) {
2382 		tmp64 = get_jiffies_64();
2383 		memcpy(&guid[0], &tmp64, sizeof(u64));
2384 		memcpy(&guid[8], &tmp64, sizeof(u64));
2385 
2386 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, guid, 16);
2387 
2388 		if (ret != 16) {
2389 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2390 			goto out_fail;
2391 		}
2392 	}
2393 
2394 	memcpy(mgr->mst_primary->guid, guid, 16);
2395 
2396 out_fail:
2397 	mutex_unlock(&mgr->lock);
2398 }
2399 
2400 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2401 {
2402 	struct amdgpu_dm_connector *aconnector;
2403 	struct drm_connector *connector;
2404 	struct drm_connector_list_iter iter;
2405 	struct drm_dp_mst_topology_mgr *mgr;
2406 
2407 	drm_connector_list_iter_begin(dev, &iter);
2408 	drm_for_each_connector_iter(connector, &iter) {
2409 		aconnector = to_amdgpu_dm_connector(connector);
2410 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2411 		    aconnector->mst_port)
2412 			continue;
2413 
2414 		mgr = &aconnector->mst_mgr;
2415 
2416 		if (suspend) {
2417 			drm_dp_mst_topology_mgr_suspend(mgr);
2418 		} else {
2419 			/* if extended timeout is supported in hardware,
2420 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2421 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2422 			 */
2423 			dc_link_aux_try_to_configure_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2424 			if (!dp_is_lttpr_present(aconnector->dc_link))
2425 				dc_link_aux_try_to_configure_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2426 
2427 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2428 			 * once topology probing work is pulled out from mst resume into mst
2429 			 * resume 2nd step. mst resume 2nd step should be called after old
2430 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2431 			 */
2432 			resume_mst_branch_status(mgr);
2433 		}
2434 	}
2435 	drm_connector_list_iter_end(&iter);
2436 }
2437 
2438 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2439 {
2440 	int ret = 0;
2441 
2442 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2443 	 * on window driver dc implementation.
2444 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2445 	 * should be passed to smu during boot up and resume from s3.
2446 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2447 	 * dcn20_resource_construct
2448 	 * then call pplib functions below to pass the settings to smu:
2449 	 * smu_set_watermarks_for_clock_ranges
2450 	 * smu_set_watermarks_table
2451 	 * navi10_set_watermarks_table
2452 	 * smu_write_watermarks_table
2453 	 *
2454 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2455 	 * dc has implemented different flow for window driver:
2456 	 * dc_hardware_init / dc_set_power_state
2457 	 * dcn10_init_hw
2458 	 * notify_wm_ranges
2459 	 * set_wm_ranges
2460 	 * -- Linux
2461 	 * smu_set_watermarks_for_clock_ranges
2462 	 * renoir_set_watermarks_table
2463 	 * smu_write_watermarks_table
2464 	 *
2465 	 * For Linux,
2466 	 * dc_hardware_init -> amdgpu_dm_init
2467 	 * dc_set_power_state --> dm_resume
2468 	 *
2469 	 * therefore, this function apply to navi10/12/14 but not Renoir
2470 	 * *
2471 	 */
2472 	switch (adev->ip_versions[DCE_HWIP][0]) {
2473 	case IP_VERSION(2, 0, 2):
2474 	case IP_VERSION(2, 0, 0):
2475 		break;
2476 	default:
2477 		return 0;
2478 	}
2479 
2480 	ret = amdgpu_dpm_write_watermarks_table(adev);
2481 	if (ret) {
2482 		DRM_ERROR("Failed to update WMTABLE!\n");
2483 		return ret;
2484 	}
2485 
2486 	return 0;
2487 }
2488 
2489 /**
2490  * dm_hw_init() - Initialize DC device
2491  * @handle: The base driver device containing the amdgpu_dm device.
2492  *
2493  * Initialize the &struct amdgpu_display_manager device. This involves calling
2494  * the initializers of each DM component, then populating the struct with them.
2495  *
2496  * Although the function implies hardware initialization, both hardware and
2497  * software are initialized here. Splitting them out to their relevant init
2498  * hooks is a future TODO item.
2499  *
2500  * Some notable things that are initialized here:
2501  *
2502  * - Display Core, both software and hardware
2503  * - DC modules that we need (freesync and color management)
2504  * - DRM software states
2505  * - Interrupt sources and handlers
2506  * - Vblank support
2507  * - Debug FS entries, if enabled
2508  */
2509 static int dm_hw_init(void *handle)
2510 {
2511 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2512 	/* Create DAL display manager */
2513 	amdgpu_dm_init(adev);
2514 	amdgpu_dm_hpd_init(adev);
2515 
2516 	return 0;
2517 }
2518 
2519 /**
2520  * dm_hw_fini() - Teardown DC device
2521  * @handle: The base driver device containing the amdgpu_dm device.
2522  *
2523  * Teardown components within &struct amdgpu_display_manager that require
2524  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
2525  * were loaded. Also flush IRQ workqueues and disable them.
2526  */
2527 static int dm_hw_fini(void *handle)
2528 {
2529 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2530 
2531 	amdgpu_dm_hpd_fini(adev);
2532 
2533 	amdgpu_dm_irq_fini(adev);
2534 	amdgpu_dm_fini(adev);
2535 	return 0;
2536 }
2537 
2538 
2539 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
2540 				 struct dc_state *state, bool enable)
2541 {
2542 	enum dc_irq_source irq_source;
2543 	struct amdgpu_crtc *acrtc;
2544 	int rc = -EBUSY;
2545 	int i = 0;
2546 
2547 	for (i = 0; i < state->stream_count; i++) {
2548 		acrtc = get_crtc_by_otg_inst(
2549 				adev, state->stream_status[i].primary_otg_inst);
2550 
2551 		if (acrtc && state->stream_status[i].plane_count != 0) {
2552 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
2553 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2554 			DRM_DEBUG_VBL("crtc %d - vupdate irq %sabling: r=%d\n",
2555 				      acrtc->crtc_id, enable ? "en" : "dis", rc);
2556 			if (rc)
2557 				DRM_WARN("Failed to %s pflip interrupts\n",
2558 					 enable ? "enable" : "disable");
2559 
2560 			if (enable) {
2561 				rc = dm_enable_vblank(&acrtc->base);
2562 				if (rc)
2563 					DRM_WARN("Failed to enable vblank interrupts\n");
2564 			} else {
2565 				dm_disable_vblank(&acrtc->base);
2566 			}
2567 
2568 		}
2569 	}
2570 
2571 }
2572 
2573 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
2574 {
2575 	struct dc_state *context = NULL;
2576 	enum dc_status res = DC_ERROR_UNEXPECTED;
2577 	int i;
2578 	struct dc_stream_state *del_streams[MAX_PIPES];
2579 	int del_streams_count = 0;
2580 
2581 	memset(del_streams, 0, sizeof(del_streams));
2582 
2583 	context = dc_create_state(dc);
2584 	if (context == NULL)
2585 		goto context_alloc_fail;
2586 
2587 	dc_resource_state_copy_construct_current(dc, context);
2588 
2589 	/* First remove from context all streams */
2590 	for (i = 0; i < context->stream_count; i++) {
2591 		struct dc_stream_state *stream = context->streams[i];
2592 
2593 		del_streams[del_streams_count++] = stream;
2594 	}
2595 
2596 	/* Remove all planes for removed streams and then remove the streams */
2597 	for (i = 0; i < del_streams_count; i++) {
2598 		if (!dc_rem_all_planes_for_stream(dc, del_streams[i], context)) {
2599 			res = DC_FAIL_DETACH_SURFACES;
2600 			goto fail;
2601 		}
2602 
2603 		res = dc_remove_stream_from_ctx(dc, context, del_streams[i]);
2604 		if (res != DC_OK)
2605 			goto fail;
2606 	}
2607 
2608 	res = dc_commit_state(dc, context);
2609 
2610 fail:
2611 	dc_release_state(context);
2612 
2613 context_alloc_fail:
2614 	return res;
2615 }
2616 
2617 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
2618 {
2619 	int i;
2620 
2621 	if (dm->hpd_rx_offload_wq) {
2622 		for (i = 0; i < dm->dc->caps.max_links; i++)
2623 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
2624 	}
2625 }
2626 
2627 static int dm_suspend(void *handle)
2628 {
2629 	struct amdgpu_device *adev = handle;
2630 	struct amdgpu_display_manager *dm = &adev->dm;
2631 	int ret = 0;
2632 
2633 	if (amdgpu_in_reset(adev)) {
2634 		mutex_lock(&dm->dc_lock);
2635 
2636 		dc_allow_idle_optimizations(adev->dm.dc, false);
2637 
2638 		dm->cached_dc_state = dc_copy_state(dm->dc->current_state);
2639 
2640 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
2641 
2642 		amdgpu_dm_commit_zero_streams(dm->dc);
2643 
2644 		amdgpu_dm_irq_suspend(adev);
2645 
2646 		hpd_rx_irq_work_suspend(dm);
2647 
2648 		return ret;
2649 	}
2650 
2651 	WARN_ON(adev->dm.cached_state);
2652 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
2653 
2654 	s3_handle_mst(adev_to_drm(adev), true);
2655 
2656 	amdgpu_dm_irq_suspend(adev);
2657 
2658 	hpd_rx_irq_work_suspend(dm);
2659 
2660 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
2661 
2662 	return 0;
2663 }
2664 
2665 struct amdgpu_dm_connector *
2666 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
2667 					     struct drm_crtc *crtc)
2668 {
2669 	u32 i;
2670 	struct drm_connector_state *new_con_state;
2671 	struct drm_connector *connector;
2672 	struct drm_crtc *crtc_from_state;
2673 
2674 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
2675 		crtc_from_state = new_con_state->crtc;
2676 
2677 		if (crtc_from_state == crtc)
2678 			return to_amdgpu_dm_connector(connector);
2679 	}
2680 
2681 	return NULL;
2682 }
2683 
2684 static void emulated_link_detect(struct dc_link *link)
2685 {
2686 	struct dc_sink_init_data sink_init_data = { 0 };
2687 	struct display_sink_capability sink_caps = { 0 };
2688 	enum dc_edid_status edid_status;
2689 	struct dc_context *dc_ctx = link->ctx;
2690 	struct dc_sink *sink = NULL;
2691 	struct dc_sink *prev_sink = NULL;
2692 
2693 	link->type = dc_connection_none;
2694 	prev_sink = link->local_sink;
2695 
2696 	if (prev_sink)
2697 		dc_sink_release(prev_sink);
2698 
2699 	switch (link->connector_signal) {
2700 	case SIGNAL_TYPE_HDMI_TYPE_A: {
2701 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2702 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
2703 		break;
2704 	}
2705 
2706 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
2707 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2708 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
2709 		break;
2710 	}
2711 
2712 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
2713 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2714 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
2715 		break;
2716 	}
2717 
2718 	case SIGNAL_TYPE_LVDS: {
2719 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2720 		sink_caps.signal = SIGNAL_TYPE_LVDS;
2721 		break;
2722 	}
2723 
2724 	case SIGNAL_TYPE_EDP: {
2725 		sink_caps.transaction_type =
2726 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2727 		sink_caps.signal = SIGNAL_TYPE_EDP;
2728 		break;
2729 	}
2730 
2731 	case SIGNAL_TYPE_DISPLAY_PORT: {
2732 		sink_caps.transaction_type =
2733 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2734 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
2735 		break;
2736 	}
2737 
2738 	default:
2739 		DC_ERROR("Invalid connector type! signal:%d\n",
2740 			link->connector_signal);
2741 		return;
2742 	}
2743 
2744 	sink_init_data.link = link;
2745 	sink_init_data.sink_signal = sink_caps.signal;
2746 
2747 	sink = dc_sink_create(&sink_init_data);
2748 	if (!sink) {
2749 		DC_ERROR("Failed to create sink!\n");
2750 		return;
2751 	}
2752 
2753 	/* dc_sink_create returns a new reference */
2754 	link->local_sink = sink;
2755 
2756 	edid_status = dm_helpers_read_local_edid(
2757 			link->ctx,
2758 			link,
2759 			sink);
2760 
2761 	if (edid_status != EDID_OK)
2762 		DC_ERROR("Failed to read EDID");
2763 
2764 }
2765 
2766 static void dm_gpureset_commit_state(struct dc_state *dc_state,
2767 				     struct amdgpu_display_manager *dm)
2768 {
2769 	struct {
2770 		struct dc_surface_update surface_updates[MAX_SURFACES];
2771 		struct dc_plane_info plane_infos[MAX_SURFACES];
2772 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
2773 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
2774 		struct dc_stream_update stream_update;
2775 	} *bundle;
2776 	int k, m;
2777 
2778 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
2779 
2780 	if (!bundle) {
2781 		dm_error("Failed to allocate update bundle\n");
2782 		goto cleanup;
2783 	}
2784 
2785 	for (k = 0; k < dc_state->stream_count; k++) {
2786 		bundle->stream_update.stream = dc_state->streams[k];
2787 
2788 		for (m = 0; m < dc_state->stream_status->plane_count; m++) {
2789 			bundle->surface_updates[m].surface =
2790 				dc_state->stream_status->plane_states[m];
2791 			bundle->surface_updates[m].surface->force_full_update =
2792 				true;
2793 		}
2794 
2795 		update_planes_and_stream_adapter(dm->dc,
2796 					 UPDATE_TYPE_FULL,
2797 					 dc_state->stream_status->plane_count,
2798 					 dc_state->streams[k],
2799 					 &bundle->stream_update,
2800 					 bundle->surface_updates);
2801 	}
2802 
2803 cleanup:
2804 	kfree(bundle);
2805 }
2806 
2807 static int dm_resume(void *handle)
2808 {
2809 	struct amdgpu_device *adev = handle;
2810 	struct drm_device *ddev = adev_to_drm(adev);
2811 	struct amdgpu_display_manager *dm = &adev->dm;
2812 	struct amdgpu_dm_connector *aconnector;
2813 	struct drm_connector *connector;
2814 	struct drm_connector_list_iter iter;
2815 	struct drm_crtc *crtc;
2816 	struct drm_crtc_state *new_crtc_state;
2817 	struct dm_crtc_state *dm_new_crtc_state;
2818 	struct drm_plane *plane;
2819 	struct drm_plane_state *new_plane_state;
2820 	struct dm_plane_state *dm_new_plane_state;
2821 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
2822 	enum dc_connection_type new_connection_type = dc_connection_none;
2823 	struct dc_state *dc_state;
2824 	int i, r, j, ret;
2825 	bool need_hotplug = false;
2826 
2827 	if (amdgpu_in_reset(adev)) {
2828 		dc_state = dm->cached_dc_state;
2829 
2830 		/*
2831 		 * The dc->current_state is backed up into dm->cached_dc_state
2832 		 * before we commit 0 streams.
2833 		 *
2834 		 * DC will clear link encoder assignments on the real state
2835 		 * but the changes won't propagate over to the copy we made
2836 		 * before the 0 streams commit.
2837 		 *
2838 		 * DC expects that link encoder assignments are *not* valid
2839 		 * when committing a state, so as a workaround we can copy
2840 		 * off of the current state.
2841 		 *
2842 		 * We lose the previous assignments, but we had already
2843 		 * commit 0 streams anyway.
2844 		 */
2845 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
2846 
2847 		r = dm_dmub_hw_init(adev);
2848 		if (r)
2849 			DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
2850 
2851 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2852 		dc_resume(dm->dc);
2853 
2854 		amdgpu_dm_irq_resume_early(adev);
2855 
2856 		for (i = 0; i < dc_state->stream_count; i++) {
2857 			dc_state->streams[i]->mode_changed = true;
2858 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
2859 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
2860 					= 0xffffffff;
2861 			}
2862 		}
2863 
2864 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2865 			amdgpu_dm_outbox_init(adev);
2866 			dc_enable_dmub_outbox(adev->dm.dc);
2867 		}
2868 
2869 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
2870 
2871 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
2872 
2873 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
2874 
2875 		dc_release_state(dm->cached_dc_state);
2876 		dm->cached_dc_state = NULL;
2877 
2878 		amdgpu_dm_irq_resume_late(adev);
2879 
2880 		mutex_unlock(&dm->dc_lock);
2881 
2882 		return 0;
2883 	}
2884 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
2885 	dc_release_state(dm_state->context);
2886 	dm_state->context = dc_create_state(dm->dc);
2887 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
2888 	dc_resource_state_construct(dm->dc, dm_state->context);
2889 
2890 	/* Before powering on DC we need to re-initialize DMUB. */
2891 	dm_dmub_hw_resume(adev);
2892 
2893 	/* Re-enable outbox interrupts for DPIA. */
2894 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2895 		amdgpu_dm_outbox_init(adev);
2896 		dc_enable_dmub_outbox(adev->dm.dc);
2897 	}
2898 
2899 	/* power on hardware */
2900 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2901 
2902 	/* program HPD filter */
2903 	dc_resume(dm->dc);
2904 
2905 	/*
2906 	 * early enable HPD Rx IRQ, should be done before set mode as short
2907 	 * pulse interrupts are used for MST
2908 	 */
2909 	amdgpu_dm_irq_resume_early(adev);
2910 
2911 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
2912 	s3_handle_mst(ddev, false);
2913 
2914 	/* Do detection*/
2915 	drm_connector_list_iter_begin(ddev, &iter);
2916 	drm_for_each_connector_iter(connector, &iter) {
2917 		aconnector = to_amdgpu_dm_connector(connector);
2918 
2919 		if (!aconnector->dc_link)
2920 			continue;
2921 
2922 		/*
2923 		 * this is the case when traversing through already created end sink
2924 		 * MST connectors, should be skipped
2925 		 */
2926 		if (aconnector && aconnector->mst_port)
2927 			continue;
2928 
2929 		mutex_lock(&aconnector->hpd_lock);
2930 		if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
2931 			DRM_ERROR("KMS: Failed to detect connector\n");
2932 
2933 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2934 			emulated_link_detect(aconnector->dc_link);
2935 		} else {
2936 			mutex_lock(&dm->dc_lock);
2937 			dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
2938 			mutex_unlock(&dm->dc_lock);
2939 		}
2940 
2941 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2942 			aconnector->fake_enable = false;
2943 
2944 		if (aconnector->dc_sink)
2945 			dc_sink_release(aconnector->dc_sink);
2946 		aconnector->dc_sink = NULL;
2947 		amdgpu_dm_update_connector_after_detect(aconnector);
2948 		mutex_unlock(&aconnector->hpd_lock);
2949 	}
2950 	drm_connector_list_iter_end(&iter);
2951 
2952 	/* Force mode set in atomic commit */
2953 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
2954 		new_crtc_state->active_changed = true;
2955 
2956 	/*
2957 	 * atomic_check is expected to create the dc states. We need to release
2958 	 * them here, since they were duplicated as part of the suspend
2959 	 * procedure.
2960 	 */
2961 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
2962 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
2963 		if (dm_new_crtc_state->stream) {
2964 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
2965 			dc_stream_release(dm_new_crtc_state->stream);
2966 			dm_new_crtc_state->stream = NULL;
2967 		}
2968 	}
2969 
2970 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
2971 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
2972 		if (dm_new_plane_state->dc_state) {
2973 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
2974 			dc_plane_state_release(dm_new_plane_state->dc_state);
2975 			dm_new_plane_state->dc_state = NULL;
2976 		}
2977 	}
2978 
2979 	drm_atomic_helper_resume(ddev, dm->cached_state);
2980 
2981 	dm->cached_state = NULL;
2982 
2983 	/* Do mst topology probing after resuming cached state*/
2984 	drm_connector_list_iter_begin(ddev, &iter);
2985 	drm_for_each_connector_iter(connector, &iter) {
2986 		aconnector = to_amdgpu_dm_connector(connector);
2987 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2988 		    aconnector->mst_port)
2989 			continue;
2990 
2991 		ret = drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr, true);
2992 
2993 		if (ret < 0) {
2994 			dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2995 					aconnector->dc_link);
2996 			need_hotplug = true;
2997 		}
2998 	}
2999 	drm_connector_list_iter_end(&iter);
3000 
3001 	if (need_hotplug)
3002 		drm_kms_helper_hotplug_event(ddev);
3003 
3004 	amdgpu_dm_irq_resume_late(adev);
3005 
3006 	amdgpu_dm_smu_write_watermarks_table(adev);
3007 
3008 	return 0;
3009 }
3010 
3011 /**
3012  * DOC: DM Lifecycle
3013  *
3014  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3015  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3016  * the base driver's device list to be initialized and torn down accordingly.
3017  *
3018  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3019  */
3020 
3021 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3022 	.name = "dm",
3023 	.early_init = dm_early_init,
3024 	.late_init = dm_late_init,
3025 	.sw_init = dm_sw_init,
3026 	.sw_fini = dm_sw_fini,
3027 	.early_fini = amdgpu_dm_early_fini,
3028 	.hw_init = dm_hw_init,
3029 	.hw_fini = dm_hw_fini,
3030 	.suspend = dm_suspend,
3031 	.resume = dm_resume,
3032 	.is_idle = dm_is_idle,
3033 	.wait_for_idle = dm_wait_for_idle,
3034 	.check_soft_reset = dm_check_soft_reset,
3035 	.soft_reset = dm_soft_reset,
3036 	.set_clockgating_state = dm_set_clockgating_state,
3037 	.set_powergating_state = dm_set_powergating_state,
3038 };
3039 
3040 const struct amdgpu_ip_block_version dm_ip_block = {
3041 	.type = AMD_IP_BLOCK_TYPE_DCE,
3042 	.major = 1,
3043 	.minor = 0,
3044 	.rev = 0,
3045 	.funcs = &amdgpu_dm_funcs,
3046 };
3047 
3048 
3049 /**
3050  * DOC: atomic
3051  *
3052  * *WIP*
3053  */
3054 
3055 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3056 	.fb_create = amdgpu_display_user_framebuffer_create,
3057 	.get_format_info = amd_get_format_info,
3058 	.atomic_check = amdgpu_dm_atomic_check,
3059 	.atomic_commit = drm_atomic_helper_commit,
3060 };
3061 
3062 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3063 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3064 	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
3065 };
3066 
3067 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3068 {
3069 	struct amdgpu_dm_backlight_caps *caps;
3070 	struct amdgpu_display_manager *dm;
3071 	struct drm_connector *conn_base;
3072 	struct amdgpu_device *adev;
3073 	struct dc_link *link = NULL;
3074 	struct drm_luminance_range_info *luminance_range;
3075 	int i;
3076 
3077 	if (!aconnector || !aconnector->dc_link)
3078 		return;
3079 
3080 	link = aconnector->dc_link;
3081 	if (link->connector_signal != SIGNAL_TYPE_EDP)
3082 		return;
3083 
3084 	conn_base = &aconnector->base;
3085 	adev = drm_to_adev(conn_base->dev);
3086 	dm = &adev->dm;
3087 	for (i = 0; i < dm->num_of_edps; i++) {
3088 		if (link == dm->backlight_link[i])
3089 			break;
3090 	}
3091 	if (i >= dm->num_of_edps)
3092 		return;
3093 	caps = &dm->backlight_caps[i];
3094 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3095 	caps->aux_support = false;
3096 
3097 	if (caps->ext_caps->bits.oled == 1
3098 	    /*
3099 	     * ||
3100 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3101 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3102 	     */)
3103 		caps->aux_support = true;
3104 
3105 	if (amdgpu_backlight == 0)
3106 		caps->aux_support = false;
3107 	else if (amdgpu_backlight == 1)
3108 		caps->aux_support = true;
3109 
3110 	luminance_range = &conn_base->display_info.luminance_range;
3111 	caps->aux_min_input_signal = luminance_range->min_luminance;
3112 	caps->aux_max_input_signal = luminance_range->max_luminance;
3113 }
3114 
3115 void amdgpu_dm_update_connector_after_detect(
3116 		struct amdgpu_dm_connector *aconnector)
3117 {
3118 	struct drm_connector *connector = &aconnector->base;
3119 	struct drm_device *dev = connector->dev;
3120 	struct dc_sink *sink;
3121 
3122 	/* MST handled by drm_mst framework */
3123 	if (aconnector->mst_mgr.mst_state == true)
3124 		return;
3125 
3126 	sink = aconnector->dc_link->local_sink;
3127 	if (sink)
3128 		dc_sink_retain(sink);
3129 
3130 	/*
3131 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3132 	 * the connector sink is set to either fake or physical sink depends on link status.
3133 	 * Skip if already done during boot.
3134 	 */
3135 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3136 			&& aconnector->dc_em_sink) {
3137 
3138 		/*
3139 		 * For S3 resume with headless use eml_sink to fake stream
3140 		 * because on resume connector->sink is set to NULL
3141 		 */
3142 		mutex_lock(&dev->mode_config.mutex);
3143 
3144 		if (sink) {
3145 			if (aconnector->dc_sink) {
3146 				amdgpu_dm_update_freesync_caps(connector, NULL);
3147 				/*
3148 				 * retain and release below are used to
3149 				 * bump up refcount for sink because the link doesn't point
3150 				 * to it anymore after disconnect, so on next crtc to connector
3151 				 * reshuffle by UMD we will get into unwanted dc_sink release
3152 				 */
3153 				dc_sink_release(aconnector->dc_sink);
3154 			}
3155 			aconnector->dc_sink = sink;
3156 			dc_sink_retain(aconnector->dc_sink);
3157 			amdgpu_dm_update_freesync_caps(connector,
3158 					aconnector->edid);
3159 		} else {
3160 			amdgpu_dm_update_freesync_caps(connector, NULL);
3161 			if (!aconnector->dc_sink) {
3162 				aconnector->dc_sink = aconnector->dc_em_sink;
3163 				dc_sink_retain(aconnector->dc_sink);
3164 			}
3165 		}
3166 
3167 		mutex_unlock(&dev->mode_config.mutex);
3168 
3169 		if (sink)
3170 			dc_sink_release(sink);
3171 		return;
3172 	}
3173 
3174 	/*
3175 	 * TODO: temporary guard to look for proper fix
3176 	 * if this sink is MST sink, we should not do anything
3177 	 */
3178 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
3179 		dc_sink_release(sink);
3180 		return;
3181 	}
3182 
3183 	if (aconnector->dc_sink == sink) {
3184 		/*
3185 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3186 		 * Do nothing!!
3187 		 */
3188 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
3189 				aconnector->connector_id);
3190 		if (sink)
3191 			dc_sink_release(sink);
3192 		return;
3193 	}
3194 
3195 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3196 		aconnector->connector_id, aconnector->dc_sink, sink);
3197 
3198 	mutex_lock(&dev->mode_config.mutex);
3199 
3200 	/*
3201 	 * 1. Update status of the drm connector
3202 	 * 2. Send an event and let userspace tell us what to do
3203 	 */
3204 	if (sink) {
3205 		/*
3206 		 * TODO: check if we still need the S3 mode update workaround.
3207 		 * If yes, put it here.
3208 		 */
3209 		if (aconnector->dc_sink) {
3210 			amdgpu_dm_update_freesync_caps(connector, NULL);
3211 			dc_sink_release(aconnector->dc_sink);
3212 		}
3213 
3214 		aconnector->dc_sink = sink;
3215 		dc_sink_retain(aconnector->dc_sink);
3216 		if (sink->dc_edid.length == 0) {
3217 			aconnector->edid = NULL;
3218 			if (aconnector->dc_link->aux_mode) {
3219 				drm_dp_cec_unset_edid(
3220 					&aconnector->dm_dp_aux.aux);
3221 			}
3222 		} else {
3223 			aconnector->edid =
3224 				(struct edid *)sink->dc_edid.raw_edid;
3225 
3226 			if (aconnector->dc_link->aux_mode)
3227 				drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
3228 						    aconnector->edid);
3229 		}
3230 
3231 		aconnector->timing_requested = kzalloc(sizeof(struct dc_crtc_timing), GFP_KERNEL);
3232 		if (!aconnector->timing_requested)
3233 			dm_error("%s: failed to create aconnector->requested_timing\n", __func__);
3234 
3235 		drm_connector_update_edid_property(connector, aconnector->edid);
3236 		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
3237 		update_connector_ext_caps(aconnector);
3238 	} else {
3239 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3240 		amdgpu_dm_update_freesync_caps(connector, NULL);
3241 		drm_connector_update_edid_property(connector, NULL);
3242 		aconnector->num_modes = 0;
3243 		dc_sink_release(aconnector->dc_sink);
3244 		aconnector->dc_sink = NULL;
3245 		aconnector->edid = NULL;
3246 		kfree(aconnector->timing_requested);
3247 		aconnector->timing_requested = NULL;
3248 #ifdef CONFIG_DRM_AMD_DC_HDCP
3249 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3250 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3251 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3252 #endif
3253 	}
3254 
3255 	mutex_unlock(&dev->mode_config.mutex);
3256 
3257 	update_subconnector_property(aconnector);
3258 
3259 	if (sink)
3260 		dc_sink_release(sink);
3261 }
3262 
3263 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3264 {
3265 	struct drm_connector *connector = &aconnector->base;
3266 	struct drm_device *dev = connector->dev;
3267 	enum dc_connection_type new_connection_type = dc_connection_none;
3268 	struct amdgpu_device *adev = drm_to_adev(dev);
3269 #ifdef CONFIG_DRM_AMD_DC_HDCP
3270 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3271 #endif
3272 	bool ret = false;
3273 
3274 	if (adev->dm.disable_hpd_irq)
3275 		return;
3276 
3277 	/*
3278 	 * In case of failure or MST no need to update connector status or notify the OS
3279 	 * since (for MST case) MST does this in its own context.
3280 	 */
3281 	mutex_lock(&aconnector->hpd_lock);
3282 
3283 #ifdef CONFIG_DRM_AMD_DC_HDCP
3284 	if (adev->dm.hdcp_workqueue) {
3285 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3286 		dm_con_state->update_hdcp = true;
3287 	}
3288 #endif
3289 	if (aconnector->fake_enable)
3290 		aconnector->fake_enable = false;
3291 
3292 	aconnector->timing_changed = false;
3293 
3294 	if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
3295 		DRM_ERROR("KMS: Failed to detect connector\n");
3296 
3297 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
3298 		emulated_link_detect(aconnector->dc_link);
3299 
3300 		drm_modeset_lock_all(dev);
3301 		dm_restore_drm_connector_state(dev, connector);
3302 		drm_modeset_unlock_all(dev);
3303 
3304 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3305 			drm_kms_helper_connector_hotplug_event(connector);
3306 	} else {
3307 		mutex_lock(&adev->dm.dc_lock);
3308 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3309 		mutex_unlock(&adev->dm.dc_lock);
3310 		if (ret) {
3311 			amdgpu_dm_update_connector_after_detect(aconnector);
3312 
3313 			drm_modeset_lock_all(dev);
3314 			dm_restore_drm_connector_state(dev, connector);
3315 			drm_modeset_unlock_all(dev);
3316 
3317 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3318 				drm_kms_helper_connector_hotplug_event(connector);
3319 		}
3320 	}
3321 	mutex_unlock(&aconnector->hpd_lock);
3322 
3323 }
3324 
3325 static void handle_hpd_irq(void *param)
3326 {
3327 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3328 
3329 	handle_hpd_irq_helper(aconnector);
3330 
3331 }
3332 
3333 static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
3334 							union hpd_irq_data hpd_irq_data)
3335 {
3336 	struct hpd_rx_irq_offload_work *offload_work =
3337 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
3338 
3339 	if (!offload_work) {
3340 		DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
3341 		return;
3342 	}
3343 
3344 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3345 	offload_work->data = hpd_irq_data;
3346 	offload_work->offload_wq = offload_wq;
3347 
3348 	queue_work(offload_wq->wq, &offload_work->work);
3349 	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3350 }
3351 
3352 static void handle_hpd_rx_irq(void *param)
3353 {
3354 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3355 	struct drm_connector *connector = &aconnector->base;
3356 	struct drm_device *dev = connector->dev;
3357 	struct dc_link *dc_link = aconnector->dc_link;
3358 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3359 	bool result = false;
3360 	enum dc_connection_type new_connection_type = dc_connection_none;
3361 	struct amdgpu_device *adev = drm_to_adev(dev);
3362 	union hpd_irq_data hpd_irq_data;
3363 	bool link_loss = false;
3364 	bool has_left_work = false;
3365 	int idx = dc_link->link_index;
3366 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3367 
3368 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3369 
3370 	if (adev->dm.disable_hpd_irq)
3371 		return;
3372 
3373 	/*
3374 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3375 	 * conflict, after implement i2c helper, this mutex should be
3376 	 * retired.
3377 	 */
3378 	mutex_lock(&aconnector->hpd_lock);
3379 
3380 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3381 						&link_loss, true, &has_left_work);
3382 
3383 	if (!has_left_work)
3384 		goto out;
3385 
3386 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3387 		schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3388 		goto out;
3389 	}
3390 
3391 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3392 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3393 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3394 			bool skip = false;
3395 
3396 			/*
3397 			 * DOWN_REP_MSG_RDY is also handled by polling method
3398 			 * mgr->cbs->poll_hpd_irq()
3399 			 */
3400 			spin_lock(&offload_wq->offload_lock);
3401 			skip = offload_wq->is_handling_mst_msg_rdy_event;
3402 
3403 			if (!skip)
3404 				offload_wq->is_handling_mst_msg_rdy_event = true;
3405 
3406 			spin_unlock(&offload_wq->offload_lock);
3407 
3408 			if (!skip)
3409 				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3410 
3411 			goto out;
3412 		}
3413 
3414 		if (link_loss) {
3415 			bool skip = false;
3416 
3417 			spin_lock(&offload_wq->offload_lock);
3418 			skip = offload_wq->is_handling_link_loss;
3419 
3420 			if (!skip)
3421 				offload_wq->is_handling_link_loss = true;
3422 
3423 			spin_unlock(&offload_wq->offload_lock);
3424 
3425 			if (!skip)
3426 				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3427 
3428 			goto out;
3429 		}
3430 	}
3431 
3432 out:
3433 	if (result && !is_mst_root_connector) {
3434 		/* Downstream Port status changed. */
3435 		if (!dc_link_detect_sink(dc_link, &new_connection_type))
3436 			DRM_ERROR("KMS: Failed to detect connector\n");
3437 
3438 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3439 			emulated_link_detect(dc_link);
3440 
3441 			if (aconnector->fake_enable)
3442 				aconnector->fake_enable = false;
3443 
3444 			amdgpu_dm_update_connector_after_detect(aconnector);
3445 
3446 
3447 			drm_modeset_lock_all(dev);
3448 			dm_restore_drm_connector_state(dev, connector);
3449 			drm_modeset_unlock_all(dev);
3450 
3451 			drm_kms_helper_connector_hotplug_event(connector);
3452 		} else {
3453 			bool ret = false;
3454 
3455 			mutex_lock(&adev->dm.dc_lock);
3456 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
3457 			mutex_unlock(&adev->dm.dc_lock);
3458 
3459 			if (ret) {
3460 				if (aconnector->fake_enable)
3461 					aconnector->fake_enable = false;
3462 
3463 				amdgpu_dm_update_connector_after_detect(aconnector);
3464 
3465 				drm_modeset_lock_all(dev);
3466 				dm_restore_drm_connector_state(dev, connector);
3467 				drm_modeset_unlock_all(dev);
3468 
3469 				drm_kms_helper_connector_hotplug_event(connector);
3470 			}
3471 		}
3472 	}
3473 #ifdef CONFIG_DRM_AMD_DC_HDCP
3474 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
3475 		if (adev->dm.hdcp_workqueue)
3476 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
3477 	}
3478 #endif
3479 
3480 	if (dc_link->type != dc_connection_mst_branch)
3481 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
3482 
3483 	mutex_unlock(&aconnector->hpd_lock);
3484 }
3485 
3486 static void register_hpd_handlers(struct amdgpu_device *adev)
3487 {
3488 	struct drm_device *dev = adev_to_drm(adev);
3489 	struct drm_connector *connector;
3490 	struct amdgpu_dm_connector *aconnector;
3491 	const struct dc_link *dc_link;
3492 	struct dc_interrupt_params int_params = {0};
3493 
3494 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3495 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3496 
3497 	list_for_each_entry(connector,
3498 			&dev->mode_config.connector_list, head)	{
3499 
3500 		aconnector = to_amdgpu_dm_connector(connector);
3501 		dc_link = aconnector->dc_link;
3502 
3503 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
3504 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3505 			int_params.irq_source = dc_link->irq_source_hpd;
3506 
3507 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3508 					handle_hpd_irq,
3509 					(void *) aconnector);
3510 		}
3511 
3512 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
3513 
3514 			/* Also register for DP short pulse (hpd_rx). */
3515 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3516 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
3517 
3518 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3519 					handle_hpd_rx_irq,
3520 					(void *) aconnector);
3521 		}
3522 
3523 		if (adev->dm.hpd_rx_offload_wq)
3524 			adev->dm.hpd_rx_offload_wq[connector->index].aconnector =
3525 				aconnector;
3526 	}
3527 }
3528 
3529 #if defined(CONFIG_DRM_AMD_DC_SI)
3530 /* Register IRQ sources and initialize IRQ callbacks */
3531 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
3532 {
3533 	struct dc *dc = adev->dm.dc;
3534 	struct common_irq_params *c_irq_params;
3535 	struct dc_interrupt_params int_params = {0};
3536 	int r;
3537 	int i;
3538 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3539 
3540 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3541 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3542 
3543 	/*
3544 	 * Actions of amdgpu_irq_add_id():
3545 	 * 1. Register a set() function with base driver.
3546 	 *    Base driver will call set() function to enable/disable an
3547 	 *    interrupt in DC hardware.
3548 	 * 2. Register amdgpu_dm_irq_handler().
3549 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3550 	 *    coming from DC hardware.
3551 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3552 	 *    for acknowledging and handling.
3553 	 */
3554 
3555 	/* Use VBLANK interrupt */
3556 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
3557 		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
3558 		if (r) {
3559 			DRM_ERROR("Failed to add crtc irq id!\n");
3560 			return r;
3561 		}
3562 
3563 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3564 		int_params.irq_source =
3565 			dc_interrupt_to_irq_source(dc, i + 1, 0);
3566 
3567 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3568 
3569 		c_irq_params->adev = adev;
3570 		c_irq_params->irq_src = int_params.irq_source;
3571 
3572 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3573 				dm_crtc_high_irq, c_irq_params);
3574 	}
3575 
3576 	/* Use GRPH_PFLIP interrupt */
3577 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3578 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3579 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3580 		if (r) {
3581 			DRM_ERROR("Failed to add page flip irq id!\n");
3582 			return r;
3583 		}
3584 
3585 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3586 		int_params.irq_source =
3587 			dc_interrupt_to_irq_source(dc, i, 0);
3588 
3589 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3590 
3591 		c_irq_params->adev = adev;
3592 		c_irq_params->irq_src = int_params.irq_source;
3593 
3594 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3595 				dm_pflip_high_irq, c_irq_params);
3596 
3597 	}
3598 
3599 	/* HPD */
3600 	r = amdgpu_irq_add_id(adev, client_id,
3601 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3602 	if (r) {
3603 		DRM_ERROR("Failed to add hpd irq id!\n");
3604 		return r;
3605 	}
3606 
3607 	register_hpd_handlers(adev);
3608 
3609 	return 0;
3610 }
3611 #endif
3612 
3613 /* Register IRQ sources and initialize IRQ callbacks */
3614 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
3615 {
3616 	struct dc *dc = adev->dm.dc;
3617 	struct common_irq_params *c_irq_params;
3618 	struct dc_interrupt_params int_params = {0};
3619 	int r;
3620 	int i;
3621 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3622 
3623 	if (adev->family >= AMDGPU_FAMILY_AI)
3624 		client_id = SOC15_IH_CLIENTID_DCE;
3625 
3626 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3627 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3628 
3629 	/*
3630 	 * Actions of amdgpu_irq_add_id():
3631 	 * 1. Register a set() function with base driver.
3632 	 *    Base driver will call set() function to enable/disable an
3633 	 *    interrupt in DC hardware.
3634 	 * 2. Register amdgpu_dm_irq_handler().
3635 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3636 	 *    coming from DC hardware.
3637 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3638 	 *    for acknowledging and handling.
3639 	 */
3640 
3641 	/* Use VBLANK interrupt */
3642 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
3643 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
3644 		if (r) {
3645 			DRM_ERROR("Failed to add crtc irq id!\n");
3646 			return r;
3647 		}
3648 
3649 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3650 		int_params.irq_source =
3651 			dc_interrupt_to_irq_source(dc, i, 0);
3652 
3653 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3654 
3655 		c_irq_params->adev = adev;
3656 		c_irq_params->irq_src = int_params.irq_source;
3657 
3658 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3659 				dm_crtc_high_irq, c_irq_params);
3660 	}
3661 
3662 	/* Use VUPDATE interrupt */
3663 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
3664 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
3665 		if (r) {
3666 			DRM_ERROR("Failed to add vupdate irq id!\n");
3667 			return r;
3668 		}
3669 
3670 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3671 		int_params.irq_source =
3672 			dc_interrupt_to_irq_source(dc, i, 0);
3673 
3674 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3675 
3676 		c_irq_params->adev = adev;
3677 		c_irq_params->irq_src = int_params.irq_source;
3678 
3679 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3680 				dm_vupdate_high_irq, c_irq_params);
3681 	}
3682 
3683 	/* Use GRPH_PFLIP interrupt */
3684 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3685 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3686 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3687 		if (r) {
3688 			DRM_ERROR("Failed to add page flip irq id!\n");
3689 			return r;
3690 		}
3691 
3692 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3693 		int_params.irq_source =
3694 			dc_interrupt_to_irq_source(dc, i, 0);
3695 
3696 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3697 
3698 		c_irq_params->adev = adev;
3699 		c_irq_params->irq_src = int_params.irq_source;
3700 
3701 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3702 				dm_pflip_high_irq, c_irq_params);
3703 
3704 	}
3705 
3706 	/* HPD */
3707 	r = amdgpu_irq_add_id(adev, client_id,
3708 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3709 	if (r) {
3710 		DRM_ERROR("Failed to add hpd irq id!\n");
3711 		return r;
3712 	}
3713 
3714 	register_hpd_handlers(adev);
3715 
3716 	return 0;
3717 }
3718 
3719 /* Register IRQ sources and initialize IRQ callbacks */
3720 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
3721 {
3722 	struct dc *dc = adev->dm.dc;
3723 	struct common_irq_params *c_irq_params;
3724 	struct dc_interrupt_params int_params = {0};
3725 	int r;
3726 	int i;
3727 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3728 	static const unsigned int vrtl_int_srcid[] = {
3729 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
3730 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
3731 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
3732 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
3733 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
3734 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
3735 	};
3736 #endif
3737 
3738 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3739 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3740 
3741 	/*
3742 	 * Actions of amdgpu_irq_add_id():
3743 	 * 1. Register a set() function with base driver.
3744 	 *    Base driver will call set() function to enable/disable an
3745 	 *    interrupt in DC hardware.
3746 	 * 2. Register amdgpu_dm_irq_handler().
3747 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3748 	 *    coming from DC hardware.
3749 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3750 	 *    for acknowledging and handling.
3751 	 */
3752 
3753 	/* Use VSTARTUP interrupt */
3754 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
3755 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
3756 			i++) {
3757 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
3758 
3759 		if (r) {
3760 			DRM_ERROR("Failed to add crtc irq id!\n");
3761 			return r;
3762 		}
3763 
3764 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3765 		int_params.irq_source =
3766 			dc_interrupt_to_irq_source(dc, i, 0);
3767 
3768 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3769 
3770 		c_irq_params->adev = adev;
3771 		c_irq_params->irq_src = int_params.irq_source;
3772 
3773 		amdgpu_dm_irq_register_interrupt(
3774 			adev, &int_params, dm_crtc_high_irq, c_irq_params);
3775 	}
3776 
3777 	/* Use otg vertical line interrupt */
3778 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3779 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
3780 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
3781 				vrtl_int_srcid[i], &adev->vline0_irq);
3782 
3783 		if (r) {
3784 			DRM_ERROR("Failed to add vline0 irq id!\n");
3785 			return r;
3786 		}
3787 
3788 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3789 		int_params.irq_source =
3790 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
3791 
3792 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
3793 			DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
3794 			break;
3795 		}
3796 
3797 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
3798 					- DC_IRQ_SOURCE_DC1_VLINE0];
3799 
3800 		c_irq_params->adev = adev;
3801 		c_irq_params->irq_src = int_params.irq_source;
3802 
3803 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3804 				dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
3805 	}
3806 #endif
3807 
3808 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
3809 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
3810 	 * to trigger at end of each vblank, regardless of state of the lock,
3811 	 * matching DCE behaviour.
3812 	 */
3813 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
3814 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
3815 	     i++) {
3816 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
3817 
3818 		if (r) {
3819 			DRM_ERROR("Failed to add vupdate irq id!\n");
3820 			return r;
3821 		}
3822 
3823 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3824 		int_params.irq_source =
3825 			dc_interrupt_to_irq_source(dc, i, 0);
3826 
3827 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3828 
3829 		c_irq_params->adev = adev;
3830 		c_irq_params->irq_src = int_params.irq_source;
3831 
3832 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3833 				dm_vupdate_high_irq, c_irq_params);
3834 	}
3835 
3836 	/* Use GRPH_PFLIP interrupt */
3837 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
3838 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
3839 			i++) {
3840 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
3841 		if (r) {
3842 			DRM_ERROR("Failed to add page flip irq id!\n");
3843 			return r;
3844 		}
3845 
3846 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3847 		int_params.irq_source =
3848 			dc_interrupt_to_irq_source(dc, i, 0);
3849 
3850 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3851 
3852 		c_irq_params->adev = adev;
3853 		c_irq_params->irq_src = int_params.irq_source;
3854 
3855 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3856 				dm_pflip_high_irq, c_irq_params);
3857 
3858 	}
3859 
3860 	/* HPD */
3861 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
3862 			&adev->hpd_irq);
3863 	if (r) {
3864 		DRM_ERROR("Failed to add hpd irq id!\n");
3865 		return r;
3866 	}
3867 
3868 	register_hpd_handlers(adev);
3869 
3870 	return 0;
3871 }
3872 /* Register Outbox IRQ sources and initialize IRQ callbacks */
3873 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
3874 {
3875 	struct dc *dc = adev->dm.dc;
3876 	struct common_irq_params *c_irq_params;
3877 	struct dc_interrupt_params int_params = {0};
3878 	int r, i;
3879 
3880 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3881 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3882 
3883 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
3884 			&adev->dmub_outbox_irq);
3885 	if (r) {
3886 		DRM_ERROR("Failed to add outbox irq id!\n");
3887 		return r;
3888 	}
3889 
3890 	if (dc->ctx->dmub_srv) {
3891 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
3892 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3893 		int_params.irq_source =
3894 		dc_interrupt_to_irq_source(dc, i, 0);
3895 
3896 		c_irq_params = &adev->dm.dmub_outbox_params[0];
3897 
3898 		c_irq_params->adev = adev;
3899 		c_irq_params->irq_src = int_params.irq_source;
3900 
3901 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3902 				dm_dmub_outbox1_low_irq, c_irq_params);
3903 	}
3904 
3905 	return 0;
3906 }
3907 
3908 /*
3909  * Acquires the lock for the atomic state object and returns
3910  * the new atomic state.
3911  *
3912  * This should only be called during atomic check.
3913  */
3914 int dm_atomic_get_state(struct drm_atomic_state *state,
3915 			struct dm_atomic_state **dm_state)
3916 {
3917 	struct drm_device *dev = state->dev;
3918 	struct amdgpu_device *adev = drm_to_adev(dev);
3919 	struct amdgpu_display_manager *dm = &adev->dm;
3920 	struct drm_private_state *priv_state;
3921 
3922 	if (*dm_state)
3923 		return 0;
3924 
3925 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
3926 	if (IS_ERR(priv_state))
3927 		return PTR_ERR(priv_state);
3928 
3929 	*dm_state = to_dm_atomic_state(priv_state);
3930 
3931 	return 0;
3932 }
3933 
3934 static struct dm_atomic_state *
3935 dm_atomic_get_new_state(struct drm_atomic_state *state)
3936 {
3937 	struct drm_device *dev = state->dev;
3938 	struct amdgpu_device *adev = drm_to_adev(dev);
3939 	struct amdgpu_display_manager *dm = &adev->dm;
3940 	struct drm_private_obj *obj;
3941 	struct drm_private_state *new_obj_state;
3942 	int i;
3943 
3944 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
3945 		if (obj->funcs == dm->atomic_obj.funcs)
3946 			return to_dm_atomic_state(new_obj_state);
3947 	}
3948 
3949 	return NULL;
3950 }
3951 
3952 static struct drm_private_state *
3953 dm_atomic_duplicate_state(struct drm_private_obj *obj)
3954 {
3955 	struct dm_atomic_state *old_state, *new_state;
3956 
3957 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
3958 	if (!new_state)
3959 		return NULL;
3960 
3961 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
3962 
3963 	old_state = to_dm_atomic_state(obj->state);
3964 
3965 	if (old_state && old_state->context)
3966 		new_state->context = dc_copy_state(old_state->context);
3967 
3968 	if (!new_state->context) {
3969 		kfree(new_state);
3970 		return NULL;
3971 	}
3972 
3973 	return &new_state->base;
3974 }
3975 
3976 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
3977 				    struct drm_private_state *state)
3978 {
3979 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3980 
3981 	if (dm_state && dm_state->context)
3982 		dc_release_state(dm_state->context);
3983 
3984 	kfree(dm_state);
3985 }
3986 
3987 static struct drm_private_state_funcs dm_atomic_state_funcs = {
3988 	.atomic_duplicate_state = dm_atomic_duplicate_state,
3989 	.atomic_destroy_state = dm_atomic_destroy_state,
3990 };
3991 
3992 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
3993 {
3994 	struct dm_atomic_state *state;
3995 	int r;
3996 
3997 	adev->mode_info.mode_config_initialized = true;
3998 
3999 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4000 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4001 
4002 	adev_to_drm(adev)->mode_config.max_width = 16384;
4003 	adev_to_drm(adev)->mode_config.max_height = 16384;
4004 
4005 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4006 	if (adev->asic_type == CHIP_HAWAII)
4007 		/* disable prefer shadow for now due to hibernation issues */
4008 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4009 	else
4010 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4011 	/* indicates support for immediate flip */
4012 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4013 
4014 	adev_to_drm(adev)->mode_config.fb_base = adev->gmc.aper_base;
4015 
4016 	state = kzalloc(sizeof(*state), GFP_KERNEL);
4017 	if (!state)
4018 		return -ENOMEM;
4019 
4020 	state->context = dc_create_state(adev->dm.dc);
4021 	if (!state->context) {
4022 		kfree(state);
4023 		return -ENOMEM;
4024 	}
4025 
4026 	dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
4027 
4028 	drm_atomic_private_obj_init(adev_to_drm(adev),
4029 				    &adev->dm.atomic_obj,
4030 				    &state->base,
4031 				    &dm_atomic_state_funcs);
4032 
4033 	r = amdgpu_display_modeset_create_props(adev);
4034 	if (r) {
4035 		dc_release_state(state->context);
4036 		kfree(state);
4037 		return r;
4038 	}
4039 
4040 	r = amdgpu_dm_audio_init(adev);
4041 	if (r) {
4042 		dc_release_state(state->context);
4043 		kfree(state);
4044 		return r;
4045 	}
4046 
4047 	return 0;
4048 }
4049 
4050 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4051 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4052 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4053 
4054 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4055 					    int bl_idx)
4056 {
4057 #if defined(CONFIG_ACPI)
4058 	struct amdgpu_dm_backlight_caps caps;
4059 
4060 	memset(&caps, 0, sizeof(caps));
4061 
4062 	if (dm->backlight_caps[bl_idx].caps_valid)
4063 		return;
4064 
4065 	amdgpu_acpi_get_backlight_caps(&caps);
4066 	if (caps.caps_valid) {
4067 		dm->backlight_caps[bl_idx].caps_valid = true;
4068 		if (caps.aux_support)
4069 			return;
4070 		dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
4071 		dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
4072 	} else {
4073 		dm->backlight_caps[bl_idx].min_input_signal =
4074 				AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4075 		dm->backlight_caps[bl_idx].max_input_signal =
4076 				AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4077 	}
4078 #else
4079 	if (dm->backlight_caps[bl_idx].aux_support)
4080 		return;
4081 
4082 	dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4083 	dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4084 #endif
4085 }
4086 
4087 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
4088 				unsigned int *min, unsigned int *max)
4089 {
4090 	if (!caps)
4091 		return 0;
4092 
4093 	if (caps->aux_support) {
4094 		// Firmware limits are in nits, DC API wants millinits.
4095 		*max = 1000 * caps->aux_max_input_signal;
4096 		*min = 1000 * caps->aux_min_input_signal;
4097 	} else {
4098 		// Firmware limits are 8-bit, PWM control is 16-bit.
4099 		*max = 0x101 * caps->max_input_signal;
4100 		*min = 0x101 * caps->min_input_signal;
4101 	}
4102 	return 1;
4103 }
4104 
4105 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
4106 					uint32_t brightness)
4107 {
4108 	unsigned int min, max;
4109 
4110 	if (!get_brightness_range(caps, &min, &max))
4111 		return brightness;
4112 
4113 	// Rescale 0..255 to min..max
4114 	return min + DIV_ROUND_CLOSEST((max - min) * brightness,
4115 				       AMDGPU_MAX_BL_LEVEL);
4116 }
4117 
4118 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
4119 				      uint32_t brightness)
4120 {
4121 	unsigned int min, max;
4122 
4123 	if (!get_brightness_range(caps, &min, &max))
4124 		return brightness;
4125 
4126 	if (brightness < min)
4127 		return 0;
4128 	// Rescale min..max to 0..255
4129 	return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
4130 				 max - min);
4131 }
4132 
4133 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
4134 					 int bl_idx,
4135 					 u32 user_brightness)
4136 {
4137 	struct amdgpu_dm_backlight_caps caps;
4138 	struct dc_link *link;
4139 	u32 brightness;
4140 	bool rc;
4141 
4142 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4143 	caps = dm->backlight_caps[bl_idx];
4144 
4145 	dm->brightness[bl_idx] = user_brightness;
4146 	/* update scratch register */
4147 	if (bl_idx == 0)
4148 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
4149 	brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
4150 	link = (struct dc_link *)dm->backlight_link[bl_idx];
4151 
4152 	/* Change brightness based on AUX property */
4153 	if (caps.aux_support) {
4154 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
4155 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
4156 		if (!rc)
4157 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
4158 	} else {
4159 		rc = dc_link_set_backlight_level(link, brightness, 0);
4160 		if (!rc)
4161 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
4162 	}
4163 
4164 	if (rc)
4165 		dm->actual_brightness[bl_idx] = user_brightness;
4166 }
4167 
4168 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
4169 {
4170 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4171 	int i;
4172 
4173 	for (i = 0; i < dm->num_of_edps; i++) {
4174 		if (bd == dm->backlight_dev[i])
4175 			break;
4176 	}
4177 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4178 		i = 0;
4179 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
4180 
4181 	return 0;
4182 }
4183 
4184 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
4185 					 int bl_idx)
4186 {
4187 	struct amdgpu_dm_backlight_caps caps;
4188 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
4189 
4190 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4191 	caps = dm->backlight_caps[bl_idx];
4192 
4193 	if (caps.aux_support) {
4194 		u32 avg, peak;
4195 		bool rc;
4196 
4197 		rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
4198 		if (!rc)
4199 			return dm->brightness[bl_idx];
4200 		return convert_brightness_to_user(&caps, avg);
4201 	} else {
4202 		int ret = dc_link_get_backlight_level(link);
4203 
4204 		if (ret == DC_ERROR_UNEXPECTED)
4205 			return dm->brightness[bl_idx];
4206 		return convert_brightness_to_user(&caps, ret);
4207 	}
4208 }
4209 
4210 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
4211 {
4212 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4213 	int i;
4214 
4215 	for (i = 0; i < dm->num_of_edps; i++) {
4216 		if (bd == dm->backlight_dev[i])
4217 			break;
4218 	}
4219 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4220 		i = 0;
4221 	return amdgpu_dm_backlight_get_level(dm, i);
4222 }
4223 
4224 static const struct backlight_ops amdgpu_dm_backlight_ops = {
4225 	.options = BL_CORE_SUSPENDRESUME,
4226 	.get_brightness = amdgpu_dm_backlight_get_brightness,
4227 	.update_status	= amdgpu_dm_backlight_update_status,
4228 };
4229 
4230 static void
4231 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
4232 {
4233 	char bl_name[16];
4234 	struct backlight_properties props = { 0 };
4235 
4236 	amdgpu_dm_update_backlight_caps(dm, dm->num_of_edps);
4237 	dm->brightness[dm->num_of_edps] = AMDGPU_MAX_BL_LEVEL;
4238 
4239 	if (!acpi_video_backlight_use_native()) {
4240 		drm_info(adev_to_drm(dm->adev), "Skipping amdgpu DM backlight registration\n");
4241 		/* Try registering an ACPI video backlight device instead. */
4242 		acpi_video_register_backlight();
4243 		return;
4244 	}
4245 
4246 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
4247 	props.brightness = AMDGPU_MAX_BL_LEVEL;
4248 	props.type = BACKLIGHT_RAW;
4249 
4250 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
4251 		 adev_to_drm(dm->adev)->primary->index + dm->num_of_edps);
4252 
4253 	dm->backlight_dev[dm->num_of_edps] = backlight_device_register(bl_name,
4254 								       adev_to_drm(dm->adev)->dev,
4255 								       dm,
4256 								       &amdgpu_dm_backlight_ops,
4257 								       &props);
4258 
4259 	if (IS_ERR(dm->backlight_dev[dm->num_of_edps]))
4260 		DRM_ERROR("DM: Backlight registration failed!\n");
4261 	else
4262 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
4263 }
4264 
4265 static int initialize_plane(struct amdgpu_display_manager *dm,
4266 			    struct amdgpu_mode_info *mode_info, int plane_id,
4267 			    enum drm_plane_type plane_type,
4268 			    const struct dc_plane_cap *plane_cap)
4269 {
4270 	struct drm_plane *plane;
4271 	unsigned long possible_crtcs;
4272 	int ret = 0;
4273 
4274 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
4275 	if (!plane) {
4276 		DRM_ERROR("KMS: Failed to allocate plane\n");
4277 		return -ENOMEM;
4278 	}
4279 	plane->type = plane_type;
4280 
4281 	/*
4282 	 * HACK: IGT tests expect that the primary plane for a CRTC
4283 	 * can only have one possible CRTC. Only expose support for
4284 	 * any CRTC if they're not going to be used as a primary plane
4285 	 * for a CRTC - like overlay or underlay planes.
4286 	 */
4287 	possible_crtcs = 1 << plane_id;
4288 	if (plane_id >= dm->dc->caps.max_streams)
4289 		possible_crtcs = 0xff;
4290 
4291 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
4292 
4293 	if (ret) {
4294 		DRM_ERROR("KMS: Failed to initialize plane\n");
4295 		kfree(plane);
4296 		return ret;
4297 	}
4298 
4299 	if (mode_info)
4300 		mode_info->planes[plane_id] = plane;
4301 
4302 	return ret;
4303 }
4304 
4305 
4306 static void register_backlight_device(struct amdgpu_display_manager *dm,
4307 				      struct dc_link *link)
4308 {
4309 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4310 	    link->type != dc_connection_none) {
4311 		/*
4312 		 * Event if registration failed, we should continue with
4313 		 * DM initialization because not having a backlight control
4314 		 * is better then a black screen.
4315 		 */
4316 		if (!dm->backlight_dev[dm->num_of_edps])
4317 			amdgpu_dm_register_backlight_device(dm);
4318 
4319 		if (dm->backlight_dev[dm->num_of_edps]) {
4320 			dm->backlight_link[dm->num_of_edps] = link;
4321 			dm->num_of_edps++;
4322 		}
4323 	}
4324 }
4325 
4326 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
4327 
4328 /*
4329  * In this architecture, the association
4330  * connector -> encoder -> crtc
4331  * id not really requried. The crtc and connector will hold the
4332  * display_index as an abstraction to use with DAL component
4333  *
4334  * Returns 0 on success
4335  */
4336 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
4337 {
4338 	struct amdgpu_display_manager *dm = &adev->dm;
4339 	s32 i;
4340 	struct amdgpu_dm_connector *aconnector = NULL;
4341 	struct amdgpu_encoder *aencoder = NULL;
4342 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
4343 	u32 link_cnt;
4344 	s32 primary_planes;
4345 	enum dc_connection_type new_connection_type = dc_connection_none;
4346 	const struct dc_plane_cap *plane;
4347 	bool psr_feature_enabled = false;
4348 
4349 	dm->display_indexes_num = dm->dc->caps.max_streams;
4350 	/* Update the actual used number of crtc */
4351 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
4352 
4353 	link_cnt = dm->dc->caps.max_links;
4354 	if (amdgpu_dm_mode_config_init(dm->adev)) {
4355 		DRM_ERROR("DM: Failed to initialize mode config\n");
4356 		return -EINVAL;
4357 	}
4358 
4359 	/* There is one primary plane per CRTC */
4360 	primary_planes = dm->dc->caps.max_streams;
4361 	ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
4362 
4363 	/*
4364 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
4365 	 * Order is reversed to match iteration order in atomic check.
4366 	 */
4367 	for (i = (primary_planes - 1); i >= 0; i--) {
4368 		plane = &dm->dc->caps.planes[i];
4369 
4370 		if (initialize_plane(dm, mode_info, i,
4371 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
4372 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
4373 			goto fail;
4374 		}
4375 	}
4376 
4377 	/*
4378 	 * Initialize overlay planes, index starting after primary planes.
4379 	 * These planes have a higher DRM index than the primary planes since
4380 	 * they should be considered as having a higher z-order.
4381 	 * Order is reversed to match iteration order in atomic check.
4382 	 *
4383 	 * Only support DCN for now, and only expose one so we don't encourage
4384 	 * userspace to use up all the pipes.
4385 	 */
4386 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
4387 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
4388 
4389 		/* Do not create overlay if MPO disabled */
4390 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
4391 			break;
4392 
4393 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
4394 			continue;
4395 
4396 		if (!plane->blends_with_above || !plane->blends_with_below)
4397 			continue;
4398 
4399 		if (!plane->pixel_format_support.argb8888)
4400 			continue;
4401 
4402 		if (initialize_plane(dm, NULL, primary_planes + i,
4403 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
4404 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
4405 			goto fail;
4406 		}
4407 
4408 		/* Only create one overlay plane. */
4409 		break;
4410 	}
4411 
4412 	for (i = 0; i < dm->dc->caps.max_streams; i++)
4413 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
4414 			DRM_ERROR("KMS: Failed to initialize crtc\n");
4415 			goto fail;
4416 		}
4417 
4418 	/* Use Outbox interrupt */
4419 	switch (adev->ip_versions[DCE_HWIP][0]) {
4420 	case IP_VERSION(3, 0, 0):
4421 	case IP_VERSION(3, 1, 2):
4422 	case IP_VERSION(3, 1, 3):
4423 	case IP_VERSION(3, 1, 4):
4424 	case IP_VERSION(3, 1, 5):
4425 	case IP_VERSION(3, 1, 6):
4426 	case IP_VERSION(3, 2, 0):
4427 	case IP_VERSION(3, 2, 1):
4428 	case IP_VERSION(2, 1, 0):
4429 		if (register_outbox_irq_handlers(dm->adev)) {
4430 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4431 			goto fail;
4432 		}
4433 		break;
4434 	default:
4435 		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
4436 			      adev->ip_versions[DCE_HWIP][0]);
4437 	}
4438 
4439 	/* Determine whether to enable PSR support by default. */
4440 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
4441 		switch (adev->ip_versions[DCE_HWIP][0]) {
4442 		case IP_VERSION(3, 1, 2):
4443 		case IP_VERSION(3, 1, 3):
4444 		case IP_VERSION(3, 1, 4):
4445 		case IP_VERSION(3, 1, 5):
4446 		case IP_VERSION(3, 1, 6):
4447 		case IP_VERSION(3, 2, 0):
4448 		case IP_VERSION(3, 2, 1):
4449 			psr_feature_enabled = true;
4450 			break;
4451 		default:
4452 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
4453 			break;
4454 		}
4455 	}
4456 
4457 	/* loops over all connectors on the board */
4458 	for (i = 0; i < link_cnt; i++) {
4459 		struct dc_link *link = NULL;
4460 
4461 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
4462 			DRM_ERROR(
4463 				"KMS: Cannot support more than %d display indexes\n",
4464 					AMDGPU_DM_MAX_DISPLAY_INDEX);
4465 			continue;
4466 		}
4467 
4468 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
4469 		if (!aconnector)
4470 			goto fail;
4471 
4472 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
4473 		if (!aencoder)
4474 			goto fail;
4475 
4476 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
4477 			DRM_ERROR("KMS: Failed to initialize encoder\n");
4478 			goto fail;
4479 		}
4480 
4481 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
4482 			DRM_ERROR("KMS: Failed to initialize connector\n");
4483 			goto fail;
4484 		}
4485 
4486 		link = dc_get_link_at_index(dm->dc, i);
4487 
4488 		if (!dc_link_detect_sink(link, &new_connection_type))
4489 			DRM_ERROR("KMS: Failed to detect connector\n");
4490 
4491 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4492 			emulated_link_detect(link);
4493 			amdgpu_dm_update_connector_after_detect(aconnector);
4494 		} else {
4495 			bool ret = false;
4496 
4497 			mutex_lock(&dm->dc_lock);
4498 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
4499 			mutex_unlock(&dm->dc_lock);
4500 
4501 			if (ret) {
4502 				amdgpu_dm_update_connector_after_detect(aconnector);
4503 				register_backlight_device(dm, link);
4504 
4505 				if (dm->num_of_edps)
4506 					update_connector_ext_caps(aconnector);
4507 
4508 				if (psr_feature_enabled)
4509 					amdgpu_dm_set_psr_caps(link);
4510 
4511 				/* TODO: Fix vblank control helpers to delay PSR entry to allow this when
4512 				 * PSR is also supported.
4513 				 */
4514 				if (link->psr_settings.psr_feature_enabled)
4515 					adev_to_drm(adev)->vblank_disable_immediate = false;
4516 			}
4517 		}
4518 		amdgpu_set_panel_orientation(&aconnector->base);
4519 	}
4520 
4521 	/* If we didn't find a panel, notify the acpi video detection */
4522 	if (dm->adev->flags & AMD_IS_APU && dm->num_of_edps == 0)
4523 		acpi_video_report_nolcd();
4524 
4525 	/* Software is initialized. Now we can register interrupt handlers. */
4526 	switch (adev->asic_type) {
4527 #if defined(CONFIG_DRM_AMD_DC_SI)
4528 	case CHIP_TAHITI:
4529 	case CHIP_PITCAIRN:
4530 	case CHIP_VERDE:
4531 	case CHIP_OLAND:
4532 		if (dce60_register_irq_handlers(dm->adev)) {
4533 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4534 			goto fail;
4535 		}
4536 		break;
4537 #endif
4538 	case CHIP_BONAIRE:
4539 	case CHIP_HAWAII:
4540 	case CHIP_KAVERI:
4541 	case CHIP_KABINI:
4542 	case CHIP_MULLINS:
4543 	case CHIP_TONGA:
4544 	case CHIP_FIJI:
4545 	case CHIP_CARRIZO:
4546 	case CHIP_STONEY:
4547 	case CHIP_POLARIS11:
4548 	case CHIP_POLARIS10:
4549 	case CHIP_POLARIS12:
4550 	case CHIP_VEGAM:
4551 	case CHIP_VEGA10:
4552 	case CHIP_VEGA12:
4553 	case CHIP_VEGA20:
4554 		if (dce110_register_irq_handlers(dm->adev)) {
4555 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4556 			goto fail;
4557 		}
4558 		break;
4559 	default:
4560 		switch (adev->ip_versions[DCE_HWIP][0]) {
4561 		case IP_VERSION(1, 0, 0):
4562 		case IP_VERSION(1, 0, 1):
4563 		case IP_VERSION(2, 0, 2):
4564 		case IP_VERSION(2, 0, 3):
4565 		case IP_VERSION(2, 0, 0):
4566 		case IP_VERSION(2, 1, 0):
4567 		case IP_VERSION(3, 0, 0):
4568 		case IP_VERSION(3, 0, 2):
4569 		case IP_VERSION(3, 0, 3):
4570 		case IP_VERSION(3, 0, 1):
4571 		case IP_VERSION(3, 1, 2):
4572 		case IP_VERSION(3, 1, 3):
4573 		case IP_VERSION(3, 1, 4):
4574 		case IP_VERSION(3, 1, 5):
4575 		case IP_VERSION(3, 1, 6):
4576 		case IP_VERSION(3, 2, 0):
4577 		case IP_VERSION(3, 2, 1):
4578 			if (dcn10_register_irq_handlers(dm->adev)) {
4579 				DRM_ERROR("DM: Failed to initialize IRQ\n");
4580 				goto fail;
4581 			}
4582 			break;
4583 		default:
4584 			DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4585 					adev->ip_versions[DCE_HWIP][0]);
4586 			goto fail;
4587 		}
4588 		break;
4589 	}
4590 
4591 	return 0;
4592 fail:
4593 	kfree(aencoder);
4594 	kfree(aconnector);
4595 
4596 	return -EINVAL;
4597 }
4598 
4599 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4600 {
4601 	drm_atomic_private_obj_fini(&dm->atomic_obj);
4602 }
4603 
4604 /******************************************************************************
4605  * amdgpu_display_funcs functions
4606  *****************************************************************************/
4607 
4608 /*
4609  * dm_bandwidth_update - program display watermarks
4610  *
4611  * @adev: amdgpu_device pointer
4612  *
4613  * Calculate and program the display watermarks and line buffer allocation.
4614  */
4615 static void dm_bandwidth_update(struct amdgpu_device *adev)
4616 {
4617 	/* TODO: implement later */
4618 }
4619 
4620 static const struct amdgpu_display_funcs dm_display_funcs = {
4621 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4622 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4623 	.backlight_set_level = NULL, /* never called for DC */
4624 	.backlight_get_level = NULL, /* never called for DC */
4625 	.hpd_sense = NULL,/* called unconditionally */
4626 	.hpd_set_polarity = NULL, /* called unconditionally */
4627 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4628 	.page_flip_get_scanoutpos =
4629 		dm_crtc_get_scanoutpos,/* called unconditionally */
4630 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4631 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
4632 };
4633 
4634 #if defined(CONFIG_DEBUG_KERNEL_DC)
4635 
4636 static ssize_t s3_debug_store(struct device *device,
4637 			      struct device_attribute *attr,
4638 			      const char *buf,
4639 			      size_t count)
4640 {
4641 	int ret;
4642 	int s3_state;
4643 	struct drm_device *drm_dev = dev_get_drvdata(device);
4644 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
4645 
4646 	ret = kstrtoint(buf, 0, &s3_state);
4647 
4648 	if (ret == 0) {
4649 		if (s3_state) {
4650 			dm_resume(adev);
4651 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
4652 		} else
4653 			dm_suspend(adev);
4654 	}
4655 
4656 	return ret == 0 ? count : 0;
4657 }
4658 
4659 DEVICE_ATTR_WO(s3_debug);
4660 
4661 #endif
4662 
4663 static int dm_early_init(void *handle)
4664 {
4665 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4666 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
4667 	struct atom_context *ctx = mode_info->atom_context;
4668 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
4669 	u16 data_offset;
4670 
4671 	/* if there is no object header, skip DM */
4672 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
4673 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
4674 		dev_info(adev->dev, "No object header, skipping DM\n");
4675 		return -ENOENT;
4676 	}
4677 
4678 	switch (adev->asic_type) {
4679 #if defined(CONFIG_DRM_AMD_DC_SI)
4680 	case CHIP_TAHITI:
4681 	case CHIP_PITCAIRN:
4682 	case CHIP_VERDE:
4683 		adev->mode_info.num_crtc = 6;
4684 		adev->mode_info.num_hpd = 6;
4685 		adev->mode_info.num_dig = 6;
4686 		break;
4687 	case CHIP_OLAND:
4688 		adev->mode_info.num_crtc = 2;
4689 		adev->mode_info.num_hpd = 2;
4690 		adev->mode_info.num_dig = 2;
4691 		break;
4692 #endif
4693 	case CHIP_BONAIRE:
4694 	case CHIP_HAWAII:
4695 		adev->mode_info.num_crtc = 6;
4696 		adev->mode_info.num_hpd = 6;
4697 		adev->mode_info.num_dig = 6;
4698 		break;
4699 	case CHIP_KAVERI:
4700 		adev->mode_info.num_crtc = 4;
4701 		adev->mode_info.num_hpd = 6;
4702 		adev->mode_info.num_dig = 7;
4703 		break;
4704 	case CHIP_KABINI:
4705 	case CHIP_MULLINS:
4706 		adev->mode_info.num_crtc = 2;
4707 		adev->mode_info.num_hpd = 6;
4708 		adev->mode_info.num_dig = 6;
4709 		break;
4710 	case CHIP_FIJI:
4711 	case CHIP_TONGA:
4712 		adev->mode_info.num_crtc = 6;
4713 		adev->mode_info.num_hpd = 6;
4714 		adev->mode_info.num_dig = 7;
4715 		break;
4716 	case CHIP_CARRIZO:
4717 		adev->mode_info.num_crtc = 3;
4718 		adev->mode_info.num_hpd = 6;
4719 		adev->mode_info.num_dig = 9;
4720 		break;
4721 	case CHIP_STONEY:
4722 		adev->mode_info.num_crtc = 2;
4723 		adev->mode_info.num_hpd = 6;
4724 		adev->mode_info.num_dig = 9;
4725 		break;
4726 	case CHIP_POLARIS11:
4727 	case CHIP_POLARIS12:
4728 		adev->mode_info.num_crtc = 5;
4729 		adev->mode_info.num_hpd = 5;
4730 		adev->mode_info.num_dig = 5;
4731 		break;
4732 	case CHIP_POLARIS10:
4733 	case CHIP_VEGAM:
4734 		adev->mode_info.num_crtc = 6;
4735 		adev->mode_info.num_hpd = 6;
4736 		adev->mode_info.num_dig = 6;
4737 		break;
4738 	case CHIP_VEGA10:
4739 	case CHIP_VEGA12:
4740 	case CHIP_VEGA20:
4741 		adev->mode_info.num_crtc = 6;
4742 		adev->mode_info.num_hpd = 6;
4743 		adev->mode_info.num_dig = 6;
4744 		break;
4745 	default:
4746 
4747 		switch (adev->ip_versions[DCE_HWIP][0]) {
4748 		case IP_VERSION(2, 0, 2):
4749 		case IP_VERSION(3, 0, 0):
4750 			adev->mode_info.num_crtc = 6;
4751 			adev->mode_info.num_hpd = 6;
4752 			adev->mode_info.num_dig = 6;
4753 			break;
4754 		case IP_VERSION(2, 0, 0):
4755 		case IP_VERSION(3, 0, 2):
4756 			adev->mode_info.num_crtc = 5;
4757 			adev->mode_info.num_hpd = 5;
4758 			adev->mode_info.num_dig = 5;
4759 			break;
4760 		case IP_VERSION(2, 0, 3):
4761 		case IP_VERSION(3, 0, 3):
4762 			adev->mode_info.num_crtc = 2;
4763 			adev->mode_info.num_hpd = 2;
4764 			adev->mode_info.num_dig = 2;
4765 			break;
4766 		case IP_VERSION(1, 0, 0):
4767 		case IP_VERSION(1, 0, 1):
4768 		case IP_VERSION(3, 0, 1):
4769 		case IP_VERSION(2, 1, 0):
4770 		case IP_VERSION(3, 1, 2):
4771 		case IP_VERSION(3, 1, 3):
4772 		case IP_VERSION(3, 1, 4):
4773 		case IP_VERSION(3, 1, 5):
4774 		case IP_VERSION(3, 1, 6):
4775 		case IP_VERSION(3, 2, 0):
4776 		case IP_VERSION(3, 2, 1):
4777 			adev->mode_info.num_crtc = 4;
4778 			adev->mode_info.num_hpd = 4;
4779 			adev->mode_info.num_dig = 4;
4780 			break;
4781 		default:
4782 			DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4783 					adev->ip_versions[DCE_HWIP][0]);
4784 			return -EINVAL;
4785 		}
4786 		break;
4787 	}
4788 
4789 	amdgpu_dm_set_irq_funcs(adev);
4790 
4791 	if (adev->mode_info.funcs == NULL)
4792 		adev->mode_info.funcs = &dm_display_funcs;
4793 
4794 	/*
4795 	 * Note: Do NOT change adev->audio_endpt_rreg and
4796 	 * adev->audio_endpt_wreg because they are initialised in
4797 	 * amdgpu_device_init()
4798 	 */
4799 #if defined(CONFIG_DEBUG_KERNEL_DC)
4800 	device_create_file(
4801 		adev_to_drm(adev)->dev,
4802 		&dev_attr_s3_debug);
4803 #endif
4804 
4805 	return 0;
4806 }
4807 
4808 static bool modereset_required(struct drm_crtc_state *crtc_state)
4809 {
4810 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4811 }
4812 
4813 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4814 {
4815 	drm_encoder_cleanup(encoder);
4816 	kfree(encoder);
4817 }
4818 
4819 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4820 	.destroy = amdgpu_dm_encoder_destroy,
4821 };
4822 
4823 static int
4824 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4825 			    const enum surface_pixel_format format,
4826 			    enum dc_color_space *color_space)
4827 {
4828 	bool full_range;
4829 
4830 	*color_space = COLOR_SPACE_SRGB;
4831 
4832 	/* DRM color properties only affect non-RGB formats. */
4833 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4834 		return 0;
4835 
4836 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4837 
4838 	switch (plane_state->color_encoding) {
4839 	case DRM_COLOR_YCBCR_BT601:
4840 		if (full_range)
4841 			*color_space = COLOR_SPACE_YCBCR601;
4842 		else
4843 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
4844 		break;
4845 
4846 	case DRM_COLOR_YCBCR_BT709:
4847 		if (full_range)
4848 			*color_space = COLOR_SPACE_YCBCR709;
4849 		else
4850 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
4851 		break;
4852 
4853 	case DRM_COLOR_YCBCR_BT2020:
4854 		if (full_range)
4855 			*color_space = COLOR_SPACE_2020_YCBCR;
4856 		else
4857 			return -EINVAL;
4858 		break;
4859 
4860 	default:
4861 		return -EINVAL;
4862 	}
4863 
4864 	return 0;
4865 }
4866 
4867 static int
4868 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4869 			    const struct drm_plane_state *plane_state,
4870 			    const u64 tiling_flags,
4871 			    struct dc_plane_info *plane_info,
4872 			    struct dc_plane_address *address,
4873 			    bool tmz_surface,
4874 			    bool force_disable_dcc)
4875 {
4876 	const struct drm_framebuffer *fb = plane_state->fb;
4877 	const struct amdgpu_framebuffer *afb =
4878 		to_amdgpu_framebuffer(plane_state->fb);
4879 	int ret;
4880 
4881 	memset(plane_info, 0, sizeof(*plane_info));
4882 
4883 	switch (fb->format->format) {
4884 	case DRM_FORMAT_C8:
4885 		plane_info->format =
4886 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4887 		break;
4888 	case DRM_FORMAT_RGB565:
4889 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4890 		break;
4891 	case DRM_FORMAT_XRGB8888:
4892 	case DRM_FORMAT_ARGB8888:
4893 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4894 		break;
4895 	case DRM_FORMAT_XRGB2101010:
4896 	case DRM_FORMAT_ARGB2101010:
4897 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4898 		break;
4899 	case DRM_FORMAT_XBGR2101010:
4900 	case DRM_FORMAT_ABGR2101010:
4901 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4902 		break;
4903 	case DRM_FORMAT_XBGR8888:
4904 	case DRM_FORMAT_ABGR8888:
4905 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4906 		break;
4907 	case DRM_FORMAT_NV21:
4908 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4909 		break;
4910 	case DRM_FORMAT_NV12:
4911 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4912 		break;
4913 	case DRM_FORMAT_P010:
4914 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4915 		break;
4916 	case DRM_FORMAT_XRGB16161616F:
4917 	case DRM_FORMAT_ARGB16161616F:
4918 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4919 		break;
4920 	case DRM_FORMAT_XBGR16161616F:
4921 	case DRM_FORMAT_ABGR16161616F:
4922 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4923 		break;
4924 	case DRM_FORMAT_XRGB16161616:
4925 	case DRM_FORMAT_ARGB16161616:
4926 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4927 		break;
4928 	case DRM_FORMAT_XBGR16161616:
4929 	case DRM_FORMAT_ABGR16161616:
4930 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4931 		break;
4932 	default:
4933 		DRM_ERROR(
4934 			"Unsupported screen format %p4cc\n",
4935 			&fb->format->format);
4936 		return -EINVAL;
4937 	}
4938 
4939 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4940 	case DRM_MODE_ROTATE_0:
4941 		plane_info->rotation = ROTATION_ANGLE_0;
4942 		break;
4943 	case DRM_MODE_ROTATE_90:
4944 		plane_info->rotation = ROTATION_ANGLE_90;
4945 		break;
4946 	case DRM_MODE_ROTATE_180:
4947 		plane_info->rotation = ROTATION_ANGLE_180;
4948 		break;
4949 	case DRM_MODE_ROTATE_270:
4950 		plane_info->rotation = ROTATION_ANGLE_270;
4951 		break;
4952 	default:
4953 		plane_info->rotation = ROTATION_ANGLE_0;
4954 		break;
4955 	}
4956 
4957 
4958 	plane_info->visible = true;
4959 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4960 
4961 	plane_info->layer_index = plane_state->normalized_zpos;
4962 
4963 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
4964 					  &plane_info->color_space);
4965 	if (ret)
4966 		return ret;
4967 
4968 	ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4969 					   plane_info->rotation, tiling_flags,
4970 					   &plane_info->tiling_info,
4971 					   &plane_info->plane_size,
4972 					   &plane_info->dcc, address,
4973 					   tmz_surface, force_disable_dcc);
4974 	if (ret)
4975 		return ret;
4976 
4977 	fill_blending_from_plane_state(
4978 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4979 		&plane_info->global_alpha, &plane_info->global_alpha_value);
4980 
4981 	return 0;
4982 }
4983 
4984 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4985 				    struct dc_plane_state *dc_plane_state,
4986 				    struct drm_plane_state *plane_state,
4987 				    struct drm_crtc_state *crtc_state)
4988 {
4989 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4990 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4991 	struct dc_scaling_info scaling_info;
4992 	struct dc_plane_info plane_info;
4993 	int ret;
4994 	bool force_disable_dcc = false;
4995 
4996 	ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4997 	if (ret)
4998 		return ret;
4999 
5000 	dc_plane_state->src_rect = scaling_info.src_rect;
5001 	dc_plane_state->dst_rect = scaling_info.dst_rect;
5002 	dc_plane_state->clip_rect = scaling_info.clip_rect;
5003 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
5004 
5005 	force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
5006 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
5007 					  afb->tiling_flags,
5008 					  &plane_info,
5009 					  &dc_plane_state->address,
5010 					  afb->tmz_surface,
5011 					  force_disable_dcc);
5012 	if (ret)
5013 		return ret;
5014 
5015 	dc_plane_state->format = plane_info.format;
5016 	dc_plane_state->color_space = plane_info.color_space;
5017 	dc_plane_state->format = plane_info.format;
5018 	dc_plane_state->plane_size = plane_info.plane_size;
5019 	dc_plane_state->rotation = plane_info.rotation;
5020 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
5021 	dc_plane_state->stereo_format = plane_info.stereo_format;
5022 	dc_plane_state->tiling_info = plane_info.tiling_info;
5023 	dc_plane_state->visible = plane_info.visible;
5024 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
5025 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
5026 	dc_plane_state->global_alpha = plane_info.global_alpha;
5027 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
5028 	dc_plane_state->dcc = plane_info.dcc;
5029 	dc_plane_state->layer_index = plane_info.layer_index;
5030 	dc_plane_state->flip_int_enabled = true;
5031 
5032 	/*
5033 	 * Always set input transfer function, since plane state is refreshed
5034 	 * every time.
5035 	 */
5036 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
5037 	if (ret)
5038 		return ret;
5039 
5040 	return 0;
5041 }
5042 
5043 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
5044 				      struct rect *dirty_rect, int32_t x,
5045 				      int32_t y, int32_t width, int32_t height,
5046 				      int *i, bool ffu)
5047 {
5048 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
5049 
5050 	dirty_rect->x = x;
5051 	dirty_rect->y = y;
5052 	dirty_rect->width = width;
5053 	dirty_rect->height = height;
5054 
5055 	if (ffu)
5056 		drm_dbg(plane->dev,
5057 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
5058 			plane->base.id, width, height);
5059 	else
5060 		drm_dbg(plane->dev,
5061 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
5062 			plane->base.id, x, y, width, height);
5063 
5064 	(*i)++;
5065 }
5066 
5067 /**
5068  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
5069  *
5070  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
5071  *         remote fb
5072  * @old_plane_state: Old state of @plane
5073  * @new_plane_state: New state of @plane
5074  * @crtc_state: New state of CRTC connected to the @plane
5075  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
5076  *
5077  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
5078  * (referred to as "damage clips" in DRM nomenclature) that require updating on
5079  * the eDP remote buffer. The responsibility of specifying the dirty regions is
5080  * amdgpu_dm's.
5081  *
5082  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
5083  * plane with regions that require flushing to the eDP remote buffer. In
5084  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
5085  * implicitly provide damage clips without any client support via the plane
5086  * bounds.
5087  */
5088 static void fill_dc_dirty_rects(struct drm_plane *plane,
5089 				struct drm_plane_state *old_plane_state,
5090 				struct drm_plane_state *new_plane_state,
5091 				struct drm_crtc_state *crtc_state,
5092 				struct dc_flip_addrs *flip_addrs)
5093 {
5094 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
5095 	struct rect *dirty_rects = flip_addrs->dirty_rects;
5096 	uint32_t num_clips;
5097 	struct drm_mode_rect *clips;
5098 	bool bb_changed;
5099 	bool fb_changed;
5100 	u32 i = 0;
5101 
5102 	/*
5103 	 * Cursor plane has it's own dirty rect update interface. See
5104 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
5105 	 */
5106 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
5107 		return;
5108 
5109 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
5110 	clips = drm_plane_get_damage_clips(new_plane_state);
5111 
5112 	if (!dm_crtc_state->mpo_requested) {
5113 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
5114 			goto ffu;
5115 
5116 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
5117 			fill_dc_dirty_rect(new_plane_state->plane,
5118 					   &dirty_rects[flip_addrs->dirty_rect_count],
5119 					   clips->x1, clips->y1,
5120 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
5121 					   &flip_addrs->dirty_rect_count,
5122 					   false);
5123 		return;
5124 	}
5125 
5126 	/*
5127 	 * MPO is requested. Add entire plane bounding box to dirty rects if
5128 	 * flipped to or damaged.
5129 	 *
5130 	 * If plane is moved or resized, also add old bounding box to dirty
5131 	 * rects.
5132 	 */
5133 	fb_changed = old_plane_state->fb->base.id !=
5134 		     new_plane_state->fb->base.id;
5135 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
5136 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
5137 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
5138 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
5139 
5140 	drm_dbg(plane->dev,
5141 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
5142 		new_plane_state->plane->base.id,
5143 		bb_changed, fb_changed, num_clips);
5144 
5145 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
5146 		goto ffu;
5147 
5148 	if (bb_changed) {
5149 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5150 				   new_plane_state->crtc_x,
5151 				   new_plane_state->crtc_y,
5152 				   new_plane_state->crtc_w,
5153 				   new_plane_state->crtc_h, &i, false);
5154 
5155 		/* Add old plane bounding-box if plane is moved or resized */
5156 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5157 				   old_plane_state->crtc_x,
5158 				   old_plane_state->crtc_y,
5159 				   old_plane_state->crtc_w,
5160 				   old_plane_state->crtc_h, &i, false);
5161 	}
5162 
5163 	if (num_clips) {
5164 		for (; i < num_clips; clips++)
5165 			fill_dc_dirty_rect(new_plane_state->plane,
5166 					   &dirty_rects[i], clips->x1,
5167 					   clips->y1, clips->x2 - clips->x1,
5168 					   clips->y2 - clips->y1, &i, false);
5169 	} else if (fb_changed && !bb_changed) {
5170 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5171 				   new_plane_state->crtc_x,
5172 				   new_plane_state->crtc_y,
5173 				   new_plane_state->crtc_w,
5174 				   new_plane_state->crtc_h, &i, false);
5175 	}
5176 
5177 	flip_addrs->dirty_rect_count = i;
5178 	return;
5179 
5180 ffu:
5181 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
5182 			   dm_crtc_state->base.mode.crtc_hdisplay,
5183 			   dm_crtc_state->base.mode.crtc_vdisplay,
5184 			   &flip_addrs->dirty_rect_count, true);
5185 }
5186 
5187 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
5188 					   const struct dm_connector_state *dm_state,
5189 					   struct dc_stream_state *stream)
5190 {
5191 	enum amdgpu_rmx_type rmx_type;
5192 
5193 	struct rect src = { 0 }; /* viewport in composition space*/
5194 	struct rect dst = { 0 }; /* stream addressable area */
5195 
5196 	/* no mode. nothing to be done */
5197 	if (!mode)
5198 		return;
5199 
5200 	/* Full screen scaling by default */
5201 	src.width = mode->hdisplay;
5202 	src.height = mode->vdisplay;
5203 	dst.width = stream->timing.h_addressable;
5204 	dst.height = stream->timing.v_addressable;
5205 
5206 	if (dm_state) {
5207 		rmx_type = dm_state->scaling;
5208 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5209 			if (src.width * dst.height <
5210 					src.height * dst.width) {
5211 				/* height needs less upscaling/more downscaling */
5212 				dst.width = src.width *
5213 						dst.height / src.height;
5214 			} else {
5215 				/* width needs less upscaling/more downscaling */
5216 				dst.height = src.height *
5217 						dst.width / src.width;
5218 			}
5219 		} else if (rmx_type == RMX_CENTER) {
5220 			dst = src;
5221 		}
5222 
5223 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
5224 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
5225 
5226 		if (dm_state->underscan_enable) {
5227 			dst.x += dm_state->underscan_hborder / 2;
5228 			dst.y += dm_state->underscan_vborder / 2;
5229 			dst.width -= dm_state->underscan_hborder;
5230 			dst.height -= dm_state->underscan_vborder;
5231 		}
5232 	}
5233 
5234 	stream->src = src;
5235 	stream->dst = dst;
5236 
5237 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5238 		      dst.x, dst.y, dst.width, dst.height);
5239 
5240 }
5241 
5242 static enum dc_color_depth
5243 convert_color_depth_from_display_info(const struct drm_connector *connector,
5244 				      bool is_y420, int requested_bpc)
5245 {
5246 	u8 bpc;
5247 
5248 	if (is_y420) {
5249 		bpc = 8;
5250 
5251 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
5252 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5253 			bpc = 16;
5254 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5255 			bpc = 12;
5256 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5257 			bpc = 10;
5258 	} else {
5259 		bpc = (uint8_t)connector->display_info.bpc;
5260 		/* Assume 8 bpc by default if no bpc is specified. */
5261 		bpc = bpc ? bpc : 8;
5262 	}
5263 
5264 	if (requested_bpc > 0) {
5265 		/*
5266 		 * Cap display bpc based on the user requested value.
5267 		 *
5268 		 * The value for state->max_bpc may not correctly updated
5269 		 * depending on when the connector gets added to the state
5270 		 * or if this was called outside of atomic check, so it
5271 		 * can't be used directly.
5272 		 */
5273 		bpc = min_t(u8, bpc, requested_bpc);
5274 
5275 		/* Round down to the nearest even number. */
5276 		bpc = bpc - (bpc & 1);
5277 	}
5278 
5279 	switch (bpc) {
5280 	case 0:
5281 		/*
5282 		 * Temporary Work around, DRM doesn't parse color depth for
5283 		 * EDID revision before 1.4
5284 		 * TODO: Fix edid parsing
5285 		 */
5286 		return COLOR_DEPTH_888;
5287 	case 6:
5288 		return COLOR_DEPTH_666;
5289 	case 8:
5290 		return COLOR_DEPTH_888;
5291 	case 10:
5292 		return COLOR_DEPTH_101010;
5293 	case 12:
5294 		return COLOR_DEPTH_121212;
5295 	case 14:
5296 		return COLOR_DEPTH_141414;
5297 	case 16:
5298 		return COLOR_DEPTH_161616;
5299 	default:
5300 		return COLOR_DEPTH_UNDEFINED;
5301 	}
5302 }
5303 
5304 static enum dc_aspect_ratio
5305 get_aspect_ratio(const struct drm_display_mode *mode_in)
5306 {
5307 	/* 1-1 mapping, since both enums follow the HDMI spec. */
5308 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5309 }
5310 
5311 static enum dc_color_space
5312 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5313 {
5314 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
5315 
5316 	switch (dc_crtc_timing->pixel_encoding)	{
5317 	case PIXEL_ENCODING_YCBCR422:
5318 	case PIXEL_ENCODING_YCBCR444:
5319 	case PIXEL_ENCODING_YCBCR420:
5320 	{
5321 		/*
5322 		 * 27030khz is the separation point between HDTV and SDTV
5323 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
5324 		 * respectively
5325 		 */
5326 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
5327 			if (dc_crtc_timing->flags.Y_ONLY)
5328 				color_space =
5329 					COLOR_SPACE_YCBCR709_LIMITED;
5330 			else
5331 				color_space = COLOR_SPACE_YCBCR709;
5332 		} else {
5333 			if (dc_crtc_timing->flags.Y_ONLY)
5334 				color_space =
5335 					COLOR_SPACE_YCBCR601_LIMITED;
5336 			else
5337 				color_space = COLOR_SPACE_YCBCR601;
5338 		}
5339 
5340 	}
5341 	break;
5342 	case PIXEL_ENCODING_RGB:
5343 		color_space = COLOR_SPACE_SRGB;
5344 		break;
5345 
5346 	default:
5347 		WARN_ON(1);
5348 		break;
5349 	}
5350 
5351 	return color_space;
5352 }
5353 
5354 static bool adjust_colour_depth_from_display_info(
5355 	struct dc_crtc_timing *timing_out,
5356 	const struct drm_display_info *info)
5357 {
5358 	enum dc_color_depth depth = timing_out->display_color_depth;
5359 	int normalized_clk;
5360 
5361 	do {
5362 		normalized_clk = timing_out->pix_clk_100hz / 10;
5363 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5364 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5365 			normalized_clk /= 2;
5366 		/* Adjusting pix clock following on HDMI spec based on colour depth */
5367 		switch (depth) {
5368 		case COLOR_DEPTH_888:
5369 			break;
5370 		case COLOR_DEPTH_101010:
5371 			normalized_clk = (normalized_clk * 30) / 24;
5372 			break;
5373 		case COLOR_DEPTH_121212:
5374 			normalized_clk = (normalized_clk * 36) / 24;
5375 			break;
5376 		case COLOR_DEPTH_161616:
5377 			normalized_clk = (normalized_clk * 48) / 24;
5378 			break;
5379 		default:
5380 			/* The above depths are the only ones valid for HDMI. */
5381 			return false;
5382 		}
5383 		if (normalized_clk <= info->max_tmds_clock) {
5384 			timing_out->display_color_depth = depth;
5385 			return true;
5386 		}
5387 	} while (--depth > COLOR_DEPTH_666);
5388 	return false;
5389 }
5390 
5391 static void fill_stream_properties_from_drm_display_mode(
5392 	struct dc_stream_state *stream,
5393 	const struct drm_display_mode *mode_in,
5394 	const struct drm_connector *connector,
5395 	const struct drm_connector_state *connector_state,
5396 	const struct dc_stream_state *old_stream,
5397 	int requested_bpc)
5398 {
5399 	struct dc_crtc_timing *timing_out = &stream->timing;
5400 	const struct drm_display_info *info = &connector->display_info;
5401 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5402 	struct hdmi_vendor_infoframe hv_frame;
5403 	struct hdmi_avi_infoframe avi_frame;
5404 
5405 	memset(&hv_frame, 0, sizeof(hv_frame));
5406 	memset(&avi_frame, 0, sizeof(avi_frame));
5407 
5408 	timing_out->h_border_left = 0;
5409 	timing_out->h_border_right = 0;
5410 	timing_out->v_border_top = 0;
5411 	timing_out->v_border_bottom = 0;
5412 	/* TODO: un-hardcode */
5413 	if (drm_mode_is_420_only(info, mode_in)
5414 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5415 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5416 	else if (drm_mode_is_420_also(info, mode_in)
5417 			&& aconnector->force_yuv420_output)
5418 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5419 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5420 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5421 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5422 	else
5423 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5424 
5425 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5426 	timing_out->display_color_depth = convert_color_depth_from_display_info(
5427 		connector,
5428 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5429 		requested_bpc);
5430 	timing_out->scan_type = SCANNING_TYPE_NODATA;
5431 	timing_out->hdmi_vic = 0;
5432 
5433 	if (old_stream) {
5434 		timing_out->vic = old_stream->timing.vic;
5435 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5436 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5437 	} else {
5438 		timing_out->vic = drm_match_cea_mode(mode_in);
5439 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5440 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5441 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5442 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5443 	}
5444 
5445 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5446 		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5447 		timing_out->vic = avi_frame.video_code;
5448 		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5449 		timing_out->hdmi_vic = hv_frame.vic;
5450 	}
5451 
5452 	if (is_freesync_video_mode(mode_in, aconnector)) {
5453 		timing_out->h_addressable = mode_in->hdisplay;
5454 		timing_out->h_total = mode_in->htotal;
5455 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5456 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5457 		timing_out->v_total = mode_in->vtotal;
5458 		timing_out->v_addressable = mode_in->vdisplay;
5459 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5460 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5461 		timing_out->pix_clk_100hz = mode_in->clock * 10;
5462 	} else {
5463 		timing_out->h_addressable = mode_in->crtc_hdisplay;
5464 		timing_out->h_total = mode_in->crtc_htotal;
5465 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5466 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5467 		timing_out->v_total = mode_in->crtc_vtotal;
5468 		timing_out->v_addressable = mode_in->crtc_vdisplay;
5469 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5470 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5471 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5472 	}
5473 
5474 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5475 
5476 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5477 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5478 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5479 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5480 		    drm_mode_is_420_also(info, mode_in) &&
5481 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5482 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5483 			adjust_colour_depth_from_display_info(timing_out, info);
5484 		}
5485 	}
5486 
5487 	stream->output_color_space = get_output_color_space(timing_out);
5488 }
5489 
5490 static void fill_audio_info(struct audio_info *audio_info,
5491 			    const struct drm_connector *drm_connector,
5492 			    const struct dc_sink *dc_sink)
5493 {
5494 	int i = 0;
5495 	int cea_revision = 0;
5496 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5497 
5498 	audio_info->manufacture_id = edid_caps->manufacturer_id;
5499 	audio_info->product_id = edid_caps->product_id;
5500 
5501 	cea_revision = drm_connector->display_info.cea_rev;
5502 
5503 	strscpy(audio_info->display_name,
5504 		edid_caps->display_name,
5505 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5506 
5507 	if (cea_revision >= 3) {
5508 		audio_info->mode_count = edid_caps->audio_mode_count;
5509 
5510 		for (i = 0; i < audio_info->mode_count; ++i) {
5511 			audio_info->modes[i].format_code =
5512 					(enum audio_format_code)
5513 					(edid_caps->audio_modes[i].format_code);
5514 			audio_info->modes[i].channel_count =
5515 					edid_caps->audio_modes[i].channel_count;
5516 			audio_info->modes[i].sample_rates.all =
5517 					edid_caps->audio_modes[i].sample_rate;
5518 			audio_info->modes[i].sample_size =
5519 					edid_caps->audio_modes[i].sample_size;
5520 		}
5521 	}
5522 
5523 	audio_info->flags.all = edid_caps->speaker_flags;
5524 
5525 	/* TODO: We only check for the progressive mode, check for interlace mode too */
5526 	if (drm_connector->latency_present[0]) {
5527 		audio_info->video_latency = drm_connector->video_latency[0];
5528 		audio_info->audio_latency = drm_connector->audio_latency[0];
5529 	}
5530 
5531 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5532 
5533 }
5534 
5535 static void
5536 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5537 				      struct drm_display_mode *dst_mode)
5538 {
5539 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5540 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5541 	dst_mode->crtc_clock = src_mode->crtc_clock;
5542 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5543 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5544 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5545 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5546 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
5547 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
5548 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5549 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5550 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5551 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5552 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5553 }
5554 
5555 static void
5556 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5557 					const struct drm_display_mode *native_mode,
5558 					bool scale_enabled)
5559 {
5560 	if (scale_enabled) {
5561 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5562 	} else if (native_mode->clock == drm_mode->clock &&
5563 			native_mode->htotal == drm_mode->htotal &&
5564 			native_mode->vtotal == drm_mode->vtotal) {
5565 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5566 	} else {
5567 		/* no scaling nor amdgpu inserted, no need to patch */
5568 	}
5569 }
5570 
5571 static struct dc_sink *
5572 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5573 {
5574 	struct dc_sink_init_data sink_init_data = { 0 };
5575 	struct dc_sink *sink = NULL;
5576 
5577 	sink_init_data.link = aconnector->dc_link;
5578 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5579 
5580 	sink = dc_sink_create(&sink_init_data);
5581 	if (!sink) {
5582 		DRM_ERROR("Failed to create sink!\n");
5583 		return NULL;
5584 	}
5585 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5586 
5587 	return sink;
5588 }
5589 
5590 static void set_multisync_trigger_params(
5591 		struct dc_stream_state *stream)
5592 {
5593 	struct dc_stream_state *master = NULL;
5594 
5595 	if (stream->triggered_crtc_reset.enabled) {
5596 		master = stream->triggered_crtc_reset.event_source;
5597 		stream->triggered_crtc_reset.event =
5598 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5599 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5600 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5601 	}
5602 }
5603 
5604 static void set_master_stream(struct dc_stream_state *stream_set[],
5605 			      int stream_count)
5606 {
5607 	int j, highest_rfr = 0, master_stream = 0;
5608 
5609 	for (j = 0;  j < stream_count; j++) {
5610 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5611 			int refresh_rate = 0;
5612 
5613 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5614 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5615 			if (refresh_rate > highest_rfr) {
5616 				highest_rfr = refresh_rate;
5617 				master_stream = j;
5618 			}
5619 		}
5620 	}
5621 	for (j = 0;  j < stream_count; j++) {
5622 		if (stream_set[j])
5623 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5624 	}
5625 }
5626 
5627 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5628 {
5629 	int i = 0;
5630 	struct dc_stream_state *stream;
5631 
5632 	if (context->stream_count < 2)
5633 		return;
5634 	for (i = 0; i < context->stream_count ; i++) {
5635 		if (!context->streams[i])
5636 			continue;
5637 		/*
5638 		 * TODO: add a function to read AMD VSDB bits and set
5639 		 * crtc_sync_master.multi_sync_enabled flag
5640 		 * For now it's set to false
5641 		 */
5642 	}
5643 
5644 	set_master_stream(context->streams, context->stream_count);
5645 
5646 	for (i = 0; i < context->stream_count ; i++) {
5647 		stream = context->streams[i];
5648 
5649 		if (!stream)
5650 			continue;
5651 
5652 		set_multisync_trigger_params(stream);
5653 	}
5654 }
5655 
5656 /**
5657  * DOC: FreeSync Video
5658  *
5659  * When a userspace application wants to play a video, the content follows a
5660  * standard format definition that usually specifies the FPS for that format.
5661  * The below list illustrates some video format and the expected FPS,
5662  * respectively:
5663  *
5664  * - TV/NTSC (23.976 FPS)
5665  * - Cinema (24 FPS)
5666  * - TV/PAL (25 FPS)
5667  * - TV/NTSC (29.97 FPS)
5668  * - TV/NTSC (30 FPS)
5669  * - Cinema HFR (48 FPS)
5670  * - TV/PAL (50 FPS)
5671  * - Commonly used (60 FPS)
5672  * - Multiples of 24 (48,72,96 FPS)
5673  *
5674  * The list of standards video format is not huge and can be added to the
5675  * connector modeset list beforehand. With that, userspace can leverage
5676  * FreeSync to extends the front porch in order to attain the target refresh
5677  * rate. Such a switch will happen seamlessly, without screen blanking or
5678  * reprogramming of the output in any other way. If the userspace requests a
5679  * modesetting change compatible with FreeSync modes that only differ in the
5680  * refresh rate, DC will skip the full update and avoid blink during the
5681  * transition. For example, the video player can change the modesetting from
5682  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5683  * causing any display blink. This same concept can be applied to a mode
5684  * setting change.
5685  */
5686 static struct drm_display_mode *
5687 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5688 		bool use_probed_modes)
5689 {
5690 	struct drm_display_mode *m, *m_pref = NULL;
5691 	u16 current_refresh, highest_refresh;
5692 	struct list_head *list_head = use_probed_modes ?
5693 		&aconnector->base.probed_modes :
5694 		&aconnector->base.modes;
5695 
5696 	if (aconnector->freesync_vid_base.clock != 0)
5697 		return &aconnector->freesync_vid_base;
5698 
5699 	/* Find the preferred mode */
5700 	list_for_each_entry(m, list_head, head) {
5701 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
5702 			m_pref = m;
5703 			break;
5704 		}
5705 	}
5706 
5707 	if (!m_pref) {
5708 		/* Probably an EDID with no preferred mode. Fallback to first entry */
5709 		m_pref = list_first_entry_or_null(
5710 				&aconnector->base.modes, struct drm_display_mode, head);
5711 		if (!m_pref) {
5712 			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5713 			return NULL;
5714 		}
5715 	}
5716 
5717 	highest_refresh = drm_mode_vrefresh(m_pref);
5718 
5719 	/*
5720 	 * Find the mode with highest refresh rate with same resolution.
5721 	 * For some monitors, preferred mode is not the mode with highest
5722 	 * supported refresh rate.
5723 	 */
5724 	list_for_each_entry(m, list_head, head) {
5725 		current_refresh  = drm_mode_vrefresh(m);
5726 
5727 		if (m->hdisplay == m_pref->hdisplay &&
5728 		    m->vdisplay == m_pref->vdisplay &&
5729 		    highest_refresh < current_refresh) {
5730 			highest_refresh = current_refresh;
5731 			m_pref = m;
5732 		}
5733 	}
5734 
5735 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5736 	return m_pref;
5737 }
5738 
5739 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5740 		struct amdgpu_dm_connector *aconnector)
5741 {
5742 	struct drm_display_mode *high_mode;
5743 	int timing_diff;
5744 
5745 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
5746 	if (!high_mode || !mode)
5747 		return false;
5748 
5749 	timing_diff = high_mode->vtotal - mode->vtotal;
5750 
5751 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5752 	    high_mode->hdisplay != mode->hdisplay ||
5753 	    high_mode->vdisplay != mode->vdisplay ||
5754 	    high_mode->hsync_start != mode->hsync_start ||
5755 	    high_mode->hsync_end != mode->hsync_end ||
5756 	    high_mode->htotal != mode->htotal ||
5757 	    high_mode->hskew != mode->hskew ||
5758 	    high_mode->vscan != mode->vscan ||
5759 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
5760 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
5761 		return false;
5762 	else
5763 		return true;
5764 }
5765 
5766 #if defined(CONFIG_DRM_AMD_DC_DCN)
5767 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5768 			    struct dc_sink *sink, struct dc_stream_state *stream,
5769 			    struct dsc_dec_dpcd_caps *dsc_caps)
5770 {
5771 	stream->timing.flags.DSC = 0;
5772 	dsc_caps->is_dsc_supported = false;
5773 
5774 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5775 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
5776 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5777 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5778 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5779 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5780 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5781 				dsc_caps);
5782 	}
5783 }
5784 
5785 
5786 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5787 				    struct dc_sink *sink, struct dc_stream_state *stream,
5788 				    struct dsc_dec_dpcd_caps *dsc_caps,
5789 				    uint32_t max_dsc_target_bpp_limit_override)
5790 {
5791 	const struct dc_link_settings *verified_link_cap = NULL;
5792 	u32 link_bw_in_kbps;
5793 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
5794 	struct dc *dc = sink->ctx->dc;
5795 	struct dc_dsc_bw_range bw_range = {0};
5796 	struct dc_dsc_config dsc_cfg = {0};
5797 
5798 	verified_link_cap = dc_link_get_link_cap(stream->link);
5799 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5800 	edp_min_bpp_x16 = 8 * 16;
5801 	edp_max_bpp_x16 = 8 * 16;
5802 
5803 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5804 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5805 
5806 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
5807 		edp_min_bpp_x16 = edp_max_bpp_x16;
5808 
5809 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5810 				dc->debug.dsc_min_slice_height_override,
5811 				edp_min_bpp_x16, edp_max_bpp_x16,
5812 				dsc_caps,
5813 				&stream->timing,
5814 				&bw_range)) {
5815 
5816 		if (bw_range.max_kbps < link_bw_in_kbps) {
5817 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5818 					dsc_caps,
5819 					dc->debug.dsc_min_slice_height_override,
5820 					max_dsc_target_bpp_limit_override,
5821 					0,
5822 					&stream->timing,
5823 					&dsc_cfg)) {
5824 				stream->timing.dsc_cfg = dsc_cfg;
5825 				stream->timing.flags.DSC = 1;
5826 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5827 			}
5828 			return;
5829 		}
5830 	}
5831 
5832 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5833 				dsc_caps,
5834 				dc->debug.dsc_min_slice_height_override,
5835 				max_dsc_target_bpp_limit_override,
5836 				link_bw_in_kbps,
5837 				&stream->timing,
5838 				&dsc_cfg)) {
5839 		stream->timing.dsc_cfg = dsc_cfg;
5840 		stream->timing.flags.DSC = 1;
5841 	}
5842 }
5843 
5844 
5845 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5846 					struct dc_sink *sink, struct dc_stream_state *stream,
5847 					struct dsc_dec_dpcd_caps *dsc_caps)
5848 {
5849 	struct drm_connector *drm_connector = &aconnector->base;
5850 	u32 link_bandwidth_kbps;
5851 	struct dc *dc = sink->ctx->dc;
5852 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
5853 	u32 dsc_max_supported_bw_in_kbps;
5854 	u32 max_dsc_target_bpp_limit_override =
5855 		drm_connector->display_info.max_dsc_bpp;
5856 
5857 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5858 							dc_link_get_link_cap(aconnector->dc_link));
5859 
5860 	/* Set DSC policy according to dsc_clock_en */
5861 	dc_dsc_policy_set_enable_dsc_when_not_needed(
5862 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5863 
5864 	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5865 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5866 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5867 
5868 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5869 
5870 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5871 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5872 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5873 						dsc_caps,
5874 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5875 						max_dsc_target_bpp_limit_override,
5876 						link_bandwidth_kbps,
5877 						&stream->timing,
5878 						&stream->timing.dsc_cfg)) {
5879 				stream->timing.flags.DSC = 1;
5880 				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5881 			}
5882 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5883 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5884 			max_supported_bw_in_kbps = link_bandwidth_kbps;
5885 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5886 
5887 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5888 					max_supported_bw_in_kbps > 0 &&
5889 					dsc_max_supported_bw_in_kbps > 0)
5890 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5891 						dsc_caps,
5892 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5893 						max_dsc_target_bpp_limit_override,
5894 						dsc_max_supported_bw_in_kbps,
5895 						&stream->timing,
5896 						&stream->timing.dsc_cfg)) {
5897 					stream->timing.flags.DSC = 1;
5898 					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5899 									 __func__, drm_connector->name);
5900 				}
5901 		}
5902 	}
5903 
5904 	/* Overwrite the stream flag if DSC is enabled through debugfs */
5905 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5906 		stream->timing.flags.DSC = 1;
5907 
5908 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5909 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5910 
5911 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5912 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5913 
5914 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5915 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5916 }
5917 #endif /* CONFIG_DRM_AMD_DC_DCN */
5918 
5919 static struct dc_stream_state *
5920 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5921 		       const struct drm_display_mode *drm_mode,
5922 		       const struct dm_connector_state *dm_state,
5923 		       const struct dc_stream_state *old_stream,
5924 		       int requested_bpc)
5925 {
5926 	struct drm_display_mode *preferred_mode = NULL;
5927 	struct drm_connector *drm_connector;
5928 	const struct drm_connector_state *con_state =
5929 		dm_state ? &dm_state->base : NULL;
5930 	struct dc_stream_state *stream = NULL;
5931 	struct drm_display_mode mode = *drm_mode;
5932 	struct drm_display_mode saved_mode;
5933 	struct drm_display_mode *freesync_mode = NULL;
5934 	bool native_mode_found = false;
5935 	bool recalculate_timing = false;
5936 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5937 	int mode_refresh;
5938 	int preferred_refresh = 0;
5939 #if defined(CONFIG_DRM_AMD_DC_DCN)
5940 	struct dsc_dec_dpcd_caps dsc_caps;
5941 #endif
5942 
5943 	struct dc_sink *sink = NULL;
5944 
5945 	memset(&saved_mode, 0, sizeof(saved_mode));
5946 
5947 	if (aconnector == NULL) {
5948 		DRM_ERROR("aconnector is NULL!\n");
5949 		return stream;
5950 	}
5951 
5952 	drm_connector = &aconnector->base;
5953 
5954 	if (!aconnector->dc_sink) {
5955 		sink = create_fake_sink(aconnector);
5956 		if (!sink)
5957 			return stream;
5958 	} else {
5959 		sink = aconnector->dc_sink;
5960 		dc_sink_retain(sink);
5961 	}
5962 
5963 	stream = dc_create_stream_for_sink(sink);
5964 
5965 	if (stream == NULL) {
5966 		DRM_ERROR("Failed to create stream for sink!\n");
5967 		goto finish;
5968 	}
5969 
5970 	stream->dm_stream_context = aconnector;
5971 
5972 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5973 		drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5974 
5975 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5976 		/* Search for preferred mode */
5977 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5978 			native_mode_found = true;
5979 			break;
5980 		}
5981 	}
5982 	if (!native_mode_found)
5983 		preferred_mode = list_first_entry_or_null(
5984 				&aconnector->base.modes,
5985 				struct drm_display_mode,
5986 				head);
5987 
5988 	mode_refresh = drm_mode_vrefresh(&mode);
5989 
5990 	if (preferred_mode == NULL) {
5991 		/*
5992 		 * This may not be an error, the use case is when we have no
5993 		 * usermode calls to reset and set mode upon hotplug. In this
5994 		 * case, we call set mode ourselves to restore the previous mode
5995 		 * and the modelist may not be filled in time.
5996 		 */
5997 		DRM_DEBUG_DRIVER("No preferred mode found\n");
5998 	} else {
5999 		recalculate_timing = is_freesync_video_mode(&mode, aconnector);
6000 		if (recalculate_timing) {
6001 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
6002 			drm_mode_copy(&saved_mode, &mode);
6003 			drm_mode_copy(&mode, freesync_mode);
6004 		} else {
6005 			decide_crtc_timing_for_drm_display_mode(
6006 					&mode, preferred_mode, scale);
6007 
6008 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
6009 		}
6010 	}
6011 
6012 	if (recalculate_timing)
6013 		drm_mode_set_crtcinfo(&saved_mode, 0);
6014 	else if (!dm_state)
6015 		drm_mode_set_crtcinfo(&mode, 0);
6016 
6017 	/*
6018 	 * If scaling is enabled and refresh rate didn't change
6019 	 * we copy the vic and polarities of the old timings
6020 	 */
6021 	if (!scale || mode_refresh != preferred_refresh)
6022 		fill_stream_properties_from_drm_display_mode(
6023 			stream, &mode, &aconnector->base, con_state, NULL,
6024 			requested_bpc);
6025 	else
6026 		fill_stream_properties_from_drm_display_mode(
6027 			stream, &mode, &aconnector->base, con_state, old_stream,
6028 			requested_bpc);
6029 
6030 	if (aconnector->timing_changed) {
6031 		DC_LOG_DEBUG("%s: overriding timing for automated test, bpc %d, changing to %d\n",
6032 				__func__,
6033 				stream->timing.display_color_depth,
6034 				aconnector->timing_requested->display_color_depth);
6035 		stream->timing = *aconnector->timing_requested;
6036 	}
6037 
6038 #if defined(CONFIG_DRM_AMD_DC_DCN)
6039 	/* SST DSC determination policy */
6040 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
6041 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
6042 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
6043 #endif
6044 
6045 	update_stream_scaling_settings(&mode, dm_state, stream);
6046 
6047 	fill_audio_info(
6048 		&stream->audio_info,
6049 		drm_connector,
6050 		sink);
6051 
6052 	update_stream_signal(stream, sink);
6053 
6054 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6055 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
6056 
6057 	if (stream->link->psr_settings.psr_feature_enabled) {
6058 		//
6059 		// should decide stream support vsc sdp colorimetry capability
6060 		// before building vsc info packet
6061 		//
6062 		stream->use_vsc_sdp_for_colorimetry = false;
6063 		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
6064 			stream->use_vsc_sdp_for_colorimetry =
6065 				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
6066 		} else {
6067 			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
6068 				stream->use_vsc_sdp_for_colorimetry = true;
6069 		}
6070 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space);
6071 		aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
6072 
6073 	}
6074 finish:
6075 	dc_sink_release(sink);
6076 
6077 	return stream;
6078 }
6079 
6080 static enum drm_connector_status
6081 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
6082 {
6083 	bool connected;
6084 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6085 
6086 	/*
6087 	 * Notes:
6088 	 * 1. This interface is NOT called in context of HPD irq.
6089 	 * 2. This interface *is called* in context of user-mode ioctl. Which
6090 	 * makes it a bad place for *any* MST-related activity.
6091 	 */
6092 
6093 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
6094 	    !aconnector->fake_enable)
6095 		connected = (aconnector->dc_sink != NULL);
6096 	else
6097 		connected = (aconnector->base.force == DRM_FORCE_ON ||
6098 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
6099 
6100 	update_subconnector_property(aconnector);
6101 
6102 	return (connected ? connector_status_connected :
6103 			connector_status_disconnected);
6104 }
6105 
6106 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
6107 					    struct drm_connector_state *connector_state,
6108 					    struct drm_property *property,
6109 					    uint64_t val)
6110 {
6111 	struct drm_device *dev = connector->dev;
6112 	struct amdgpu_device *adev = drm_to_adev(dev);
6113 	struct dm_connector_state *dm_old_state =
6114 		to_dm_connector_state(connector->state);
6115 	struct dm_connector_state *dm_new_state =
6116 		to_dm_connector_state(connector_state);
6117 
6118 	int ret = -EINVAL;
6119 
6120 	if (property == dev->mode_config.scaling_mode_property) {
6121 		enum amdgpu_rmx_type rmx_type;
6122 
6123 		switch (val) {
6124 		case DRM_MODE_SCALE_CENTER:
6125 			rmx_type = RMX_CENTER;
6126 			break;
6127 		case DRM_MODE_SCALE_ASPECT:
6128 			rmx_type = RMX_ASPECT;
6129 			break;
6130 		case DRM_MODE_SCALE_FULLSCREEN:
6131 			rmx_type = RMX_FULL;
6132 			break;
6133 		case DRM_MODE_SCALE_NONE:
6134 		default:
6135 			rmx_type = RMX_OFF;
6136 			break;
6137 		}
6138 
6139 		if (dm_old_state->scaling == rmx_type)
6140 			return 0;
6141 
6142 		dm_new_state->scaling = rmx_type;
6143 		ret = 0;
6144 	} else if (property == adev->mode_info.underscan_hborder_property) {
6145 		dm_new_state->underscan_hborder = val;
6146 		ret = 0;
6147 	} else if (property == adev->mode_info.underscan_vborder_property) {
6148 		dm_new_state->underscan_vborder = val;
6149 		ret = 0;
6150 	} else if (property == adev->mode_info.underscan_property) {
6151 		dm_new_state->underscan_enable = val;
6152 		ret = 0;
6153 	} else if (property == adev->mode_info.abm_level_property) {
6154 		dm_new_state->abm_level = val ?: ABM_LEVEL_IMMEDIATE_DISABLE;
6155 		ret = 0;
6156 	}
6157 
6158 	return ret;
6159 }
6160 
6161 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
6162 					    const struct drm_connector_state *state,
6163 					    struct drm_property *property,
6164 					    uint64_t *val)
6165 {
6166 	struct drm_device *dev = connector->dev;
6167 	struct amdgpu_device *adev = drm_to_adev(dev);
6168 	struct dm_connector_state *dm_state =
6169 		to_dm_connector_state(state);
6170 	int ret = -EINVAL;
6171 
6172 	if (property == dev->mode_config.scaling_mode_property) {
6173 		switch (dm_state->scaling) {
6174 		case RMX_CENTER:
6175 			*val = DRM_MODE_SCALE_CENTER;
6176 			break;
6177 		case RMX_ASPECT:
6178 			*val = DRM_MODE_SCALE_ASPECT;
6179 			break;
6180 		case RMX_FULL:
6181 			*val = DRM_MODE_SCALE_FULLSCREEN;
6182 			break;
6183 		case RMX_OFF:
6184 		default:
6185 			*val = DRM_MODE_SCALE_NONE;
6186 			break;
6187 		}
6188 		ret = 0;
6189 	} else if (property == adev->mode_info.underscan_hborder_property) {
6190 		*val = dm_state->underscan_hborder;
6191 		ret = 0;
6192 	} else if (property == adev->mode_info.underscan_vborder_property) {
6193 		*val = dm_state->underscan_vborder;
6194 		ret = 0;
6195 	} else if (property == adev->mode_info.underscan_property) {
6196 		*val = dm_state->underscan_enable;
6197 		ret = 0;
6198 	} else if (property == adev->mode_info.abm_level_property) {
6199 		*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
6200 			dm_state->abm_level : 0;
6201 		ret = 0;
6202 	}
6203 
6204 	return ret;
6205 }
6206 
6207 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6208 {
6209 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6210 
6211 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6212 }
6213 
6214 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6215 {
6216 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6217 	const struct dc_link *link = aconnector->dc_link;
6218 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6219 	struct amdgpu_display_manager *dm = &adev->dm;
6220 	int i;
6221 
6222 	/*
6223 	 * Call only if mst_mgr was initialized before since it's not done
6224 	 * for all connector types.
6225 	 */
6226 	if (aconnector->mst_mgr.dev)
6227 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6228 
6229 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
6230 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
6231 	for (i = 0; i < dm->num_of_edps; i++) {
6232 		if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6233 			backlight_device_unregister(dm->backlight_dev[i]);
6234 			dm->backlight_dev[i] = NULL;
6235 		}
6236 	}
6237 #endif
6238 
6239 	if (aconnector->dc_em_sink)
6240 		dc_sink_release(aconnector->dc_em_sink);
6241 	aconnector->dc_em_sink = NULL;
6242 	if (aconnector->dc_sink)
6243 		dc_sink_release(aconnector->dc_sink);
6244 	aconnector->dc_sink = NULL;
6245 
6246 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6247 	drm_connector_unregister(connector);
6248 	drm_connector_cleanup(connector);
6249 	if (aconnector->i2c) {
6250 		i2c_del_adapter(&aconnector->i2c->base);
6251 		kfree(aconnector->i2c);
6252 	}
6253 	kfree(aconnector->dm_dp_aux.aux.name);
6254 
6255 	kfree(connector);
6256 }
6257 
6258 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6259 {
6260 	struct dm_connector_state *state =
6261 		to_dm_connector_state(connector->state);
6262 
6263 	if (connector->state)
6264 		__drm_atomic_helper_connector_destroy_state(connector->state);
6265 
6266 	kfree(state);
6267 
6268 	state = kzalloc(sizeof(*state), GFP_KERNEL);
6269 
6270 	if (state) {
6271 		state->scaling = RMX_OFF;
6272 		state->underscan_enable = false;
6273 		state->underscan_hborder = 0;
6274 		state->underscan_vborder = 0;
6275 		state->base.max_requested_bpc = 8;
6276 		state->vcpi_slots = 0;
6277 		state->pbn = 0;
6278 
6279 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6280 			state->abm_level = amdgpu_dm_abm_level ?:
6281 				ABM_LEVEL_IMMEDIATE_DISABLE;
6282 
6283 		__drm_atomic_helper_connector_reset(connector, &state->base);
6284 	}
6285 }
6286 
6287 struct drm_connector_state *
6288 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6289 {
6290 	struct dm_connector_state *state =
6291 		to_dm_connector_state(connector->state);
6292 
6293 	struct dm_connector_state *new_state =
6294 			kmemdup(state, sizeof(*state), GFP_KERNEL);
6295 
6296 	if (!new_state)
6297 		return NULL;
6298 
6299 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6300 
6301 	new_state->freesync_capable = state->freesync_capable;
6302 	new_state->abm_level = state->abm_level;
6303 	new_state->scaling = state->scaling;
6304 	new_state->underscan_enable = state->underscan_enable;
6305 	new_state->underscan_hborder = state->underscan_hborder;
6306 	new_state->underscan_vborder = state->underscan_vborder;
6307 	new_state->vcpi_slots = state->vcpi_slots;
6308 	new_state->pbn = state->pbn;
6309 	return &new_state->base;
6310 }
6311 
6312 static int
6313 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6314 {
6315 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6316 		to_amdgpu_dm_connector(connector);
6317 	int r;
6318 
6319 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6320 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6321 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6322 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6323 		if (r)
6324 			return r;
6325 	}
6326 
6327 #if defined(CONFIG_DEBUG_FS)
6328 	connector_debugfs_init(amdgpu_dm_connector);
6329 #endif
6330 
6331 	return 0;
6332 }
6333 
6334 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6335 	.reset = amdgpu_dm_connector_funcs_reset,
6336 	.detect = amdgpu_dm_connector_detect,
6337 	.fill_modes = drm_helper_probe_single_connector_modes,
6338 	.destroy = amdgpu_dm_connector_destroy,
6339 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6340 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6341 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6342 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6343 	.late_register = amdgpu_dm_connector_late_register,
6344 	.early_unregister = amdgpu_dm_connector_unregister
6345 };
6346 
6347 static int get_modes(struct drm_connector *connector)
6348 {
6349 	return amdgpu_dm_connector_get_modes(connector);
6350 }
6351 
6352 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6353 {
6354 	struct dc_sink_init_data init_params = {
6355 			.link = aconnector->dc_link,
6356 			.sink_signal = SIGNAL_TYPE_VIRTUAL
6357 	};
6358 	struct edid *edid;
6359 
6360 	if (!aconnector->base.edid_blob_ptr) {
6361 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6362 				aconnector->base.name);
6363 
6364 		aconnector->base.force = DRM_FORCE_OFF;
6365 		aconnector->base.override_edid = false;
6366 		return;
6367 	}
6368 
6369 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6370 
6371 	aconnector->edid = edid;
6372 
6373 	aconnector->dc_em_sink = dc_link_add_remote_sink(
6374 		aconnector->dc_link,
6375 		(uint8_t *)edid,
6376 		(edid->extensions + 1) * EDID_LENGTH,
6377 		&init_params);
6378 
6379 	if (aconnector->base.force == DRM_FORCE_ON) {
6380 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
6381 		aconnector->dc_link->local_sink :
6382 		aconnector->dc_em_sink;
6383 		dc_sink_retain(aconnector->dc_sink);
6384 	}
6385 }
6386 
6387 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6388 {
6389 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6390 
6391 	/*
6392 	 * In case of headless boot with force on for DP managed connector
6393 	 * Those settings have to be != 0 to get initial modeset
6394 	 */
6395 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6396 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6397 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6398 	}
6399 
6400 
6401 	aconnector->base.override_edid = true;
6402 	create_eml_sink(aconnector);
6403 }
6404 
6405 struct dc_stream_state *
6406 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6407 				const struct drm_display_mode *drm_mode,
6408 				const struct dm_connector_state *dm_state,
6409 				const struct dc_stream_state *old_stream)
6410 {
6411 	struct drm_connector *connector = &aconnector->base;
6412 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6413 	struct dc_stream_state *stream;
6414 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6415 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6416 	enum dc_status dc_result = DC_OK;
6417 
6418 	do {
6419 		stream = create_stream_for_sink(aconnector, drm_mode,
6420 						dm_state, old_stream,
6421 						requested_bpc);
6422 		if (stream == NULL) {
6423 			DRM_ERROR("Failed to create stream for sink!\n");
6424 			break;
6425 		}
6426 
6427 		dc_result = dc_validate_stream(adev->dm.dc, stream);
6428 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6429 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6430 
6431 		if (dc_result != DC_OK) {
6432 			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6433 				      drm_mode->hdisplay,
6434 				      drm_mode->vdisplay,
6435 				      drm_mode->clock,
6436 				      dc_result,
6437 				      dc_status_to_str(dc_result));
6438 
6439 			dc_stream_release(stream);
6440 			stream = NULL;
6441 			requested_bpc -= 2; /* lower bpc to retry validation */
6442 		}
6443 
6444 	} while (stream == NULL && requested_bpc >= 6);
6445 
6446 	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6447 		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6448 
6449 		aconnector->force_yuv420_output = true;
6450 		stream = create_validate_stream_for_sink(aconnector, drm_mode,
6451 						dm_state, old_stream);
6452 		aconnector->force_yuv420_output = false;
6453 	}
6454 
6455 	return stream;
6456 }
6457 
6458 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6459 				   struct drm_display_mode *mode)
6460 {
6461 	int result = MODE_ERROR;
6462 	struct dc_sink *dc_sink;
6463 	/* TODO: Unhardcode stream count */
6464 	struct dc_stream_state *stream;
6465 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6466 
6467 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6468 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
6469 		return result;
6470 
6471 	/*
6472 	 * Only run this the first time mode_valid is called to initilialize
6473 	 * EDID mgmt
6474 	 */
6475 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6476 		!aconnector->dc_em_sink)
6477 		handle_edid_mgmt(aconnector);
6478 
6479 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6480 
6481 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6482 				aconnector->base.force != DRM_FORCE_ON) {
6483 		DRM_ERROR("dc_sink is NULL!\n");
6484 		goto fail;
6485 	}
6486 
6487 	stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6488 	if (stream) {
6489 		dc_stream_release(stream);
6490 		result = MODE_OK;
6491 	}
6492 
6493 fail:
6494 	/* TODO: error handling*/
6495 	return result;
6496 }
6497 
6498 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6499 				struct dc_info_packet *out)
6500 {
6501 	struct hdmi_drm_infoframe frame;
6502 	unsigned char buf[30]; /* 26 + 4 */
6503 	ssize_t len;
6504 	int ret, i;
6505 
6506 	memset(out, 0, sizeof(*out));
6507 
6508 	if (!state->hdr_output_metadata)
6509 		return 0;
6510 
6511 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6512 	if (ret)
6513 		return ret;
6514 
6515 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6516 	if (len < 0)
6517 		return (int)len;
6518 
6519 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
6520 	if (len != 30)
6521 		return -EINVAL;
6522 
6523 	/* Prepare the infopacket for DC. */
6524 	switch (state->connector->connector_type) {
6525 	case DRM_MODE_CONNECTOR_HDMIA:
6526 		out->hb0 = 0x87; /* type */
6527 		out->hb1 = 0x01; /* version */
6528 		out->hb2 = 0x1A; /* length */
6529 		out->sb[0] = buf[3]; /* checksum */
6530 		i = 1;
6531 		break;
6532 
6533 	case DRM_MODE_CONNECTOR_DisplayPort:
6534 	case DRM_MODE_CONNECTOR_eDP:
6535 		out->hb0 = 0x00; /* sdp id, zero */
6536 		out->hb1 = 0x87; /* type */
6537 		out->hb2 = 0x1D; /* payload len - 1 */
6538 		out->hb3 = (0x13 << 2); /* sdp version */
6539 		out->sb[0] = 0x01; /* version */
6540 		out->sb[1] = 0x1A; /* length */
6541 		i = 2;
6542 		break;
6543 
6544 	default:
6545 		return -EINVAL;
6546 	}
6547 
6548 	memcpy(&out->sb[i], &buf[4], 26);
6549 	out->valid = true;
6550 
6551 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6552 		       sizeof(out->sb), false);
6553 
6554 	return 0;
6555 }
6556 
6557 static int
6558 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6559 				 struct drm_atomic_state *state)
6560 {
6561 	struct drm_connector_state *new_con_state =
6562 		drm_atomic_get_new_connector_state(state, conn);
6563 	struct drm_connector_state *old_con_state =
6564 		drm_atomic_get_old_connector_state(state, conn);
6565 	struct drm_crtc *crtc = new_con_state->crtc;
6566 	struct drm_crtc_state *new_crtc_state;
6567 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6568 	int ret;
6569 
6570 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
6571 
6572 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6573 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6574 		if (ret < 0)
6575 			return ret;
6576 	}
6577 
6578 	if (!crtc)
6579 		return 0;
6580 
6581 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6582 		struct dc_info_packet hdr_infopacket;
6583 
6584 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6585 		if (ret)
6586 			return ret;
6587 
6588 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6589 		if (IS_ERR(new_crtc_state))
6590 			return PTR_ERR(new_crtc_state);
6591 
6592 		/*
6593 		 * DC considers the stream backends changed if the
6594 		 * static metadata changes. Forcing the modeset also
6595 		 * gives a simple way for userspace to switch from
6596 		 * 8bpc to 10bpc when setting the metadata to enter
6597 		 * or exit HDR.
6598 		 *
6599 		 * Changing the static metadata after it's been
6600 		 * set is permissible, however. So only force a
6601 		 * modeset if we're entering or exiting HDR.
6602 		 */
6603 		new_crtc_state->mode_changed =
6604 			!old_con_state->hdr_output_metadata ||
6605 			!new_con_state->hdr_output_metadata;
6606 	}
6607 
6608 	return 0;
6609 }
6610 
6611 static const struct drm_connector_helper_funcs
6612 amdgpu_dm_connector_helper_funcs = {
6613 	/*
6614 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
6615 	 * modes will be filtered by drm_mode_validate_size(), and those modes
6616 	 * are missing after user start lightdm. So we need to renew modes list.
6617 	 * in get_modes call back, not just return the modes count
6618 	 */
6619 	.get_modes = get_modes,
6620 	.mode_valid = amdgpu_dm_connector_mode_valid,
6621 	.atomic_check = amdgpu_dm_connector_atomic_check,
6622 };
6623 
6624 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6625 {
6626 
6627 }
6628 
6629 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6630 {
6631 	switch (display_color_depth) {
6632 	case COLOR_DEPTH_666:
6633 		return 6;
6634 	case COLOR_DEPTH_888:
6635 		return 8;
6636 	case COLOR_DEPTH_101010:
6637 		return 10;
6638 	case COLOR_DEPTH_121212:
6639 		return 12;
6640 	case COLOR_DEPTH_141414:
6641 		return 14;
6642 	case COLOR_DEPTH_161616:
6643 		return 16;
6644 	default:
6645 		break;
6646 	}
6647 	return 0;
6648 }
6649 
6650 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6651 					  struct drm_crtc_state *crtc_state,
6652 					  struct drm_connector_state *conn_state)
6653 {
6654 	struct drm_atomic_state *state = crtc_state->state;
6655 	struct drm_connector *connector = conn_state->connector;
6656 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6657 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6658 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6659 	struct drm_dp_mst_topology_mgr *mst_mgr;
6660 	struct drm_dp_mst_port *mst_port;
6661 	struct drm_dp_mst_topology_state *mst_state;
6662 	enum dc_color_depth color_depth;
6663 	int clock, bpp = 0;
6664 	bool is_y420 = false;
6665 
6666 	if (!aconnector->port)
6667 		return 0;
6668 
6669 	mst_port = aconnector->port;
6670 	mst_mgr = &aconnector->mst_port->mst_mgr;
6671 
6672 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6673 		return 0;
6674 
6675 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6676 	if (IS_ERR(mst_state))
6677 		return PTR_ERR(mst_state);
6678 
6679 	if (!mst_state->pbn_div)
6680 		mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_port->dc_link);
6681 
6682 	if (!state->duplicated) {
6683 		int max_bpc = conn_state->max_requested_bpc;
6684 
6685 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6686 			  aconnector->force_yuv420_output;
6687 		color_depth = convert_color_depth_from_display_info(connector,
6688 								    is_y420,
6689 								    max_bpc);
6690 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6691 		clock = adjusted_mode->clock;
6692 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6693 	}
6694 
6695 	dm_new_connector_state->vcpi_slots =
6696 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6697 					      dm_new_connector_state->pbn);
6698 	if (dm_new_connector_state->vcpi_slots < 0) {
6699 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6700 		return dm_new_connector_state->vcpi_slots;
6701 	}
6702 	return 0;
6703 }
6704 
6705 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6706 	.disable = dm_encoder_helper_disable,
6707 	.atomic_check = dm_encoder_helper_atomic_check
6708 };
6709 
6710 #if defined(CONFIG_DRM_AMD_DC_DCN)
6711 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6712 					    struct dc_state *dc_state,
6713 					    struct dsc_mst_fairness_vars *vars)
6714 {
6715 	struct dc_stream_state *stream = NULL;
6716 	struct drm_connector *connector;
6717 	struct drm_connector_state *new_con_state;
6718 	struct amdgpu_dm_connector *aconnector;
6719 	struct dm_connector_state *dm_conn_state;
6720 	int i, j, ret;
6721 	int vcpi, pbn_div, pbn, slot_num = 0;
6722 
6723 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
6724 
6725 		aconnector = to_amdgpu_dm_connector(connector);
6726 
6727 		if (!aconnector->port)
6728 			continue;
6729 
6730 		if (!new_con_state || !new_con_state->crtc)
6731 			continue;
6732 
6733 		dm_conn_state = to_dm_connector_state(new_con_state);
6734 
6735 		for (j = 0; j < dc_state->stream_count; j++) {
6736 			stream = dc_state->streams[j];
6737 			if (!stream)
6738 				continue;
6739 
6740 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6741 				break;
6742 
6743 			stream = NULL;
6744 		}
6745 
6746 		if (!stream)
6747 			continue;
6748 
6749 		pbn_div = dm_mst_get_pbn_divider(stream->link);
6750 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
6751 		for (j = 0; j < dc_state->stream_count; j++) {
6752 			if (vars[j].aconnector == aconnector) {
6753 				pbn = vars[j].pbn;
6754 				break;
6755 			}
6756 		}
6757 
6758 		if (j == dc_state->stream_count)
6759 			continue;
6760 
6761 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
6762 
6763 		if (stream->timing.flags.DSC != 1) {
6764 			dm_conn_state->pbn = pbn;
6765 			dm_conn_state->vcpi_slots = slot_num;
6766 
6767 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->port,
6768 							   dm_conn_state->pbn, false);
6769 			if (ret < 0)
6770 				return ret;
6771 
6772 			continue;
6773 		}
6774 
6775 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->port, pbn, true);
6776 		if (vcpi < 0)
6777 			return vcpi;
6778 
6779 		dm_conn_state->pbn = pbn;
6780 		dm_conn_state->vcpi_slots = vcpi;
6781 	}
6782 	return 0;
6783 }
6784 #endif
6785 
6786 static int to_drm_connector_type(enum amd_signal_type st)
6787 {
6788 	switch (st) {
6789 	case SIGNAL_TYPE_HDMI_TYPE_A:
6790 		return DRM_MODE_CONNECTOR_HDMIA;
6791 	case SIGNAL_TYPE_EDP:
6792 		return DRM_MODE_CONNECTOR_eDP;
6793 	case SIGNAL_TYPE_LVDS:
6794 		return DRM_MODE_CONNECTOR_LVDS;
6795 	case SIGNAL_TYPE_RGB:
6796 		return DRM_MODE_CONNECTOR_VGA;
6797 	case SIGNAL_TYPE_DISPLAY_PORT:
6798 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
6799 		return DRM_MODE_CONNECTOR_DisplayPort;
6800 	case SIGNAL_TYPE_DVI_DUAL_LINK:
6801 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
6802 		return DRM_MODE_CONNECTOR_DVID;
6803 	case SIGNAL_TYPE_VIRTUAL:
6804 		return DRM_MODE_CONNECTOR_VIRTUAL;
6805 
6806 	default:
6807 		return DRM_MODE_CONNECTOR_Unknown;
6808 	}
6809 }
6810 
6811 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6812 {
6813 	struct drm_encoder *encoder;
6814 
6815 	/* There is only one encoder per connector */
6816 	drm_connector_for_each_possible_encoder(connector, encoder)
6817 		return encoder;
6818 
6819 	return NULL;
6820 }
6821 
6822 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6823 {
6824 	struct drm_encoder *encoder;
6825 	struct amdgpu_encoder *amdgpu_encoder;
6826 
6827 	encoder = amdgpu_dm_connector_to_encoder(connector);
6828 
6829 	if (encoder == NULL)
6830 		return;
6831 
6832 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6833 
6834 	amdgpu_encoder->native_mode.clock = 0;
6835 
6836 	if (!list_empty(&connector->probed_modes)) {
6837 		struct drm_display_mode *preferred_mode = NULL;
6838 
6839 		list_for_each_entry(preferred_mode,
6840 				    &connector->probed_modes,
6841 				    head) {
6842 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6843 				amdgpu_encoder->native_mode = *preferred_mode;
6844 
6845 			break;
6846 		}
6847 
6848 	}
6849 }
6850 
6851 static struct drm_display_mode *
6852 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6853 			     char *name,
6854 			     int hdisplay, int vdisplay)
6855 {
6856 	struct drm_device *dev = encoder->dev;
6857 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6858 	struct drm_display_mode *mode = NULL;
6859 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6860 
6861 	mode = drm_mode_duplicate(dev, native_mode);
6862 
6863 	if (mode == NULL)
6864 		return NULL;
6865 
6866 	mode->hdisplay = hdisplay;
6867 	mode->vdisplay = vdisplay;
6868 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6869 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6870 
6871 	return mode;
6872 
6873 }
6874 
6875 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6876 						 struct drm_connector *connector)
6877 {
6878 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6879 	struct drm_display_mode *mode = NULL;
6880 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6881 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6882 				to_amdgpu_dm_connector(connector);
6883 	int i;
6884 	int n;
6885 	struct mode_size {
6886 		char name[DRM_DISPLAY_MODE_LEN];
6887 		int w;
6888 		int h;
6889 	} common_modes[] = {
6890 		{  "640x480",  640,  480},
6891 		{  "800x600",  800,  600},
6892 		{ "1024x768", 1024,  768},
6893 		{ "1280x720", 1280,  720},
6894 		{ "1280x800", 1280,  800},
6895 		{"1280x1024", 1280, 1024},
6896 		{ "1440x900", 1440,  900},
6897 		{"1680x1050", 1680, 1050},
6898 		{"1600x1200", 1600, 1200},
6899 		{"1920x1080", 1920, 1080},
6900 		{"1920x1200", 1920, 1200}
6901 	};
6902 
6903 	n = ARRAY_SIZE(common_modes);
6904 
6905 	for (i = 0; i < n; i++) {
6906 		struct drm_display_mode *curmode = NULL;
6907 		bool mode_existed = false;
6908 
6909 		if (common_modes[i].w > native_mode->hdisplay ||
6910 		    common_modes[i].h > native_mode->vdisplay ||
6911 		   (common_modes[i].w == native_mode->hdisplay &&
6912 		    common_modes[i].h == native_mode->vdisplay))
6913 			continue;
6914 
6915 		list_for_each_entry(curmode, &connector->probed_modes, head) {
6916 			if (common_modes[i].w == curmode->hdisplay &&
6917 			    common_modes[i].h == curmode->vdisplay) {
6918 				mode_existed = true;
6919 				break;
6920 			}
6921 		}
6922 
6923 		if (mode_existed)
6924 			continue;
6925 
6926 		mode = amdgpu_dm_create_common_mode(encoder,
6927 				common_modes[i].name, common_modes[i].w,
6928 				common_modes[i].h);
6929 		if (!mode)
6930 			continue;
6931 
6932 		drm_mode_probed_add(connector, mode);
6933 		amdgpu_dm_connector->num_modes++;
6934 	}
6935 }
6936 
6937 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6938 {
6939 	struct drm_encoder *encoder;
6940 	struct amdgpu_encoder *amdgpu_encoder;
6941 	const struct drm_display_mode *native_mode;
6942 
6943 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6944 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6945 		return;
6946 
6947 	mutex_lock(&connector->dev->mode_config.mutex);
6948 	amdgpu_dm_connector_get_modes(connector);
6949 	mutex_unlock(&connector->dev->mode_config.mutex);
6950 
6951 	encoder = amdgpu_dm_connector_to_encoder(connector);
6952 	if (!encoder)
6953 		return;
6954 
6955 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6956 
6957 	native_mode = &amdgpu_encoder->native_mode;
6958 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6959 		return;
6960 
6961 	drm_connector_set_panel_orientation_with_quirk(connector,
6962 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6963 						       native_mode->hdisplay,
6964 						       native_mode->vdisplay);
6965 }
6966 
6967 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6968 					      struct edid *edid)
6969 {
6970 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6971 			to_amdgpu_dm_connector(connector);
6972 
6973 	if (edid) {
6974 		/* empty probed_modes */
6975 		INIT_LIST_HEAD(&connector->probed_modes);
6976 		amdgpu_dm_connector->num_modes =
6977 				drm_add_edid_modes(connector, edid);
6978 
6979 		/* sorting the probed modes before calling function
6980 		 * amdgpu_dm_get_native_mode() since EDID can have
6981 		 * more than one preferred mode. The modes that are
6982 		 * later in the probed mode list could be of higher
6983 		 * and preferred resolution. For example, 3840x2160
6984 		 * resolution in base EDID preferred timing and 4096x2160
6985 		 * preferred resolution in DID extension block later.
6986 		 */
6987 		drm_mode_sort(&connector->probed_modes);
6988 		amdgpu_dm_get_native_mode(connector);
6989 
6990 		/* Freesync capabilities are reset by calling
6991 		 * drm_add_edid_modes() and need to be
6992 		 * restored here.
6993 		 */
6994 		amdgpu_dm_update_freesync_caps(connector, edid);
6995 	} else {
6996 		amdgpu_dm_connector->num_modes = 0;
6997 	}
6998 }
6999 
7000 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
7001 			      struct drm_display_mode *mode)
7002 {
7003 	struct drm_display_mode *m;
7004 
7005 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
7006 		if (drm_mode_equal(m, mode))
7007 			return true;
7008 	}
7009 
7010 	return false;
7011 }
7012 
7013 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
7014 {
7015 	const struct drm_display_mode *m;
7016 	struct drm_display_mode *new_mode;
7017 	uint i;
7018 	u32 new_modes_count = 0;
7019 
7020 	/* Standard FPS values
7021 	 *
7022 	 * 23.976       - TV/NTSC
7023 	 * 24 	        - Cinema
7024 	 * 25 	        - TV/PAL
7025 	 * 29.97        - TV/NTSC
7026 	 * 30 	        - TV/NTSC
7027 	 * 48 	        - Cinema HFR
7028 	 * 50 	        - TV/PAL
7029 	 * 60 	        - Commonly used
7030 	 * 48,72,96,120 - Multiples of 24
7031 	 */
7032 	static const u32 common_rates[] = {
7033 		23976, 24000, 25000, 29970, 30000,
7034 		48000, 50000, 60000, 72000, 96000, 120000
7035 	};
7036 
7037 	/*
7038 	 * Find mode with highest refresh rate with the same resolution
7039 	 * as the preferred mode. Some monitors report a preferred mode
7040 	 * with lower resolution than the highest refresh rate supported.
7041 	 */
7042 
7043 	m = get_highest_refresh_rate_mode(aconnector, true);
7044 	if (!m)
7045 		return 0;
7046 
7047 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
7048 		u64 target_vtotal, target_vtotal_diff;
7049 		u64 num, den;
7050 
7051 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
7052 			continue;
7053 
7054 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
7055 		    common_rates[i] > aconnector->max_vfreq * 1000)
7056 			continue;
7057 
7058 		num = (unsigned long long)m->clock * 1000 * 1000;
7059 		den = common_rates[i] * (unsigned long long)m->htotal;
7060 		target_vtotal = div_u64(num, den);
7061 		target_vtotal_diff = target_vtotal - m->vtotal;
7062 
7063 		/* Check for illegal modes */
7064 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
7065 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
7066 		    m->vtotal + target_vtotal_diff < m->vsync_end)
7067 			continue;
7068 
7069 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
7070 		if (!new_mode)
7071 			goto out;
7072 
7073 		new_mode->vtotal += (u16)target_vtotal_diff;
7074 		new_mode->vsync_start += (u16)target_vtotal_diff;
7075 		new_mode->vsync_end += (u16)target_vtotal_diff;
7076 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
7077 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
7078 
7079 		if (!is_duplicate_mode(aconnector, new_mode)) {
7080 			drm_mode_probed_add(&aconnector->base, new_mode);
7081 			new_modes_count += 1;
7082 		} else
7083 			drm_mode_destroy(aconnector->base.dev, new_mode);
7084 	}
7085  out:
7086 	return new_modes_count;
7087 }
7088 
7089 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
7090 						   struct edid *edid)
7091 {
7092 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7093 		to_amdgpu_dm_connector(connector);
7094 
7095 	if (!edid)
7096 		return;
7097 
7098 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
7099 		amdgpu_dm_connector->num_modes +=
7100 			add_fs_modes(amdgpu_dm_connector);
7101 }
7102 
7103 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
7104 {
7105 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7106 			to_amdgpu_dm_connector(connector);
7107 	struct drm_encoder *encoder;
7108 	struct edid *edid = amdgpu_dm_connector->edid;
7109 
7110 	encoder = amdgpu_dm_connector_to_encoder(connector);
7111 
7112 	if (!drm_edid_is_valid(edid)) {
7113 		amdgpu_dm_connector->num_modes =
7114 				drm_add_modes_noedid(connector, 640, 480);
7115 	} else {
7116 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
7117 		amdgpu_dm_connector_add_common_modes(encoder, connector);
7118 		amdgpu_dm_connector_add_freesync_modes(connector, edid);
7119 	}
7120 	amdgpu_dm_fbc_init(connector);
7121 
7122 	return amdgpu_dm_connector->num_modes;
7123 }
7124 
7125 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
7126 				     struct amdgpu_dm_connector *aconnector,
7127 				     int connector_type,
7128 				     struct dc_link *link,
7129 				     int link_index)
7130 {
7131 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
7132 
7133 	/*
7134 	 * Some of the properties below require access to state, like bpc.
7135 	 * Allocate some default initial connector state with our reset helper.
7136 	 */
7137 	if (aconnector->base.funcs->reset)
7138 		aconnector->base.funcs->reset(&aconnector->base);
7139 
7140 	aconnector->connector_id = link_index;
7141 	aconnector->dc_link = link;
7142 	aconnector->base.interlace_allowed = false;
7143 	aconnector->base.doublescan_allowed = false;
7144 	aconnector->base.stereo_allowed = false;
7145 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
7146 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
7147 	aconnector->audio_inst = -1;
7148 	rw_init(&aconnector->hpd_lock, "dmhpd");
7149 	rw_init(&aconnector->handle_mst_msg_ready, "dmmr");
7150 
7151 	/*
7152 	 * configure support HPD hot plug connector_>polled default value is 0
7153 	 * which means HPD hot plug not supported
7154 	 */
7155 	switch (connector_type) {
7156 	case DRM_MODE_CONNECTOR_HDMIA:
7157 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7158 		aconnector->base.ycbcr_420_allowed =
7159 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
7160 		break;
7161 	case DRM_MODE_CONNECTOR_DisplayPort:
7162 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7163 		link->link_enc = link_enc_cfg_get_link_enc(link);
7164 		ASSERT(link->link_enc);
7165 		if (link->link_enc)
7166 			aconnector->base.ycbcr_420_allowed =
7167 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
7168 		break;
7169 	case DRM_MODE_CONNECTOR_DVID:
7170 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7171 		break;
7172 	default:
7173 		break;
7174 	}
7175 
7176 	drm_object_attach_property(&aconnector->base.base,
7177 				dm->ddev->mode_config.scaling_mode_property,
7178 				DRM_MODE_SCALE_NONE);
7179 
7180 	drm_object_attach_property(&aconnector->base.base,
7181 				adev->mode_info.underscan_property,
7182 				UNDERSCAN_OFF);
7183 	drm_object_attach_property(&aconnector->base.base,
7184 				adev->mode_info.underscan_hborder_property,
7185 				0);
7186 	drm_object_attach_property(&aconnector->base.base,
7187 				adev->mode_info.underscan_vborder_property,
7188 				0);
7189 
7190 	if (!aconnector->mst_port)
7191 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7192 
7193 	/* This defaults to the max in the range, but we want 8bpc for non-edp. */
7194 	aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7195 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7196 
7197 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7198 	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7199 		drm_object_attach_property(&aconnector->base.base,
7200 				adev->mode_info.abm_level_property, 0);
7201 	}
7202 
7203 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7204 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7205 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
7206 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7207 
7208 		if (!aconnector->mst_port)
7209 			drm_connector_attach_vrr_capable_property(&aconnector->base);
7210 
7211 #ifdef CONFIG_DRM_AMD_DC_HDCP
7212 		if (adev->dm.hdcp_workqueue)
7213 			drm_connector_attach_content_protection_property(&aconnector->base, true);
7214 #endif
7215 	}
7216 }
7217 
7218 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7219 			      struct i2c_msg *msgs, int num)
7220 {
7221 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7222 	struct ddc_service *ddc_service = i2c->ddc_service;
7223 	struct i2c_command cmd;
7224 	int i;
7225 	int result = -EIO;
7226 
7227 	if (!ddc_service->ddc_pin || !ddc_service->ddc_pin->hw_info.hw_supported)
7228 		return result;
7229 
7230 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7231 
7232 	if (!cmd.payloads)
7233 		return result;
7234 
7235 	cmd.number_of_payloads = num;
7236 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7237 	cmd.speed = 100;
7238 
7239 	for (i = 0; i < num; i++) {
7240 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7241 		cmd.payloads[i].address = msgs[i].addr;
7242 		cmd.payloads[i].length = msgs[i].len;
7243 		cmd.payloads[i].data = msgs[i].buf;
7244 	}
7245 
7246 	if (dc_submit_i2c(
7247 			ddc_service->ctx->dc,
7248 			ddc_service->link->link_index,
7249 			&cmd))
7250 		result = num;
7251 
7252 	kfree(cmd.payloads);
7253 	return result;
7254 }
7255 
7256 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7257 {
7258 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7259 }
7260 
7261 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7262 	.master_xfer = amdgpu_dm_i2c_xfer,
7263 	.functionality = amdgpu_dm_i2c_func,
7264 };
7265 
7266 static struct amdgpu_i2c_adapter *
7267 create_i2c(struct ddc_service *ddc_service,
7268 	   int link_index,
7269 	   int *res)
7270 {
7271 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7272 	struct amdgpu_i2c_adapter *i2c;
7273 
7274 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7275 	if (!i2c)
7276 		return NULL;
7277 #ifdef notyet
7278 	i2c->base.owner = THIS_MODULE;
7279 	i2c->base.class = I2C_CLASS_DDC;
7280 	i2c->base.dev.parent = &adev->pdev->dev;
7281 #endif
7282 	i2c->base.algo = &amdgpu_dm_i2c_algo;
7283 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7284 	i2c_set_adapdata(&i2c->base, i2c);
7285 	i2c->ddc_service = ddc_service;
7286 
7287 	return i2c;
7288 }
7289 
7290 
7291 /*
7292  * Note: this function assumes that dc_link_detect() was called for the
7293  * dc_link which will be represented by this aconnector.
7294  */
7295 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7296 				    struct amdgpu_dm_connector *aconnector,
7297 				    u32 link_index,
7298 				    struct amdgpu_encoder *aencoder)
7299 {
7300 	int res = 0;
7301 	int connector_type;
7302 	struct dc *dc = dm->dc;
7303 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
7304 	struct amdgpu_i2c_adapter *i2c;
7305 
7306 	link->priv = aconnector;
7307 
7308 
7309 	i2c = create_i2c(link->ddc, link->link_index, &res);
7310 	if (!i2c) {
7311 		DRM_ERROR("Failed to create i2c adapter data\n");
7312 		return -ENOMEM;
7313 	}
7314 
7315 	aconnector->i2c = i2c;
7316 	res = i2c_add_adapter(&i2c->base);
7317 
7318 	if (res) {
7319 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7320 		goto out_free;
7321 	}
7322 
7323 	connector_type = to_drm_connector_type(link->connector_signal);
7324 
7325 	res = drm_connector_init_with_ddc(
7326 			dm->ddev,
7327 			&aconnector->base,
7328 			&amdgpu_dm_connector_funcs,
7329 			connector_type,
7330 			&i2c->base);
7331 
7332 	if (res) {
7333 		DRM_ERROR("connector_init failed\n");
7334 		aconnector->connector_id = -1;
7335 		goto out_free;
7336 	}
7337 
7338 	drm_connector_helper_add(
7339 			&aconnector->base,
7340 			&amdgpu_dm_connector_helper_funcs);
7341 
7342 	amdgpu_dm_connector_init_helper(
7343 		dm,
7344 		aconnector,
7345 		connector_type,
7346 		link,
7347 		link_index);
7348 
7349 	drm_connector_attach_encoder(
7350 		&aconnector->base, &aencoder->base);
7351 
7352 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7353 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
7354 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7355 
7356 out_free:
7357 	if (res) {
7358 		kfree(i2c);
7359 		aconnector->i2c = NULL;
7360 	}
7361 	return res;
7362 }
7363 
7364 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7365 {
7366 	switch (adev->mode_info.num_crtc) {
7367 	case 1:
7368 		return 0x1;
7369 	case 2:
7370 		return 0x3;
7371 	case 3:
7372 		return 0x7;
7373 	case 4:
7374 		return 0xf;
7375 	case 5:
7376 		return 0x1f;
7377 	case 6:
7378 	default:
7379 		return 0x3f;
7380 	}
7381 }
7382 
7383 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7384 				  struct amdgpu_encoder *aencoder,
7385 				  uint32_t link_index)
7386 {
7387 	struct amdgpu_device *adev = drm_to_adev(dev);
7388 
7389 	int res = drm_encoder_init(dev,
7390 				   &aencoder->base,
7391 				   &amdgpu_dm_encoder_funcs,
7392 				   DRM_MODE_ENCODER_TMDS,
7393 				   NULL);
7394 
7395 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7396 
7397 	if (!res)
7398 		aencoder->encoder_id = link_index;
7399 	else
7400 		aencoder->encoder_id = -1;
7401 
7402 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7403 
7404 	return res;
7405 }
7406 
7407 static void manage_dm_interrupts(struct amdgpu_device *adev,
7408 				 struct amdgpu_crtc *acrtc,
7409 				 bool enable)
7410 {
7411 	/*
7412 	 * We have no guarantee that the frontend index maps to the same
7413 	 * backend index - some even map to more than one.
7414 	 *
7415 	 * TODO: Use a different interrupt or check DC itself for the mapping.
7416 	 */
7417 	int irq_type =
7418 		amdgpu_display_crtc_idx_to_irq_type(
7419 			adev,
7420 			acrtc->crtc_id);
7421 
7422 	if (enable) {
7423 		drm_crtc_vblank_on(&acrtc->base);
7424 		amdgpu_irq_get(
7425 			adev,
7426 			&adev->pageflip_irq,
7427 			irq_type);
7428 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7429 		amdgpu_irq_get(
7430 			adev,
7431 			&adev->vline0_irq,
7432 			irq_type);
7433 #endif
7434 	} else {
7435 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7436 		amdgpu_irq_put(
7437 			adev,
7438 			&adev->vline0_irq,
7439 			irq_type);
7440 #endif
7441 		amdgpu_irq_put(
7442 			adev,
7443 			&adev->pageflip_irq,
7444 			irq_type);
7445 		drm_crtc_vblank_off(&acrtc->base);
7446 	}
7447 }
7448 
7449 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7450 				      struct amdgpu_crtc *acrtc)
7451 {
7452 	int irq_type =
7453 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7454 
7455 	/**
7456 	 * This reads the current state for the IRQ and force reapplies
7457 	 * the setting to hardware.
7458 	 */
7459 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7460 }
7461 
7462 static bool
7463 is_scaling_state_different(const struct dm_connector_state *dm_state,
7464 			   const struct dm_connector_state *old_dm_state)
7465 {
7466 	if (dm_state->scaling != old_dm_state->scaling)
7467 		return true;
7468 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7469 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7470 			return true;
7471 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7472 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7473 			return true;
7474 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7475 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7476 		return true;
7477 	return false;
7478 }
7479 
7480 #ifdef CONFIG_DRM_AMD_DC_HDCP
7481 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
7482 					    struct drm_crtc_state *old_crtc_state,
7483 					    struct drm_connector_state *new_conn_state,
7484 					    struct drm_connector_state *old_conn_state,
7485 					    const struct drm_connector *connector,
7486 					    struct hdcp_workqueue *hdcp_w)
7487 {
7488 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7489 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7490 
7491 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
7492 		connector->index, connector->status, connector->dpms);
7493 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
7494 		old_conn_state->content_protection, new_conn_state->content_protection);
7495 
7496 	if (old_crtc_state)
7497 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7498 		old_crtc_state->enable,
7499 		old_crtc_state->active,
7500 		old_crtc_state->mode_changed,
7501 		old_crtc_state->active_changed,
7502 		old_crtc_state->connectors_changed);
7503 
7504 	if (new_crtc_state)
7505 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7506 		new_crtc_state->enable,
7507 		new_crtc_state->active,
7508 		new_crtc_state->mode_changed,
7509 		new_crtc_state->active_changed,
7510 		new_crtc_state->connectors_changed);
7511 
7512 	/* hdcp content type change */
7513 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
7514 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7515 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7516 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
7517 		return true;
7518 	}
7519 
7520 	/* CP is being re enabled, ignore this */
7521 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7522 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7523 		if (new_crtc_state && new_crtc_state->mode_changed) {
7524 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7525 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
7526 			return true;
7527 		};
7528 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7529 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
7530 		return false;
7531 	}
7532 
7533 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7534 	 *
7535 	 * Handles:	UNDESIRED -> ENABLED
7536 	 */
7537 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7538 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7539 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7540 
7541 	/* Stream removed and re-enabled
7542 	 *
7543 	 * Can sometimes overlap with the HPD case,
7544 	 * thus set update_hdcp to false to avoid
7545 	 * setting HDCP multiple times.
7546 	 *
7547 	 * Handles:	DESIRED -> DESIRED (Special case)
7548 	 */
7549 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
7550 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
7551 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7552 		dm_con_state->update_hdcp = false;
7553 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
7554 			__func__);
7555 		return true;
7556 	}
7557 
7558 	/* Hot-plug, headless s3, dpms
7559 	 *
7560 	 * Only start HDCP if the display is connected/enabled.
7561 	 * update_hdcp flag will be set to false until the next
7562 	 * HPD comes in.
7563 	 *
7564 	 * Handles:	DESIRED -> DESIRED (Special case)
7565 	 */
7566 	if (dm_con_state->update_hdcp &&
7567 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7568 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7569 		dm_con_state->update_hdcp = false;
7570 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
7571 			__func__);
7572 		return true;
7573 	}
7574 
7575 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
7576 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7577 			if (new_crtc_state && new_crtc_state->mode_changed) {
7578 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
7579 					__func__);
7580 				return true;
7581 			};
7582 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
7583 				__func__);
7584 			return false;
7585 		};
7586 
7587 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
7588 		return false;
7589 	}
7590 
7591 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
7592 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
7593 			__func__);
7594 		return true;
7595 	}
7596 
7597 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
7598 	return false;
7599 }
7600 #endif
7601 
7602 static void remove_stream(struct amdgpu_device *adev,
7603 			  struct amdgpu_crtc *acrtc,
7604 			  struct dc_stream_state *stream)
7605 {
7606 	/* this is the update mode case */
7607 
7608 	acrtc->otg_inst = -1;
7609 	acrtc->enabled = false;
7610 }
7611 
7612 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7613 {
7614 
7615 	assert_spin_locked(&acrtc->base.dev->event_lock);
7616 	WARN_ON(acrtc->event);
7617 
7618 	acrtc->event = acrtc->base.state->event;
7619 
7620 	/* Set the flip status */
7621 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7622 
7623 	/* Mark this event as consumed */
7624 	acrtc->base.state->event = NULL;
7625 
7626 	DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7627 		     acrtc->crtc_id);
7628 }
7629 
7630 static void update_freesync_state_on_stream(
7631 	struct amdgpu_display_manager *dm,
7632 	struct dm_crtc_state *new_crtc_state,
7633 	struct dc_stream_state *new_stream,
7634 	struct dc_plane_state *surface,
7635 	u32 flip_timestamp_in_us)
7636 {
7637 	struct mod_vrr_params vrr_params;
7638 	struct dc_info_packet vrr_infopacket = {0};
7639 	struct amdgpu_device *adev = dm->adev;
7640 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7641 	unsigned long flags;
7642 	bool pack_sdp_v1_3 = false;
7643 
7644 	if (!new_stream)
7645 		return;
7646 
7647 	/*
7648 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7649 	 * For now it's sufficient to just guard against these conditions.
7650 	 */
7651 
7652 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7653 		return;
7654 
7655 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7656         vrr_params = acrtc->dm_irq_params.vrr_params;
7657 
7658 	if (surface) {
7659 		mod_freesync_handle_preflip(
7660 			dm->freesync_module,
7661 			surface,
7662 			new_stream,
7663 			flip_timestamp_in_us,
7664 			&vrr_params);
7665 
7666 		if (adev->family < AMDGPU_FAMILY_AI &&
7667 		    amdgpu_dm_vrr_active(new_crtc_state)) {
7668 			mod_freesync_handle_v_update(dm->freesync_module,
7669 						     new_stream, &vrr_params);
7670 
7671 			/* Need to call this before the frame ends. */
7672 			dc_stream_adjust_vmin_vmax(dm->dc,
7673 						   new_crtc_state->stream,
7674 						   &vrr_params.adjust);
7675 		}
7676 	}
7677 
7678 	mod_freesync_build_vrr_infopacket(
7679 		dm->freesync_module,
7680 		new_stream,
7681 		&vrr_params,
7682 		PACKET_TYPE_VRR,
7683 		TRANSFER_FUNC_UNKNOWN,
7684 		&vrr_infopacket,
7685 		pack_sdp_v1_3);
7686 
7687 	new_crtc_state->freesync_vrr_info_changed |=
7688 		(memcmp(&new_crtc_state->vrr_infopacket,
7689 			&vrr_infopacket,
7690 			sizeof(vrr_infopacket)) != 0);
7691 
7692 	acrtc->dm_irq_params.vrr_params = vrr_params;
7693 	new_crtc_state->vrr_infopacket = vrr_infopacket;
7694 
7695 	new_stream->vrr_infopacket = vrr_infopacket;
7696 
7697 	if (new_crtc_state->freesync_vrr_info_changed)
7698 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7699 			      new_crtc_state->base.crtc->base.id,
7700 			      (int)new_crtc_state->base.vrr_enabled,
7701 			      (int)vrr_params.state);
7702 
7703 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7704 }
7705 
7706 static void update_stream_irq_parameters(
7707 	struct amdgpu_display_manager *dm,
7708 	struct dm_crtc_state *new_crtc_state)
7709 {
7710 	struct dc_stream_state *new_stream = new_crtc_state->stream;
7711 	struct mod_vrr_params vrr_params;
7712 	struct mod_freesync_config config = new_crtc_state->freesync_config;
7713 	struct amdgpu_device *adev = dm->adev;
7714 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7715 	unsigned long flags;
7716 
7717 	if (!new_stream)
7718 		return;
7719 
7720 	/*
7721 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7722 	 * For now it's sufficient to just guard against these conditions.
7723 	 */
7724 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7725 		return;
7726 
7727 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7728 	vrr_params = acrtc->dm_irq_params.vrr_params;
7729 
7730 	if (new_crtc_state->vrr_supported &&
7731 	    config.min_refresh_in_uhz &&
7732 	    config.max_refresh_in_uhz) {
7733 		/*
7734 		 * if freesync compatible mode was set, config.state will be set
7735 		 * in atomic check
7736 		 */
7737 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7738 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7739 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7740 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7741 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7742 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7743 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7744 		} else {
7745 			config.state = new_crtc_state->base.vrr_enabled ?
7746 						     VRR_STATE_ACTIVE_VARIABLE :
7747 						     VRR_STATE_INACTIVE;
7748 		}
7749 	} else {
7750 		config.state = VRR_STATE_UNSUPPORTED;
7751 	}
7752 
7753 	mod_freesync_build_vrr_params(dm->freesync_module,
7754 				      new_stream,
7755 				      &config, &vrr_params);
7756 
7757 	new_crtc_state->freesync_config = config;
7758 	/* Copy state for access from DM IRQ handler */
7759 	acrtc->dm_irq_params.freesync_config = config;
7760 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7761 	acrtc->dm_irq_params.vrr_params = vrr_params;
7762 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7763 }
7764 
7765 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7766 					    struct dm_crtc_state *new_state)
7767 {
7768 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7769 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7770 
7771 	if (!old_vrr_active && new_vrr_active) {
7772 		/* Transition VRR inactive -> active:
7773 		 * While VRR is active, we must not disable vblank irq, as a
7774 		 * reenable after disable would compute bogus vblank/pflip
7775 		 * timestamps if it likely happened inside display front-porch.
7776 		 *
7777 		 * We also need vupdate irq for the actual core vblank handling
7778 		 * at end of vblank.
7779 		 */
7780 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7781 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7782 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7783 				 __func__, new_state->base.crtc->base.id);
7784 	} else if (old_vrr_active && !new_vrr_active) {
7785 		/* Transition VRR active -> inactive:
7786 		 * Allow vblank irq disable again for fixed refresh rate.
7787 		 */
7788 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7789 		drm_crtc_vblank_put(new_state->base.crtc);
7790 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7791 				 __func__, new_state->base.crtc->base.id);
7792 	}
7793 }
7794 
7795 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7796 {
7797 	struct drm_plane *plane;
7798 	struct drm_plane_state *old_plane_state;
7799 	int i;
7800 
7801 	/*
7802 	 * TODO: Make this per-stream so we don't issue redundant updates for
7803 	 * commits with multiple streams.
7804 	 */
7805 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
7806 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
7807 			handle_cursor_update(plane, old_plane_state);
7808 }
7809 
7810 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
7811 {
7812 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
7813 
7814 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
7815 }
7816 
7817 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7818 				    struct dc_state *dc_state,
7819 				    struct drm_device *dev,
7820 				    struct amdgpu_display_manager *dm,
7821 				    struct drm_crtc *pcrtc,
7822 				    bool wait_for_vblank)
7823 {
7824 	u32 i;
7825 	u64 timestamp_ns;
7826 	struct drm_plane *plane;
7827 	struct drm_plane_state *old_plane_state, *new_plane_state;
7828 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7829 	struct drm_crtc_state *new_pcrtc_state =
7830 			drm_atomic_get_new_crtc_state(state, pcrtc);
7831 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7832 	struct dm_crtc_state *dm_old_crtc_state =
7833 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7834 	int planes_count = 0, vpos, hpos;
7835 	unsigned long flags;
7836 	u32 target_vblank, last_flip_vblank;
7837 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7838 	bool cursor_update = false;
7839 	bool pflip_present = false;
7840 	struct {
7841 		struct dc_surface_update surface_updates[MAX_SURFACES];
7842 		struct dc_plane_info plane_infos[MAX_SURFACES];
7843 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
7844 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7845 		struct dc_stream_update stream_update;
7846 	} *bundle;
7847 
7848 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7849 
7850 	if (!bundle) {
7851 		dm_error("Failed to allocate update bundle\n");
7852 		goto cleanup;
7853 	}
7854 
7855 	/*
7856 	 * Disable the cursor first if we're disabling all the planes.
7857 	 * It'll remain on the screen after the planes are re-enabled
7858 	 * if we don't.
7859 	 */
7860 	if (acrtc_state->active_planes == 0)
7861 		amdgpu_dm_commit_cursors(state);
7862 
7863 	/* update planes when needed */
7864 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7865 		struct drm_crtc *crtc = new_plane_state->crtc;
7866 		struct drm_crtc_state *new_crtc_state;
7867 		struct drm_framebuffer *fb = new_plane_state->fb;
7868 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7869 		bool plane_needs_flip;
7870 		struct dc_plane_state *dc_plane;
7871 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7872 
7873 		/* Cursor plane is handled after stream updates */
7874 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7875 			if ((fb && crtc == pcrtc) ||
7876 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7877 				cursor_update = true;
7878 
7879 			continue;
7880 		}
7881 
7882 		if (!fb || !crtc || pcrtc != crtc)
7883 			continue;
7884 
7885 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7886 		if (!new_crtc_state->active)
7887 			continue;
7888 
7889 		dc_plane = dm_new_plane_state->dc_state;
7890 		if (!dc_plane)
7891 			continue;
7892 
7893 		bundle->surface_updates[planes_count].surface = dc_plane;
7894 		if (new_pcrtc_state->color_mgmt_changed) {
7895 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7896 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7897 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7898 		}
7899 
7900 		fill_dc_scaling_info(dm->adev, new_plane_state,
7901 				     &bundle->scaling_infos[planes_count]);
7902 
7903 		bundle->surface_updates[planes_count].scaling_info =
7904 			&bundle->scaling_infos[planes_count];
7905 
7906 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7907 
7908 		pflip_present = pflip_present || plane_needs_flip;
7909 
7910 		if (!plane_needs_flip) {
7911 			planes_count += 1;
7912 			continue;
7913 		}
7914 
7915 		fill_dc_plane_info_and_addr(
7916 			dm->adev, new_plane_state,
7917 			afb->tiling_flags,
7918 			&bundle->plane_infos[planes_count],
7919 			&bundle->flip_addrs[planes_count].address,
7920 			afb->tmz_surface, false);
7921 
7922 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7923 				 new_plane_state->plane->index,
7924 				 bundle->plane_infos[planes_count].dcc.enable);
7925 
7926 		bundle->surface_updates[planes_count].plane_info =
7927 			&bundle->plane_infos[planes_count];
7928 
7929 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7930 			fill_dc_dirty_rects(plane, old_plane_state,
7931 					    new_plane_state, new_crtc_state,
7932 					    &bundle->flip_addrs[planes_count]);
7933 
7934 		/*
7935 		 * Only allow immediate flips for fast updates that don't
7936 		 * change memory domain, FB pitch, DCC state, rotation or
7937 		 * mirroring.
7938 		 *
7939 		 * dm_crtc_helper_atomic_check() only accepts async flips with
7940 		 * fast updates.
7941 		 */
7942 		if (crtc->state->async_flip &&
7943 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
7944 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
7945 			drm_warn_once(state->dev,
7946 				      "[PLANE:%d:%s] async flip with non-fast update\n",
7947 				      plane->base.id, plane->name);
7948 
7949 		bundle->flip_addrs[planes_count].flip_immediate =
7950 			crtc->state->async_flip &&
7951 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
7952 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
7953 
7954 		timestamp_ns = ktime_get_ns();
7955 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7956 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7957 		bundle->surface_updates[planes_count].surface = dc_plane;
7958 
7959 		if (!bundle->surface_updates[planes_count].surface) {
7960 			DRM_ERROR("No surface for CRTC: id=%d\n",
7961 					acrtc_attach->crtc_id);
7962 			continue;
7963 		}
7964 
7965 		if (plane == pcrtc->primary)
7966 			update_freesync_state_on_stream(
7967 				dm,
7968 				acrtc_state,
7969 				acrtc_state->stream,
7970 				dc_plane,
7971 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7972 
7973 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7974 				 __func__,
7975 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7976 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7977 
7978 		planes_count += 1;
7979 
7980 	}
7981 
7982 	if (pflip_present) {
7983 		if (!vrr_active) {
7984 			/* Use old throttling in non-vrr fixed refresh rate mode
7985 			 * to keep flip scheduling based on target vblank counts
7986 			 * working in a backwards compatible way, e.g., for
7987 			 * clients using the GLX_OML_sync_control extension or
7988 			 * DRI3/Present extension with defined target_msc.
7989 			 */
7990 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7991 		} else {
7992 			/* For variable refresh rate mode only:
7993 			 * Get vblank of last completed flip to avoid > 1 vrr
7994 			 * flips per video frame by use of throttling, but allow
7995 			 * flip programming anywhere in the possibly large
7996 			 * variable vrr vblank interval for fine-grained flip
7997 			 * timing control and more opportunity to avoid stutter
7998 			 * on late submission of flips.
7999 			 */
8000 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8001 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
8002 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8003 		}
8004 
8005 		target_vblank = last_flip_vblank + wait_for_vblank;
8006 
8007 		/*
8008 		 * Wait until we're out of the vertical blank period before the one
8009 		 * targeted by the flip
8010 		 */
8011 		while ((acrtc_attach->enabled &&
8012 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
8013 							    0, &vpos, &hpos, NULL,
8014 							    NULL, &pcrtc->hwmode)
8015 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
8016 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
8017 			(int)(target_vblank -
8018 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
8019 			usleep_range(1000, 1100);
8020 		}
8021 
8022 		/**
8023 		 * Prepare the flip event for the pageflip interrupt to handle.
8024 		 *
8025 		 * This only works in the case where we've already turned on the
8026 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
8027 		 * from 0 -> n planes we have to skip a hardware generated event
8028 		 * and rely on sending it from software.
8029 		 */
8030 		if (acrtc_attach->base.state->event &&
8031 		    acrtc_state->active_planes > 0) {
8032 			drm_crtc_vblank_get(pcrtc);
8033 
8034 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8035 
8036 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
8037 			prepare_flip_isr(acrtc_attach);
8038 
8039 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8040 		}
8041 
8042 		if (acrtc_state->stream) {
8043 			if (acrtc_state->freesync_vrr_info_changed)
8044 				bundle->stream_update.vrr_infopacket =
8045 					&acrtc_state->stream->vrr_infopacket;
8046 		}
8047 	} else if (cursor_update && acrtc_state->active_planes > 0 &&
8048 		   acrtc_attach->base.state->event) {
8049 		drm_crtc_vblank_get(pcrtc);
8050 
8051 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8052 
8053 		acrtc_attach->event = acrtc_attach->base.state->event;
8054 		acrtc_attach->base.state->event = NULL;
8055 
8056 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8057 	}
8058 
8059 	/* Update the planes if changed or disable if we don't have any. */
8060 	if ((planes_count || acrtc_state->active_planes == 0) &&
8061 		acrtc_state->stream) {
8062 		/*
8063 		 * If PSR or idle optimizations are enabled then flush out
8064 		 * any pending work before hardware programming.
8065 		 */
8066 		if (dm->vblank_control_workqueue)
8067 			flush_workqueue(dm->vblank_control_workqueue);
8068 
8069 		bundle->stream_update.stream = acrtc_state->stream;
8070 		if (new_pcrtc_state->mode_changed) {
8071 			bundle->stream_update.src = acrtc_state->stream->src;
8072 			bundle->stream_update.dst = acrtc_state->stream->dst;
8073 		}
8074 
8075 		if (new_pcrtc_state->color_mgmt_changed) {
8076 			/*
8077 			 * TODO: This isn't fully correct since we've actually
8078 			 * already modified the stream in place.
8079 			 */
8080 			bundle->stream_update.gamut_remap =
8081 				&acrtc_state->stream->gamut_remap_matrix;
8082 			bundle->stream_update.output_csc_transform =
8083 				&acrtc_state->stream->csc_color_matrix;
8084 			bundle->stream_update.out_transfer_func =
8085 				acrtc_state->stream->out_transfer_func;
8086 		}
8087 
8088 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
8089 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
8090 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
8091 
8092 		mutex_lock(&dm->dc_lock);
8093 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8094 				acrtc_state->stream->link->psr_settings.psr_allow_active)
8095 			amdgpu_dm_psr_disable(acrtc_state->stream);
8096 		mutex_unlock(&dm->dc_lock);
8097 
8098 		/*
8099 		 * If FreeSync state on the stream has changed then we need to
8100 		 * re-adjust the min/max bounds now that DC doesn't handle this
8101 		 * as part of commit.
8102 		 */
8103 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
8104 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8105 			dc_stream_adjust_vmin_vmax(
8106 				dm->dc, acrtc_state->stream,
8107 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
8108 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8109 		}
8110 		mutex_lock(&dm->dc_lock);
8111 		update_planes_and_stream_adapter(dm->dc,
8112 					 acrtc_state->update_type,
8113 					 planes_count,
8114 					 acrtc_state->stream,
8115 					 &bundle->stream_update,
8116 					 bundle->surface_updates);
8117 
8118 		/**
8119 		 * Enable or disable the interrupts on the backend.
8120 		 *
8121 		 * Most pipes are put into power gating when unused.
8122 		 *
8123 		 * When power gating is enabled on a pipe we lose the
8124 		 * interrupt enablement state when power gating is disabled.
8125 		 *
8126 		 * So we need to update the IRQ control state in hardware
8127 		 * whenever the pipe turns on (since it could be previously
8128 		 * power gated) or off (since some pipes can't be power gated
8129 		 * on some ASICs).
8130 		 */
8131 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
8132 			dm_update_pflip_irq_state(drm_to_adev(dev),
8133 						  acrtc_attach);
8134 
8135 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8136 				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
8137 				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
8138 			amdgpu_dm_link_setup_psr(acrtc_state->stream);
8139 
8140 		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
8141 		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
8142 		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
8143 			struct amdgpu_dm_connector *aconn =
8144 				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8145 
8146 			if (aconn->psr_skip_count > 0)
8147 				aconn->psr_skip_count--;
8148 
8149 			/* Allow PSR when skip count is 0. */
8150 			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
8151 
8152 			/*
8153 			 * If sink supports PSR SU, there is no need to rely on
8154 			 * a vblank event disable request to enable PSR. PSR SU
8155 			 * can be enabled immediately once OS demonstrates an
8156 			 * adequate number of fast atomic commits to notify KMD
8157 			 * of update events. See `vblank_control_worker()`.
8158 			 */
8159 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
8160 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
8161 			    !acrtc_state->stream->link->psr_settings.psr_allow_active)
8162 				amdgpu_dm_psr_enable(acrtc_state->stream);
8163 		} else {
8164 			acrtc_attach->dm_irq_params.allow_psr_entry = false;
8165 		}
8166 
8167 		mutex_unlock(&dm->dc_lock);
8168 	}
8169 
8170 	/*
8171 	 * Update cursor state *after* programming all the planes.
8172 	 * This avoids redundant programming in the case where we're going
8173 	 * to be disabling a single plane - those pipes are being disabled.
8174 	 */
8175 	if (acrtc_state->active_planes)
8176 		amdgpu_dm_commit_cursors(state);
8177 
8178 cleanup:
8179 	kfree(bundle);
8180 }
8181 
8182 static void amdgpu_dm_commit_audio(struct drm_device *dev,
8183 				   struct drm_atomic_state *state)
8184 {
8185 	struct amdgpu_device *adev = drm_to_adev(dev);
8186 	struct amdgpu_dm_connector *aconnector;
8187 	struct drm_connector *connector;
8188 	struct drm_connector_state *old_con_state, *new_con_state;
8189 	struct drm_crtc_state *new_crtc_state;
8190 	struct dm_crtc_state *new_dm_crtc_state;
8191 	const struct dc_stream_status *status;
8192 	int i, inst;
8193 
8194 	/* Notify device removals. */
8195 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8196 		if (old_con_state->crtc != new_con_state->crtc) {
8197 			/* CRTC changes require notification. */
8198 			goto notify;
8199 		}
8200 
8201 		if (!new_con_state->crtc)
8202 			continue;
8203 
8204 		new_crtc_state = drm_atomic_get_new_crtc_state(
8205 			state, new_con_state->crtc);
8206 
8207 		if (!new_crtc_state)
8208 			continue;
8209 
8210 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8211 			continue;
8212 
8213 	notify:
8214 		aconnector = to_amdgpu_dm_connector(connector);
8215 
8216 		mutex_lock(&adev->dm.audio_lock);
8217 		inst = aconnector->audio_inst;
8218 		aconnector->audio_inst = -1;
8219 		mutex_unlock(&adev->dm.audio_lock);
8220 
8221 		amdgpu_dm_audio_eld_notify(adev, inst);
8222 	}
8223 
8224 	/* Notify audio device additions. */
8225 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8226 		if (!new_con_state->crtc)
8227 			continue;
8228 
8229 		new_crtc_state = drm_atomic_get_new_crtc_state(
8230 			state, new_con_state->crtc);
8231 
8232 		if (!new_crtc_state)
8233 			continue;
8234 
8235 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8236 			continue;
8237 
8238 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
8239 		if (!new_dm_crtc_state->stream)
8240 			continue;
8241 
8242 		status = dc_stream_get_status(new_dm_crtc_state->stream);
8243 		if (!status)
8244 			continue;
8245 
8246 		aconnector = to_amdgpu_dm_connector(connector);
8247 
8248 		mutex_lock(&adev->dm.audio_lock);
8249 		inst = status->audio_inst;
8250 		aconnector->audio_inst = inst;
8251 		mutex_unlock(&adev->dm.audio_lock);
8252 
8253 		amdgpu_dm_audio_eld_notify(adev, inst);
8254 	}
8255 }
8256 
8257 /*
8258  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8259  * @crtc_state: the DRM CRTC state
8260  * @stream_state: the DC stream state.
8261  *
8262  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8263  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8264  */
8265 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8266 						struct dc_stream_state *stream_state)
8267 {
8268 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8269 }
8270 
8271 /**
8272  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8273  * @state: The atomic state to commit
8274  *
8275  * This will tell DC to commit the constructed DC state from atomic_check,
8276  * programming the hardware. Any failures here implies a hardware failure, since
8277  * atomic check should have filtered anything non-kosher.
8278  */
8279 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8280 {
8281 	struct drm_device *dev = state->dev;
8282 	struct amdgpu_device *adev = drm_to_adev(dev);
8283 	struct amdgpu_display_manager *dm = &adev->dm;
8284 	struct dm_atomic_state *dm_state;
8285 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8286 	u32 i, j;
8287 	struct drm_crtc *crtc;
8288 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8289 	unsigned long flags;
8290 	bool wait_for_vblank = true;
8291 	struct drm_connector *connector;
8292 	struct drm_connector_state *old_con_state, *new_con_state;
8293 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8294 	int crtc_disable_count = 0;
8295 	bool mode_set_reset_required = false;
8296 	int r;
8297 
8298 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
8299 
8300 	r = drm_atomic_helper_wait_for_fences(dev, state, false);
8301 	if (unlikely(r))
8302 		DRM_ERROR("Waiting for fences timed out!");
8303 
8304 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
8305 	drm_dp_mst_atomic_wait_for_dependencies(state);
8306 
8307 	dm_state = dm_atomic_get_new_state(state);
8308 	if (dm_state && dm_state->context) {
8309 		dc_state = dm_state->context;
8310 	} else {
8311 		/* No state changes, retain current state. */
8312 		dc_state_temp = dc_create_state(dm->dc);
8313 		ASSERT(dc_state_temp);
8314 		dc_state = dc_state_temp;
8315 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
8316 	}
8317 
8318 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
8319 				      new_crtc_state, i) {
8320 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8321 
8322 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8323 
8324 		if (old_crtc_state->active &&
8325 		    (!new_crtc_state->active ||
8326 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8327 			manage_dm_interrupts(adev, acrtc, false);
8328 			dc_stream_release(dm_old_crtc_state->stream);
8329 		}
8330 	}
8331 
8332 	drm_atomic_helper_calc_timestamping_constants(state);
8333 
8334 	/* update changed items */
8335 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8336 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8337 
8338 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8339 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8340 
8341 		drm_dbg_state(state->dev,
8342 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
8343 			acrtc->crtc_id,
8344 			new_crtc_state->enable,
8345 			new_crtc_state->active,
8346 			new_crtc_state->planes_changed,
8347 			new_crtc_state->mode_changed,
8348 			new_crtc_state->active_changed,
8349 			new_crtc_state->connectors_changed);
8350 
8351 		/* Disable cursor if disabling crtc */
8352 		if (old_crtc_state->active && !new_crtc_state->active) {
8353 			struct dc_cursor_position position;
8354 
8355 			memset(&position, 0, sizeof(position));
8356 			mutex_lock(&dm->dc_lock);
8357 			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8358 			mutex_unlock(&dm->dc_lock);
8359 		}
8360 
8361 		/* Copy all transient state flags into dc state */
8362 		if (dm_new_crtc_state->stream) {
8363 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8364 							    dm_new_crtc_state->stream);
8365 		}
8366 
8367 		/* handles headless hotplug case, updating new_state and
8368 		 * aconnector as needed
8369 		 */
8370 
8371 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8372 
8373 			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8374 
8375 			if (!dm_new_crtc_state->stream) {
8376 				/*
8377 				 * this could happen because of issues with
8378 				 * userspace notifications delivery.
8379 				 * In this case userspace tries to set mode on
8380 				 * display which is disconnected in fact.
8381 				 * dc_sink is NULL in this case on aconnector.
8382 				 * We expect reset mode will come soon.
8383 				 *
8384 				 * This can also happen when unplug is done
8385 				 * during resume sequence ended
8386 				 *
8387 				 * In this case, we want to pretend we still
8388 				 * have a sink to keep the pipe running so that
8389 				 * hw state is consistent with the sw state
8390 				 */
8391 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8392 						__func__, acrtc->base.base.id);
8393 				continue;
8394 			}
8395 
8396 			if (dm_old_crtc_state->stream)
8397 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8398 
8399 			pm_runtime_get_noresume(dev->dev);
8400 
8401 			acrtc->enabled = true;
8402 			acrtc->hw_mode = new_crtc_state->mode;
8403 			crtc->hwmode = new_crtc_state->mode;
8404 			mode_set_reset_required = true;
8405 		} else if (modereset_required(new_crtc_state)) {
8406 			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8407 			/* i.e. reset mode */
8408 			if (dm_old_crtc_state->stream)
8409 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8410 
8411 			mode_set_reset_required = true;
8412 		}
8413 	} /* for_each_crtc_in_state() */
8414 
8415 	if (dc_state) {
8416 		/* if there mode set or reset, disable eDP PSR */
8417 		if (mode_set_reset_required) {
8418 			if (dm->vblank_control_workqueue)
8419 				flush_workqueue(dm->vblank_control_workqueue);
8420 
8421 			amdgpu_dm_psr_disable_all(dm);
8422 		}
8423 
8424 		dm_enable_per_frame_crtc_master_sync(dc_state);
8425 		mutex_lock(&dm->dc_lock);
8426 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
8427 
8428 		/* Allow idle optimization when vblank count is 0 for display off */
8429 		if (dm->active_vblank_irq_count == 0)
8430 			dc_allow_idle_optimizations(dm->dc, true);
8431 		mutex_unlock(&dm->dc_lock);
8432 	}
8433 
8434 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8435 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8436 
8437 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8438 
8439 		if (dm_new_crtc_state->stream != NULL) {
8440 			const struct dc_stream_status *status =
8441 					dc_stream_get_status(dm_new_crtc_state->stream);
8442 
8443 			if (!status)
8444 				status = dc_stream_get_status_from_state(dc_state,
8445 									 dm_new_crtc_state->stream);
8446 			if (!status)
8447 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8448 			else
8449 				acrtc->otg_inst = status->primary_otg_inst;
8450 		}
8451 	}
8452 #ifdef CONFIG_DRM_AMD_DC_HDCP
8453 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8454 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8455 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8456 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8457 
8458 		if (!adev->dm.hdcp_workqueue)
8459 			continue;
8460 
8461 		pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
8462 
8463 		if (!connector)
8464 			continue;
8465 
8466 		pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8467 			connector->index, connector->status, connector->dpms);
8468 		pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8469 			old_con_state->content_protection, new_con_state->content_protection);
8470 
8471 		if (aconnector->dc_sink) {
8472 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
8473 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
8474 				pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
8475 				aconnector->dc_sink->edid_caps.display_name);
8476 			}
8477 		}
8478 
8479 		new_crtc_state = NULL;
8480 		old_crtc_state = NULL;
8481 
8482 		if (acrtc) {
8483 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8484 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8485 		}
8486 
8487 		if (old_crtc_state)
8488 			pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8489 			old_crtc_state->enable,
8490 			old_crtc_state->active,
8491 			old_crtc_state->mode_changed,
8492 			old_crtc_state->active_changed,
8493 			old_crtc_state->connectors_changed);
8494 
8495 		if (new_crtc_state)
8496 			pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8497 			new_crtc_state->enable,
8498 			new_crtc_state->active,
8499 			new_crtc_state->mode_changed,
8500 			new_crtc_state->active_changed,
8501 			new_crtc_state->connectors_changed);
8502 	}
8503 
8504 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8505 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8506 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8507 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8508 
8509 		if (!adev->dm.hdcp_workqueue)
8510 			continue;
8511 
8512 		new_crtc_state = NULL;
8513 		old_crtc_state = NULL;
8514 
8515 		if (acrtc) {
8516 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8517 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8518 		}
8519 
8520 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8521 
8522 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8523 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8524 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8525 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8526 			dm_new_con_state->update_hdcp = true;
8527 			continue;
8528 		}
8529 
8530 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
8531 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
8532 			/* when display is unplugged from mst hub, connctor will
8533 			 * be destroyed within dm_dp_mst_connector_destroy. connector
8534 			 * hdcp perperties, like type, undesired, desired, enabled,
8535 			 * will be lost. So, save hdcp properties into hdcp_work within
8536 			 * amdgpu_dm_atomic_commit_tail. if the same display is
8537 			 * plugged back with same display index, its hdcp properties
8538 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
8539 			 */
8540 
8541 			bool enable_encryption = false;
8542 
8543 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
8544 				enable_encryption = true;
8545 
8546 			if (aconnector->dc_link && aconnector->dc_sink &&
8547 				aconnector->dc_link->type == dc_connection_mst_branch) {
8548 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
8549 				struct hdcp_workqueue *hdcp_w =
8550 					&hdcp_work[aconnector->dc_link->link_index];
8551 
8552 				hdcp_w->hdcp_content_type[connector->index] =
8553 					new_con_state->hdcp_content_type;
8554 				hdcp_w->content_protection[connector->index] =
8555 					new_con_state->content_protection;
8556 			}
8557 
8558 			if (new_crtc_state && new_crtc_state->mode_changed &&
8559 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
8560 				enable_encryption = true;
8561 
8562 			DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
8563 
8564 			hdcp_update_display(
8565 				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8566 				new_con_state->hdcp_content_type, enable_encryption);
8567 		}
8568 	}
8569 #endif
8570 
8571 	/* Handle connector state changes */
8572 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8573 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8574 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8575 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8576 		struct dc_surface_update dummy_updates[MAX_SURFACES];
8577 		struct dc_stream_update stream_update;
8578 		struct dc_info_packet hdr_packet;
8579 		struct dc_stream_status *status = NULL;
8580 		bool abm_changed, hdr_changed, scaling_changed;
8581 
8582 		memset(&dummy_updates, 0, sizeof(dummy_updates));
8583 		memset(&stream_update, 0, sizeof(stream_update));
8584 
8585 		if (acrtc) {
8586 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8587 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8588 		}
8589 
8590 		/* Skip any modesets/resets */
8591 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8592 			continue;
8593 
8594 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8595 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8596 
8597 		scaling_changed = is_scaling_state_different(dm_new_con_state,
8598 							     dm_old_con_state);
8599 
8600 		abm_changed = dm_new_crtc_state->abm_level !=
8601 			      dm_old_crtc_state->abm_level;
8602 
8603 		hdr_changed =
8604 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8605 
8606 		if (!scaling_changed && !abm_changed && !hdr_changed)
8607 			continue;
8608 
8609 		stream_update.stream = dm_new_crtc_state->stream;
8610 		if (scaling_changed) {
8611 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8612 					dm_new_con_state, dm_new_crtc_state->stream);
8613 
8614 			stream_update.src = dm_new_crtc_state->stream->src;
8615 			stream_update.dst = dm_new_crtc_state->stream->dst;
8616 		}
8617 
8618 		if (abm_changed) {
8619 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8620 
8621 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
8622 		}
8623 
8624 		if (hdr_changed) {
8625 			fill_hdr_info_packet(new_con_state, &hdr_packet);
8626 			stream_update.hdr_static_metadata = &hdr_packet;
8627 		}
8628 
8629 		status = dc_stream_get_status(dm_new_crtc_state->stream);
8630 
8631 		if (WARN_ON(!status))
8632 			continue;
8633 
8634 		WARN_ON(!status->plane_count);
8635 
8636 		/*
8637 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
8638 		 * Here we create an empty update on each plane.
8639 		 * To fix this, DC should permit updating only stream properties.
8640 		 */
8641 		for (j = 0; j < status->plane_count; j++)
8642 			dummy_updates[j].surface = status->plane_states[0];
8643 
8644 
8645 		mutex_lock(&dm->dc_lock);
8646 		dc_update_planes_and_stream(dm->dc,
8647 					    dummy_updates,
8648 					    status->plane_count,
8649 					    dm_new_crtc_state->stream,
8650 					    &stream_update);
8651 		mutex_unlock(&dm->dc_lock);
8652 	}
8653 
8654 	/**
8655 	 * Enable interrupts for CRTCs that are newly enabled or went through
8656 	 * a modeset. It was intentionally deferred until after the front end
8657 	 * state was modified to wait until the OTG was on and so the IRQ
8658 	 * handlers didn't access stale or invalid state.
8659 	 */
8660 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8661 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8662 #ifdef CONFIG_DEBUG_FS
8663 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
8664 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8665 		struct crc_rd_work *crc_rd_wrk;
8666 #endif
8667 #endif
8668 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
8669 		if (old_crtc_state->active && !new_crtc_state->active)
8670 			crtc_disable_count++;
8671 
8672 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8673 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8674 
8675 		/* For freesync config update on crtc state and params for irq */
8676 		update_stream_irq_parameters(dm, dm_new_crtc_state);
8677 
8678 #ifdef CONFIG_DEBUG_FS
8679 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8680 		crc_rd_wrk = dm->crc_rd_wrk;
8681 #endif
8682 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8683 		cur_crc_src = acrtc->dm_irq_params.crc_src;
8684 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8685 #endif
8686 
8687 		if (new_crtc_state->active &&
8688 		    (!old_crtc_state->active ||
8689 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8690 			dc_stream_retain(dm_new_crtc_state->stream);
8691 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8692 			manage_dm_interrupts(adev, acrtc, true);
8693 		}
8694 		/* Handle vrr on->off / off->on transitions */
8695 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8696 
8697 #ifdef CONFIG_DEBUG_FS
8698 		if (new_crtc_state->active &&
8699 		    (!old_crtc_state->active ||
8700 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8701 			/**
8702 			 * Frontend may have changed so reapply the CRC capture
8703 			 * settings for the stream.
8704 			 */
8705 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8706 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8707 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
8708 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8709 					acrtc->dm_irq_params.crc_window.update_win = true;
8710 					acrtc->dm_irq_params.crc_window.skip_frame_cnt = 2;
8711 					spin_lock_irq(&crc_rd_wrk->crc_rd_work_lock);
8712 					crc_rd_wrk->crtc = crtc;
8713 					spin_unlock_irq(&crc_rd_wrk->crc_rd_work_lock);
8714 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8715 				}
8716 #endif
8717 				if (amdgpu_dm_crtc_configure_crc_source(
8718 					crtc, dm_new_crtc_state, cur_crc_src))
8719 					DRM_DEBUG_DRIVER("Failed to configure crc source");
8720 			}
8721 		}
8722 #endif
8723 	}
8724 
8725 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8726 		if (new_crtc_state->async_flip)
8727 			wait_for_vblank = false;
8728 
8729 	/* update planes when needed per crtc*/
8730 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8731 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8732 
8733 		if (dm_new_crtc_state->stream)
8734 			amdgpu_dm_commit_planes(state, dc_state, dev,
8735 						dm, crtc, wait_for_vblank);
8736 	}
8737 
8738 	/* Update audio instances for each connector. */
8739 	amdgpu_dm_commit_audio(dev, state);
8740 
8741 	/* restore the backlight level */
8742 	for (i = 0; i < dm->num_of_edps; i++) {
8743 		if (dm->backlight_dev[i] &&
8744 		    (dm->actual_brightness[i] != dm->brightness[i]))
8745 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8746 	}
8747 
8748 	/*
8749 	 * send vblank event on all events not handled in flip and
8750 	 * mark consumed event for drm_atomic_helper_commit_hw_done
8751 	 */
8752 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8753 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8754 
8755 		if (new_crtc_state->event)
8756 			drm_send_event_locked(dev, &new_crtc_state->event->base);
8757 
8758 		new_crtc_state->event = NULL;
8759 	}
8760 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8761 
8762 	/* Signal HW programming completion */
8763 	drm_atomic_helper_commit_hw_done(state);
8764 
8765 	if (wait_for_vblank)
8766 		drm_atomic_helper_wait_for_flip_done(dev, state);
8767 
8768 	drm_atomic_helper_cleanup_planes(dev, state);
8769 
8770 	/* return the stolen vga memory back to VRAM */
8771 	if (!adev->mman.keep_stolen_vga_memory)
8772 		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8773 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8774 
8775 	/*
8776 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
8777 	 * so we can put the GPU into runtime suspend if we're not driving any
8778 	 * displays anymore
8779 	 */
8780 	for (i = 0; i < crtc_disable_count; i++)
8781 		pm_runtime_put_autosuspend(dev->dev);
8782 	pm_runtime_mark_last_busy(dev->dev);
8783 
8784 	if (dc_state_temp)
8785 		dc_release_state(dc_state_temp);
8786 }
8787 
8788 static int dm_force_atomic_commit(struct drm_connector *connector)
8789 {
8790 	int ret = 0;
8791 	struct drm_device *ddev = connector->dev;
8792 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8793 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8794 	struct drm_plane *plane = disconnected_acrtc->base.primary;
8795 	struct drm_connector_state *conn_state;
8796 	struct drm_crtc_state *crtc_state;
8797 	struct drm_plane_state *plane_state;
8798 
8799 	if (!state)
8800 		return -ENOMEM;
8801 
8802 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
8803 
8804 	/* Construct an atomic state to restore previous display setting */
8805 
8806 	/*
8807 	 * Attach connectors to drm_atomic_state
8808 	 */
8809 	conn_state = drm_atomic_get_connector_state(state, connector);
8810 
8811 	ret = PTR_ERR_OR_ZERO(conn_state);
8812 	if (ret)
8813 		goto out;
8814 
8815 	/* Attach crtc to drm_atomic_state*/
8816 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8817 
8818 	ret = PTR_ERR_OR_ZERO(crtc_state);
8819 	if (ret)
8820 		goto out;
8821 
8822 	/* force a restore */
8823 	crtc_state->mode_changed = true;
8824 
8825 	/* Attach plane to drm_atomic_state */
8826 	plane_state = drm_atomic_get_plane_state(state, plane);
8827 
8828 	ret = PTR_ERR_OR_ZERO(plane_state);
8829 	if (ret)
8830 		goto out;
8831 
8832 	/* Call commit internally with the state we just constructed */
8833 	ret = drm_atomic_commit(state);
8834 
8835 out:
8836 	drm_atomic_state_put(state);
8837 	if (ret)
8838 		DRM_ERROR("Restoring old state failed with %i\n", ret);
8839 
8840 	return ret;
8841 }
8842 
8843 /*
8844  * This function handles all cases when set mode does not come upon hotplug.
8845  * This includes when a display is unplugged then plugged back into the
8846  * same port and when running without usermode desktop manager supprot
8847  */
8848 void dm_restore_drm_connector_state(struct drm_device *dev,
8849 				    struct drm_connector *connector)
8850 {
8851 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8852 	struct amdgpu_crtc *disconnected_acrtc;
8853 	struct dm_crtc_state *acrtc_state;
8854 
8855 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8856 		return;
8857 
8858 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8859 	if (!disconnected_acrtc)
8860 		return;
8861 
8862 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8863 	if (!acrtc_state->stream)
8864 		return;
8865 
8866 	/*
8867 	 * If the previous sink is not released and different from the current,
8868 	 * we deduce we are in a state where we can not rely on usermode call
8869 	 * to turn on the display, so we do it here
8870 	 */
8871 	if (acrtc_state->stream->sink != aconnector->dc_sink)
8872 		dm_force_atomic_commit(&aconnector->base);
8873 }
8874 
8875 /*
8876  * Grabs all modesetting locks to serialize against any blocking commits,
8877  * Waits for completion of all non blocking commits.
8878  */
8879 static int do_aquire_global_lock(struct drm_device *dev,
8880 				 struct drm_atomic_state *state)
8881 {
8882 	struct drm_crtc *crtc;
8883 	struct drm_crtc_commit *commit;
8884 	long ret;
8885 
8886 	/*
8887 	 * Adding all modeset locks to aquire_ctx will
8888 	 * ensure that when the framework release it the
8889 	 * extra locks we are locking here will get released to
8890 	 */
8891 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8892 	if (ret)
8893 		return ret;
8894 
8895 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8896 		spin_lock(&crtc->commit_lock);
8897 		commit = list_first_entry_or_null(&crtc->commit_list,
8898 				struct drm_crtc_commit, commit_entry);
8899 		if (commit)
8900 			drm_crtc_commit_get(commit);
8901 		spin_unlock(&crtc->commit_lock);
8902 
8903 		if (!commit)
8904 			continue;
8905 
8906 		/*
8907 		 * Make sure all pending HW programming completed and
8908 		 * page flips done
8909 		 */
8910 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8911 
8912 		if (ret > 0)
8913 			ret = wait_for_completion_interruptible_timeout(
8914 					&commit->flip_done, 10*HZ);
8915 
8916 		if (ret == 0)
8917 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done timed out\n",
8918 				  crtc->base.id, crtc->name);
8919 
8920 		drm_crtc_commit_put(commit);
8921 	}
8922 
8923 	return ret < 0 ? ret : 0;
8924 }
8925 
8926 static void get_freesync_config_for_crtc(
8927 	struct dm_crtc_state *new_crtc_state,
8928 	struct dm_connector_state *new_con_state)
8929 {
8930 	struct mod_freesync_config config = {0};
8931 	struct amdgpu_dm_connector *aconnector =
8932 			to_amdgpu_dm_connector(new_con_state->base.connector);
8933 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
8934 	int vrefresh = drm_mode_vrefresh(mode);
8935 	bool fs_vid_mode = false;
8936 
8937 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8938 					vrefresh >= aconnector->min_vfreq &&
8939 					vrefresh <= aconnector->max_vfreq;
8940 
8941 	if (new_crtc_state->vrr_supported) {
8942 		new_crtc_state->stream->ignore_msa_timing_param = true;
8943 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8944 
8945 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8946 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8947 		config.vsif_supported = true;
8948 		config.btr = true;
8949 
8950 		if (fs_vid_mode) {
8951 			config.state = VRR_STATE_ACTIVE_FIXED;
8952 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8953 			goto out;
8954 		} else if (new_crtc_state->base.vrr_enabled) {
8955 			config.state = VRR_STATE_ACTIVE_VARIABLE;
8956 		} else {
8957 			config.state = VRR_STATE_INACTIVE;
8958 		}
8959 	}
8960 out:
8961 	new_crtc_state->freesync_config = config;
8962 }
8963 
8964 static void reset_freesync_config_for_crtc(
8965 	struct dm_crtc_state *new_crtc_state)
8966 {
8967 	new_crtc_state->vrr_supported = false;
8968 
8969 	memset(&new_crtc_state->vrr_infopacket, 0,
8970 	       sizeof(new_crtc_state->vrr_infopacket));
8971 }
8972 
8973 static bool
8974 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8975 				 struct drm_crtc_state *new_crtc_state)
8976 {
8977 	const struct drm_display_mode *old_mode, *new_mode;
8978 
8979 	if (!old_crtc_state || !new_crtc_state)
8980 		return false;
8981 
8982 	old_mode = &old_crtc_state->mode;
8983 	new_mode = &new_crtc_state->mode;
8984 
8985 	if (old_mode->clock       == new_mode->clock &&
8986 	    old_mode->hdisplay    == new_mode->hdisplay &&
8987 	    old_mode->vdisplay    == new_mode->vdisplay &&
8988 	    old_mode->htotal      == new_mode->htotal &&
8989 	    old_mode->vtotal      != new_mode->vtotal &&
8990 	    old_mode->hsync_start == new_mode->hsync_start &&
8991 	    old_mode->vsync_start != new_mode->vsync_start &&
8992 	    old_mode->hsync_end   == new_mode->hsync_end &&
8993 	    old_mode->vsync_end   != new_mode->vsync_end &&
8994 	    old_mode->hskew       == new_mode->hskew &&
8995 	    old_mode->vscan       == new_mode->vscan &&
8996 	    (old_mode->vsync_end - old_mode->vsync_start) ==
8997 	    (new_mode->vsync_end - new_mode->vsync_start))
8998 		return true;
8999 
9000 	return false;
9001 }
9002 
9003 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
9004 {
9005 	u64 num, den, res;
9006 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
9007 
9008 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
9009 
9010 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
9011 	den = (unsigned long long)new_crtc_state->mode.htotal *
9012 	      (unsigned long long)new_crtc_state->mode.vtotal;
9013 
9014 	res = div_u64(num, den);
9015 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
9016 }
9017 
9018 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
9019 			 struct drm_atomic_state *state,
9020 			 struct drm_crtc *crtc,
9021 			 struct drm_crtc_state *old_crtc_state,
9022 			 struct drm_crtc_state *new_crtc_state,
9023 			 bool enable,
9024 			 bool *lock_and_validation_needed)
9025 {
9026 	struct dm_atomic_state *dm_state = NULL;
9027 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9028 	struct dc_stream_state *new_stream;
9029 	int ret = 0;
9030 
9031 	/*
9032 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
9033 	 * update changed items
9034 	 */
9035 	struct amdgpu_crtc *acrtc = NULL;
9036 	struct amdgpu_dm_connector *aconnector = NULL;
9037 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
9038 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
9039 
9040 	new_stream = NULL;
9041 
9042 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9043 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9044 	acrtc = to_amdgpu_crtc(crtc);
9045 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
9046 
9047 	/* TODO This hack should go away */
9048 	if (aconnector && enable) {
9049 		/* Make sure fake sink is created in plug-in scenario */
9050 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
9051 							    &aconnector->base);
9052 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
9053 							    &aconnector->base);
9054 
9055 		if (IS_ERR(drm_new_conn_state)) {
9056 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
9057 			goto fail;
9058 		}
9059 
9060 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
9061 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
9062 
9063 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9064 			goto skip_modeset;
9065 
9066 		new_stream = create_validate_stream_for_sink(aconnector,
9067 							     &new_crtc_state->mode,
9068 							     dm_new_conn_state,
9069 							     dm_old_crtc_state->stream);
9070 
9071 		/*
9072 		 * we can have no stream on ACTION_SET if a display
9073 		 * was disconnected during S3, in this case it is not an
9074 		 * error, the OS will be updated after detection, and
9075 		 * will do the right thing on next atomic commit
9076 		 */
9077 
9078 		if (!new_stream) {
9079 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
9080 					__func__, acrtc->base.base.id);
9081 			ret = -ENOMEM;
9082 			goto fail;
9083 		}
9084 
9085 		/*
9086 		 * TODO: Check VSDB bits to decide whether this should
9087 		 * be enabled or not.
9088 		 */
9089 		new_stream->triggered_crtc_reset.enabled =
9090 			dm->force_timing_sync;
9091 
9092 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9093 
9094 		ret = fill_hdr_info_packet(drm_new_conn_state,
9095 					   &new_stream->hdr_static_metadata);
9096 		if (ret)
9097 			goto fail;
9098 
9099 		/*
9100 		 * If we already removed the old stream from the context
9101 		 * (and set the new stream to NULL) then we can't reuse
9102 		 * the old stream even if the stream and scaling are unchanged.
9103 		 * We'll hit the BUG_ON and black screen.
9104 		 *
9105 		 * TODO: Refactor this function to allow this check to work
9106 		 * in all conditions.
9107 		 */
9108 		if (dm_new_crtc_state->stream &&
9109 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
9110 			goto skip_modeset;
9111 
9112 		if (dm_new_crtc_state->stream &&
9113 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9114 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
9115 			new_crtc_state->mode_changed = false;
9116 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
9117 					 new_crtc_state->mode_changed);
9118 		}
9119 	}
9120 
9121 	/* mode_changed flag may get updated above, need to check again */
9122 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9123 		goto skip_modeset;
9124 
9125 	drm_dbg_state(state->dev,
9126 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
9127 		acrtc->crtc_id,
9128 		new_crtc_state->enable,
9129 		new_crtc_state->active,
9130 		new_crtc_state->planes_changed,
9131 		new_crtc_state->mode_changed,
9132 		new_crtc_state->active_changed,
9133 		new_crtc_state->connectors_changed);
9134 
9135 	/* Remove stream for any changed/disabled CRTC */
9136 	if (!enable) {
9137 
9138 		if (!dm_old_crtc_state->stream)
9139 			goto skip_modeset;
9140 
9141 		/* Unset freesync video if it was active before */
9142 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
9143 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
9144 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
9145 		}
9146 
9147 		/* Now check if we should set freesync video mode */
9148 		if (dm_new_crtc_state->stream &&
9149 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9150 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
9151 		    is_timing_unchanged_for_freesync(new_crtc_state,
9152 						     old_crtc_state)) {
9153 			new_crtc_state->mode_changed = false;
9154 			DRM_DEBUG_DRIVER(
9155 				"Mode change not required for front porch change, setting mode_changed to %d",
9156 				new_crtc_state->mode_changed);
9157 
9158 			set_freesync_fixed_config(dm_new_crtc_state);
9159 
9160 			goto skip_modeset;
9161 		} else if (aconnector &&
9162 			   is_freesync_video_mode(&new_crtc_state->mode,
9163 						  aconnector)) {
9164 			struct drm_display_mode *high_mode;
9165 
9166 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
9167 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
9168 				set_freesync_fixed_config(dm_new_crtc_state);
9169 		}
9170 
9171 		ret = dm_atomic_get_state(state, &dm_state);
9172 		if (ret)
9173 			goto fail;
9174 
9175 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
9176 				crtc->base.id);
9177 
9178 		/* i.e. reset mode */
9179 		if (dc_remove_stream_from_ctx(
9180 				dm->dc,
9181 				dm_state->context,
9182 				dm_old_crtc_state->stream) != DC_OK) {
9183 			ret = -EINVAL;
9184 			goto fail;
9185 		}
9186 
9187 		dc_stream_release(dm_old_crtc_state->stream);
9188 		dm_new_crtc_state->stream = NULL;
9189 
9190 		reset_freesync_config_for_crtc(dm_new_crtc_state);
9191 
9192 		*lock_and_validation_needed = true;
9193 
9194 	} else {/* Add stream for any updated/enabled CRTC */
9195 		/*
9196 		 * Quick fix to prevent NULL pointer on new_stream when
9197 		 * added MST connectors not found in existing crtc_state in the chained mode
9198 		 * TODO: need to dig out the root cause of that
9199 		 */
9200 		if (!aconnector)
9201 			goto skip_modeset;
9202 
9203 		if (modereset_required(new_crtc_state))
9204 			goto skip_modeset;
9205 
9206 		if (modeset_required(new_crtc_state, new_stream,
9207 				     dm_old_crtc_state->stream)) {
9208 
9209 			WARN_ON(dm_new_crtc_state->stream);
9210 
9211 			ret = dm_atomic_get_state(state, &dm_state);
9212 			if (ret)
9213 				goto fail;
9214 
9215 			dm_new_crtc_state->stream = new_stream;
9216 
9217 			dc_stream_retain(new_stream);
9218 
9219 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
9220 					 crtc->base.id);
9221 
9222 			if (dc_add_stream_to_ctx(
9223 					dm->dc,
9224 					dm_state->context,
9225 					dm_new_crtc_state->stream) != DC_OK) {
9226 				ret = -EINVAL;
9227 				goto fail;
9228 			}
9229 
9230 			*lock_and_validation_needed = true;
9231 		}
9232 	}
9233 
9234 skip_modeset:
9235 	/* Release extra reference */
9236 	if (new_stream)
9237 		 dc_stream_release(new_stream);
9238 
9239 	/*
9240 	 * We want to do dc stream updates that do not require a
9241 	 * full modeset below.
9242 	 */
9243 	if (!(enable && aconnector && new_crtc_state->active))
9244 		return 0;
9245 	/*
9246 	 * Given above conditions, the dc state cannot be NULL because:
9247 	 * 1. We're in the process of enabling CRTCs (just been added
9248 	 *    to the dc context, or already is on the context)
9249 	 * 2. Has a valid connector attached, and
9250 	 * 3. Is currently active and enabled.
9251 	 * => The dc stream state currently exists.
9252 	 */
9253 	BUG_ON(dm_new_crtc_state->stream == NULL);
9254 
9255 	/* Scaling or underscan settings */
9256 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
9257 				drm_atomic_crtc_needs_modeset(new_crtc_state))
9258 		update_stream_scaling_settings(
9259 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
9260 
9261 	/* ABM settings */
9262 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9263 
9264 	/*
9265 	 * Color management settings. We also update color properties
9266 	 * when a modeset is needed, to ensure it gets reprogrammed.
9267 	 */
9268 	if (dm_new_crtc_state->base.color_mgmt_changed ||
9269 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9270 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
9271 		if (ret)
9272 			goto fail;
9273 	}
9274 
9275 	/* Update Freesync settings. */
9276 	get_freesync_config_for_crtc(dm_new_crtc_state,
9277 				     dm_new_conn_state);
9278 
9279 	return ret;
9280 
9281 fail:
9282 	if (new_stream)
9283 		dc_stream_release(new_stream);
9284 	return ret;
9285 }
9286 
9287 static bool should_reset_plane(struct drm_atomic_state *state,
9288 			       struct drm_plane *plane,
9289 			       struct drm_plane_state *old_plane_state,
9290 			       struct drm_plane_state *new_plane_state)
9291 {
9292 	struct drm_plane *other;
9293 	struct drm_plane_state *old_other_state, *new_other_state;
9294 	struct drm_crtc_state *new_crtc_state;
9295 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9296 	int i;
9297 
9298 	/*
9299 	 * TODO: Remove this hack for all asics once it proves that the
9300 	 * fast updates works fine on DCN3.2+.
9301 	 */
9302 	if (adev->ip_versions[DCE_HWIP][0] < IP_VERSION(3, 2, 0) && state->allow_modeset)
9303 		return true;
9304 
9305 	/* Exit early if we know that we're adding or removing the plane. */
9306 	if (old_plane_state->crtc != new_plane_state->crtc)
9307 		return true;
9308 
9309 	/* old crtc == new_crtc == NULL, plane not in context. */
9310 	if (!new_plane_state->crtc)
9311 		return false;
9312 
9313 	new_crtc_state =
9314 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
9315 
9316 	if (!new_crtc_state)
9317 		return true;
9318 
9319 	/* CRTC Degamma changes currently require us to recreate planes. */
9320 	if (new_crtc_state->color_mgmt_changed)
9321 		return true;
9322 
9323 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
9324 		return true;
9325 
9326 	/*
9327 	 * If there are any new primary or overlay planes being added or
9328 	 * removed then the z-order can potentially change. To ensure
9329 	 * correct z-order and pipe acquisition the current DC architecture
9330 	 * requires us to remove and recreate all existing planes.
9331 	 *
9332 	 * TODO: Come up with a more elegant solution for this.
9333 	 */
9334 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9335 		struct amdgpu_framebuffer *old_afb, *new_afb;
9336 
9337 		if (other->type == DRM_PLANE_TYPE_CURSOR)
9338 			continue;
9339 
9340 		if (old_other_state->crtc != new_plane_state->crtc &&
9341 		    new_other_state->crtc != new_plane_state->crtc)
9342 			continue;
9343 
9344 		if (old_other_state->crtc != new_other_state->crtc)
9345 			return true;
9346 
9347 		/* Src/dst size and scaling updates. */
9348 		if (old_other_state->src_w != new_other_state->src_w ||
9349 		    old_other_state->src_h != new_other_state->src_h ||
9350 		    old_other_state->crtc_w != new_other_state->crtc_w ||
9351 		    old_other_state->crtc_h != new_other_state->crtc_h)
9352 			return true;
9353 
9354 		/* Rotation / mirroring updates. */
9355 		if (old_other_state->rotation != new_other_state->rotation)
9356 			return true;
9357 
9358 		/* Blending updates. */
9359 		if (old_other_state->pixel_blend_mode !=
9360 		    new_other_state->pixel_blend_mode)
9361 			return true;
9362 
9363 		/* Alpha updates. */
9364 		if (old_other_state->alpha != new_other_state->alpha)
9365 			return true;
9366 
9367 		/* Colorspace changes. */
9368 		if (old_other_state->color_range != new_other_state->color_range ||
9369 		    old_other_state->color_encoding != new_other_state->color_encoding)
9370 			return true;
9371 
9372 		/* Framebuffer checks fall at the end. */
9373 		if (!old_other_state->fb || !new_other_state->fb)
9374 			continue;
9375 
9376 		/* Pixel format changes can require bandwidth updates. */
9377 		if (old_other_state->fb->format != new_other_state->fb->format)
9378 			return true;
9379 
9380 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9381 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9382 
9383 		/* Tiling and DCC changes also require bandwidth updates. */
9384 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
9385 		    old_afb->base.modifier != new_afb->base.modifier)
9386 			return true;
9387 	}
9388 
9389 	return false;
9390 }
9391 
9392 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9393 			      struct drm_plane_state *new_plane_state,
9394 			      struct drm_framebuffer *fb)
9395 {
9396 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9397 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9398 	unsigned int pitch;
9399 	bool linear;
9400 
9401 	if (fb->width > new_acrtc->max_cursor_width ||
9402 	    fb->height > new_acrtc->max_cursor_height) {
9403 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9404 				 new_plane_state->fb->width,
9405 				 new_plane_state->fb->height);
9406 		return -EINVAL;
9407 	}
9408 	if (new_plane_state->src_w != fb->width << 16 ||
9409 	    new_plane_state->src_h != fb->height << 16) {
9410 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9411 		return -EINVAL;
9412 	}
9413 
9414 	/* Pitch in pixels */
9415 	pitch = fb->pitches[0] / fb->format->cpp[0];
9416 
9417 	if (fb->width != pitch) {
9418 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9419 				 fb->width, pitch);
9420 		return -EINVAL;
9421 	}
9422 
9423 	switch (pitch) {
9424 	case 64:
9425 	case 128:
9426 	case 256:
9427 		/* FB pitch is supported by cursor plane */
9428 		break;
9429 	default:
9430 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9431 		return -EINVAL;
9432 	}
9433 
9434 	/* Core DRM takes care of checking FB modifiers, so we only need to
9435 	 * check tiling flags when the FB doesn't have a modifier.
9436 	 */
9437 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9438 		if (adev->family < AMDGPU_FAMILY_AI) {
9439 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9440 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9441 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9442 		} else {
9443 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9444 		}
9445 		if (!linear) {
9446 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
9447 			return -EINVAL;
9448 		}
9449 	}
9450 
9451 	return 0;
9452 }
9453 
9454 static int dm_update_plane_state(struct dc *dc,
9455 				 struct drm_atomic_state *state,
9456 				 struct drm_plane *plane,
9457 				 struct drm_plane_state *old_plane_state,
9458 				 struct drm_plane_state *new_plane_state,
9459 				 bool enable,
9460 				 bool *lock_and_validation_needed)
9461 {
9462 
9463 	struct dm_atomic_state *dm_state = NULL;
9464 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9465 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9466 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9467 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9468 	struct amdgpu_crtc *new_acrtc;
9469 	bool needs_reset;
9470 	int ret = 0;
9471 
9472 
9473 	new_plane_crtc = new_plane_state->crtc;
9474 	old_plane_crtc = old_plane_state->crtc;
9475 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
9476 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
9477 
9478 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9479 		if (!enable || !new_plane_crtc ||
9480 			drm_atomic_plane_disabling(plane->state, new_plane_state))
9481 			return 0;
9482 
9483 		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9484 
9485 		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9486 			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9487 			return -EINVAL;
9488 		}
9489 
9490 		if (new_plane_state->fb) {
9491 			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9492 						 new_plane_state->fb);
9493 			if (ret)
9494 				return ret;
9495 		}
9496 
9497 		return 0;
9498 	}
9499 
9500 	needs_reset = should_reset_plane(state, plane, old_plane_state,
9501 					 new_plane_state);
9502 
9503 	/* Remove any changed/removed planes */
9504 	if (!enable) {
9505 		if (!needs_reset)
9506 			return 0;
9507 
9508 		if (!old_plane_crtc)
9509 			return 0;
9510 
9511 		old_crtc_state = drm_atomic_get_old_crtc_state(
9512 				state, old_plane_crtc);
9513 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9514 
9515 		if (!dm_old_crtc_state->stream)
9516 			return 0;
9517 
9518 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9519 				plane->base.id, old_plane_crtc->base.id);
9520 
9521 		ret = dm_atomic_get_state(state, &dm_state);
9522 		if (ret)
9523 			return ret;
9524 
9525 		if (!dc_remove_plane_from_context(
9526 				dc,
9527 				dm_old_crtc_state->stream,
9528 				dm_old_plane_state->dc_state,
9529 				dm_state->context)) {
9530 
9531 			return -EINVAL;
9532 		}
9533 
9534 		if (dm_old_plane_state->dc_state)
9535 			dc_plane_state_release(dm_old_plane_state->dc_state);
9536 
9537 		dm_new_plane_state->dc_state = NULL;
9538 
9539 		*lock_and_validation_needed = true;
9540 
9541 	} else { /* Add new planes */
9542 		struct dc_plane_state *dc_new_plane_state;
9543 
9544 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9545 			return 0;
9546 
9547 		if (!new_plane_crtc)
9548 			return 0;
9549 
9550 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9551 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9552 
9553 		if (!dm_new_crtc_state->stream)
9554 			return 0;
9555 
9556 		if (!needs_reset)
9557 			return 0;
9558 
9559 		ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9560 		if (ret)
9561 			return ret;
9562 
9563 		WARN_ON(dm_new_plane_state->dc_state);
9564 
9565 		dc_new_plane_state = dc_create_plane_state(dc);
9566 		if (!dc_new_plane_state)
9567 			return -ENOMEM;
9568 
9569 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9570 				 plane->base.id, new_plane_crtc->base.id);
9571 
9572 		ret = fill_dc_plane_attributes(
9573 			drm_to_adev(new_plane_crtc->dev),
9574 			dc_new_plane_state,
9575 			new_plane_state,
9576 			new_crtc_state);
9577 		if (ret) {
9578 			dc_plane_state_release(dc_new_plane_state);
9579 			return ret;
9580 		}
9581 
9582 		ret = dm_atomic_get_state(state, &dm_state);
9583 		if (ret) {
9584 			dc_plane_state_release(dc_new_plane_state);
9585 			return ret;
9586 		}
9587 
9588 		/*
9589 		 * Any atomic check errors that occur after this will
9590 		 * not need a release. The plane state will be attached
9591 		 * to the stream, and therefore part of the atomic
9592 		 * state. It'll be released when the atomic state is
9593 		 * cleaned.
9594 		 */
9595 		if (!dc_add_plane_to_context(
9596 				dc,
9597 				dm_new_crtc_state->stream,
9598 				dc_new_plane_state,
9599 				dm_state->context)) {
9600 
9601 			dc_plane_state_release(dc_new_plane_state);
9602 			return -EINVAL;
9603 		}
9604 
9605 		dm_new_plane_state->dc_state = dc_new_plane_state;
9606 
9607 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9608 
9609 		/* Tell DC to do a full surface update every time there
9610 		 * is a plane change. Inefficient, but works for now.
9611 		 */
9612 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9613 
9614 		*lock_and_validation_needed = true;
9615 	}
9616 
9617 
9618 	return ret;
9619 }
9620 
9621 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9622 				       int *src_w, int *src_h)
9623 {
9624 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9625 	case DRM_MODE_ROTATE_90:
9626 	case DRM_MODE_ROTATE_270:
9627 		*src_w = plane_state->src_h >> 16;
9628 		*src_h = plane_state->src_w >> 16;
9629 		break;
9630 	case DRM_MODE_ROTATE_0:
9631 	case DRM_MODE_ROTATE_180:
9632 	default:
9633 		*src_w = plane_state->src_w >> 16;
9634 		*src_h = plane_state->src_h >> 16;
9635 		break;
9636 	}
9637 }
9638 
9639 static void
9640 dm_get_plane_scale(struct drm_plane_state *plane_state,
9641 		   int *out_plane_scale_w, int *out_plane_scale_h)
9642 {
9643 	int plane_src_w, plane_src_h;
9644 
9645 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
9646 	*out_plane_scale_w = plane_state->crtc_w * 1000 / plane_src_w;
9647 	*out_plane_scale_h = plane_state->crtc_h * 1000 / plane_src_h;
9648 }
9649 
9650 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9651 				struct drm_crtc *crtc,
9652 				struct drm_crtc_state *new_crtc_state)
9653 {
9654 	struct drm_plane *cursor = crtc->cursor, *plane, *underlying;
9655 	struct drm_plane_state *old_plane_state, *new_plane_state;
9656 	struct drm_plane_state *new_cursor_state, *new_underlying_state;
9657 	int i;
9658 	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9659 	bool any_relevant_change = false;
9660 
9661 	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9662 	 * cursor per pipe but it's going to inherit the scaling and
9663 	 * positioning from the underlying pipe. Check the cursor plane's
9664 	 * blending properties match the underlying planes'.
9665 	 */
9666 
9667 	/* If no plane was enabled or changed scaling, no need to check again */
9668 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9669 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
9670 
9671 		if (!new_plane_state || !new_plane_state->fb || new_plane_state->crtc != crtc)
9672 			continue;
9673 
9674 		if (!old_plane_state || !old_plane_state->fb || old_plane_state->crtc != crtc) {
9675 			any_relevant_change = true;
9676 			break;
9677 		}
9678 
9679 		if (new_plane_state->fb == old_plane_state->fb &&
9680 		    new_plane_state->crtc_w == old_plane_state->crtc_w &&
9681 		    new_plane_state->crtc_h == old_plane_state->crtc_h)
9682 			continue;
9683 
9684 		dm_get_plane_scale(new_plane_state, &new_scale_w, &new_scale_h);
9685 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
9686 
9687 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
9688 			any_relevant_change = true;
9689 			break;
9690 		}
9691 	}
9692 
9693 	if (!any_relevant_change)
9694 		return 0;
9695 
9696 	new_cursor_state = drm_atomic_get_plane_state(state, cursor);
9697 	if (IS_ERR(new_cursor_state))
9698 		return PTR_ERR(new_cursor_state);
9699 
9700 	if (!new_cursor_state->fb)
9701 		return 0;
9702 
9703 	dm_get_plane_scale(new_cursor_state, &cursor_scale_w, &cursor_scale_h);
9704 
9705 	/* Need to check all enabled planes, even if this commit doesn't change
9706 	 * their state
9707 	 */
9708 	i = drm_atomic_add_affected_planes(state, crtc);
9709 	if (i)
9710 		return i;
9711 
9712 	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9713 		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
9714 		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9715 			continue;
9716 
9717 		/* Ignore disabled planes */
9718 		if (!new_underlying_state->fb)
9719 			continue;
9720 
9721 		dm_get_plane_scale(new_underlying_state,
9722 				   &underlying_scale_w, &underlying_scale_h);
9723 
9724 		if (cursor_scale_w != underlying_scale_w ||
9725 		    cursor_scale_h != underlying_scale_h) {
9726 			drm_dbg_atomic(crtc->dev,
9727 				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9728 				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9729 			return -EINVAL;
9730 		}
9731 
9732 		/* If this plane covers the whole CRTC, no need to check planes underneath */
9733 		if (new_underlying_state->crtc_x <= 0 &&
9734 		    new_underlying_state->crtc_y <= 0 &&
9735 		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9736 		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9737 			break;
9738 	}
9739 
9740 	return 0;
9741 }
9742 
9743 #if defined(CONFIG_DRM_AMD_DC_DCN)
9744 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9745 {
9746 	struct drm_connector *connector;
9747 	struct drm_connector_state *conn_state, *old_conn_state;
9748 	struct amdgpu_dm_connector *aconnector = NULL;
9749 	int i;
9750 
9751 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9752 		if (!conn_state->crtc)
9753 			conn_state = old_conn_state;
9754 
9755 		if (conn_state->crtc != crtc)
9756 			continue;
9757 
9758 		aconnector = to_amdgpu_dm_connector(connector);
9759 		if (!aconnector->port || !aconnector->mst_port)
9760 			aconnector = NULL;
9761 		else
9762 			break;
9763 	}
9764 
9765 	if (!aconnector)
9766 		return 0;
9767 
9768 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_port->mst_mgr);
9769 }
9770 #endif
9771 
9772 /**
9773  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9774  *
9775  * @dev: The DRM device
9776  * @state: The atomic state to commit
9777  *
9778  * Validate that the given atomic state is programmable by DC into hardware.
9779  * This involves constructing a &struct dc_state reflecting the new hardware
9780  * state we wish to commit, then querying DC to see if it is programmable. It's
9781  * important not to modify the existing DC state. Otherwise, atomic_check
9782  * may unexpectedly commit hardware changes.
9783  *
9784  * When validating the DC state, it's important that the right locks are
9785  * acquired. For full updates case which removes/adds/updates streams on one
9786  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9787  * that any such full update commit will wait for completion of any outstanding
9788  * flip using DRMs synchronization events.
9789  *
9790  * Note that DM adds the affected connectors for all CRTCs in state, when that
9791  * might not seem necessary. This is because DC stream creation requires the
9792  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9793  * be possible but non-trivial - a possible TODO item.
9794  *
9795  * Return: -Error code if validation failed.
9796  */
9797 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9798 				  struct drm_atomic_state *state)
9799 {
9800 	struct amdgpu_device *adev = drm_to_adev(dev);
9801 	struct dm_atomic_state *dm_state = NULL;
9802 	struct dc *dc = adev->dm.dc;
9803 	struct drm_connector *connector;
9804 	struct drm_connector_state *old_con_state, *new_con_state;
9805 	struct drm_crtc *crtc;
9806 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9807 	struct drm_plane *plane;
9808 	struct drm_plane_state *old_plane_state, *new_plane_state;
9809 	enum dc_status status;
9810 	int ret, i;
9811 	bool lock_and_validation_needed = false;
9812 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9813 #if defined(CONFIG_DRM_AMD_DC_DCN)
9814 	struct drm_dp_mst_topology_mgr *mgr;
9815 	struct drm_dp_mst_topology_state *mst_state;
9816 	struct dsc_mst_fairness_vars vars[MAX_PIPES];
9817 #endif
9818 
9819 	trace_amdgpu_dm_atomic_check_begin(state);
9820 
9821 	ret = drm_atomic_helper_check_modeset(dev, state);
9822 	if (ret) {
9823 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9824 		goto fail;
9825 	}
9826 
9827 	/* Check connector changes */
9828 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9829 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9830 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9831 
9832 		/* Skip connectors that are disabled or part of modeset already. */
9833 		if (!new_con_state->crtc)
9834 			continue;
9835 
9836 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9837 		if (IS_ERR(new_crtc_state)) {
9838 			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9839 			ret = PTR_ERR(new_crtc_state);
9840 			goto fail;
9841 		}
9842 
9843 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
9844 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
9845 			new_crtc_state->connectors_changed = true;
9846 	}
9847 
9848 #if defined(CONFIG_DRM_AMD_DC_DCN)
9849 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9850 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9851 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9852 				ret = add_affected_mst_dsc_crtcs(state, crtc);
9853 				if (ret) {
9854 					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9855 					goto fail;
9856 				}
9857 			}
9858 		}
9859 	}
9860 #endif
9861 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9862 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9863 
9864 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9865 		    !new_crtc_state->color_mgmt_changed &&
9866 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9867 			dm_old_crtc_state->dsc_force_changed == false)
9868 			continue;
9869 
9870 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9871 		if (ret) {
9872 			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9873 			goto fail;
9874 		}
9875 
9876 		if (!new_crtc_state->enable)
9877 			continue;
9878 
9879 		ret = drm_atomic_add_affected_connectors(state, crtc);
9880 		if (ret) {
9881 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9882 			goto fail;
9883 		}
9884 
9885 		ret = drm_atomic_add_affected_planes(state, crtc);
9886 		if (ret) {
9887 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9888 			goto fail;
9889 		}
9890 
9891 		if (dm_old_crtc_state->dsc_force_changed)
9892 			new_crtc_state->mode_changed = true;
9893 	}
9894 
9895 	/*
9896 	 * Add all primary and overlay planes on the CRTC to the state
9897 	 * whenever a plane is enabled to maintain correct z-ordering
9898 	 * and to enable fast surface updates.
9899 	 */
9900 	drm_for_each_crtc(crtc, dev) {
9901 		bool modified = false;
9902 
9903 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9904 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9905 				continue;
9906 
9907 			if (new_plane_state->crtc == crtc ||
9908 			    old_plane_state->crtc == crtc) {
9909 				modified = true;
9910 				break;
9911 			}
9912 		}
9913 
9914 		if (!modified)
9915 			continue;
9916 
9917 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9918 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9919 				continue;
9920 
9921 			new_plane_state =
9922 				drm_atomic_get_plane_state(state, plane);
9923 
9924 			if (IS_ERR(new_plane_state)) {
9925 				ret = PTR_ERR(new_plane_state);
9926 				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9927 				goto fail;
9928 			}
9929 		}
9930 	}
9931 
9932 	/*
9933 	 * DC consults the zpos (layer_index in DC terminology) to determine the
9934 	 * hw plane on which to enable the hw cursor (see
9935 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9936 	 * atomic state, so call drm helper to normalize zpos.
9937 	 */
9938 	ret = drm_atomic_normalize_zpos(dev, state);
9939 	if (ret) {
9940 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
9941 		goto fail;
9942 	}
9943 
9944 	/* Remove exiting planes if they are modified */
9945 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9946 		if (old_plane_state->fb && new_plane_state->fb &&
9947 		    get_mem_type(old_plane_state->fb) !=
9948 		    get_mem_type(new_plane_state->fb))
9949 			lock_and_validation_needed = true;
9950 
9951 		ret = dm_update_plane_state(dc, state, plane,
9952 					    old_plane_state,
9953 					    new_plane_state,
9954 					    false,
9955 					    &lock_and_validation_needed);
9956 		if (ret) {
9957 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9958 			goto fail;
9959 		}
9960 	}
9961 
9962 	/* Disable all crtcs which require disable */
9963 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9964 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9965 					   old_crtc_state,
9966 					   new_crtc_state,
9967 					   false,
9968 					   &lock_and_validation_needed);
9969 		if (ret) {
9970 			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9971 			goto fail;
9972 		}
9973 	}
9974 
9975 	/* Enable all crtcs which require enable */
9976 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9977 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9978 					   old_crtc_state,
9979 					   new_crtc_state,
9980 					   true,
9981 					   &lock_and_validation_needed);
9982 		if (ret) {
9983 			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9984 			goto fail;
9985 		}
9986 	}
9987 
9988 	/* Add new/modified planes */
9989 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9990 		ret = dm_update_plane_state(dc, state, plane,
9991 					    old_plane_state,
9992 					    new_plane_state,
9993 					    true,
9994 					    &lock_and_validation_needed);
9995 		if (ret) {
9996 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9997 			goto fail;
9998 		}
9999 	}
10000 
10001 #if defined(CONFIG_DRM_AMD_DC_DCN)
10002 	if (dc_resource_is_dsc_encoding_supported(dc)) {
10003 		ret = pre_validate_dsc(state, &dm_state, vars);
10004 		if (ret != 0)
10005 			goto fail;
10006 	}
10007 #endif
10008 
10009 	/* Run this here since we want to validate the streams we created */
10010 	ret = drm_atomic_helper_check_planes(dev, state);
10011 	if (ret) {
10012 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
10013 		goto fail;
10014 	}
10015 
10016 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10017 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10018 		if (dm_new_crtc_state->mpo_requested)
10019 			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
10020 	}
10021 
10022 	/* Check cursor planes scaling */
10023 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10024 		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
10025 		if (ret) {
10026 			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
10027 			goto fail;
10028 		}
10029 	}
10030 
10031 	if (state->legacy_cursor_update) {
10032 		/*
10033 		 * This is a fast cursor update coming from the plane update
10034 		 * helper, check if it can be done asynchronously for better
10035 		 * performance.
10036 		 */
10037 		state->async_update =
10038 			!drm_atomic_helper_async_check(dev, state);
10039 
10040 		/*
10041 		 * Skip the remaining global validation if this is an async
10042 		 * update. Cursor updates can be done without affecting
10043 		 * state or bandwidth calcs and this avoids the performance
10044 		 * penalty of locking the private state object and
10045 		 * allocating a new dc_state.
10046 		 */
10047 		if (state->async_update)
10048 			return 0;
10049 	}
10050 
10051 	/* Check scaling and underscan changes*/
10052 	/* TODO Removed scaling changes validation due to inability to commit
10053 	 * new stream into context w\o causing full reset. Need to
10054 	 * decide how to handle.
10055 	 */
10056 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10057 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10058 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10059 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10060 
10061 		/* Skip any modesets/resets */
10062 		if (!acrtc || drm_atomic_crtc_needs_modeset(
10063 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
10064 			continue;
10065 
10066 		/* Skip any thing not scale or underscan changes */
10067 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
10068 			continue;
10069 
10070 		lock_and_validation_needed = true;
10071 	}
10072 
10073 #if defined(CONFIG_DRM_AMD_DC_DCN)
10074 	/* set the slot info for each mst_state based on the link encoding format */
10075 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
10076 		struct amdgpu_dm_connector *aconnector;
10077 		struct drm_connector *connector;
10078 		struct drm_connector_list_iter iter;
10079 		u8 link_coding_cap;
10080 
10081 		drm_connector_list_iter_begin(dev, &iter);
10082 		drm_for_each_connector_iter(connector, &iter) {
10083 			if (connector->index == mst_state->mgr->conn_base_id) {
10084 				aconnector = to_amdgpu_dm_connector(connector);
10085 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
10086 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
10087 
10088 				break;
10089 			}
10090 		}
10091 		drm_connector_list_iter_end(&iter);
10092 	}
10093 #endif
10094 
10095 	/**
10096 	 * Streams and planes are reset when there are changes that affect
10097 	 * bandwidth. Anything that affects bandwidth needs to go through
10098 	 * DC global validation to ensure that the configuration can be applied
10099 	 * to hardware.
10100 	 *
10101 	 * We have to currently stall out here in atomic_check for outstanding
10102 	 * commits to finish in this case because our IRQ handlers reference
10103 	 * DRM state directly - we can end up disabling interrupts too early
10104 	 * if we don't.
10105 	 *
10106 	 * TODO: Remove this stall and drop DM state private objects.
10107 	 */
10108 	if (lock_and_validation_needed) {
10109 		ret = dm_atomic_get_state(state, &dm_state);
10110 		if (ret) {
10111 			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
10112 			goto fail;
10113 		}
10114 
10115 		ret = do_aquire_global_lock(dev, state);
10116 		if (ret) {
10117 			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
10118 			goto fail;
10119 		}
10120 
10121 #if defined(CONFIG_DRM_AMD_DC_DCN)
10122 		ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
10123 		if (ret) {
10124 			DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
10125 			ret = -EINVAL;
10126 			goto fail;
10127 		}
10128 
10129 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
10130 		if (ret) {
10131 			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
10132 			goto fail;
10133 		}
10134 #endif
10135 
10136 		/*
10137 		 * Perform validation of MST topology in the state:
10138 		 * We need to perform MST atomic check before calling
10139 		 * dc_validate_global_state(), or there is a chance
10140 		 * to get stuck in an infinite loop and hang eventually.
10141 		 */
10142 		ret = drm_dp_mst_atomic_check(state);
10143 		if (ret) {
10144 			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
10145 			goto fail;
10146 		}
10147 		status = dc_validate_global_state(dc, dm_state->context, true);
10148 		if (status != DC_OK) {
10149 			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
10150 				       dc_status_to_str(status), status);
10151 			ret = -EINVAL;
10152 			goto fail;
10153 		}
10154 	} else {
10155 		/*
10156 		 * The commit is a fast update. Fast updates shouldn't change
10157 		 * the DC context, affect global validation, and can have their
10158 		 * commit work done in parallel with other commits not touching
10159 		 * the same resource. If we have a new DC context as part of
10160 		 * the DM atomic state from validation we need to free it and
10161 		 * retain the existing one instead.
10162 		 *
10163 		 * Furthermore, since the DM atomic state only contains the DC
10164 		 * context and can safely be annulled, we can free the state
10165 		 * and clear the associated private object now to free
10166 		 * some memory and avoid a possible use-after-free later.
10167 		 */
10168 
10169 		for (i = 0; i < state->num_private_objs; i++) {
10170 			struct drm_private_obj *obj = state->private_objs[i].ptr;
10171 
10172 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
10173 				int j = state->num_private_objs-1;
10174 
10175 				dm_atomic_destroy_state(obj,
10176 						state->private_objs[i].state);
10177 
10178 				/* If i is not at the end of the array then the
10179 				 * last element needs to be moved to where i was
10180 				 * before the array can safely be truncated.
10181 				 */
10182 				if (i != j)
10183 					state->private_objs[i] =
10184 						state->private_objs[j];
10185 
10186 				state->private_objs[j].ptr = NULL;
10187 				state->private_objs[j].state = NULL;
10188 				state->private_objs[j].old_state = NULL;
10189 				state->private_objs[j].new_state = NULL;
10190 
10191 				state->num_private_objs = j;
10192 				break;
10193 			}
10194 		}
10195 	}
10196 
10197 	/* Store the overall update type for use later in atomic check. */
10198 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10199 		struct dm_crtc_state *dm_new_crtc_state =
10200 			to_dm_crtc_state(new_crtc_state);
10201 
10202 		/*
10203 		 * Only allow async flips for fast updates that don't change
10204 		 * the FB pitch, the DCC state, rotation, etc.
10205 		 */
10206 		if (new_crtc_state->async_flip && lock_and_validation_needed) {
10207 			drm_dbg_atomic(crtc->dev,
10208 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
10209 				       crtc->base.id, crtc->name);
10210 			ret = -EINVAL;
10211 			goto fail;
10212 		}
10213 
10214 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
10215 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
10216 	}
10217 
10218 	/* Must be success */
10219 	WARN_ON(ret);
10220 
10221 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10222 
10223 	return ret;
10224 
10225 fail:
10226 	if (ret == -EDEADLK)
10227 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10228 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10229 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10230 	else
10231 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d\n", ret);
10232 
10233 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10234 
10235 	return ret;
10236 }
10237 
10238 static bool is_dp_capable_without_timing_msa(struct dc *dc,
10239 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
10240 {
10241 	u8 dpcd_data;
10242 	bool capable = false;
10243 
10244 	if (amdgpu_dm_connector->dc_link &&
10245 		dm_helpers_dp_read_dpcd(
10246 				NULL,
10247 				amdgpu_dm_connector->dc_link,
10248 				DP_DOWN_STREAM_PORT_COUNT,
10249 				&dpcd_data,
10250 				sizeof(dpcd_data))) {
10251 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10252 	}
10253 
10254 	return capable;
10255 }
10256 
10257 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10258 		unsigned int offset,
10259 		unsigned int total_length,
10260 		u8 *data,
10261 		unsigned int length,
10262 		struct amdgpu_hdmi_vsdb_info *vsdb)
10263 {
10264 	bool res;
10265 	union dmub_rb_cmd cmd;
10266 	struct dmub_cmd_send_edid_cea *input;
10267 	struct dmub_cmd_edid_cea_output *output;
10268 
10269 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10270 		return false;
10271 
10272 	memset(&cmd, 0, sizeof(cmd));
10273 
10274 	input = &cmd.edid_cea.data.input;
10275 
10276 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10277 	cmd.edid_cea.header.sub_type = 0;
10278 	cmd.edid_cea.header.payload_bytes =
10279 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10280 	input->offset = offset;
10281 	input->length = length;
10282 	input->cea_total_length = total_length;
10283 	memcpy(input->payload, data, length);
10284 
10285 	res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
10286 	if (!res) {
10287 		DRM_ERROR("EDID CEA parser failed\n");
10288 		return false;
10289 	}
10290 
10291 	output = &cmd.edid_cea.data.output;
10292 
10293 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10294 		if (!output->ack.success) {
10295 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
10296 					output->ack.offset);
10297 		}
10298 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10299 		if (!output->amd_vsdb.vsdb_found)
10300 			return false;
10301 
10302 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10303 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10304 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10305 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10306 	} else {
10307 		if (output->type != 0)
10308 			DRM_WARN("Unknown EDID CEA parser results\n");
10309 		return false;
10310 	}
10311 
10312 	return true;
10313 }
10314 
10315 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10316 		u8 *edid_ext, int len,
10317 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10318 {
10319 	int i;
10320 
10321 	/* send extension block to DMCU for parsing */
10322 	for (i = 0; i < len; i += 8) {
10323 		bool res;
10324 		int offset;
10325 
10326 		/* send 8 bytes a time */
10327 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10328 			return false;
10329 
10330 		if (i+8 == len) {
10331 			/* EDID block sent completed, expect result */
10332 			int version, min_rate, max_rate;
10333 
10334 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10335 			if (res) {
10336 				/* amd vsdb found */
10337 				vsdb_info->freesync_supported = 1;
10338 				vsdb_info->amd_vsdb_version = version;
10339 				vsdb_info->min_refresh_rate_hz = min_rate;
10340 				vsdb_info->max_refresh_rate_hz = max_rate;
10341 				return true;
10342 			}
10343 			/* not amd vsdb */
10344 			return false;
10345 		}
10346 
10347 		/* check for ack*/
10348 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10349 		if (!res)
10350 			return false;
10351 	}
10352 
10353 	return false;
10354 }
10355 
10356 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10357 		u8 *edid_ext, int len,
10358 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10359 {
10360 	int i;
10361 
10362 	/* send extension block to DMCU for parsing */
10363 	for (i = 0; i < len; i += 8) {
10364 		/* send 8 bytes a time */
10365 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10366 			return false;
10367 	}
10368 
10369 	return vsdb_info->freesync_supported;
10370 }
10371 
10372 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
10373 		u8 *edid_ext, int len,
10374 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10375 {
10376 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
10377 
10378 	if (adev->dm.dmub_srv)
10379 		return parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
10380 	else
10381 		return parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
10382 }
10383 
10384 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
10385 		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
10386 {
10387 	u8 *edid_ext = NULL;
10388 	int i;
10389 	bool valid_vsdb_found = false;
10390 
10391 	/*----- drm_find_cea_extension() -----*/
10392 	/* No EDID or EDID extensions */
10393 	if (edid == NULL || edid->extensions == 0)
10394 		return -ENODEV;
10395 
10396 	/* Find CEA extension */
10397 	for (i = 0; i < edid->extensions; i++) {
10398 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
10399 		if (edid_ext[0] == CEA_EXT)
10400 			break;
10401 	}
10402 
10403 	if (i == edid->extensions)
10404 		return -ENODEV;
10405 
10406 	/*----- cea_db_offsets() -----*/
10407 	if (edid_ext[0] != CEA_EXT)
10408 		return -ENODEV;
10409 
10410 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
10411 
10412 	return valid_vsdb_found ? i : -ENODEV;
10413 }
10414 
10415 /**
10416  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
10417  *
10418  * @connector: Connector to query.
10419  * @edid: EDID from monitor
10420  *
10421  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
10422  * track of some of the display information in the internal data struct used by
10423  * amdgpu_dm. This function checks which type of connector we need to set the
10424  * FreeSync parameters.
10425  */
10426 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
10427 				    struct edid *edid)
10428 {
10429 	int i = 0;
10430 	struct detailed_timing *timing;
10431 	struct detailed_non_pixel *data;
10432 	struct detailed_data_monitor_range *range;
10433 	struct amdgpu_dm_connector *amdgpu_dm_connector =
10434 			to_amdgpu_dm_connector(connector);
10435 	struct dm_connector_state *dm_con_state = NULL;
10436 	struct dc_sink *sink;
10437 
10438 	struct drm_device *dev = connector->dev;
10439 	struct amdgpu_device *adev = drm_to_adev(dev);
10440 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10441 	bool freesync_capable = false;
10442 
10443 	if (!connector->state) {
10444 		DRM_ERROR("%s - Connector has no state", __func__);
10445 		goto update;
10446 	}
10447 
10448 	sink = amdgpu_dm_connector->dc_sink ?
10449 		amdgpu_dm_connector->dc_sink :
10450 		amdgpu_dm_connector->dc_em_sink;
10451 
10452 	if (!edid || !sink) {
10453 		dm_con_state = to_dm_connector_state(connector->state);
10454 
10455 		amdgpu_dm_connector->min_vfreq = 0;
10456 		amdgpu_dm_connector->max_vfreq = 0;
10457 		amdgpu_dm_connector->pixel_clock_mhz = 0;
10458 		connector->display_info.monitor_range.min_vfreq = 0;
10459 		connector->display_info.monitor_range.max_vfreq = 0;
10460 		freesync_capable = false;
10461 
10462 		goto update;
10463 	}
10464 
10465 	dm_con_state = to_dm_connector_state(connector->state);
10466 
10467 	if (!adev->dm.freesync_module)
10468 		goto update;
10469 
10470 	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10471 		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
10472 		bool edid_check_required = false;
10473 
10474 		if (edid) {
10475 			edid_check_required = is_dp_capable_without_timing_msa(
10476 						adev->dm.dc,
10477 						amdgpu_dm_connector);
10478 		}
10479 
10480 		if (edid_check_required == true && (edid->version > 1 ||
10481 		   (edid->version == 1 && edid->revision > 1))) {
10482 			for (i = 0; i < 4; i++) {
10483 
10484 				timing	= &edid->detailed_timings[i];
10485 				data	= &timing->data.other_data;
10486 				range	= &data->data.range;
10487 				/*
10488 				 * Check if monitor has continuous frequency mode
10489 				 */
10490 				if (data->type != EDID_DETAIL_MONITOR_RANGE)
10491 					continue;
10492 				/*
10493 				 * Check for flag range limits only. If flag == 1 then
10494 				 * no additional timing information provided.
10495 				 * Default GTF, GTF Secondary curve and CVT are not
10496 				 * supported
10497 				 */
10498 				if (range->flags != 1)
10499 					continue;
10500 
10501 				amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10502 				amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10503 				amdgpu_dm_connector->pixel_clock_mhz =
10504 					range->pixel_clock_mhz * 10;
10505 
10506 				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10507 				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10508 
10509 				break;
10510 			}
10511 
10512 			if (amdgpu_dm_connector->max_vfreq -
10513 			    amdgpu_dm_connector->min_vfreq > 10) {
10514 
10515 				freesync_capable = true;
10516 			}
10517 		}
10518 	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10519 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10520 		if (i >= 0 && vsdb_info.freesync_supported) {
10521 			timing  = &edid->detailed_timings[i];
10522 			data    = &timing->data.other_data;
10523 
10524 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10525 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10526 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10527 				freesync_capable = true;
10528 
10529 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10530 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10531 		}
10532 	}
10533 
10534 update:
10535 	if (dm_con_state)
10536 		dm_con_state->freesync_capable = freesync_capable;
10537 
10538 	if (connector->vrr_capable_property)
10539 		drm_connector_set_vrr_capable_property(connector,
10540 						       freesync_capable);
10541 }
10542 
10543 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10544 {
10545 	struct amdgpu_device *adev = drm_to_adev(dev);
10546 	struct dc *dc = adev->dm.dc;
10547 	int i;
10548 
10549 	mutex_lock(&adev->dm.dc_lock);
10550 	if (dc->current_state) {
10551 		for (i = 0; i < dc->current_state->stream_count; ++i)
10552 			dc->current_state->streams[i]
10553 				->triggered_crtc_reset.enabled =
10554 				adev->dm.force_timing_sync;
10555 
10556 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
10557 		dc_trigger_sync(dc, dc->current_state);
10558 	}
10559 	mutex_unlock(&adev->dm.dc_lock);
10560 }
10561 
10562 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10563 		       u32 value, const char *func_name)
10564 {
10565 #ifdef DM_CHECK_ADDR_0
10566 	if (address == 0) {
10567 		DC_ERR("invalid register write. address = 0");
10568 		return;
10569 	}
10570 #endif
10571 	cgs_write_register(ctx->cgs_device, address, value);
10572 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10573 }
10574 
10575 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10576 			  const char *func_name)
10577 {
10578 	u32 value;
10579 #ifdef DM_CHECK_ADDR_0
10580 	if (address == 0) {
10581 		DC_ERR("invalid register read; address = 0\n");
10582 		return 0;
10583 	}
10584 #endif
10585 
10586 	if (ctx->dmub_srv &&
10587 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10588 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10589 		ASSERT(false);
10590 		return 0;
10591 	}
10592 
10593 	value = cgs_read_register(ctx->cgs_device, address);
10594 
10595 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10596 
10597 	return value;
10598 }
10599 
10600 int amdgpu_dm_process_dmub_aux_transfer_sync(
10601 		struct dc_context *ctx,
10602 		unsigned int link_index,
10603 		struct aux_payload *payload,
10604 		enum aux_return_code_type *operation_result)
10605 {
10606 	struct amdgpu_device *adev = ctx->driver_context;
10607 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
10608 	int ret = -1;
10609 
10610 	mutex_lock(&adev->dm.dpia_aux_lock);
10611 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
10612 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10613 		goto out;
10614  	}
10615 
10616 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10617 		DRM_ERROR("wait_for_completion_timeout timeout!");
10618 		*operation_result = AUX_RET_ERROR_TIMEOUT;
10619 		goto out;
10620 	}
10621 
10622 	if (p_notify->result != AUX_RET_SUCCESS) {
10623 		/*
10624 		 * Transient states before tunneling is enabled could
10625 		 * lead to this error. We can ignore this for now.
10626 		 */
10627 		if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
10628 			DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
10629 					payload->address, payload->length,
10630 					p_notify->result);
10631 		}
10632 		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10633 		goto out;
10634 	}
10635 
10636 
10637 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10638 	if (!payload->write && p_notify->aux_reply.length &&
10639 			(payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
10640 
10641 		if (payload->length != p_notify->aux_reply.length) {
10642 			DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
10643 				p_notify->aux_reply.length,
10644 					payload->address, payload->length);
10645 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10646 			goto out;
10647 		}
10648 
10649 		memcpy(payload->data, p_notify->aux_reply.data,
10650 				p_notify->aux_reply.length);
10651 	}
10652 
10653 	/* success */
10654 	ret = p_notify->aux_reply.length;
10655 	*operation_result = p_notify->result;
10656 out:
10657 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
10658 	mutex_unlock(&adev->dm.dpia_aux_lock);
10659 	return ret;
10660 }
10661 
10662 int amdgpu_dm_process_dmub_set_config_sync(
10663 		struct dc_context *ctx,
10664 		unsigned int link_index,
10665 		struct set_config_cmd_payload *payload,
10666 		enum set_config_status *operation_result)
10667 {
10668 	struct amdgpu_device *adev = ctx->driver_context;
10669 	bool is_cmd_complete;
10670 	int ret;
10671 
10672 	mutex_lock(&adev->dm.dpia_aux_lock);
10673 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
10674 			link_index, payload, adev->dm.dmub_notify);
10675 
10676 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10677 		ret = 0;
10678 		*operation_result = adev->dm.dmub_notify->sc_status;
10679 	} else {
10680 		DRM_ERROR("wait_for_completion_timeout timeout!");
10681 		ret = -1;
10682 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
10683 	}
10684 
10685 	if (!is_cmd_complete)
10686 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
10687 	mutex_unlock(&adev->dm.dpia_aux_lock);
10688 	return ret;
10689 }
10690 
10691 /*
10692  * Check whether seamless boot is supported.
10693  *
10694  * So far we only support seamless boot on CHIP_VANGOGH.
10695  * If everything goes well, we may consider expanding
10696  * seamless boot to other ASICs.
10697  */
10698 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10699 {
10700 	switch (adev->asic_type) {
10701 	case CHIP_VANGOGH:
10702 		if (!adev->mman.keep_stolen_vga_memory)
10703 			return true;
10704 		break;
10705 	default:
10706 		break;
10707 	}
10708 
10709 	return false;
10710 }
10711