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