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