xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision f8ad62c0a93e5dd94243e10f1b742232e4d6411e)
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->stream->adjust.timing_adjust_pending)
378 		return true;
379 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
380 		return true;
381 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
382 		return true;
383 	else
384 		return false;
385 }
386 
387 /*
388  * DC will program planes with their z-order determined by their ordering
389  * in the dc_surface_updates array. This comparator is used to sort them
390  * by descending zpos.
391  */
392 static int dm_plane_layer_index_cmp(const void *a, const void *b)
393 {
394 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
395 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
396 
397 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
398 	return sb->surface->layer_index - sa->surface->layer_index;
399 }
400 
401 /**
402  * update_planes_and_stream_adapter() - Send planes to be updated in DC
403  *
404  * DC has a generic way to update planes and stream via
405  * dc_update_planes_and_stream function; however, DM might need some
406  * adjustments and preparation before calling it. This function is a wrapper
407  * for the dc_update_planes_and_stream that does any required configuration
408  * before passing control to DC.
409  *
410  * @dc: Display Core control structure
411  * @update_type: specify whether it is FULL/MEDIUM/FAST update
412  * @planes_count: planes count to update
413  * @stream: stream state
414  * @stream_update: stream update
415  * @array_of_surface_update: dc surface update pointer
416  *
417  */
418 static inline bool update_planes_and_stream_adapter(struct dc *dc,
419 						    int update_type,
420 						    int planes_count,
421 						    struct dc_stream_state *stream,
422 						    struct dc_stream_update *stream_update,
423 						    struct dc_surface_update *array_of_surface_update)
424 {
425 	sort(array_of_surface_update, planes_count,
426 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
427 
428 	/*
429 	 * Previous frame finished and HW is ready for optimization.
430 	 */
431 	if (update_type == UPDATE_TYPE_FAST)
432 		dc_post_update_surfaces_to_stream(dc);
433 
434 	return dc_update_planes_and_stream(dc,
435 					   array_of_surface_update,
436 					   planes_count,
437 					   stream,
438 					   stream_update);
439 }
440 
441 /**
442  * dm_pflip_high_irq() - Handle pageflip interrupt
443  * @interrupt_params: ignored
444  *
445  * Handles the pageflip interrupt by notifying all interested parties
446  * that the pageflip has been completed.
447  */
448 static void dm_pflip_high_irq(void *interrupt_params)
449 {
450 	struct amdgpu_crtc *amdgpu_crtc;
451 	struct common_irq_params *irq_params = interrupt_params;
452 	struct amdgpu_device *adev = irq_params->adev;
453 	struct drm_device *dev = adev_to_drm(adev);
454 	unsigned long flags;
455 	struct drm_pending_vblank_event *e;
456 	u32 vpos, hpos, v_blank_start, v_blank_end;
457 	bool vrr_active;
458 
459 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
460 
461 	/* IRQ could occur when in initial stage */
462 	/* TODO work and BO cleanup */
463 	if (amdgpu_crtc == NULL) {
464 		drm_dbg_state(dev, "CRTC is null, returning.\n");
465 		return;
466 	}
467 
468 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
469 
470 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
471 		drm_dbg_state(dev,
472 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
473 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
474 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
475 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
476 		return;
477 	}
478 
479 	/* page flip completed. */
480 	e = amdgpu_crtc->event;
481 	amdgpu_crtc->event = NULL;
482 
483 	WARN_ON(!e);
484 
485 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
486 
487 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
488 	if (!vrr_active ||
489 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
490 				      &v_blank_end, &hpos, &vpos) ||
491 	    (vpos < v_blank_start)) {
492 		/* Update to correct count and vblank timestamp if racing with
493 		 * vblank irq. This also updates to the correct vblank timestamp
494 		 * even in VRR mode, as scanout is past the front-porch atm.
495 		 */
496 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
497 
498 		/* Wake up userspace by sending the pageflip event with proper
499 		 * count and timestamp of vblank of flip completion.
500 		 */
501 		if (e) {
502 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
503 
504 			/* Event sent, so done with vblank for this flip */
505 			drm_crtc_vblank_put(&amdgpu_crtc->base);
506 		}
507 	} else if (e) {
508 		/* VRR active and inside front-porch: vblank count and
509 		 * timestamp for pageflip event will only be up to date after
510 		 * drm_crtc_handle_vblank() has been executed from late vblank
511 		 * irq handler after start of back-porch (vline 0). We queue the
512 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
513 		 * updated timestamp and count, once it runs after us.
514 		 *
515 		 * We need to open-code this instead of using the helper
516 		 * drm_crtc_arm_vblank_event(), as that helper would
517 		 * call drm_crtc_accurate_vblank_count(), which we must
518 		 * not call in VRR mode while we are in front-porch!
519 		 */
520 
521 		/* sequence will be replaced by real count during send-out. */
522 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
523 		e->pipe = amdgpu_crtc->crtc_id;
524 
525 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
526 		e = NULL;
527 	}
528 
529 	/* Keep track of vblank of this flip for flip throttling. We use the
530 	 * cooked hw counter, as that one incremented at start of this vblank
531 	 * of pageflip completion, so last_flip_vblank is the forbidden count
532 	 * for queueing new pageflips if vsync + VRR is enabled.
533 	 */
534 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
535 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
536 
537 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
538 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
539 
540 	drm_dbg_state(dev,
541 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
542 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
543 }
544 
545 static void dm_vupdate_high_irq(void *interrupt_params)
546 {
547 	struct common_irq_params *irq_params = interrupt_params;
548 	struct amdgpu_device *adev = irq_params->adev;
549 	struct amdgpu_crtc *acrtc;
550 	struct drm_device *drm_dev;
551 	struct drm_vblank_crtc *vblank;
552 	ktime_t frame_duration_ns, previous_timestamp;
553 	unsigned long flags;
554 	int vrr_active;
555 
556 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
557 
558 	if (acrtc) {
559 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
560 		drm_dev = acrtc->base.dev;
561 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
562 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
563 		frame_duration_ns = vblank->time - previous_timestamp;
564 
565 		if (frame_duration_ns > 0) {
566 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
567 						frame_duration_ns,
568 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
569 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
570 		}
571 
572 		drm_dbg_vbl(drm_dev,
573 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
574 			    vrr_active);
575 
576 		/* Core vblank handling is done here after end of front-porch in
577 		 * vrr mode, as vblank timestamping will give valid results
578 		 * while now done after front-porch. This will also deliver
579 		 * page-flip completion events that have been queued to us
580 		 * if a pageflip happened inside front-porch.
581 		 */
582 		if (vrr_active) {
583 			amdgpu_dm_crtc_handle_vblank(acrtc);
584 
585 			/* BTR processing for pre-DCE12 ASICs */
586 			if (acrtc->dm_irq_params.stream &&
587 			    adev->family < AMDGPU_FAMILY_AI) {
588 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
589 				mod_freesync_handle_v_update(
590 				    adev->dm.freesync_module,
591 				    acrtc->dm_irq_params.stream,
592 				    &acrtc->dm_irq_params.vrr_params);
593 
594 				dc_stream_adjust_vmin_vmax(
595 				    adev->dm.dc,
596 				    acrtc->dm_irq_params.stream,
597 				    &acrtc->dm_irq_params.vrr_params.adjust);
598 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
599 			}
600 		}
601 	}
602 }
603 
604 /**
605  * dm_crtc_high_irq() - Handles CRTC interrupt
606  * @interrupt_params: used for determining the CRTC instance
607  *
608  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
609  * event handler.
610  */
611 static void dm_crtc_high_irq(void *interrupt_params)
612 {
613 	struct common_irq_params *irq_params = interrupt_params;
614 	struct amdgpu_device *adev = irq_params->adev;
615 	struct drm_writeback_job *job;
616 	struct amdgpu_crtc *acrtc;
617 	unsigned long flags;
618 	int vrr_active;
619 
620 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
621 	if (!acrtc)
622 		return;
623 
624 	if (acrtc->wb_conn) {
625 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
626 
627 		if (acrtc->wb_pending) {
628 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
629 						       struct drm_writeback_job,
630 						       list_entry);
631 			acrtc->wb_pending = false;
632 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
633 
634 			if (job) {
635 				unsigned int v_total, refresh_hz;
636 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
637 
638 				v_total = stream->adjust.v_total_max ?
639 					  stream->adjust.v_total_max : stream->timing.v_total;
640 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
641 					     100LL, (v_total * stream->timing.h_total));
642 				mdelay(1000 / refresh_hz);
643 
644 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
645 				dc_stream_fc_disable_writeback(adev->dm.dc,
646 							       acrtc->dm_irq_params.stream, 0);
647 			}
648 		} else
649 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
650 	}
651 
652 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
653 
654 	drm_dbg_vbl(adev_to_drm(adev),
655 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
656 		    vrr_active, acrtc->dm_irq_params.active_planes);
657 
658 	/**
659 	 * Core vblank handling at start of front-porch is only possible
660 	 * in non-vrr mode, as only there vblank timestamping will give
661 	 * valid results while done in front-porch. Otherwise defer it
662 	 * to dm_vupdate_high_irq after end of front-porch.
663 	 */
664 	if (!vrr_active)
665 		amdgpu_dm_crtc_handle_vblank(acrtc);
666 
667 	/**
668 	 * Following stuff must happen at start of vblank, for crc
669 	 * computation and below-the-range btr support in vrr mode.
670 	 */
671 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
672 
673 	/* BTR updates need to happen before VUPDATE on Vega and above. */
674 	if (adev->family < AMDGPU_FAMILY_AI)
675 		return;
676 
677 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
678 
679 	if (acrtc->dm_irq_params.stream &&
680 		acrtc->dm_irq_params.vrr_params.supported) {
681 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
682 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
683 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
684 
685 		mod_freesync_handle_v_update(adev->dm.freesync_module,
686 					     acrtc->dm_irq_params.stream,
687 					     &acrtc->dm_irq_params.vrr_params);
688 
689 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
690 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
691 			dc_stream_adjust_vmin_vmax(adev->dm.dc,
692 					acrtc->dm_irq_params.stream,
693 					&acrtc->dm_irq_params.vrr_params.adjust);
694 		}
695 	}
696 
697 	/*
698 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
699 	 * In that case, pageflip completion interrupts won't fire and pageflip
700 	 * completion events won't get delivered. Prevent this by sending
701 	 * pending pageflip events from here if a flip is still pending.
702 	 *
703 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
704 	 * avoid race conditions between flip programming and completion,
705 	 * which could cause too early flip completion events.
706 	 */
707 	if (adev->family >= AMDGPU_FAMILY_RV &&
708 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
709 	    acrtc->dm_irq_params.active_planes == 0) {
710 		if (acrtc->event) {
711 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
712 			acrtc->event = NULL;
713 			drm_crtc_vblank_put(&acrtc->base);
714 		}
715 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
716 	}
717 
718 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
719 }
720 
721 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
722 /**
723  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
724  * DCN generation ASICs
725  * @interrupt_params: interrupt parameters
726  *
727  * Used to set crc window/read out crc value at vertical line 0 position
728  */
729 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
730 {
731 	struct common_irq_params *irq_params = interrupt_params;
732 	struct amdgpu_device *adev = irq_params->adev;
733 	struct amdgpu_crtc *acrtc;
734 
735 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
736 
737 	if (!acrtc)
738 		return;
739 
740 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
741 }
742 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
743 
744 /**
745  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
746  * @adev: amdgpu_device pointer
747  * @notify: dmub notification structure
748  *
749  * Dmub AUX or SET_CONFIG command completion processing callback
750  * Copies dmub notification to DM which is to be read by AUX command.
751  * issuing thread and also signals the event to wake up the thread.
752  */
753 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
754 					struct dmub_notification *notify)
755 {
756 	if (adev->dm.dmub_notify)
757 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
758 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
759 		complete(&adev->dm.dmub_aux_transfer_done);
760 }
761 
762 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
763 					struct dmub_notification *notify)
764 {
765 	if (!adev || !notify) {
766 		ASSERT(false);
767 		return;
768 	}
769 
770 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
771 	const uint8_t ddc_line = req->u.aux.ddc_line;
772 
773 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
774 		ASSERT(false);
775 		return;
776 	}
777 
778 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
779 
780 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
781 	memcpy(sync->reply_data, req, sizeof(*req));
782 	complete(&sync->replied);
783 }
784 
785 /**
786  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
787  * @adev: amdgpu_device pointer
788  * @notify: dmub notification structure
789  *
790  * Dmub Hpd interrupt processing callback. Gets displayindex through the
791  * ink index and calls helper to do the processing.
792  */
793 static void dmub_hpd_callback(struct amdgpu_device *adev,
794 			      struct dmub_notification *notify)
795 {
796 	struct amdgpu_dm_connector *aconnector;
797 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
798 	struct drm_connector *connector;
799 	struct drm_connector_list_iter iter;
800 	struct dc_link *link;
801 	u8 link_index = 0;
802 	struct drm_device *dev;
803 
804 	if (adev == NULL)
805 		return;
806 
807 	if (notify == NULL) {
808 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
809 		return;
810 	}
811 
812 	if (notify->link_index > adev->dm.dc->link_count) {
813 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
814 		return;
815 	}
816 
817 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
818 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
819 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
820 		return;
821 	}
822 
823 	link_index = notify->link_index;
824 	link = adev->dm.dc->links[link_index];
825 	dev = adev->dm.ddev;
826 
827 	drm_connector_list_iter_begin(dev, &iter);
828 	drm_for_each_connector_iter(connector, &iter) {
829 
830 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
831 			continue;
832 
833 		aconnector = to_amdgpu_dm_connector(connector);
834 		if (link && aconnector->dc_link == link) {
835 			if (notify->type == DMUB_NOTIFICATION_HPD)
836 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
837 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
838 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
839 			else
840 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
841 						notify->type, link_index);
842 
843 			hpd_aconnector = aconnector;
844 			break;
845 		}
846 	}
847 	drm_connector_list_iter_end(&iter);
848 
849 	if (hpd_aconnector) {
850 		if (notify->type == DMUB_NOTIFICATION_HPD) {
851 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
852 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
853 			handle_hpd_irq_helper(hpd_aconnector);
854 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
855 			handle_hpd_rx_irq(hpd_aconnector);
856 		}
857 	}
858 }
859 
860 /**
861  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
862  * @adev: amdgpu_device pointer
863  * @notify: dmub notification structure
864  *
865  * HPD sense changes can occur during low power states and need to be
866  * notified from firmware to driver.
867  */
868 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
869 			      struct dmub_notification *notify)
870 {
871 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
872 }
873 
874 /**
875  * register_dmub_notify_callback - Sets callback for DMUB notify
876  * @adev: amdgpu_device pointer
877  * @type: Type of dmub notification
878  * @callback: Dmub interrupt callback function
879  * @dmub_int_thread_offload: offload indicator
880  *
881  * API to register a dmub callback handler for a dmub notification
882  * Also sets indicator whether callback processing to be offloaded.
883  * to dmub interrupt handling thread
884  * Return: true if successfully registered, false if there is existing registration
885  */
886 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
887 					  enum dmub_notification_type type,
888 					  dmub_notify_interrupt_callback_t callback,
889 					  bool dmub_int_thread_offload)
890 {
891 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
892 		adev->dm.dmub_callback[type] = callback;
893 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
894 	} else
895 		return false;
896 
897 	return true;
898 }
899 
900 static void dm_handle_hpd_work(struct work_struct *work)
901 {
902 	struct dmub_hpd_work *dmub_hpd_wrk;
903 
904 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
905 
906 	if (!dmub_hpd_wrk->dmub_notify) {
907 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
908 		return;
909 	}
910 
911 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
912 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
913 		dmub_hpd_wrk->dmub_notify);
914 	}
915 
916 	kfree(dmub_hpd_wrk->dmub_notify);
917 	kfree(dmub_hpd_wrk);
918 
919 }
920 
921 static const char *dmub_notification_type_str(enum dmub_notification_type e)
922 {
923 	switch (e) {
924 	case DMUB_NOTIFICATION_NO_DATA:
925 		return "NO_DATA";
926 	case DMUB_NOTIFICATION_AUX_REPLY:
927 		return "AUX_REPLY";
928 	case DMUB_NOTIFICATION_HPD:
929 		return "HPD";
930 	case DMUB_NOTIFICATION_HPD_IRQ:
931 		return "HPD_IRQ";
932 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
933 		return "SET_CONFIG_REPLY";
934 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
935 		return "DPIA_NOTIFICATION";
936 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
937 		return "HPD_SENSE_NOTIFY";
938 	case DMUB_NOTIFICATION_FUSED_IO:
939 		return "FUSED_IO";
940 	default:
941 		return "<unknown>";
942 	}
943 }
944 
945 #define DMUB_TRACE_MAX_READ 64
946 /**
947  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
948  * @interrupt_params: used for determining the Outbox instance
949  *
950  * Handles the Outbox Interrupt
951  * event handler.
952  */
953 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
954 {
955 	struct dmub_notification notify = {0};
956 	struct common_irq_params *irq_params = interrupt_params;
957 	struct amdgpu_device *adev = irq_params->adev;
958 	struct amdgpu_display_manager *dm = &adev->dm;
959 	struct dmcub_trace_buf_entry entry = { 0 };
960 	u32 count = 0;
961 	struct dmub_hpd_work *dmub_hpd_wrk;
962 
963 	do {
964 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
965 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
966 							entry.param0, entry.param1);
967 
968 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
969 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
970 		} else
971 			break;
972 
973 		count++;
974 
975 	} while (count <= DMUB_TRACE_MAX_READ);
976 
977 	if (count > DMUB_TRACE_MAX_READ)
978 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
979 
980 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
981 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
982 
983 		do {
984 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
985 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
986 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
987 				continue;
988 			}
989 			if (!dm->dmub_callback[notify.type]) {
990 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
991 					dmub_notification_type_str(notify.type));
992 				continue;
993 			}
994 			if (dm->dmub_thread_offload[notify.type] == true) {
995 				dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
996 				if (!dmub_hpd_wrk) {
997 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
998 					return;
999 				}
1000 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1001 								    GFP_ATOMIC);
1002 				if (!dmub_hpd_wrk->dmub_notify) {
1003 					kfree(dmub_hpd_wrk);
1004 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1005 					return;
1006 				}
1007 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1008 				dmub_hpd_wrk->adev = adev;
1009 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1010 			} else {
1011 				dm->dmub_callback[notify.type](adev, &notify);
1012 			}
1013 		} while (notify.pending_notification);
1014 	}
1015 }
1016 
1017 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1018 		  enum amd_clockgating_state state)
1019 {
1020 	return 0;
1021 }
1022 
1023 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1024 		  enum amd_powergating_state state)
1025 {
1026 	return 0;
1027 }
1028 
1029 /* Prototypes of private functions */
1030 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1031 
1032 /* Allocate memory for FBC compressed data  */
1033 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1034 {
1035 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1036 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1037 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1038 	struct drm_display_mode *mode;
1039 	unsigned long max_size = 0;
1040 
1041 	if (adev->dm.dc->fbc_compressor == NULL)
1042 		return;
1043 
1044 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1045 		return;
1046 
1047 	if (compressor->bo_ptr)
1048 		return;
1049 
1050 
1051 	list_for_each_entry(mode, &connector->modes, head) {
1052 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1053 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1054 	}
1055 
1056 	if (max_size) {
1057 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1058 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1059 			    &compressor->gpu_addr, &compressor->cpu_addr);
1060 
1061 		if (r)
1062 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1063 		else {
1064 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1065 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1066 		}
1067 
1068 	}
1069 
1070 }
1071 
1072 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1073 					  int pipe, bool *enabled,
1074 					  unsigned char *buf, int max_bytes)
1075 {
1076 	struct drm_device *dev = dev_get_drvdata(kdev);
1077 	struct amdgpu_device *adev = drm_to_adev(dev);
1078 	struct drm_connector *connector;
1079 	struct drm_connector_list_iter conn_iter;
1080 	struct amdgpu_dm_connector *aconnector;
1081 	int ret = 0;
1082 
1083 	*enabled = false;
1084 
1085 	mutex_lock(&adev->dm.audio_lock);
1086 
1087 	drm_connector_list_iter_begin(dev, &conn_iter);
1088 	drm_for_each_connector_iter(connector, &conn_iter) {
1089 
1090 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1091 			continue;
1092 
1093 		aconnector = to_amdgpu_dm_connector(connector);
1094 		if (aconnector->audio_inst != port)
1095 			continue;
1096 
1097 		*enabled = true;
1098 		mutex_lock(&connector->eld_mutex);
1099 		ret = drm_eld_size(connector->eld);
1100 		memcpy(buf, connector->eld, min(max_bytes, ret));
1101 		mutex_unlock(&connector->eld_mutex);
1102 
1103 		break;
1104 	}
1105 	drm_connector_list_iter_end(&conn_iter);
1106 
1107 	mutex_unlock(&adev->dm.audio_lock);
1108 
1109 	DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1110 
1111 	return ret;
1112 }
1113 
1114 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1115 	.get_eld = amdgpu_dm_audio_component_get_eld,
1116 };
1117 
1118 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1119 				       struct device *hda_kdev, void *data)
1120 {
1121 	struct drm_device *dev = dev_get_drvdata(kdev);
1122 	struct amdgpu_device *adev = drm_to_adev(dev);
1123 	struct drm_audio_component *acomp = data;
1124 
1125 	acomp->ops = &amdgpu_dm_audio_component_ops;
1126 	acomp->dev = kdev;
1127 	adev->dm.audio_component = acomp;
1128 
1129 	return 0;
1130 }
1131 
1132 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1133 					  struct device *hda_kdev, void *data)
1134 {
1135 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1136 	struct drm_audio_component *acomp = data;
1137 
1138 	acomp->ops = NULL;
1139 	acomp->dev = NULL;
1140 	adev->dm.audio_component = NULL;
1141 }
1142 
1143 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1144 	.bind	= amdgpu_dm_audio_component_bind,
1145 	.unbind	= amdgpu_dm_audio_component_unbind,
1146 };
1147 
1148 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1149 {
1150 	int i, ret;
1151 
1152 	if (!amdgpu_audio)
1153 		return 0;
1154 
1155 	adev->mode_info.audio.enabled = true;
1156 
1157 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1158 
1159 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1160 		adev->mode_info.audio.pin[i].channels = -1;
1161 		adev->mode_info.audio.pin[i].rate = -1;
1162 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1163 		adev->mode_info.audio.pin[i].status_bits = 0;
1164 		adev->mode_info.audio.pin[i].category_code = 0;
1165 		adev->mode_info.audio.pin[i].connected = false;
1166 		adev->mode_info.audio.pin[i].id =
1167 			adev->dm.dc->res_pool->audios[i]->inst;
1168 		adev->mode_info.audio.pin[i].offset = 0;
1169 	}
1170 
1171 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1172 	if (ret < 0)
1173 		return ret;
1174 
1175 	adev->dm.audio_registered = true;
1176 
1177 	return 0;
1178 }
1179 
1180 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1181 {
1182 	if (!amdgpu_audio)
1183 		return;
1184 
1185 	if (!adev->mode_info.audio.enabled)
1186 		return;
1187 
1188 	if (adev->dm.audio_registered) {
1189 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1190 		adev->dm.audio_registered = false;
1191 	}
1192 
1193 	/* TODO: Disable audio? */
1194 
1195 	adev->mode_info.audio.enabled = false;
1196 }
1197 
1198 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1199 {
1200 	struct drm_audio_component *acomp = adev->dm.audio_component;
1201 
1202 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1203 		DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
1204 
1205 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1206 						 pin, -1);
1207 	}
1208 }
1209 
1210 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1211 {
1212 	const struct dmcub_firmware_header_v1_0 *hdr;
1213 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1214 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1215 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1216 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1217 	struct abm *abm = adev->dm.dc->res_pool->abm;
1218 	struct dc_context *ctx = adev->dm.dc->ctx;
1219 	struct dmub_srv_hw_params hw_params;
1220 	enum dmub_status status;
1221 	const unsigned char *fw_inst_const, *fw_bss_data;
1222 	u32 i, fw_inst_const_size, fw_bss_data_size;
1223 	bool has_hw_support;
1224 
1225 	if (!dmub_srv)
1226 		/* DMUB isn't supported on the ASIC. */
1227 		return 0;
1228 
1229 	if (!fb_info) {
1230 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1231 		return -EINVAL;
1232 	}
1233 
1234 	if (!dmub_fw) {
1235 		/* Firmware required for DMUB support. */
1236 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1237 		return -EINVAL;
1238 	}
1239 
1240 	/* initialize register offsets for ASICs with runtime initialization available */
1241 	if (dmub_srv->hw_funcs.init_reg_offsets)
1242 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1243 
1244 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1245 	if (status != DMUB_STATUS_OK) {
1246 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1247 		return -EINVAL;
1248 	}
1249 
1250 	if (!has_hw_support) {
1251 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1252 		return 0;
1253 	}
1254 
1255 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1256 	status = dmub_srv_hw_reset(dmub_srv);
1257 	if (status != DMUB_STATUS_OK)
1258 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1259 
1260 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1261 
1262 	fw_inst_const = dmub_fw->data +
1263 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1264 			PSP_HEADER_BYTES;
1265 
1266 	fw_bss_data = dmub_fw->data +
1267 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1268 		      le32_to_cpu(hdr->inst_const_bytes);
1269 
1270 	/* Copy firmware and bios info into FB memory. */
1271 	fw_inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
1272 			     PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
1273 
1274 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1275 
1276 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1277 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1278 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1279 	 * will be done by dm_dmub_hw_init
1280 	 */
1281 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1282 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1283 				fw_inst_const_size);
1284 	}
1285 
1286 	if (fw_bss_data_size)
1287 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1288 		       fw_bss_data, fw_bss_data_size);
1289 
1290 	/* Copy firmware bios info into FB memory. */
1291 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1292 	       adev->bios_size);
1293 
1294 	/* Reset regions that need to be reset. */
1295 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1296 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1297 
1298 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1299 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1300 
1301 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1302 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1303 
1304 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1305 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1306 
1307 	/* Initialize hardware. */
1308 	memset(&hw_params, 0, sizeof(hw_params));
1309 	hw_params.fb_base = adev->gmc.fb_start;
1310 	hw_params.fb_offset = adev->vm_manager.vram_base_offset;
1311 
1312 	/* backdoor load firmware and trigger dmub running */
1313 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1314 		hw_params.load_inst_const = true;
1315 
1316 	if (dmcu)
1317 		hw_params.psp_version = dmcu->psp_version;
1318 
1319 	for (i = 0; i < fb_info->num_fb; ++i)
1320 		hw_params.fb[i] = &fb_info->fb[i];
1321 
1322 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1323 	case IP_VERSION(3, 1, 3):
1324 	case IP_VERSION(3, 1, 4):
1325 	case IP_VERSION(3, 5, 0):
1326 	case IP_VERSION(3, 5, 1):
1327 	case IP_VERSION(3, 6, 0):
1328 	case IP_VERSION(4, 0, 1):
1329 		hw_params.dpia_supported = true;
1330 		hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
1331 		break;
1332 	default:
1333 		break;
1334 	}
1335 
1336 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1337 	case IP_VERSION(3, 5, 0):
1338 	case IP_VERSION(3, 5, 1):
1339 	case IP_VERSION(3, 6, 0):
1340 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1341 		hw_params.lower_hbr3_phy_ssc = true;
1342 		break;
1343 	default:
1344 		break;
1345 	}
1346 
1347 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1348 	if (status != DMUB_STATUS_OK) {
1349 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1350 		return -EINVAL;
1351 	}
1352 
1353 	/* Wait for firmware load to finish. */
1354 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1355 	if (status != DMUB_STATUS_OK)
1356 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1357 
1358 	/* Init DMCU and ABM if available. */
1359 	if (dmcu && abm) {
1360 		dmcu->funcs->dmcu_init(dmcu);
1361 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1362 	}
1363 
1364 	if (!adev->dm.dc->ctx->dmub_srv)
1365 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1366 	if (!adev->dm.dc->ctx->dmub_srv) {
1367 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1368 		return -ENOMEM;
1369 	}
1370 
1371 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1372 		 adev->dm.dmcub_fw_version);
1373 
1374 	/* Keeping sanity checks off if
1375 	 * DCN31 >= 4.0.59.0
1376 	 * DCN314 >= 8.0.16.0
1377 	 * Otherwise, turn on sanity checks
1378 	 */
1379 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1380 	case IP_VERSION(3, 1, 2):
1381 	case IP_VERSION(3, 1, 3):
1382 		if (adev->dm.dmcub_fw_version &&
1383 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1384 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1385 				adev->dm.dc->debug.sanity_checks = true;
1386 		break;
1387 	case IP_VERSION(3, 1, 4):
1388 		if (adev->dm.dmcub_fw_version &&
1389 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1390 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1391 				adev->dm.dc->debug.sanity_checks = true;
1392 		break;
1393 	default:
1394 		break;
1395 	}
1396 
1397 	return 0;
1398 }
1399 
1400 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1401 {
1402 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1403 	enum dmub_status status;
1404 	bool init;
1405 	int r;
1406 
1407 	if (!dmub_srv) {
1408 		/* DMUB isn't supported on the ASIC. */
1409 		return;
1410 	}
1411 
1412 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1413 	if (status != DMUB_STATUS_OK)
1414 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1415 
1416 	if (status == DMUB_STATUS_OK && init) {
1417 		/* Wait for firmware load to finish. */
1418 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1419 		if (status != DMUB_STATUS_OK)
1420 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1421 	} else {
1422 		/* Perform the full hardware initialization. */
1423 		r = dm_dmub_hw_init(adev);
1424 		if (r)
1425 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1426 	}
1427 }
1428 
1429 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1430 {
1431 	u64 pt_base;
1432 	u32 logical_addr_low;
1433 	u32 logical_addr_high;
1434 	u32 agp_base, agp_bot, agp_top;
1435 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1436 
1437 	memset(pa_config, 0, sizeof(*pa_config));
1438 
1439 	agp_base = 0;
1440 	agp_bot = adev->gmc.agp_start >> 24;
1441 	agp_top = adev->gmc.agp_end >> 24;
1442 
1443 	/* AGP aperture is disabled */
1444 	if (agp_bot > agp_top) {
1445 		logical_addr_low = adev->gmc.fb_start >> 18;
1446 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1447 				       AMD_APU_IS_RENOIR |
1448 				       AMD_APU_IS_GREEN_SARDINE))
1449 			/*
1450 			 * Raven2 has a HW issue that it is unable to use the vram which
1451 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1452 			 * workaround that increase system aperture high address (add 1)
1453 			 * to get rid of the VM fault and hardware hang.
1454 			 */
1455 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1456 		else
1457 			logical_addr_high = adev->gmc.fb_end >> 18;
1458 	} else {
1459 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1460 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1461 				       AMD_APU_IS_RENOIR |
1462 				       AMD_APU_IS_GREEN_SARDINE))
1463 			/*
1464 			 * Raven2 has a HW issue that it is unable to use the vram which
1465 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1466 			 * workaround that increase system aperture high address (add 1)
1467 			 * to get rid of the VM fault and hardware hang.
1468 			 */
1469 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1470 		else
1471 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1472 	}
1473 
1474 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1475 
1476 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1477 						   AMDGPU_GPU_PAGE_SHIFT);
1478 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1479 						  AMDGPU_GPU_PAGE_SHIFT);
1480 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1481 						 AMDGPU_GPU_PAGE_SHIFT);
1482 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1483 						AMDGPU_GPU_PAGE_SHIFT);
1484 	page_table_base.high_part = upper_32_bits(pt_base);
1485 	page_table_base.low_part = lower_32_bits(pt_base);
1486 
1487 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1488 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1489 
1490 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1491 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1492 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1493 
1494 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1495 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1496 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1497 
1498 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1499 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1500 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1501 
1502 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1503 
1504 }
1505 
1506 static void force_connector_state(
1507 	struct amdgpu_dm_connector *aconnector,
1508 	enum drm_connector_force force_state)
1509 {
1510 	struct drm_connector *connector = &aconnector->base;
1511 
1512 	mutex_lock(&connector->dev->mode_config.mutex);
1513 	aconnector->base.force = force_state;
1514 	mutex_unlock(&connector->dev->mode_config.mutex);
1515 
1516 	mutex_lock(&aconnector->hpd_lock);
1517 	drm_kms_helper_connector_hotplug_event(connector);
1518 	mutex_unlock(&aconnector->hpd_lock);
1519 }
1520 
1521 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1522 {
1523 	struct hpd_rx_irq_offload_work *offload_work;
1524 	struct amdgpu_dm_connector *aconnector;
1525 	struct dc_link *dc_link;
1526 	struct amdgpu_device *adev;
1527 	enum dc_connection_type new_connection_type = dc_connection_none;
1528 	unsigned long flags;
1529 	union test_response test_response;
1530 
1531 	memset(&test_response, 0, sizeof(test_response));
1532 
1533 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1534 	aconnector = offload_work->offload_wq->aconnector;
1535 	adev = offload_work->adev;
1536 
1537 	if (!aconnector) {
1538 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1539 		goto skip;
1540 	}
1541 
1542 	dc_link = aconnector->dc_link;
1543 
1544 	mutex_lock(&aconnector->hpd_lock);
1545 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1546 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1547 	mutex_unlock(&aconnector->hpd_lock);
1548 
1549 	if (new_connection_type == dc_connection_none)
1550 		goto skip;
1551 
1552 	if (amdgpu_in_reset(adev))
1553 		goto skip;
1554 
1555 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1556 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1557 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1558 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1559 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1560 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1561 		goto skip;
1562 	}
1563 
1564 	mutex_lock(&adev->dm.dc_lock);
1565 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1566 		dc_link_dp_handle_automated_test(dc_link);
1567 
1568 		if (aconnector->timing_changed) {
1569 			/* force connector disconnect and reconnect */
1570 			force_connector_state(aconnector, DRM_FORCE_OFF);
1571 			msleep(100);
1572 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1573 		}
1574 
1575 		test_response.bits.ACK = 1;
1576 
1577 		core_link_write_dpcd(
1578 		dc_link,
1579 		DP_TEST_RESPONSE,
1580 		&test_response.raw,
1581 		sizeof(test_response));
1582 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1583 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1584 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1585 		/* offload_work->data is from handle_hpd_rx_irq->
1586 		 * schedule_hpd_rx_offload_work.this is defer handle
1587 		 * for hpd short pulse. upon here, link status may be
1588 		 * changed, need get latest link status from dpcd
1589 		 * registers. if link status is good, skip run link
1590 		 * training again.
1591 		 */
1592 		union hpd_irq_data irq_data;
1593 
1594 		memset(&irq_data, 0, sizeof(irq_data));
1595 
1596 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1597 		 * request be added to work queue if link lost at end of dc_link_
1598 		 * dp_handle_link_loss
1599 		 */
1600 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1601 		offload_work->offload_wq->is_handling_link_loss = false;
1602 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1603 
1604 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1605 			dc_link_check_link_loss_status(dc_link, &irq_data))
1606 			dc_link_dp_handle_link_loss(dc_link);
1607 	}
1608 	mutex_unlock(&adev->dm.dc_lock);
1609 
1610 skip:
1611 	kfree(offload_work);
1612 
1613 }
1614 
1615 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1616 {
1617 	struct dc *dc = adev->dm.dc;
1618 	int max_caps = dc->caps.max_links;
1619 	int i = 0;
1620 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1621 
1622 	hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
1623 
1624 	if (!hpd_rx_offload_wq)
1625 		return NULL;
1626 
1627 
1628 	for (i = 0; i < max_caps; i++) {
1629 		hpd_rx_offload_wq[i].wq =
1630 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1631 
1632 		if (hpd_rx_offload_wq[i].wq == NULL) {
1633 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1634 			goto out_err;
1635 		}
1636 
1637 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1638 	}
1639 
1640 	return hpd_rx_offload_wq;
1641 
1642 out_err:
1643 	for (i = 0; i < max_caps; i++) {
1644 		if (hpd_rx_offload_wq[i].wq)
1645 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1646 	}
1647 	kfree(hpd_rx_offload_wq);
1648 	return NULL;
1649 }
1650 
1651 struct amdgpu_stutter_quirk {
1652 	u16 chip_vendor;
1653 	u16 chip_device;
1654 	u16 subsys_vendor;
1655 	u16 subsys_device;
1656 	u8 revision;
1657 };
1658 
1659 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1660 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1661 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1662 	{ 0, 0, 0, 0, 0 },
1663 };
1664 
1665 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1666 {
1667 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1668 
1669 	while (p && p->chip_device != 0) {
1670 		if (pdev->vendor == p->chip_vendor &&
1671 		    pdev->device == p->chip_device &&
1672 		    pdev->subsystem_vendor == p->subsys_vendor &&
1673 		    pdev->subsystem_device == p->subsys_device &&
1674 		    pdev->revision == p->revision) {
1675 			return true;
1676 		}
1677 		++p;
1678 	}
1679 	return false;
1680 }
1681 
1682 struct amdgpu_dm_quirks {
1683 	bool aux_hpd_discon;
1684 	bool support_edp0_on_dp1;
1685 };
1686 
1687 static struct amdgpu_dm_quirks quirk_entries = {
1688 	.aux_hpd_discon = false,
1689 	.support_edp0_on_dp1 = false
1690 };
1691 
1692 static int edp0_on_dp1_callback(const struct dmi_system_id *id)
1693 {
1694 	quirk_entries.support_edp0_on_dp1 = true;
1695 	return 0;
1696 }
1697 
1698 static int aux_hpd_discon_callback(const struct dmi_system_id *id)
1699 {
1700 	quirk_entries.aux_hpd_discon = true;
1701 	return 0;
1702 }
1703 
1704 static const struct dmi_system_id dmi_quirk_table[] = {
1705 	{
1706 		.callback = aux_hpd_discon_callback,
1707 		.matches = {
1708 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1709 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3660"),
1710 		},
1711 	},
1712 	{
1713 		.callback = aux_hpd_discon_callback,
1714 		.matches = {
1715 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1716 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3260"),
1717 		},
1718 	},
1719 	{
1720 		.callback = aux_hpd_discon_callback,
1721 		.matches = {
1722 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1723 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3460"),
1724 		},
1725 	},
1726 	{
1727 		.callback = aux_hpd_discon_callback,
1728 		.matches = {
1729 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1730 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower Plus 7010"),
1731 		},
1732 	},
1733 	{
1734 		.callback = aux_hpd_discon_callback,
1735 		.matches = {
1736 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1737 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower 7010"),
1738 		},
1739 	},
1740 	{
1741 		.callback = aux_hpd_discon_callback,
1742 		.matches = {
1743 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1744 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF Plus 7010"),
1745 		},
1746 	},
1747 	{
1748 		.callback = aux_hpd_discon_callback,
1749 		.matches = {
1750 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1751 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF 7010"),
1752 		},
1753 	},
1754 	{
1755 		.callback = aux_hpd_discon_callback,
1756 		.matches = {
1757 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1758 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro Plus 7010"),
1759 		},
1760 	},
1761 	{
1762 		.callback = aux_hpd_discon_callback,
1763 		.matches = {
1764 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1765 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro 7010"),
1766 		},
1767 	},
1768 	{
1769 		.callback = edp0_on_dp1_callback,
1770 		.matches = {
1771 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1772 			DMI_MATCH(DMI_PRODUCT_NAME, "HP Elite mt645 G8 Mobile Thin Client"),
1773 		},
1774 	},
1775 	{
1776 		.callback = edp0_on_dp1_callback,
1777 		.matches = {
1778 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1779 			DMI_MATCH(DMI_PRODUCT_NAME, "HP EliteBook 645 14 inch G11 Notebook PC"),
1780 		},
1781 	},
1782 	{
1783 		.callback = edp0_on_dp1_callback,
1784 		.matches = {
1785 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1786 			DMI_MATCH(DMI_PRODUCT_NAME, "HP EliteBook 665 16 inch G11 Notebook PC"),
1787 		},
1788 	},
1789 	{
1790 		.callback = edp0_on_dp1_callback,
1791 		.matches = {
1792 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1793 			DMI_MATCH(DMI_PRODUCT_NAME, "HP ProBook 445 14 inch G11 Notebook PC"),
1794 		},
1795 	},
1796 	{
1797 		.callback = edp0_on_dp1_callback,
1798 		.matches = {
1799 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1800 			DMI_MATCH(DMI_PRODUCT_NAME, "HP ProBook 465 16 inch G11 Notebook PC"),
1801 		},
1802 	},
1803 	{}
1804 	/* TODO: refactor this from a fixed table to a dynamic option */
1805 };
1806 
1807 static void retrieve_dmi_info(struct amdgpu_display_manager *dm, struct dc_init_data *init_data)
1808 {
1809 	int dmi_id;
1810 	struct drm_device *dev = dm->ddev;
1811 
1812 	dm->aux_hpd_discon_quirk = false;
1813 	init_data->flags.support_edp0_on_dp1 = false;
1814 
1815 	dmi_id = dmi_check_system(dmi_quirk_table);
1816 
1817 	if (!dmi_id)
1818 		return;
1819 
1820 	if (quirk_entries.aux_hpd_discon) {
1821 		dm->aux_hpd_discon_quirk = true;
1822 		drm_info(dev, "aux_hpd_discon_quirk attached\n");
1823 	}
1824 	if (quirk_entries.support_edp0_on_dp1) {
1825 		init_data->flags.support_edp0_on_dp1 = true;
1826 		drm_info(dev, "support_edp0_on_dp1 attached\n");
1827 	}
1828 }
1829 
1830 void*
1831 dm_allocate_gpu_mem(
1832 		struct amdgpu_device *adev,
1833 		enum dc_gpu_mem_alloc_type type,
1834 		size_t size,
1835 		long long *addr)
1836 {
1837 	struct dal_allocation *da;
1838 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1839 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1840 	int ret;
1841 
1842 	da = kzalloc(sizeof(struct dal_allocation), GFP_KERNEL);
1843 	if (!da)
1844 		return NULL;
1845 
1846 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1847 				      domain, &da->bo,
1848 				      &da->gpu_addr, &da->cpu_ptr);
1849 
1850 	*addr = da->gpu_addr;
1851 
1852 	if (ret) {
1853 		kfree(da);
1854 		return NULL;
1855 	}
1856 
1857 	/* add da to list in dm */
1858 	list_add(&da->list, &adev->dm.da_list);
1859 
1860 	return da->cpu_ptr;
1861 }
1862 
1863 void
1864 dm_free_gpu_mem(
1865 		struct amdgpu_device *adev,
1866 		enum dc_gpu_mem_alloc_type type,
1867 		void *pvMem)
1868 {
1869 	struct dal_allocation *da;
1870 
1871 	/* walk the da list in DM */
1872 	list_for_each_entry(da, &adev->dm.da_list, list) {
1873 		if (pvMem == da->cpu_ptr) {
1874 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1875 			list_del(&da->list);
1876 			kfree(da);
1877 			break;
1878 		}
1879 	}
1880 
1881 }
1882 
1883 static enum dmub_status
1884 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1885 				 enum dmub_gpint_command command_code,
1886 				 uint16_t param,
1887 				 uint32_t timeout_us)
1888 {
1889 	union dmub_gpint_data_register reg, test;
1890 	uint32_t i;
1891 
1892 	/* Assume that VBIOS DMUB is ready to take commands */
1893 
1894 	reg.bits.status = 1;
1895 	reg.bits.command_code = command_code;
1896 	reg.bits.param = param;
1897 
1898 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1899 
1900 	for (i = 0; i < timeout_us; ++i) {
1901 		udelay(1);
1902 
1903 		/* Check if our GPINT got acked */
1904 		reg.bits.status = 0;
1905 		test = (union dmub_gpint_data_register)
1906 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1907 
1908 		if (test.all == reg.all)
1909 			return DMUB_STATUS_OK;
1910 	}
1911 
1912 	return DMUB_STATUS_TIMEOUT;
1913 }
1914 
1915 static struct dml2_soc_bb *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1916 {
1917 	struct dml2_soc_bb *bb;
1918 	long long addr;
1919 	int i = 0;
1920 	uint16_t chunk;
1921 	enum dmub_gpint_command send_addrs[] = {
1922 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1923 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1924 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1925 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1926 	};
1927 	enum dmub_status ret;
1928 
1929 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1930 	case IP_VERSION(4, 0, 1):
1931 		break;
1932 	default:
1933 		return NULL;
1934 	}
1935 
1936 	bb =  dm_allocate_gpu_mem(adev,
1937 				  DC_MEM_ALLOC_TYPE_GART,
1938 				  sizeof(struct dml2_soc_bb),
1939 				  &addr);
1940 	if (!bb)
1941 		return NULL;
1942 
1943 	for (i = 0; i < 4; i++) {
1944 		/* Extract 16-bit chunk */
1945 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1946 		/* Send the chunk */
1947 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1948 		if (ret != DMUB_STATUS_OK)
1949 			goto free_bb;
1950 	}
1951 
1952 	/* Now ask DMUB to copy the bb */
1953 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1954 	if (ret != DMUB_STATUS_OK)
1955 		goto free_bb;
1956 
1957 	return bb;
1958 
1959 free_bb:
1960 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1961 	return NULL;
1962 
1963 }
1964 
1965 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1966 	struct amdgpu_device *adev)
1967 {
1968 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1969 
1970 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1971 	case IP_VERSION(3, 5, 0):
1972 	case IP_VERSION(3, 6, 0):
1973 	case IP_VERSION(3, 5, 1):
1974 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1975 		break;
1976 	default:
1977 		/* ASICs older than DCN35 do not have IPSs */
1978 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1979 			ret = DMUB_IPS_DISABLE_ALL;
1980 		break;
1981 	}
1982 
1983 	return ret;
1984 }
1985 
1986 static int amdgpu_dm_init(struct amdgpu_device *adev)
1987 {
1988 	struct dc_init_data init_data;
1989 	struct dc_callback_init init_params;
1990 	int r;
1991 
1992 	adev->dm.ddev = adev_to_drm(adev);
1993 	adev->dm.adev = adev;
1994 
1995 	/* Zero all the fields */
1996 	memset(&init_data, 0, sizeof(init_data));
1997 	memset(&init_params, 0, sizeof(init_params));
1998 
1999 	mutex_init(&adev->dm.dpia_aux_lock);
2000 	mutex_init(&adev->dm.dc_lock);
2001 	mutex_init(&adev->dm.audio_lock);
2002 
2003 	if (amdgpu_dm_irq_init(adev)) {
2004 		drm_err(adev_to_drm(adev), "amdgpu: failed to initialize DM IRQ support.\n");
2005 		goto error;
2006 	}
2007 
2008 	init_data.asic_id.chip_family = adev->family;
2009 
2010 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2011 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2012 	init_data.asic_id.chip_id = adev->pdev->device;
2013 
2014 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2015 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2016 	init_data.asic_id.atombios_base_address =
2017 		adev->mode_info.atom_context->bios;
2018 
2019 	init_data.driver = adev;
2020 
2021 	/* cgs_device was created in dm_sw_init() */
2022 	init_data.cgs_device = adev->dm.cgs_device;
2023 
2024 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2025 
2026 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2027 	case IP_VERSION(2, 1, 0):
2028 		switch (adev->dm.dmcub_fw_version) {
2029 		case 0: /* development */
2030 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2031 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2032 			init_data.flags.disable_dmcu = false;
2033 			break;
2034 		default:
2035 			init_data.flags.disable_dmcu = true;
2036 		}
2037 		break;
2038 	case IP_VERSION(2, 0, 3):
2039 		init_data.flags.disable_dmcu = true;
2040 		break;
2041 	default:
2042 		break;
2043 	}
2044 
2045 	/* APU support S/G display by default except:
2046 	 * ASICs before Carrizo,
2047 	 * RAVEN1 (Users reported stability issue)
2048 	 */
2049 
2050 	if (adev->asic_type < CHIP_CARRIZO) {
2051 		init_data.flags.gpu_vm_support = false;
2052 	} else if (adev->asic_type == CHIP_RAVEN) {
2053 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2054 			init_data.flags.gpu_vm_support = false;
2055 		else
2056 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2057 	} else {
2058 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2059 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2060 		else
2061 			init_data.flags.gpu_vm_support =
2062 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2063 	}
2064 
2065 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2066 
2067 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2068 		init_data.flags.fbc_support = true;
2069 
2070 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2071 		init_data.flags.multi_mon_pp_mclk_switch = true;
2072 
2073 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2074 		init_data.flags.disable_fractional_pwm = true;
2075 
2076 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2077 		init_data.flags.edp_no_power_sequencing = true;
2078 
2079 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2080 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2081 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2082 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2083 
2084 	init_data.flags.seamless_boot_edp_requested = false;
2085 
2086 	if (amdgpu_device_seamless_boot_supported(adev)) {
2087 		init_data.flags.seamless_boot_edp_requested = true;
2088 		init_data.flags.allow_seamless_boot_optimization = true;
2089 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2090 	}
2091 
2092 	init_data.flags.enable_mipi_converter_optimization = true;
2093 
2094 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2095 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2096 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2097 
2098 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2099 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2100 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2101 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2102 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2103 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2104 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2105 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2106 	else
2107 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2108 
2109 	init_data.flags.disable_ips_in_vpb = 0;
2110 
2111 	/* Enable DWB for tested platforms only */
2112 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2113 		init_data.num_virtual_links = 1;
2114 
2115 	retrieve_dmi_info(&adev->dm, &init_data);
2116 
2117 	if (adev->dm.bb_from_dmub)
2118 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2119 	else
2120 		init_data.bb_from_dmub = NULL;
2121 
2122 	/* Display Core create. */
2123 	adev->dm.dc = dc_create(&init_data);
2124 
2125 	if (adev->dm.dc) {
2126 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2127 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2128 	} else {
2129 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2130 		goto error;
2131 	}
2132 
2133 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2134 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2135 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2136 	}
2137 
2138 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2139 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2140 	if (dm_should_disable_stutter(adev->pdev))
2141 		adev->dm.dc->debug.disable_stutter = true;
2142 
2143 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2144 		adev->dm.dc->debug.disable_stutter = true;
2145 
2146 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2147 		adev->dm.dc->debug.disable_dsc = true;
2148 
2149 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2150 		adev->dm.dc->debug.disable_clock_gate = true;
2151 
2152 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2153 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2154 
2155 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP)
2156 		adev->dm.dc->debug.force_disable_subvp = true;
2157 
2158 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2159 		adev->dm.dc->debug.using_dml2 = true;
2160 		adev->dm.dc->debug.using_dml21 = true;
2161 	}
2162 
2163 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2164 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2165 
2166 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2167 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2168 
2169 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2170 
2171 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2172 	adev->dm.dc->debug.ignore_cable_id = true;
2173 
2174 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2175 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2176 
2177 	r = dm_dmub_hw_init(adev);
2178 	if (r) {
2179 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2180 		goto error;
2181 	}
2182 
2183 	dc_hardware_init(adev->dm.dc);
2184 
2185 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2186 	if (!adev->dm.hpd_rx_offload_wq) {
2187 		drm_err(adev_to_drm(adev), "amdgpu: failed to create hpd rx offload workqueue.\n");
2188 		goto error;
2189 	}
2190 
2191 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2192 		struct dc_phy_addr_space_config pa_config;
2193 
2194 		mmhub_read_system_context(adev, &pa_config);
2195 
2196 		// Call the DC init_memory func
2197 		dc_setup_system_context(adev->dm.dc, &pa_config);
2198 	}
2199 
2200 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2201 	if (!adev->dm.freesync_module) {
2202 		drm_err(adev_to_drm(adev),
2203 		"amdgpu: failed to initialize freesync_module.\n");
2204 	} else
2205 		drm_dbg_driver(adev_to_drm(adev), "amdgpu: freesync_module init done %p.\n",
2206 				adev->dm.freesync_module);
2207 
2208 	amdgpu_dm_init_color_mod();
2209 
2210 	if (adev->dm.dc->caps.max_links > 0) {
2211 		adev->dm.vblank_control_workqueue =
2212 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2213 		if (!adev->dm.vblank_control_workqueue)
2214 			drm_err(adev_to_drm(adev), "amdgpu: failed to initialize vblank_workqueue.\n");
2215 	}
2216 
2217 	if (adev->dm.dc->caps.ips_support &&
2218 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2219 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2220 
2221 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2222 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2223 
2224 		if (!adev->dm.hdcp_workqueue)
2225 			drm_err(adev_to_drm(adev), "amdgpu: failed to initialize hdcp_workqueue.\n");
2226 		else
2227 			drm_dbg_driver(adev_to_drm(adev), "amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
2228 
2229 		dc_init_callbacks(adev->dm.dc, &init_params);
2230 	}
2231 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2232 		init_completion(&adev->dm.dmub_aux_transfer_done);
2233 		adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
2234 		if (!adev->dm.dmub_notify) {
2235 			drm_info(adev_to_drm(adev), "amdgpu: fail to allocate adev->dm.dmub_notify");
2236 			goto error;
2237 		}
2238 
2239 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2240 		if (!adev->dm.delayed_hpd_wq) {
2241 			drm_err(adev_to_drm(adev), "amdgpu: failed to create hpd offload workqueue.\n");
2242 			goto error;
2243 		}
2244 
2245 		amdgpu_dm_outbox_init(adev);
2246 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2247 			dmub_aux_setconfig_callback, false)) {
2248 			drm_err(adev_to_drm(adev), "amdgpu: fail to register dmub aux callback");
2249 			goto error;
2250 		}
2251 
2252 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2253 			init_completion(&adev->dm.fused_io[i].replied);
2254 
2255 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2256 			dmub_aux_fused_io_callback, false)) {
2257 			drm_err(adev_to_drm(adev), "amdgpu: fail to register dmub fused io callback");
2258 			goto error;
2259 		}
2260 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2261 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2262 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2263 		 * align legacy interface initialization sequence. Connection status will be proactivly
2264 		 * detected once in the amdgpu_dm_initialize_drm_device.
2265 		 */
2266 		dc_enable_dmub_outbox(adev->dm.dc);
2267 
2268 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2269 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2270 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2271 	}
2272 
2273 	if (amdgpu_dm_initialize_drm_device(adev)) {
2274 		drm_err(adev_to_drm(adev),
2275 		"amdgpu: failed to initialize sw for display support.\n");
2276 		goto error;
2277 	}
2278 
2279 	/* create fake encoders for MST */
2280 	dm_dp_create_fake_mst_encoders(adev);
2281 
2282 	/* TODO: Add_display_info? */
2283 
2284 	/* TODO use dynamic cursor width */
2285 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2286 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2287 
2288 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2289 		drm_err(adev_to_drm(adev),
2290 		"amdgpu: failed to initialize sw for display support.\n");
2291 		goto error;
2292 	}
2293 
2294 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2295 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2296 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2297 		drm_err(adev_to_drm(adev), "amdgpu: failed to initialize secure display contexts.\n");
2298 
2299 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2300 		adev->dm.secure_display_ctx.support_mul_roi = true;
2301 
2302 #endif
2303 
2304 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2305 
2306 	return 0;
2307 error:
2308 	amdgpu_dm_fini(adev);
2309 
2310 	return -EINVAL;
2311 }
2312 
2313 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2314 {
2315 	struct amdgpu_device *adev = ip_block->adev;
2316 
2317 	amdgpu_dm_audio_fini(adev);
2318 
2319 	return 0;
2320 }
2321 
2322 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2323 {
2324 	int i;
2325 
2326 	if (adev->dm.vblank_control_workqueue) {
2327 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2328 		adev->dm.vblank_control_workqueue = NULL;
2329 	}
2330 
2331 	if (adev->dm.idle_workqueue) {
2332 		if (adev->dm.idle_workqueue->running) {
2333 			adev->dm.idle_workqueue->enable = false;
2334 			flush_work(&adev->dm.idle_workqueue->work);
2335 		}
2336 
2337 		kfree(adev->dm.idle_workqueue);
2338 		adev->dm.idle_workqueue = NULL;
2339 	}
2340 
2341 	amdgpu_dm_destroy_drm_device(&adev->dm);
2342 
2343 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2344 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2345 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2346 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2347 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2348 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2349 			}
2350 		}
2351 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2352 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2353 	}
2354 #endif
2355 	if (adev->dm.hdcp_workqueue) {
2356 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2357 		adev->dm.hdcp_workqueue = NULL;
2358 	}
2359 
2360 	if (adev->dm.dc) {
2361 		dc_deinit_callbacks(adev->dm.dc);
2362 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2363 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2364 			kfree(adev->dm.dmub_notify);
2365 			adev->dm.dmub_notify = NULL;
2366 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2367 			adev->dm.delayed_hpd_wq = NULL;
2368 		}
2369 	}
2370 
2371 	if (adev->dm.dmub_bo)
2372 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2373 				      &adev->dm.dmub_bo_gpu_addr,
2374 				      &adev->dm.dmub_bo_cpu_addr);
2375 
2376 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2377 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2378 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2379 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2380 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2381 			}
2382 		}
2383 
2384 		kfree(adev->dm.hpd_rx_offload_wq);
2385 		adev->dm.hpd_rx_offload_wq = NULL;
2386 	}
2387 
2388 	/* DC Destroy TODO: Replace destroy DAL */
2389 	if (adev->dm.dc)
2390 		dc_destroy(&adev->dm.dc);
2391 	/*
2392 	 * TODO: pageflip, vlank interrupt
2393 	 *
2394 	 * amdgpu_dm_irq_fini(adev);
2395 	 */
2396 
2397 	if (adev->dm.cgs_device) {
2398 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2399 		adev->dm.cgs_device = NULL;
2400 	}
2401 	if (adev->dm.freesync_module) {
2402 		mod_freesync_destroy(adev->dm.freesync_module);
2403 		adev->dm.freesync_module = NULL;
2404 	}
2405 
2406 	mutex_destroy(&adev->dm.audio_lock);
2407 	mutex_destroy(&adev->dm.dc_lock);
2408 	mutex_destroy(&adev->dm.dpia_aux_lock);
2409 }
2410 
2411 static int load_dmcu_fw(struct amdgpu_device *adev)
2412 {
2413 	const char *fw_name_dmcu = NULL;
2414 	int r;
2415 	const struct dmcu_firmware_header_v1_0 *hdr;
2416 
2417 	switch (adev->asic_type) {
2418 #if defined(CONFIG_DRM_AMD_DC_SI)
2419 	case CHIP_TAHITI:
2420 	case CHIP_PITCAIRN:
2421 	case CHIP_VERDE:
2422 	case CHIP_OLAND:
2423 #endif
2424 	case CHIP_BONAIRE:
2425 	case CHIP_HAWAII:
2426 	case CHIP_KAVERI:
2427 	case CHIP_KABINI:
2428 	case CHIP_MULLINS:
2429 	case CHIP_TONGA:
2430 	case CHIP_FIJI:
2431 	case CHIP_CARRIZO:
2432 	case CHIP_STONEY:
2433 	case CHIP_POLARIS11:
2434 	case CHIP_POLARIS10:
2435 	case CHIP_POLARIS12:
2436 	case CHIP_VEGAM:
2437 	case CHIP_VEGA10:
2438 	case CHIP_VEGA12:
2439 	case CHIP_VEGA20:
2440 		return 0;
2441 	case CHIP_NAVI12:
2442 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2443 		break;
2444 	case CHIP_RAVEN:
2445 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2446 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2447 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2448 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2449 		else
2450 			return 0;
2451 		break;
2452 	default:
2453 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2454 		case IP_VERSION(2, 0, 2):
2455 		case IP_VERSION(2, 0, 3):
2456 		case IP_VERSION(2, 0, 0):
2457 		case IP_VERSION(2, 1, 0):
2458 		case IP_VERSION(3, 0, 0):
2459 		case IP_VERSION(3, 0, 2):
2460 		case IP_VERSION(3, 0, 3):
2461 		case IP_VERSION(3, 0, 1):
2462 		case IP_VERSION(3, 1, 2):
2463 		case IP_VERSION(3, 1, 3):
2464 		case IP_VERSION(3, 1, 4):
2465 		case IP_VERSION(3, 1, 5):
2466 		case IP_VERSION(3, 1, 6):
2467 		case IP_VERSION(3, 2, 0):
2468 		case IP_VERSION(3, 2, 1):
2469 		case IP_VERSION(3, 5, 0):
2470 		case IP_VERSION(3, 5, 1):
2471 		case IP_VERSION(3, 6, 0):
2472 		case IP_VERSION(4, 0, 1):
2473 			return 0;
2474 		default:
2475 			break;
2476 		}
2477 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2478 		return -EINVAL;
2479 	}
2480 
2481 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2482 		DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
2483 		return 0;
2484 	}
2485 
2486 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2487 				 "%s", fw_name_dmcu);
2488 	if (r == -ENODEV) {
2489 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2490 		DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
2491 		adev->dm.fw_dmcu = NULL;
2492 		return 0;
2493 	}
2494 	if (r) {
2495 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2496 			fw_name_dmcu);
2497 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2498 		return r;
2499 	}
2500 
2501 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2502 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2503 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2504 	adev->firmware.fw_size +=
2505 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2506 
2507 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2508 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2509 	adev->firmware.fw_size +=
2510 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2511 
2512 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2513 
2514 	DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
2515 
2516 	return 0;
2517 }
2518 
2519 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2520 {
2521 	struct amdgpu_device *adev = ctx;
2522 
2523 	return dm_read_reg(adev->dm.dc->ctx, address);
2524 }
2525 
2526 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2527 				     uint32_t value)
2528 {
2529 	struct amdgpu_device *adev = ctx;
2530 
2531 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2532 }
2533 
2534 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2535 {
2536 	struct dmub_srv_create_params create_params;
2537 	struct dmub_srv_region_params region_params;
2538 	struct dmub_srv_region_info region_info;
2539 	struct dmub_srv_memory_params memory_params;
2540 	struct dmub_srv_fb_info *fb_info;
2541 	struct dmub_srv *dmub_srv;
2542 	const struct dmcub_firmware_header_v1_0 *hdr;
2543 	enum dmub_asic dmub_asic;
2544 	enum dmub_status status;
2545 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2546 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2547 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2548 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2549 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2550 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2551 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2552 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2553 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2554 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2555 	};
2556 	int r;
2557 
2558 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2559 	case IP_VERSION(2, 1, 0):
2560 		dmub_asic = DMUB_ASIC_DCN21;
2561 		break;
2562 	case IP_VERSION(3, 0, 0):
2563 		dmub_asic = DMUB_ASIC_DCN30;
2564 		break;
2565 	case IP_VERSION(3, 0, 1):
2566 		dmub_asic = DMUB_ASIC_DCN301;
2567 		break;
2568 	case IP_VERSION(3, 0, 2):
2569 		dmub_asic = DMUB_ASIC_DCN302;
2570 		break;
2571 	case IP_VERSION(3, 0, 3):
2572 		dmub_asic = DMUB_ASIC_DCN303;
2573 		break;
2574 	case IP_VERSION(3, 1, 2):
2575 	case IP_VERSION(3, 1, 3):
2576 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2577 		break;
2578 	case IP_VERSION(3, 1, 4):
2579 		dmub_asic = DMUB_ASIC_DCN314;
2580 		break;
2581 	case IP_VERSION(3, 1, 5):
2582 		dmub_asic = DMUB_ASIC_DCN315;
2583 		break;
2584 	case IP_VERSION(3, 1, 6):
2585 		dmub_asic = DMUB_ASIC_DCN316;
2586 		break;
2587 	case IP_VERSION(3, 2, 0):
2588 		dmub_asic = DMUB_ASIC_DCN32;
2589 		break;
2590 	case IP_VERSION(3, 2, 1):
2591 		dmub_asic = DMUB_ASIC_DCN321;
2592 		break;
2593 	case IP_VERSION(3, 5, 0):
2594 	case IP_VERSION(3, 5, 1):
2595 		dmub_asic = DMUB_ASIC_DCN35;
2596 		break;
2597 	case IP_VERSION(3, 6, 0):
2598 		dmub_asic = DMUB_ASIC_DCN36;
2599 		break;
2600 	case IP_VERSION(4, 0, 1):
2601 		dmub_asic = DMUB_ASIC_DCN401;
2602 		break;
2603 
2604 	default:
2605 		/* ASIC doesn't support DMUB. */
2606 		return 0;
2607 	}
2608 
2609 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2610 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2611 
2612 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2613 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2614 			AMDGPU_UCODE_ID_DMCUB;
2615 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2616 			adev->dm.dmub_fw;
2617 		adev->firmware.fw_size +=
2618 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2619 
2620 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2621 			 adev->dm.dmcub_fw_version);
2622 	}
2623 
2624 
2625 	adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
2626 	dmub_srv = adev->dm.dmub_srv;
2627 
2628 	if (!dmub_srv) {
2629 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2630 		return -ENOMEM;
2631 	}
2632 
2633 	memset(&create_params, 0, sizeof(create_params));
2634 	create_params.user_ctx = adev;
2635 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2636 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2637 	create_params.asic = dmub_asic;
2638 
2639 	/* Create the DMUB service. */
2640 	status = dmub_srv_create(dmub_srv, &create_params);
2641 	if (status != DMUB_STATUS_OK) {
2642 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2643 		return -EINVAL;
2644 	}
2645 
2646 	/* Calculate the size of all the regions for the DMUB service. */
2647 	memset(&region_params, 0, sizeof(region_params));
2648 
2649 	region_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2650 					PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
2651 	region_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2652 	region_params.vbios_size = adev->bios_size;
2653 	region_params.fw_bss_data = region_params.bss_data_size ?
2654 		adev->dm.dmub_fw->data +
2655 		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2656 		le32_to_cpu(hdr->inst_const_bytes) : NULL;
2657 	region_params.fw_inst_const =
2658 		adev->dm.dmub_fw->data +
2659 		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2660 		PSP_HEADER_BYTES;
2661 	region_params.window_memory_type = window_memory_type;
2662 
2663 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2664 					   &region_info);
2665 
2666 	if (status != DMUB_STATUS_OK) {
2667 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2668 		return -EINVAL;
2669 	}
2670 
2671 	/*
2672 	 * Allocate a framebuffer based on the total size of all the regions.
2673 	 * TODO: Move this into GART.
2674 	 */
2675 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2676 				    AMDGPU_GEM_DOMAIN_VRAM |
2677 				    AMDGPU_GEM_DOMAIN_GTT,
2678 				    &adev->dm.dmub_bo,
2679 				    &adev->dm.dmub_bo_gpu_addr,
2680 				    &adev->dm.dmub_bo_cpu_addr);
2681 	if (r)
2682 		return r;
2683 
2684 	/* Rebase the regions on the framebuffer address. */
2685 	memset(&memory_params, 0, sizeof(memory_params));
2686 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2687 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2688 	memory_params.region_info = &region_info;
2689 	memory_params.window_memory_type = window_memory_type;
2690 
2691 	adev->dm.dmub_fb_info =
2692 		kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2693 	fb_info = adev->dm.dmub_fb_info;
2694 
2695 	if (!fb_info) {
2696 		drm_err(adev_to_drm(adev),
2697 			"Failed to allocate framebuffer info for DMUB service!\n");
2698 		return -ENOMEM;
2699 	}
2700 
2701 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2702 	if (status != DMUB_STATUS_OK) {
2703 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2704 		return -EINVAL;
2705 	}
2706 
2707 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2708 
2709 	return 0;
2710 }
2711 
2712 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2713 {
2714 	struct amdgpu_device *adev = ip_block->adev;
2715 	int r;
2716 
2717 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2718 
2719 	if (!adev->dm.cgs_device) {
2720 		drm_err(adev_to_drm(adev), "amdgpu: failed to create cgs device.\n");
2721 		return -EINVAL;
2722 	}
2723 
2724 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2725 	INIT_LIST_HEAD(&adev->dm.da_list);
2726 
2727 	r = dm_dmub_sw_init(adev);
2728 	if (r)
2729 		return r;
2730 
2731 	return load_dmcu_fw(adev);
2732 }
2733 
2734 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2735 {
2736 	struct amdgpu_device *adev = ip_block->adev;
2737 	struct dal_allocation *da;
2738 
2739 	list_for_each_entry(da, &adev->dm.da_list, list) {
2740 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2741 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2742 			list_del(&da->list);
2743 			kfree(da);
2744 			adev->dm.bb_from_dmub = NULL;
2745 			break;
2746 		}
2747 	}
2748 
2749 
2750 	kfree(adev->dm.dmub_fb_info);
2751 	adev->dm.dmub_fb_info = NULL;
2752 
2753 	if (adev->dm.dmub_srv) {
2754 		dmub_srv_destroy(adev->dm.dmub_srv);
2755 		kfree(adev->dm.dmub_srv);
2756 		adev->dm.dmub_srv = NULL;
2757 	}
2758 
2759 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2760 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2761 
2762 	return 0;
2763 }
2764 
2765 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2766 {
2767 	struct amdgpu_dm_connector *aconnector;
2768 	struct drm_connector *connector;
2769 	struct drm_connector_list_iter iter;
2770 	int ret = 0;
2771 
2772 	drm_connector_list_iter_begin(dev, &iter);
2773 	drm_for_each_connector_iter(connector, &iter) {
2774 
2775 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2776 			continue;
2777 
2778 		aconnector = to_amdgpu_dm_connector(connector);
2779 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2780 		    aconnector->mst_mgr.aux) {
2781 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2782 					 aconnector,
2783 					 aconnector->base.base.id);
2784 
2785 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2786 			if (ret < 0) {
2787 				drm_err(dev, "DM_MST: Failed to start MST\n");
2788 				aconnector->dc_link->type =
2789 					dc_connection_single;
2790 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2791 								     aconnector->dc_link);
2792 				break;
2793 			}
2794 		}
2795 	}
2796 	drm_connector_list_iter_end(&iter);
2797 
2798 	return ret;
2799 }
2800 
2801 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2802 {
2803 	struct amdgpu_device *adev = ip_block->adev;
2804 
2805 	struct dmcu_iram_parameters params;
2806 	unsigned int linear_lut[16];
2807 	int i;
2808 	struct dmcu *dmcu = NULL;
2809 
2810 	dmcu = adev->dm.dc->res_pool->dmcu;
2811 
2812 	for (i = 0; i < 16; i++)
2813 		linear_lut[i] = 0xFFFF * i / 15;
2814 
2815 	params.set = 0;
2816 	params.backlight_ramping_override = false;
2817 	params.backlight_ramping_start = 0xCCCC;
2818 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2819 	params.backlight_lut_array_size = 16;
2820 	params.backlight_lut_array = linear_lut;
2821 
2822 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2823 	 * 0xFFFF x 0.01 = 0x28F
2824 	 */
2825 	params.min_abm_backlight = 0x28F;
2826 	/* In the case where abm is implemented on dmcub,
2827 	 * dmcu object will be null.
2828 	 * ABM 2.4 and up are implemented on dmcub.
2829 	 */
2830 	if (dmcu) {
2831 		if (!dmcu_load_iram(dmcu, params))
2832 			return -EINVAL;
2833 	} else if (adev->dm.dc->ctx->dmub_srv) {
2834 		struct dc_link *edp_links[MAX_NUM_EDP];
2835 		int edp_num;
2836 
2837 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2838 		for (i = 0; i < edp_num; i++) {
2839 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2840 				return -EINVAL;
2841 		}
2842 	}
2843 
2844 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2845 }
2846 
2847 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2848 {
2849 	u8 buf[UUID_SIZE];
2850 	guid_t guid;
2851 	int ret;
2852 
2853 	mutex_lock(&mgr->lock);
2854 	if (!mgr->mst_primary)
2855 		goto out_fail;
2856 
2857 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2858 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2859 		goto out_fail;
2860 	}
2861 
2862 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2863 				 DP_MST_EN |
2864 				 DP_UP_REQ_EN |
2865 				 DP_UPSTREAM_IS_SRC);
2866 	if (ret < 0) {
2867 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2868 		goto out_fail;
2869 	}
2870 
2871 	/* Some hubs forget their guids after they resume */
2872 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2873 	if (ret != sizeof(buf)) {
2874 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2875 		goto out_fail;
2876 	}
2877 
2878 	import_guid(&guid, buf);
2879 
2880 	if (guid_is_null(&guid)) {
2881 		guid_gen(&guid);
2882 		export_guid(buf, &guid);
2883 
2884 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2885 
2886 		if (ret != sizeof(buf)) {
2887 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2888 			goto out_fail;
2889 		}
2890 	}
2891 
2892 	guid_copy(&mgr->mst_primary->guid, &guid);
2893 
2894 out_fail:
2895 	mutex_unlock(&mgr->lock);
2896 }
2897 
2898 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2899 {
2900 	struct cec_notifier *n = aconnector->notifier;
2901 
2902 	if (!n)
2903 		return;
2904 
2905 	cec_notifier_phys_addr_invalidate(n);
2906 }
2907 
2908 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2909 {
2910 	struct drm_connector *connector = &aconnector->base;
2911 	struct cec_notifier *n = aconnector->notifier;
2912 
2913 	if (!n)
2914 		return;
2915 
2916 	cec_notifier_set_phys_addr(n,
2917 				   connector->display_info.source_physical_address);
2918 }
2919 
2920 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2921 {
2922 	struct amdgpu_dm_connector *aconnector;
2923 	struct drm_connector *connector;
2924 	struct drm_connector_list_iter conn_iter;
2925 
2926 	drm_connector_list_iter_begin(ddev, &conn_iter);
2927 	drm_for_each_connector_iter(connector, &conn_iter) {
2928 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2929 			continue;
2930 
2931 		aconnector = to_amdgpu_dm_connector(connector);
2932 		if (suspend)
2933 			hdmi_cec_unset_edid(aconnector);
2934 		else
2935 			hdmi_cec_set_edid(aconnector);
2936 	}
2937 	drm_connector_list_iter_end(&conn_iter);
2938 }
2939 
2940 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2941 {
2942 	struct amdgpu_dm_connector *aconnector;
2943 	struct drm_connector *connector;
2944 	struct drm_connector_list_iter iter;
2945 	struct drm_dp_mst_topology_mgr *mgr;
2946 
2947 	drm_connector_list_iter_begin(dev, &iter);
2948 	drm_for_each_connector_iter(connector, &iter) {
2949 
2950 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2951 			continue;
2952 
2953 		aconnector = to_amdgpu_dm_connector(connector);
2954 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2955 		    aconnector->mst_root)
2956 			continue;
2957 
2958 		mgr = &aconnector->mst_mgr;
2959 
2960 		if (suspend) {
2961 			drm_dp_mst_topology_mgr_suspend(mgr);
2962 		} else {
2963 			/* if extended timeout is supported in hardware,
2964 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2965 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2966 			 */
2967 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2968 			if (!dp_is_lttpr_present(aconnector->dc_link))
2969 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2970 
2971 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2972 			 * once topology probing work is pulled out from mst resume into mst
2973 			 * resume 2nd step. mst resume 2nd step should be called after old
2974 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2975 			 */
2976 			resume_mst_branch_status(mgr);
2977 		}
2978 	}
2979 	drm_connector_list_iter_end(&iter);
2980 }
2981 
2982 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2983 {
2984 	int ret = 0;
2985 
2986 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2987 	 * on window driver dc implementation.
2988 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2989 	 * should be passed to smu during boot up and resume from s3.
2990 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2991 	 * dcn20_resource_construct
2992 	 * then call pplib functions below to pass the settings to smu:
2993 	 * smu_set_watermarks_for_clock_ranges
2994 	 * smu_set_watermarks_table
2995 	 * navi10_set_watermarks_table
2996 	 * smu_write_watermarks_table
2997 	 *
2998 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2999 	 * dc has implemented different flow for window driver:
3000 	 * dc_hardware_init / dc_set_power_state
3001 	 * dcn10_init_hw
3002 	 * notify_wm_ranges
3003 	 * set_wm_ranges
3004 	 * -- Linux
3005 	 * smu_set_watermarks_for_clock_ranges
3006 	 * renoir_set_watermarks_table
3007 	 * smu_write_watermarks_table
3008 	 *
3009 	 * For Linux,
3010 	 * dc_hardware_init -> amdgpu_dm_init
3011 	 * dc_set_power_state --> dm_resume
3012 	 *
3013 	 * therefore, this function apply to navi10/12/14 but not Renoir
3014 	 * *
3015 	 */
3016 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3017 	case IP_VERSION(2, 0, 2):
3018 	case IP_VERSION(2, 0, 0):
3019 		break;
3020 	default:
3021 		return 0;
3022 	}
3023 
3024 	ret = amdgpu_dpm_write_watermarks_table(adev);
3025 	if (ret) {
3026 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3027 		return ret;
3028 	}
3029 
3030 	return 0;
3031 }
3032 
3033 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3034 {
3035 	struct amdgpu_display_manager *dm = &adev->dm;
3036 	struct amdgpu_i2c_adapter *oem_i2c;
3037 	struct ddc_service *oem_ddc_service;
3038 	int r;
3039 
3040 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3041 	if (oem_ddc_service) {
3042 		oem_i2c = create_i2c(oem_ddc_service, true);
3043 		if (!oem_i2c) {
3044 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3045 			return -ENOMEM;
3046 		}
3047 
3048 		r = i2c_add_adapter(&oem_i2c->base);
3049 		if (r) {
3050 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3051 			kfree(oem_i2c);
3052 			return r;
3053 		}
3054 		dm->oem_i2c = oem_i2c;
3055 	}
3056 
3057 	return 0;
3058 }
3059 
3060 /**
3061  * dm_hw_init() - Initialize DC device
3062  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3063  *
3064  * Initialize the &struct amdgpu_display_manager device. This involves calling
3065  * the initializers of each DM component, then populating the struct with them.
3066  *
3067  * Although the function implies hardware initialization, both hardware and
3068  * software are initialized here. Splitting them out to their relevant init
3069  * hooks is a future TODO item.
3070  *
3071  * Some notable things that are initialized here:
3072  *
3073  * - Display Core, both software and hardware
3074  * - DC modules that we need (freesync and color management)
3075  * - DRM software states
3076  * - Interrupt sources and handlers
3077  * - Vblank support
3078  * - Debug FS entries, if enabled
3079  */
3080 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3081 {
3082 	struct amdgpu_device *adev = ip_block->adev;
3083 	int r;
3084 
3085 	/* Create DAL display manager */
3086 	r = amdgpu_dm_init(adev);
3087 	if (r)
3088 		return r;
3089 	amdgpu_dm_hpd_init(adev);
3090 
3091 	r = dm_oem_i2c_hw_init(adev);
3092 	if (r)
3093 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3094 
3095 	return 0;
3096 }
3097 
3098 /**
3099  * dm_hw_fini() - Teardown DC device
3100  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3101  *
3102  * Teardown components within &struct amdgpu_display_manager that require
3103  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3104  * were loaded. Also flush IRQ workqueues and disable them.
3105  */
3106 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3107 {
3108 	struct amdgpu_device *adev = ip_block->adev;
3109 
3110 	kfree(adev->dm.oem_i2c);
3111 
3112 	amdgpu_dm_hpd_fini(adev);
3113 
3114 	amdgpu_dm_irq_fini(adev);
3115 	amdgpu_dm_fini(adev);
3116 	return 0;
3117 }
3118 
3119 
3120 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3121 				 struct dc_state *state, bool enable)
3122 {
3123 	enum dc_irq_source irq_source;
3124 	struct amdgpu_crtc *acrtc;
3125 	int rc = -EBUSY;
3126 	int i = 0;
3127 
3128 	for (i = 0; i < state->stream_count; i++) {
3129 		acrtc = get_crtc_by_otg_inst(
3130 				adev, state->stream_status[i].primary_otg_inst);
3131 
3132 		if (acrtc && state->stream_status[i].plane_count != 0) {
3133 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3134 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3135 			if (rc)
3136 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3137 					 enable ? "enable" : "disable");
3138 
3139 			if (enable) {
3140 				if (amdgpu_dm_crtc_vrr_active(to_dm_crtc_state(acrtc->base.state)))
3141 					rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, true);
3142 			} else
3143 				rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, false);
3144 
3145 			if (rc)
3146 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n", enable ? "en" : "dis");
3147 
3148 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3149 			/* During gpu-reset we disable and then enable vblank irq, so
3150 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3151 			 */
3152 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3153 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3154 		}
3155 	}
3156 
3157 }
3158 
3159 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3160 
3161 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3162 {
3163 	struct dc_state *context __free(state_release) = NULL;
3164 	int i;
3165 	struct dc_stream_state *del_streams[MAX_PIPES];
3166 	int del_streams_count = 0;
3167 	struct dc_commit_streams_params params = {};
3168 
3169 	memset(del_streams, 0, sizeof(del_streams));
3170 
3171 	context = dc_state_create_current_copy(dc);
3172 	if (context == NULL)
3173 		return DC_ERROR_UNEXPECTED;
3174 
3175 	/* First remove from context all streams */
3176 	for (i = 0; i < context->stream_count; i++) {
3177 		struct dc_stream_state *stream = context->streams[i];
3178 
3179 		del_streams[del_streams_count++] = stream;
3180 	}
3181 
3182 	/* Remove all planes for removed streams and then remove the streams */
3183 	for (i = 0; i < del_streams_count; i++) {
3184 		enum dc_status res;
3185 
3186 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3187 			return DC_FAIL_DETACH_SURFACES;
3188 
3189 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3190 		if (res != DC_OK)
3191 			return res;
3192 	}
3193 
3194 	params.streams = context->streams;
3195 	params.stream_count = context->stream_count;
3196 
3197 	return dc_commit_streams(dc, &params);
3198 }
3199 
3200 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3201 {
3202 	int i;
3203 
3204 	if (dm->hpd_rx_offload_wq) {
3205 		for (i = 0; i < dm->dc->caps.max_links; i++)
3206 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3207 	}
3208 }
3209 
3210 static int dm_prepare_suspend(struct amdgpu_ip_block *ip_block)
3211 {
3212 	struct amdgpu_device *adev = ip_block->adev;
3213 
3214 	if (amdgpu_in_reset(adev))
3215 		return 0;
3216 
3217 	WARN_ON(adev->dm.cached_state);
3218 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3219 	if (IS_ERR(adev->dm.cached_state))
3220 		return PTR_ERR(adev->dm.cached_state);
3221 
3222 	return 0;
3223 }
3224 
3225 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3226 {
3227 	struct amdgpu_device *adev = ip_block->adev;
3228 	struct amdgpu_display_manager *dm = &adev->dm;
3229 
3230 	if (amdgpu_in_reset(adev)) {
3231 		enum dc_status res;
3232 
3233 		mutex_lock(&dm->dc_lock);
3234 
3235 		dc_allow_idle_optimizations(adev->dm.dc, false);
3236 
3237 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3238 
3239 		if (dm->cached_dc_state)
3240 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3241 
3242 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3243 		if (res != DC_OK) {
3244 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3245 			return -EINVAL;
3246 		}
3247 
3248 		amdgpu_dm_irq_suspend(adev);
3249 
3250 		hpd_rx_irq_work_suspend(dm);
3251 
3252 		return 0;
3253 	}
3254 
3255 	if (!adev->dm.cached_state) {
3256 		adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3257 		if (IS_ERR(adev->dm.cached_state))
3258 			return PTR_ERR(adev->dm.cached_state);
3259 	}
3260 
3261 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3262 
3263 	s3_handle_mst(adev_to_drm(adev), true);
3264 
3265 	amdgpu_dm_irq_suspend(adev);
3266 
3267 	hpd_rx_irq_work_suspend(dm);
3268 
3269 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3270 
3271 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3272 		dc_allow_idle_optimizations(dm->dc, true);
3273 
3274 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3275 
3276 	return 0;
3277 }
3278 
3279 struct drm_connector *
3280 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3281 					     struct drm_crtc *crtc)
3282 {
3283 	u32 i;
3284 	struct drm_connector_state *new_con_state;
3285 	struct drm_connector *connector;
3286 	struct drm_crtc *crtc_from_state;
3287 
3288 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3289 		crtc_from_state = new_con_state->crtc;
3290 
3291 		if (crtc_from_state == crtc)
3292 			return connector;
3293 	}
3294 
3295 	return NULL;
3296 }
3297 
3298 static void emulated_link_detect(struct dc_link *link)
3299 {
3300 	struct dc_sink_init_data sink_init_data = { 0 };
3301 	struct display_sink_capability sink_caps = { 0 };
3302 	enum dc_edid_status edid_status;
3303 	struct dc_context *dc_ctx = link->ctx;
3304 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3305 	struct dc_sink *sink = NULL;
3306 	struct dc_sink *prev_sink = NULL;
3307 
3308 	link->type = dc_connection_none;
3309 	prev_sink = link->local_sink;
3310 
3311 	if (prev_sink)
3312 		dc_sink_release(prev_sink);
3313 
3314 	switch (link->connector_signal) {
3315 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3316 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3317 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3318 		break;
3319 	}
3320 
3321 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3322 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3323 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3324 		break;
3325 	}
3326 
3327 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3328 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3329 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3330 		break;
3331 	}
3332 
3333 	case SIGNAL_TYPE_LVDS: {
3334 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3335 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3336 		break;
3337 	}
3338 
3339 	case SIGNAL_TYPE_EDP: {
3340 		sink_caps.transaction_type =
3341 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3342 		sink_caps.signal = SIGNAL_TYPE_EDP;
3343 		break;
3344 	}
3345 
3346 	case SIGNAL_TYPE_DISPLAY_PORT: {
3347 		sink_caps.transaction_type =
3348 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3349 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3350 		break;
3351 	}
3352 
3353 	default:
3354 		drm_err(dev, "Invalid connector type! signal:%d\n",
3355 			link->connector_signal);
3356 		return;
3357 	}
3358 
3359 	sink_init_data.link = link;
3360 	sink_init_data.sink_signal = sink_caps.signal;
3361 
3362 	sink = dc_sink_create(&sink_init_data);
3363 	if (!sink) {
3364 		drm_err(dev, "Failed to create sink!\n");
3365 		return;
3366 	}
3367 
3368 	/* dc_sink_create returns a new reference */
3369 	link->local_sink = sink;
3370 
3371 	edid_status = dm_helpers_read_local_edid(
3372 			link->ctx,
3373 			link,
3374 			sink);
3375 
3376 	if (edid_status != EDID_OK)
3377 		drm_err(dev, "Failed to read EDID\n");
3378 
3379 }
3380 
3381 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3382 				     struct amdgpu_display_manager *dm)
3383 {
3384 	struct {
3385 		struct dc_surface_update surface_updates[MAX_SURFACES];
3386 		struct dc_plane_info plane_infos[MAX_SURFACES];
3387 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3388 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3389 		struct dc_stream_update stream_update;
3390 	} *bundle __free(kfree);
3391 	int k, m;
3392 
3393 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
3394 
3395 	if (!bundle) {
3396 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3397 		return;
3398 	}
3399 
3400 	for (k = 0; k < dc_state->stream_count; k++) {
3401 		bundle->stream_update.stream = dc_state->streams[k];
3402 
3403 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3404 			bundle->surface_updates[m].surface =
3405 				dc_state->stream_status[k].plane_states[m];
3406 			bundle->surface_updates[m].surface->force_full_update =
3407 				true;
3408 		}
3409 
3410 		update_planes_and_stream_adapter(dm->dc,
3411 					 UPDATE_TYPE_FULL,
3412 					 dc_state->stream_status[k].plane_count,
3413 					 dc_state->streams[k],
3414 					 &bundle->stream_update,
3415 					 bundle->surface_updates);
3416 	}
3417 }
3418 
3419 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3420 					    struct dc_sink *sink)
3421 {
3422 	struct dc_panel_patch *ppatch = NULL;
3423 
3424 	if (!sink)
3425 		return;
3426 
3427 	ppatch = &sink->edid_caps.panel_patch;
3428 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3429 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3430 		drm_dbg_driver(adev_to_drm(adev),
3431 			       "%s: adding a %ds delay as w/a for panel\n",
3432 			       __func__,
3433 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3434 	}
3435 }
3436 
3437 static int dm_resume(struct amdgpu_ip_block *ip_block)
3438 {
3439 	struct amdgpu_device *adev = ip_block->adev;
3440 	struct drm_device *ddev = adev_to_drm(adev);
3441 	struct amdgpu_display_manager *dm = &adev->dm;
3442 	struct amdgpu_dm_connector *aconnector;
3443 	struct drm_connector *connector;
3444 	struct drm_connector_list_iter iter;
3445 	struct drm_crtc *crtc;
3446 	struct drm_crtc_state *new_crtc_state;
3447 	struct dm_crtc_state *dm_new_crtc_state;
3448 	struct drm_plane *plane;
3449 	struct drm_plane_state *new_plane_state;
3450 	struct dm_plane_state *dm_new_plane_state;
3451 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3452 	enum dc_connection_type new_connection_type = dc_connection_none;
3453 	struct dc_state *dc_state;
3454 	int i, r, j;
3455 	struct dc_commit_streams_params commit_params = {};
3456 
3457 	if (dm->dc->caps.ips_support) {
3458 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3459 	}
3460 
3461 	if (amdgpu_in_reset(adev)) {
3462 		dc_state = dm->cached_dc_state;
3463 
3464 		/*
3465 		 * The dc->current_state is backed up into dm->cached_dc_state
3466 		 * before we commit 0 streams.
3467 		 *
3468 		 * DC will clear link encoder assignments on the real state
3469 		 * but the changes won't propagate over to the copy we made
3470 		 * before the 0 streams commit.
3471 		 *
3472 		 * DC expects that link encoder assignments are *not* valid
3473 		 * when committing a state, so as a workaround we can copy
3474 		 * off of the current state.
3475 		 *
3476 		 * We lose the previous assignments, but we had already
3477 		 * commit 0 streams anyway.
3478 		 */
3479 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3480 
3481 		r = dm_dmub_hw_init(adev);
3482 		if (r)
3483 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3484 
3485 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3486 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3487 
3488 		dc_resume(dm->dc);
3489 
3490 		amdgpu_dm_irq_resume_early(adev);
3491 
3492 		for (i = 0; i < dc_state->stream_count; i++) {
3493 			dc_state->streams[i]->mode_changed = true;
3494 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3495 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3496 					= 0xffffffff;
3497 			}
3498 		}
3499 
3500 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3501 			amdgpu_dm_outbox_init(adev);
3502 			dc_enable_dmub_outbox(adev->dm.dc);
3503 		}
3504 
3505 		commit_params.streams = dc_state->streams;
3506 		commit_params.stream_count = dc_state->stream_count;
3507 		dc_exit_ips_for_hw_access(dm->dc);
3508 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3509 
3510 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3511 
3512 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3513 
3514 		dc_state_release(dm->cached_dc_state);
3515 		dm->cached_dc_state = NULL;
3516 
3517 		amdgpu_dm_irq_resume_late(adev);
3518 
3519 		mutex_unlock(&dm->dc_lock);
3520 
3521 		/* set the backlight after a reset */
3522 		for (i = 0; i < dm->num_of_edps; i++) {
3523 			if (dm->backlight_dev[i])
3524 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3525 		}
3526 
3527 		return 0;
3528 	}
3529 
3530 	/* leave display off for S4 sequence */
3531 	if (adev->in_s4)
3532 		return 0;
3533 
3534 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3535 	dc_state_release(dm_state->context);
3536 	dm_state->context = dc_state_create(dm->dc, NULL);
3537 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3538 
3539 	/* Before powering on DC we need to re-initialize DMUB. */
3540 	dm_dmub_hw_resume(adev);
3541 
3542 	/* Re-enable outbox interrupts for DPIA. */
3543 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3544 		amdgpu_dm_outbox_init(adev);
3545 		dc_enable_dmub_outbox(adev->dm.dc);
3546 	}
3547 
3548 	/* power on hardware */
3549 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3550 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3551 
3552 	/* program HPD filter */
3553 	dc_resume(dm->dc);
3554 
3555 	/*
3556 	 * early enable HPD Rx IRQ, should be done before set mode as short
3557 	 * pulse interrupts are used for MST
3558 	 */
3559 	amdgpu_dm_irq_resume_early(adev);
3560 
3561 	s3_handle_hdmi_cec(ddev, false);
3562 
3563 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3564 	s3_handle_mst(ddev, false);
3565 
3566 	/* Do detection*/
3567 	drm_connector_list_iter_begin(ddev, &iter);
3568 	drm_for_each_connector_iter(connector, &iter) {
3569 		bool ret;
3570 
3571 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3572 			continue;
3573 
3574 		aconnector = to_amdgpu_dm_connector(connector);
3575 
3576 		if (!aconnector->dc_link)
3577 			continue;
3578 
3579 		/*
3580 		 * this is the case when traversing through already created end sink
3581 		 * MST connectors, should be skipped
3582 		 */
3583 		if (aconnector->mst_root)
3584 			continue;
3585 
3586 		guard(mutex)(&aconnector->hpd_lock);
3587 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3588 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3589 
3590 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3591 			emulated_link_detect(aconnector->dc_link);
3592 		} else {
3593 			guard(mutex)(&dm->dc_lock);
3594 			dc_exit_ips_for_hw_access(dm->dc);
3595 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3596 			if (ret) {
3597 				/* w/a delay for certain panels */
3598 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3599 			}
3600 		}
3601 
3602 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3603 			aconnector->fake_enable = false;
3604 
3605 		if (aconnector->dc_sink)
3606 			dc_sink_release(aconnector->dc_sink);
3607 		aconnector->dc_sink = NULL;
3608 		amdgpu_dm_update_connector_after_detect(aconnector);
3609 	}
3610 	drm_connector_list_iter_end(&iter);
3611 
3612 	/* Force mode set in atomic commit */
3613 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3614 		new_crtc_state->active_changed = true;
3615 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3616 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3617 	}
3618 
3619 	/*
3620 	 * atomic_check is expected to create the dc states. We need to release
3621 	 * them here, since they were duplicated as part of the suspend
3622 	 * procedure.
3623 	 */
3624 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3625 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3626 		if (dm_new_crtc_state->stream) {
3627 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3628 			dc_stream_release(dm_new_crtc_state->stream);
3629 			dm_new_crtc_state->stream = NULL;
3630 		}
3631 		dm_new_crtc_state->base.color_mgmt_changed = true;
3632 	}
3633 
3634 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3635 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3636 		if (dm_new_plane_state->dc_state) {
3637 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3638 			dc_plane_state_release(dm_new_plane_state->dc_state);
3639 			dm_new_plane_state->dc_state = NULL;
3640 		}
3641 	}
3642 
3643 	drm_atomic_helper_resume(ddev, dm->cached_state);
3644 
3645 	dm->cached_state = NULL;
3646 
3647 	/* Do mst topology probing after resuming cached state*/
3648 	drm_connector_list_iter_begin(ddev, &iter);
3649 	drm_for_each_connector_iter(connector, &iter) {
3650 
3651 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3652 			continue;
3653 
3654 		aconnector = to_amdgpu_dm_connector(connector);
3655 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3656 		    aconnector->mst_root)
3657 			continue;
3658 
3659 		drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3660 	}
3661 	drm_connector_list_iter_end(&iter);
3662 
3663 	amdgpu_dm_irq_resume_late(adev);
3664 
3665 	amdgpu_dm_smu_write_watermarks_table(adev);
3666 
3667 	drm_kms_helper_hotplug_event(ddev);
3668 
3669 	return 0;
3670 }
3671 
3672 /**
3673  * DOC: DM Lifecycle
3674  *
3675  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3676  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3677  * the base driver's device list to be initialized and torn down accordingly.
3678  *
3679  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3680  */
3681 
3682 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3683 	.name = "dm",
3684 	.early_init = dm_early_init,
3685 	.late_init = dm_late_init,
3686 	.sw_init = dm_sw_init,
3687 	.sw_fini = dm_sw_fini,
3688 	.early_fini = amdgpu_dm_early_fini,
3689 	.hw_init = dm_hw_init,
3690 	.hw_fini = dm_hw_fini,
3691 	.prepare_suspend = dm_prepare_suspend,
3692 	.suspend = dm_suspend,
3693 	.resume = dm_resume,
3694 	.is_idle = dm_is_idle,
3695 	.wait_for_idle = dm_wait_for_idle,
3696 	.check_soft_reset = dm_check_soft_reset,
3697 	.soft_reset = dm_soft_reset,
3698 	.set_clockgating_state = dm_set_clockgating_state,
3699 	.set_powergating_state = dm_set_powergating_state,
3700 };
3701 
3702 const struct amdgpu_ip_block_version dm_ip_block = {
3703 	.type = AMD_IP_BLOCK_TYPE_DCE,
3704 	.major = 1,
3705 	.minor = 0,
3706 	.rev = 0,
3707 	.funcs = &amdgpu_dm_funcs,
3708 };
3709 
3710 
3711 /**
3712  * DOC: atomic
3713  *
3714  * *WIP*
3715  */
3716 
3717 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3718 	.fb_create = amdgpu_display_user_framebuffer_create,
3719 	.get_format_info = amdgpu_dm_plane_get_format_info,
3720 	.atomic_check = amdgpu_dm_atomic_check,
3721 	.atomic_commit = drm_atomic_helper_commit,
3722 };
3723 
3724 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3725 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3726 	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
3727 };
3728 
3729 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3730 {
3731 	struct amdgpu_dm_backlight_caps *caps;
3732 	struct drm_connector *conn_base;
3733 	struct amdgpu_device *adev;
3734 	struct drm_luminance_range_info *luminance_range;
3735 	int min_input_signal_override;
3736 
3737 	if (aconnector->bl_idx == -1 ||
3738 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3739 		return;
3740 
3741 	conn_base = &aconnector->base;
3742 	adev = drm_to_adev(conn_base->dev);
3743 
3744 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3745 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3746 	caps->aux_support = false;
3747 
3748 	if (caps->ext_caps->bits.oled == 1
3749 	    /*
3750 	     * ||
3751 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3752 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3753 	     */)
3754 		caps->aux_support = true;
3755 
3756 	if (amdgpu_backlight == 0)
3757 		caps->aux_support = false;
3758 	else if (amdgpu_backlight == 1)
3759 		caps->aux_support = true;
3760 	if (caps->aux_support)
3761 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3762 
3763 	luminance_range = &conn_base->display_info.luminance_range;
3764 
3765 	if (luminance_range->max_luminance) {
3766 		caps->aux_min_input_signal = luminance_range->min_luminance;
3767 		caps->aux_max_input_signal = luminance_range->max_luminance;
3768 	} else {
3769 		caps->aux_min_input_signal = 0;
3770 		caps->aux_max_input_signal = 512;
3771 	}
3772 
3773 	min_input_signal_override = drm_get_panel_min_brightness_quirk(aconnector->drm_edid);
3774 	if (min_input_signal_override >= 0)
3775 		caps->min_input_signal = min_input_signal_override;
3776 }
3777 
3778 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3779 
3780 void amdgpu_dm_update_connector_after_detect(
3781 		struct amdgpu_dm_connector *aconnector)
3782 {
3783 	struct drm_connector *connector = &aconnector->base;
3784 	struct dc_sink *sink __free(sink_release) = NULL;
3785 	struct drm_device *dev = connector->dev;
3786 
3787 	/* MST handled by drm_mst framework */
3788 	if (aconnector->mst_mgr.mst_state == true)
3789 		return;
3790 
3791 	sink = aconnector->dc_link->local_sink;
3792 	if (sink)
3793 		dc_sink_retain(sink);
3794 
3795 	/*
3796 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3797 	 * the connector sink is set to either fake or physical sink depends on link status.
3798 	 * Skip if already done during boot.
3799 	 */
3800 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3801 			&& aconnector->dc_em_sink) {
3802 
3803 		/*
3804 		 * For S3 resume with headless use eml_sink to fake stream
3805 		 * because on resume connector->sink is set to NULL
3806 		 */
3807 		guard(mutex)(&dev->mode_config.mutex);
3808 
3809 		if (sink) {
3810 			if (aconnector->dc_sink) {
3811 				amdgpu_dm_update_freesync_caps(connector, NULL);
3812 				/*
3813 				 * retain and release below are used to
3814 				 * bump up refcount for sink because the link doesn't point
3815 				 * to it anymore after disconnect, so on next crtc to connector
3816 				 * reshuffle by UMD we will get into unwanted dc_sink release
3817 				 */
3818 				dc_sink_release(aconnector->dc_sink);
3819 			}
3820 			aconnector->dc_sink = sink;
3821 			dc_sink_retain(aconnector->dc_sink);
3822 			amdgpu_dm_update_freesync_caps(connector,
3823 					aconnector->drm_edid);
3824 		} else {
3825 			amdgpu_dm_update_freesync_caps(connector, NULL);
3826 			if (!aconnector->dc_sink) {
3827 				aconnector->dc_sink = aconnector->dc_em_sink;
3828 				dc_sink_retain(aconnector->dc_sink);
3829 			}
3830 		}
3831 
3832 		return;
3833 	}
3834 
3835 	/*
3836 	 * TODO: temporary guard to look for proper fix
3837 	 * if this sink is MST sink, we should not do anything
3838 	 */
3839 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
3840 		return;
3841 
3842 	if (aconnector->dc_sink == sink) {
3843 		/*
3844 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3845 		 * Do nothing!!
3846 		 */
3847 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
3848 				 aconnector->connector_id);
3849 		return;
3850 	}
3851 
3852 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3853 		    aconnector->connector_id, aconnector->dc_sink, sink);
3854 
3855 	guard(mutex)(&dev->mode_config.mutex);
3856 
3857 	/*
3858 	 * 1. Update status of the drm connector
3859 	 * 2. Send an event and let userspace tell us what to do
3860 	 */
3861 	if (sink) {
3862 		/*
3863 		 * TODO: check if we still need the S3 mode update workaround.
3864 		 * If yes, put it here.
3865 		 */
3866 		if (aconnector->dc_sink) {
3867 			amdgpu_dm_update_freesync_caps(connector, NULL);
3868 			dc_sink_release(aconnector->dc_sink);
3869 		}
3870 
3871 		aconnector->dc_sink = sink;
3872 		dc_sink_retain(aconnector->dc_sink);
3873 		if (sink->dc_edid.length == 0) {
3874 			aconnector->drm_edid = NULL;
3875 			hdmi_cec_unset_edid(aconnector);
3876 			if (aconnector->dc_link->aux_mode) {
3877 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3878 			}
3879 		} else {
3880 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
3881 
3882 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
3883 			drm_edid_connector_update(connector, aconnector->drm_edid);
3884 
3885 			hdmi_cec_set_edid(aconnector);
3886 			if (aconnector->dc_link->aux_mode)
3887 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
3888 						  connector->display_info.source_physical_address);
3889 		}
3890 
3891 		if (!aconnector->timing_requested) {
3892 			aconnector->timing_requested =
3893 				kzalloc(sizeof(struct dc_crtc_timing), GFP_KERNEL);
3894 			if (!aconnector->timing_requested)
3895 				drm_err(dev,
3896 					"failed to create aconnector->requested_timing\n");
3897 		}
3898 
3899 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid);
3900 		update_connector_ext_caps(aconnector);
3901 	} else {
3902 		hdmi_cec_unset_edid(aconnector);
3903 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3904 		amdgpu_dm_update_freesync_caps(connector, NULL);
3905 		aconnector->num_modes = 0;
3906 		dc_sink_release(aconnector->dc_sink);
3907 		aconnector->dc_sink = NULL;
3908 		drm_edid_free(aconnector->drm_edid);
3909 		aconnector->drm_edid = NULL;
3910 		kfree(aconnector->timing_requested);
3911 		aconnector->timing_requested = NULL;
3912 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3913 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3914 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3915 	}
3916 
3917 	update_subconnector_property(aconnector);
3918 }
3919 
3920 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3921 {
3922 	struct drm_connector *connector = &aconnector->base;
3923 	struct drm_device *dev = connector->dev;
3924 	enum dc_connection_type new_connection_type = dc_connection_none;
3925 	struct amdgpu_device *adev = drm_to_adev(dev);
3926 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3927 	struct dc *dc = aconnector->dc_link->ctx->dc;
3928 	bool ret = false;
3929 
3930 	if (adev->dm.disable_hpd_irq)
3931 		return;
3932 
3933 	/*
3934 	 * In case of failure or MST no need to update connector status or notify the OS
3935 	 * since (for MST case) MST does this in its own context.
3936 	 */
3937 	guard(mutex)(&aconnector->hpd_lock);
3938 
3939 	if (adev->dm.hdcp_workqueue) {
3940 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3941 		dm_con_state->update_hdcp = true;
3942 	}
3943 	if (aconnector->fake_enable)
3944 		aconnector->fake_enable = false;
3945 
3946 	aconnector->timing_changed = false;
3947 
3948 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3949 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3950 
3951 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
3952 		emulated_link_detect(aconnector->dc_link);
3953 
3954 		drm_modeset_lock_all(dev);
3955 		dm_restore_drm_connector_state(dev, connector);
3956 		drm_modeset_unlock_all(dev);
3957 
3958 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3959 			drm_kms_helper_connector_hotplug_event(connector);
3960 	} else {
3961 		scoped_guard(mutex, &adev->dm.dc_lock) {
3962 			dc_exit_ips_for_hw_access(dc);
3963 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3964 		}
3965 		if (ret) {
3966 			/* w/a delay for certain panels */
3967 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3968 			amdgpu_dm_update_connector_after_detect(aconnector);
3969 
3970 			drm_modeset_lock_all(dev);
3971 			dm_restore_drm_connector_state(dev, connector);
3972 			drm_modeset_unlock_all(dev);
3973 
3974 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3975 				drm_kms_helper_connector_hotplug_event(connector);
3976 		}
3977 	}
3978 }
3979 
3980 static void handle_hpd_irq(void *param)
3981 {
3982 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3983 
3984 	handle_hpd_irq_helper(aconnector);
3985 
3986 }
3987 
3988 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
3989 							union hpd_irq_data hpd_irq_data)
3990 {
3991 	struct hpd_rx_irq_offload_work *offload_work =
3992 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
3993 
3994 	if (!offload_work) {
3995 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
3996 		return;
3997 	}
3998 
3999 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4000 	offload_work->data = hpd_irq_data;
4001 	offload_work->offload_wq = offload_wq;
4002 	offload_work->adev = adev;
4003 
4004 	queue_work(offload_wq->wq, &offload_work->work);
4005 	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
4006 }
4007 
4008 static void handle_hpd_rx_irq(void *param)
4009 {
4010 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4011 	struct drm_connector *connector = &aconnector->base;
4012 	struct drm_device *dev = connector->dev;
4013 	struct dc_link *dc_link = aconnector->dc_link;
4014 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4015 	bool result = false;
4016 	enum dc_connection_type new_connection_type = dc_connection_none;
4017 	struct amdgpu_device *adev = drm_to_adev(dev);
4018 	union hpd_irq_data hpd_irq_data;
4019 	bool link_loss = false;
4020 	bool has_left_work = false;
4021 	int idx = dc_link->link_index;
4022 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4023 	struct dc *dc = aconnector->dc_link->ctx->dc;
4024 
4025 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4026 
4027 	if (adev->dm.disable_hpd_irq)
4028 		return;
4029 
4030 	/*
4031 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4032 	 * conflict, after implement i2c helper, this mutex should be
4033 	 * retired.
4034 	 */
4035 	mutex_lock(&aconnector->hpd_lock);
4036 
4037 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4038 						&link_loss, true, &has_left_work);
4039 
4040 	if (!has_left_work)
4041 		goto out;
4042 
4043 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4044 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4045 		goto out;
4046 	}
4047 
4048 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4049 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4050 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4051 			bool skip = false;
4052 
4053 			/*
4054 			 * DOWN_REP_MSG_RDY is also handled by polling method
4055 			 * mgr->cbs->poll_hpd_irq()
4056 			 */
4057 			spin_lock(&offload_wq->offload_lock);
4058 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4059 
4060 			if (!skip)
4061 				offload_wq->is_handling_mst_msg_rdy_event = true;
4062 
4063 			spin_unlock(&offload_wq->offload_lock);
4064 
4065 			if (!skip)
4066 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4067 
4068 			goto out;
4069 		}
4070 
4071 		if (link_loss) {
4072 			bool skip = false;
4073 
4074 			spin_lock(&offload_wq->offload_lock);
4075 			skip = offload_wq->is_handling_link_loss;
4076 
4077 			if (!skip)
4078 				offload_wq->is_handling_link_loss = true;
4079 
4080 			spin_unlock(&offload_wq->offload_lock);
4081 
4082 			if (!skip)
4083 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4084 
4085 			goto out;
4086 		}
4087 	}
4088 
4089 out:
4090 	if (result && !is_mst_root_connector) {
4091 		/* Downstream Port status changed. */
4092 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4093 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4094 
4095 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4096 			emulated_link_detect(dc_link);
4097 
4098 			if (aconnector->fake_enable)
4099 				aconnector->fake_enable = false;
4100 
4101 			amdgpu_dm_update_connector_after_detect(aconnector);
4102 
4103 
4104 			drm_modeset_lock_all(dev);
4105 			dm_restore_drm_connector_state(dev, connector);
4106 			drm_modeset_unlock_all(dev);
4107 
4108 			drm_kms_helper_connector_hotplug_event(connector);
4109 		} else {
4110 			bool ret = false;
4111 
4112 			mutex_lock(&adev->dm.dc_lock);
4113 			dc_exit_ips_for_hw_access(dc);
4114 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4115 			mutex_unlock(&adev->dm.dc_lock);
4116 
4117 			if (ret) {
4118 				if (aconnector->fake_enable)
4119 					aconnector->fake_enable = false;
4120 
4121 				amdgpu_dm_update_connector_after_detect(aconnector);
4122 
4123 				drm_modeset_lock_all(dev);
4124 				dm_restore_drm_connector_state(dev, connector);
4125 				drm_modeset_unlock_all(dev);
4126 
4127 				drm_kms_helper_connector_hotplug_event(connector);
4128 			}
4129 		}
4130 	}
4131 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4132 		if (adev->dm.hdcp_workqueue)
4133 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4134 	}
4135 
4136 	if (dc_link->type != dc_connection_mst_branch)
4137 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4138 
4139 	mutex_unlock(&aconnector->hpd_lock);
4140 }
4141 
4142 static int register_hpd_handlers(struct amdgpu_device *adev)
4143 {
4144 	struct drm_device *dev = adev_to_drm(adev);
4145 	struct drm_connector *connector;
4146 	struct amdgpu_dm_connector *aconnector;
4147 	const struct dc_link *dc_link;
4148 	struct dc_interrupt_params int_params = {0};
4149 
4150 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4151 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4152 
4153 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4154 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4155 			dmub_hpd_callback, true)) {
4156 			drm_err(adev_to_drm(adev), "amdgpu: fail to register dmub hpd callback");
4157 			return -EINVAL;
4158 		}
4159 
4160 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4161 			dmub_hpd_callback, true)) {
4162 			drm_err(adev_to_drm(adev), "amdgpu: fail to register dmub hpd callback");
4163 			return -EINVAL;
4164 		}
4165 
4166 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4167 			dmub_hpd_sense_callback, true)) {
4168 			drm_err(adev_to_drm(adev), "amdgpu: fail to register dmub hpd sense callback");
4169 			return -EINVAL;
4170 		}
4171 	}
4172 
4173 	list_for_each_entry(connector,
4174 			&dev->mode_config.connector_list, head)	{
4175 
4176 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4177 			continue;
4178 
4179 		aconnector = to_amdgpu_dm_connector(connector);
4180 		dc_link = aconnector->dc_link;
4181 
4182 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4183 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4184 			int_params.irq_source = dc_link->irq_source_hpd;
4185 
4186 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4187 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4188 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4189 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4190 				return -EINVAL;
4191 			}
4192 
4193 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4194 				handle_hpd_irq, (void *) aconnector))
4195 				return -ENOMEM;
4196 		}
4197 
4198 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4199 
4200 			/* Also register for DP short pulse (hpd_rx). */
4201 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4202 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4203 
4204 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4205 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4206 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4207 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4208 				return -EINVAL;
4209 			}
4210 
4211 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4212 				handle_hpd_rx_irq, (void *) aconnector))
4213 				return -ENOMEM;
4214 		}
4215 	}
4216 	return 0;
4217 }
4218 
4219 #if defined(CONFIG_DRM_AMD_DC_SI)
4220 /* Register IRQ sources and initialize IRQ callbacks */
4221 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
4222 {
4223 	struct dc *dc = adev->dm.dc;
4224 	struct common_irq_params *c_irq_params;
4225 	struct dc_interrupt_params int_params = {0};
4226 	int r;
4227 	int i;
4228 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4229 
4230 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4231 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4232 
4233 	/*
4234 	 * Actions of amdgpu_irq_add_id():
4235 	 * 1. Register a set() function with base driver.
4236 	 *    Base driver will call set() function to enable/disable an
4237 	 *    interrupt in DC hardware.
4238 	 * 2. Register amdgpu_dm_irq_handler().
4239 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4240 	 *    coming from DC hardware.
4241 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4242 	 *    for acknowledging and handling.
4243 	 */
4244 
4245 	/* Use VBLANK interrupt */
4246 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4247 		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
4248 		if (r) {
4249 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4250 			return r;
4251 		}
4252 
4253 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4254 		int_params.irq_source =
4255 			dc_interrupt_to_irq_source(dc, i + 1, 0);
4256 
4257 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4258 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4259 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4260 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4261 			return -EINVAL;
4262 		}
4263 
4264 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4265 
4266 		c_irq_params->adev = adev;
4267 		c_irq_params->irq_src = int_params.irq_source;
4268 
4269 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4270 			dm_crtc_high_irq, c_irq_params))
4271 			return -ENOMEM;
4272 	}
4273 
4274 	/* Use GRPH_PFLIP interrupt */
4275 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4276 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4277 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4278 		if (r) {
4279 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4280 			return r;
4281 		}
4282 
4283 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4284 		int_params.irq_source =
4285 			dc_interrupt_to_irq_source(dc, i, 0);
4286 
4287 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4288 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4289 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4290 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4291 			return -EINVAL;
4292 		}
4293 
4294 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4295 
4296 		c_irq_params->adev = adev;
4297 		c_irq_params->irq_src = int_params.irq_source;
4298 
4299 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4300 			dm_pflip_high_irq, c_irq_params))
4301 			return -ENOMEM;
4302 	}
4303 
4304 	/* HPD */
4305 	r = amdgpu_irq_add_id(adev, client_id,
4306 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4307 	if (r) {
4308 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4309 		return r;
4310 	}
4311 
4312 	r = register_hpd_handlers(adev);
4313 
4314 	return r;
4315 }
4316 #endif
4317 
4318 /* Register IRQ sources and initialize IRQ callbacks */
4319 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4320 {
4321 	struct dc *dc = adev->dm.dc;
4322 	struct common_irq_params *c_irq_params;
4323 	struct dc_interrupt_params int_params = {0};
4324 	int r;
4325 	int i;
4326 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4327 
4328 	if (adev->family >= AMDGPU_FAMILY_AI)
4329 		client_id = SOC15_IH_CLIENTID_DCE;
4330 
4331 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4332 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4333 
4334 	/*
4335 	 * Actions of amdgpu_irq_add_id():
4336 	 * 1. Register a set() function with base driver.
4337 	 *    Base driver will call set() function to enable/disable an
4338 	 *    interrupt in DC hardware.
4339 	 * 2. Register amdgpu_dm_irq_handler().
4340 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4341 	 *    coming from DC hardware.
4342 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4343 	 *    for acknowledging and handling.
4344 	 */
4345 
4346 	/* Use VBLANK interrupt */
4347 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
4348 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
4349 		if (r) {
4350 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4351 			return r;
4352 		}
4353 
4354 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4355 		int_params.irq_source =
4356 			dc_interrupt_to_irq_source(dc, i, 0);
4357 
4358 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4359 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4360 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4361 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4362 			return -EINVAL;
4363 		}
4364 
4365 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4366 
4367 		c_irq_params->adev = adev;
4368 		c_irq_params->irq_src = int_params.irq_source;
4369 
4370 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4371 			dm_crtc_high_irq, c_irq_params))
4372 			return -ENOMEM;
4373 	}
4374 
4375 	/* Use VUPDATE interrupt */
4376 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
4377 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
4378 		if (r) {
4379 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4380 			return r;
4381 		}
4382 
4383 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4384 		int_params.irq_source =
4385 			dc_interrupt_to_irq_source(dc, i, 0);
4386 
4387 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4388 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4389 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4390 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4391 			return -EINVAL;
4392 		}
4393 
4394 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4395 
4396 		c_irq_params->adev = adev;
4397 		c_irq_params->irq_src = int_params.irq_source;
4398 
4399 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4400 			dm_vupdate_high_irq, c_irq_params))
4401 			return -ENOMEM;
4402 	}
4403 
4404 	/* Use GRPH_PFLIP interrupt */
4405 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4406 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4407 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4408 		if (r) {
4409 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4410 			return r;
4411 		}
4412 
4413 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4414 		int_params.irq_source =
4415 			dc_interrupt_to_irq_source(dc, i, 0);
4416 
4417 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4418 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4419 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4420 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4421 			return -EINVAL;
4422 		}
4423 
4424 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4425 
4426 		c_irq_params->adev = adev;
4427 		c_irq_params->irq_src = int_params.irq_source;
4428 
4429 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4430 			dm_pflip_high_irq, c_irq_params))
4431 			return -ENOMEM;
4432 	}
4433 
4434 	/* HPD */
4435 	r = amdgpu_irq_add_id(adev, client_id,
4436 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4437 	if (r) {
4438 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4439 		return r;
4440 	}
4441 
4442 	r = register_hpd_handlers(adev);
4443 
4444 	return r;
4445 }
4446 
4447 /* Register IRQ sources and initialize IRQ callbacks */
4448 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4449 {
4450 	struct dc *dc = adev->dm.dc;
4451 	struct common_irq_params *c_irq_params;
4452 	struct dc_interrupt_params int_params = {0};
4453 	int r;
4454 	int i;
4455 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4456 	static const unsigned int vrtl_int_srcid[] = {
4457 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4458 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4459 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4460 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4461 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4462 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4463 	};
4464 #endif
4465 
4466 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4467 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4468 
4469 	/*
4470 	 * Actions of amdgpu_irq_add_id():
4471 	 * 1. Register a set() function with base driver.
4472 	 *    Base driver will call set() function to enable/disable an
4473 	 *    interrupt in DC hardware.
4474 	 * 2. Register amdgpu_dm_irq_handler().
4475 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4476 	 *    coming from DC hardware.
4477 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4478 	 *    for acknowledging and handling.
4479 	 */
4480 
4481 	/* Use VSTARTUP interrupt */
4482 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4483 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4484 			i++) {
4485 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4486 
4487 		if (r) {
4488 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4489 			return r;
4490 		}
4491 
4492 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4493 		int_params.irq_source =
4494 			dc_interrupt_to_irq_source(dc, i, 0);
4495 
4496 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4497 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4498 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4499 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4500 			return -EINVAL;
4501 		}
4502 
4503 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4504 
4505 		c_irq_params->adev = adev;
4506 		c_irq_params->irq_src = int_params.irq_source;
4507 
4508 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4509 			dm_crtc_high_irq, c_irq_params))
4510 			return -ENOMEM;
4511 	}
4512 
4513 	/* Use otg vertical line interrupt */
4514 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4515 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4516 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4517 				vrtl_int_srcid[i], &adev->vline0_irq);
4518 
4519 		if (r) {
4520 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4521 			return r;
4522 		}
4523 
4524 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4525 		int_params.irq_source =
4526 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4527 
4528 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4529 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4530 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4531 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4532 			return -EINVAL;
4533 		}
4534 
4535 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4536 					- DC_IRQ_SOURCE_DC1_VLINE0];
4537 
4538 		c_irq_params->adev = adev;
4539 		c_irq_params->irq_src = int_params.irq_source;
4540 
4541 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4542 			dm_dcn_vertical_interrupt0_high_irq,
4543 			c_irq_params))
4544 			return -ENOMEM;
4545 	}
4546 #endif
4547 
4548 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4549 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4550 	 * to trigger at end of each vblank, regardless of state of the lock,
4551 	 * matching DCE behaviour.
4552 	 */
4553 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4554 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4555 	     i++) {
4556 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4557 
4558 		if (r) {
4559 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4560 			return r;
4561 		}
4562 
4563 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4564 		int_params.irq_source =
4565 			dc_interrupt_to_irq_source(dc, i, 0);
4566 
4567 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4568 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4569 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4570 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4571 			return -EINVAL;
4572 		}
4573 
4574 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4575 
4576 		c_irq_params->adev = adev;
4577 		c_irq_params->irq_src = int_params.irq_source;
4578 
4579 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4580 			dm_vupdate_high_irq, c_irq_params))
4581 			return -ENOMEM;
4582 	}
4583 
4584 	/* Use GRPH_PFLIP interrupt */
4585 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4586 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4587 			i++) {
4588 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4589 		if (r) {
4590 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4591 			return r;
4592 		}
4593 
4594 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4595 		int_params.irq_source =
4596 			dc_interrupt_to_irq_source(dc, i, 0);
4597 
4598 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4599 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4600 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4601 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4602 			return -EINVAL;
4603 		}
4604 
4605 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4606 
4607 		c_irq_params->adev = adev;
4608 		c_irq_params->irq_src = int_params.irq_source;
4609 
4610 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4611 			dm_pflip_high_irq, c_irq_params))
4612 			return -ENOMEM;
4613 	}
4614 
4615 	/* HPD */
4616 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4617 			&adev->hpd_irq);
4618 	if (r) {
4619 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4620 		return r;
4621 	}
4622 
4623 	r = register_hpd_handlers(adev);
4624 
4625 	return r;
4626 }
4627 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4628 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4629 {
4630 	struct dc *dc = adev->dm.dc;
4631 	struct common_irq_params *c_irq_params;
4632 	struct dc_interrupt_params int_params = {0};
4633 	int r, i;
4634 
4635 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4636 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4637 
4638 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4639 			&adev->dmub_outbox_irq);
4640 	if (r) {
4641 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4642 		return r;
4643 	}
4644 
4645 	if (dc->ctx->dmub_srv) {
4646 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4647 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4648 		int_params.irq_source =
4649 		dc_interrupt_to_irq_source(dc, i, 0);
4650 
4651 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4652 
4653 		c_irq_params->adev = adev;
4654 		c_irq_params->irq_src = int_params.irq_source;
4655 
4656 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4657 			dm_dmub_outbox1_low_irq, c_irq_params))
4658 			return -ENOMEM;
4659 	}
4660 
4661 	return 0;
4662 }
4663 
4664 /*
4665  * Acquires the lock for the atomic state object and returns
4666  * the new atomic state.
4667  *
4668  * This should only be called during atomic check.
4669  */
4670 int dm_atomic_get_state(struct drm_atomic_state *state,
4671 			struct dm_atomic_state **dm_state)
4672 {
4673 	struct drm_device *dev = state->dev;
4674 	struct amdgpu_device *adev = drm_to_adev(dev);
4675 	struct amdgpu_display_manager *dm = &adev->dm;
4676 	struct drm_private_state *priv_state;
4677 
4678 	if (*dm_state)
4679 		return 0;
4680 
4681 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4682 	if (IS_ERR(priv_state))
4683 		return PTR_ERR(priv_state);
4684 
4685 	*dm_state = to_dm_atomic_state(priv_state);
4686 
4687 	return 0;
4688 }
4689 
4690 static struct dm_atomic_state *
4691 dm_atomic_get_new_state(struct drm_atomic_state *state)
4692 {
4693 	struct drm_device *dev = state->dev;
4694 	struct amdgpu_device *adev = drm_to_adev(dev);
4695 	struct amdgpu_display_manager *dm = &adev->dm;
4696 	struct drm_private_obj *obj;
4697 	struct drm_private_state *new_obj_state;
4698 	int i;
4699 
4700 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4701 		if (obj->funcs == dm->atomic_obj.funcs)
4702 			return to_dm_atomic_state(new_obj_state);
4703 	}
4704 
4705 	return NULL;
4706 }
4707 
4708 static struct drm_private_state *
4709 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4710 {
4711 	struct dm_atomic_state *old_state, *new_state;
4712 
4713 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
4714 	if (!new_state)
4715 		return NULL;
4716 
4717 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4718 
4719 	old_state = to_dm_atomic_state(obj->state);
4720 
4721 	if (old_state && old_state->context)
4722 		new_state->context = dc_state_create_copy(old_state->context);
4723 
4724 	if (!new_state->context) {
4725 		kfree(new_state);
4726 		return NULL;
4727 	}
4728 
4729 	return &new_state->base;
4730 }
4731 
4732 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4733 				    struct drm_private_state *state)
4734 {
4735 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4736 
4737 	if (dm_state && dm_state->context)
4738 		dc_state_release(dm_state->context);
4739 
4740 	kfree(dm_state);
4741 }
4742 
4743 static struct drm_private_state_funcs dm_atomic_state_funcs = {
4744 	.atomic_duplicate_state = dm_atomic_duplicate_state,
4745 	.atomic_destroy_state = dm_atomic_destroy_state,
4746 };
4747 
4748 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
4749 {
4750 	struct dm_atomic_state *state;
4751 	int r;
4752 
4753 	adev->mode_info.mode_config_initialized = true;
4754 
4755 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4756 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4757 
4758 	adev_to_drm(adev)->mode_config.max_width = 16384;
4759 	adev_to_drm(adev)->mode_config.max_height = 16384;
4760 
4761 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4762 	if (adev->asic_type == CHIP_HAWAII)
4763 		/* disable prefer shadow for now due to hibernation issues */
4764 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4765 	else
4766 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4767 	/* indicates support for immediate flip */
4768 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4769 
4770 	state = kzalloc(sizeof(*state), GFP_KERNEL);
4771 	if (!state)
4772 		return -ENOMEM;
4773 
4774 	state->context = dc_state_create_current_copy(adev->dm.dc);
4775 	if (!state->context) {
4776 		kfree(state);
4777 		return -ENOMEM;
4778 	}
4779 
4780 	drm_atomic_private_obj_init(adev_to_drm(adev),
4781 				    &adev->dm.atomic_obj,
4782 				    &state->base,
4783 				    &dm_atomic_state_funcs);
4784 
4785 	r = amdgpu_display_modeset_create_props(adev);
4786 	if (r) {
4787 		dc_state_release(state->context);
4788 		kfree(state);
4789 		return r;
4790 	}
4791 
4792 #ifdef AMD_PRIVATE_COLOR
4793 	if (amdgpu_dm_create_color_properties(adev)) {
4794 		dc_state_release(state->context);
4795 		kfree(state);
4796 		return -ENOMEM;
4797 	}
4798 #endif
4799 
4800 	r = amdgpu_dm_audio_init(adev);
4801 	if (r) {
4802 		dc_state_release(state->context);
4803 		kfree(state);
4804 		return r;
4805 	}
4806 
4807 	return 0;
4808 }
4809 
4810 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4811 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4812 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
4813 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4814 
4815 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4816 					    int bl_idx)
4817 {
4818 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
4819 
4820 	if (caps->caps_valid)
4821 		return;
4822 
4823 #if defined(CONFIG_ACPI)
4824 	amdgpu_acpi_get_backlight_caps(caps);
4825 
4826 	/* validate the firmware value is sane */
4827 	if (caps->caps_valid) {
4828 		int spread = caps->max_input_signal - caps->min_input_signal;
4829 
4830 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4831 		    caps->min_input_signal < 0 ||
4832 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4833 		    spread < AMDGPU_DM_MIN_SPREAD) {
4834 			DRM_DEBUG_KMS("DM: Invalid backlight caps: min=%d, max=%d\n",
4835 				      caps->min_input_signal, caps->max_input_signal);
4836 			caps->caps_valid = false;
4837 		}
4838 	}
4839 
4840 	if (!caps->caps_valid) {
4841 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4842 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4843 		caps->caps_valid = true;
4844 	}
4845 #else
4846 	if (caps->aux_support)
4847 		return;
4848 
4849 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4850 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4851 	caps->caps_valid = true;
4852 #endif
4853 }
4854 
4855 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
4856 				unsigned int *min, unsigned int *max)
4857 {
4858 	if (!caps)
4859 		return 0;
4860 
4861 	if (caps->aux_support) {
4862 		// Firmware limits are in nits, DC API wants millinits.
4863 		*max = 1000 * caps->aux_max_input_signal;
4864 		*min = 1000 * caps->aux_min_input_signal;
4865 	} else {
4866 		// Firmware limits are 8-bit, PWM control is 16-bit.
4867 		*max = 0x101 * caps->max_input_signal;
4868 		*min = 0x101 * caps->min_input_signal;
4869 	}
4870 	return 1;
4871 }
4872 
4873 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
4874 				      uint32_t *brightness)
4875 {
4876 	u8 prev_signal = 0, prev_lum = 0;
4877 	int i = 0;
4878 
4879 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
4880 		return;
4881 
4882 	if (!caps->data_points)
4883 		return;
4884 
4885 	/* choose start to run less interpolation steps */
4886 	if (caps->luminance_data[caps->data_points/2].input_signal > *brightness)
4887 		i = caps->data_points/2;
4888 	do {
4889 		u8 signal = caps->luminance_data[i].input_signal;
4890 		u8 lum = caps->luminance_data[i].luminance;
4891 
4892 		/*
4893 		 * brightness == signal: luminance is percent numerator
4894 		 * brightness < signal: interpolate between previous and current luminance numerator
4895 		 * brightness > signal: find next data point
4896 		 */
4897 		if (*brightness > signal) {
4898 			prev_signal = signal;
4899 			prev_lum = lum;
4900 			i++;
4901 			continue;
4902 		}
4903 		if (*brightness < signal)
4904 			lum = prev_lum + DIV_ROUND_CLOSEST((lum - prev_lum) *
4905 							   (*brightness - prev_signal),
4906 							   signal - prev_signal);
4907 		*brightness = DIV_ROUND_CLOSEST(lum * *brightness, 101);
4908 		return;
4909 	} while (i < caps->data_points);
4910 }
4911 
4912 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
4913 					uint32_t brightness)
4914 {
4915 	unsigned int min, max;
4916 
4917 	if (!get_brightness_range(caps, &min, &max))
4918 		return brightness;
4919 
4920 	convert_custom_brightness(caps, &brightness);
4921 
4922 	// Rescale 0..255 to min..max
4923 	return min + DIV_ROUND_CLOSEST((max - min) * brightness,
4924 				       AMDGPU_MAX_BL_LEVEL);
4925 }
4926 
4927 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
4928 				      uint32_t brightness)
4929 {
4930 	unsigned int min, max;
4931 
4932 	if (!get_brightness_range(caps, &min, &max))
4933 		return brightness;
4934 
4935 	if (brightness < min)
4936 		return 0;
4937 	// Rescale min..max to 0..255
4938 	return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
4939 				 max - min);
4940 }
4941 
4942 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
4943 					 int bl_idx,
4944 					 u32 user_brightness)
4945 {
4946 	struct amdgpu_dm_backlight_caps *caps;
4947 	struct dc_link *link;
4948 	u32 brightness;
4949 	bool rc, reallow_idle = false;
4950 
4951 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4952 	caps = &dm->backlight_caps[bl_idx];
4953 
4954 	dm->brightness[bl_idx] = user_brightness;
4955 	/* update scratch register */
4956 	if (bl_idx == 0)
4957 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
4958 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
4959 	link = (struct dc_link *)dm->backlight_link[bl_idx];
4960 
4961 	/* Change brightness based on AUX property */
4962 	mutex_lock(&dm->dc_lock);
4963 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
4964 		dc_allow_idle_optimizations(dm->dc, false);
4965 		reallow_idle = true;
4966 	}
4967 
4968 	if (caps->aux_support) {
4969 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
4970 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
4971 		if (!rc)
4972 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
4973 	} else {
4974 		struct set_backlight_level_params backlight_level_params = { 0 };
4975 
4976 		backlight_level_params.backlight_pwm_u16_16 = brightness;
4977 		backlight_level_params.transition_time_in_ms = 0;
4978 
4979 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
4980 		if (!rc)
4981 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
4982 	}
4983 
4984 	if (dm->dc->caps.ips_support && reallow_idle)
4985 		dc_allow_idle_optimizations(dm->dc, true);
4986 
4987 	mutex_unlock(&dm->dc_lock);
4988 
4989 	if (rc)
4990 		dm->actual_brightness[bl_idx] = user_brightness;
4991 }
4992 
4993 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
4994 {
4995 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4996 	int i;
4997 
4998 	for (i = 0; i < dm->num_of_edps; i++) {
4999 		if (bd == dm->backlight_dev[i])
5000 			break;
5001 	}
5002 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5003 		i = 0;
5004 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5005 
5006 	return 0;
5007 }
5008 
5009 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5010 					 int bl_idx)
5011 {
5012 	int ret;
5013 	struct amdgpu_dm_backlight_caps caps;
5014 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5015 
5016 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5017 	caps = dm->backlight_caps[bl_idx];
5018 
5019 	if (caps.aux_support) {
5020 		u32 avg, peak;
5021 		bool rc;
5022 
5023 		rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
5024 		if (!rc)
5025 			return dm->brightness[bl_idx];
5026 		return convert_brightness_to_user(&caps, avg);
5027 	}
5028 
5029 	ret = dc_link_get_backlight_level(link);
5030 
5031 	if (ret == DC_ERROR_UNEXPECTED)
5032 		return dm->brightness[bl_idx];
5033 
5034 	return convert_brightness_to_user(&caps, ret);
5035 }
5036 
5037 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5038 {
5039 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5040 	int i;
5041 
5042 	for (i = 0; i < dm->num_of_edps; i++) {
5043 		if (bd == dm->backlight_dev[i])
5044 			break;
5045 	}
5046 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5047 		i = 0;
5048 	return amdgpu_dm_backlight_get_level(dm, i);
5049 }
5050 
5051 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5052 	.options = BL_CORE_SUSPENDRESUME,
5053 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5054 	.update_status	= amdgpu_dm_backlight_update_status,
5055 };
5056 
5057 static void
5058 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5059 {
5060 	struct drm_device *drm = aconnector->base.dev;
5061 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5062 	struct backlight_properties props = { 0 };
5063 	struct amdgpu_dm_backlight_caps caps = { 0 };
5064 	char bl_name[16];
5065 
5066 	if (aconnector->bl_idx == -1)
5067 		return;
5068 
5069 	if (!acpi_video_backlight_use_native()) {
5070 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5071 		/* Try registering an ACPI video backlight device instead. */
5072 		acpi_video_register_backlight();
5073 		return;
5074 	}
5075 
5076 	amdgpu_acpi_get_backlight_caps(&caps);
5077 	if (caps.caps_valid) {
5078 		if (power_supply_is_system_supplied() > 0)
5079 			props.brightness = caps.ac_level;
5080 		else
5081 			props.brightness = caps.dc_level;
5082 	} else
5083 		props.brightness = AMDGPU_MAX_BL_LEVEL;
5084 
5085 	if (caps.data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE))
5086 		drm_info(drm, "Using custom brightness curve\n");
5087 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
5088 	props.type = BACKLIGHT_RAW;
5089 
5090 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5091 		 drm->primary->index + aconnector->bl_idx);
5092 
5093 	dm->backlight_dev[aconnector->bl_idx] =
5094 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5095 					  &amdgpu_dm_backlight_ops, &props);
5096 	dm->brightness[aconnector->bl_idx] = props.brightness;
5097 
5098 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5099 		drm_err(drm, "DM: Backlight registration failed!\n");
5100 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5101 	} else
5102 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5103 }
5104 
5105 static int initialize_plane(struct amdgpu_display_manager *dm,
5106 			    struct amdgpu_mode_info *mode_info, int plane_id,
5107 			    enum drm_plane_type plane_type,
5108 			    const struct dc_plane_cap *plane_cap)
5109 {
5110 	struct drm_plane *plane;
5111 	unsigned long possible_crtcs;
5112 	int ret = 0;
5113 
5114 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
5115 	if (!plane) {
5116 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5117 		return -ENOMEM;
5118 	}
5119 	plane->type = plane_type;
5120 
5121 	/*
5122 	 * HACK: IGT tests expect that the primary plane for a CRTC
5123 	 * can only have one possible CRTC. Only expose support for
5124 	 * any CRTC if they're not going to be used as a primary plane
5125 	 * for a CRTC - like overlay or underlay planes.
5126 	 */
5127 	possible_crtcs = 1 << plane_id;
5128 	if (plane_id >= dm->dc->caps.max_streams)
5129 		possible_crtcs = 0xff;
5130 
5131 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5132 
5133 	if (ret) {
5134 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5135 		kfree(plane);
5136 		return ret;
5137 	}
5138 
5139 	if (mode_info)
5140 		mode_info->planes[plane_id] = plane;
5141 
5142 	return ret;
5143 }
5144 
5145 
5146 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5147 				   struct amdgpu_dm_connector *aconnector)
5148 {
5149 	struct dc_link *link = aconnector->dc_link;
5150 	int bl_idx = dm->num_of_edps;
5151 
5152 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5153 	    link->type == dc_connection_none)
5154 		return;
5155 
5156 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5157 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5158 		return;
5159 	}
5160 
5161 	aconnector->bl_idx = bl_idx;
5162 
5163 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5164 	dm->backlight_link[bl_idx] = link;
5165 	dm->num_of_edps++;
5166 
5167 	update_connector_ext_caps(aconnector);
5168 }
5169 
5170 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5171 
5172 /*
5173  * In this architecture, the association
5174  * connector -> encoder -> crtc
5175  * id not really requried. The crtc and connector will hold the
5176  * display_index as an abstraction to use with DAL component
5177  *
5178  * Returns 0 on success
5179  */
5180 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5181 {
5182 	struct amdgpu_display_manager *dm = &adev->dm;
5183 	s32 i;
5184 	struct amdgpu_dm_connector *aconnector = NULL;
5185 	struct amdgpu_encoder *aencoder = NULL;
5186 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5187 	u32 link_cnt;
5188 	s32 primary_planes;
5189 	enum dc_connection_type new_connection_type = dc_connection_none;
5190 	const struct dc_plane_cap *plane;
5191 	bool psr_feature_enabled = false;
5192 	bool replay_feature_enabled = false;
5193 	int max_overlay = dm->dc->caps.max_slave_planes;
5194 
5195 	dm->display_indexes_num = dm->dc->caps.max_streams;
5196 	/* Update the actual used number of crtc */
5197 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5198 
5199 	amdgpu_dm_set_irq_funcs(adev);
5200 
5201 	link_cnt = dm->dc->caps.max_links;
5202 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5203 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5204 		return -EINVAL;
5205 	}
5206 
5207 	/* There is one primary plane per CRTC */
5208 	primary_planes = dm->dc->caps.max_streams;
5209 	if (primary_planes > AMDGPU_MAX_PLANES) {
5210 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5211 		return -EINVAL;
5212 	}
5213 
5214 	/*
5215 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5216 	 * Order is reversed to match iteration order in atomic check.
5217 	 */
5218 	for (i = (primary_planes - 1); i >= 0; i--) {
5219 		plane = &dm->dc->caps.planes[i];
5220 
5221 		if (initialize_plane(dm, mode_info, i,
5222 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5223 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5224 			goto fail;
5225 		}
5226 	}
5227 
5228 	/*
5229 	 * Initialize overlay planes, index starting after primary planes.
5230 	 * These planes have a higher DRM index than the primary planes since
5231 	 * they should be considered as having a higher z-order.
5232 	 * Order is reversed to match iteration order in atomic check.
5233 	 *
5234 	 * Only support DCN for now, and only expose one so we don't encourage
5235 	 * userspace to use up all the pipes.
5236 	 */
5237 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5238 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5239 
5240 		/* Do not create overlay if MPO disabled */
5241 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5242 			break;
5243 
5244 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5245 			continue;
5246 
5247 		if (!plane->pixel_format_support.argb8888)
5248 			continue;
5249 
5250 		if (max_overlay-- == 0)
5251 			break;
5252 
5253 		if (initialize_plane(dm, NULL, primary_planes + i,
5254 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5255 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5256 			goto fail;
5257 		}
5258 	}
5259 
5260 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5261 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5262 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5263 			goto fail;
5264 		}
5265 
5266 	/* Use Outbox interrupt */
5267 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5268 	case IP_VERSION(3, 0, 0):
5269 	case IP_VERSION(3, 1, 2):
5270 	case IP_VERSION(3, 1, 3):
5271 	case IP_VERSION(3, 1, 4):
5272 	case IP_VERSION(3, 1, 5):
5273 	case IP_VERSION(3, 1, 6):
5274 	case IP_VERSION(3, 2, 0):
5275 	case IP_VERSION(3, 2, 1):
5276 	case IP_VERSION(2, 1, 0):
5277 	case IP_VERSION(3, 5, 0):
5278 	case IP_VERSION(3, 5, 1):
5279 	case IP_VERSION(3, 6, 0):
5280 	case IP_VERSION(4, 0, 1):
5281 		if (register_outbox_irq_handlers(dm->adev)) {
5282 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5283 			goto fail;
5284 		}
5285 		break;
5286 	default:
5287 		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
5288 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5289 	}
5290 
5291 	/* Determine whether to enable PSR support by default. */
5292 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5293 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5294 		case IP_VERSION(3, 1, 2):
5295 		case IP_VERSION(3, 1, 3):
5296 		case IP_VERSION(3, 1, 4):
5297 		case IP_VERSION(3, 1, 5):
5298 		case IP_VERSION(3, 1, 6):
5299 		case IP_VERSION(3, 2, 0):
5300 		case IP_VERSION(3, 2, 1):
5301 		case IP_VERSION(3, 5, 0):
5302 		case IP_VERSION(3, 5, 1):
5303 		case IP_VERSION(3, 6, 0):
5304 		case IP_VERSION(4, 0, 1):
5305 			psr_feature_enabled = true;
5306 			break;
5307 		default:
5308 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5309 			break;
5310 		}
5311 	}
5312 
5313 	/* Determine whether to enable Replay support by default. */
5314 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5315 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5316 		case IP_VERSION(3, 1, 4):
5317 		case IP_VERSION(3, 2, 0):
5318 		case IP_VERSION(3, 2, 1):
5319 		case IP_VERSION(3, 5, 0):
5320 		case IP_VERSION(3, 5, 1):
5321 		case IP_VERSION(3, 6, 0):
5322 			replay_feature_enabled = true;
5323 			break;
5324 
5325 		default:
5326 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5327 			break;
5328 		}
5329 	}
5330 
5331 	if (link_cnt > MAX_LINKS) {
5332 		drm_err(adev_to_drm(adev),
5333 			"KMS: Cannot support more than %d display indexes\n",
5334 				MAX_LINKS);
5335 		goto fail;
5336 	}
5337 
5338 	/* loops over all connectors on the board */
5339 	for (i = 0; i < link_cnt; i++) {
5340 		struct dc_link *link = NULL;
5341 
5342 		link = dc_get_link_at_index(dm->dc, i);
5343 
5344 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5345 			struct amdgpu_dm_wb_connector *wbcon = kzalloc(sizeof(*wbcon), GFP_KERNEL);
5346 
5347 			if (!wbcon) {
5348 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5349 				continue;
5350 			}
5351 
5352 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5353 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5354 				kfree(wbcon);
5355 				continue;
5356 			}
5357 
5358 			link->psr_settings.psr_feature_enabled = false;
5359 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5360 
5361 			continue;
5362 		}
5363 
5364 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
5365 		if (!aconnector)
5366 			goto fail;
5367 
5368 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
5369 		if (!aencoder)
5370 			goto fail;
5371 
5372 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5373 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5374 			goto fail;
5375 		}
5376 
5377 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5378 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5379 			goto fail;
5380 		}
5381 
5382 		if (dm->hpd_rx_offload_wq)
5383 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5384 				aconnector;
5385 
5386 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5387 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5388 
5389 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5390 			emulated_link_detect(link);
5391 			amdgpu_dm_update_connector_after_detect(aconnector);
5392 		} else {
5393 			bool ret = false;
5394 
5395 			mutex_lock(&dm->dc_lock);
5396 			dc_exit_ips_for_hw_access(dm->dc);
5397 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5398 			mutex_unlock(&dm->dc_lock);
5399 
5400 			if (ret) {
5401 				amdgpu_dm_update_connector_after_detect(aconnector);
5402 				setup_backlight_device(dm, aconnector);
5403 
5404 				/* Disable PSR if Replay can be enabled */
5405 				if (replay_feature_enabled)
5406 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5407 						psr_feature_enabled = false;
5408 
5409 				if (psr_feature_enabled) {
5410 					amdgpu_dm_set_psr_caps(link);
5411 					drm_info(adev_to_drm(adev), "PSR support %d, DC PSR ver %d, sink PSR ver %d DPCD caps 0x%x su_y_granularity %d\n",
5412 						 link->psr_settings.psr_feature_enabled,
5413 						 link->psr_settings.psr_version,
5414 						 link->dpcd_caps.psr_info.psr_version,
5415 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5416 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5417 				}
5418 			}
5419 		}
5420 		amdgpu_set_panel_orientation(&aconnector->base);
5421 	}
5422 
5423 	/* Software is initialized. Now we can register interrupt handlers. */
5424 	switch (adev->asic_type) {
5425 #if defined(CONFIG_DRM_AMD_DC_SI)
5426 	case CHIP_TAHITI:
5427 	case CHIP_PITCAIRN:
5428 	case CHIP_VERDE:
5429 	case CHIP_OLAND:
5430 		if (dce60_register_irq_handlers(dm->adev)) {
5431 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5432 			goto fail;
5433 		}
5434 		break;
5435 #endif
5436 	case CHIP_BONAIRE:
5437 	case CHIP_HAWAII:
5438 	case CHIP_KAVERI:
5439 	case CHIP_KABINI:
5440 	case CHIP_MULLINS:
5441 	case CHIP_TONGA:
5442 	case CHIP_FIJI:
5443 	case CHIP_CARRIZO:
5444 	case CHIP_STONEY:
5445 	case CHIP_POLARIS11:
5446 	case CHIP_POLARIS10:
5447 	case CHIP_POLARIS12:
5448 	case CHIP_VEGAM:
5449 	case CHIP_VEGA10:
5450 	case CHIP_VEGA12:
5451 	case CHIP_VEGA20:
5452 		if (dce110_register_irq_handlers(dm->adev)) {
5453 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5454 			goto fail;
5455 		}
5456 		break;
5457 	default:
5458 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5459 		case IP_VERSION(1, 0, 0):
5460 		case IP_VERSION(1, 0, 1):
5461 		case IP_VERSION(2, 0, 2):
5462 		case IP_VERSION(2, 0, 3):
5463 		case IP_VERSION(2, 0, 0):
5464 		case IP_VERSION(2, 1, 0):
5465 		case IP_VERSION(3, 0, 0):
5466 		case IP_VERSION(3, 0, 2):
5467 		case IP_VERSION(3, 0, 3):
5468 		case IP_VERSION(3, 0, 1):
5469 		case IP_VERSION(3, 1, 2):
5470 		case IP_VERSION(3, 1, 3):
5471 		case IP_VERSION(3, 1, 4):
5472 		case IP_VERSION(3, 1, 5):
5473 		case IP_VERSION(3, 1, 6):
5474 		case IP_VERSION(3, 2, 0):
5475 		case IP_VERSION(3, 2, 1):
5476 		case IP_VERSION(3, 5, 0):
5477 		case IP_VERSION(3, 5, 1):
5478 		case IP_VERSION(3, 6, 0):
5479 		case IP_VERSION(4, 0, 1):
5480 			if (dcn10_register_irq_handlers(dm->adev)) {
5481 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5482 				goto fail;
5483 			}
5484 			break;
5485 		default:
5486 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5487 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5488 			goto fail;
5489 		}
5490 		break;
5491 	}
5492 
5493 	return 0;
5494 fail:
5495 	kfree(aencoder);
5496 	kfree(aconnector);
5497 
5498 	return -EINVAL;
5499 }
5500 
5501 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5502 {
5503 	drm_atomic_private_obj_fini(&dm->atomic_obj);
5504 }
5505 
5506 /******************************************************************************
5507  * amdgpu_display_funcs functions
5508  *****************************************************************************/
5509 
5510 /*
5511  * dm_bandwidth_update - program display watermarks
5512  *
5513  * @adev: amdgpu_device pointer
5514  *
5515  * Calculate and program the display watermarks and line buffer allocation.
5516  */
5517 static void dm_bandwidth_update(struct amdgpu_device *adev)
5518 {
5519 	/* TODO: implement later */
5520 }
5521 
5522 static const struct amdgpu_display_funcs dm_display_funcs = {
5523 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5524 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5525 	.backlight_set_level = NULL, /* never called for DC */
5526 	.backlight_get_level = NULL, /* never called for DC */
5527 	.hpd_sense = NULL,/* called unconditionally */
5528 	.hpd_set_polarity = NULL, /* called unconditionally */
5529 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5530 	.page_flip_get_scanoutpos =
5531 		dm_crtc_get_scanoutpos,/* called unconditionally */
5532 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5533 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5534 };
5535 
5536 #if defined(CONFIG_DEBUG_KERNEL_DC)
5537 
5538 static ssize_t s3_debug_store(struct device *device,
5539 			      struct device_attribute *attr,
5540 			      const char *buf,
5541 			      size_t count)
5542 {
5543 	int ret;
5544 	int s3_state;
5545 	struct drm_device *drm_dev = dev_get_drvdata(device);
5546 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5547 	struct amdgpu_ip_block *ip_block;
5548 
5549 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5550 	if (!ip_block)
5551 		return -EINVAL;
5552 
5553 	ret = kstrtoint(buf, 0, &s3_state);
5554 
5555 	if (ret == 0) {
5556 		if (s3_state) {
5557 			dm_resume(ip_block);
5558 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5559 		} else
5560 			dm_suspend(ip_block);
5561 	}
5562 
5563 	return ret == 0 ? count : 0;
5564 }
5565 
5566 DEVICE_ATTR_WO(s3_debug);
5567 
5568 #endif
5569 
5570 static int dm_init_microcode(struct amdgpu_device *adev)
5571 {
5572 	char *fw_name_dmub;
5573 	int r;
5574 
5575 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5576 	case IP_VERSION(2, 1, 0):
5577 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5578 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5579 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5580 		break;
5581 	case IP_VERSION(3, 0, 0):
5582 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5583 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5584 		else
5585 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5586 		break;
5587 	case IP_VERSION(3, 0, 1):
5588 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5589 		break;
5590 	case IP_VERSION(3, 0, 2):
5591 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5592 		break;
5593 	case IP_VERSION(3, 0, 3):
5594 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5595 		break;
5596 	case IP_VERSION(3, 1, 2):
5597 	case IP_VERSION(3, 1, 3):
5598 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5599 		break;
5600 	case IP_VERSION(3, 1, 4):
5601 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5602 		break;
5603 	case IP_VERSION(3, 1, 5):
5604 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5605 		break;
5606 	case IP_VERSION(3, 1, 6):
5607 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5608 		break;
5609 	case IP_VERSION(3, 2, 0):
5610 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5611 		break;
5612 	case IP_VERSION(3, 2, 1):
5613 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5614 		break;
5615 	case IP_VERSION(3, 5, 0):
5616 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5617 		break;
5618 	case IP_VERSION(3, 5, 1):
5619 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5620 		break;
5621 	case IP_VERSION(3, 6, 0):
5622 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5623 		break;
5624 	case IP_VERSION(4, 0, 1):
5625 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5626 		break;
5627 	default:
5628 		/* ASIC doesn't support DMUB. */
5629 		return 0;
5630 	}
5631 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5632 				 "%s", fw_name_dmub);
5633 	return r;
5634 }
5635 
5636 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5637 {
5638 	struct amdgpu_device *adev = ip_block->adev;
5639 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5640 	struct atom_context *ctx = mode_info->atom_context;
5641 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5642 	u16 data_offset;
5643 
5644 	/* if there is no object header, skip DM */
5645 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5646 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5647 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5648 		return -ENOENT;
5649 	}
5650 
5651 	switch (adev->asic_type) {
5652 #if defined(CONFIG_DRM_AMD_DC_SI)
5653 	case CHIP_TAHITI:
5654 	case CHIP_PITCAIRN:
5655 	case CHIP_VERDE:
5656 		adev->mode_info.num_crtc = 6;
5657 		adev->mode_info.num_hpd = 6;
5658 		adev->mode_info.num_dig = 6;
5659 		break;
5660 	case CHIP_OLAND:
5661 		adev->mode_info.num_crtc = 2;
5662 		adev->mode_info.num_hpd = 2;
5663 		adev->mode_info.num_dig = 2;
5664 		break;
5665 #endif
5666 	case CHIP_BONAIRE:
5667 	case CHIP_HAWAII:
5668 		adev->mode_info.num_crtc = 6;
5669 		adev->mode_info.num_hpd = 6;
5670 		adev->mode_info.num_dig = 6;
5671 		break;
5672 	case CHIP_KAVERI:
5673 		adev->mode_info.num_crtc = 4;
5674 		adev->mode_info.num_hpd = 6;
5675 		adev->mode_info.num_dig = 7;
5676 		break;
5677 	case CHIP_KABINI:
5678 	case CHIP_MULLINS:
5679 		adev->mode_info.num_crtc = 2;
5680 		adev->mode_info.num_hpd = 6;
5681 		adev->mode_info.num_dig = 6;
5682 		break;
5683 	case CHIP_FIJI:
5684 	case CHIP_TONGA:
5685 		adev->mode_info.num_crtc = 6;
5686 		adev->mode_info.num_hpd = 6;
5687 		adev->mode_info.num_dig = 7;
5688 		break;
5689 	case CHIP_CARRIZO:
5690 		adev->mode_info.num_crtc = 3;
5691 		adev->mode_info.num_hpd = 6;
5692 		adev->mode_info.num_dig = 9;
5693 		break;
5694 	case CHIP_STONEY:
5695 		adev->mode_info.num_crtc = 2;
5696 		adev->mode_info.num_hpd = 6;
5697 		adev->mode_info.num_dig = 9;
5698 		break;
5699 	case CHIP_POLARIS11:
5700 	case CHIP_POLARIS12:
5701 		adev->mode_info.num_crtc = 5;
5702 		adev->mode_info.num_hpd = 5;
5703 		adev->mode_info.num_dig = 5;
5704 		break;
5705 	case CHIP_POLARIS10:
5706 	case CHIP_VEGAM:
5707 		adev->mode_info.num_crtc = 6;
5708 		adev->mode_info.num_hpd = 6;
5709 		adev->mode_info.num_dig = 6;
5710 		break;
5711 	case CHIP_VEGA10:
5712 	case CHIP_VEGA12:
5713 	case CHIP_VEGA20:
5714 		adev->mode_info.num_crtc = 6;
5715 		adev->mode_info.num_hpd = 6;
5716 		adev->mode_info.num_dig = 6;
5717 		break;
5718 	default:
5719 
5720 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5721 		case IP_VERSION(2, 0, 2):
5722 		case IP_VERSION(3, 0, 0):
5723 			adev->mode_info.num_crtc = 6;
5724 			adev->mode_info.num_hpd = 6;
5725 			adev->mode_info.num_dig = 6;
5726 			break;
5727 		case IP_VERSION(2, 0, 0):
5728 		case IP_VERSION(3, 0, 2):
5729 			adev->mode_info.num_crtc = 5;
5730 			adev->mode_info.num_hpd = 5;
5731 			adev->mode_info.num_dig = 5;
5732 			break;
5733 		case IP_VERSION(2, 0, 3):
5734 		case IP_VERSION(3, 0, 3):
5735 			adev->mode_info.num_crtc = 2;
5736 			adev->mode_info.num_hpd = 2;
5737 			adev->mode_info.num_dig = 2;
5738 			break;
5739 		case IP_VERSION(1, 0, 0):
5740 		case IP_VERSION(1, 0, 1):
5741 		case IP_VERSION(3, 0, 1):
5742 		case IP_VERSION(2, 1, 0):
5743 		case IP_VERSION(3, 1, 2):
5744 		case IP_VERSION(3, 1, 3):
5745 		case IP_VERSION(3, 1, 4):
5746 		case IP_VERSION(3, 1, 5):
5747 		case IP_VERSION(3, 1, 6):
5748 		case IP_VERSION(3, 2, 0):
5749 		case IP_VERSION(3, 2, 1):
5750 		case IP_VERSION(3, 5, 0):
5751 		case IP_VERSION(3, 5, 1):
5752 		case IP_VERSION(3, 6, 0):
5753 		case IP_VERSION(4, 0, 1):
5754 			adev->mode_info.num_crtc = 4;
5755 			adev->mode_info.num_hpd = 4;
5756 			adev->mode_info.num_dig = 4;
5757 			break;
5758 		default:
5759 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
5760 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5761 			return -EINVAL;
5762 		}
5763 		break;
5764 	}
5765 
5766 	if (adev->mode_info.funcs == NULL)
5767 		adev->mode_info.funcs = &dm_display_funcs;
5768 
5769 	/*
5770 	 * Note: Do NOT change adev->audio_endpt_rreg and
5771 	 * adev->audio_endpt_wreg because they are initialised in
5772 	 * amdgpu_device_init()
5773 	 */
5774 #if defined(CONFIG_DEBUG_KERNEL_DC)
5775 	device_create_file(
5776 		adev_to_drm(adev)->dev,
5777 		&dev_attr_s3_debug);
5778 #endif
5779 	adev->dc_enabled = true;
5780 
5781 	return dm_init_microcode(adev);
5782 }
5783 
5784 static bool modereset_required(struct drm_crtc_state *crtc_state)
5785 {
5786 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
5787 }
5788 
5789 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
5790 {
5791 	drm_encoder_cleanup(encoder);
5792 	kfree(encoder);
5793 }
5794 
5795 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
5796 	.destroy = amdgpu_dm_encoder_destroy,
5797 };
5798 
5799 static int
5800 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
5801 			    const enum surface_pixel_format format,
5802 			    enum dc_color_space *color_space)
5803 {
5804 	bool full_range;
5805 
5806 	*color_space = COLOR_SPACE_SRGB;
5807 
5808 	/* DRM color properties only affect non-RGB formats. */
5809 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
5810 		return 0;
5811 
5812 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
5813 
5814 	switch (plane_state->color_encoding) {
5815 	case DRM_COLOR_YCBCR_BT601:
5816 		if (full_range)
5817 			*color_space = COLOR_SPACE_YCBCR601;
5818 		else
5819 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
5820 		break;
5821 
5822 	case DRM_COLOR_YCBCR_BT709:
5823 		if (full_range)
5824 			*color_space = COLOR_SPACE_YCBCR709;
5825 		else
5826 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
5827 		break;
5828 
5829 	case DRM_COLOR_YCBCR_BT2020:
5830 		if (full_range)
5831 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
5832 		else
5833 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
5834 		break;
5835 
5836 	default:
5837 		return -EINVAL;
5838 	}
5839 
5840 	return 0;
5841 }
5842 
5843 static int
5844 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
5845 			    const struct drm_plane_state *plane_state,
5846 			    const u64 tiling_flags,
5847 			    struct dc_plane_info *plane_info,
5848 			    struct dc_plane_address *address,
5849 			    bool tmz_surface)
5850 {
5851 	const struct drm_framebuffer *fb = plane_state->fb;
5852 	const struct amdgpu_framebuffer *afb =
5853 		to_amdgpu_framebuffer(plane_state->fb);
5854 	int ret;
5855 
5856 	memset(plane_info, 0, sizeof(*plane_info));
5857 
5858 	switch (fb->format->format) {
5859 	case DRM_FORMAT_C8:
5860 		plane_info->format =
5861 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
5862 		break;
5863 	case DRM_FORMAT_RGB565:
5864 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
5865 		break;
5866 	case DRM_FORMAT_XRGB8888:
5867 	case DRM_FORMAT_ARGB8888:
5868 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
5869 		break;
5870 	case DRM_FORMAT_XRGB2101010:
5871 	case DRM_FORMAT_ARGB2101010:
5872 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
5873 		break;
5874 	case DRM_FORMAT_XBGR2101010:
5875 	case DRM_FORMAT_ABGR2101010:
5876 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
5877 		break;
5878 	case DRM_FORMAT_XBGR8888:
5879 	case DRM_FORMAT_ABGR8888:
5880 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
5881 		break;
5882 	case DRM_FORMAT_NV21:
5883 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
5884 		break;
5885 	case DRM_FORMAT_NV12:
5886 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
5887 		break;
5888 	case DRM_FORMAT_P010:
5889 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
5890 		break;
5891 	case DRM_FORMAT_XRGB16161616F:
5892 	case DRM_FORMAT_ARGB16161616F:
5893 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
5894 		break;
5895 	case DRM_FORMAT_XBGR16161616F:
5896 	case DRM_FORMAT_ABGR16161616F:
5897 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
5898 		break;
5899 	case DRM_FORMAT_XRGB16161616:
5900 	case DRM_FORMAT_ARGB16161616:
5901 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
5902 		break;
5903 	case DRM_FORMAT_XBGR16161616:
5904 	case DRM_FORMAT_ABGR16161616:
5905 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
5906 		break;
5907 	default:
5908 		drm_err(adev_to_drm(adev),
5909 			"Unsupported screen format %p4cc\n",
5910 			&fb->format->format);
5911 		return -EINVAL;
5912 	}
5913 
5914 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
5915 	case DRM_MODE_ROTATE_0:
5916 		plane_info->rotation = ROTATION_ANGLE_0;
5917 		break;
5918 	case DRM_MODE_ROTATE_90:
5919 		plane_info->rotation = ROTATION_ANGLE_90;
5920 		break;
5921 	case DRM_MODE_ROTATE_180:
5922 		plane_info->rotation = ROTATION_ANGLE_180;
5923 		break;
5924 	case DRM_MODE_ROTATE_270:
5925 		plane_info->rotation = ROTATION_ANGLE_270;
5926 		break;
5927 	default:
5928 		plane_info->rotation = ROTATION_ANGLE_0;
5929 		break;
5930 	}
5931 
5932 
5933 	plane_info->visible = true;
5934 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
5935 
5936 	plane_info->layer_index = plane_state->normalized_zpos;
5937 
5938 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
5939 					  &plane_info->color_space);
5940 	if (ret)
5941 		return ret;
5942 
5943 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
5944 					   plane_info->rotation, tiling_flags,
5945 					   &plane_info->tiling_info,
5946 					   &plane_info->plane_size,
5947 					   &plane_info->dcc, address,
5948 					   tmz_surface);
5949 	if (ret)
5950 		return ret;
5951 
5952 	amdgpu_dm_plane_fill_blending_from_plane_state(
5953 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
5954 		&plane_info->global_alpha, &plane_info->global_alpha_value);
5955 
5956 	return 0;
5957 }
5958 
5959 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
5960 				    struct dc_plane_state *dc_plane_state,
5961 				    struct drm_plane_state *plane_state,
5962 				    struct drm_crtc_state *crtc_state)
5963 {
5964 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
5965 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
5966 	struct dc_scaling_info scaling_info;
5967 	struct dc_plane_info plane_info;
5968 	int ret;
5969 
5970 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
5971 	if (ret)
5972 		return ret;
5973 
5974 	dc_plane_state->src_rect = scaling_info.src_rect;
5975 	dc_plane_state->dst_rect = scaling_info.dst_rect;
5976 	dc_plane_state->clip_rect = scaling_info.clip_rect;
5977 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
5978 
5979 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
5980 					  afb->tiling_flags,
5981 					  &plane_info,
5982 					  &dc_plane_state->address,
5983 					  afb->tmz_surface);
5984 	if (ret)
5985 		return ret;
5986 
5987 	dc_plane_state->format = plane_info.format;
5988 	dc_plane_state->color_space = plane_info.color_space;
5989 	dc_plane_state->format = plane_info.format;
5990 	dc_plane_state->plane_size = plane_info.plane_size;
5991 	dc_plane_state->rotation = plane_info.rotation;
5992 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
5993 	dc_plane_state->stereo_format = plane_info.stereo_format;
5994 	dc_plane_state->tiling_info = plane_info.tiling_info;
5995 	dc_plane_state->visible = plane_info.visible;
5996 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
5997 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
5998 	dc_plane_state->global_alpha = plane_info.global_alpha;
5999 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6000 	dc_plane_state->dcc = plane_info.dcc;
6001 	dc_plane_state->layer_index = plane_info.layer_index;
6002 	dc_plane_state->flip_int_enabled = true;
6003 
6004 	/*
6005 	 * Always set input transfer function, since plane state is refreshed
6006 	 * every time.
6007 	 */
6008 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6009 						plane_state,
6010 						dc_plane_state);
6011 	if (ret)
6012 		return ret;
6013 
6014 	return 0;
6015 }
6016 
6017 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6018 				      struct rect *dirty_rect, int32_t x,
6019 				      s32 y, s32 width, s32 height,
6020 				      int *i, bool ffu)
6021 {
6022 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6023 
6024 	dirty_rect->x = x;
6025 	dirty_rect->y = y;
6026 	dirty_rect->width = width;
6027 	dirty_rect->height = height;
6028 
6029 	if (ffu)
6030 		drm_dbg(plane->dev,
6031 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6032 			plane->base.id, width, height);
6033 	else
6034 		drm_dbg(plane->dev,
6035 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6036 			plane->base.id, x, y, width, height);
6037 
6038 	(*i)++;
6039 }
6040 
6041 /**
6042  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6043  *
6044  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6045  *         remote fb
6046  * @old_plane_state: Old state of @plane
6047  * @new_plane_state: New state of @plane
6048  * @crtc_state: New state of CRTC connected to the @plane
6049  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6050  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6051  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6052  *             that have changed will be updated. If PSR SU is not enabled,
6053  *             or if damage clips are not available, the entire screen will be updated.
6054  * @dirty_regions_changed: dirty regions changed
6055  *
6056  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6057  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6058  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6059  * amdgpu_dm's.
6060  *
6061  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6062  * plane with regions that require flushing to the eDP remote buffer. In
6063  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6064  * implicitly provide damage clips without any client support via the plane
6065  * bounds.
6066  */
6067 static void fill_dc_dirty_rects(struct drm_plane *plane,
6068 				struct drm_plane_state *old_plane_state,
6069 				struct drm_plane_state *new_plane_state,
6070 				struct drm_crtc_state *crtc_state,
6071 				struct dc_flip_addrs *flip_addrs,
6072 				bool is_psr_su,
6073 				bool *dirty_regions_changed)
6074 {
6075 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6076 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6077 	u32 num_clips;
6078 	struct drm_mode_rect *clips;
6079 	bool bb_changed;
6080 	bool fb_changed;
6081 	u32 i = 0;
6082 	*dirty_regions_changed = false;
6083 
6084 	/*
6085 	 * Cursor plane has it's own dirty rect update interface. See
6086 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6087 	 */
6088 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6089 		return;
6090 
6091 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6092 		goto ffu;
6093 
6094 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6095 	clips = drm_plane_get_damage_clips(new_plane_state);
6096 
6097 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6098 						   is_psr_su)))
6099 		goto ffu;
6100 
6101 	if (!dm_crtc_state->mpo_requested) {
6102 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6103 			goto ffu;
6104 
6105 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6106 			fill_dc_dirty_rect(new_plane_state->plane,
6107 					   &dirty_rects[flip_addrs->dirty_rect_count],
6108 					   clips->x1, clips->y1,
6109 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6110 					   &flip_addrs->dirty_rect_count,
6111 					   false);
6112 		return;
6113 	}
6114 
6115 	/*
6116 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6117 	 * flipped to or damaged.
6118 	 *
6119 	 * If plane is moved or resized, also add old bounding box to dirty
6120 	 * rects.
6121 	 */
6122 	fb_changed = old_plane_state->fb->base.id !=
6123 		     new_plane_state->fb->base.id;
6124 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6125 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6126 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6127 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6128 
6129 	drm_dbg(plane->dev,
6130 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6131 		new_plane_state->plane->base.id,
6132 		bb_changed, fb_changed, num_clips);
6133 
6134 	*dirty_regions_changed = bb_changed;
6135 
6136 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6137 		goto ffu;
6138 
6139 	if (bb_changed) {
6140 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6141 				   new_plane_state->crtc_x,
6142 				   new_plane_state->crtc_y,
6143 				   new_plane_state->crtc_w,
6144 				   new_plane_state->crtc_h, &i, false);
6145 
6146 		/* Add old plane bounding-box if plane is moved or resized */
6147 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6148 				   old_plane_state->crtc_x,
6149 				   old_plane_state->crtc_y,
6150 				   old_plane_state->crtc_w,
6151 				   old_plane_state->crtc_h, &i, false);
6152 	}
6153 
6154 	if (num_clips) {
6155 		for (; i < num_clips; clips++)
6156 			fill_dc_dirty_rect(new_plane_state->plane,
6157 					   &dirty_rects[i], clips->x1,
6158 					   clips->y1, clips->x2 - clips->x1,
6159 					   clips->y2 - clips->y1, &i, false);
6160 	} else if (fb_changed && !bb_changed) {
6161 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6162 				   new_plane_state->crtc_x,
6163 				   new_plane_state->crtc_y,
6164 				   new_plane_state->crtc_w,
6165 				   new_plane_state->crtc_h, &i, false);
6166 	}
6167 
6168 	flip_addrs->dirty_rect_count = i;
6169 	return;
6170 
6171 ffu:
6172 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6173 			   dm_crtc_state->base.mode.crtc_hdisplay,
6174 			   dm_crtc_state->base.mode.crtc_vdisplay,
6175 			   &flip_addrs->dirty_rect_count, true);
6176 }
6177 
6178 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
6179 					   const struct dm_connector_state *dm_state,
6180 					   struct dc_stream_state *stream)
6181 {
6182 	enum amdgpu_rmx_type rmx_type;
6183 
6184 	struct rect src = { 0 }; /* viewport in composition space*/
6185 	struct rect dst = { 0 }; /* stream addressable area */
6186 
6187 	/* no mode. nothing to be done */
6188 	if (!mode)
6189 		return;
6190 
6191 	/* Full screen scaling by default */
6192 	src.width = mode->hdisplay;
6193 	src.height = mode->vdisplay;
6194 	dst.width = stream->timing.h_addressable;
6195 	dst.height = stream->timing.v_addressable;
6196 
6197 	if (dm_state) {
6198 		rmx_type = dm_state->scaling;
6199 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6200 			if (src.width * dst.height <
6201 					src.height * dst.width) {
6202 				/* height needs less upscaling/more downscaling */
6203 				dst.width = src.width *
6204 						dst.height / src.height;
6205 			} else {
6206 				/* width needs less upscaling/more downscaling */
6207 				dst.height = src.height *
6208 						dst.width / src.width;
6209 			}
6210 		} else if (rmx_type == RMX_CENTER) {
6211 			dst = src;
6212 		}
6213 
6214 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6215 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6216 
6217 		if (dm_state->underscan_enable) {
6218 			dst.x += dm_state->underscan_hborder / 2;
6219 			dst.y += dm_state->underscan_vborder / 2;
6220 			dst.width -= dm_state->underscan_hborder;
6221 			dst.height -= dm_state->underscan_vborder;
6222 		}
6223 	}
6224 
6225 	stream->src = src;
6226 	stream->dst = dst;
6227 
6228 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6229 		      dst.x, dst.y, dst.width, dst.height);
6230 
6231 }
6232 
6233 static enum dc_color_depth
6234 convert_color_depth_from_display_info(const struct drm_connector *connector,
6235 				      bool is_y420, int requested_bpc)
6236 {
6237 	u8 bpc;
6238 
6239 	if (is_y420) {
6240 		bpc = 8;
6241 
6242 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6243 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6244 			bpc = 16;
6245 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6246 			bpc = 12;
6247 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6248 			bpc = 10;
6249 	} else {
6250 		bpc = (uint8_t)connector->display_info.bpc;
6251 		/* Assume 8 bpc by default if no bpc is specified. */
6252 		bpc = bpc ? bpc : 8;
6253 	}
6254 
6255 	if (requested_bpc > 0) {
6256 		/*
6257 		 * Cap display bpc based on the user requested value.
6258 		 *
6259 		 * The value for state->max_bpc may not correctly updated
6260 		 * depending on when the connector gets added to the state
6261 		 * or if this was called outside of atomic check, so it
6262 		 * can't be used directly.
6263 		 */
6264 		bpc = min_t(u8, bpc, requested_bpc);
6265 
6266 		/* Round down to the nearest even number. */
6267 		bpc = bpc - (bpc & 1);
6268 	}
6269 
6270 	switch (bpc) {
6271 	case 0:
6272 		/*
6273 		 * Temporary Work around, DRM doesn't parse color depth for
6274 		 * EDID revision before 1.4
6275 		 * TODO: Fix edid parsing
6276 		 */
6277 		return COLOR_DEPTH_888;
6278 	case 6:
6279 		return COLOR_DEPTH_666;
6280 	case 8:
6281 		return COLOR_DEPTH_888;
6282 	case 10:
6283 		return COLOR_DEPTH_101010;
6284 	case 12:
6285 		return COLOR_DEPTH_121212;
6286 	case 14:
6287 		return COLOR_DEPTH_141414;
6288 	case 16:
6289 		return COLOR_DEPTH_161616;
6290 	default:
6291 		return COLOR_DEPTH_UNDEFINED;
6292 	}
6293 }
6294 
6295 static enum dc_aspect_ratio
6296 get_aspect_ratio(const struct drm_display_mode *mode_in)
6297 {
6298 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6299 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6300 }
6301 
6302 static enum dc_color_space
6303 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6304 		       const struct drm_connector_state *connector_state)
6305 {
6306 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6307 
6308 	switch (connector_state->colorspace) {
6309 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6310 		if (dc_crtc_timing->flags.Y_ONLY)
6311 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6312 		else
6313 			color_space = COLOR_SPACE_YCBCR601;
6314 		break;
6315 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6316 		if (dc_crtc_timing->flags.Y_ONLY)
6317 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6318 		else
6319 			color_space = COLOR_SPACE_YCBCR709;
6320 		break;
6321 	case DRM_MODE_COLORIMETRY_OPRGB:
6322 		color_space = COLOR_SPACE_ADOBERGB;
6323 		break;
6324 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6325 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6326 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6327 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6328 		else
6329 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6330 		break;
6331 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6332 	default:
6333 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6334 			color_space = COLOR_SPACE_SRGB;
6335 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6336 				color_space = COLOR_SPACE_SRGB_LIMITED;
6337 		/*
6338 		 * 27030khz is the separation point between HDTV and SDTV
6339 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6340 		 * respectively
6341 		 */
6342 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6343 			if (dc_crtc_timing->flags.Y_ONLY)
6344 				color_space =
6345 					COLOR_SPACE_YCBCR709_LIMITED;
6346 			else
6347 				color_space = COLOR_SPACE_YCBCR709;
6348 		} else {
6349 			if (dc_crtc_timing->flags.Y_ONLY)
6350 				color_space =
6351 					COLOR_SPACE_YCBCR601_LIMITED;
6352 			else
6353 				color_space = COLOR_SPACE_YCBCR601;
6354 		}
6355 		break;
6356 	}
6357 
6358 	return color_space;
6359 }
6360 
6361 static enum display_content_type
6362 get_output_content_type(const struct drm_connector_state *connector_state)
6363 {
6364 	switch (connector_state->content_type) {
6365 	default:
6366 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6367 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6368 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6369 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6370 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6371 		return DISPLAY_CONTENT_TYPE_PHOTO;
6372 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6373 		return DISPLAY_CONTENT_TYPE_CINEMA;
6374 	case DRM_MODE_CONTENT_TYPE_GAME:
6375 		return DISPLAY_CONTENT_TYPE_GAME;
6376 	}
6377 }
6378 
6379 static bool adjust_colour_depth_from_display_info(
6380 	struct dc_crtc_timing *timing_out,
6381 	const struct drm_display_info *info)
6382 {
6383 	enum dc_color_depth depth = timing_out->display_color_depth;
6384 	int normalized_clk;
6385 
6386 	do {
6387 		normalized_clk = timing_out->pix_clk_100hz / 10;
6388 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6389 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6390 			normalized_clk /= 2;
6391 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6392 		switch (depth) {
6393 		case COLOR_DEPTH_888:
6394 			break;
6395 		case COLOR_DEPTH_101010:
6396 			normalized_clk = (normalized_clk * 30) / 24;
6397 			break;
6398 		case COLOR_DEPTH_121212:
6399 			normalized_clk = (normalized_clk * 36) / 24;
6400 			break;
6401 		case COLOR_DEPTH_161616:
6402 			normalized_clk = (normalized_clk * 48) / 24;
6403 			break;
6404 		default:
6405 			/* The above depths are the only ones valid for HDMI. */
6406 			return false;
6407 		}
6408 		if (normalized_clk <= info->max_tmds_clock) {
6409 			timing_out->display_color_depth = depth;
6410 			return true;
6411 		}
6412 	} while (--depth > COLOR_DEPTH_666);
6413 	return false;
6414 }
6415 
6416 static void fill_stream_properties_from_drm_display_mode(
6417 	struct dc_stream_state *stream,
6418 	const struct drm_display_mode *mode_in,
6419 	const struct drm_connector *connector,
6420 	const struct drm_connector_state *connector_state,
6421 	const struct dc_stream_state *old_stream,
6422 	int requested_bpc)
6423 {
6424 	struct dc_crtc_timing *timing_out = &stream->timing;
6425 	const struct drm_display_info *info = &connector->display_info;
6426 	struct amdgpu_dm_connector *aconnector = NULL;
6427 	struct hdmi_vendor_infoframe hv_frame;
6428 	struct hdmi_avi_infoframe avi_frame;
6429 	ssize_t err;
6430 
6431 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6432 		aconnector = to_amdgpu_dm_connector(connector);
6433 
6434 	memset(&hv_frame, 0, sizeof(hv_frame));
6435 	memset(&avi_frame, 0, sizeof(avi_frame));
6436 
6437 	timing_out->h_border_left = 0;
6438 	timing_out->h_border_right = 0;
6439 	timing_out->v_border_top = 0;
6440 	timing_out->v_border_bottom = 0;
6441 	/* TODO: un-hardcode */
6442 	if (drm_mode_is_420_only(info, mode_in)
6443 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6444 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6445 	else if (drm_mode_is_420_also(info, mode_in)
6446 			&& aconnector
6447 			&& aconnector->force_yuv420_output)
6448 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6449 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
6450 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6451 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6452 	else
6453 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6454 
6455 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6456 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6457 		connector,
6458 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6459 		requested_bpc);
6460 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6461 	timing_out->hdmi_vic = 0;
6462 
6463 	if (old_stream) {
6464 		timing_out->vic = old_stream->timing.vic;
6465 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6466 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6467 	} else {
6468 		timing_out->vic = drm_match_cea_mode(mode_in);
6469 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6470 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6471 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6472 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6473 	}
6474 
6475 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6476 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6477 							       (struct drm_connector *)connector,
6478 							       mode_in);
6479 		if (err < 0)
6480 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd \n", connector->name, err);
6481 		timing_out->vic = avi_frame.video_code;
6482 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6483 								  (struct drm_connector *)connector,
6484 								  mode_in);
6485 		if (err < 0)
6486 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd \n", connector->name, err);
6487 		timing_out->hdmi_vic = hv_frame.vic;
6488 	}
6489 
6490 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6491 		timing_out->h_addressable = mode_in->hdisplay;
6492 		timing_out->h_total = mode_in->htotal;
6493 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6494 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6495 		timing_out->v_total = mode_in->vtotal;
6496 		timing_out->v_addressable = mode_in->vdisplay;
6497 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6498 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6499 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6500 	} else {
6501 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6502 		timing_out->h_total = mode_in->crtc_htotal;
6503 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6504 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6505 		timing_out->v_total = mode_in->crtc_vtotal;
6506 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6507 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6508 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6509 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6510 	}
6511 
6512 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6513 
6514 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6515 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6516 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6517 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6518 		    drm_mode_is_420_also(info, mode_in) &&
6519 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6520 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6521 			adjust_colour_depth_from_display_info(timing_out, info);
6522 		}
6523 	}
6524 
6525 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6526 	stream->content_type = get_output_content_type(connector_state);
6527 }
6528 
6529 static void fill_audio_info(struct audio_info *audio_info,
6530 			    const struct drm_connector *drm_connector,
6531 			    const struct dc_sink *dc_sink)
6532 {
6533 	int i = 0;
6534 	int cea_revision = 0;
6535 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6536 
6537 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6538 	audio_info->product_id = edid_caps->product_id;
6539 
6540 	cea_revision = drm_connector->display_info.cea_rev;
6541 
6542 	strscpy(audio_info->display_name,
6543 		edid_caps->display_name,
6544 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6545 
6546 	if (cea_revision >= 3) {
6547 		audio_info->mode_count = edid_caps->audio_mode_count;
6548 
6549 		for (i = 0; i < audio_info->mode_count; ++i) {
6550 			audio_info->modes[i].format_code =
6551 					(enum audio_format_code)
6552 					(edid_caps->audio_modes[i].format_code);
6553 			audio_info->modes[i].channel_count =
6554 					edid_caps->audio_modes[i].channel_count;
6555 			audio_info->modes[i].sample_rates.all =
6556 					edid_caps->audio_modes[i].sample_rate;
6557 			audio_info->modes[i].sample_size =
6558 					edid_caps->audio_modes[i].sample_size;
6559 		}
6560 	}
6561 
6562 	audio_info->flags.all = edid_caps->speaker_flags;
6563 
6564 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6565 	if (drm_connector->latency_present[0]) {
6566 		audio_info->video_latency = drm_connector->video_latency[0];
6567 		audio_info->audio_latency = drm_connector->audio_latency[0];
6568 	}
6569 
6570 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6571 
6572 }
6573 
6574 static void
6575 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6576 				      struct drm_display_mode *dst_mode)
6577 {
6578 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6579 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6580 	dst_mode->crtc_clock = src_mode->crtc_clock;
6581 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6582 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6583 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6584 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6585 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6586 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6587 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6588 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6589 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6590 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6591 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6592 }
6593 
6594 static void
6595 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6596 					const struct drm_display_mode *native_mode,
6597 					bool scale_enabled)
6598 {
6599 	if (scale_enabled || (
6600 	    native_mode->clock == drm_mode->clock &&
6601 	    native_mode->htotal == drm_mode->htotal &&
6602 	    native_mode->vtotal == drm_mode->vtotal)) {
6603 		if (native_mode->crtc_clock)
6604 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6605 	} else {
6606 		/* no scaling nor amdgpu inserted, no need to patch */
6607 	}
6608 }
6609 
6610 static struct dc_sink *
6611 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6612 {
6613 	struct dc_sink_init_data sink_init_data = { 0 };
6614 	struct dc_sink *sink = NULL;
6615 
6616 	sink_init_data.link = link;
6617 	sink_init_data.sink_signal = link->connector_signal;
6618 
6619 	sink = dc_sink_create(&sink_init_data);
6620 	if (!sink) {
6621 		drm_err(dev, "Failed to create sink!\n");
6622 		return NULL;
6623 	}
6624 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6625 
6626 	return sink;
6627 }
6628 
6629 static void set_multisync_trigger_params(
6630 		struct dc_stream_state *stream)
6631 {
6632 	struct dc_stream_state *master = NULL;
6633 
6634 	if (stream->triggered_crtc_reset.enabled) {
6635 		master = stream->triggered_crtc_reset.event_source;
6636 		stream->triggered_crtc_reset.event =
6637 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6638 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6639 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6640 	}
6641 }
6642 
6643 static void set_master_stream(struct dc_stream_state *stream_set[],
6644 			      int stream_count)
6645 {
6646 	int j, highest_rfr = 0, master_stream = 0;
6647 
6648 	for (j = 0;  j < stream_count; j++) {
6649 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
6650 			int refresh_rate = 0;
6651 
6652 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
6653 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
6654 			if (refresh_rate > highest_rfr) {
6655 				highest_rfr = refresh_rate;
6656 				master_stream = j;
6657 			}
6658 		}
6659 	}
6660 	for (j = 0;  j < stream_count; j++) {
6661 		if (stream_set[j])
6662 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
6663 	}
6664 }
6665 
6666 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
6667 {
6668 	int i = 0;
6669 	struct dc_stream_state *stream;
6670 
6671 	if (context->stream_count < 2)
6672 		return;
6673 	for (i = 0; i < context->stream_count ; i++) {
6674 		if (!context->streams[i])
6675 			continue;
6676 		/*
6677 		 * TODO: add a function to read AMD VSDB bits and set
6678 		 * crtc_sync_master.multi_sync_enabled flag
6679 		 * For now it's set to false
6680 		 */
6681 	}
6682 
6683 	set_master_stream(context->streams, context->stream_count);
6684 
6685 	for (i = 0; i < context->stream_count ; i++) {
6686 		stream = context->streams[i];
6687 
6688 		if (!stream)
6689 			continue;
6690 
6691 		set_multisync_trigger_params(stream);
6692 	}
6693 }
6694 
6695 /**
6696  * DOC: FreeSync Video
6697  *
6698  * When a userspace application wants to play a video, the content follows a
6699  * standard format definition that usually specifies the FPS for that format.
6700  * The below list illustrates some video format and the expected FPS,
6701  * respectively:
6702  *
6703  * - TV/NTSC (23.976 FPS)
6704  * - Cinema (24 FPS)
6705  * - TV/PAL (25 FPS)
6706  * - TV/NTSC (29.97 FPS)
6707  * - TV/NTSC (30 FPS)
6708  * - Cinema HFR (48 FPS)
6709  * - TV/PAL (50 FPS)
6710  * - Commonly used (60 FPS)
6711  * - Multiples of 24 (48,72,96 FPS)
6712  *
6713  * The list of standards video format is not huge and can be added to the
6714  * connector modeset list beforehand. With that, userspace can leverage
6715  * FreeSync to extends the front porch in order to attain the target refresh
6716  * rate. Such a switch will happen seamlessly, without screen blanking or
6717  * reprogramming of the output in any other way. If the userspace requests a
6718  * modesetting change compatible with FreeSync modes that only differ in the
6719  * refresh rate, DC will skip the full update and avoid blink during the
6720  * transition. For example, the video player can change the modesetting from
6721  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
6722  * causing any display blink. This same concept can be applied to a mode
6723  * setting change.
6724  */
6725 static struct drm_display_mode *
6726 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
6727 		bool use_probed_modes)
6728 {
6729 	struct drm_display_mode *m, *m_pref = NULL;
6730 	u16 current_refresh, highest_refresh;
6731 	struct list_head *list_head = use_probed_modes ?
6732 		&aconnector->base.probed_modes :
6733 		&aconnector->base.modes;
6734 
6735 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
6736 		return NULL;
6737 
6738 	if (aconnector->freesync_vid_base.clock != 0)
6739 		return &aconnector->freesync_vid_base;
6740 
6741 	/* Find the preferred mode */
6742 	list_for_each_entry(m, list_head, head) {
6743 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
6744 			m_pref = m;
6745 			break;
6746 		}
6747 	}
6748 
6749 	if (!m_pref) {
6750 		/* Probably an EDID with no preferred mode. Fallback to first entry */
6751 		m_pref = list_first_entry_or_null(
6752 				&aconnector->base.modes, struct drm_display_mode, head);
6753 		if (!m_pref) {
6754 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
6755 			return NULL;
6756 		}
6757 	}
6758 
6759 	highest_refresh = drm_mode_vrefresh(m_pref);
6760 
6761 	/*
6762 	 * Find the mode with highest refresh rate with same resolution.
6763 	 * For some monitors, preferred mode is not the mode with highest
6764 	 * supported refresh rate.
6765 	 */
6766 	list_for_each_entry(m, list_head, head) {
6767 		current_refresh  = drm_mode_vrefresh(m);
6768 
6769 		if (m->hdisplay == m_pref->hdisplay &&
6770 		    m->vdisplay == m_pref->vdisplay &&
6771 		    highest_refresh < current_refresh) {
6772 			highest_refresh = current_refresh;
6773 			m_pref = m;
6774 		}
6775 	}
6776 
6777 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
6778 	return m_pref;
6779 }
6780 
6781 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
6782 		struct amdgpu_dm_connector *aconnector)
6783 {
6784 	struct drm_display_mode *high_mode;
6785 	int timing_diff;
6786 
6787 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
6788 	if (!high_mode || !mode)
6789 		return false;
6790 
6791 	timing_diff = high_mode->vtotal - mode->vtotal;
6792 
6793 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
6794 	    high_mode->hdisplay != mode->hdisplay ||
6795 	    high_mode->vdisplay != mode->vdisplay ||
6796 	    high_mode->hsync_start != mode->hsync_start ||
6797 	    high_mode->hsync_end != mode->hsync_end ||
6798 	    high_mode->htotal != mode->htotal ||
6799 	    high_mode->hskew != mode->hskew ||
6800 	    high_mode->vscan != mode->vscan ||
6801 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
6802 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
6803 		return false;
6804 	else
6805 		return true;
6806 }
6807 
6808 #if defined(CONFIG_DRM_AMD_DC_FP)
6809 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
6810 			    struct dc_sink *sink, struct dc_stream_state *stream,
6811 			    struct dsc_dec_dpcd_caps *dsc_caps)
6812 {
6813 	stream->timing.flags.DSC = 0;
6814 	dsc_caps->is_dsc_supported = false;
6815 
6816 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
6817 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
6818 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
6819 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
6820 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
6821 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
6822 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
6823 				dsc_caps);
6824 	}
6825 }
6826 
6827 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
6828 				    struct dc_sink *sink, struct dc_stream_state *stream,
6829 				    struct dsc_dec_dpcd_caps *dsc_caps,
6830 				    uint32_t max_dsc_target_bpp_limit_override)
6831 {
6832 	const struct dc_link_settings *verified_link_cap = NULL;
6833 	u32 link_bw_in_kbps;
6834 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
6835 	struct dc *dc = sink->ctx->dc;
6836 	struct dc_dsc_bw_range bw_range = {0};
6837 	struct dc_dsc_config dsc_cfg = {0};
6838 	struct dc_dsc_config_options dsc_options = {0};
6839 
6840 	dc_dsc_get_default_config_option(dc, &dsc_options);
6841 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
6842 
6843 	verified_link_cap = dc_link_get_link_cap(stream->link);
6844 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
6845 	edp_min_bpp_x16 = 8 * 16;
6846 	edp_max_bpp_x16 = 8 * 16;
6847 
6848 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
6849 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
6850 
6851 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
6852 		edp_min_bpp_x16 = edp_max_bpp_x16;
6853 
6854 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
6855 				dc->debug.dsc_min_slice_height_override,
6856 				edp_min_bpp_x16, edp_max_bpp_x16,
6857 				dsc_caps,
6858 				&stream->timing,
6859 				dc_link_get_highest_encoding_format(aconnector->dc_link),
6860 				&bw_range)) {
6861 
6862 		if (bw_range.max_kbps < link_bw_in_kbps) {
6863 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
6864 					dsc_caps,
6865 					&dsc_options,
6866 					0,
6867 					&stream->timing,
6868 					dc_link_get_highest_encoding_format(aconnector->dc_link),
6869 					&dsc_cfg)) {
6870 				stream->timing.dsc_cfg = dsc_cfg;
6871 				stream->timing.flags.DSC = 1;
6872 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
6873 			}
6874 			return;
6875 		}
6876 	}
6877 
6878 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
6879 				dsc_caps,
6880 				&dsc_options,
6881 				link_bw_in_kbps,
6882 				&stream->timing,
6883 				dc_link_get_highest_encoding_format(aconnector->dc_link),
6884 				&dsc_cfg)) {
6885 		stream->timing.dsc_cfg = dsc_cfg;
6886 		stream->timing.flags.DSC = 1;
6887 	}
6888 }
6889 
6890 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
6891 					struct dc_sink *sink, struct dc_stream_state *stream,
6892 					struct dsc_dec_dpcd_caps *dsc_caps)
6893 {
6894 	struct drm_connector *drm_connector = &aconnector->base;
6895 	u32 link_bandwidth_kbps;
6896 	struct dc *dc = sink->ctx->dc;
6897 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
6898 	u32 dsc_max_supported_bw_in_kbps;
6899 	u32 max_dsc_target_bpp_limit_override =
6900 		drm_connector->display_info.max_dsc_bpp;
6901 	struct dc_dsc_config_options dsc_options = {0};
6902 
6903 	dc_dsc_get_default_config_option(dc, &dsc_options);
6904 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
6905 
6906 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
6907 							dc_link_get_link_cap(aconnector->dc_link));
6908 
6909 	/* Set DSC policy according to dsc_clock_en */
6910 	dc_dsc_policy_set_enable_dsc_when_not_needed(
6911 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
6912 
6913 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
6914 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
6915 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
6916 
6917 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
6918 
6919 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6920 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
6921 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
6922 						dsc_caps,
6923 						&dsc_options,
6924 						link_bandwidth_kbps,
6925 						&stream->timing,
6926 						dc_link_get_highest_encoding_format(aconnector->dc_link),
6927 						&stream->timing.dsc_cfg)) {
6928 				stream->timing.flags.DSC = 1;
6929 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
6930 							__func__, drm_connector->name);
6931 			}
6932 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
6933 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
6934 					dc_link_get_highest_encoding_format(aconnector->dc_link));
6935 			max_supported_bw_in_kbps = link_bandwidth_kbps;
6936 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
6937 
6938 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
6939 					max_supported_bw_in_kbps > 0 &&
6940 					dsc_max_supported_bw_in_kbps > 0)
6941 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
6942 						dsc_caps,
6943 						&dsc_options,
6944 						dsc_max_supported_bw_in_kbps,
6945 						&stream->timing,
6946 						dc_link_get_highest_encoding_format(aconnector->dc_link),
6947 						&stream->timing.dsc_cfg)) {
6948 					stream->timing.flags.DSC = 1;
6949 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
6950 									 __func__, drm_connector->name);
6951 				}
6952 		}
6953 	}
6954 
6955 	/* Overwrite the stream flag if DSC is enabled through debugfs */
6956 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
6957 		stream->timing.flags.DSC = 1;
6958 
6959 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
6960 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
6961 
6962 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
6963 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
6964 
6965 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
6966 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
6967 }
6968 #endif
6969 
6970 static struct dc_stream_state *
6971 create_stream_for_sink(struct drm_connector *connector,
6972 		       const struct drm_display_mode *drm_mode,
6973 		       const struct dm_connector_state *dm_state,
6974 		       const struct dc_stream_state *old_stream,
6975 		       int requested_bpc)
6976 {
6977 	struct drm_device *dev = connector->dev;
6978 	struct amdgpu_dm_connector *aconnector = NULL;
6979 	struct drm_display_mode *preferred_mode = NULL;
6980 	const struct drm_connector_state *con_state = &dm_state->base;
6981 	struct dc_stream_state *stream = NULL;
6982 	struct drm_display_mode mode;
6983 	struct drm_display_mode saved_mode;
6984 	struct drm_display_mode *freesync_mode = NULL;
6985 	bool native_mode_found = false;
6986 	bool recalculate_timing = false;
6987 	bool scale = dm_state->scaling != RMX_OFF;
6988 	int mode_refresh;
6989 	int preferred_refresh = 0;
6990 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
6991 #if defined(CONFIG_DRM_AMD_DC_FP)
6992 	struct dsc_dec_dpcd_caps dsc_caps;
6993 #endif
6994 	struct dc_link *link = NULL;
6995 	struct dc_sink *sink = NULL;
6996 
6997 	drm_mode_init(&mode, drm_mode);
6998 	memset(&saved_mode, 0, sizeof(saved_mode));
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_dbg_driver(dev, "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_dbg_driver(new_state->base.crtc->dev, "%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_dbg_driver(new_state->base.crtc->dev, "%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 	/* Check for error in getting connector state */
10609 	if (IS_ERR(conn_state)) {
10610 		ret = PTR_ERR(conn_state);
10611 		goto out;
10612 	}
10613 
10614 	/* Attach crtc to drm_atomic_state*/
10615 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
10616 
10617 	/* Check for error in getting crtc state */
10618 	if (IS_ERR(crtc_state)) {
10619 		ret = PTR_ERR(crtc_state);
10620 		goto out;
10621 	}
10622 
10623 	/* force a restore */
10624 	crtc_state->mode_changed = true;
10625 
10626 	/* Attach plane to drm_atomic_state */
10627 	plane_state = drm_atomic_get_plane_state(state, plane);
10628 
10629 	/* Check for error in getting plane state */
10630 	if (IS_ERR(plane_state)) {
10631 		ret = PTR_ERR(plane_state);
10632 		goto out;
10633 	}
10634 
10635 	/* Call commit internally with the state we just constructed */
10636 	ret = drm_atomic_commit(state);
10637 
10638 out:
10639 	drm_atomic_state_put(state);
10640 	if (ret)
10641 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
10642 
10643 	return ret;
10644 }
10645 
10646 /*
10647  * This function handles all cases when set mode does not come upon hotplug.
10648  * This includes when a display is unplugged then plugged back into the
10649  * same port and when running without usermode desktop manager supprot
10650  */
10651 void dm_restore_drm_connector_state(struct drm_device *dev,
10652 				    struct drm_connector *connector)
10653 {
10654 	struct amdgpu_dm_connector *aconnector;
10655 	struct amdgpu_crtc *disconnected_acrtc;
10656 	struct dm_crtc_state *acrtc_state;
10657 
10658 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10659 		return;
10660 
10661 	aconnector = to_amdgpu_dm_connector(connector);
10662 
10663 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
10664 		return;
10665 
10666 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
10667 	if (!disconnected_acrtc)
10668 		return;
10669 
10670 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
10671 	if (!acrtc_state->stream)
10672 		return;
10673 
10674 	/*
10675 	 * If the previous sink is not released and different from the current,
10676 	 * we deduce we are in a state where we can not rely on usermode call
10677 	 * to turn on the display, so we do it here
10678 	 */
10679 	if (acrtc_state->stream->sink != aconnector->dc_sink)
10680 		dm_force_atomic_commit(&aconnector->base);
10681 }
10682 
10683 /*
10684  * Grabs all modesetting locks to serialize against any blocking commits,
10685  * Waits for completion of all non blocking commits.
10686  */
10687 static int do_aquire_global_lock(struct drm_device *dev,
10688 				 struct drm_atomic_state *state)
10689 {
10690 	struct drm_crtc *crtc;
10691 	struct drm_crtc_commit *commit;
10692 	long ret;
10693 
10694 	/*
10695 	 * Adding all modeset locks to aquire_ctx will
10696 	 * ensure that when the framework release it the
10697 	 * extra locks we are locking here will get released to
10698 	 */
10699 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
10700 	if (ret)
10701 		return ret;
10702 
10703 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
10704 		spin_lock(&crtc->commit_lock);
10705 		commit = list_first_entry_or_null(&crtc->commit_list,
10706 				struct drm_crtc_commit, commit_entry);
10707 		if (commit)
10708 			drm_crtc_commit_get(commit);
10709 		spin_unlock(&crtc->commit_lock);
10710 
10711 		if (!commit)
10712 			continue;
10713 
10714 		/*
10715 		 * Make sure all pending HW programming completed and
10716 		 * page flips done
10717 		 */
10718 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
10719 
10720 		if (ret > 0)
10721 			ret = wait_for_completion_interruptible_timeout(
10722 					&commit->flip_done, 10*HZ);
10723 
10724 		if (ret == 0)
10725 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
10726 				  crtc->base.id, crtc->name);
10727 
10728 		drm_crtc_commit_put(commit);
10729 	}
10730 
10731 	return ret < 0 ? ret : 0;
10732 }
10733 
10734 static void get_freesync_config_for_crtc(
10735 	struct dm_crtc_state *new_crtc_state,
10736 	struct dm_connector_state *new_con_state)
10737 {
10738 	struct mod_freesync_config config = {0};
10739 	struct amdgpu_dm_connector *aconnector;
10740 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
10741 	int vrefresh = drm_mode_vrefresh(mode);
10742 	bool fs_vid_mode = false;
10743 
10744 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10745 		return;
10746 
10747 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
10748 
10749 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
10750 					vrefresh >= aconnector->min_vfreq &&
10751 					vrefresh <= aconnector->max_vfreq;
10752 
10753 	if (new_crtc_state->vrr_supported) {
10754 		new_crtc_state->stream->ignore_msa_timing_param = true;
10755 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
10756 
10757 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
10758 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
10759 		config.vsif_supported = true;
10760 		config.btr = true;
10761 
10762 		if (fs_vid_mode) {
10763 			config.state = VRR_STATE_ACTIVE_FIXED;
10764 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
10765 			goto out;
10766 		} else if (new_crtc_state->base.vrr_enabled) {
10767 			config.state = VRR_STATE_ACTIVE_VARIABLE;
10768 		} else {
10769 			config.state = VRR_STATE_INACTIVE;
10770 		}
10771 	}
10772 out:
10773 	new_crtc_state->freesync_config = config;
10774 }
10775 
10776 static void reset_freesync_config_for_crtc(
10777 	struct dm_crtc_state *new_crtc_state)
10778 {
10779 	new_crtc_state->vrr_supported = false;
10780 
10781 	memset(&new_crtc_state->vrr_infopacket, 0,
10782 	       sizeof(new_crtc_state->vrr_infopacket));
10783 }
10784 
10785 static bool
10786 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
10787 				 struct drm_crtc_state *new_crtc_state)
10788 {
10789 	const struct drm_display_mode *old_mode, *new_mode;
10790 
10791 	if (!old_crtc_state || !new_crtc_state)
10792 		return false;
10793 
10794 	old_mode = &old_crtc_state->mode;
10795 	new_mode = &new_crtc_state->mode;
10796 
10797 	if (old_mode->clock       == new_mode->clock &&
10798 	    old_mode->hdisplay    == new_mode->hdisplay &&
10799 	    old_mode->vdisplay    == new_mode->vdisplay &&
10800 	    old_mode->htotal      == new_mode->htotal &&
10801 	    old_mode->vtotal      != new_mode->vtotal &&
10802 	    old_mode->hsync_start == new_mode->hsync_start &&
10803 	    old_mode->vsync_start != new_mode->vsync_start &&
10804 	    old_mode->hsync_end   == new_mode->hsync_end &&
10805 	    old_mode->vsync_end   != new_mode->vsync_end &&
10806 	    old_mode->hskew       == new_mode->hskew &&
10807 	    old_mode->vscan       == new_mode->vscan &&
10808 	    (old_mode->vsync_end - old_mode->vsync_start) ==
10809 	    (new_mode->vsync_end - new_mode->vsync_start))
10810 		return true;
10811 
10812 	return false;
10813 }
10814 
10815 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
10816 {
10817 	u64 num, den, res;
10818 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
10819 
10820 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
10821 
10822 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
10823 	den = (unsigned long long)new_crtc_state->mode.htotal *
10824 	      (unsigned long long)new_crtc_state->mode.vtotal;
10825 
10826 	res = div_u64(num, den);
10827 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
10828 }
10829 
10830 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
10831 			 struct drm_atomic_state *state,
10832 			 struct drm_crtc *crtc,
10833 			 struct drm_crtc_state *old_crtc_state,
10834 			 struct drm_crtc_state *new_crtc_state,
10835 			 bool enable,
10836 			 bool *lock_and_validation_needed)
10837 {
10838 	struct dm_atomic_state *dm_state = NULL;
10839 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10840 	struct dc_stream_state *new_stream;
10841 	struct amdgpu_device *adev = dm->adev;
10842 	int ret = 0;
10843 
10844 	/*
10845 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
10846 	 * update changed items
10847 	 */
10848 	struct amdgpu_crtc *acrtc = NULL;
10849 	struct drm_connector *connector = NULL;
10850 	struct amdgpu_dm_connector *aconnector = NULL;
10851 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
10852 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
10853 
10854 	new_stream = NULL;
10855 
10856 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10857 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10858 	acrtc = to_amdgpu_crtc(crtc);
10859 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
10860 	if (connector)
10861 		aconnector = to_amdgpu_dm_connector(connector);
10862 
10863 	/* TODO This hack should go away */
10864 	if (connector && enable) {
10865 		/* Make sure fake sink is created in plug-in scenario */
10866 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
10867 									connector);
10868 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
10869 									connector);
10870 
10871 		if (WARN_ON(!drm_new_conn_state)) {
10872 			ret = -EINVAL;
10873 			goto fail;
10874 		}
10875 
10876 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
10877 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
10878 
10879 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10880 			goto skip_modeset;
10881 
10882 		new_stream = create_validate_stream_for_sink(connector,
10883 							     &new_crtc_state->mode,
10884 							     dm_new_conn_state,
10885 							     dm_old_crtc_state->stream);
10886 
10887 		/*
10888 		 * we can have no stream on ACTION_SET if a display
10889 		 * was disconnected during S3, in this case it is not an
10890 		 * error, the OS will be updated after detection, and
10891 		 * will do the right thing on next atomic commit
10892 		 */
10893 
10894 		if (!new_stream) {
10895 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
10896 					__func__, acrtc->base.base.id);
10897 			ret = -ENOMEM;
10898 			goto fail;
10899 		}
10900 
10901 		/*
10902 		 * TODO: Check VSDB bits to decide whether this should
10903 		 * be enabled or not.
10904 		 */
10905 		new_stream->triggered_crtc_reset.enabled =
10906 			dm->force_timing_sync;
10907 
10908 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
10909 
10910 		ret = fill_hdr_info_packet(drm_new_conn_state,
10911 					   &new_stream->hdr_static_metadata);
10912 		if (ret)
10913 			goto fail;
10914 
10915 		/*
10916 		 * If we already removed the old stream from the context
10917 		 * (and set the new stream to NULL) then we can't reuse
10918 		 * the old stream even if the stream and scaling are unchanged.
10919 		 * We'll hit the BUG_ON and black screen.
10920 		 *
10921 		 * TODO: Refactor this function to allow this check to work
10922 		 * in all conditions.
10923 		 */
10924 		if (amdgpu_freesync_vid_mode &&
10925 		    dm_new_crtc_state->stream &&
10926 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
10927 			goto skip_modeset;
10928 
10929 		if (dm_new_crtc_state->stream &&
10930 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10931 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
10932 			new_crtc_state->mode_changed = false;
10933 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
10934 					 new_crtc_state->mode_changed);
10935 		}
10936 	}
10937 
10938 	/* mode_changed flag may get updated above, need to check again */
10939 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10940 		goto skip_modeset;
10941 
10942 	drm_dbg_state(state->dev,
10943 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10944 		acrtc->crtc_id,
10945 		new_crtc_state->enable,
10946 		new_crtc_state->active,
10947 		new_crtc_state->planes_changed,
10948 		new_crtc_state->mode_changed,
10949 		new_crtc_state->active_changed,
10950 		new_crtc_state->connectors_changed);
10951 
10952 	/* Remove stream for any changed/disabled CRTC */
10953 	if (!enable) {
10954 
10955 		if (!dm_old_crtc_state->stream)
10956 			goto skip_modeset;
10957 
10958 		/* Unset freesync video if it was active before */
10959 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
10960 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
10961 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
10962 		}
10963 
10964 		/* Now check if we should set freesync video mode */
10965 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
10966 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10967 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
10968 		    is_timing_unchanged_for_freesync(new_crtc_state,
10969 						     old_crtc_state)) {
10970 			new_crtc_state->mode_changed = false;
10971 			drm_dbg_driver(adev_to_drm(adev),
10972 				"Mode change not required for front porch change, setting mode_changed to %d",
10973 				new_crtc_state->mode_changed);
10974 
10975 			set_freesync_fixed_config(dm_new_crtc_state);
10976 
10977 			goto skip_modeset;
10978 		} else if (amdgpu_freesync_vid_mode && aconnector &&
10979 			   is_freesync_video_mode(&new_crtc_state->mode,
10980 						  aconnector)) {
10981 			struct drm_display_mode *high_mode;
10982 
10983 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
10984 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
10985 				set_freesync_fixed_config(dm_new_crtc_state);
10986 		}
10987 
10988 		ret = dm_atomic_get_state(state, &dm_state);
10989 		if (ret)
10990 			goto fail;
10991 
10992 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
10993 				crtc->base.id);
10994 
10995 		/* i.e. reset mode */
10996 		if (dc_state_remove_stream(
10997 				dm->dc,
10998 				dm_state->context,
10999 				dm_old_crtc_state->stream) != DC_OK) {
11000 			ret = -EINVAL;
11001 			goto fail;
11002 		}
11003 
11004 		dc_stream_release(dm_old_crtc_state->stream);
11005 		dm_new_crtc_state->stream = NULL;
11006 
11007 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11008 
11009 		*lock_and_validation_needed = true;
11010 
11011 	} else {/* Add stream for any updated/enabled CRTC */
11012 		/*
11013 		 * Quick fix to prevent NULL pointer on new_stream when
11014 		 * added MST connectors not found in existing crtc_state in the chained mode
11015 		 * TODO: need to dig out the root cause of that
11016 		 */
11017 		if (!connector)
11018 			goto skip_modeset;
11019 
11020 		if (modereset_required(new_crtc_state))
11021 			goto skip_modeset;
11022 
11023 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11024 				     dm_old_crtc_state->stream)) {
11025 
11026 			WARN_ON(dm_new_crtc_state->stream);
11027 
11028 			ret = dm_atomic_get_state(state, &dm_state);
11029 			if (ret)
11030 				goto fail;
11031 
11032 			dm_new_crtc_state->stream = new_stream;
11033 
11034 			dc_stream_retain(new_stream);
11035 
11036 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
11037 					 crtc->base.id);
11038 
11039 			if (dc_state_add_stream(
11040 					dm->dc,
11041 					dm_state->context,
11042 					dm_new_crtc_state->stream) != DC_OK) {
11043 				ret = -EINVAL;
11044 				goto fail;
11045 			}
11046 
11047 			*lock_and_validation_needed = true;
11048 		}
11049 	}
11050 
11051 skip_modeset:
11052 	/* Release extra reference */
11053 	if (new_stream)
11054 		dc_stream_release(new_stream);
11055 
11056 	/*
11057 	 * We want to do dc stream updates that do not require a
11058 	 * full modeset below.
11059 	 */
11060 	if (!(enable && connector && new_crtc_state->active))
11061 		return 0;
11062 	/*
11063 	 * Given above conditions, the dc state cannot be NULL because:
11064 	 * 1. We're in the process of enabling CRTCs (just been added
11065 	 *    to the dc context, or already is on the context)
11066 	 * 2. Has a valid connector attached, and
11067 	 * 3. Is currently active and enabled.
11068 	 * => The dc stream state currently exists.
11069 	 */
11070 	BUG_ON(dm_new_crtc_state->stream == NULL);
11071 
11072 	/* Scaling or underscan settings */
11073 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11074 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11075 		update_stream_scaling_settings(
11076 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11077 
11078 	/* ABM settings */
11079 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11080 
11081 	/*
11082 	 * Color management settings. We also update color properties
11083 	 * when a modeset is needed, to ensure it gets reprogrammed.
11084 	 */
11085 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11086 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11087 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11088 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11089 		if (ret)
11090 			goto fail;
11091 	}
11092 
11093 	/* Update Freesync settings. */
11094 	get_freesync_config_for_crtc(dm_new_crtc_state,
11095 				     dm_new_conn_state);
11096 
11097 	return ret;
11098 
11099 fail:
11100 	if (new_stream)
11101 		dc_stream_release(new_stream);
11102 	return ret;
11103 }
11104 
11105 static bool should_reset_plane(struct drm_atomic_state *state,
11106 			       struct drm_plane *plane,
11107 			       struct drm_plane_state *old_plane_state,
11108 			       struct drm_plane_state *new_plane_state)
11109 {
11110 	struct drm_plane *other;
11111 	struct drm_plane_state *old_other_state, *new_other_state;
11112 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11113 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11114 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11115 	int i;
11116 
11117 	/*
11118 	 * TODO: Remove this hack for all asics once it proves that the
11119 	 * fast updates works fine on DCN3.2+.
11120 	 */
11121 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11122 	    state->allow_modeset)
11123 		return true;
11124 
11125 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11126 		return true;
11127 
11128 	/* Exit early if we know that we're adding or removing the plane. */
11129 	if (old_plane_state->crtc != new_plane_state->crtc)
11130 		return true;
11131 
11132 	/* old crtc == new_crtc == NULL, plane not in context. */
11133 	if (!new_plane_state->crtc)
11134 		return false;
11135 
11136 	new_crtc_state =
11137 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11138 	old_crtc_state =
11139 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11140 
11141 	if (!new_crtc_state)
11142 		return true;
11143 
11144 	/*
11145 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11146 	 * released from the state
11147 	 */
11148 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11149 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11150 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11151 	    old_dm_crtc_state != NULL &&
11152 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11153 		return true;
11154 	}
11155 
11156 	/* CRTC Degamma changes currently require us to recreate planes. */
11157 	if (new_crtc_state->color_mgmt_changed)
11158 		return true;
11159 
11160 	/*
11161 	 * On zpos change, planes need to be reordered by removing and re-adding
11162 	 * them one by one to the dc state, in order of descending zpos.
11163 	 *
11164 	 * TODO: We can likely skip bandwidth validation if the only thing that
11165 	 * changed about the plane was it'z z-ordering.
11166 	 */
11167 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11168 		return true;
11169 
11170 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11171 		return true;
11172 
11173 	/*
11174 	 * If there are any new primary or overlay planes being added or
11175 	 * removed then the z-order can potentially change. To ensure
11176 	 * correct z-order and pipe acquisition the current DC architecture
11177 	 * requires us to remove and recreate all existing planes.
11178 	 *
11179 	 * TODO: Come up with a more elegant solution for this.
11180 	 */
11181 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11182 		struct amdgpu_framebuffer *old_afb, *new_afb;
11183 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11184 
11185 		dm_new_other_state = to_dm_plane_state(new_other_state);
11186 		dm_old_other_state = to_dm_plane_state(old_other_state);
11187 
11188 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11189 			continue;
11190 
11191 		if (old_other_state->crtc != new_plane_state->crtc &&
11192 		    new_other_state->crtc != new_plane_state->crtc)
11193 			continue;
11194 
11195 		if (old_other_state->crtc != new_other_state->crtc)
11196 			return true;
11197 
11198 		/* Src/dst size and scaling updates. */
11199 		if (old_other_state->src_w != new_other_state->src_w ||
11200 		    old_other_state->src_h != new_other_state->src_h ||
11201 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11202 		    old_other_state->crtc_h != new_other_state->crtc_h)
11203 			return true;
11204 
11205 		/* Rotation / mirroring updates. */
11206 		if (old_other_state->rotation != new_other_state->rotation)
11207 			return true;
11208 
11209 		/* Blending updates. */
11210 		if (old_other_state->pixel_blend_mode !=
11211 		    new_other_state->pixel_blend_mode)
11212 			return true;
11213 
11214 		/* Alpha updates. */
11215 		if (old_other_state->alpha != new_other_state->alpha)
11216 			return true;
11217 
11218 		/* Colorspace changes. */
11219 		if (old_other_state->color_range != new_other_state->color_range ||
11220 		    old_other_state->color_encoding != new_other_state->color_encoding)
11221 			return true;
11222 
11223 		/* HDR/Transfer Function changes. */
11224 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11225 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11226 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11227 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11228 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11229 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11230 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11231 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11232 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11233 			return true;
11234 
11235 		/* Framebuffer checks fall at the end. */
11236 		if (!old_other_state->fb || !new_other_state->fb)
11237 			continue;
11238 
11239 		/* Pixel format changes can require bandwidth updates. */
11240 		if (old_other_state->fb->format != new_other_state->fb->format)
11241 			return true;
11242 
11243 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11244 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11245 
11246 		/* Tiling and DCC changes also require bandwidth updates. */
11247 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11248 		    old_afb->base.modifier != new_afb->base.modifier)
11249 			return true;
11250 	}
11251 
11252 	return false;
11253 }
11254 
11255 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11256 			      struct drm_plane_state *new_plane_state,
11257 			      struct drm_framebuffer *fb)
11258 {
11259 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11260 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11261 	unsigned int pitch;
11262 	bool linear;
11263 
11264 	if (fb->width > new_acrtc->max_cursor_width ||
11265 	    fb->height > new_acrtc->max_cursor_height) {
11266 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
11267 				 new_plane_state->fb->width,
11268 				 new_plane_state->fb->height);
11269 		return -EINVAL;
11270 	}
11271 	if (new_plane_state->src_w != fb->width << 16 ||
11272 	    new_plane_state->src_h != fb->height << 16) {
11273 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
11274 		return -EINVAL;
11275 	}
11276 
11277 	/* Pitch in pixels */
11278 	pitch = fb->pitches[0] / fb->format->cpp[0];
11279 
11280 	if (fb->width != pitch) {
11281 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
11282 				 fb->width, pitch);
11283 		return -EINVAL;
11284 	}
11285 
11286 	switch (pitch) {
11287 	case 64:
11288 	case 128:
11289 	case 256:
11290 		/* FB pitch is supported by cursor plane */
11291 		break;
11292 	default:
11293 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
11294 		return -EINVAL;
11295 	}
11296 
11297 	/* Core DRM takes care of checking FB modifiers, so we only need to
11298 	 * check tiling flags when the FB doesn't have a modifier.
11299 	 */
11300 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11301 		if (adev->family >= AMDGPU_FAMILY_GC_12_0_0) {
11302 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11303 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11304 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11305 		} else {
11306 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11307 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11308 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11309 		}
11310 		if (!linear) {
11311 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
11312 			return -EINVAL;
11313 		}
11314 	}
11315 
11316 	return 0;
11317 }
11318 
11319 /*
11320  * Helper function for checking the cursor in native mode
11321  */
11322 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11323 					struct drm_plane *plane,
11324 					struct drm_plane_state *new_plane_state,
11325 					bool enable)
11326 {
11327 
11328 	struct amdgpu_crtc *new_acrtc;
11329 	int ret;
11330 
11331 	if (!enable || !new_plane_crtc ||
11332 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11333 		return 0;
11334 
11335 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11336 
11337 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11338 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
11339 		return -EINVAL;
11340 	}
11341 
11342 	if (new_plane_state->fb) {
11343 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11344 						new_plane_state->fb);
11345 		if (ret)
11346 			return ret;
11347 	}
11348 
11349 	return 0;
11350 }
11351 
11352 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11353 					   struct drm_crtc *old_plane_crtc,
11354 					   struct drm_crtc *new_plane_crtc,
11355 					   bool enable)
11356 {
11357 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11358 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11359 
11360 	if (!enable) {
11361 		if (old_plane_crtc == NULL)
11362 			return true;
11363 
11364 		old_crtc_state = drm_atomic_get_old_crtc_state(
11365 			state, old_plane_crtc);
11366 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11367 
11368 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11369 	} else {
11370 		if (new_plane_crtc == NULL)
11371 			return true;
11372 
11373 		new_crtc_state = drm_atomic_get_new_crtc_state(
11374 			state, new_plane_crtc);
11375 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11376 
11377 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11378 	}
11379 }
11380 
11381 static int dm_update_plane_state(struct dc *dc,
11382 				 struct drm_atomic_state *state,
11383 				 struct drm_plane *plane,
11384 				 struct drm_plane_state *old_plane_state,
11385 				 struct drm_plane_state *new_plane_state,
11386 				 bool enable,
11387 				 bool *lock_and_validation_needed,
11388 				 bool *is_top_most_overlay)
11389 {
11390 
11391 	struct dm_atomic_state *dm_state = NULL;
11392 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11393 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11394 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11395 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11396 	bool needs_reset, update_native_cursor;
11397 	int ret = 0;
11398 
11399 
11400 	new_plane_crtc = new_plane_state->crtc;
11401 	old_plane_crtc = old_plane_state->crtc;
11402 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11403 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11404 
11405 	update_native_cursor = dm_should_update_native_cursor(state,
11406 							      old_plane_crtc,
11407 							      new_plane_crtc,
11408 							      enable);
11409 
11410 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11411 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11412 						    new_plane_state, enable);
11413 		if (ret)
11414 			return ret;
11415 
11416 		return 0;
11417 	}
11418 
11419 	needs_reset = should_reset_plane(state, plane, old_plane_state,
11420 					 new_plane_state);
11421 
11422 	/* Remove any changed/removed planes */
11423 	if (!enable) {
11424 		if (!needs_reset)
11425 			return 0;
11426 
11427 		if (!old_plane_crtc)
11428 			return 0;
11429 
11430 		old_crtc_state = drm_atomic_get_old_crtc_state(
11431 				state, old_plane_crtc);
11432 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11433 
11434 		if (!dm_old_crtc_state->stream)
11435 			return 0;
11436 
11437 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
11438 				plane->base.id, old_plane_crtc->base.id);
11439 
11440 		ret = dm_atomic_get_state(state, &dm_state);
11441 		if (ret)
11442 			return ret;
11443 
11444 		if (!dc_state_remove_plane(
11445 				dc,
11446 				dm_old_crtc_state->stream,
11447 				dm_old_plane_state->dc_state,
11448 				dm_state->context)) {
11449 
11450 			return -EINVAL;
11451 		}
11452 
11453 		if (dm_old_plane_state->dc_state)
11454 			dc_plane_state_release(dm_old_plane_state->dc_state);
11455 
11456 		dm_new_plane_state->dc_state = NULL;
11457 
11458 		*lock_and_validation_needed = true;
11459 
11460 	} else { /* Add new planes */
11461 		struct dc_plane_state *dc_new_plane_state;
11462 
11463 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
11464 			return 0;
11465 
11466 		if (!new_plane_crtc)
11467 			return 0;
11468 
11469 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
11470 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11471 
11472 		if (!dm_new_crtc_state->stream)
11473 			return 0;
11474 
11475 		if (!needs_reset)
11476 			return 0;
11477 
11478 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
11479 		if (ret)
11480 			goto out;
11481 
11482 		WARN_ON(dm_new_plane_state->dc_state);
11483 
11484 		dc_new_plane_state = dc_create_plane_state(dc);
11485 		if (!dc_new_plane_state) {
11486 			ret = -ENOMEM;
11487 			goto out;
11488 		}
11489 
11490 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
11491 				 plane->base.id, new_plane_crtc->base.id);
11492 
11493 		ret = fill_dc_plane_attributes(
11494 			drm_to_adev(new_plane_crtc->dev),
11495 			dc_new_plane_state,
11496 			new_plane_state,
11497 			new_crtc_state);
11498 		if (ret) {
11499 			dc_plane_state_release(dc_new_plane_state);
11500 			goto out;
11501 		}
11502 
11503 		ret = dm_atomic_get_state(state, &dm_state);
11504 		if (ret) {
11505 			dc_plane_state_release(dc_new_plane_state);
11506 			goto out;
11507 		}
11508 
11509 		/*
11510 		 * Any atomic check errors that occur after this will
11511 		 * not need a release. The plane state will be attached
11512 		 * to the stream, and therefore part of the atomic
11513 		 * state. It'll be released when the atomic state is
11514 		 * cleaned.
11515 		 */
11516 		if (!dc_state_add_plane(
11517 				dc,
11518 				dm_new_crtc_state->stream,
11519 				dc_new_plane_state,
11520 				dm_state->context)) {
11521 
11522 			dc_plane_state_release(dc_new_plane_state);
11523 			ret = -EINVAL;
11524 			goto out;
11525 		}
11526 
11527 		dm_new_plane_state->dc_state = dc_new_plane_state;
11528 
11529 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
11530 
11531 		/* Tell DC to do a full surface update every time there
11532 		 * is a plane change. Inefficient, but works for now.
11533 		 */
11534 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
11535 
11536 		*lock_and_validation_needed = true;
11537 	}
11538 
11539 out:
11540 	/* If enabling cursor overlay failed, attempt fallback to native mode */
11541 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
11542 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11543 						    new_plane_state, enable);
11544 		if (ret)
11545 			return ret;
11546 
11547 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
11548 	}
11549 
11550 	return ret;
11551 }
11552 
11553 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
11554 				       int *src_w, int *src_h)
11555 {
11556 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
11557 	case DRM_MODE_ROTATE_90:
11558 	case DRM_MODE_ROTATE_270:
11559 		*src_w = plane_state->src_h >> 16;
11560 		*src_h = plane_state->src_w >> 16;
11561 		break;
11562 	case DRM_MODE_ROTATE_0:
11563 	case DRM_MODE_ROTATE_180:
11564 	default:
11565 		*src_w = plane_state->src_w >> 16;
11566 		*src_h = plane_state->src_h >> 16;
11567 		break;
11568 	}
11569 }
11570 
11571 static void
11572 dm_get_plane_scale(struct drm_plane_state *plane_state,
11573 		   int *out_plane_scale_w, int *out_plane_scale_h)
11574 {
11575 	int plane_src_w, plane_src_h;
11576 
11577 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
11578 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
11579 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
11580 }
11581 
11582 /*
11583  * The normalized_zpos value cannot be used by this iterator directly. It's only
11584  * calculated for enabled planes, potentially causing normalized_zpos collisions
11585  * between enabled/disabled planes in the atomic state. We need a unique value
11586  * so that the iterator will not generate the same object twice, or loop
11587  * indefinitely.
11588  */
11589 static inline struct __drm_planes_state *__get_next_zpos(
11590 	struct drm_atomic_state *state,
11591 	struct __drm_planes_state *prev)
11592 {
11593 	unsigned int highest_zpos = 0, prev_zpos = 256;
11594 	uint32_t highest_id = 0, prev_id = UINT_MAX;
11595 	struct drm_plane_state *new_plane_state;
11596 	struct drm_plane *plane;
11597 	int i, highest_i = -1;
11598 
11599 	if (prev != NULL) {
11600 		prev_zpos = prev->new_state->zpos;
11601 		prev_id = prev->ptr->base.id;
11602 	}
11603 
11604 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
11605 		/* Skip planes with higher zpos than the previously returned */
11606 		if (new_plane_state->zpos > prev_zpos ||
11607 		    (new_plane_state->zpos == prev_zpos &&
11608 		     plane->base.id >= prev_id))
11609 			continue;
11610 
11611 		/* Save the index of the plane with highest zpos */
11612 		if (new_plane_state->zpos > highest_zpos ||
11613 		    (new_plane_state->zpos == highest_zpos &&
11614 		     plane->base.id > highest_id)) {
11615 			highest_zpos = new_plane_state->zpos;
11616 			highest_id = plane->base.id;
11617 			highest_i = i;
11618 		}
11619 	}
11620 
11621 	if (highest_i < 0)
11622 		return NULL;
11623 
11624 	return &state->planes[highest_i];
11625 }
11626 
11627 /*
11628  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
11629  * by descending zpos, as read from the new plane state. This is the same
11630  * ordering as defined by drm_atomic_normalize_zpos().
11631  */
11632 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
11633 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
11634 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
11635 		for_each_if(((plane) = __i->ptr,				\
11636 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
11637 			     (old_plane_state) = __i->old_state,		\
11638 			     (new_plane_state) = __i->new_state, 1))
11639 
11640 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
11641 {
11642 	struct drm_connector *connector;
11643 	struct drm_connector_state *conn_state, *old_conn_state;
11644 	struct amdgpu_dm_connector *aconnector = NULL;
11645 	int i;
11646 
11647 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
11648 		if (!conn_state->crtc)
11649 			conn_state = old_conn_state;
11650 
11651 		if (conn_state->crtc != crtc)
11652 			continue;
11653 
11654 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11655 			continue;
11656 
11657 		aconnector = to_amdgpu_dm_connector(connector);
11658 		if (!aconnector->mst_output_port || !aconnector->mst_root)
11659 			aconnector = NULL;
11660 		else
11661 			break;
11662 	}
11663 
11664 	if (!aconnector)
11665 		return 0;
11666 
11667 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
11668 }
11669 
11670 /**
11671  * DOC: Cursor Modes - Native vs Overlay
11672  *
11673  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
11674  * plane. It does not require a dedicated hw plane to enable, but it is
11675  * subjected to the same z-order and scaling as the hw plane. It also has format
11676  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
11677  * hw plane.
11678  *
11679  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
11680  * own scaling and z-pos. It also has no blending restrictions. It lends to a
11681  * cursor behavior more akin to a DRM client's expectations. However, it does
11682  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
11683  * available.
11684  */
11685 
11686 /**
11687  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
11688  * @adev: amdgpu device
11689  * @state: DRM atomic state
11690  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
11691  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
11692  *
11693  * Get whether the cursor should be enabled in native mode, or overlay mode, on
11694  * the dm_crtc_state.
11695  *
11696  * The cursor should be enabled in overlay mode if there exists an underlying
11697  * plane - on which the cursor may be blended - that is either YUV formatted, or
11698  * scaled differently from the cursor.
11699  *
11700  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
11701  * calling this function.
11702  *
11703  * Return: 0 on success, or an error code if getting the cursor plane state
11704  * failed.
11705  */
11706 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
11707 				   struct drm_atomic_state *state,
11708 				   struct dm_crtc_state *dm_crtc_state,
11709 				   enum amdgpu_dm_cursor_mode *cursor_mode)
11710 {
11711 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
11712 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
11713 	struct drm_plane *plane;
11714 	bool consider_mode_change = false;
11715 	bool entire_crtc_covered = false;
11716 	bool cursor_changed = false;
11717 	int underlying_scale_w, underlying_scale_h;
11718 	int cursor_scale_w, cursor_scale_h;
11719 	int i;
11720 
11721 	/* Overlay cursor not supported on HW before DCN
11722 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
11723 	 * as previous DCN generations, so enable native mode on DCN401 in addition to DCE
11724 	 */
11725 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0 ||
11726 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
11727 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11728 		return 0;
11729 	}
11730 
11731 	/* Init cursor_mode to be the same as current */
11732 	*cursor_mode = dm_crtc_state->cursor_mode;
11733 
11734 	/*
11735 	 * Cursor mode can change if a plane's format changes, scale changes, is
11736 	 * enabled/disabled, or z-order changes.
11737 	 */
11738 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
11739 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
11740 
11741 		/* Only care about planes on this CRTC */
11742 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
11743 			continue;
11744 
11745 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
11746 			cursor_changed = true;
11747 
11748 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
11749 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
11750 		    old_plane_state->fb->format != plane_state->fb->format) {
11751 			consider_mode_change = true;
11752 			break;
11753 		}
11754 
11755 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
11756 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
11757 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
11758 			consider_mode_change = true;
11759 			break;
11760 		}
11761 	}
11762 
11763 	if (!consider_mode_change && !crtc_state->zpos_changed)
11764 		return 0;
11765 
11766 	/*
11767 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
11768 	 * no need to set cursor mode. This avoids needlessly locking the cursor
11769 	 * state.
11770 	 */
11771 	if (!cursor_changed &&
11772 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
11773 		return 0;
11774 	}
11775 
11776 	cursor_state = drm_atomic_get_plane_state(state,
11777 						  crtc_state->crtc->cursor);
11778 	if (IS_ERR(cursor_state))
11779 		return PTR_ERR(cursor_state);
11780 
11781 	/* Cursor is disabled */
11782 	if (!cursor_state->fb)
11783 		return 0;
11784 
11785 	/* For all planes in descending z-order (all of which are below cursor
11786 	 * as per zpos definitions), check their scaling and format
11787 	 */
11788 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
11789 
11790 		/* Only care about non-cursor planes on this CRTC */
11791 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
11792 		    plane->type == DRM_PLANE_TYPE_CURSOR)
11793 			continue;
11794 
11795 		/* Underlying plane is YUV format - use overlay cursor */
11796 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
11797 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11798 			return 0;
11799 		}
11800 
11801 		dm_get_plane_scale(plane_state,
11802 				   &underlying_scale_w, &underlying_scale_h);
11803 		dm_get_plane_scale(cursor_state,
11804 				   &cursor_scale_w, &cursor_scale_h);
11805 
11806 		/* Underlying plane has different scale - use overlay cursor */
11807 		if (cursor_scale_w != underlying_scale_w &&
11808 		    cursor_scale_h != underlying_scale_h) {
11809 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11810 			return 0;
11811 		}
11812 
11813 		/* If this plane covers the whole CRTC, no need to check planes underneath */
11814 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
11815 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
11816 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
11817 			entire_crtc_covered = true;
11818 			break;
11819 		}
11820 	}
11821 
11822 	/* If planes do not cover the entire CRTC, use overlay mode to enable
11823 	 * cursor over holes
11824 	 */
11825 	if (entire_crtc_covered)
11826 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11827 	else
11828 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11829 
11830 	return 0;
11831 }
11832 
11833 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
11834 					    struct drm_atomic_state *state,
11835 					    struct drm_crtc_state *crtc_state)
11836 {
11837 	struct drm_plane *plane;
11838 	struct drm_plane_state *new_plane_state, *old_plane_state;
11839 
11840 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
11841 		new_plane_state = drm_atomic_get_plane_state(state, plane);
11842 		old_plane_state = drm_atomic_get_plane_state(state, plane);
11843 
11844 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
11845 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
11846 			return false;
11847 		}
11848 
11849 		if (old_plane_state->fb && new_plane_state->fb &&
11850 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
11851 			return true;
11852 	}
11853 
11854 	return false;
11855 }
11856 
11857 /**
11858  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
11859  *
11860  * @dev: The DRM device
11861  * @state: The atomic state to commit
11862  *
11863  * Validate that the given atomic state is programmable by DC into hardware.
11864  * This involves constructing a &struct dc_state reflecting the new hardware
11865  * state we wish to commit, then querying DC to see if it is programmable. It's
11866  * important not to modify the existing DC state. Otherwise, atomic_check
11867  * may unexpectedly commit hardware changes.
11868  *
11869  * When validating the DC state, it's important that the right locks are
11870  * acquired. For full updates case which removes/adds/updates streams on one
11871  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
11872  * that any such full update commit will wait for completion of any outstanding
11873  * flip using DRMs synchronization events.
11874  *
11875  * Note that DM adds the affected connectors for all CRTCs in state, when that
11876  * might not seem necessary. This is because DC stream creation requires the
11877  * DC sink, which is tied to the DRM connector state. Cleaning this up should
11878  * be possible but non-trivial - a possible TODO item.
11879  *
11880  * Return: -Error code if validation failed.
11881  */
11882 static int amdgpu_dm_atomic_check(struct drm_device *dev,
11883 				  struct drm_atomic_state *state)
11884 {
11885 	struct amdgpu_device *adev = drm_to_adev(dev);
11886 	struct dm_atomic_state *dm_state = NULL;
11887 	struct dc *dc = adev->dm.dc;
11888 	struct drm_connector *connector;
11889 	struct drm_connector_state *old_con_state, *new_con_state;
11890 	struct drm_crtc *crtc;
11891 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11892 	struct drm_plane *plane;
11893 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
11894 	enum dc_status status;
11895 	int ret, i;
11896 	bool lock_and_validation_needed = false;
11897 	bool is_top_most_overlay = true;
11898 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11899 	struct drm_dp_mst_topology_mgr *mgr;
11900 	struct drm_dp_mst_topology_state *mst_state;
11901 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
11902 
11903 	trace_amdgpu_dm_atomic_check_begin(state);
11904 
11905 	ret = drm_atomic_helper_check_modeset(dev, state);
11906 	if (ret) {
11907 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
11908 		goto fail;
11909 	}
11910 
11911 	/* Check connector changes */
11912 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11913 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11914 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11915 
11916 		/* Skip connectors that are disabled or part of modeset already. */
11917 		if (!new_con_state->crtc)
11918 			continue;
11919 
11920 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
11921 		if (IS_ERR(new_crtc_state)) {
11922 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
11923 			ret = PTR_ERR(new_crtc_state);
11924 			goto fail;
11925 		}
11926 
11927 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
11928 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
11929 			new_crtc_state->connectors_changed = true;
11930 	}
11931 
11932 	if (dc_resource_is_dsc_encoding_supported(dc)) {
11933 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11934 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11935 				ret = add_affected_mst_dsc_crtcs(state, crtc);
11936 				if (ret) {
11937 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
11938 					goto fail;
11939 				}
11940 			}
11941 		}
11942 	}
11943 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11944 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11945 
11946 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
11947 		    !new_crtc_state->color_mgmt_changed &&
11948 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
11949 			dm_old_crtc_state->dsc_force_changed == false)
11950 			continue;
11951 
11952 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
11953 		if (ret) {
11954 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
11955 			goto fail;
11956 		}
11957 
11958 		if (!new_crtc_state->enable)
11959 			continue;
11960 
11961 		ret = drm_atomic_add_affected_connectors(state, crtc);
11962 		if (ret) {
11963 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
11964 			goto fail;
11965 		}
11966 
11967 		ret = drm_atomic_add_affected_planes(state, crtc);
11968 		if (ret) {
11969 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
11970 			goto fail;
11971 		}
11972 
11973 		if (dm_old_crtc_state->dsc_force_changed)
11974 			new_crtc_state->mode_changed = true;
11975 	}
11976 
11977 	/*
11978 	 * Add all primary and overlay planes on the CRTC to the state
11979 	 * whenever a plane is enabled to maintain correct z-ordering
11980 	 * and to enable fast surface updates.
11981 	 */
11982 	drm_for_each_crtc(crtc, dev) {
11983 		bool modified = false;
11984 
11985 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
11986 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
11987 				continue;
11988 
11989 			if (new_plane_state->crtc == crtc ||
11990 			    old_plane_state->crtc == crtc) {
11991 				modified = true;
11992 				break;
11993 			}
11994 		}
11995 
11996 		if (!modified)
11997 			continue;
11998 
11999 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12000 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12001 				continue;
12002 
12003 			new_plane_state =
12004 				drm_atomic_get_plane_state(state, plane);
12005 
12006 			if (IS_ERR(new_plane_state)) {
12007 				ret = PTR_ERR(new_plane_state);
12008 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12009 				goto fail;
12010 			}
12011 		}
12012 	}
12013 
12014 	/*
12015 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12016 	 * hw plane on which to enable the hw cursor (see
12017 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12018 	 * atomic state, so call drm helper to normalize zpos.
12019 	 */
12020 	ret = drm_atomic_normalize_zpos(dev, state);
12021 	if (ret) {
12022 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12023 		goto fail;
12024 	}
12025 
12026 	/*
12027 	 * Determine whether cursors on each CRTC should be enabled in native or
12028 	 * overlay mode.
12029 	 */
12030 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12031 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12032 
12033 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12034 					      &dm_new_crtc_state->cursor_mode);
12035 		if (ret) {
12036 			drm_dbg(dev, "Failed to determine cursor mode\n");
12037 			goto fail;
12038 		}
12039 
12040 		/*
12041 		 * If overlay cursor is needed, DC cannot go through the
12042 		 * native cursor update path. All enabled planes on the CRTC
12043 		 * need to be added for DC to not disable a plane by mistake
12044 		 */
12045 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12046 			ret = drm_atomic_add_affected_planes(state, crtc);
12047 			if (ret)
12048 				goto fail;
12049 		}
12050 	}
12051 
12052 	/* Remove exiting planes if they are modified */
12053 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12054 
12055 		ret = dm_update_plane_state(dc, state, plane,
12056 					    old_plane_state,
12057 					    new_plane_state,
12058 					    false,
12059 					    &lock_and_validation_needed,
12060 					    &is_top_most_overlay);
12061 		if (ret) {
12062 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12063 			goto fail;
12064 		}
12065 	}
12066 
12067 	/* Disable all crtcs which require disable */
12068 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12069 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12070 					   old_crtc_state,
12071 					   new_crtc_state,
12072 					   false,
12073 					   &lock_and_validation_needed);
12074 		if (ret) {
12075 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12076 			goto fail;
12077 		}
12078 	}
12079 
12080 	/* Enable all crtcs which require enable */
12081 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12082 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12083 					   old_crtc_state,
12084 					   new_crtc_state,
12085 					   true,
12086 					   &lock_and_validation_needed);
12087 		if (ret) {
12088 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12089 			goto fail;
12090 		}
12091 	}
12092 
12093 	/* Add new/modified planes */
12094 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12095 		ret = dm_update_plane_state(dc, state, plane,
12096 					    old_plane_state,
12097 					    new_plane_state,
12098 					    true,
12099 					    &lock_and_validation_needed,
12100 					    &is_top_most_overlay);
12101 		if (ret) {
12102 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12103 			goto fail;
12104 		}
12105 	}
12106 
12107 #if defined(CONFIG_DRM_AMD_DC_FP)
12108 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12109 		ret = pre_validate_dsc(state, &dm_state, vars);
12110 		if (ret != 0)
12111 			goto fail;
12112 	}
12113 #endif
12114 
12115 	/* Run this here since we want to validate the streams we created */
12116 	ret = drm_atomic_helper_check_planes(dev, state);
12117 	if (ret) {
12118 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12119 		goto fail;
12120 	}
12121 
12122 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12123 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12124 		if (dm_new_crtc_state->mpo_requested)
12125 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12126 	}
12127 
12128 	/* Check cursor restrictions */
12129 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12130 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12131 		int is_rotated, is_scaled;
12132 
12133 		/* Overlay cusor not subject to native cursor restrictions */
12134 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12135 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12136 			continue;
12137 
12138 		/* Check if rotation or scaling is enabled on DCN401 */
12139 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12140 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12141 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12142 
12143 			is_rotated = new_cursor_state &&
12144 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12145 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12146 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12147 
12148 			if (is_rotated || is_scaled) {
12149 				drm_dbg_driver(
12150 					crtc->dev,
12151 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12152 					crtc->base.id, crtc->name);
12153 				ret = -EINVAL;
12154 				goto fail;
12155 			}
12156 		}
12157 
12158 		/* If HW can only do native cursor, check restrictions again */
12159 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12160 					      &required_cursor_mode);
12161 		if (ret) {
12162 			drm_dbg_driver(crtc->dev,
12163 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12164 				       crtc->base.id, crtc->name);
12165 			goto fail;
12166 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12167 			drm_dbg_driver(crtc->dev,
12168 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12169 				       crtc->base.id, crtc->name);
12170 			ret = -EINVAL;
12171 			goto fail;
12172 		}
12173 	}
12174 
12175 	if (state->legacy_cursor_update) {
12176 		/*
12177 		 * This is a fast cursor update coming from the plane update
12178 		 * helper, check if it can be done asynchronously for better
12179 		 * performance.
12180 		 */
12181 		state->async_update =
12182 			!drm_atomic_helper_async_check(dev, state);
12183 
12184 		/*
12185 		 * Skip the remaining global validation if this is an async
12186 		 * update. Cursor updates can be done without affecting
12187 		 * state or bandwidth calcs and this avoids the performance
12188 		 * penalty of locking the private state object and
12189 		 * allocating a new dc_state.
12190 		 */
12191 		if (state->async_update)
12192 			return 0;
12193 	}
12194 
12195 	/* Check scaling and underscan changes*/
12196 	/* TODO Removed scaling changes validation due to inability to commit
12197 	 * new stream into context w\o causing full reset. Need to
12198 	 * decide how to handle.
12199 	 */
12200 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12201 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12202 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12203 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12204 
12205 		/* Skip any modesets/resets */
12206 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12207 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12208 			continue;
12209 
12210 		/* Skip any thing not scale or underscan changes */
12211 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12212 			continue;
12213 
12214 		lock_and_validation_needed = true;
12215 	}
12216 
12217 	/* set the slot info for each mst_state based on the link encoding format */
12218 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12219 		struct amdgpu_dm_connector *aconnector;
12220 		struct drm_connector *connector;
12221 		struct drm_connector_list_iter iter;
12222 		u8 link_coding_cap;
12223 
12224 		drm_connector_list_iter_begin(dev, &iter);
12225 		drm_for_each_connector_iter(connector, &iter) {
12226 			if (connector->index == mst_state->mgr->conn_base_id) {
12227 				aconnector = to_amdgpu_dm_connector(connector);
12228 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12229 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12230 
12231 				break;
12232 			}
12233 		}
12234 		drm_connector_list_iter_end(&iter);
12235 	}
12236 
12237 	/**
12238 	 * Streams and planes are reset when there are changes that affect
12239 	 * bandwidth. Anything that affects bandwidth needs to go through
12240 	 * DC global validation to ensure that the configuration can be applied
12241 	 * to hardware.
12242 	 *
12243 	 * We have to currently stall out here in atomic_check for outstanding
12244 	 * commits to finish in this case because our IRQ handlers reference
12245 	 * DRM state directly - we can end up disabling interrupts too early
12246 	 * if we don't.
12247 	 *
12248 	 * TODO: Remove this stall and drop DM state private objects.
12249 	 */
12250 	if (lock_and_validation_needed) {
12251 		ret = dm_atomic_get_state(state, &dm_state);
12252 		if (ret) {
12253 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12254 			goto fail;
12255 		}
12256 
12257 		ret = do_aquire_global_lock(dev, state);
12258 		if (ret) {
12259 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12260 			goto fail;
12261 		}
12262 
12263 #if defined(CONFIG_DRM_AMD_DC_FP)
12264 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12265 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12266 			if (ret) {
12267 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12268 				ret = -EINVAL;
12269 				goto fail;
12270 			}
12271 		}
12272 #endif
12273 
12274 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12275 		if (ret) {
12276 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12277 			goto fail;
12278 		}
12279 
12280 		/*
12281 		 * Perform validation of MST topology in the state:
12282 		 * We need to perform MST atomic check before calling
12283 		 * dc_validate_global_state(), or there is a chance
12284 		 * to get stuck in an infinite loop and hang eventually.
12285 		 */
12286 		ret = drm_dp_mst_atomic_check(state);
12287 		if (ret) {
12288 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12289 			goto fail;
12290 		}
12291 		status = dc_validate_global_state(dc, dm_state->context, true);
12292 		if (status != DC_OK) {
12293 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12294 				       dc_status_to_str(status), status);
12295 			ret = -EINVAL;
12296 			goto fail;
12297 		}
12298 	} else {
12299 		/*
12300 		 * The commit is a fast update. Fast updates shouldn't change
12301 		 * the DC context, affect global validation, and can have their
12302 		 * commit work done in parallel with other commits not touching
12303 		 * the same resource. If we have a new DC context as part of
12304 		 * the DM atomic state from validation we need to free it and
12305 		 * retain the existing one instead.
12306 		 *
12307 		 * Furthermore, since the DM atomic state only contains the DC
12308 		 * context and can safely be annulled, we can free the state
12309 		 * and clear the associated private object now to free
12310 		 * some memory and avoid a possible use-after-free later.
12311 		 */
12312 
12313 		for (i = 0; i < state->num_private_objs; i++) {
12314 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12315 
12316 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12317 				int j = state->num_private_objs-1;
12318 
12319 				dm_atomic_destroy_state(obj,
12320 						state->private_objs[i].state);
12321 
12322 				/* If i is not at the end of the array then the
12323 				 * last element needs to be moved to where i was
12324 				 * before the array can safely be truncated.
12325 				 */
12326 				if (i != j)
12327 					state->private_objs[i] =
12328 						state->private_objs[j];
12329 
12330 				state->private_objs[j].ptr = NULL;
12331 				state->private_objs[j].state = NULL;
12332 				state->private_objs[j].old_state = NULL;
12333 				state->private_objs[j].new_state = NULL;
12334 
12335 				state->num_private_objs = j;
12336 				break;
12337 			}
12338 		}
12339 	}
12340 
12341 	/* Store the overall update type for use later in atomic check. */
12342 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12343 		struct dm_crtc_state *dm_new_crtc_state =
12344 			to_dm_crtc_state(new_crtc_state);
12345 
12346 		/*
12347 		 * Only allow async flips for fast updates that don't change
12348 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12349 		 */
12350 		if (new_crtc_state->async_flip &&
12351 		    (lock_and_validation_needed ||
12352 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12353 			drm_dbg_atomic(crtc->dev,
12354 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12355 				       crtc->base.id, crtc->name);
12356 			ret = -EINVAL;
12357 			goto fail;
12358 		}
12359 
12360 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12361 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12362 	}
12363 
12364 	/* Must be success */
12365 	WARN_ON(ret);
12366 
12367 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12368 
12369 	return ret;
12370 
12371 fail:
12372 	if (ret == -EDEADLK)
12373 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12374 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12375 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12376 	else
12377 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12378 
12379 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12380 
12381 	return ret;
12382 }
12383 
12384 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12385 		unsigned int offset,
12386 		unsigned int total_length,
12387 		u8 *data,
12388 		unsigned int length,
12389 		struct amdgpu_hdmi_vsdb_info *vsdb)
12390 {
12391 	bool res;
12392 	union dmub_rb_cmd cmd;
12393 	struct dmub_cmd_send_edid_cea *input;
12394 	struct dmub_cmd_edid_cea_output *output;
12395 
12396 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12397 		return false;
12398 
12399 	memset(&cmd, 0, sizeof(cmd));
12400 
12401 	input = &cmd.edid_cea.data.input;
12402 
12403 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12404 	cmd.edid_cea.header.sub_type = 0;
12405 	cmd.edid_cea.header.payload_bytes =
12406 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12407 	input->offset = offset;
12408 	input->length = length;
12409 	input->cea_total_length = total_length;
12410 	memcpy(input->payload, data, length);
12411 
12412 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12413 	if (!res) {
12414 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
12415 		return false;
12416 	}
12417 
12418 	output = &cmd.edid_cea.data.output;
12419 
12420 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
12421 		if (!output->ack.success) {
12422 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
12423 					output->ack.offset);
12424 		}
12425 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
12426 		if (!output->amd_vsdb.vsdb_found)
12427 			return false;
12428 
12429 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
12430 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
12431 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
12432 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
12433 	} else {
12434 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
12435 		return false;
12436 	}
12437 
12438 	return true;
12439 }
12440 
12441 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
12442 		u8 *edid_ext, int len,
12443 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12444 {
12445 	int i;
12446 
12447 	/* send extension block to DMCU for parsing */
12448 	for (i = 0; i < len; i += 8) {
12449 		bool res;
12450 		int offset;
12451 
12452 		/* send 8 bytes a time */
12453 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
12454 			return false;
12455 
12456 		if (i+8 == len) {
12457 			/* EDID block sent completed, expect result */
12458 			int version, min_rate, max_rate;
12459 
12460 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
12461 			if (res) {
12462 				/* amd vsdb found */
12463 				vsdb_info->freesync_supported = 1;
12464 				vsdb_info->amd_vsdb_version = version;
12465 				vsdb_info->min_refresh_rate_hz = min_rate;
12466 				vsdb_info->max_refresh_rate_hz = max_rate;
12467 				return true;
12468 			}
12469 			/* not amd vsdb */
12470 			return false;
12471 		}
12472 
12473 		/* check for ack*/
12474 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
12475 		if (!res)
12476 			return false;
12477 	}
12478 
12479 	return false;
12480 }
12481 
12482 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
12483 		u8 *edid_ext, int len,
12484 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12485 {
12486 	int i;
12487 
12488 	/* send extension block to DMCU for parsing */
12489 	for (i = 0; i < len; i += 8) {
12490 		/* send 8 bytes a time */
12491 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
12492 			return false;
12493 	}
12494 
12495 	return vsdb_info->freesync_supported;
12496 }
12497 
12498 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
12499 		u8 *edid_ext, int len,
12500 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12501 {
12502 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
12503 	bool ret;
12504 
12505 	mutex_lock(&adev->dm.dc_lock);
12506 	if (adev->dm.dmub_srv)
12507 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
12508 	else
12509 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
12510 	mutex_unlock(&adev->dm.dc_lock);
12511 	return ret;
12512 }
12513 
12514 static void parse_edid_displayid_vrr(struct drm_connector *connector,
12515 				     const struct edid *edid)
12516 {
12517 	u8 *edid_ext = NULL;
12518 	int i;
12519 	int j = 0;
12520 	u16 min_vfreq;
12521 	u16 max_vfreq;
12522 
12523 	if (edid == NULL || edid->extensions == 0)
12524 		return;
12525 
12526 	/* Find DisplayID extension */
12527 	for (i = 0; i < edid->extensions; i++) {
12528 		edid_ext = (void *)(edid + (i + 1));
12529 		if (edid_ext[0] == DISPLAYID_EXT)
12530 			break;
12531 	}
12532 
12533 	if (edid_ext == NULL)
12534 		return;
12535 
12536 	while (j < EDID_LENGTH) {
12537 		/* Get dynamic video timing range from DisplayID if available */
12538 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
12539 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
12540 			min_vfreq = edid_ext[j+9];
12541 			if (edid_ext[j+1] & 7)
12542 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
12543 			else
12544 				max_vfreq = edid_ext[j+10];
12545 
12546 			if (max_vfreq && min_vfreq) {
12547 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
12548 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
12549 
12550 				return;
12551 			}
12552 		}
12553 		j++;
12554 	}
12555 }
12556 
12557 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12558 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
12559 {
12560 	u8 *edid_ext = NULL;
12561 	int i;
12562 	int j = 0;
12563 
12564 	if (edid == NULL || edid->extensions == 0)
12565 		return -ENODEV;
12566 
12567 	/* Find DisplayID extension */
12568 	for (i = 0; i < edid->extensions; i++) {
12569 		edid_ext = (void *)(edid + (i + 1));
12570 		if (edid_ext[0] == DISPLAYID_EXT)
12571 			break;
12572 	}
12573 
12574 	while (j < EDID_LENGTH - sizeof(struct amd_vsdb_block)) {
12575 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
12576 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
12577 
12578 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
12579 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
12580 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
12581 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
12582 			DRM_DEBUG_KMS("Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
12583 
12584 			return true;
12585 		}
12586 		j++;
12587 	}
12588 
12589 	return false;
12590 }
12591 
12592 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12593 			       const struct edid *edid,
12594 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
12595 {
12596 	u8 *edid_ext = NULL;
12597 	int i;
12598 	bool valid_vsdb_found = false;
12599 
12600 	/*----- drm_find_cea_extension() -----*/
12601 	/* No EDID or EDID extensions */
12602 	if (edid == NULL || edid->extensions == 0)
12603 		return -ENODEV;
12604 
12605 	/* Find CEA extension */
12606 	for (i = 0; i < edid->extensions; i++) {
12607 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
12608 		if (edid_ext[0] == CEA_EXT)
12609 			break;
12610 	}
12611 
12612 	if (i == edid->extensions)
12613 		return -ENODEV;
12614 
12615 	/*----- cea_db_offsets() -----*/
12616 	if (edid_ext[0] != CEA_EXT)
12617 		return -ENODEV;
12618 
12619 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
12620 
12621 	return valid_vsdb_found ? i : -ENODEV;
12622 }
12623 
12624 /**
12625  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
12626  *
12627  * @connector: Connector to query.
12628  * @drm_edid: DRM EDID from monitor
12629  *
12630  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
12631  * track of some of the display information in the internal data struct used by
12632  * amdgpu_dm. This function checks which type of connector we need to set the
12633  * FreeSync parameters.
12634  */
12635 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
12636 				    const struct drm_edid *drm_edid)
12637 {
12638 	int i = 0;
12639 	struct amdgpu_dm_connector *amdgpu_dm_connector =
12640 			to_amdgpu_dm_connector(connector);
12641 	struct dm_connector_state *dm_con_state = NULL;
12642 	struct dc_sink *sink;
12643 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
12644 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
12645 	const struct edid *edid;
12646 	bool freesync_capable = false;
12647 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
12648 
12649 	if (!connector->state) {
12650 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
12651 		goto update;
12652 	}
12653 
12654 	sink = amdgpu_dm_connector->dc_sink ?
12655 		amdgpu_dm_connector->dc_sink :
12656 		amdgpu_dm_connector->dc_em_sink;
12657 
12658 	drm_edid_connector_update(connector, drm_edid);
12659 
12660 	if (!drm_edid || !sink) {
12661 		dm_con_state = to_dm_connector_state(connector->state);
12662 
12663 		amdgpu_dm_connector->min_vfreq = 0;
12664 		amdgpu_dm_connector->max_vfreq = 0;
12665 		freesync_capable = false;
12666 
12667 		goto update;
12668 	}
12669 
12670 	dm_con_state = to_dm_connector_state(connector->state);
12671 
12672 	if (!adev->dm.freesync_module)
12673 		goto update;
12674 
12675 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
12676 
12677 	/* Some eDP panels only have the refresh rate range info in DisplayID */
12678 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
12679 	     connector->display_info.monitor_range.max_vfreq == 0))
12680 		parse_edid_displayid_vrr(connector, edid);
12681 
12682 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
12683 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
12684 		if (amdgpu_dm_connector->dc_link &&
12685 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
12686 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
12687 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
12688 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12689 				freesync_capable = true;
12690 		}
12691 
12692 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12693 
12694 		if (vsdb_info.replay_mode) {
12695 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
12696 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
12697 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
12698 		}
12699 
12700 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
12701 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12702 		if (i >= 0 && vsdb_info.freesync_supported) {
12703 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12704 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12705 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12706 				freesync_capable = true;
12707 
12708 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12709 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12710 		}
12711 	}
12712 
12713 	if (amdgpu_dm_connector->dc_link)
12714 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
12715 
12716 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
12717 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12718 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
12719 
12720 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
12721 			amdgpu_dm_connector->as_type = as_type;
12722 			amdgpu_dm_connector->vsdb_info = vsdb_info;
12723 
12724 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12725 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12726 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12727 				freesync_capable = true;
12728 
12729 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12730 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12731 		}
12732 	}
12733 
12734 update:
12735 	if (dm_con_state)
12736 		dm_con_state->freesync_capable = freesync_capable;
12737 
12738 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
12739 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
12740 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
12741 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
12742 	}
12743 
12744 	if (connector->vrr_capable_property)
12745 		drm_connector_set_vrr_capable_property(connector,
12746 						       freesync_capable);
12747 }
12748 
12749 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
12750 {
12751 	struct amdgpu_device *adev = drm_to_adev(dev);
12752 	struct dc *dc = adev->dm.dc;
12753 	int i;
12754 
12755 	mutex_lock(&adev->dm.dc_lock);
12756 	if (dc->current_state) {
12757 		for (i = 0; i < dc->current_state->stream_count; ++i)
12758 			dc->current_state->streams[i]
12759 				->triggered_crtc_reset.enabled =
12760 				adev->dm.force_timing_sync;
12761 
12762 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
12763 		dc_trigger_sync(dc, dc->current_state);
12764 	}
12765 	mutex_unlock(&adev->dm.dc_lock);
12766 }
12767 
12768 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
12769 {
12770 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
12771 		dc_exit_ips_for_hw_access(dc);
12772 }
12773 
12774 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
12775 		       u32 value, const char *func_name)
12776 {
12777 #ifdef DM_CHECK_ADDR_0
12778 	if (address == 0) {
12779 		drm_err(adev_to_drm(ctx->driver_context),
12780 			"invalid register write. address = 0");
12781 		return;
12782 	}
12783 #endif
12784 
12785 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12786 	cgs_write_register(ctx->cgs_device, address, value);
12787 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
12788 }
12789 
12790 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
12791 			  const char *func_name)
12792 {
12793 	u32 value;
12794 #ifdef DM_CHECK_ADDR_0
12795 	if (address == 0) {
12796 		drm_err(adev_to_drm(ctx->driver_context),
12797 			"invalid register read; address = 0\n");
12798 		return 0;
12799 	}
12800 #endif
12801 
12802 	if (ctx->dmub_srv &&
12803 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
12804 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
12805 		ASSERT(false);
12806 		return 0;
12807 	}
12808 
12809 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12810 
12811 	value = cgs_read_register(ctx->cgs_device, address);
12812 
12813 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
12814 
12815 	return value;
12816 }
12817 
12818 int amdgpu_dm_process_dmub_aux_transfer_sync(
12819 		struct dc_context *ctx,
12820 		unsigned int link_index,
12821 		struct aux_payload *payload,
12822 		enum aux_return_code_type *operation_result)
12823 {
12824 	struct amdgpu_device *adev = ctx->driver_context;
12825 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
12826 	int ret = -1;
12827 
12828 	mutex_lock(&adev->dm.dpia_aux_lock);
12829 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
12830 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
12831 		goto out;
12832 	}
12833 
12834 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12835 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
12836 		*operation_result = AUX_RET_ERROR_TIMEOUT;
12837 		goto out;
12838 	}
12839 
12840 	if (p_notify->result != AUX_RET_SUCCESS) {
12841 		/*
12842 		 * Transient states before tunneling is enabled could
12843 		 * lead to this error. We can ignore this for now.
12844 		 */
12845 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
12846 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
12847 					payload->address, payload->length,
12848 					p_notify->result);
12849 		}
12850 		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
12851 		goto out;
12852 	}
12853 
12854 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
12855 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
12856 		/* The reply is stored in the top nibble of the command. */
12857 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
12858 
12859 	/*write req may receive a byte indicating partially written number as well*/
12860 	if (p_notify->aux_reply.length)
12861 		memcpy(payload->data, p_notify->aux_reply.data,
12862 				p_notify->aux_reply.length);
12863 
12864 	/* success */
12865 	ret = p_notify->aux_reply.length;
12866 	*operation_result = p_notify->result;
12867 out:
12868 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
12869 	mutex_unlock(&adev->dm.dpia_aux_lock);
12870 	return ret;
12871 }
12872 
12873 static void abort_fused_io(
12874 		struct dc_context *ctx,
12875 		const struct dmub_cmd_fused_request *request
12876 )
12877 {
12878 	union dmub_rb_cmd command = { 0 };
12879 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
12880 
12881 	io->header.type = DMUB_CMD__FUSED_IO;
12882 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
12883 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
12884 	io->request = *request;
12885 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
12886 }
12887 
12888 static bool execute_fused_io(
12889 		struct amdgpu_device *dev,
12890 		struct dc_context *ctx,
12891 		union dmub_rb_cmd *commands,
12892 		uint8_t count,
12893 		uint32_t timeout_us
12894 )
12895 {
12896 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
12897 
12898 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
12899 		return false;
12900 
12901 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
12902 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
12903 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
12904 			&& first->header.ret_status
12905 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
12906 
12907 	if (!result)
12908 		return false;
12909 
12910 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
12911 		reinit_completion(&sync->replied);
12912 
12913 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
12914 
12915 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
12916 
12917 		if (reply->identifier == first->request.identifier) {
12918 			first->request = *reply;
12919 			return true;
12920 		}
12921 	}
12922 
12923 	reinit_completion(&sync->replied);
12924 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
12925 	abort_fused_io(ctx, &first->request);
12926 	return false;
12927 }
12928 
12929 bool amdgpu_dm_execute_fused_io(
12930 		struct amdgpu_device *dev,
12931 		struct dc_link *link,
12932 		union dmub_rb_cmd *commands,
12933 		uint8_t count,
12934 		uint32_t timeout_us)
12935 {
12936 	struct amdgpu_display_manager *dm = &dev->dm;
12937 
12938 	mutex_lock(&dm->dpia_aux_lock);
12939 
12940 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
12941 
12942 	mutex_unlock(&dm->dpia_aux_lock);
12943 	return result;
12944 }
12945 
12946 int amdgpu_dm_process_dmub_set_config_sync(
12947 		struct dc_context *ctx,
12948 		unsigned int link_index,
12949 		struct set_config_cmd_payload *payload,
12950 		enum set_config_status *operation_result)
12951 {
12952 	struct amdgpu_device *adev = ctx->driver_context;
12953 	bool is_cmd_complete;
12954 	int ret;
12955 
12956 	mutex_lock(&adev->dm.dpia_aux_lock);
12957 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
12958 			link_index, payload, adev->dm.dmub_notify);
12959 
12960 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12961 		ret = 0;
12962 		*operation_result = adev->dm.dmub_notify->sc_status;
12963 	} else {
12964 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
12965 		ret = -1;
12966 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
12967 	}
12968 
12969 	if (!is_cmd_complete)
12970 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
12971 	mutex_unlock(&adev->dm.dpia_aux_lock);
12972 	return ret;
12973 }
12974 
12975 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
12976 {
12977 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
12978 }
12979 
12980 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)
12981 {
12982 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
12983 }
12984 
12985 void dm_acpi_process_phy_transition_interlock(
12986 	const struct dc_context *ctx,
12987 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
12988 {
12989 	// Not yet implemented
12990 }
12991