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