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