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