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