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