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