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