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