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