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