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