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