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