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