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