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