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