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