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