xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision df4c0441c41a1d3d5edcfec61c8e3be3513c412a)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 /**
162  * DOC: overview
163  *
164  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
165  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
166  * requests into DC requests, and DC responses into DRM responses.
167  *
168  * The root control structure is &struct amdgpu_display_manager.
169  */
170 
171 /* basic init/fini API */
172 static int amdgpu_dm_init(struct amdgpu_device *adev);
173 static void amdgpu_dm_fini(struct amdgpu_device *adev);
174 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
175 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
176 static struct amdgpu_i2c_adapter *
177 create_i2c(struct ddc_service *ddc_service, bool oem);
178 
179 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
180 {
181 	switch (link->dpcd_caps.dongle_type) {
182 	case DISPLAY_DONGLE_NONE:
183 		return DRM_MODE_SUBCONNECTOR_Native;
184 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
185 		return DRM_MODE_SUBCONNECTOR_VGA;
186 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
187 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
188 		return DRM_MODE_SUBCONNECTOR_DVID;
189 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_HDMIA;
192 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
193 	default:
194 		return DRM_MODE_SUBCONNECTOR_Unknown;
195 	}
196 }
197 
198 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
199 {
200 	struct dc_link *link = aconnector->dc_link;
201 	struct drm_connector *connector = &aconnector->base;
202 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
203 
204 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
205 		return;
206 
207 	if (aconnector->dc_sink)
208 		subconnector = get_subconnector_type(link);
209 
210 	drm_object_property_set_value(&connector->base,
211 			connector->dev->mode_config.dp_subconnector_property,
212 			subconnector);
213 }
214 
215 /*
216  * initializes drm_device display related structures, based on the information
217  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
218  * drm_encoder, drm_mode_config
219  *
220  * Returns 0 on success
221  */
222 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
223 /* removes and deallocates the drm structures, created by the above function */
224 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
225 
226 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
227 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
228 				    u32 link_index,
229 				    struct amdgpu_encoder *amdgpu_encoder);
230 static int amdgpu_dm_encoder_init(struct drm_device *dev,
231 				  struct amdgpu_encoder *aencoder,
232 				  uint32_t link_index);
233 
234 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
235 
236 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state);
237 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
238 
239 static int amdgpu_dm_atomic_check(struct drm_device *dev,
240 				  struct drm_atomic_state *state);
241 
242 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
243 static void handle_hpd_rx_irq(void *param);
244 
245 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
246 					 int bl_idx,
247 					 u32 user_brightness);
248 
249 static bool
250 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
251 				 struct drm_crtc_state *new_crtc_state);
252 /*
253  * dm_vblank_get_counter
254  *
255  * @brief
256  * Get counter for number of vertical blanks
257  *
258  * @param
259  * struct amdgpu_device *adev - [in] desired amdgpu device
260  * int disp_idx - [in] which CRTC to get the counter from
261  *
262  * @return
263  * Counter for vertical blanks
264  */
265 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
266 {
267 	struct amdgpu_crtc *acrtc = NULL;
268 
269 	if (crtc >= adev->mode_info.num_crtc)
270 		return 0;
271 
272 	acrtc = adev->mode_info.crtcs[crtc];
273 
274 	if (!acrtc->dm_irq_params.stream) {
275 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
276 			  crtc);
277 		return 0;
278 	}
279 
280 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
281 }
282 
283 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
284 				  u32 *vbl, u32 *position)
285 {
286 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
287 	struct amdgpu_crtc *acrtc = NULL;
288 	struct dc *dc = adev->dm.dc;
289 
290 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
291 		return -EINVAL;
292 
293 	acrtc = adev->mode_info.crtcs[crtc];
294 
295 	if (!acrtc->dm_irq_params.stream) {
296 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
297 			  crtc);
298 		return 0;
299 	}
300 
301 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
302 		dc_allow_idle_optimizations(dc, false);
303 
304 	/*
305 	 * TODO rework base driver to use values directly.
306 	 * for now parse it back into reg-format
307 	 */
308 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
309 				 &v_blank_start,
310 				 &v_blank_end,
311 				 &h_position,
312 				 &v_position);
313 
314 	*position = v_position | (h_position << 16);
315 	*vbl = v_blank_start | (v_blank_end << 16);
316 
317 	return 0;
318 }
319 
320 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
321 {
322 	/* XXX todo */
323 	return true;
324 }
325 
326 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
327 {
328 	/* XXX todo */
329 	return 0;
330 }
331 
332 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
333 {
334 	return false;
335 }
336 
337 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
338 {
339 	/* XXX todo */
340 	return 0;
341 }
342 
343 static struct amdgpu_crtc *
344 get_crtc_by_otg_inst(struct amdgpu_device *adev,
345 		     int otg_inst)
346 {
347 	struct drm_device *dev = adev_to_drm(adev);
348 	struct drm_crtc *crtc;
349 	struct amdgpu_crtc *amdgpu_crtc;
350 
351 	if (WARN_ON(otg_inst == -1))
352 		return adev->mode_info.crtcs[0];
353 
354 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
355 		amdgpu_crtc = to_amdgpu_crtc(crtc);
356 
357 		if (amdgpu_crtc->otg_inst == otg_inst)
358 			return amdgpu_crtc;
359 	}
360 
361 	return NULL;
362 }
363 
364 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
365 					      struct dm_crtc_state *new_state)
366 {
367 	if (new_state->stream->adjust.timing_adjust_pending)
368 		return true;
369 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
370 		return true;
371 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
372 		return true;
373 	else
374 		return false;
375 }
376 
377 /*
378  * DC will program planes with their z-order determined by their ordering
379  * in the dc_surface_updates array. This comparator is used to sort them
380  * by descending zpos.
381  */
382 static int dm_plane_layer_index_cmp(const void *a, const void *b)
383 {
384 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
385 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
386 
387 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
388 	return sb->surface->layer_index - sa->surface->layer_index;
389 }
390 
391 /**
392  * update_planes_and_stream_adapter() - Send planes to be updated in DC
393  *
394  * DC has a generic way to update planes and stream via
395  * dc_update_planes_and_stream function; however, DM might need some
396  * adjustments and preparation before calling it. This function is a wrapper
397  * for the dc_update_planes_and_stream that does any required configuration
398  * before passing control to DC.
399  *
400  * @dc: Display Core control structure
401  * @update_type: specify whether it is FULL/MEDIUM/FAST update
402  * @planes_count: planes count to update
403  * @stream: stream state
404  * @stream_update: stream update
405  * @array_of_surface_update: dc surface update pointer
406  *
407  */
408 static inline bool update_planes_and_stream_adapter(struct dc *dc,
409 						    int update_type,
410 						    int planes_count,
411 						    struct dc_stream_state *stream,
412 						    struct dc_stream_update *stream_update,
413 						    struct dc_surface_update *array_of_surface_update)
414 {
415 	sort(array_of_surface_update, planes_count,
416 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
417 
418 	/*
419 	 * Previous frame finished and HW is ready for optimization.
420 	 */
421 	dc_post_update_surfaces_to_stream(dc);
422 
423 	return dc_update_planes_and_stream(dc,
424 					   array_of_surface_update,
425 					   planes_count,
426 					   stream,
427 					   stream_update);
428 }
429 
430 /**
431  * dm_pflip_high_irq() - Handle pageflip interrupt
432  * @interrupt_params: ignored
433  *
434  * Handles the pageflip interrupt by notifying all interested parties
435  * that the pageflip has been completed.
436  */
437 static void dm_pflip_high_irq(void *interrupt_params)
438 {
439 	struct amdgpu_crtc *amdgpu_crtc;
440 	struct common_irq_params *irq_params = interrupt_params;
441 	struct amdgpu_device *adev = irq_params->adev;
442 	struct drm_device *dev = adev_to_drm(adev);
443 	unsigned long flags;
444 	struct drm_pending_vblank_event *e;
445 	u32 vpos, hpos, v_blank_start, v_blank_end;
446 	bool vrr_active;
447 
448 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
449 
450 	/* IRQ could occur when in initial stage */
451 	/* TODO work and BO cleanup */
452 	if (amdgpu_crtc == NULL) {
453 		drm_dbg_state(dev, "CRTC is null, returning.\n");
454 		return;
455 	}
456 
457 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
458 
459 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
460 		drm_dbg_state(dev,
461 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
462 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
463 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
464 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
465 		return;
466 	}
467 
468 	/* page flip completed. */
469 	e = amdgpu_crtc->event;
470 	amdgpu_crtc->event = NULL;
471 
472 	WARN_ON(!e);
473 
474 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
475 
476 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
477 	if (!vrr_active ||
478 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
479 				      &v_blank_end, &hpos, &vpos) ||
480 	    (vpos < v_blank_start)) {
481 		/* Update to correct count and vblank timestamp if racing with
482 		 * vblank irq. This also updates to the correct vblank timestamp
483 		 * even in VRR mode, as scanout is past the front-porch atm.
484 		 */
485 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
486 
487 		/* Wake up userspace by sending the pageflip event with proper
488 		 * count and timestamp of vblank of flip completion.
489 		 */
490 		if (e) {
491 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
492 
493 			/* Event sent, so done with vblank for this flip */
494 			drm_crtc_vblank_put(&amdgpu_crtc->base);
495 		}
496 	} else if (e) {
497 		/* VRR active and inside front-porch: vblank count and
498 		 * timestamp for pageflip event will only be up to date after
499 		 * drm_crtc_handle_vblank() has been executed from late vblank
500 		 * irq handler after start of back-porch (vline 0). We queue the
501 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
502 		 * updated timestamp and count, once it runs after us.
503 		 *
504 		 * We need to open-code this instead of using the helper
505 		 * drm_crtc_arm_vblank_event(), as that helper would
506 		 * call drm_crtc_accurate_vblank_count(), which we must
507 		 * not call in VRR mode while we are in front-porch!
508 		 */
509 
510 		/* sequence will be replaced by real count during send-out. */
511 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
512 		e->pipe = amdgpu_crtc->crtc_id;
513 
514 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
515 		e = NULL;
516 	}
517 
518 	/* Keep track of vblank of this flip for flip throttling. We use the
519 	 * cooked hw counter, as that one incremented at start of this vblank
520 	 * of pageflip completion, so last_flip_vblank is the forbidden count
521 	 * for queueing new pageflips if vsync + VRR is enabled.
522 	 */
523 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
524 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
525 
526 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
527 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
528 
529 	drm_dbg_state(dev,
530 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
531 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
532 }
533 
534 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
535 {
536 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
537 	struct amdgpu_device *adev = work->adev;
538 	struct dc_stream_state *stream = work->stream;
539 	struct dc_crtc_timing_adjust *adjust = work->adjust;
540 
541 	mutex_lock(&adev->dm.dc_lock);
542 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
543 	mutex_unlock(&adev->dm.dc_lock);
544 
545 	dc_stream_release(stream);
546 	kfree(work->adjust);
547 	kfree(work);
548 }
549 
550 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
551 	struct dc_stream_state *stream,
552 	struct dc_crtc_timing_adjust *adjust)
553 {
554 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
555 								GFP_NOWAIT);
556 	if (!offload_work) {
557 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
558 		return;
559 	}
560 
561 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
562 								GFP_NOWAIT);
563 	if (!adjust_copy) {
564 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
565 		kfree(offload_work);
566 		return;
567 	}
568 
569 	dc_stream_retain(stream);
570 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
571 
572 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
573 	offload_work->adev = adev;
574 	offload_work->stream = stream;
575 	offload_work->adjust = adjust_copy;
576 
577 	queue_work(system_percpu_wq, &offload_work->work);
578 }
579 
580 static void dm_vupdate_high_irq(void *interrupt_params)
581 {
582 	struct common_irq_params *irq_params = interrupt_params;
583 	struct amdgpu_device *adev = irq_params->adev;
584 	struct amdgpu_crtc *acrtc;
585 	struct drm_device *drm_dev;
586 	struct drm_vblank_crtc *vblank;
587 	ktime_t frame_duration_ns, previous_timestamp;
588 	unsigned long flags;
589 	int vrr_active;
590 
591 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
592 
593 	if (acrtc) {
594 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
595 		drm_dev = acrtc->base.dev;
596 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
597 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
598 		frame_duration_ns = vblank->time - previous_timestamp;
599 
600 		if (frame_duration_ns > 0) {
601 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
602 						frame_duration_ns,
603 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
604 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
605 		}
606 
607 		drm_dbg_vbl(drm_dev,
608 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
609 			    vrr_active);
610 
611 		/* Core vblank handling is done here after end of front-porch in
612 		 * vrr mode, as vblank timestamping will give valid results
613 		 * while now done after front-porch. This will also deliver
614 		 * page-flip completion events that have been queued to us
615 		 * if a pageflip happened inside front-porch.
616 		 */
617 		if (vrr_active && acrtc->dm_irq_params.stream) {
618 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
619 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
620 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
621 				== VRR_STATE_ACTIVE_VARIABLE;
622 
623 			amdgpu_dm_crtc_handle_vblank(acrtc);
624 
625 			/* BTR processing for pre-DCE12 ASICs */
626 			if (adev->family < AMDGPU_FAMILY_AI) {
627 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
628 				mod_freesync_handle_v_update(
629 				    adev->dm.freesync_module,
630 				    acrtc->dm_irq_params.stream,
631 				    &acrtc->dm_irq_params.vrr_params);
632 
633 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
634 					schedule_dc_vmin_vmax(adev,
635 						acrtc->dm_irq_params.stream,
636 						&acrtc->dm_irq_params.vrr_params.adjust);
637 				}
638 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
639 			}
640 		}
641 	}
642 }
643 
644 /**
645  * dm_crtc_high_irq() - Handles CRTC interrupt
646  * @interrupt_params: used for determining the CRTC instance
647  *
648  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
649  * event handler.
650  */
651 static void dm_crtc_high_irq(void *interrupt_params)
652 {
653 	struct common_irq_params *irq_params = interrupt_params;
654 	struct amdgpu_device *adev = irq_params->adev;
655 	struct drm_writeback_job *job;
656 	struct amdgpu_crtc *acrtc;
657 	unsigned long flags;
658 	int vrr_active;
659 
660 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
661 	if (!acrtc)
662 		return;
663 
664 	if (acrtc->wb_conn) {
665 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
666 
667 		if (acrtc->wb_pending) {
668 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
669 						       struct drm_writeback_job,
670 						       list_entry);
671 			acrtc->wb_pending = false;
672 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
673 
674 			if (job) {
675 				unsigned int v_total, refresh_hz;
676 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
677 
678 				v_total = stream->adjust.v_total_max ?
679 					  stream->adjust.v_total_max : stream->timing.v_total;
680 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
681 					     100LL, (v_total * stream->timing.h_total));
682 				mdelay(1000 / refresh_hz);
683 
684 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
685 				dc_stream_fc_disable_writeback(adev->dm.dc,
686 							       acrtc->dm_irq_params.stream, 0);
687 			}
688 		} else
689 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
690 	}
691 
692 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
693 
694 	drm_dbg_vbl(adev_to_drm(adev),
695 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
696 		    vrr_active, acrtc->dm_irq_params.active_planes);
697 
698 	/**
699 	 * Core vblank handling at start of front-porch is only possible
700 	 * in non-vrr mode, as only there vblank timestamping will give
701 	 * valid results while done in front-porch. Otherwise defer it
702 	 * to dm_vupdate_high_irq after end of front-porch.
703 	 */
704 	if (!vrr_active)
705 		amdgpu_dm_crtc_handle_vblank(acrtc);
706 
707 	/**
708 	 * Following stuff must happen at start of vblank, for crc
709 	 * computation and below-the-range btr support in vrr mode.
710 	 */
711 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
712 
713 	/* BTR updates need to happen before VUPDATE on Vega and above. */
714 	if (adev->family < AMDGPU_FAMILY_AI)
715 		return;
716 
717 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
718 
719 	if (acrtc->dm_irq_params.stream &&
720 		acrtc->dm_irq_params.vrr_params.supported) {
721 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
722 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
723 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
724 
725 		mod_freesync_handle_v_update(adev->dm.freesync_module,
726 					     acrtc->dm_irq_params.stream,
727 					     &acrtc->dm_irq_params.vrr_params);
728 
729 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
730 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
731 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
732 					&acrtc->dm_irq_params.vrr_params.adjust);
733 		}
734 	}
735 
736 	/*
737 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
738 	 * In that case, pageflip completion interrupts won't fire and pageflip
739 	 * completion events won't get delivered. Prevent this by sending
740 	 * pending pageflip events from here if a flip is still pending.
741 	 *
742 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
743 	 * avoid race conditions between flip programming and completion,
744 	 * which could cause too early flip completion events.
745 	 */
746 	if (adev->family >= AMDGPU_FAMILY_RV &&
747 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
748 	    acrtc->dm_irq_params.active_planes == 0) {
749 		if (acrtc->event) {
750 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
751 			acrtc->event = NULL;
752 			drm_crtc_vblank_put(&acrtc->base);
753 		}
754 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
755 	}
756 
757 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
758 }
759 
760 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
761 /**
762  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
763  * DCN generation ASICs
764  * @interrupt_params: interrupt parameters
765  *
766  * Used to set crc window/read out crc value at vertical line 0 position
767  */
768 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
769 {
770 	struct common_irq_params *irq_params = interrupt_params;
771 	struct amdgpu_device *adev = irq_params->adev;
772 	struct amdgpu_crtc *acrtc;
773 
774 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
775 
776 	if (!acrtc)
777 		return;
778 
779 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
780 }
781 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
782 
783 /**
784  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
785  * @adev: amdgpu_device pointer
786  * @notify: dmub notification structure
787  *
788  * Dmub AUX or SET_CONFIG command completion processing callback
789  * Copies dmub notification to DM which is to be read by AUX command.
790  * issuing thread and also signals the event to wake up the thread.
791  */
792 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
793 					struct dmub_notification *notify)
794 {
795 	if (adev->dm.dmub_notify)
796 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
797 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
798 		complete(&adev->dm.dmub_aux_transfer_done);
799 }
800 
801 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
802 					struct dmub_notification *notify)
803 {
804 	if (!adev || !notify) {
805 		ASSERT(false);
806 		return;
807 	}
808 
809 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
810 	const uint8_t ddc_line = req->u.aux.ddc_line;
811 
812 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
813 		ASSERT(false);
814 		return;
815 	}
816 
817 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
818 
819 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
820 	memcpy(sync->reply_data, req, sizeof(*req));
821 	complete(&sync->replied);
822 }
823 
824 /**
825  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
826  * @adev: amdgpu_device pointer
827  * @notify: dmub notification structure
828  *
829  * Dmub Hpd interrupt processing callback. Gets displayindex through the
830  * ink index and calls helper to do the processing.
831  */
832 static void dmub_hpd_callback(struct amdgpu_device *adev,
833 			      struct dmub_notification *notify)
834 {
835 	struct amdgpu_dm_connector *aconnector;
836 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
837 	struct drm_connector *connector;
838 	struct drm_connector_list_iter iter;
839 	struct dc_link *link;
840 	u8 link_index = 0;
841 	struct drm_device *dev;
842 
843 	if (adev == NULL)
844 		return;
845 
846 	if (notify == NULL) {
847 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
848 		return;
849 	}
850 
851 	if (notify->link_index > adev->dm.dc->link_count) {
852 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
853 		return;
854 	}
855 
856 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
857 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
858 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
859 		return;
860 	}
861 
862 	link_index = notify->link_index;
863 	link = adev->dm.dc->links[link_index];
864 	dev = adev->dm.ddev;
865 
866 	drm_connector_list_iter_begin(dev, &iter);
867 	drm_for_each_connector_iter(connector, &iter) {
868 
869 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
870 			continue;
871 
872 		aconnector = to_amdgpu_dm_connector(connector);
873 		if (link && aconnector->dc_link == link) {
874 			if (notify->type == DMUB_NOTIFICATION_HPD)
875 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
876 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
877 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
878 			else
879 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
880 						notify->type, link_index);
881 
882 			hpd_aconnector = aconnector;
883 			break;
884 		}
885 	}
886 	drm_connector_list_iter_end(&iter);
887 
888 	if (hpd_aconnector) {
889 		if (notify->type == DMUB_NOTIFICATION_HPD) {
890 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
891 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
892 			handle_hpd_irq_helper(hpd_aconnector);
893 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
894 			handle_hpd_rx_irq(hpd_aconnector);
895 		}
896 	}
897 }
898 
899 /**
900  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
901  * @adev: amdgpu_device pointer
902  * @notify: dmub notification structure
903  *
904  * HPD sense changes can occur during low power states and need to be
905  * notified from firmware to driver.
906  */
907 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
908 			      struct dmub_notification *notify)
909 {
910 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
911 }
912 
913 /**
914  * register_dmub_notify_callback - Sets callback for DMUB notify
915  * @adev: amdgpu_device pointer
916  * @type: Type of dmub notification
917  * @callback: Dmub interrupt callback function
918  * @dmub_int_thread_offload: offload indicator
919  *
920  * API to register a dmub callback handler for a dmub notification
921  * Also sets indicator whether callback processing to be offloaded.
922  * to dmub interrupt handling thread
923  * Return: true if successfully registered, false if there is existing registration
924  */
925 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
926 					  enum dmub_notification_type type,
927 					  dmub_notify_interrupt_callback_t callback,
928 					  bool dmub_int_thread_offload)
929 {
930 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
931 		adev->dm.dmub_callback[type] = callback;
932 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
933 	} else
934 		return false;
935 
936 	return true;
937 }
938 
939 static void dm_handle_hpd_work(struct work_struct *work)
940 {
941 	struct dmub_hpd_work *dmub_hpd_wrk;
942 
943 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
944 
945 	if (!dmub_hpd_wrk->dmub_notify) {
946 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
947 		return;
948 	}
949 
950 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
951 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
952 		dmub_hpd_wrk->dmub_notify);
953 	}
954 
955 	kfree(dmub_hpd_wrk->dmub_notify);
956 	kfree(dmub_hpd_wrk);
957 
958 }
959 
960 static const char *dmub_notification_type_str(enum dmub_notification_type e)
961 {
962 	switch (e) {
963 	case DMUB_NOTIFICATION_NO_DATA:
964 		return "NO_DATA";
965 	case DMUB_NOTIFICATION_AUX_REPLY:
966 		return "AUX_REPLY";
967 	case DMUB_NOTIFICATION_HPD:
968 		return "HPD";
969 	case DMUB_NOTIFICATION_HPD_IRQ:
970 		return "HPD_IRQ";
971 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
972 		return "SET_CONFIG_REPLY";
973 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
974 		return "DPIA_NOTIFICATION";
975 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
976 		return "HPD_SENSE_NOTIFY";
977 	case DMUB_NOTIFICATION_FUSED_IO:
978 		return "FUSED_IO";
979 	default:
980 		return "<unknown>";
981 	}
982 }
983 
984 #define DMUB_TRACE_MAX_READ 64
985 /**
986  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
987  * @interrupt_params: used for determining the Outbox instance
988  *
989  * Handles the Outbox Interrupt
990  * event handler.
991  */
992 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
993 {
994 	struct dmub_notification notify = {0};
995 	struct common_irq_params *irq_params = interrupt_params;
996 	struct amdgpu_device *adev = irq_params->adev;
997 	struct amdgpu_display_manager *dm = &adev->dm;
998 	struct dmcub_trace_buf_entry entry = { 0 };
999 	u32 count = 0;
1000 	struct dmub_hpd_work *dmub_hpd_wrk;
1001 
1002 	do {
1003 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1004 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1005 							entry.param0, entry.param1);
1006 
1007 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1008 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1009 		} else
1010 			break;
1011 
1012 		count++;
1013 
1014 	} while (count <= DMUB_TRACE_MAX_READ);
1015 
1016 	if (count > DMUB_TRACE_MAX_READ)
1017 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1018 
1019 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1020 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1021 
1022 		do {
1023 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1024 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1025 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1026 				continue;
1027 			}
1028 			if (!dm->dmub_callback[notify.type]) {
1029 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1030 					dmub_notification_type_str(notify.type));
1031 				continue;
1032 			}
1033 			if (dm->dmub_thread_offload[notify.type] == true) {
1034 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1035 							   GFP_ATOMIC);
1036 				if (!dmub_hpd_wrk) {
1037 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1038 					return;
1039 				}
1040 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1041 								    GFP_ATOMIC);
1042 				if (!dmub_hpd_wrk->dmub_notify) {
1043 					kfree(dmub_hpd_wrk);
1044 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1045 					return;
1046 				}
1047 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1048 				dmub_hpd_wrk->adev = adev;
1049 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1050 			} else {
1051 				dm->dmub_callback[notify.type](adev, &notify);
1052 			}
1053 		} while (notify.pending_notification);
1054 	}
1055 }
1056 
1057 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1058 		  enum amd_clockgating_state state)
1059 {
1060 	return 0;
1061 }
1062 
1063 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1064 		  enum amd_powergating_state state)
1065 {
1066 	return 0;
1067 }
1068 
1069 /* Prototypes of private functions */
1070 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1071 
1072 /* Allocate memory for FBC compressed data  */
1073 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1074 {
1075 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1076 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1077 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1078 	struct drm_display_mode *mode;
1079 	unsigned long max_size = 0;
1080 
1081 	if (adev->dm.dc->fbc_compressor == NULL)
1082 		return;
1083 
1084 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1085 		return;
1086 
1087 	if (compressor->bo_ptr)
1088 		return;
1089 
1090 
1091 	list_for_each_entry(mode, &connector->modes, head) {
1092 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1093 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1094 	}
1095 
1096 	if (max_size) {
1097 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1098 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1099 			    &compressor->gpu_addr, &compressor->cpu_addr);
1100 
1101 		if (r)
1102 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1103 		else {
1104 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1105 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1106 		}
1107 
1108 	}
1109 
1110 }
1111 
1112 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1113 					  int pipe, bool *enabled,
1114 					  unsigned char *buf, int max_bytes)
1115 {
1116 	struct drm_device *dev = dev_get_drvdata(kdev);
1117 	struct amdgpu_device *adev = drm_to_adev(dev);
1118 	struct drm_connector *connector;
1119 	struct drm_connector_list_iter conn_iter;
1120 	struct amdgpu_dm_connector *aconnector;
1121 	int ret = 0;
1122 
1123 	*enabled = false;
1124 
1125 	mutex_lock(&adev->dm.audio_lock);
1126 
1127 	drm_connector_list_iter_begin(dev, &conn_iter);
1128 	drm_for_each_connector_iter(connector, &conn_iter) {
1129 
1130 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1131 			continue;
1132 
1133 		aconnector = to_amdgpu_dm_connector(connector);
1134 		if (aconnector->audio_inst != port)
1135 			continue;
1136 
1137 		*enabled = true;
1138 		mutex_lock(&connector->eld_mutex);
1139 		ret = drm_eld_size(connector->eld);
1140 		memcpy(buf, connector->eld, min(max_bytes, ret));
1141 		mutex_unlock(&connector->eld_mutex);
1142 
1143 		break;
1144 	}
1145 	drm_connector_list_iter_end(&conn_iter);
1146 
1147 	mutex_unlock(&adev->dm.audio_lock);
1148 
1149 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1150 
1151 	return ret;
1152 }
1153 
1154 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1155 	.get_eld = amdgpu_dm_audio_component_get_eld,
1156 };
1157 
1158 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1159 				       struct device *hda_kdev, void *data)
1160 {
1161 	struct drm_device *dev = dev_get_drvdata(kdev);
1162 	struct amdgpu_device *adev = drm_to_adev(dev);
1163 	struct drm_audio_component *acomp = data;
1164 
1165 	acomp->ops = &amdgpu_dm_audio_component_ops;
1166 	acomp->dev = kdev;
1167 	adev->dm.audio_component = acomp;
1168 
1169 	return 0;
1170 }
1171 
1172 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1173 					  struct device *hda_kdev, void *data)
1174 {
1175 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1176 	struct drm_audio_component *acomp = data;
1177 
1178 	acomp->ops = NULL;
1179 	acomp->dev = NULL;
1180 	adev->dm.audio_component = NULL;
1181 }
1182 
1183 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1184 	.bind	= amdgpu_dm_audio_component_bind,
1185 	.unbind	= amdgpu_dm_audio_component_unbind,
1186 };
1187 
1188 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1189 {
1190 	int i, ret;
1191 
1192 	if (!amdgpu_audio)
1193 		return 0;
1194 
1195 	adev->mode_info.audio.enabled = true;
1196 
1197 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1198 
1199 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1200 		adev->mode_info.audio.pin[i].channels = -1;
1201 		adev->mode_info.audio.pin[i].rate = -1;
1202 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1203 		adev->mode_info.audio.pin[i].status_bits = 0;
1204 		adev->mode_info.audio.pin[i].category_code = 0;
1205 		adev->mode_info.audio.pin[i].connected = false;
1206 		adev->mode_info.audio.pin[i].id =
1207 			adev->dm.dc->res_pool->audios[i]->inst;
1208 		adev->mode_info.audio.pin[i].offset = 0;
1209 	}
1210 
1211 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1212 	if (ret < 0)
1213 		return ret;
1214 
1215 	adev->dm.audio_registered = true;
1216 
1217 	return 0;
1218 }
1219 
1220 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1221 {
1222 	if (!amdgpu_audio)
1223 		return;
1224 
1225 	if (!adev->mode_info.audio.enabled)
1226 		return;
1227 
1228 	if (adev->dm.audio_registered) {
1229 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1230 		adev->dm.audio_registered = false;
1231 	}
1232 
1233 	/* TODO: Disable audio? */
1234 
1235 	adev->mode_info.audio.enabled = false;
1236 }
1237 
1238 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1239 {
1240 	struct drm_audio_component *acomp = adev->dm.audio_component;
1241 
1242 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1243 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1244 
1245 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1246 						 pin, -1);
1247 	}
1248 }
1249 
1250 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1251 {
1252 	const struct dmcub_firmware_header_v1_0 *hdr;
1253 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1254 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1255 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1256 	struct dc *dc = adev->dm.dc;
1257 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1258 	struct abm *abm = adev->dm.dc->res_pool->abm;
1259 	struct dc_context *ctx = adev->dm.dc->ctx;
1260 	struct dmub_srv_hw_params hw_params;
1261 	enum dmub_status status;
1262 	const unsigned char *fw_inst_const, *fw_bss_data;
1263 	u32 i, fw_inst_const_size, fw_bss_data_size;
1264 	bool has_hw_support;
1265 
1266 	if (!dmub_srv)
1267 		/* DMUB isn't supported on the ASIC. */
1268 		return 0;
1269 
1270 	if (!fb_info) {
1271 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1272 		return -EINVAL;
1273 	}
1274 
1275 	if (!dmub_fw) {
1276 		/* Firmware required for DMUB support. */
1277 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1278 		return -EINVAL;
1279 	}
1280 
1281 	/* initialize register offsets for ASICs with runtime initialization available */
1282 	if (dmub_srv->hw_funcs.init_reg_offsets)
1283 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1284 
1285 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1286 	if (status != DMUB_STATUS_OK) {
1287 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1288 		return -EINVAL;
1289 	}
1290 
1291 	if (!has_hw_support) {
1292 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1293 		return 0;
1294 	}
1295 
1296 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1297 	status = dmub_srv_hw_reset(dmub_srv);
1298 	if (status != DMUB_STATUS_OK)
1299 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1300 
1301 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1302 
1303 	fw_inst_const = dmub_fw->data +
1304 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1305 			PSP_HEADER_BYTES_256;
1306 
1307 	fw_bss_data = dmub_fw->data +
1308 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1309 		      le32_to_cpu(hdr->inst_const_bytes);
1310 
1311 	/* Copy firmware and bios info into FB memory. */
1312 	fw_inst_const_size = adev->dm.fw_inst_size;
1313 
1314 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1315 
1316 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1317 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1318 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1319 	 * will be done by dm_dmub_hw_init
1320 	 */
1321 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1322 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1323 				fw_inst_const_size);
1324 	}
1325 
1326 	if (fw_bss_data_size)
1327 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1328 		       fw_bss_data, fw_bss_data_size);
1329 
1330 	/* Copy firmware bios info into FB memory. */
1331 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1332 	       adev->bios_size);
1333 
1334 	/* Reset regions that need to be reset. */
1335 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1336 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1337 
1338 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1339 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1346 
1347 	/* Initialize hardware. */
1348 	memset(&hw_params, 0, sizeof(hw_params));
1349 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1350 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1351 
1352 	/* backdoor load firmware and trigger dmub running */
1353 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1354 		hw_params.load_inst_const = true;
1355 
1356 	if (dmcu)
1357 		hw_params.psp_version = dmcu->psp_version;
1358 
1359 	for (i = 0; i < fb_info->num_fb; ++i)
1360 		hw_params.fb[i] = &fb_info->fb[i];
1361 
1362 	/* Enable usb4 dpia in the FW APU */
1363 	if (dc->caps.is_apu &&
1364 		dc->res_pool->usb4_dpia_count != 0 &&
1365 		!dc->debug.dpia_debug.bits.disable_dpia) {
1366 		hw_params.dpia_supported = true;
1367 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1368 		hw_params.dpia_hpd_int_enable_supported = false;
1369 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1370 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1371 	}
1372 
1373 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1374 	case IP_VERSION(3, 5, 0):
1375 	case IP_VERSION(3, 5, 1):
1376 	case IP_VERSION(3, 6, 0):
1377 	case IP_VERSION(4, 2, 0):
1378 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1379 		hw_params.lower_hbr3_phy_ssc = true;
1380 		break;
1381 	default:
1382 		break;
1383 	}
1384 
1385 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1386 	if (status != DMUB_STATUS_OK) {
1387 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1388 		return -EINVAL;
1389 	}
1390 
1391 	/* Wait for firmware load to finish. */
1392 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1393 	if (status != DMUB_STATUS_OK)
1394 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1395 
1396 	/* Init DMCU and ABM if available. */
1397 	if (dmcu && abm) {
1398 		dmcu->funcs->dmcu_init(dmcu);
1399 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1400 	}
1401 
1402 	if (!adev->dm.dc->ctx->dmub_srv)
1403 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1404 	if (!adev->dm.dc->ctx->dmub_srv) {
1405 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1406 		return -ENOMEM;
1407 	}
1408 
1409 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1410 		 adev->dm.dmcub_fw_version);
1411 
1412 	/* Keeping sanity checks off if
1413 	 * DCN31 >= 4.0.59.0
1414 	 * DCN314 >= 8.0.16.0
1415 	 * Otherwise, turn on sanity checks
1416 	 */
1417 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1418 	case IP_VERSION(3, 1, 2):
1419 	case IP_VERSION(3, 1, 3):
1420 		if (adev->dm.dmcub_fw_version &&
1421 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1422 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1423 				adev->dm.dc->debug.sanity_checks = true;
1424 		break;
1425 	case IP_VERSION(3, 1, 4):
1426 		if (adev->dm.dmcub_fw_version &&
1427 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1428 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1429 				adev->dm.dc->debug.sanity_checks = true;
1430 		break;
1431 	default:
1432 		break;
1433 	}
1434 
1435 	return 0;
1436 }
1437 
1438 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1439 {
1440 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1441 	enum dmub_status status;
1442 	bool init;
1443 	int r;
1444 
1445 	if (!dmub_srv) {
1446 		/* DMUB isn't supported on the ASIC. */
1447 		return;
1448 	}
1449 
1450 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1451 	if (status != DMUB_STATUS_OK)
1452 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1453 
1454 	if (status == DMUB_STATUS_OK && init) {
1455 		/* Wait for firmware load to finish. */
1456 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1457 		if (status != DMUB_STATUS_OK)
1458 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1459 	} else {
1460 		/* Perform the full hardware initialization. */
1461 		r = dm_dmub_hw_init(adev);
1462 		if (r)
1463 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1464 	}
1465 }
1466 
1467 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1468 {
1469 	u64 pt_base;
1470 	u32 logical_addr_low;
1471 	u32 logical_addr_high;
1472 	u32 agp_base, agp_bot, agp_top;
1473 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1474 
1475 	memset(pa_config, 0, sizeof(*pa_config));
1476 
1477 	agp_base = 0;
1478 	agp_bot = adev->gmc.agp_start >> 24;
1479 	agp_top = adev->gmc.agp_end >> 24;
1480 
1481 	/* AGP aperture is disabled */
1482 	if (agp_bot > agp_top) {
1483 		logical_addr_low = adev->gmc.fb_start >> 18;
1484 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1485 				       AMD_APU_IS_RENOIR |
1486 				       AMD_APU_IS_GREEN_SARDINE))
1487 			/*
1488 			 * Raven2 has a HW issue that it is unable to use the vram which
1489 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1490 			 * workaround that increase system aperture high address (add 1)
1491 			 * to get rid of the VM fault and hardware hang.
1492 			 */
1493 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1494 		else
1495 			logical_addr_high = adev->gmc.fb_end >> 18;
1496 	} else {
1497 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1498 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1499 				       AMD_APU_IS_RENOIR |
1500 				       AMD_APU_IS_GREEN_SARDINE))
1501 			/*
1502 			 * Raven2 has a HW issue that it is unable to use the vram which
1503 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1504 			 * workaround that increase system aperture high address (add 1)
1505 			 * to get rid of the VM fault and hardware hang.
1506 			 */
1507 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1508 		else
1509 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1510 	}
1511 
1512 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1513 
1514 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1515 						   AMDGPU_GPU_PAGE_SHIFT);
1516 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1517 						  AMDGPU_GPU_PAGE_SHIFT);
1518 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1519 						 AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1521 						AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_base.high_part = upper_32_bits(pt_base);
1523 	page_table_base.low_part = lower_32_bits(pt_base);
1524 
1525 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1526 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1527 
1528 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1529 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1530 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1531 
1532 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1533 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1534 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1535 
1536 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1537 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1538 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1539 
1540 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1541 
1542 }
1543 
1544 static void force_connector_state(
1545 	struct amdgpu_dm_connector *aconnector,
1546 	enum drm_connector_force force_state)
1547 {
1548 	struct drm_connector *connector = &aconnector->base;
1549 
1550 	mutex_lock(&connector->dev->mode_config.mutex);
1551 	aconnector->base.force = force_state;
1552 	mutex_unlock(&connector->dev->mode_config.mutex);
1553 
1554 	mutex_lock(&aconnector->hpd_lock);
1555 	drm_kms_helper_connector_hotplug_event(connector);
1556 	mutex_unlock(&aconnector->hpd_lock);
1557 }
1558 
1559 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1560 {
1561 	struct hpd_rx_irq_offload_work *offload_work;
1562 	struct amdgpu_dm_connector *aconnector;
1563 	struct dc_link *dc_link;
1564 	struct amdgpu_device *adev;
1565 	enum dc_connection_type new_connection_type = dc_connection_none;
1566 	unsigned long flags;
1567 	union test_response test_response;
1568 
1569 	memset(&test_response, 0, sizeof(test_response));
1570 
1571 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1572 	aconnector = offload_work->offload_wq->aconnector;
1573 	adev = offload_work->adev;
1574 
1575 	if (!aconnector) {
1576 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1577 		goto skip;
1578 	}
1579 
1580 	dc_link = aconnector->dc_link;
1581 
1582 	mutex_lock(&aconnector->hpd_lock);
1583 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1584 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1585 	mutex_unlock(&aconnector->hpd_lock);
1586 
1587 	if (new_connection_type == dc_connection_none)
1588 		goto skip;
1589 
1590 	if (amdgpu_in_reset(adev))
1591 		goto skip;
1592 
1593 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1594 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1595 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1596 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1597 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1598 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1599 		goto skip;
1600 	}
1601 
1602 	mutex_lock(&adev->dm.dc_lock);
1603 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1604 		dc_link_dp_handle_automated_test(dc_link);
1605 
1606 		if (aconnector->timing_changed) {
1607 			/* force connector disconnect and reconnect */
1608 			force_connector_state(aconnector, DRM_FORCE_OFF);
1609 			msleep(100);
1610 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1611 		}
1612 
1613 		test_response.bits.ACK = 1;
1614 
1615 		core_link_write_dpcd(
1616 		dc_link,
1617 		DP_TEST_RESPONSE,
1618 		&test_response.raw,
1619 		sizeof(test_response));
1620 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1621 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1622 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1623 		/* offload_work->data is from handle_hpd_rx_irq->
1624 		 * schedule_hpd_rx_offload_work.this is defer handle
1625 		 * for hpd short pulse. upon here, link status may be
1626 		 * changed, need get latest link status from dpcd
1627 		 * registers. if link status is good, skip run link
1628 		 * training again.
1629 		 */
1630 		union hpd_irq_data irq_data;
1631 
1632 		memset(&irq_data, 0, sizeof(irq_data));
1633 
1634 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1635 		 * request be added to work queue if link lost at end of dc_link_
1636 		 * dp_handle_link_loss
1637 		 */
1638 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1639 		offload_work->offload_wq->is_handling_link_loss = false;
1640 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1641 
1642 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1643 			dc_link_check_link_loss_status(dc_link, &irq_data))
1644 			dc_link_dp_handle_link_loss(dc_link);
1645 	}
1646 	mutex_unlock(&adev->dm.dc_lock);
1647 
1648 skip:
1649 	kfree(offload_work);
1650 
1651 }
1652 
1653 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1654 {
1655 	struct dc *dc = adev->dm.dc;
1656 	int max_caps = dc->caps.max_links;
1657 	int i = 0;
1658 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1659 
1660 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1661 
1662 	if (!hpd_rx_offload_wq)
1663 		return NULL;
1664 
1665 
1666 	for (i = 0; i < max_caps; i++) {
1667 		hpd_rx_offload_wq[i].wq =
1668 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1669 
1670 		if (hpd_rx_offload_wq[i].wq == NULL) {
1671 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1672 			goto out_err;
1673 		}
1674 
1675 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1676 	}
1677 
1678 	return hpd_rx_offload_wq;
1679 
1680 out_err:
1681 	for (i = 0; i < max_caps; i++) {
1682 		if (hpd_rx_offload_wq[i].wq)
1683 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1684 	}
1685 	kfree(hpd_rx_offload_wq);
1686 	return NULL;
1687 }
1688 
1689 struct amdgpu_stutter_quirk {
1690 	u16 chip_vendor;
1691 	u16 chip_device;
1692 	u16 subsys_vendor;
1693 	u16 subsys_device;
1694 	u8 revision;
1695 };
1696 
1697 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1698 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1699 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1700 	{ 0, 0, 0, 0, 0 },
1701 };
1702 
1703 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1704 {
1705 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1706 
1707 	while (p && p->chip_device != 0) {
1708 		if (pdev->vendor == p->chip_vendor &&
1709 		    pdev->device == p->chip_device &&
1710 		    pdev->subsystem_vendor == p->subsys_vendor &&
1711 		    pdev->subsystem_device == p->subsys_device &&
1712 		    pdev->revision == p->revision) {
1713 			return true;
1714 		}
1715 		++p;
1716 	}
1717 	return false;
1718 }
1719 
1720 
1721 void*
1722 dm_allocate_gpu_mem(
1723 		struct amdgpu_device *adev,
1724 		enum dc_gpu_mem_alloc_type type,
1725 		size_t size,
1726 		long long *addr)
1727 {
1728 	struct dal_allocation *da;
1729 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1730 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1731 	int ret;
1732 
1733 	da = kzalloc_obj(struct dal_allocation);
1734 	if (!da)
1735 		return NULL;
1736 
1737 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1738 				      domain, &da->bo,
1739 				      &da->gpu_addr, &da->cpu_ptr);
1740 
1741 	*addr = da->gpu_addr;
1742 
1743 	if (ret) {
1744 		kfree(da);
1745 		return NULL;
1746 	}
1747 
1748 	/* add da to list in dm */
1749 	list_add(&da->list, &adev->dm.da_list);
1750 
1751 	return da->cpu_ptr;
1752 }
1753 
1754 void
1755 dm_free_gpu_mem(
1756 		struct amdgpu_device *adev,
1757 		enum dc_gpu_mem_alloc_type type,
1758 		void *pvMem)
1759 {
1760 	struct dal_allocation *da;
1761 
1762 	/* walk the da list in DM */
1763 	list_for_each_entry(da, &adev->dm.da_list, list) {
1764 		if (pvMem == da->cpu_ptr) {
1765 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1766 			list_del(&da->list);
1767 			kfree(da);
1768 			break;
1769 		}
1770 	}
1771 
1772 }
1773 
1774 static enum dmub_status
1775 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1776 				 enum dmub_gpint_command command_code,
1777 				 uint16_t param,
1778 				 uint32_t timeout_us)
1779 {
1780 	union dmub_gpint_data_register reg, test;
1781 	uint32_t i;
1782 
1783 	/* Assume that VBIOS DMUB is ready to take commands */
1784 
1785 	reg.bits.status = 1;
1786 	reg.bits.command_code = command_code;
1787 	reg.bits.param = param;
1788 
1789 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1790 
1791 	for (i = 0; i < timeout_us; ++i) {
1792 		udelay(1);
1793 
1794 		/* Check if our GPINT got acked */
1795 		reg.bits.status = 0;
1796 		test = (union dmub_gpint_data_register)
1797 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1798 
1799 		if (test.all == reg.all)
1800 			return DMUB_STATUS_OK;
1801 	}
1802 
1803 	return DMUB_STATUS_TIMEOUT;
1804 }
1805 
1806 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1807 {
1808 	void *bb;
1809 	long long addr;
1810 	unsigned int bb_size;
1811 	int i = 0;
1812 	uint16_t chunk;
1813 	enum dmub_gpint_command send_addrs[] = {
1814 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1815 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1816 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1817 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1818 	};
1819 	enum dmub_status ret;
1820 
1821 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1822 	case IP_VERSION(4, 0, 1):
1823 		bb_size = sizeof(struct dml2_soc_bb);
1824 		break;
1825 	case IP_VERSION(4, 2, 0):
1826 		bb_size = sizeof(struct dml2_soc_bb);
1827 		break;
1828 	default:
1829 		return NULL;
1830 	}
1831 
1832 	bb =  dm_allocate_gpu_mem(adev,
1833 				  DC_MEM_ALLOC_TYPE_GART,
1834 				  bb_size,
1835 				  &addr);
1836 	if (!bb)
1837 		return NULL;
1838 
1839 	for (i = 0; i < 4; i++) {
1840 		/* Extract 16-bit chunk */
1841 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1842 		/* Send the chunk */
1843 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1844 		if (ret != DMUB_STATUS_OK)
1845 			goto free_bb;
1846 	}
1847 
1848 	/* Now ask DMUB to copy the bb */
1849 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1850 	if (ret != DMUB_STATUS_OK)
1851 		goto free_bb;
1852 
1853 	return bb;
1854 
1855 free_bb:
1856 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1857 	return NULL;
1858 
1859 }
1860 
1861 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1862 	struct amdgpu_device *adev)
1863 {
1864 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1865 
1866 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1867 	case IP_VERSION(3, 5, 0):
1868 	case IP_VERSION(3, 6, 0):
1869 	case IP_VERSION(3, 5, 1):
1870 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1871 		break;
1872 	case IP_VERSION(4, 2, 0):
1873 		ret =  DMUB_IPS_DISABLE_ALL;
1874 		break;
1875 	default:
1876 		/* ASICs older than DCN35 do not have IPSs */
1877 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1878 			ret = DMUB_IPS_DISABLE_ALL;
1879 		break;
1880 	}
1881 
1882 	return ret;
1883 }
1884 
1885 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1886 {
1887 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1888 
1889 	if (dm->num_of_edps == 0) {
1890 		drm_dbg_driver(
1891 			dm->ddev,
1892 			"amdgpu: No eDP detected, skip initializing power module\n");
1893 		return 0;
1894 	}
1895 
1896 	/* Initialize all the power module parameters */
1897 	for (int i = 0; i < dm->num_of_edps; i++) {
1898 		init_data[i].allow_psr_smu_optimizations =
1899 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1900 		init_data[i].allow_psr_multi_disp_optimizations =
1901 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1902 		/* See dm_late_init */
1903 		init_data[i].backlight_ramping_override = false;
1904 		init_data[i].backlight_ramping_start = 0xCCCC;
1905 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1906 		init_data[i].def_varibright_level = 0;
1907 		init_data[i].abm_config_setting = 0;
1908 		init_data[i].num_backlight_levels = 101;
1909 		init_data[i].use_nits_based_brightness = false;
1910 		init_data[i].panel_max_millinits = 0;
1911 		init_data[i].panel_min_millinits = 0;
1912 		init_data[i].disable_fractional_pwm =
1913 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1914 		init_data[i].use_custom_backlight_caps = false;
1915 		init_data[i].custom_backlight_caps_config_no = 0;
1916 		init_data[i].use_linear_backlight_curve = false;
1917 		init_data[i].def_varibright_enable = 0;
1918 		init_data[i].varibright_level = 0;
1919 		/*
1920 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1921 		 * than 8-bit(0XFF max)
1922 		 */
1923 		init_data[i].min_backlight_pwm =
1924 			dm->backlight_caps[i].min_input_signal * 0x101;
1925 		init_data[i].max_backlight_pwm =
1926 			dm->backlight_caps[i].max_input_signal * 0x101;
1927 		init_data[i].min_abm_backlight =
1928 			dm->backlight_caps[i].min_input_signal * 0x101;
1929 
1930 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1931 		 * 0xFFFF x 0.01 = 0x28F
1932 		 */
1933 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1934 			0x28F : init_data[i].min_abm_backlight;
1935 	}
1936 
1937 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1938 	if (!dm->power_module) {
1939 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1940 		return -ENOMEM;
1941 	}
1942 
1943 	mod_power_hw_init(dm->power_module);
1944 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1945 
1946 	return 0;
1947 }
1948 
1949 static int amdgpu_dm_init(struct amdgpu_device *adev)
1950 {
1951 	struct dc_init_data init_data;
1952 	struct dc_callback_init init_params;
1953 	int r;
1954 
1955 	adev->dm.ddev = adev_to_drm(adev);
1956 	adev->dm.adev = adev;
1957 
1958 	/* Zero all the fields */
1959 	memset(&init_data, 0, sizeof(init_data));
1960 	memset(&init_params, 0, sizeof(init_params));
1961 
1962 	mutex_init(&adev->dm.dpia_aux_lock);
1963 	mutex_init(&adev->dm.dc_lock);
1964 	mutex_init(&adev->dm.audio_lock);
1965 
1966 	spin_lock_init(&adev->dm.dmub_lock);
1967 
1968 	if (amdgpu_dm_irq_init(adev)) {
1969 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1970 		goto error;
1971 	}
1972 
1973 	init_data.asic_id.chip_family = adev->family;
1974 
1975 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1976 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1977 	init_data.asic_id.chip_id = adev->pdev->device;
1978 
1979 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1980 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1981 	init_data.asic_id.atombios_base_address =
1982 		adev->mode_info.atom_context->bios;
1983 
1984 	init_data.driver = adev;
1985 
1986 	/* cgs_device was created in dm_sw_init() */
1987 	init_data.cgs_device = adev->dm.cgs_device;
1988 
1989 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1990 
1991 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1992 	case IP_VERSION(2, 1, 0):
1993 		switch (adev->dm.dmcub_fw_version) {
1994 		case 0: /* development */
1995 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1996 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1997 			init_data.flags.disable_dmcu = false;
1998 			break;
1999 		default:
2000 			init_data.flags.disable_dmcu = true;
2001 		}
2002 		break;
2003 	case IP_VERSION(2, 0, 3):
2004 		init_data.flags.disable_dmcu = true;
2005 		break;
2006 	default:
2007 		break;
2008 	}
2009 
2010 	/* APU support S/G display by default except:
2011 	 * ASICs before Carrizo,
2012 	 * RAVEN1 (Users reported stability issue)
2013 	 */
2014 
2015 	if (adev->asic_type < CHIP_CARRIZO) {
2016 		init_data.flags.gpu_vm_support = false;
2017 	} else if (adev->asic_type == CHIP_RAVEN) {
2018 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2019 			init_data.flags.gpu_vm_support = false;
2020 		else
2021 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2022 	} else {
2023 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2024 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2025 		else
2026 			init_data.flags.gpu_vm_support =
2027 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2028 	}
2029 
2030 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2031 
2032 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2033 		init_data.flags.fbc_support = true;
2034 
2035 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2036 		init_data.flags.multi_mon_pp_mclk_switch = true;
2037 
2038 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2039 		init_data.flags.disable_fractional_pwm = true;
2040 
2041 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2042 		init_data.flags.edp_no_power_sequencing = true;
2043 
2044 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2045 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2046 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2047 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2048 
2049 	init_data.flags.seamless_boot_edp_requested = false;
2050 
2051 	if (amdgpu_device_seamless_boot_supported(adev)) {
2052 		init_data.flags.seamless_boot_edp_requested = true;
2053 		init_data.flags.allow_seamless_boot_optimization = true;
2054 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2055 	}
2056 
2057 	init_data.flags.enable_mipi_converter_optimization = true;
2058 
2059 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2060 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2061 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2062 
2063 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2064 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2065 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2066 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2067 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2068 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2069 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2070 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2071 	else
2072 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2073 
2074 	init_data.flags.disable_ips_in_vpb = 0;
2075 
2076 	/* DCN35 and above supports dynamic DTBCLK switch */
2077 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2078 		init_data.flags.allow_0_dtb_clk = true;
2079 
2080 	/* Enable DWB for tested platforms only */
2081 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2082 		init_data.num_virtual_links = 1;
2083 
2084 	/* DCN42 and above dpia switch to unified link training path */
2085 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2086 		init_data.flags.consolidated_dpia_dp_lt = true;
2087 		init_data.flags.enable_dpia_pre_training = true;
2088 		init_data.flags.unify_link_enc_assignment = true;
2089 		init_data.flags.usb4_bw_alloc_support = true;
2090 	}
2091 	retrieve_dmi_info(&adev->dm);
2092 	if (adev->dm.edp0_on_dp1_quirk)
2093 		init_data.flags.support_edp0_on_dp1 = true;
2094 
2095 	if (adev->dm.bb_from_dmub)
2096 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2097 	else
2098 		init_data.bb_from_dmub = NULL;
2099 
2100 	/* Display Core create. */
2101 	adev->dm.dc = dc_create(&init_data);
2102 
2103 	if (adev->dm.dc) {
2104 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2105 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2106 	} else {
2107 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2108 		goto error;
2109 	}
2110 
2111 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2112 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2113 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2114 	}
2115 
2116 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2117 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2118 	if (dm_should_disable_stutter(adev->pdev))
2119 		adev->dm.dc->debug.disable_stutter = true;
2120 
2121 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2122 		adev->dm.dc->debug.disable_stutter = true;
2123 
2124 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2125 		adev->dm.dc->debug.disable_dsc = true;
2126 
2127 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2128 		adev->dm.dc->debug.disable_clock_gate = true;
2129 
2130 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2131 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2132 
2133 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2134 		adev->dm.dc->debug.force_disable_subvp = true;
2135 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2136 	}
2137 
2138 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2139 		adev->dm.dc->debug.using_dml2 = true;
2140 		adev->dm.dc->debug.using_dml21 = true;
2141 	}
2142 
2143 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2144 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2145 
2146 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2147 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2148 
2149 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2150 		adev->dm.dc->debug.skip_detection_link_training = true;
2151 
2152 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2153 
2154 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2155 	adev->dm.dc->debug.ignore_cable_id = true;
2156 
2157 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2158 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2159 
2160 	r = dm_dmub_hw_init(adev);
2161 	if (r) {
2162 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2163 		goto error;
2164 	}
2165 
2166 	dc_hardware_init(adev->dm.dc);
2167 
2168 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2169 	if (!adev->dm.hpd_rx_offload_wq) {
2170 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2171 		goto error;
2172 	}
2173 
2174 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2175 		struct dc_phy_addr_space_config pa_config;
2176 
2177 		mmhub_read_system_context(adev, &pa_config);
2178 
2179 		// Call the DC init_memory func
2180 		dc_setup_system_context(adev->dm.dc, &pa_config);
2181 	}
2182 
2183 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2184 	if (!adev->dm.freesync_module) {
2185 		drm_err(adev_to_drm(adev),
2186 		"failed to initialize freesync_module.\n");
2187 	} else
2188 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2189 				adev->dm.freesync_module);
2190 
2191 	amdgpu_dm_init_color_mod();
2192 
2193 	if (adev->dm.dc->caps.max_links > 0) {
2194 		adev->dm.vblank_control_workqueue =
2195 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2196 		if (!adev->dm.vblank_control_workqueue)
2197 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2198 	}
2199 
2200 	if (adev->dm.dc->caps.ips_support &&
2201 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2202 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2203 
2204 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2205 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2206 
2207 		if (!adev->dm.hdcp_workqueue)
2208 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2209 		else
2210 			drm_dbg_driver(adev_to_drm(adev),
2211 				       "hdcp_workqueue init done %p.\n",
2212 				       adev->dm.hdcp_workqueue);
2213 
2214 		dc_init_callbacks(adev->dm.dc, &init_params);
2215 	}
2216 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2217 		init_completion(&adev->dm.dmub_aux_transfer_done);
2218 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2219 		if (!adev->dm.dmub_notify) {
2220 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2221 			goto error;
2222 		}
2223 
2224 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2225 		if (!adev->dm.delayed_hpd_wq) {
2226 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2227 			goto error;
2228 		}
2229 
2230 		amdgpu_dm_outbox_init(adev);
2231 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2232 			dmub_aux_setconfig_callback, false)) {
2233 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2234 			goto error;
2235 		}
2236 
2237 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2238 			init_completion(&adev->dm.fused_io[i].replied);
2239 
2240 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2241 			dmub_aux_fused_io_callback, false)) {
2242 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2243 			goto error;
2244 		}
2245 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2246 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2247 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2248 		 * align legacy interface initialization sequence. Connection status will be proactivly
2249 		 * detected once in the amdgpu_dm_initialize_drm_device.
2250 		 */
2251 		dc_enable_dmub_outbox(adev->dm.dc);
2252 
2253 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2254 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2255 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2256 	}
2257 
2258 	if (amdgpu_dm_initialize_drm_device(adev)) {
2259 		drm_err(adev_to_drm(adev),
2260 		"failed to initialize sw for display support.\n");
2261 		goto error;
2262 	}
2263 
2264 	if (amdgpu_dm_init_power_module(&adev->dm))
2265 		goto error;
2266 
2267 	/* create fake encoders for MST */
2268 	dm_dp_create_fake_mst_encoders(adev);
2269 
2270 	/* TODO: Add_display_info? */
2271 
2272 	/* TODO use dynamic cursor width */
2273 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2274 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2275 
2276 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2277 		drm_err(adev_to_drm(adev),
2278 		"failed to initialize vblank for display support.\n");
2279 		goto error;
2280 	}
2281 
2282 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2283 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2284 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2285 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2286 
2287 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2288 		adev->dm.secure_display_ctx.support_mul_roi = true;
2289 
2290 #endif
2291 
2292 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2293 
2294 	return 0;
2295 error:
2296 	amdgpu_dm_fini(adev);
2297 
2298 	return -EINVAL;
2299 }
2300 
2301 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2302 {
2303 	struct amdgpu_device *adev = ip_block->adev;
2304 
2305 	amdgpu_dm_audio_fini(adev);
2306 
2307 	return 0;
2308 }
2309 
2310 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2311 {
2312 	int i;
2313 
2314 	if (adev->dm.vblank_control_workqueue) {
2315 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2316 		adev->dm.vblank_control_workqueue = NULL;
2317 	}
2318 
2319 	if (adev->dm.idle_workqueue) {
2320 		if (adev->dm.idle_workqueue->running) {
2321 			adev->dm.idle_workqueue->enable = false;
2322 			flush_work(&adev->dm.idle_workqueue->work);
2323 		}
2324 
2325 		kfree(adev->dm.idle_workqueue);
2326 		adev->dm.idle_workqueue = NULL;
2327 	}
2328 
2329 	/* Disable ISM before dc_destroy() invalidates dm->dc */
2330 	scoped_guard(mutex, &adev->dm.dc_lock)
2331 		amdgpu_dm_ism_disable(&adev->dm);
2332 
2333 	amdgpu_dm_destroy_drm_device(&adev->dm);
2334 
2335 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2336 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2337 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2338 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2339 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2340 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2341 			}
2342 		}
2343 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2344 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2345 	}
2346 #endif
2347 	if (adev->dm.hdcp_workqueue) {
2348 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2349 		adev->dm.hdcp_workqueue = NULL;
2350 	}
2351 
2352 	if (adev->dm.dc) {
2353 		dc_deinit_callbacks(adev->dm.dc);
2354 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2355 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2356 			kfree(adev->dm.dmub_notify);
2357 			adev->dm.dmub_notify = NULL;
2358 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2359 			adev->dm.delayed_hpd_wq = NULL;
2360 		}
2361 	}
2362 
2363 	if (adev->dm.dmub_bo)
2364 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2365 				      &adev->dm.dmub_bo_gpu_addr,
2366 				      &adev->dm.dmub_bo_cpu_addr);
2367 
2368 	if (adev->dm.boot_time_crc_info.bo_ptr)
2369 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2370 					&adev->dm.boot_time_crc_info.gpu_addr,
2371 					&adev->dm.boot_time_crc_info.cpu_addr);
2372 
2373 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2374 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2375 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2376 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2377 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2378 			}
2379 		}
2380 
2381 		kfree(adev->dm.hpd_rx_offload_wq);
2382 		adev->dm.hpd_rx_offload_wq = NULL;
2383 	}
2384 
2385 	/* DC Destroy TODO: Replace destroy DAL */
2386 	if (adev->dm.dc)
2387 		dc_destroy(&adev->dm.dc);
2388 	/*
2389 	 * TODO: pageflip, vlank interrupt
2390 	 *
2391 	 * amdgpu_dm_irq_fini(adev);
2392 	 */
2393 
2394 	if (adev->dm.cgs_device) {
2395 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2396 		adev->dm.cgs_device = NULL;
2397 	}
2398 	if (adev->dm.freesync_module) {
2399 		mod_freesync_destroy(adev->dm.freesync_module);
2400 		adev->dm.freesync_module = NULL;
2401 	}
2402 
2403 	if (adev->dm.power_module) {
2404 		mod_power_destroy(adev->dm.power_module);
2405 		adev->dm.power_module = NULL;
2406 	}
2407 	mutex_destroy(&adev->dm.audio_lock);
2408 	mutex_destroy(&adev->dm.dc_lock);
2409 	mutex_destroy(&adev->dm.dpia_aux_lock);
2410 }
2411 
2412 static int load_dmcu_fw(struct amdgpu_device *adev)
2413 {
2414 	const char *fw_name_dmcu = NULL;
2415 	int r;
2416 	const struct dmcu_firmware_header_v1_0 *hdr;
2417 
2418 	switch (adev->asic_type) {
2419 #if defined(CONFIG_DRM_AMD_DC_SI)
2420 	case CHIP_TAHITI:
2421 	case CHIP_PITCAIRN:
2422 	case CHIP_VERDE:
2423 	case CHIP_OLAND:
2424 #endif
2425 	case CHIP_BONAIRE:
2426 	case CHIP_HAWAII:
2427 	case CHIP_KAVERI:
2428 	case CHIP_KABINI:
2429 	case CHIP_MULLINS:
2430 	case CHIP_TONGA:
2431 	case CHIP_FIJI:
2432 	case CHIP_CARRIZO:
2433 	case CHIP_STONEY:
2434 	case CHIP_POLARIS11:
2435 	case CHIP_POLARIS10:
2436 	case CHIP_POLARIS12:
2437 	case CHIP_VEGAM:
2438 	case CHIP_VEGA10:
2439 	case CHIP_VEGA12:
2440 	case CHIP_VEGA20:
2441 		return 0;
2442 	case CHIP_NAVI12:
2443 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2444 		break;
2445 	case CHIP_RAVEN:
2446 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2447 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2448 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2449 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2450 		else
2451 			return 0;
2452 		break;
2453 	default:
2454 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2455 		case IP_VERSION(2, 0, 2):
2456 		case IP_VERSION(2, 0, 3):
2457 		case IP_VERSION(2, 0, 0):
2458 		case IP_VERSION(2, 1, 0):
2459 		case IP_VERSION(3, 0, 0):
2460 		case IP_VERSION(3, 0, 2):
2461 		case IP_VERSION(3, 0, 3):
2462 		case IP_VERSION(3, 0, 1):
2463 		case IP_VERSION(3, 1, 2):
2464 		case IP_VERSION(3, 1, 3):
2465 		case IP_VERSION(3, 1, 4):
2466 		case IP_VERSION(3, 1, 5):
2467 		case IP_VERSION(3, 1, 6):
2468 		case IP_VERSION(3, 2, 0):
2469 		case IP_VERSION(3, 2, 1):
2470 		case IP_VERSION(3, 5, 0):
2471 		case IP_VERSION(3, 5, 1):
2472 		case IP_VERSION(3, 6, 0):
2473 		case IP_VERSION(4, 0, 1):
2474 		case IP_VERSION(4, 2, 0):
2475 			return 0;
2476 		default:
2477 			break;
2478 		}
2479 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2480 		return -EINVAL;
2481 	}
2482 
2483 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2484 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2485 		return 0;
2486 	}
2487 
2488 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2489 				 "%s", fw_name_dmcu);
2490 	if (r == -ENODEV) {
2491 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2492 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2493 		adev->dm.fw_dmcu = NULL;
2494 		return 0;
2495 	}
2496 	if (r) {
2497 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2498 			fw_name_dmcu);
2499 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2500 		return r;
2501 	}
2502 
2503 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2504 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2505 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2506 	adev->firmware.fw_size +=
2507 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2508 
2509 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2510 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2511 	adev->firmware.fw_size +=
2512 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2513 
2514 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2515 
2516 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2517 
2518 	return 0;
2519 }
2520 
2521 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2522 {
2523 	struct amdgpu_device *adev = ctx;
2524 
2525 	return dm_read_reg(adev->dm.dc->ctx, address);
2526 }
2527 
2528 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2529 				     uint32_t value)
2530 {
2531 	struct amdgpu_device *adev = ctx;
2532 
2533 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2534 }
2535 
2536 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2537 {
2538 	struct dmub_srv_create_params create_params;
2539 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2540 	struct dmub_srv_region_params region_params;
2541 	struct dmub_srv_region_info region_info;
2542 	struct dmub_srv_memory_params memory_params;
2543 	struct dmub_fw_meta_info fw_info;
2544 	struct dmub_srv_fb_info *fb_info;
2545 	struct dmub_srv *dmub_srv;
2546 	const struct dmcub_firmware_header_v1_0 *hdr;
2547 	enum dmub_asic dmub_asic;
2548 	enum dmub_status status;
2549 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2550 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2551 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2552 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2553 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2554 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2555 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2556 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2557 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2558 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2559 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2560 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2561 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2562 	};
2563 	int r;
2564 
2565 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2566 	case IP_VERSION(2, 1, 0):
2567 		dmub_asic = DMUB_ASIC_DCN21;
2568 		break;
2569 	case IP_VERSION(3, 0, 0):
2570 		dmub_asic = DMUB_ASIC_DCN30;
2571 		break;
2572 	case IP_VERSION(3, 0, 1):
2573 		dmub_asic = DMUB_ASIC_DCN301;
2574 		break;
2575 	case IP_VERSION(3, 0, 2):
2576 		dmub_asic = DMUB_ASIC_DCN302;
2577 		break;
2578 	case IP_VERSION(3, 0, 3):
2579 		dmub_asic = DMUB_ASIC_DCN303;
2580 		break;
2581 	case IP_VERSION(3, 1, 2):
2582 	case IP_VERSION(3, 1, 3):
2583 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2584 		break;
2585 	case IP_VERSION(3, 1, 4):
2586 		dmub_asic = DMUB_ASIC_DCN314;
2587 		break;
2588 	case IP_VERSION(3, 1, 5):
2589 		dmub_asic = DMUB_ASIC_DCN315;
2590 		break;
2591 	case IP_VERSION(3, 1, 6):
2592 		dmub_asic = DMUB_ASIC_DCN316;
2593 		break;
2594 	case IP_VERSION(3, 2, 0):
2595 		dmub_asic = DMUB_ASIC_DCN32;
2596 		break;
2597 	case IP_VERSION(3, 2, 1):
2598 		dmub_asic = DMUB_ASIC_DCN321;
2599 		break;
2600 	case IP_VERSION(3, 5, 0):
2601 	case IP_VERSION(3, 5, 1):
2602 		dmub_asic = DMUB_ASIC_DCN35;
2603 		break;
2604 	case IP_VERSION(3, 6, 0):
2605 		dmub_asic = DMUB_ASIC_DCN36;
2606 		break;
2607 	case IP_VERSION(4, 0, 1):
2608 		dmub_asic = DMUB_ASIC_DCN401;
2609 		break;
2610 	case IP_VERSION(4, 2, 0):
2611 		dmub_asic = DMUB_ASIC_DCN42;
2612 		break;
2613 	default:
2614 		/* ASIC doesn't support DMUB. */
2615 		return 0;
2616 	}
2617 
2618 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2619 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2620 
2621 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2622 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2623 			AMDGPU_UCODE_ID_DMCUB;
2624 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2625 			adev->dm.dmub_fw;
2626 		adev->firmware.fw_size +=
2627 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2628 
2629 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2630 			 adev->dm.dmcub_fw_version);
2631 	}
2632 
2633 
2634 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2635 	dmub_srv = adev->dm.dmub_srv;
2636 
2637 	if (!dmub_srv) {
2638 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2639 		return -ENOMEM;
2640 	}
2641 
2642 	memset(&create_params, 0, sizeof(create_params));
2643 	create_params.user_ctx = adev;
2644 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2645 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2646 	create_params.asic = dmub_asic;
2647 
2648 	/* Create the DMUB service. */
2649 	status = dmub_srv_create(dmub_srv, &create_params);
2650 	if (status != DMUB_STATUS_OK) {
2651 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2652 		return -EINVAL;
2653 	}
2654 
2655 	/* Extract the FW meta info. */
2656 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2657 
2658 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2659 					      PSP_HEADER_BYTES_256;
2660 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2661 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2662 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2663 					    PSP_HEADER_BYTES_256;
2664 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2665 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2666 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2667 	fw_meta_info_params.custom_psp_footer_size = 0;
2668 
2669 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2670 	if (status != DMUB_STATUS_OK) {
2671 		/* Skip returning early, just log the error. */
2672 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2673 		// return -EINVAL;
2674 	}
2675 
2676 	/* Calculate the size of all the regions for the DMUB service. */
2677 	memset(&region_params, 0, sizeof(region_params));
2678 
2679 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2680 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2681 	region_params.vbios_size = adev->bios_size;
2682 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2683 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2684 	region_params.window_memory_type = window_memory_type;
2685 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2686 
2687 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2688 					   &region_info);
2689 
2690 	if (status != DMUB_STATUS_OK) {
2691 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2692 		return -EINVAL;
2693 	}
2694 
2695 	/*
2696 	 * Allocate a framebuffer based on the total size of all the regions.
2697 	 * TODO: Move this into GART.
2698 	 */
2699 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2700 				    AMDGPU_GEM_DOMAIN_VRAM |
2701 				    AMDGPU_GEM_DOMAIN_GTT,
2702 				    &adev->dm.dmub_bo,
2703 				    &adev->dm.dmub_bo_gpu_addr,
2704 				    &adev->dm.dmub_bo_cpu_addr);
2705 	if (r)
2706 		return r;
2707 
2708 	/* Rebase the regions on the framebuffer address. */
2709 	memset(&memory_params, 0, sizeof(memory_params));
2710 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2711 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2712 	memory_params.region_info = &region_info;
2713 	memory_params.window_memory_type = window_memory_type;
2714 
2715 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2716 	fb_info = adev->dm.dmub_fb_info;
2717 
2718 	if (!fb_info) {
2719 		drm_err(adev_to_drm(adev),
2720 			"Failed to allocate framebuffer info for DMUB service!\n");
2721 		return -ENOMEM;
2722 	}
2723 
2724 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2725 	if (status != DMUB_STATUS_OK) {
2726 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2727 		return -EINVAL;
2728 	}
2729 
2730 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2731 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2732 
2733 	return 0;
2734 }
2735 
2736 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2737 {
2738 	struct amdgpu_device *adev = ip_block->adev;
2739 	int r;
2740 
2741 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2742 
2743 	if (!adev->dm.cgs_device) {
2744 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2745 		return -EINVAL;
2746 	}
2747 
2748 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2749 	INIT_LIST_HEAD(&adev->dm.da_list);
2750 
2751 	r = dm_dmub_sw_init(adev);
2752 	if (r)
2753 		return r;
2754 
2755 	return load_dmcu_fw(adev);
2756 }
2757 
2758 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2759 {
2760 	struct amdgpu_device *adev = ip_block->adev;
2761 	struct dal_allocation *da;
2762 
2763 	list_for_each_entry(da, &adev->dm.da_list, list) {
2764 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2765 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2766 			list_del(&da->list);
2767 			kfree(da);
2768 			adev->dm.bb_from_dmub = NULL;
2769 			break;
2770 		}
2771 	}
2772 
2773 
2774 	kfree(adev->dm.dmub_fb_info);
2775 	adev->dm.dmub_fb_info = NULL;
2776 
2777 	if (adev->dm.dmub_srv) {
2778 		dmub_srv_destroy(adev->dm.dmub_srv);
2779 		kfree(adev->dm.dmub_srv);
2780 		adev->dm.dmub_srv = NULL;
2781 	}
2782 
2783 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2784 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2785 
2786 	return 0;
2787 }
2788 
2789 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2790 {
2791 	struct amdgpu_dm_connector *aconnector;
2792 	struct drm_connector *connector;
2793 	struct drm_connector_list_iter iter;
2794 	int ret = 0;
2795 
2796 	drm_connector_list_iter_begin(dev, &iter);
2797 	drm_for_each_connector_iter(connector, &iter) {
2798 
2799 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2800 			continue;
2801 
2802 		aconnector = to_amdgpu_dm_connector(connector);
2803 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2804 		    aconnector->mst_mgr.aux) {
2805 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2806 					 aconnector,
2807 					 aconnector->base.base.id);
2808 
2809 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2810 			if (ret < 0) {
2811 				drm_err(dev, "DM_MST: Failed to start MST\n");
2812 				aconnector->dc_link->type =
2813 					dc_connection_single;
2814 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2815 								     aconnector->dc_link);
2816 				break;
2817 			}
2818 		}
2819 	}
2820 	drm_connector_list_iter_end(&iter);
2821 
2822 	return ret;
2823 }
2824 
2825 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2826 {
2827 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2828 	struct dmub_srv *dmub = NULL;
2829 	union dmub_fw_boot_options option = {0};
2830 	int ret = 0;
2831 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2832 
2833 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2834 		!adev->dm.dc->ctx->dmub_srv) {
2835 		return;
2836 	}
2837 
2838 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2839 	bootcrc_info = &adev->dm.boot_time_crc_info;
2840 
2841 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2842 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2843 		return;
2844 	}
2845 
2846 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2847 
2848 	/* Return if boot time CRC is not enabled */
2849 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2850 		return;
2851 
2852 	/* Create a buffer for boot time CRC */
2853 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2854 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2855 		&bootcrc_info->bo_ptr,
2856 		&bootcrc_info->gpu_addr,
2857 		&bootcrc_info->cpu_addr);
2858 
2859 	if (ret) {
2860 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2861 	} else {
2862 		bootcrc_info->size = fb_size;
2863 
2864 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2865 			bootcrc_info->gpu_addr, bootcrc_info->size);
2866 
2867 		/* Send the buffer info to DMUB */
2868 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2869 			bootcrc_info->gpu_addr, bootcrc_info->size);
2870 	}
2871 }
2872 
2873 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2874 {
2875 	struct amdgpu_device *adev = ip_block->adev;
2876 
2877 	struct dmcu_iram_parameters params;
2878 	unsigned int linear_lut[16];
2879 	int i;
2880 	struct dmcu *dmcu = NULL;
2881 
2882 	dmcu = adev->dm.dc->res_pool->dmcu;
2883 
2884 	/* Init the boot time CRC (skip in resume) */
2885 	if ((adev->in_suspend == 0) &&
2886 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2887 		amdgpu_dm_boot_time_crc_init(adev);
2888 
2889 	for (i = 0; i < 16; i++)
2890 		linear_lut[i] = 0xFFFF * i / 15;
2891 
2892 	params.set = 0;
2893 	params.backlight_ramping_override = false;
2894 	params.backlight_ramping_start = 0xCCCC;
2895 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2896 	params.backlight_lut_array_size = 16;
2897 	params.backlight_lut_array = linear_lut;
2898 
2899 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2900 	 * 0xFFFF x 0.01 = 0x28F
2901 	 */
2902 	params.min_abm_backlight = 0x28F;
2903 	/* In the case where abm is implemented on dmcub,
2904 	 * dmcu object will be null.
2905 	 * ABM 2.4 and up are implemented on dmcub.
2906 	 */
2907 	if (dmcu) {
2908 		if (!dmcu_load_iram(dmcu, params))
2909 			return -EINVAL;
2910 	} else if (adev->dm.dc->ctx->dmub_srv) {
2911 		struct dc_link *edp_links[MAX_NUM_EDP];
2912 		int edp_num;
2913 
2914 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2915 		for (i = 0; i < edp_num; i++) {
2916 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2917 				return -EINVAL;
2918 		}
2919 	}
2920 
2921 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2922 }
2923 
2924 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2925 {
2926 	u8 buf[UUID_SIZE];
2927 	guid_t guid;
2928 	int ret;
2929 
2930 	mutex_lock(&mgr->lock);
2931 	if (!mgr->mst_primary)
2932 		goto out_fail;
2933 
2934 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2935 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2936 		goto out_fail;
2937 	}
2938 
2939 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2940 				 DP_MST_EN |
2941 				 DP_UP_REQ_EN |
2942 				 DP_UPSTREAM_IS_SRC);
2943 	if (ret < 0) {
2944 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2945 		goto out_fail;
2946 	}
2947 
2948 	/* Some hubs forget their guids after they resume */
2949 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2950 	if (ret != sizeof(buf)) {
2951 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2952 		goto out_fail;
2953 	}
2954 
2955 	import_guid(&guid, buf);
2956 
2957 	if (guid_is_null(&guid)) {
2958 		guid_gen(&guid);
2959 		export_guid(buf, &guid);
2960 
2961 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2962 
2963 		if (ret != sizeof(buf)) {
2964 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2965 			goto out_fail;
2966 		}
2967 	}
2968 
2969 	guid_copy(&mgr->mst_primary->guid, &guid);
2970 
2971 out_fail:
2972 	mutex_unlock(&mgr->lock);
2973 }
2974 
2975 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2976 {
2977 	struct cec_notifier *n = aconnector->notifier;
2978 
2979 	if (!n)
2980 		return;
2981 
2982 	cec_notifier_phys_addr_invalidate(n);
2983 }
2984 
2985 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2986 {
2987 	struct drm_connector *connector = &aconnector->base;
2988 	struct cec_notifier *n = aconnector->notifier;
2989 
2990 	if (!n)
2991 		return;
2992 
2993 	cec_notifier_set_phys_addr(n,
2994 				   connector->display_info.source_physical_address);
2995 }
2996 
2997 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2998 {
2999 	struct amdgpu_dm_connector *aconnector;
3000 	struct drm_connector *connector;
3001 	struct drm_connector_list_iter conn_iter;
3002 
3003 	drm_connector_list_iter_begin(ddev, &conn_iter);
3004 	drm_for_each_connector_iter(connector, &conn_iter) {
3005 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3006 			continue;
3007 
3008 		aconnector = to_amdgpu_dm_connector(connector);
3009 		if (suspend)
3010 			hdmi_cec_unset_edid(aconnector);
3011 		else
3012 			hdmi_cec_set_edid(aconnector);
3013 	}
3014 	drm_connector_list_iter_end(&conn_iter);
3015 }
3016 
3017 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3018 {
3019 	struct amdgpu_dm_connector *aconnector;
3020 	struct drm_connector *connector;
3021 	struct drm_connector_list_iter iter;
3022 	struct drm_dp_mst_topology_mgr *mgr;
3023 
3024 	drm_connector_list_iter_begin(dev, &iter);
3025 	drm_for_each_connector_iter(connector, &iter) {
3026 
3027 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3028 			continue;
3029 
3030 		aconnector = to_amdgpu_dm_connector(connector);
3031 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3032 		    aconnector->mst_root)
3033 			continue;
3034 
3035 		mgr = &aconnector->mst_mgr;
3036 
3037 		if (suspend) {
3038 			drm_dp_mst_topology_mgr_suspend(mgr);
3039 		} else {
3040 			/* if extended timeout is supported in hardware,
3041 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3042 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3043 			 */
3044 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3045 			if (!dp_is_lttpr_present(aconnector->dc_link))
3046 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3047 
3048 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3049 			 * once topology probing work is pulled out from mst resume into mst
3050 			 * resume 2nd step. mst resume 2nd step should be called after old
3051 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3052 			 */
3053 			resume_mst_branch_status(mgr);
3054 		}
3055 	}
3056 	drm_connector_list_iter_end(&iter);
3057 }
3058 
3059 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3060 {
3061 	int ret = 0;
3062 
3063 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3064 	 * on window driver dc implementation.
3065 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3066 	 * should be passed to smu during boot up and resume from s3.
3067 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3068 	 * dcn20_resource_construct
3069 	 * then call pplib functions below to pass the settings to smu:
3070 	 * smu_set_watermarks_for_clock_ranges
3071 	 * smu_set_watermarks_table
3072 	 * navi10_set_watermarks_table
3073 	 * smu_write_watermarks_table
3074 	 *
3075 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3076 	 * dc has implemented different flow for window driver:
3077 	 * dc_hardware_init / dc_set_power_state
3078 	 * dcn10_init_hw
3079 	 * notify_wm_ranges
3080 	 * set_wm_ranges
3081 	 * -- Linux
3082 	 * smu_set_watermarks_for_clock_ranges
3083 	 * renoir_set_watermarks_table
3084 	 * smu_write_watermarks_table
3085 	 *
3086 	 * For Linux,
3087 	 * dc_hardware_init -> amdgpu_dm_init
3088 	 * dc_set_power_state --> dm_resume
3089 	 *
3090 	 * therefore, this function apply to navi10/12/14 but not Renoir
3091 	 * *
3092 	 */
3093 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3094 	case IP_VERSION(2, 0, 2):
3095 	case IP_VERSION(2, 0, 0):
3096 		break;
3097 	default:
3098 		return 0;
3099 	}
3100 
3101 	ret = amdgpu_dpm_write_watermarks_table(adev);
3102 	if (ret) {
3103 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3104 		return ret;
3105 	}
3106 
3107 	return 0;
3108 }
3109 
3110 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3111 {
3112 	struct amdgpu_display_manager *dm = &adev->dm;
3113 	struct amdgpu_i2c_adapter *oem_i2c;
3114 	struct ddc_service *oem_ddc_service;
3115 	int r;
3116 
3117 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3118 	if (oem_ddc_service) {
3119 		oem_i2c = create_i2c(oem_ddc_service, true);
3120 		if (!oem_i2c) {
3121 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3122 			return -ENOMEM;
3123 		}
3124 
3125 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3126 		if (r) {
3127 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3128 			kfree(oem_i2c);
3129 			return r;
3130 		}
3131 		dm->oem_i2c = oem_i2c;
3132 	}
3133 
3134 	return 0;
3135 }
3136 
3137 /**
3138  * dm_hw_init() - Initialize DC device
3139  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3140  *
3141  * Initialize the &struct amdgpu_display_manager device. This involves calling
3142  * the initializers of each DM component, then populating the struct with them.
3143  *
3144  * Although the function implies hardware initialization, both hardware and
3145  * software are initialized here. Splitting them out to their relevant init
3146  * hooks is a future TODO item.
3147  *
3148  * Some notable things that are initialized here:
3149  *
3150  * - Display Core, both software and hardware
3151  * - DC modules that we need (freesync and color management)
3152  * - DRM software states
3153  * - Interrupt sources and handlers
3154  * - Vblank support
3155  * - Debug FS entries, if enabled
3156  */
3157 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3158 {
3159 	struct amdgpu_device *adev = ip_block->adev;
3160 	int r;
3161 
3162 	/* Create DAL display manager */
3163 	r = amdgpu_dm_init(adev);
3164 	if (r)
3165 		return r;
3166 	amdgpu_dm_hpd_init(adev);
3167 
3168 	r = dm_oem_i2c_hw_init(adev);
3169 	if (r)
3170 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3171 
3172 	return 0;
3173 }
3174 
3175 /**
3176  * dm_hw_fini() - Teardown DC device
3177  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3178  *
3179  * Teardown components within &struct amdgpu_display_manager that require
3180  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3181  * were loaded. Also flush IRQ workqueues and disable them.
3182  */
3183 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3184 {
3185 	struct amdgpu_device *adev = ip_block->adev;
3186 
3187 	amdgpu_dm_hpd_fini(adev);
3188 
3189 	amdgpu_dm_irq_fini(adev);
3190 	amdgpu_dm_fini(adev);
3191 	return 0;
3192 }
3193 
3194 
3195 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3196 				 struct dc_state *state, bool enable)
3197 {
3198 	enum dc_irq_source irq_source;
3199 	struct amdgpu_crtc *acrtc;
3200 	int rc = -EBUSY;
3201 	int i = 0;
3202 
3203 	for (i = 0; i < state->stream_count; i++) {
3204 		acrtc = get_crtc_by_otg_inst(
3205 				adev, state->stream_status[i].primary_otg_inst);
3206 
3207 		if (acrtc && state->stream_status[i].plane_count != 0) {
3208 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3209 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3210 			if (rc)
3211 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3212 					 enable ? "enable" : "disable");
3213 
3214 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3215 				if (enable) {
3216 					if (amdgpu_dm_crtc_vrr_active(
3217 							to_dm_crtc_state(acrtc->base.state)))
3218 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3219 							&acrtc->base, true);
3220 				} else
3221 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3222 							&acrtc->base, false);
3223 
3224 				if (rc)
3225 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3226 						enable ? "en" : "dis");
3227 			}
3228 
3229 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3230 			/* During gpu-reset we disable and then enable vblank irq, so
3231 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3232 			 */
3233 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3234 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3235 		}
3236 	}
3237 
3238 }
3239 
3240 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3241 
3242 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3243 {
3244 	struct dc_state *context __free(state_release) = NULL;
3245 	int i;
3246 	struct dc_stream_state *del_streams[MAX_PIPES];
3247 	int del_streams_count = 0;
3248 	struct dc_commit_streams_params params = {};
3249 
3250 	memset(del_streams, 0, sizeof(del_streams));
3251 
3252 	context = dc_state_create_current_copy(dc);
3253 	if (context == NULL)
3254 		return DC_ERROR_UNEXPECTED;
3255 
3256 	/* First remove from context all streams */
3257 	for (i = 0; i < context->stream_count; i++) {
3258 		struct dc_stream_state *stream = context->streams[i];
3259 
3260 		del_streams[del_streams_count++] = stream;
3261 	}
3262 
3263 	/* Remove all planes for removed streams and then remove the streams */
3264 	for (i = 0; i < del_streams_count; i++) {
3265 		enum dc_status res;
3266 
3267 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3268 			return DC_FAIL_DETACH_SURFACES;
3269 
3270 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3271 		if (res != DC_OK)
3272 			return res;
3273 	}
3274 
3275 	params.streams = context->streams;
3276 	params.stream_count = context->stream_count;
3277 
3278 	return dc_commit_streams(dc, &params);
3279 }
3280 
3281 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3282 {
3283 	int i;
3284 
3285 	if (dm->hpd_rx_offload_wq) {
3286 		for (i = 0; i < dm->dc->caps.max_links; i++)
3287 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3288 	}
3289 }
3290 
3291 static int dm_cache_state(struct amdgpu_device *adev)
3292 {
3293 	int r;
3294 
3295 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3296 	if (IS_ERR(adev->dm.cached_state)) {
3297 		r = PTR_ERR(adev->dm.cached_state);
3298 		adev->dm.cached_state = NULL;
3299 	}
3300 
3301 	return adev->dm.cached_state ? 0 : r;
3302 }
3303 
3304 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3305 {
3306 	struct amdgpu_display_manager *dm = &adev->dm;
3307 	struct drm_device *ddev = adev_to_drm(adev);
3308 	struct dm_plane_state *dm_new_plane_state;
3309 	struct drm_plane_state *new_plane_state;
3310 	struct dm_crtc_state *dm_new_crtc_state;
3311 	struct drm_crtc_state *new_crtc_state;
3312 	struct drm_plane *plane;
3313 	struct drm_crtc *crtc;
3314 	int i;
3315 
3316 	if (!dm->cached_state)
3317 		return;
3318 
3319 	/* Force mode set in atomic commit */
3320 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3321 		new_crtc_state->active_changed = true;
3322 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3323 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3324 	}
3325 
3326 	/*
3327 	 * atomic_check is expected to create the dc states. We need to release
3328 	 * them here, since they were duplicated as part of the suspend
3329 	 * procedure.
3330 	 */
3331 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3332 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3333 		if (dm_new_crtc_state->stream) {
3334 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3335 			dc_stream_release(dm_new_crtc_state->stream);
3336 			dm_new_crtc_state->stream = NULL;
3337 		}
3338 		dm_new_crtc_state->base.color_mgmt_changed = true;
3339 	}
3340 
3341 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3342 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3343 		if (dm_new_plane_state->dc_state) {
3344 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3345 			dc_plane_state_release(dm_new_plane_state->dc_state);
3346 			dm_new_plane_state->dc_state = NULL;
3347 		}
3348 	}
3349 
3350 	drm_atomic_helper_resume(ddev, dm->cached_state);
3351 
3352 	dm->cached_state = NULL;
3353 }
3354 
3355 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3356 {
3357 	struct amdgpu_device *adev = ip_block->adev;
3358 	struct amdgpu_display_manager *dm = &adev->dm;
3359 
3360 	if (amdgpu_in_reset(adev)) {
3361 		enum dc_status res;
3362 
3363 		mutex_lock(&dm->dc_lock);
3364 
3365 		amdgpu_dm_ism_disable(dm);
3366 		dc_allow_idle_optimizations(adev->dm.dc, false);
3367 
3368 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3369 
3370 		if (dm->cached_dc_state)
3371 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3372 
3373 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3374 		if (res != DC_OK) {
3375 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3376 			return -EINVAL;
3377 		}
3378 
3379 		amdgpu_dm_irq_suspend(adev);
3380 
3381 		hpd_rx_irq_work_suspend(dm);
3382 
3383 		return 0;
3384 	}
3385 
3386 	if (!adev->dm.cached_state) {
3387 		int r = dm_cache_state(adev);
3388 
3389 		if (r)
3390 			return r;
3391 	}
3392 
3393 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3394 
3395 	s3_handle_mst(adev_to_drm(adev), true);
3396 
3397 	amdgpu_dm_irq_suspend(adev);
3398 
3399 	scoped_guard(mutex, &dm->dc_lock)
3400 		amdgpu_dm_ism_disable(dm);
3401 
3402 	hpd_rx_irq_work_suspend(dm);
3403 
3404 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3405 
3406 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3407 		dc_allow_idle_optimizations(dm->dc, true);
3408 
3409 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3410 
3411 	return 0;
3412 }
3413 
3414 struct drm_connector *
3415 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3416 					     struct drm_crtc *crtc)
3417 {
3418 	u32 i;
3419 	struct drm_connector_state *new_con_state;
3420 	struct drm_connector *connector;
3421 	struct drm_crtc *crtc_from_state;
3422 
3423 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3424 		crtc_from_state = new_con_state->crtc;
3425 
3426 		if (crtc_from_state == crtc)
3427 			return connector;
3428 	}
3429 
3430 	return NULL;
3431 }
3432 
3433 static void emulated_link_detect(struct dc_link *link)
3434 {
3435 	struct dc_sink_init_data sink_init_data = { 0 };
3436 	struct display_sink_capability sink_caps = { 0 };
3437 	enum dc_edid_status edid_status;
3438 	struct dc_context *dc_ctx = link->ctx;
3439 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3440 	struct dc_sink *sink = NULL;
3441 	struct dc_sink *prev_sink = NULL;
3442 
3443 	link->type = dc_connection_none;
3444 	prev_sink = link->local_sink;
3445 
3446 	if (prev_sink)
3447 		dc_sink_release(prev_sink);
3448 
3449 	switch (link->connector_signal) {
3450 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3451 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3452 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3453 		break;
3454 	}
3455 
3456 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3457 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3458 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3459 		break;
3460 	}
3461 
3462 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3463 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3464 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3465 		break;
3466 	}
3467 
3468 	case SIGNAL_TYPE_LVDS: {
3469 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3470 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3471 		break;
3472 	}
3473 
3474 	case SIGNAL_TYPE_EDP: {
3475 		sink_caps.transaction_type =
3476 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3477 		sink_caps.signal = SIGNAL_TYPE_EDP;
3478 		break;
3479 	}
3480 
3481 	case SIGNAL_TYPE_DISPLAY_PORT: {
3482 		sink_caps.transaction_type =
3483 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3484 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3485 		break;
3486 	}
3487 
3488 	default:
3489 		drm_err(dev, "Invalid connector type! signal:%d\n",
3490 			link->connector_signal);
3491 		return;
3492 	}
3493 
3494 	sink_init_data.link = link;
3495 	sink_init_data.sink_signal = sink_caps.signal;
3496 
3497 	sink = dc_sink_create(&sink_init_data);
3498 	if (!sink) {
3499 		drm_err(dev, "Failed to create sink!\n");
3500 		return;
3501 	}
3502 
3503 	/* dc_sink_create returns a new reference */
3504 	link->local_sink = sink;
3505 
3506 	edid_status = dm_helpers_read_local_edid(
3507 			link->ctx,
3508 			link,
3509 			sink);
3510 
3511 	if (edid_status != EDID_OK)
3512 		drm_err(dev, "Failed to read EDID\n");
3513 
3514 }
3515 
3516 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3517 				     struct amdgpu_display_manager *dm)
3518 {
3519 	struct {
3520 		struct dc_surface_update surface_updates[MAX_SURFACES];
3521 		struct dc_plane_info plane_infos[MAX_SURFACES];
3522 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3523 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3524 		struct dc_stream_update stream_update;
3525 	} *bundle __free(kfree);
3526 	int k, m;
3527 
3528 	bundle = kzalloc_obj(*bundle);
3529 
3530 	if (!bundle) {
3531 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3532 		return;
3533 	}
3534 
3535 	for (k = 0; k < dc_state->stream_count; k++) {
3536 		bundle->stream_update.stream = dc_state->streams[k];
3537 
3538 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3539 			bundle->surface_updates[m].surface =
3540 				dc_state->stream_status[k].plane_states[m];
3541 			bundle->surface_updates[m].surface->force_full_update =
3542 				true;
3543 		}
3544 
3545 		update_planes_and_stream_adapter(dm->dc,
3546 					 UPDATE_TYPE_FULL,
3547 					 dc_state->stream_status[k].plane_count,
3548 					 dc_state->streams[k],
3549 					 &bundle->stream_update,
3550 					 bundle->surface_updates);
3551 	}
3552 }
3553 
3554 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3555 					    struct dc_sink *sink)
3556 {
3557 	struct dc_panel_patch *ppatch = NULL;
3558 
3559 	if (!sink)
3560 		return;
3561 
3562 	ppatch = &sink->edid_caps.panel_patch;
3563 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3564 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3565 		drm_dbg_driver(adev_to_drm(adev),
3566 			       "%s: adding a %ds delay as w/a for panel\n",
3567 			       __func__,
3568 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3569 	}
3570 }
3571 
3572 /**
3573  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3574  * @adev: amdgpu device pointer
3575  *
3576  * Iterates through all DC links and dumps information about local and remote
3577  * (MST) sinks. Should be called after connector detection is complete to see
3578  * the final state of all links.
3579  */
3580 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3581 {
3582 	struct dc *dc = adev->dm.dc;
3583 	struct drm_device *dev = adev_to_drm(adev);
3584 	int li;
3585 
3586 	if (!dc)
3587 		return;
3588 
3589 	for (li = 0; li < dc->link_count; li++) {
3590 		struct dc_link *l = dc->links[li];
3591 		const char *name = NULL;
3592 		int rs;
3593 
3594 		if (!l)
3595 			continue;
3596 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3597 			name = l->local_sink->edid_caps.display_name;
3598 		else
3599 			name = "n/a";
3600 
3601 		drm_dbg_kms(dev,
3602 			"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",
3603 			li,
3604 			l->local_sink,
3605 			l->type,
3606 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3607 			l->sink_count,
3608 			name,
3609 			l->dpcd_caps.is_mst_capable,
3610 			l->mst_stream_alloc_table.stream_count);
3611 
3612 		/* Dump remote (MST) sinks if any */
3613 		for (rs = 0; rs < l->sink_count; rs++) {
3614 			struct dc_sink *rsink = l->remote_sinks[rs];
3615 			const char *rname = NULL;
3616 
3617 			if (!rsink)
3618 				continue;
3619 			if (rsink->edid_caps.display_name[0])
3620 				rname = rsink->edid_caps.display_name;
3621 			else
3622 				rname = "n/a";
3623 			drm_dbg_kms(dev,
3624 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3625 				li, rs,
3626 				rsink,
3627 				rsink->sink_signal,
3628 				rname);
3629 		}
3630 	}
3631 }
3632 
3633 static int dm_resume(struct amdgpu_ip_block *ip_block)
3634 {
3635 	struct amdgpu_device *adev = ip_block->adev;
3636 	struct drm_device *ddev = adev_to_drm(adev);
3637 	struct amdgpu_display_manager *dm = &adev->dm;
3638 	struct amdgpu_dm_connector *aconnector;
3639 	struct drm_connector *connector;
3640 	struct drm_connector_list_iter iter;
3641 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3642 	enum dc_connection_type new_connection_type = dc_connection_none;
3643 	struct dc_state *dc_state;
3644 	int i, r, j;
3645 	struct dc_commit_streams_params commit_params = {};
3646 
3647 	if (dm->dc->caps.ips_support) {
3648 		if (!amdgpu_in_reset(adev))
3649 			mutex_lock(&dm->dc_lock);
3650 
3651 		/* Need to set POWER_STATE_D0 first or it will not execute
3652 		 * idle_power_optimizations command to DMUB.
3653 		 */
3654 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3655 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3656 
3657 		if (!amdgpu_in_reset(adev))
3658 			mutex_unlock(&dm->dc_lock);
3659 	}
3660 
3661 	if (amdgpu_in_reset(adev)) {
3662 		dc_state = dm->cached_dc_state;
3663 
3664 		/*
3665 		 * The dc->current_state is backed up into dm->cached_dc_state
3666 		 * before we commit 0 streams.
3667 		 *
3668 		 * DC will clear link encoder assignments on the real state
3669 		 * but the changes won't propagate over to the copy we made
3670 		 * before the 0 streams commit.
3671 		 *
3672 		 * DC expects that link encoder assignments are *not* valid
3673 		 * when committing a state, so as a workaround we can copy
3674 		 * off of the current state.
3675 		 *
3676 		 * We lose the previous assignments, but we had already
3677 		 * commit 0 streams anyway.
3678 		 */
3679 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3680 
3681 		r = dm_dmub_hw_init(adev);
3682 		if (r) {
3683 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3684 			return r;
3685 		}
3686 
3687 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3688 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3689 
3690 		dc_resume(dm->dc);
3691 
3692 		amdgpu_dm_ism_enable(dm);
3693 		amdgpu_dm_irq_resume_early(adev);
3694 
3695 		for (i = 0; i < dc_state->stream_count; i++) {
3696 			dc_state->streams[i]->mode_changed = true;
3697 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3698 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3699 					= 0xffffffff;
3700 			}
3701 		}
3702 
3703 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3704 			amdgpu_dm_outbox_init(adev);
3705 			dc_enable_dmub_outbox(adev->dm.dc);
3706 		}
3707 
3708 		commit_params.streams = dc_state->streams;
3709 		commit_params.stream_count = dc_state->stream_count;
3710 		dc_exit_ips_for_hw_access(dm->dc);
3711 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3712 
3713 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3714 
3715 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3716 
3717 		dc_state_release(dm->cached_dc_state);
3718 		dm->cached_dc_state = NULL;
3719 
3720 		amdgpu_dm_irq_resume_late(adev);
3721 
3722 		mutex_unlock(&dm->dc_lock);
3723 
3724 		/* set the backlight after a reset */
3725 		for (i = 0; i < dm->num_of_edps; i++) {
3726 			if (dm->backlight_dev[i])
3727 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3728 		}
3729 
3730 		return 0;
3731 	}
3732 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3733 	dc_state_release(dm_state->context);
3734 	dm_state->context = dc_state_create(dm->dc, NULL);
3735 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3736 
3737 	/* Before powering on DC we need to re-initialize DMUB. */
3738 	dm_dmub_hw_resume(adev);
3739 
3740 	/* Re-enable outbox interrupts for DPIA. */
3741 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3742 		amdgpu_dm_outbox_init(adev);
3743 		dc_enable_dmub_outbox(adev->dm.dc);
3744 	}
3745 
3746 	/* power on hardware */
3747 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3748 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3749 
3750 	/* program HPD filter */
3751 	dc_resume(dm->dc);
3752 
3753 	scoped_guard(mutex, &dm->dc_lock)
3754 		amdgpu_dm_ism_enable(dm);
3755 
3756 	/*
3757 	 * early enable HPD Rx IRQ, should be done before set mode as short
3758 	 * pulse interrupts are used for MST
3759 	 */
3760 	amdgpu_dm_irq_resume_early(adev);
3761 
3762 	s3_handle_hdmi_cec(ddev, false);
3763 
3764 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3765 	s3_handle_mst(ddev, false);
3766 
3767 	/* Do detection*/
3768 	drm_connector_list_iter_begin(ddev, &iter);
3769 	drm_for_each_connector_iter(connector, &iter) {
3770 		bool ret;
3771 
3772 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3773 			continue;
3774 
3775 		aconnector = to_amdgpu_dm_connector(connector);
3776 
3777 		if (!aconnector->dc_link)
3778 			continue;
3779 
3780 		/*
3781 		 * this is the case when traversing through already created end sink
3782 		 * MST connectors, should be skipped
3783 		 */
3784 		if (aconnector->mst_root)
3785 			continue;
3786 
3787 		/* Skip eDP detection, when there is no sink present */
3788 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3789 		    !aconnector->dc_link->edp_sink_present)
3790 			continue;
3791 
3792 		guard(mutex)(&aconnector->hpd_lock);
3793 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3794 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3795 
3796 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3797 			emulated_link_detect(aconnector->dc_link);
3798 		} else {
3799 			guard(mutex)(&dm->dc_lock);
3800 			dc_exit_ips_for_hw_access(dm->dc);
3801 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3802 			if (ret) {
3803 				/* w/a delay for certain panels */
3804 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3805 			}
3806 		}
3807 
3808 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3809 			aconnector->fake_enable = false;
3810 
3811 		if (aconnector->dc_sink)
3812 			dc_sink_release(aconnector->dc_sink);
3813 		aconnector->dc_sink = NULL;
3814 		amdgpu_dm_update_connector_after_detect(aconnector);
3815 	}
3816 	drm_connector_list_iter_end(&iter);
3817 
3818 	dm_destroy_cached_state(adev);
3819 
3820 	/* Do mst topology probing after resuming cached state*/
3821 	drm_connector_list_iter_begin(ddev, &iter);
3822 	drm_for_each_connector_iter(connector, &iter) {
3823 		bool init = false;
3824 
3825 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3826 			continue;
3827 
3828 		aconnector = to_amdgpu_dm_connector(connector);
3829 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3830 		    aconnector->mst_root)
3831 			continue;
3832 
3833 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3834 			init = !aconnector->mst_mgr.mst_primary;
3835 		}
3836 		if (init)
3837 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3838 				aconnector->dc_link, false);
3839 		else
3840 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3841 	}
3842 	drm_connector_list_iter_end(&iter);
3843 
3844 	/* Debug dump: list all DC links and their associated sinks after detection
3845 	 * is complete for all connectors. This provides a comprehensive view of the
3846 	 * final state without repeating the dump for each connector.
3847 	 */
3848 	amdgpu_dm_dump_links_and_sinks(adev);
3849 
3850 	amdgpu_dm_irq_resume_late(adev);
3851 
3852 	amdgpu_dm_smu_write_watermarks_table(adev);
3853 
3854 	drm_kms_helper_hotplug_event(ddev);
3855 
3856 	return 0;
3857 }
3858 
3859 /**
3860  * DOC: DM Lifecycle
3861  *
3862  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3863  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3864  * the base driver's device list to be initialized and torn down accordingly.
3865  *
3866  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3867  */
3868 
3869 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3870 	.name = "dm",
3871 	.early_init = dm_early_init,
3872 	.late_init = dm_late_init,
3873 	.sw_init = dm_sw_init,
3874 	.sw_fini = dm_sw_fini,
3875 	.early_fini = amdgpu_dm_early_fini,
3876 	.hw_init = dm_hw_init,
3877 	.hw_fini = dm_hw_fini,
3878 	.suspend = dm_suspend,
3879 	.resume = dm_resume,
3880 	.is_idle = dm_is_idle,
3881 	.wait_for_idle = dm_wait_for_idle,
3882 	.check_soft_reset = dm_check_soft_reset,
3883 	.soft_reset = dm_soft_reset,
3884 	.set_clockgating_state = dm_set_clockgating_state,
3885 	.set_powergating_state = dm_set_powergating_state,
3886 };
3887 
3888 const struct amdgpu_ip_block_version dm_ip_block = {
3889 	.type = AMD_IP_BLOCK_TYPE_DCE,
3890 	.major = 1,
3891 	.minor = 0,
3892 	.rev = 0,
3893 	.funcs = &amdgpu_dm_funcs,
3894 };
3895 
3896 
3897 /**
3898  * DOC: atomic
3899  *
3900  * *WIP*
3901  */
3902 
3903 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3904 	.fb_create = amdgpu_display_user_framebuffer_create,
3905 	.get_format_info = amdgpu_dm_plane_get_format_info,
3906 	.atomic_check = amdgpu_dm_atomic_check,
3907 	.atomic_commit = drm_atomic_helper_commit,
3908 };
3909 
3910 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3911 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3912 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3913 };
3914 
3915 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3916 
3917 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3918 {
3919 	struct drm_connector *connector = &aconnector->base;
3920 	struct drm_display_info *display_info = &connector->display_info;
3921 	struct dc_link *link = aconnector->dc_link;
3922 	struct amdgpu_device *adev;
3923 
3924 	adev = drm_to_adev(connector->dev);
3925 
3926 	link->panel_type = PANEL_TYPE_NONE;
3927 
3928 	switch (display_info->amd_vsdb.panel_type) {
3929 	case AMD_VSDB_PANEL_TYPE_OLED:
3930 		link->panel_type = PANEL_TYPE_OLED;
3931 		break;
3932 	case AMD_VSDB_PANEL_TYPE_MINILED:
3933 		link->panel_type = PANEL_TYPE_MINILED;
3934 		break;
3935 	}
3936 
3937 	/* If VSDB didn't determine panel type, check DPCD ext caps */
3938 	if (link->panel_type == PANEL_TYPE_NONE) {
3939 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
3940 			link->panel_type = PANEL_TYPE_MINILED;
3941 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
3942 			link->panel_type = PANEL_TYPE_OLED;
3943 	}
3944 
3945 	/*
3946 	 * TODO: get panel type from DID2 that has device technology field
3947 	 * to specify if it's OLED or not. But we need to wait for DID2
3948 	 * support in DC and EDID parser to be able to use it here.
3949 	 */
3950 
3951 	if (link->panel_type == PANEL_TYPE_NONE) {
3952 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
3953 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
3954 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
3955 
3956 		if (vsdb->version && link->local_sink &&
3957 		    link->local_sink->edid_caps.manufacturer_id ==
3958 		    DDC_MANUFACTURERNAME_SAMSUNG &&
3959 		    lum1_max >= ((lum2_max * 3) / 2))
3960 			link->panel_type = PANEL_TYPE_MINILED;
3961 	}
3962 
3963 	if (link->panel_type == PANEL_TYPE_OLED)
3964 		drm_object_property_set_value(&connector->base,
3965 		    adev_to_drm(adev)->mode_config.panel_type_property,
3966 		    DRM_MODE_PANEL_TYPE_OLED);
3967 	else
3968 		drm_object_property_set_value(&connector->base,
3969 		    adev_to_drm(adev)->mode_config.panel_type_property,
3970 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
3971 
3972 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
3973 }
3974 
3975 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3976 {
3977 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3978 	struct amdgpu_dm_backlight_caps *caps;
3979 	struct drm_connector *conn_base;
3980 	struct amdgpu_device *adev;
3981 	struct drm_luminance_range_info *luminance_range;
3982 	struct drm_device *drm;
3983 
3984 	if (aconnector->bl_idx == -1 ||
3985 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3986 		return;
3987 
3988 	conn_base = &aconnector->base;
3989 	drm = conn_base->dev;
3990 	adev = drm_to_adev(drm);
3991 
3992 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3993 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3994 	caps->aux_support = false;
3995 
3996 	if (caps->ext_caps->bits.oled == 1
3997 	    /*
3998 	     * ||
3999 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4000 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4001 	     */)
4002 		caps->aux_support = true;
4003 
4004 	if (amdgpu_backlight == 0)
4005 		caps->aux_support = false;
4006 	else if (amdgpu_backlight == 1)
4007 		caps->aux_support = true;
4008 	if (caps->aux_support)
4009 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4010 
4011 	luminance_range = &conn_base->display_info.luminance_range;
4012 
4013 	if (luminance_range->max_luminance)
4014 		caps->aux_max_input_signal = luminance_range->max_luminance;
4015 	else
4016 		caps->aux_max_input_signal = 512;
4017 
4018 	if (luminance_range->min_luminance)
4019 		caps->aux_min_input_signal = luminance_range->min_luminance;
4020 	else
4021 		caps->aux_min_input_signal = 1;
4022 
4023 	panel_backlight_quirk =
4024 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4025 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4026 		if (panel_backlight_quirk->min_brightness) {
4027 			caps->min_input_signal =
4028 				panel_backlight_quirk->min_brightness - 1;
4029 			drm_info(drm,
4030 				 "Applying panel backlight quirk, min_brightness: %d\n",
4031 				 caps->min_input_signal);
4032 		}
4033 		if (panel_backlight_quirk->brightness_mask) {
4034 			drm_info(drm,
4035 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4036 				 panel_backlight_quirk->brightness_mask);
4037 			caps->brightness_mask =
4038 				panel_backlight_quirk->brightness_mask;
4039 		}
4040 	}
4041 }
4042 
4043 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4044 
4045 void amdgpu_dm_update_connector_after_detect(
4046 		struct amdgpu_dm_connector *aconnector)
4047 {
4048 	struct drm_connector *connector = &aconnector->base;
4049 	struct dc_sink *sink __free(sink_release) = NULL;
4050 	struct drm_device *dev = connector->dev;
4051 
4052 	/* MST handled by drm_mst framework */
4053 	if (aconnector->mst_mgr.mst_state == true)
4054 		return;
4055 
4056 	sink = aconnector->dc_link->local_sink;
4057 	if (sink)
4058 		dc_sink_retain(sink);
4059 
4060 	/*
4061 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4062 	 * the connector sink is set to either fake or physical sink depends on link status.
4063 	 * Skip if already done during boot.
4064 	 */
4065 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4066 			&& aconnector->dc_em_sink) {
4067 
4068 		/*
4069 		 * For S3 resume with headless use eml_sink to fake stream
4070 		 * because on resume connector->sink is set to NULL
4071 		 */
4072 		guard(mutex)(&dev->mode_config.mutex);
4073 
4074 		if (sink) {
4075 			if (aconnector->dc_sink) {
4076 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4077 				/*
4078 				 * retain and release below are used to
4079 				 * bump up refcount for sink because the link doesn't point
4080 				 * to it anymore after disconnect, so on next crtc to connector
4081 				 * reshuffle by UMD we will get into unwanted dc_sink release
4082 				 */
4083 				dc_sink_release(aconnector->dc_sink);
4084 			}
4085 			aconnector->dc_sink = sink;
4086 			dc_sink_retain(aconnector->dc_sink);
4087 			amdgpu_dm_update_freesync_caps(connector,
4088 					aconnector->drm_edid, true);
4089 		} else {
4090 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4091 			if (!aconnector->dc_sink) {
4092 				aconnector->dc_sink = aconnector->dc_em_sink;
4093 				dc_sink_retain(aconnector->dc_sink);
4094 			}
4095 		}
4096 
4097 		return;
4098 	}
4099 
4100 	/*
4101 	 * TODO: temporary guard to look for proper fix
4102 	 * if this sink is MST sink, we should not do anything
4103 	 */
4104 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4105 		return;
4106 
4107 	if (aconnector->dc_sink == sink) {
4108 		/*
4109 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4110 		 * Do nothing!!
4111 		 */
4112 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4113 				 aconnector->connector_id);
4114 		return;
4115 	}
4116 
4117 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4118 		    aconnector->connector_id, aconnector->dc_sink, sink);
4119 
4120 	/* When polling, DRM has already locked the mutex for us. */
4121 	if (!drm_kms_helper_is_poll_worker())
4122 		mutex_lock(&dev->mode_config.mutex);
4123 
4124 	/*
4125 	 * 1. Update status of the drm connector
4126 	 * 2. Send an event and let userspace tell us what to do
4127 	 */
4128 	if (sink) {
4129 		/*
4130 		 * TODO: check if we still need the S3 mode update workaround.
4131 		 * If yes, put it here.
4132 		 */
4133 		if (aconnector->dc_sink) {
4134 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4135 			dc_sink_release(aconnector->dc_sink);
4136 		}
4137 
4138 		aconnector->dc_sink = sink;
4139 		dc_sink_retain(aconnector->dc_sink);
4140 		drm_edid_free(aconnector->drm_edid);
4141 		aconnector->drm_edid = NULL;
4142 		if (sink->dc_edid.length == 0) {
4143 			hdmi_cec_unset_edid(aconnector);
4144 			if (aconnector->dc_link->aux_mode) {
4145 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4146 			}
4147 		} else {
4148 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4149 
4150 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4151 			drm_edid_connector_update(connector, aconnector->drm_edid);
4152 
4153 			hdmi_cec_set_edid(aconnector);
4154 			if (aconnector->dc_link->aux_mode)
4155 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4156 						  connector->display_info.source_physical_address);
4157 		}
4158 
4159 		if (!aconnector->timing_requested) {
4160 			aconnector->timing_requested =
4161 				kzalloc_obj(struct dc_crtc_timing);
4162 			if (!aconnector->timing_requested)
4163 				drm_err(dev,
4164 					"failed to create aconnector->requested_timing\n");
4165 		}
4166 
4167 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4168 		update_connector_ext_caps(aconnector);
4169 		dm_set_panel_type(aconnector);
4170 	} else {
4171 		hdmi_cec_unset_edid(aconnector);
4172 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4173 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4174 		aconnector->num_modes = 0;
4175 		dc_sink_release(aconnector->dc_sink);
4176 		aconnector->dc_sink = NULL;
4177 		drm_edid_free(aconnector->drm_edid);
4178 		aconnector->drm_edid = NULL;
4179 		kfree(aconnector->timing_requested);
4180 		aconnector->timing_requested = NULL;
4181 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4182 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4183 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4184 	}
4185 
4186 	update_subconnector_property(aconnector);
4187 
4188 	/* When polling, the mutex will be unlocked for us by DRM. */
4189 	if (!drm_kms_helper_is_poll_worker())
4190 		mutex_unlock(&dev->mode_config.mutex);
4191 }
4192 
4193 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4194 {
4195 	if (!sink1 || !sink2)
4196 		return false;
4197 	if (sink1->sink_signal != sink2->sink_signal)
4198 		return false;
4199 
4200 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4201 		return false;
4202 
4203 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4204 		   sink1->dc_edid.length) != 0)
4205 		return false;
4206 	return true;
4207 }
4208 
4209 
4210 /**
4211  * DOC: hdmi_hpd_debounce_work
4212  *
4213  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4214  * (such as during power save transitions), this delay determines how long to
4215  * wait before processing the HPD event. This allows distinguishing between a
4216  * physical unplug (>hdmi_hpd_debounce_delay)
4217  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4218  *
4219  * If the toggle is less than this delay, the driver compares sink capabilities
4220  * and permits a hotplug event if they changed.
4221  *
4222  * The default value of 1500ms was chosen based on experimental testing with
4223  * various monitors that exhibit spontaneous HPD toggling behavior.
4224  */
4225 static void hdmi_hpd_debounce_work(struct work_struct *work)
4226 {
4227 	struct amdgpu_dm_connector *aconnector =
4228 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4229 			     hdmi_hpd_debounce_work);
4230 	struct drm_connector *connector = &aconnector->base;
4231 	struct drm_device *dev = connector->dev;
4232 	struct amdgpu_device *adev = drm_to_adev(dev);
4233 	struct dc *dc = aconnector->dc_link->ctx->dc;
4234 	bool fake_reconnect = false;
4235 	bool reallow_idle = false;
4236 	bool ret = false;
4237 	guard(mutex)(&aconnector->hpd_lock);
4238 
4239 	/* Re-detect the display */
4240 	scoped_guard(mutex, &adev->dm.dc_lock) {
4241 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4242 			dc_allow_idle_optimizations(dc, false);
4243 			reallow_idle = true;
4244 		}
4245 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4246 	}
4247 
4248 	if (ret) {
4249 		/* Apply workaround delay for certain panels */
4250 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4251 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4252 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4253 			/*
4254 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4255 			*/
4256 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4257 			fake_reconnect = true;
4258 		}
4259 
4260 		/* Update connector state */
4261 		amdgpu_dm_update_connector_after_detect(aconnector);
4262 
4263 		drm_modeset_lock_all(dev);
4264 		dm_restore_drm_connector_state(dev, connector);
4265 		drm_modeset_unlock_all(dev);
4266 
4267 		/* Only notify OS if sink actually changed */
4268 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4269 			drm_kms_helper_hotplug_event(dev);
4270 	}
4271 
4272 	/* Release the cached sink reference */
4273 	if (aconnector->hdmi_prev_sink) {
4274 		dc_sink_release(aconnector->hdmi_prev_sink);
4275 		aconnector->hdmi_prev_sink = NULL;
4276 	}
4277 
4278 	scoped_guard(mutex, &adev->dm.dc_lock) {
4279 		if (reallow_idle && dc->caps.ips_support)
4280 			dc_allow_idle_optimizations(dc, true);
4281 	}
4282 }
4283 
4284 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4285 {
4286 	struct drm_connector *connector = &aconnector->base;
4287 	struct drm_device *dev = connector->dev;
4288 	enum dc_connection_type new_connection_type = dc_connection_none;
4289 	struct amdgpu_device *adev = drm_to_adev(dev);
4290 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4291 	struct dc *dc = aconnector->dc_link->ctx->dc;
4292 	bool ret = false;
4293 	bool debounce_required = false;
4294 
4295 	if (adev->dm.disable_hpd_irq)
4296 		return;
4297 
4298 	/*
4299 	 * In case of failure or MST no need to update connector status or notify the OS
4300 	 * since (for MST case) MST does this in its own context.
4301 	 */
4302 	guard(mutex)(&aconnector->hpd_lock);
4303 
4304 	if (adev->dm.hdcp_workqueue) {
4305 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4306 		dm_con_state->update_hdcp = true;
4307 	}
4308 	if (aconnector->fake_enable)
4309 		aconnector->fake_enable = false;
4310 
4311 	aconnector->timing_changed = false;
4312 
4313 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4314 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4315 
4316 	/*
4317 	 * Check for HDMI disconnect with debounce enabled.
4318 	 */
4319 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4320 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4321 			      new_connection_type == dc_connection_none &&
4322 			      aconnector->dc_link->local_sink != NULL);
4323 
4324 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4325 		emulated_link_detect(aconnector->dc_link);
4326 
4327 		drm_modeset_lock_all(dev);
4328 		dm_restore_drm_connector_state(dev, connector);
4329 		drm_modeset_unlock_all(dev);
4330 
4331 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4332 			drm_kms_helper_connector_hotplug_event(connector);
4333 	} else if (debounce_required) {
4334 		/*
4335 		 * HDMI disconnect detected - schedule delayed work instead of
4336 		 * processing immediately. This allows us to coalesce spurious
4337 		 * HDMI signals from physical unplugs.
4338 		 */
4339 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4340 			    aconnector->hdmi_hpd_debounce_delay_ms);
4341 
4342 		/* Cache the current sink for later comparison */
4343 		if (aconnector->hdmi_prev_sink)
4344 			dc_sink_release(aconnector->hdmi_prev_sink);
4345 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4346 		if (aconnector->hdmi_prev_sink)
4347 			dc_sink_retain(aconnector->hdmi_prev_sink);
4348 
4349 		/* Schedule delayed detection. */
4350 		if (mod_delayed_work(system_percpu_wq,
4351 				 &aconnector->hdmi_hpd_debounce_work,
4352 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4353 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4354 
4355 	} else {
4356 
4357 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4358 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4359 			return;
4360 
4361 		scoped_guard(mutex, &adev->dm.dc_lock) {
4362 			dc_exit_ips_for_hw_access(dc);
4363 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4364 		}
4365 		if (ret) {
4366 			/* w/a delay for certain panels */
4367 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4368 			amdgpu_dm_update_connector_after_detect(aconnector);
4369 
4370 			drm_modeset_lock_all(dev);
4371 			dm_restore_drm_connector_state(dev, connector);
4372 			drm_modeset_unlock_all(dev);
4373 
4374 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4375 				drm_kms_helper_connector_hotplug_event(connector);
4376 		}
4377 	}
4378 }
4379 
4380 static void handle_hpd_irq(void *param)
4381 {
4382 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4383 
4384 	handle_hpd_irq_helper(aconnector);
4385 
4386 }
4387 
4388 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4389 							union hpd_irq_data hpd_irq_data)
4390 {
4391 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4392 
4393 	if (!offload_work) {
4394 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4395 		return;
4396 	}
4397 
4398 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4399 	offload_work->data = hpd_irq_data;
4400 	offload_work->offload_wq = offload_wq;
4401 	offload_work->adev = adev;
4402 
4403 	queue_work(offload_wq->wq, &offload_work->work);
4404 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4405 }
4406 
4407 static void handle_hpd_rx_irq(void *param)
4408 {
4409 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4410 	struct drm_connector *connector = &aconnector->base;
4411 	struct drm_device *dev = connector->dev;
4412 	struct dc_link *dc_link = aconnector->dc_link;
4413 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4414 	bool result = false;
4415 	enum dc_connection_type new_connection_type = dc_connection_none;
4416 	struct amdgpu_device *adev = drm_to_adev(dev);
4417 	union hpd_irq_data hpd_irq_data;
4418 	bool link_loss = false;
4419 	bool has_left_work = false;
4420 	int idx = dc_link->link_index;
4421 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4422 	struct dc *dc = aconnector->dc_link->ctx->dc;
4423 
4424 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4425 
4426 	if (adev->dm.disable_hpd_irq)
4427 		return;
4428 
4429 	/*
4430 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4431 	 * conflict, after implement i2c helper, this mutex should be
4432 	 * retired.
4433 	 */
4434 	mutex_lock(&aconnector->hpd_lock);
4435 
4436 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4437 						&link_loss, true, &has_left_work);
4438 
4439 	if (!has_left_work)
4440 		goto out;
4441 
4442 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4443 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4444 		goto out;
4445 	}
4446 
4447 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4448 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4449 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4450 			bool skip = false;
4451 
4452 			/*
4453 			 * DOWN_REP_MSG_RDY is also handled by polling method
4454 			 * mgr->cbs->poll_hpd_irq()
4455 			 */
4456 			spin_lock(&offload_wq->offload_lock);
4457 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4458 
4459 			if (!skip)
4460 				offload_wq->is_handling_mst_msg_rdy_event = true;
4461 
4462 			spin_unlock(&offload_wq->offload_lock);
4463 
4464 			if (!skip)
4465 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4466 
4467 			goto out;
4468 		}
4469 
4470 		if (link_loss) {
4471 			bool skip = false;
4472 
4473 			spin_lock(&offload_wq->offload_lock);
4474 			skip = offload_wq->is_handling_link_loss;
4475 
4476 			if (!skip)
4477 				offload_wq->is_handling_link_loss = true;
4478 
4479 			spin_unlock(&offload_wq->offload_lock);
4480 
4481 			if (!skip)
4482 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4483 
4484 			goto out;
4485 		}
4486 	}
4487 
4488 out:
4489 	if (result && !is_mst_root_connector) {
4490 		/* Downstream Port status changed. */
4491 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4492 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4493 
4494 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4495 			emulated_link_detect(dc_link);
4496 
4497 			if (aconnector->fake_enable)
4498 				aconnector->fake_enable = false;
4499 
4500 			amdgpu_dm_update_connector_after_detect(aconnector);
4501 
4502 
4503 			drm_modeset_lock_all(dev);
4504 			dm_restore_drm_connector_state(dev, connector);
4505 			drm_modeset_unlock_all(dev);
4506 
4507 			drm_kms_helper_connector_hotplug_event(connector);
4508 		} else {
4509 			bool ret = false;
4510 
4511 			mutex_lock(&adev->dm.dc_lock);
4512 			dc_exit_ips_for_hw_access(dc);
4513 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4514 			mutex_unlock(&adev->dm.dc_lock);
4515 
4516 			if (ret) {
4517 				if (aconnector->fake_enable)
4518 					aconnector->fake_enable = false;
4519 
4520 				amdgpu_dm_update_connector_after_detect(aconnector);
4521 
4522 				drm_modeset_lock_all(dev);
4523 				dm_restore_drm_connector_state(dev, connector);
4524 				drm_modeset_unlock_all(dev);
4525 
4526 				drm_kms_helper_connector_hotplug_event(connector);
4527 			}
4528 		}
4529 	}
4530 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4531 		if (adev->dm.hdcp_workqueue)
4532 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4533 	}
4534 
4535 	if (dc_link->type != dc_connection_mst_branch)
4536 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4537 
4538 	mutex_unlock(&aconnector->hpd_lock);
4539 }
4540 
4541 static int register_hpd_handlers(struct amdgpu_device *adev)
4542 {
4543 	struct drm_device *dev = adev_to_drm(adev);
4544 	struct drm_connector *connector;
4545 	struct amdgpu_dm_connector *aconnector;
4546 	const struct dc_link *dc_link;
4547 	struct dc_interrupt_params int_params = {0};
4548 
4549 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4550 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4551 
4552 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4553 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4554 			dmub_hpd_callback, true)) {
4555 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4556 			return -EINVAL;
4557 		}
4558 
4559 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4560 			dmub_hpd_callback, true)) {
4561 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4562 			return -EINVAL;
4563 		}
4564 
4565 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4566 			dmub_hpd_sense_callback, true)) {
4567 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4568 			return -EINVAL;
4569 		}
4570 	}
4571 
4572 	list_for_each_entry(connector,
4573 			&dev->mode_config.connector_list, head)	{
4574 
4575 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4576 			continue;
4577 
4578 		aconnector = to_amdgpu_dm_connector(connector);
4579 		dc_link = aconnector->dc_link;
4580 
4581 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4582 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4583 			int_params.irq_source = dc_link->irq_source_hpd;
4584 
4585 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4586 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4587 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4588 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4589 				return -EINVAL;
4590 			}
4591 
4592 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4593 				handle_hpd_irq, (void *) aconnector))
4594 				return -ENOMEM;
4595 		}
4596 
4597 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4598 
4599 			/* Also register for DP short pulse (hpd_rx). */
4600 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4601 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4602 
4603 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4604 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4605 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4606 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4607 				return -EINVAL;
4608 			}
4609 
4610 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4611 				handle_hpd_rx_irq, (void *) aconnector))
4612 				return -ENOMEM;
4613 		}
4614 	}
4615 	return 0;
4616 }
4617 
4618 /* Register IRQ sources and initialize IRQ callbacks */
4619 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4620 {
4621 	struct dc *dc = adev->dm.dc;
4622 	struct common_irq_params *c_irq_params;
4623 	struct dc_interrupt_params int_params = {0};
4624 	int r;
4625 	int i;
4626 	unsigned int src_id;
4627 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4628 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4629 	const unsigned int vblank_d1 =
4630 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4631 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4632 
4633 	if (adev->family >= AMDGPU_FAMILY_AI)
4634 		client_id = SOC15_IH_CLIENTID_DCE;
4635 
4636 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4637 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4638 
4639 	/*
4640 	 * Actions of amdgpu_irq_add_id():
4641 	 * 1. Register a set() function with base driver.
4642 	 *    Base driver will call set() function to enable/disable an
4643 	 *    interrupt in DC hardware.
4644 	 * 2. Register amdgpu_dm_irq_handler().
4645 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4646 	 *    coming from DC hardware.
4647 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4648 	 *    for acknowledging and handling.
4649 	 */
4650 
4651 	/* Use VBLANK interrupt */
4652 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4653 		src_id = vblank_d1 + i;
4654 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4655 		if (r) {
4656 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4657 			return r;
4658 		}
4659 
4660 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4661 		int_params.irq_source =
4662 			dc_interrupt_to_irq_source(dc, src_id, 0);
4663 
4664 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4665 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4666 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4667 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4668 			return -EINVAL;
4669 		}
4670 
4671 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4672 
4673 		c_irq_params->adev = adev;
4674 		c_irq_params->irq_src = int_params.irq_source;
4675 
4676 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4677 			dm_crtc_high_irq, c_irq_params))
4678 			return -ENOMEM;
4679 	}
4680 
4681 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4682 		/* Use VUPDATE interrupt */
4683 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4684 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4685 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4686 			if (r) {
4687 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4688 				return r;
4689 			}
4690 
4691 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4692 			int_params.irq_source =
4693 				dc_interrupt_to_irq_source(dc, src_id, 0);
4694 
4695 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4696 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4697 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4698 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4699 				return -EINVAL;
4700 			}
4701 
4702 			c_irq_params = &adev->dm.vupdate_params[
4703 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4704 			c_irq_params->adev = adev;
4705 			c_irq_params->irq_src = int_params.irq_source;
4706 
4707 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4708 				dm_vupdate_high_irq, c_irq_params))
4709 				return -ENOMEM;
4710 		}
4711 	}
4712 
4713 	/* Use GRPH_PFLIP interrupt */
4714 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4715 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4716 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4717 		if (r) {
4718 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4719 			return r;
4720 		}
4721 
4722 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4723 		int_params.irq_source =
4724 			dc_interrupt_to_irq_source(dc, i, 0);
4725 
4726 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4727 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4728 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4729 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4730 			return -EINVAL;
4731 		}
4732 
4733 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4734 
4735 		c_irq_params->adev = adev;
4736 		c_irq_params->irq_src = int_params.irq_source;
4737 
4738 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4739 			dm_pflip_high_irq, c_irq_params))
4740 			return -ENOMEM;
4741 	}
4742 
4743 	/* HPD */
4744 	r = amdgpu_irq_add_id(adev, client_id,
4745 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4746 	if (r) {
4747 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4748 		return r;
4749 	}
4750 
4751 	r = register_hpd_handlers(adev);
4752 
4753 	return r;
4754 }
4755 
4756 /* Register IRQ sources and initialize IRQ callbacks */
4757 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4758 {
4759 	struct dc *dc = adev->dm.dc;
4760 	struct common_irq_params *c_irq_params;
4761 	struct dc_interrupt_params int_params = {0};
4762 	int r;
4763 	int i;
4764 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4765 	static const unsigned int vrtl_int_srcid[] = {
4766 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4767 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4768 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4769 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4770 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4771 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4772 	};
4773 #endif
4774 
4775 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4776 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4777 
4778 	/*
4779 	 * Actions of amdgpu_irq_add_id():
4780 	 * 1. Register a set() function with base driver.
4781 	 *    Base driver will call set() function to enable/disable an
4782 	 *    interrupt in DC hardware.
4783 	 * 2. Register amdgpu_dm_irq_handler().
4784 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4785 	 *    coming from DC hardware.
4786 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4787 	 *    for acknowledging and handling.
4788 	 */
4789 
4790 	/* Use VSTARTUP interrupt */
4791 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4792 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4793 			i++) {
4794 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4795 
4796 		if (r) {
4797 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4798 			return r;
4799 		}
4800 
4801 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4802 		int_params.irq_source =
4803 			dc_interrupt_to_irq_source(dc, i, 0);
4804 
4805 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4806 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4807 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4808 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4809 			return -EINVAL;
4810 		}
4811 
4812 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4813 
4814 		c_irq_params->adev = adev;
4815 		c_irq_params->irq_src = int_params.irq_source;
4816 
4817 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4818 			dm_crtc_high_irq, c_irq_params))
4819 			return -ENOMEM;
4820 	}
4821 
4822 	/* Use otg vertical line interrupt */
4823 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4824 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4825 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4826 				vrtl_int_srcid[i], &adev->vline0_irq);
4827 
4828 		if (r) {
4829 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4830 			return r;
4831 		}
4832 
4833 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4834 		int_params.irq_source =
4835 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4836 
4837 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4838 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4839 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4840 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4841 			return -EINVAL;
4842 		}
4843 
4844 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4845 					- DC_IRQ_SOURCE_DC1_VLINE0];
4846 
4847 		c_irq_params->adev = adev;
4848 		c_irq_params->irq_src = int_params.irq_source;
4849 
4850 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4851 			dm_dcn_vertical_interrupt0_high_irq,
4852 			c_irq_params))
4853 			return -ENOMEM;
4854 	}
4855 #endif
4856 
4857 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4858 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4859 	 * to trigger at end of each vblank, regardless of state of the lock,
4860 	 * matching DCE behaviour.
4861 	 */
4862 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4863 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4864 	     i++) {
4865 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4866 
4867 		if (r) {
4868 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4869 			return r;
4870 		}
4871 
4872 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4873 		int_params.irq_source =
4874 			dc_interrupt_to_irq_source(dc, i, 0);
4875 
4876 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4877 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4878 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4879 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4880 			return -EINVAL;
4881 		}
4882 
4883 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4884 
4885 		c_irq_params->adev = adev;
4886 		c_irq_params->irq_src = int_params.irq_source;
4887 
4888 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4889 			dm_vupdate_high_irq, c_irq_params))
4890 			return -ENOMEM;
4891 	}
4892 
4893 	/* Use GRPH_PFLIP interrupt */
4894 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4895 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4896 			i++) {
4897 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4898 		if (r) {
4899 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4900 			return r;
4901 		}
4902 
4903 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4904 		int_params.irq_source =
4905 			dc_interrupt_to_irq_source(dc, i, 0);
4906 
4907 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4908 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4909 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4910 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4911 			return -EINVAL;
4912 		}
4913 
4914 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4915 
4916 		c_irq_params->adev = adev;
4917 		c_irq_params->irq_src = int_params.irq_source;
4918 
4919 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4920 			dm_pflip_high_irq, c_irq_params))
4921 			return -ENOMEM;
4922 	}
4923 
4924 	/* HPD */
4925 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4926 			&adev->hpd_irq);
4927 	if (r) {
4928 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4929 		return r;
4930 	}
4931 
4932 	r = register_hpd_handlers(adev);
4933 
4934 	return r;
4935 }
4936 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4937 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4938 {
4939 	struct dc *dc = adev->dm.dc;
4940 	struct common_irq_params *c_irq_params;
4941 	struct dc_interrupt_params int_params = {0};
4942 	int r, i;
4943 
4944 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4945 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4946 
4947 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4948 			&adev->dmub_outbox_irq);
4949 	if (r) {
4950 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4951 		return r;
4952 	}
4953 
4954 	if (dc->ctx->dmub_srv) {
4955 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4956 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4957 		int_params.irq_source =
4958 		dc_interrupt_to_irq_source(dc, i, 0);
4959 
4960 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4961 
4962 		c_irq_params->adev = adev;
4963 		c_irq_params->irq_src = int_params.irq_source;
4964 
4965 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4966 			dm_dmub_outbox1_low_irq, c_irq_params))
4967 			return -ENOMEM;
4968 	}
4969 
4970 	return 0;
4971 }
4972 
4973 /*
4974  * Acquires the lock for the atomic state object and returns
4975  * the new atomic state.
4976  *
4977  * This should only be called during atomic check.
4978  */
4979 int dm_atomic_get_state(struct drm_atomic_state *state,
4980 			struct dm_atomic_state **dm_state)
4981 {
4982 	struct drm_device *dev = state->dev;
4983 	struct amdgpu_device *adev = drm_to_adev(dev);
4984 	struct amdgpu_display_manager *dm = &adev->dm;
4985 	struct drm_private_state *priv_state;
4986 
4987 	if (*dm_state)
4988 		return 0;
4989 
4990 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4991 	if (IS_ERR(priv_state))
4992 		return PTR_ERR(priv_state);
4993 
4994 	*dm_state = to_dm_atomic_state(priv_state);
4995 
4996 	return 0;
4997 }
4998 
4999 static struct dm_atomic_state *
5000 dm_atomic_get_new_state(struct drm_atomic_state *state)
5001 {
5002 	struct drm_device *dev = state->dev;
5003 	struct amdgpu_device *adev = drm_to_adev(dev);
5004 	struct amdgpu_display_manager *dm = &adev->dm;
5005 	struct drm_private_obj *obj;
5006 	struct drm_private_state *new_obj_state;
5007 	int i;
5008 
5009 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5010 		if (obj->funcs == dm->atomic_obj.funcs)
5011 			return to_dm_atomic_state(new_obj_state);
5012 	}
5013 
5014 	return NULL;
5015 }
5016 
5017 static struct drm_private_state *
5018 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5019 {
5020 	struct dm_atomic_state *old_state, *new_state;
5021 
5022 	new_state = kzalloc_obj(*new_state);
5023 	if (!new_state)
5024 		return NULL;
5025 
5026 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5027 
5028 	old_state = to_dm_atomic_state(obj->state);
5029 
5030 	if (old_state && old_state->context)
5031 		new_state->context = dc_state_create_copy(old_state->context);
5032 
5033 	if (!new_state->context) {
5034 		kfree(new_state);
5035 		return NULL;
5036 	}
5037 
5038 	return &new_state->base;
5039 }
5040 
5041 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5042 				    struct drm_private_state *state)
5043 {
5044 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5045 
5046 	if (dm_state && dm_state->context)
5047 		dc_state_release(dm_state->context);
5048 
5049 	kfree(dm_state);
5050 }
5051 
5052 static struct drm_private_state *
5053 dm_atomic_create_state(struct drm_private_obj *obj)
5054 {
5055 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5056 	struct dm_atomic_state *dm_state;
5057 	struct dc_state *context;
5058 
5059 	dm_state = kzalloc_obj(*dm_state);
5060 	if (!dm_state)
5061 		return ERR_PTR(-ENOMEM);
5062 
5063 	context = dc_state_create_current_copy(adev->dm.dc);
5064 	if (!context) {
5065 		kfree(dm_state);
5066 		return ERR_PTR(-ENOMEM);
5067 	}
5068 
5069 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5070 	dm_state->context = context;
5071 
5072 	return &dm_state->base;
5073 }
5074 
5075 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5076 	.atomic_create_state = dm_atomic_create_state,
5077 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5078 	.atomic_destroy_state = dm_atomic_destroy_state,
5079 };
5080 
5081 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5082 {
5083 	int r;
5084 
5085 	adev->mode_info.mode_config_initialized = true;
5086 
5087 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5088 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5089 
5090 	adev_to_drm(adev)->mode_config.max_width = 16384;
5091 	adev_to_drm(adev)->mode_config.max_height = 16384;
5092 
5093 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5094 	if (adev->asic_type == CHIP_HAWAII)
5095 		/* disable prefer shadow for now due to hibernation issues */
5096 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5097 	else
5098 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5099 	/* indicates support for immediate flip */
5100 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5101 
5102 	drm_atomic_private_obj_init(adev_to_drm(adev),
5103 				    &adev->dm.atomic_obj,
5104 				    &dm_atomic_state_funcs);
5105 
5106 	r = amdgpu_display_modeset_create_props(adev);
5107 	if (r)
5108 		return r;
5109 
5110 #ifdef AMD_PRIVATE_COLOR
5111 	if (amdgpu_dm_create_color_properties(adev))
5112 		return -ENOMEM;
5113 #endif
5114 
5115 	r = amdgpu_dm_audio_init(adev);
5116 	if (r)
5117 		return r;
5118 
5119 	return 0;
5120 }
5121 
5122 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5123 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5124 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5125 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5126 
5127 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5128 				     int bl_idx)
5129 {
5130 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5131 
5132 	if (caps->caps_valid)
5133 		return;
5134 
5135 #if defined(CONFIG_ACPI)
5136 	amdgpu_acpi_get_backlight_caps(caps);
5137 
5138 	/* validate the firmware value is sane */
5139 	if (caps->caps_valid) {
5140 		int spread = caps->max_input_signal - caps->min_input_signal;
5141 
5142 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5143 		    caps->min_input_signal < 0 ||
5144 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5145 		    spread < AMDGPU_DM_MIN_SPREAD) {
5146 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5147 				      caps->min_input_signal, caps->max_input_signal);
5148 			caps->caps_valid = false;
5149 		}
5150 	}
5151 
5152 	if (!caps->caps_valid) {
5153 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5154 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5155 		caps->caps_valid = true;
5156 	}
5157 #else
5158 	if (caps->aux_support)
5159 		return;
5160 
5161 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5162 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5163 	caps->caps_valid = true;
5164 #endif
5165 }
5166 
5167 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5168 				unsigned int *min, unsigned int *max)
5169 {
5170 	if (!caps)
5171 		return 0;
5172 
5173 	if (caps->aux_support) {
5174 		// Firmware limits are in nits, DC API wants millinits.
5175 		*max = 1000 * caps->aux_max_input_signal;
5176 		*min = 1000 * caps->aux_min_input_signal;
5177 	} else {
5178 		// Firmware limits are 8-bit, PWM control is 16-bit.
5179 		*max = 0x101 * caps->max_input_signal;
5180 		*min = 0x101 * caps->min_input_signal;
5181 	}
5182 	return 1;
5183 }
5184 
5185 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5186 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5187 {
5188 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5189 }
5190 
5191 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5192 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5193 {
5194 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5195 }
5196 
5197 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5198 				      unsigned int min, unsigned int max,
5199 				      uint32_t *user_brightness)
5200 {
5201 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5202 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5203 	int left, right;
5204 
5205 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5206 		return;
5207 
5208 	if (!caps->data_points)
5209 		return;
5210 
5211 	/*
5212 	 * Handle the case where brightness is below the first data point
5213 	 * Interpolate between (0,0) and (first_signal, first_lum)
5214 	 */
5215 	if (brightness < caps->luminance_data[0].input_signal) {
5216 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5217 					caps->luminance_data[0].input_signal);
5218 		goto scale;
5219 	}
5220 
5221 	left = 0;
5222 	right = caps->data_points - 1;
5223 	while (left <= right) {
5224 		int mid = left + (right - left) / 2;
5225 		u8 signal = caps->luminance_data[mid].input_signal;
5226 
5227 		/* Exact match found */
5228 		if (signal == brightness) {
5229 			lum = caps->luminance_data[mid].luminance;
5230 			goto scale;
5231 		}
5232 
5233 		if (signal < brightness)
5234 			left = mid + 1;
5235 		else
5236 			right = mid - 1;
5237 	}
5238 
5239 	/* verify bound */
5240 	if (left >= caps->data_points)
5241 		left = caps->data_points - 1;
5242 
5243 	/* At this point, left > right */
5244 	lower_signal = caps->luminance_data[right].input_signal;
5245 	upper_signal = caps->luminance_data[left].input_signal;
5246 	lower_lum = caps->luminance_data[right].luminance;
5247 	upper_lum = caps->luminance_data[left].luminance;
5248 
5249 	/* interpolate */
5250 	if (right == left || !lower_lum)
5251 		lum = upper_lum;
5252 	else
5253 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5254 						    (brightness - lower_signal),
5255 						    upper_signal - lower_signal);
5256 scale:
5257 	*user_brightness = scale_fw_to_input(min, max,
5258 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5259 }
5260 
5261 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5262 					uint32_t brightness)
5263 {
5264 	unsigned int min, max;
5265 
5266 	if (!get_brightness_range(caps, &min, &max))
5267 		return brightness;
5268 
5269 	convert_custom_brightness(caps, min, max, &brightness);
5270 
5271 	// Rescale 0..max to min..max
5272 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5273 }
5274 
5275 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5276 				      uint32_t brightness)
5277 {
5278 	unsigned int min, max;
5279 
5280 	if (!get_brightness_range(caps, &min, &max))
5281 		return brightness;
5282 
5283 	if (brightness < min)
5284 		return 0;
5285 	// Rescale min..max to 0..max
5286 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5287 				 max - min);
5288 }
5289 
5290 static struct dc_stream_state *dm_find_stream_with_link(
5291 	struct amdgpu_display_manager *dm,
5292 	struct dc_link *link)
5293 {
5294 	struct dc_state *cur_dc_state = dm->dc->current_state;
5295 	struct dc_stream_state *stream = NULL;
5296 	int i;
5297 
5298 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5299 		stream = cur_dc_state->streams[i];
5300 		if (stream->link == link)
5301 			return stream;
5302 	}
5303 
5304 	return NULL;
5305 }
5306 
5307 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5308 					 int bl_idx,
5309 					 u32 user_brightness)
5310 {
5311 	struct amdgpu_dm_backlight_caps *caps;
5312 	struct dc_link *link;
5313 	u32 brightness = 0;
5314 	bool rc = false, reallow_idle = false;
5315 	struct drm_connector *connector;
5316 	struct dc_stream_state *stream;
5317 	unsigned int min, max;
5318 
5319 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5320 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5321 
5322 		if (aconnector->bl_idx != bl_idx)
5323 			continue;
5324 
5325 		/* if connector is off, save the brightness for next time it's on */
5326 		if (!aconnector->base.encoder) {
5327 			dm->brightness[bl_idx] = user_brightness;
5328 			dm->actual_brightness[bl_idx] = 0;
5329 			return;
5330 		}
5331 	}
5332 
5333 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5334 	caps = &dm->backlight_caps[bl_idx];
5335 
5336 	dm->brightness[bl_idx] = user_brightness;
5337 	/* update scratch register */
5338 	if (bl_idx == 0)
5339 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5340 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5341 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5342 
5343 	/* Apply brightness quirk */
5344 	if (caps->brightness_mask)
5345 		brightness |= caps->brightness_mask;
5346 
5347 	if (trace_amdgpu_dm_brightness_enabled()) {
5348 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5349 					   user_brightness,
5350 					   brightness,
5351 					   caps->aux_support,
5352 					   power_supply_is_system_supplied() > 0);
5353 	}
5354 
5355 	stream = dm_find_stream_with_link(dm, link);
5356 	if (!stream)
5357 		return;
5358 
5359 	mutex_lock(&dm->dc_lock);
5360 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5361 		dc_allow_idle_optimizations(dm->dc, false);
5362 		reallow_idle = true;
5363 	}
5364 
5365 	if (caps->aux_support) {
5366 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5367 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5368 	} else {
5369 		/* power module uses millipercent */
5370 		get_brightness_range(caps, &min, &max);
5371 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5372 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5373 						     brightness, 0, false);
5374 	}
5375 
5376 	/*
5377 	 * Some kms clients create a ramped backlight transition effect
5378 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5379 	 * fw to exit psr/replay before programming backlight. To
5380 	 * prevent lag, keep disable psr/replay and let the next atomic
5381 	 * flip clear the event.
5382 	 *
5383 	 * ToDo: use ISM to handle rapidly backlight change
5384 	 *
5385 	 * Rapidly backlight change is similar to rapidly cursor events,
5386 	 * which is now handled by ISM. ISM can delay the event until system
5387 	 * is really idle, so we may use ISM to handle backlight change as well.
5388 	 */
5389 	amdgpu_dm_psr_set_event(dm, stream, true,
5390 		psr_event_hw_programming, true);
5391 	amdgpu_dm_replay_set_event(dm, stream, true,
5392 		replay_event_hw_programming, true);
5393 
5394 	if (dm->dc->caps.ips_support && reallow_idle)
5395 		dc_allow_idle_optimizations(dm->dc, true);
5396 
5397 	mutex_unlock(&dm->dc_lock);
5398 
5399 	if (rc)
5400 		dm->actual_brightness[bl_idx] = user_brightness;
5401 }
5402 
5403 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5404 {
5405 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5406 	int i;
5407 
5408 	for (i = 0; i < dm->num_of_edps; i++) {
5409 		if (bd == dm->backlight_dev[i])
5410 			break;
5411 	}
5412 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5413 		i = 0;
5414 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5415 
5416 	return 0;
5417 }
5418 
5419 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5420 					 int bl_idx)
5421 {
5422 	int ret;
5423 	struct amdgpu_dm_backlight_caps caps;
5424 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5425 
5426 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5427 	caps = dm->backlight_caps[bl_idx];
5428 
5429 	if (caps.aux_support) {
5430 		u32 avg, peak;
5431 
5432 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5433 			return dm->brightness[bl_idx];
5434 		return convert_brightness_to_user(&caps, avg);
5435 	}
5436 
5437 	ret = dc_link_get_backlight_level(link);
5438 
5439 	if (ret == DC_ERROR_UNEXPECTED)
5440 		return dm->brightness[bl_idx];
5441 
5442 	return convert_brightness_to_user(&caps, ret);
5443 }
5444 
5445 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5446 {
5447 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5448 	int i;
5449 
5450 	for (i = 0; i < dm->num_of_edps; i++) {
5451 		if (bd == dm->backlight_dev[i])
5452 			break;
5453 	}
5454 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5455 		i = 0;
5456 	return amdgpu_dm_backlight_get_level(dm, i);
5457 }
5458 
5459 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5460 	.options = BL_CORE_SUSPENDRESUME,
5461 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5462 	.update_status	= amdgpu_dm_backlight_update_status,
5463 };
5464 
5465 static void
5466 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5467 {
5468 	struct drm_device *drm = aconnector->base.dev;
5469 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5470 	struct backlight_properties props = { 0 };
5471 	struct amdgpu_dm_backlight_caps *caps;
5472 	char bl_name[16];
5473 	int min, max;
5474 	int real_brightness;
5475 	int init_brightness;
5476 
5477 	if (aconnector->bl_idx == -1)
5478 		return;
5479 
5480 	if (!acpi_video_backlight_use_native()) {
5481 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5482 		/* Try registering an ACPI video backlight device instead. */
5483 		acpi_video_register_backlight();
5484 		return;
5485 	}
5486 
5487 	caps = &dm->backlight_caps[aconnector->bl_idx];
5488 	if (get_brightness_range(caps, &min, &max)) {
5489 		if (power_supply_is_system_supplied() > 0)
5490 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5491 		else
5492 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5493 		/* min is zero, so max needs to be adjusted */
5494 		props.max_brightness = max - min;
5495 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5496 			caps->ac_level, caps->dc_level);
5497 	} else
5498 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5499 
5500 	init_brightness = props.brightness;
5501 
5502 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5503 		drm_info(drm, "Using custom brightness curve\n");
5504 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5505 	} else
5506 		props.scale = BACKLIGHT_SCALE_LINEAR;
5507 	props.type = BACKLIGHT_RAW;
5508 
5509 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5510 		 drm->primary->index + aconnector->bl_idx);
5511 
5512 	dm->backlight_dev[aconnector->bl_idx] =
5513 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5514 					  &amdgpu_dm_backlight_ops, &props);
5515 	dm->brightness[aconnector->bl_idx] = props.brightness;
5516 
5517 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5518 		drm_err(drm, "DM: Backlight registration failed!\n");
5519 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5520 	} else {
5521 		/*
5522 		 * dm->brightness[x] can be inconsistent just after startup until
5523 		 * ops.get_brightness is called.
5524 		 */
5525 		real_brightness =
5526 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5527 
5528 		if (real_brightness != init_brightness) {
5529 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5530 			dm->brightness[aconnector->bl_idx] = real_brightness;
5531 		}
5532 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5533 	}
5534 }
5535 
5536 static int initialize_plane(struct amdgpu_display_manager *dm,
5537 			    struct amdgpu_mode_info *mode_info, int plane_id,
5538 			    enum drm_plane_type plane_type,
5539 			    const struct dc_plane_cap *plane_cap)
5540 {
5541 	struct drm_plane *plane;
5542 	unsigned long possible_crtcs;
5543 	int ret = 0;
5544 
5545 	plane = kzalloc_obj(struct drm_plane);
5546 	if (!plane) {
5547 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5548 		return -ENOMEM;
5549 	}
5550 	plane->type = plane_type;
5551 
5552 	/*
5553 	 * HACK: IGT tests expect that the primary plane for a CRTC
5554 	 * can only have one possible CRTC. Only expose support for
5555 	 * any CRTC if they're not going to be used as a primary plane
5556 	 * for a CRTC - like overlay or underlay planes.
5557 	 */
5558 	possible_crtcs = 1 << plane_id;
5559 	if (plane_id >= dm->dc->caps.max_streams)
5560 		possible_crtcs = 0xff;
5561 
5562 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5563 
5564 	if (ret) {
5565 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5566 		kfree(plane);
5567 		return ret;
5568 	}
5569 
5570 	if (mode_info)
5571 		mode_info->planes[plane_id] = plane;
5572 
5573 	return ret;
5574 }
5575 
5576 
5577 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5578 				   struct amdgpu_dm_connector *aconnector)
5579 {
5580 	struct amdgpu_dm_backlight_caps *caps;
5581 	struct dc_link *link = aconnector->dc_link;
5582 	int bl_idx = dm->num_of_edps;
5583 
5584 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5585 	    link->type == dc_connection_none)
5586 		return;
5587 
5588 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5589 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5590 		return;
5591 	}
5592 
5593 	aconnector->bl_idx = bl_idx;
5594 
5595 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5596 	dm->backlight_link[bl_idx] = link;
5597 	dm->num_of_edps++;
5598 
5599 	update_connector_ext_caps(aconnector);
5600 	caps = &dm->backlight_caps[aconnector->bl_idx];
5601 
5602 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5603 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5604 		drm_object_attach_property(&aconnector->base.base,
5605 					   dm->adev->mode_info.abm_level_property,
5606 					   ABM_SYSFS_CONTROL);
5607 }
5608 
5609 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5610 
5611 
5612 
5613 /*
5614  * In this architecture, the association
5615  * connector -> encoder -> crtc
5616  * id not really requried. The crtc and connector will hold the
5617  * display_index as an abstraction to use with DAL component
5618  *
5619  * Returns 0 on success
5620  */
5621 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5622 {
5623 	struct amdgpu_display_manager *dm = &adev->dm;
5624 	s32 i;
5625 	struct amdgpu_dm_connector *aconnector = NULL;
5626 	struct amdgpu_encoder *aencoder = NULL;
5627 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5628 	u32 link_cnt;
5629 	s32 primary_planes;
5630 	enum dc_connection_type new_connection_type = dc_connection_none;
5631 	const struct dc_plane_cap *plane;
5632 	bool psr_feature_enabled = false;
5633 	bool replay_feature_enabled = false;
5634 	int max_overlay = dm->dc->caps.max_slave_planes;
5635 
5636 	dm->display_indexes_num = dm->dc->caps.max_streams;
5637 	/* Update the actual used number of crtc */
5638 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5639 
5640 	amdgpu_dm_set_irq_funcs(adev);
5641 
5642 	link_cnt = dm->dc->caps.max_links;
5643 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5644 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5645 		return -EINVAL;
5646 	}
5647 
5648 	/* There is one primary plane per CRTC */
5649 	primary_planes = dm->dc->caps.max_streams;
5650 	if (primary_planes > AMDGPU_MAX_PLANES) {
5651 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5652 		return -EINVAL;
5653 	}
5654 
5655 	/*
5656 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5657 	 * Order is reversed to match iteration order in atomic check.
5658 	 */
5659 	for (i = (primary_planes - 1); i >= 0; i--) {
5660 		plane = &dm->dc->caps.planes[i];
5661 
5662 		if (initialize_plane(dm, mode_info, i,
5663 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5664 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5665 			goto fail;
5666 		}
5667 	}
5668 
5669 	/*
5670 	 * Initialize overlay planes, index starting after primary planes.
5671 	 * These planes have a higher DRM index than the primary planes since
5672 	 * they should be considered as having a higher z-order.
5673 	 * Order is reversed to match iteration order in atomic check.
5674 	 *
5675 	 * Only support DCN for now, and only expose one so we don't encourage
5676 	 * userspace to use up all the pipes.
5677 	 */
5678 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5679 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5680 
5681 		/* Do not create overlay if MPO disabled */
5682 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5683 			break;
5684 
5685 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5686 			continue;
5687 
5688 		if (!plane->pixel_format_support.argb8888)
5689 			continue;
5690 
5691 		if (max_overlay-- == 0)
5692 			break;
5693 
5694 		if (initialize_plane(dm, NULL, primary_planes + i,
5695 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5696 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5697 			goto fail;
5698 		}
5699 	}
5700 
5701 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5702 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5703 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5704 			goto fail;
5705 		}
5706 
5707 	/* Use Outbox interrupt */
5708 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5709 	case IP_VERSION(3, 0, 0):
5710 	case IP_VERSION(3, 1, 2):
5711 	case IP_VERSION(3, 1, 3):
5712 	case IP_VERSION(3, 1, 4):
5713 	case IP_VERSION(3, 1, 5):
5714 	case IP_VERSION(3, 1, 6):
5715 	case IP_VERSION(3, 2, 0):
5716 	case IP_VERSION(3, 2, 1):
5717 	case IP_VERSION(2, 1, 0):
5718 	case IP_VERSION(3, 5, 0):
5719 	case IP_VERSION(3, 5, 1):
5720 	case IP_VERSION(3, 6, 0):
5721 	case IP_VERSION(4, 0, 1):
5722 	case IP_VERSION(4, 2, 0):
5723 		if (register_outbox_irq_handlers(dm->adev)) {
5724 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5725 			goto fail;
5726 		}
5727 		break;
5728 	default:
5729 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5730 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5731 	}
5732 
5733 	/* Determine whether to enable PSR support by default. */
5734 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5735 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5736 		case IP_VERSION(3, 1, 2):
5737 		case IP_VERSION(3, 1, 3):
5738 		case IP_VERSION(3, 1, 4):
5739 		case IP_VERSION(3, 1, 5):
5740 		case IP_VERSION(3, 1, 6):
5741 		case IP_VERSION(3, 2, 0):
5742 		case IP_VERSION(3, 2, 1):
5743 		case IP_VERSION(3, 5, 0):
5744 		case IP_VERSION(3, 5, 1):
5745 		case IP_VERSION(3, 6, 0):
5746 		case IP_VERSION(4, 0, 1):
5747 		case IP_VERSION(4, 2, 0):
5748 			psr_feature_enabled = true;
5749 			break;
5750 		default:
5751 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5752 			break;
5753 		}
5754 	}
5755 
5756 	/* Determine whether to enable Replay support by default. */
5757 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5758 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5759 		case IP_VERSION(3, 1, 4):
5760 		case IP_VERSION(3, 2, 0):
5761 		case IP_VERSION(3, 2, 1):
5762 		case IP_VERSION(3, 5, 0):
5763 		case IP_VERSION(3, 5, 1):
5764 		case IP_VERSION(3, 6, 0):
5765 		case IP_VERSION(4, 2, 0):
5766 			replay_feature_enabled = true;
5767 			break;
5768 
5769 		default:
5770 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5771 			break;
5772 		}
5773 	}
5774 
5775 	if (link_cnt > MAX_LINKS) {
5776 		drm_err(adev_to_drm(adev),
5777 			"KMS: Cannot support more than %d display indexes\n",
5778 				MAX_LINKS);
5779 		goto fail;
5780 	}
5781 
5782 	/* loops over all connectors on the board */
5783 	for (i = 0; i < link_cnt; i++) {
5784 		struct dc_link *link = NULL;
5785 
5786 		link = dc_get_link_at_index(dm->dc, i);
5787 
5788 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5789 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5790 
5791 			if (!wbcon) {
5792 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5793 				continue;
5794 			}
5795 
5796 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5797 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5798 				kfree(wbcon);
5799 				continue;
5800 			}
5801 
5802 			link->psr_settings.psr_feature_enabled = false;
5803 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5804 
5805 			continue;
5806 		}
5807 
5808 		aconnector = kzalloc_obj(*aconnector);
5809 		if (!aconnector)
5810 			goto fail;
5811 
5812 		aencoder = kzalloc_obj(*aencoder);
5813 		if (!aencoder)
5814 			goto fail;
5815 
5816 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5817 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5818 			goto fail;
5819 		}
5820 
5821 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5822 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5823 			goto fail;
5824 		}
5825 
5826 		if (dm->hpd_rx_offload_wq)
5827 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5828 				aconnector;
5829 
5830 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5831 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5832 
5833 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5834 			emulated_link_detect(link);
5835 			amdgpu_dm_update_connector_after_detect(aconnector);
5836 		} else {
5837 			bool ret = false;
5838 
5839 			mutex_lock(&dm->dc_lock);
5840 			dc_exit_ips_for_hw_access(dm->dc);
5841 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5842 			mutex_unlock(&dm->dc_lock);
5843 
5844 			if (ret) {
5845 				amdgpu_dm_update_connector_after_detect(aconnector);
5846 				setup_backlight_device(dm, aconnector);
5847 
5848 				/* Disable PSR if Replay can be enabled */
5849 				if (replay_feature_enabled)
5850 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5851 						psr_feature_enabled = false;
5852 
5853 				if (psr_feature_enabled) {
5854 					amdgpu_dm_set_psr_caps(link, aconnector);
5855 					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",
5856 						 aconnector->base.name,
5857 						 link->psr_settings.psr_feature_enabled,
5858 						 link->psr_settings.psr_version,
5859 						 link->dpcd_caps.psr_info.psr_version,
5860 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5861 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5862 				}
5863 			}
5864 		}
5865 		amdgpu_set_panel_orientation(&aconnector->base);
5866 	}
5867 
5868 	/* Debug dump: list all DC links and their associated sinks after detection
5869 	 * is complete for all connectors. This provides a comprehensive view of the
5870 	 * final state without repeating the dump for each connector.
5871 	 */
5872 	amdgpu_dm_dump_links_and_sinks(adev);
5873 
5874 	/* Software is initialized. Now we can register interrupt handlers. */
5875 	switch (adev->asic_type) {
5876 #if defined(CONFIG_DRM_AMD_DC_SI)
5877 	case CHIP_TAHITI:
5878 	case CHIP_PITCAIRN:
5879 	case CHIP_VERDE:
5880 	case CHIP_OLAND:
5881 #endif
5882 	case CHIP_BONAIRE:
5883 	case CHIP_HAWAII:
5884 	case CHIP_KAVERI:
5885 	case CHIP_KABINI:
5886 	case CHIP_MULLINS:
5887 	case CHIP_TONGA:
5888 	case CHIP_FIJI:
5889 	case CHIP_CARRIZO:
5890 	case CHIP_STONEY:
5891 	case CHIP_POLARIS11:
5892 	case CHIP_POLARIS10:
5893 	case CHIP_POLARIS12:
5894 	case CHIP_VEGAM:
5895 	case CHIP_VEGA10:
5896 	case CHIP_VEGA12:
5897 	case CHIP_VEGA20:
5898 		if (dce110_register_irq_handlers(dm->adev)) {
5899 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5900 			goto fail;
5901 		}
5902 		break;
5903 	default:
5904 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5905 		case IP_VERSION(1, 0, 0):
5906 		case IP_VERSION(1, 0, 1):
5907 		case IP_VERSION(2, 0, 2):
5908 		case IP_VERSION(2, 0, 3):
5909 		case IP_VERSION(2, 0, 0):
5910 		case IP_VERSION(2, 1, 0):
5911 		case IP_VERSION(3, 0, 0):
5912 		case IP_VERSION(3, 0, 2):
5913 		case IP_VERSION(3, 0, 3):
5914 		case IP_VERSION(3, 0, 1):
5915 		case IP_VERSION(3, 1, 2):
5916 		case IP_VERSION(3, 1, 3):
5917 		case IP_VERSION(3, 1, 4):
5918 		case IP_VERSION(3, 1, 5):
5919 		case IP_VERSION(3, 1, 6):
5920 		case IP_VERSION(3, 2, 0):
5921 		case IP_VERSION(3, 2, 1):
5922 		case IP_VERSION(3, 5, 0):
5923 		case IP_VERSION(3, 5, 1):
5924 		case IP_VERSION(3, 6, 0):
5925 		case IP_VERSION(4, 0, 1):
5926 		case IP_VERSION(4, 2, 0):
5927 			if (dcn10_register_irq_handlers(dm->adev)) {
5928 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5929 				goto fail;
5930 			}
5931 			break;
5932 		default:
5933 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5934 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5935 			goto fail;
5936 		}
5937 		break;
5938 	}
5939 
5940 	return 0;
5941 fail:
5942 	kfree(aencoder);
5943 	kfree(aconnector);
5944 
5945 	return -EINVAL;
5946 }
5947 
5948 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5949 {
5950 	if (dm->atomic_obj.state)
5951 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5952 }
5953 
5954 /******************************************************************************
5955  * amdgpu_display_funcs functions
5956  *****************************************************************************/
5957 
5958 /*
5959  * dm_bandwidth_update - program display watermarks
5960  *
5961  * @adev: amdgpu_device pointer
5962  *
5963  * Calculate and program the display watermarks and line buffer allocation.
5964  */
5965 static void dm_bandwidth_update(struct amdgpu_device *adev)
5966 {
5967 	/* TODO: implement later */
5968 }
5969 
5970 static const struct amdgpu_display_funcs dm_display_funcs = {
5971 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5972 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5973 	.backlight_set_level = NULL, /* never called for DC */
5974 	.backlight_get_level = NULL, /* never called for DC */
5975 	.hpd_sense = NULL,/* called unconditionally */
5976 	.hpd_set_polarity = NULL, /* called unconditionally */
5977 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5978 	.page_flip_get_scanoutpos =
5979 		dm_crtc_get_scanoutpos,/* called unconditionally */
5980 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5981 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5982 };
5983 
5984 #if defined(CONFIG_DEBUG_KERNEL_DC)
5985 
5986 static ssize_t s3_debug_store(struct device *device,
5987 			      struct device_attribute *attr,
5988 			      const char *buf,
5989 			      size_t count)
5990 {
5991 	int ret;
5992 	int s3_state;
5993 	struct drm_device *drm_dev = dev_get_drvdata(device);
5994 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5995 	struct amdgpu_ip_block *ip_block;
5996 
5997 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5998 	if (!ip_block)
5999 		return -EINVAL;
6000 
6001 	ret = kstrtoint(buf, 0, &s3_state);
6002 
6003 	if (ret == 0) {
6004 		if (s3_state) {
6005 			dm_resume(ip_block);
6006 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6007 		} else
6008 			dm_suspend(ip_block);
6009 	}
6010 
6011 	return ret == 0 ? count : 0;
6012 }
6013 
6014 DEVICE_ATTR_WO(s3_debug);
6015 
6016 #endif
6017 
6018 static int dm_init_microcode(struct amdgpu_device *adev)
6019 {
6020 	char *fw_name_dmub;
6021 	int r;
6022 
6023 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6024 	case IP_VERSION(2, 1, 0):
6025 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6026 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6027 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6028 		break;
6029 	case IP_VERSION(3, 0, 0):
6030 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6031 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6032 		else
6033 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6034 		break;
6035 	case IP_VERSION(3, 0, 1):
6036 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6037 		break;
6038 	case IP_VERSION(3, 0, 2):
6039 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6040 		break;
6041 	case IP_VERSION(3, 0, 3):
6042 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6043 		break;
6044 	case IP_VERSION(3, 1, 2):
6045 	case IP_VERSION(3, 1, 3):
6046 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6047 		break;
6048 	case IP_VERSION(3, 1, 4):
6049 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6050 		break;
6051 	case IP_VERSION(3, 1, 5):
6052 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6053 		break;
6054 	case IP_VERSION(3, 1, 6):
6055 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6056 		break;
6057 	case IP_VERSION(3, 2, 0):
6058 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6059 		break;
6060 	case IP_VERSION(3, 2, 1):
6061 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6062 		break;
6063 	case IP_VERSION(3, 5, 0):
6064 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6065 		break;
6066 	case IP_VERSION(3, 5, 1):
6067 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6068 		break;
6069 	case IP_VERSION(3, 6, 0):
6070 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6071 		break;
6072 	case IP_VERSION(4, 0, 1):
6073 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6074 		break;
6075 	case IP_VERSION(4, 2, 0):
6076 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6077 		break;
6078 	default:
6079 		/* ASIC doesn't support DMUB. */
6080 		return 0;
6081 	}
6082 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6083 				 "%s", fw_name_dmub);
6084 	return r;
6085 }
6086 
6087 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6088 {
6089 	struct amdgpu_device *adev = ip_block->adev;
6090 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6091 	struct atom_context *ctx = mode_info->atom_context;
6092 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6093 	u16 data_offset;
6094 
6095 	/* if there is no object header, skip DM */
6096 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6097 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6098 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6099 		return -ENOENT;
6100 	}
6101 
6102 	switch (adev->asic_type) {
6103 #if defined(CONFIG_DRM_AMD_DC_SI)
6104 	case CHIP_TAHITI:
6105 	case CHIP_PITCAIRN:
6106 	case CHIP_VERDE:
6107 		adev->mode_info.num_crtc = 6;
6108 		adev->mode_info.num_hpd = 6;
6109 		adev->mode_info.num_dig = 6;
6110 		break;
6111 	case CHIP_OLAND:
6112 		adev->mode_info.num_crtc = 2;
6113 		adev->mode_info.num_hpd = 2;
6114 		adev->mode_info.num_dig = 2;
6115 		break;
6116 #endif
6117 	case CHIP_BONAIRE:
6118 	case CHIP_HAWAII:
6119 		adev->mode_info.num_crtc = 6;
6120 		adev->mode_info.num_hpd = 6;
6121 		adev->mode_info.num_dig = 6;
6122 		break;
6123 	case CHIP_KAVERI:
6124 		adev->mode_info.num_crtc = 4;
6125 		adev->mode_info.num_hpd = 6;
6126 		adev->mode_info.num_dig = 7;
6127 		break;
6128 	case CHIP_KABINI:
6129 	case CHIP_MULLINS:
6130 		adev->mode_info.num_crtc = 2;
6131 		adev->mode_info.num_hpd = 6;
6132 		adev->mode_info.num_dig = 6;
6133 		break;
6134 	case CHIP_FIJI:
6135 	case CHIP_TONGA:
6136 		adev->mode_info.num_crtc = 6;
6137 		adev->mode_info.num_hpd = 6;
6138 		adev->mode_info.num_dig = 7;
6139 		break;
6140 	case CHIP_CARRIZO:
6141 		adev->mode_info.num_crtc = 3;
6142 		adev->mode_info.num_hpd = 6;
6143 		adev->mode_info.num_dig = 9;
6144 		break;
6145 	case CHIP_STONEY:
6146 		adev->mode_info.num_crtc = 2;
6147 		adev->mode_info.num_hpd = 6;
6148 		adev->mode_info.num_dig = 9;
6149 		break;
6150 	case CHIP_POLARIS11:
6151 	case CHIP_POLARIS12:
6152 		adev->mode_info.num_crtc = 5;
6153 		adev->mode_info.num_hpd = 5;
6154 		adev->mode_info.num_dig = 5;
6155 		break;
6156 	case CHIP_POLARIS10:
6157 	case CHIP_VEGAM:
6158 		adev->mode_info.num_crtc = 6;
6159 		adev->mode_info.num_hpd = 6;
6160 		adev->mode_info.num_dig = 6;
6161 		break;
6162 	case CHIP_VEGA10:
6163 	case CHIP_VEGA12:
6164 	case CHIP_VEGA20:
6165 		adev->mode_info.num_crtc = 6;
6166 		adev->mode_info.num_hpd = 6;
6167 		adev->mode_info.num_dig = 6;
6168 		break;
6169 	default:
6170 
6171 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6172 		case IP_VERSION(2, 0, 2):
6173 		case IP_VERSION(3, 0, 0):
6174 			adev->mode_info.num_crtc = 6;
6175 			adev->mode_info.num_hpd = 6;
6176 			adev->mode_info.num_dig = 6;
6177 			break;
6178 		case IP_VERSION(2, 0, 0):
6179 		case IP_VERSION(3, 0, 2):
6180 			adev->mode_info.num_crtc = 5;
6181 			adev->mode_info.num_hpd = 5;
6182 			adev->mode_info.num_dig = 5;
6183 			break;
6184 		case IP_VERSION(2, 0, 3):
6185 		case IP_VERSION(3, 0, 3):
6186 			adev->mode_info.num_crtc = 2;
6187 			adev->mode_info.num_hpd = 2;
6188 			adev->mode_info.num_dig = 2;
6189 			break;
6190 		case IP_VERSION(1, 0, 0):
6191 		case IP_VERSION(1, 0, 1):
6192 		case IP_VERSION(3, 0, 1):
6193 		case IP_VERSION(2, 1, 0):
6194 		case IP_VERSION(3, 1, 2):
6195 		case IP_VERSION(3, 1, 3):
6196 		case IP_VERSION(3, 1, 4):
6197 		case IP_VERSION(3, 1, 5):
6198 		case IP_VERSION(3, 1, 6):
6199 		case IP_VERSION(3, 2, 0):
6200 		case IP_VERSION(3, 2, 1):
6201 		case IP_VERSION(3, 5, 0):
6202 		case IP_VERSION(3, 5, 1):
6203 		case IP_VERSION(3, 6, 0):
6204 		case IP_VERSION(4, 0, 1):
6205 		case IP_VERSION(4, 2, 0):
6206 			adev->mode_info.num_crtc = 4;
6207 			adev->mode_info.num_hpd = 4;
6208 			adev->mode_info.num_dig = 4;
6209 			break;
6210 		default:
6211 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6212 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6213 			return -EINVAL;
6214 		}
6215 		break;
6216 	}
6217 
6218 	if (adev->mode_info.funcs == NULL)
6219 		adev->mode_info.funcs = &dm_display_funcs;
6220 
6221 	/*
6222 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6223 	 * adev->reg.audio_endpt.wreg because they are initialised in
6224 	 * amdgpu_device_init()
6225 	 */
6226 #if defined(CONFIG_DEBUG_KERNEL_DC)
6227 	device_create_file(
6228 		adev_to_drm(adev)->dev,
6229 		&dev_attr_s3_debug);
6230 #endif
6231 	adev->dc_enabled = true;
6232 
6233 	return dm_init_microcode(adev);
6234 }
6235 
6236 static bool modereset_required(struct drm_crtc_state *crtc_state)
6237 {
6238 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6239 }
6240 
6241 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6242 {
6243 	drm_encoder_cleanup(encoder);
6244 	kfree(encoder);
6245 }
6246 
6247 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6248 	.destroy = amdgpu_dm_encoder_destroy,
6249 };
6250 
6251 static int
6252 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6253 			    const enum surface_pixel_format format,
6254 			    enum dc_color_space *color_space)
6255 {
6256 	bool full_range;
6257 
6258 	*color_space = COLOR_SPACE_SRGB;
6259 
6260 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6261 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6262 		return 0;
6263 
6264 	/* DRM color properties only affect non-RGB formats. */
6265 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6266 		return 0;
6267 
6268 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6269 
6270 	switch (plane_state->color_encoding) {
6271 	case DRM_COLOR_YCBCR_BT601:
6272 		if (full_range)
6273 			*color_space = COLOR_SPACE_YCBCR601;
6274 		else
6275 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6276 		break;
6277 
6278 	case DRM_COLOR_YCBCR_BT709:
6279 		if (full_range)
6280 			*color_space = COLOR_SPACE_YCBCR709;
6281 		else
6282 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6283 		break;
6284 
6285 	case DRM_COLOR_YCBCR_BT2020:
6286 		if (full_range)
6287 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6288 		else
6289 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6290 		break;
6291 
6292 	default:
6293 		return -EINVAL;
6294 	}
6295 
6296 	return 0;
6297 }
6298 
6299 static int
6300 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6301 			    const struct drm_plane_state *plane_state,
6302 			    const u64 tiling_flags,
6303 			    struct dc_plane_info *plane_info,
6304 			    struct dc_plane_address *address,
6305 			    bool tmz_surface)
6306 {
6307 	const struct drm_framebuffer *fb = plane_state->fb;
6308 	const struct amdgpu_framebuffer *afb =
6309 		to_amdgpu_framebuffer(plane_state->fb);
6310 	int ret;
6311 
6312 	memset(plane_info, 0, sizeof(*plane_info));
6313 
6314 	switch (fb->format->format) {
6315 	case DRM_FORMAT_C8:
6316 		plane_info->format =
6317 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6318 		break;
6319 	case DRM_FORMAT_RGB565:
6320 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6321 		break;
6322 	case DRM_FORMAT_XRGB8888:
6323 	case DRM_FORMAT_ARGB8888:
6324 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6325 		break;
6326 	case DRM_FORMAT_XRGB2101010:
6327 	case DRM_FORMAT_ARGB2101010:
6328 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6329 		break;
6330 	case DRM_FORMAT_XBGR2101010:
6331 	case DRM_FORMAT_ABGR2101010:
6332 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6333 		break;
6334 	case DRM_FORMAT_XBGR8888:
6335 	case DRM_FORMAT_ABGR8888:
6336 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6337 		break;
6338 	case DRM_FORMAT_NV21:
6339 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6340 		break;
6341 	case DRM_FORMAT_NV12:
6342 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6343 		break;
6344 	case DRM_FORMAT_P010:
6345 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6346 		break;
6347 	case DRM_FORMAT_XRGB16161616F:
6348 	case DRM_FORMAT_ARGB16161616F:
6349 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6350 		break;
6351 	case DRM_FORMAT_XBGR16161616F:
6352 	case DRM_FORMAT_ABGR16161616F:
6353 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6354 		break;
6355 	case DRM_FORMAT_XRGB16161616:
6356 	case DRM_FORMAT_ARGB16161616:
6357 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6358 		break;
6359 	case DRM_FORMAT_XBGR16161616:
6360 	case DRM_FORMAT_ABGR16161616:
6361 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6362 		break;
6363 	default:
6364 		drm_err(adev_to_drm(adev),
6365 			"Unsupported screen format %p4cc\n",
6366 			&fb->format->format);
6367 		return -EINVAL;
6368 	}
6369 
6370 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6371 	case DRM_MODE_ROTATE_0:
6372 		plane_info->rotation = ROTATION_ANGLE_0;
6373 		break;
6374 	case DRM_MODE_ROTATE_90:
6375 		plane_info->rotation = ROTATION_ANGLE_90;
6376 		break;
6377 	case DRM_MODE_ROTATE_180:
6378 		plane_info->rotation = ROTATION_ANGLE_180;
6379 		break;
6380 	case DRM_MODE_ROTATE_270:
6381 		plane_info->rotation = ROTATION_ANGLE_270;
6382 		break;
6383 	default:
6384 		plane_info->rotation = ROTATION_ANGLE_0;
6385 		break;
6386 	}
6387 
6388 
6389 	plane_info->visible = true;
6390 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6391 
6392 	plane_info->layer_index = plane_state->normalized_zpos;
6393 
6394 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6395 					  &plane_info->color_space);
6396 	if (ret)
6397 		return ret;
6398 
6399 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6400 					   plane_info->rotation, tiling_flags,
6401 					   &plane_info->tiling_info,
6402 					   &plane_info->plane_size,
6403 					   &plane_info->dcc, address,
6404 					   tmz_surface);
6405 	if (ret)
6406 		return ret;
6407 
6408 	amdgpu_dm_plane_fill_blending_from_plane_state(
6409 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6410 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6411 
6412 	return 0;
6413 }
6414 
6415 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6416 				    struct dc_plane_state *dc_plane_state,
6417 				    struct drm_plane_state *plane_state,
6418 				    struct drm_crtc_state *crtc_state)
6419 {
6420 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6421 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6422 	struct dc_scaling_info scaling_info;
6423 	struct dc_plane_info plane_info;
6424 	int ret;
6425 
6426 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6427 	if (ret)
6428 		return ret;
6429 
6430 	dc_plane_state->src_rect = scaling_info.src_rect;
6431 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6432 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6433 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6434 
6435 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6436 					  afb->tiling_flags,
6437 					  &plane_info,
6438 					  &dc_plane_state->address,
6439 					  afb->tmz_surface);
6440 	if (ret)
6441 		return ret;
6442 
6443 	dc_plane_state->format = plane_info.format;
6444 	dc_plane_state->color_space = plane_info.color_space;
6445 	dc_plane_state->format = plane_info.format;
6446 	dc_plane_state->plane_size = plane_info.plane_size;
6447 	dc_plane_state->rotation = plane_info.rotation;
6448 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6449 	dc_plane_state->stereo_format = plane_info.stereo_format;
6450 	dc_plane_state->tiling_info = plane_info.tiling_info;
6451 	dc_plane_state->visible = plane_info.visible;
6452 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6453 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6454 	dc_plane_state->global_alpha = plane_info.global_alpha;
6455 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6456 	dc_plane_state->dcc = plane_info.dcc;
6457 	dc_plane_state->layer_index = plane_info.layer_index;
6458 	dc_plane_state->flip_int_enabled = true;
6459 
6460 	/*
6461 	 * Always set input transfer function, since plane state is refreshed
6462 	 * every time.
6463 	 */
6464 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6465 						plane_state,
6466 						dc_plane_state);
6467 	if (ret)
6468 		return ret;
6469 
6470 	return 0;
6471 }
6472 
6473 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6474 				      struct rect *dirty_rect, int32_t x,
6475 				      s32 y, s32 width, s32 height,
6476 				      int *i, bool ffu)
6477 {
6478 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6479 
6480 	dirty_rect->x = x;
6481 	dirty_rect->y = y;
6482 	dirty_rect->width = width;
6483 	dirty_rect->height = height;
6484 
6485 	if (ffu)
6486 		drm_dbg(plane->dev,
6487 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6488 			plane->base.id, width, height);
6489 	else
6490 		drm_dbg(plane->dev,
6491 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6492 			plane->base.id, x, y, width, height);
6493 
6494 	(*i)++;
6495 }
6496 
6497 /**
6498  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6499  *
6500  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6501  *         remote fb
6502  * @old_plane_state: Old state of @plane
6503  * @new_plane_state: New state of @plane
6504  * @crtc_state: New state of CRTC connected to the @plane
6505  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6506  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6507  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6508  *             that have changed will be updated. If PSR SU is not enabled,
6509  *             or if damage clips are not available, the entire screen will be updated.
6510  * @dirty_regions_changed: dirty regions changed
6511  *
6512  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6513  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6514  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6515  * amdgpu_dm's.
6516  *
6517  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6518  * plane with regions that require flushing to the eDP remote buffer. In
6519  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6520  * implicitly provide damage clips without any client support via the plane
6521  * bounds.
6522  */
6523 static void fill_dc_dirty_rects(struct drm_plane *plane,
6524 				struct drm_plane_state *old_plane_state,
6525 				struct drm_plane_state *new_plane_state,
6526 				struct drm_crtc_state *crtc_state,
6527 				struct dc_flip_addrs *flip_addrs,
6528 				bool is_psr_su,
6529 				bool *dirty_regions_changed)
6530 {
6531 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6532 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6533 	u32 num_clips;
6534 	struct drm_mode_rect *clips;
6535 	bool bb_changed;
6536 	bool fb_changed;
6537 	u32 i = 0;
6538 	*dirty_regions_changed = false;
6539 
6540 	/*
6541 	 * Cursor plane has it's own dirty rect update interface. See
6542 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6543 	 */
6544 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6545 		return;
6546 
6547 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6548 		goto ffu;
6549 
6550 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6551 	clips = drm_plane_get_damage_clips(new_plane_state);
6552 
6553 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6554 						   is_psr_su)))
6555 		goto ffu;
6556 
6557 	if (!dm_crtc_state->mpo_requested) {
6558 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6559 			goto ffu;
6560 
6561 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6562 			fill_dc_dirty_rect(new_plane_state->plane,
6563 					   &dirty_rects[flip_addrs->dirty_rect_count],
6564 					   clips->x1, clips->y1,
6565 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6566 					   &flip_addrs->dirty_rect_count,
6567 					   false);
6568 		return;
6569 	}
6570 
6571 	/*
6572 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6573 	 * flipped to or damaged.
6574 	 *
6575 	 * If plane is moved or resized, also add old bounding box to dirty
6576 	 * rects.
6577 	 */
6578 	fb_changed = old_plane_state->fb->base.id !=
6579 		     new_plane_state->fb->base.id;
6580 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6581 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6582 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6583 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6584 
6585 	drm_dbg(plane->dev,
6586 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6587 		new_plane_state->plane->base.id,
6588 		bb_changed, fb_changed, num_clips);
6589 
6590 	*dirty_regions_changed = bb_changed;
6591 
6592 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6593 		goto ffu;
6594 
6595 	if (bb_changed) {
6596 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6597 				   new_plane_state->crtc_x,
6598 				   new_plane_state->crtc_y,
6599 				   new_plane_state->crtc_w,
6600 				   new_plane_state->crtc_h, &i, false);
6601 
6602 		/* Add old plane bounding-box if plane is moved or resized */
6603 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6604 				   old_plane_state->crtc_x,
6605 				   old_plane_state->crtc_y,
6606 				   old_plane_state->crtc_w,
6607 				   old_plane_state->crtc_h, &i, false);
6608 	}
6609 
6610 	if (num_clips) {
6611 		for (; i < num_clips; clips++)
6612 			fill_dc_dirty_rect(new_plane_state->plane,
6613 					   &dirty_rects[i], clips->x1,
6614 					   clips->y1, clips->x2 - clips->x1,
6615 					   clips->y2 - clips->y1, &i, false);
6616 	} else if (fb_changed && !bb_changed) {
6617 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6618 				   new_plane_state->crtc_x,
6619 				   new_plane_state->crtc_y,
6620 				   new_plane_state->crtc_w,
6621 				   new_plane_state->crtc_h, &i, false);
6622 	}
6623 
6624 	flip_addrs->dirty_rect_count = i;
6625 	return;
6626 
6627 ffu:
6628 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6629 			   dm_crtc_state->base.mode.crtc_hdisplay,
6630 			   dm_crtc_state->base.mode.crtc_vdisplay,
6631 			   &flip_addrs->dirty_rect_count, true);
6632 }
6633 
6634 static void update_stream_scaling_settings(struct drm_device *dev,
6635 					   const struct drm_display_mode *mode,
6636 					   const struct dm_connector_state *dm_state,
6637 					   struct dc_stream_state *stream)
6638 {
6639 	enum amdgpu_rmx_type rmx_type;
6640 
6641 	struct rect src = { 0 }; /* viewport in composition space*/
6642 	struct rect dst = { 0 }; /* stream addressable area */
6643 
6644 	/* no mode. nothing to be done */
6645 	if (!mode)
6646 		return;
6647 
6648 	/* Full screen scaling by default */
6649 	src.width = mode->hdisplay;
6650 	src.height = mode->vdisplay;
6651 	dst.width = stream->timing.h_addressable;
6652 	dst.height = stream->timing.v_addressable;
6653 
6654 	if (dm_state) {
6655 		rmx_type = dm_state->scaling;
6656 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6657 			if (src.width * dst.height <
6658 					src.height * dst.width) {
6659 				/* height needs less upscaling/more downscaling */
6660 				dst.width = src.width *
6661 						dst.height / src.height;
6662 			} else {
6663 				/* width needs less upscaling/more downscaling */
6664 				dst.height = src.height *
6665 						dst.width / src.width;
6666 			}
6667 		} else if (rmx_type == RMX_CENTER) {
6668 			dst = src;
6669 		}
6670 
6671 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6672 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6673 
6674 		if (dm_state->underscan_enable) {
6675 			dst.x += dm_state->underscan_hborder / 2;
6676 			dst.y += dm_state->underscan_vborder / 2;
6677 			dst.width -= dm_state->underscan_hborder;
6678 			dst.height -= dm_state->underscan_vborder;
6679 		}
6680 	}
6681 
6682 	stream->src = src;
6683 	stream->dst = dst;
6684 
6685 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6686 		    dst.x, dst.y, dst.width, dst.height);
6687 
6688 }
6689 
6690 static enum dc_color_depth
6691 convert_color_depth_from_display_info(const struct drm_connector *connector,
6692 				      bool is_y420, int requested_bpc)
6693 {
6694 	u8 bpc;
6695 
6696 	if (is_y420) {
6697 		bpc = 8;
6698 
6699 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6700 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6701 			bpc = 16;
6702 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6703 			bpc = 12;
6704 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6705 			bpc = 10;
6706 	} else {
6707 		bpc = (uint8_t)connector->display_info.bpc;
6708 		/* Assume 8 bpc by default if no bpc is specified. */
6709 		bpc = bpc ? bpc : 8;
6710 	}
6711 
6712 	if (requested_bpc > 0) {
6713 		/*
6714 		 * Cap display bpc based on the user requested value.
6715 		 *
6716 		 * The value for state->max_bpc may not correctly updated
6717 		 * depending on when the connector gets added to the state
6718 		 * or if this was called outside of atomic check, so it
6719 		 * can't be used directly.
6720 		 */
6721 		bpc = min_t(u8, bpc, requested_bpc);
6722 
6723 		/* Round down to the nearest even number. */
6724 		bpc = bpc - (bpc & 1);
6725 	}
6726 
6727 	switch (bpc) {
6728 	case 0:
6729 		/*
6730 		 * Temporary Work around, DRM doesn't parse color depth for
6731 		 * EDID revision before 1.4
6732 		 * TODO: Fix edid parsing
6733 		 */
6734 		return COLOR_DEPTH_888;
6735 	case 6:
6736 		return COLOR_DEPTH_666;
6737 	case 8:
6738 		return COLOR_DEPTH_888;
6739 	case 10:
6740 		return COLOR_DEPTH_101010;
6741 	case 12:
6742 		return COLOR_DEPTH_121212;
6743 	case 14:
6744 		return COLOR_DEPTH_141414;
6745 	case 16:
6746 		return COLOR_DEPTH_161616;
6747 	default:
6748 		return COLOR_DEPTH_UNDEFINED;
6749 	}
6750 }
6751 
6752 static enum dc_aspect_ratio
6753 get_aspect_ratio(const struct drm_display_mode *mode_in)
6754 {
6755 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6756 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6757 }
6758 
6759 static enum dc_color_space
6760 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6761 		       const struct drm_connector_state *connector_state)
6762 {
6763 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6764 
6765 	switch (connector_state->colorspace) {
6766 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6767 		if (dc_crtc_timing->flags.Y_ONLY)
6768 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6769 		else
6770 			color_space = COLOR_SPACE_YCBCR601;
6771 		break;
6772 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6773 		if (dc_crtc_timing->flags.Y_ONLY)
6774 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6775 		else
6776 			color_space = COLOR_SPACE_YCBCR709;
6777 		break;
6778 	case DRM_MODE_COLORIMETRY_OPRGB:
6779 		color_space = COLOR_SPACE_ADOBERGB;
6780 		break;
6781 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6782 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6783 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6784 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6785 		else
6786 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6787 		break;
6788 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6789 	default:
6790 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6791 			color_space = COLOR_SPACE_SRGB;
6792 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6793 				color_space = COLOR_SPACE_SRGB_LIMITED;
6794 		/*
6795 		 * 27030khz is the separation point between HDTV and SDTV
6796 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6797 		 * respectively
6798 		 */
6799 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6800 			if (dc_crtc_timing->flags.Y_ONLY)
6801 				color_space =
6802 					COLOR_SPACE_YCBCR709_LIMITED;
6803 			else
6804 				color_space = COLOR_SPACE_YCBCR709;
6805 		} else {
6806 			if (dc_crtc_timing->flags.Y_ONLY)
6807 				color_space =
6808 					COLOR_SPACE_YCBCR601_LIMITED;
6809 			else
6810 				color_space = COLOR_SPACE_YCBCR601;
6811 		}
6812 		break;
6813 	}
6814 
6815 	return color_space;
6816 }
6817 
6818 static enum display_content_type
6819 get_output_content_type(const struct drm_connector_state *connector_state)
6820 {
6821 	switch (connector_state->content_type) {
6822 	default:
6823 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6824 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6825 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6826 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6827 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6828 		return DISPLAY_CONTENT_TYPE_PHOTO;
6829 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6830 		return DISPLAY_CONTENT_TYPE_CINEMA;
6831 	case DRM_MODE_CONTENT_TYPE_GAME:
6832 		return DISPLAY_CONTENT_TYPE_GAME;
6833 	}
6834 }
6835 
6836 static bool adjust_colour_depth_from_display_info(
6837 	struct dc_crtc_timing *timing_out,
6838 	const struct drm_display_info *info)
6839 {
6840 	enum dc_color_depth depth = timing_out->display_color_depth;
6841 	int normalized_clk;
6842 
6843 	do {
6844 		normalized_clk = timing_out->pix_clk_100hz / 10;
6845 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6846 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6847 			normalized_clk /= 2;
6848 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6849 		switch (depth) {
6850 		case COLOR_DEPTH_888:
6851 			break;
6852 		case COLOR_DEPTH_101010:
6853 			normalized_clk = (normalized_clk * 30) / 24;
6854 			break;
6855 		case COLOR_DEPTH_121212:
6856 			normalized_clk = (normalized_clk * 36) / 24;
6857 			break;
6858 		case COLOR_DEPTH_161616:
6859 			normalized_clk = (normalized_clk * 48) / 24;
6860 			break;
6861 		default:
6862 			/* The above depths are the only ones valid for HDMI. */
6863 			return false;
6864 		}
6865 		if (normalized_clk <= info->max_tmds_clock) {
6866 			timing_out->display_color_depth = depth;
6867 			return true;
6868 		}
6869 	} while (--depth > COLOR_DEPTH_666);
6870 	return false;
6871 }
6872 
6873 static void fill_stream_properties_from_drm_display_mode(
6874 	struct dc_stream_state *stream,
6875 	const struct drm_display_mode *mode_in,
6876 	const struct drm_connector *connector,
6877 	const struct drm_connector_state *connector_state,
6878 	const struct dc_stream_state *old_stream,
6879 	int requested_bpc)
6880 {
6881 	struct dc_crtc_timing *timing_out = &stream->timing;
6882 	const struct drm_display_info *info = &connector->display_info;
6883 	struct amdgpu_dm_connector *aconnector = NULL;
6884 	struct hdmi_vendor_infoframe hv_frame;
6885 	struct hdmi_avi_infoframe avi_frame;
6886 	ssize_t err;
6887 
6888 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6889 		aconnector = to_amdgpu_dm_connector(connector);
6890 
6891 	memset(&hv_frame, 0, sizeof(hv_frame));
6892 	memset(&avi_frame, 0, sizeof(avi_frame));
6893 
6894 	timing_out->h_border_left = 0;
6895 	timing_out->h_border_right = 0;
6896 	timing_out->v_border_top = 0;
6897 	timing_out->v_border_bottom = 0;
6898 	/* TODO: un-hardcode */
6899 	if (drm_mode_is_420_only(info, mode_in)
6900 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6901 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6902 	else if (drm_mode_is_420_also(info, mode_in)
6903 			&& aconnector
6904 			&& aconnector->force_yuv420_output)
6905 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6906 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6907 			&& aconnector
6908 			&& aconnector->force_yuv422_output)
6909 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6910 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
6911 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6912 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6913 	else
6914 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6915 
6916 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6917 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6918 		connector,
6919 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6920 		requested_bpc);
6921 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6922 	timing_out->hdmi_vic = 0;
6923 
6924 	if (old_stream) {
6925 		timing_out->vic = old_stream->timing.vic;
6926 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6927 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6928 	} else {
6929 		timing_out->vic = drm_match_cea_mode(mode_in);
6930 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6931 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6932 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6933 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6934 	}
6935 
6936 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6937 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6938 							       (struct drm_connector *)connector,
6939 							       mode_in);
6940 		if (err < 0)
6941 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6942 				      connector->name, err);
6943 		timing_out->vic = avi_frame.video_code;
6944 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6945 								  (struct drm_connector *)connector,
6946 								  mode_in);
6947 		if (err < 0)
6948 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6949 				      connector->name, err);
6950 		timing_out->hdmi_vic = hv_frame.vic;
6951 	}
6952 
6953 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6954 		timing_out->h_addressable = mode_in->hdisplay;
6955 		timing_out->h_total = mode_in->htotal;
6956 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6957 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6958 		timing_out->v_total = mode_in->vtotal;
6959 		timing_out->v_addressable = mode_in->vdisplay;
6960 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6961 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6962 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6963 	} else {
6964 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6965 		timing_out->h_total = mode_in->crtc_htotal;
6966 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6967 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6968 		timing_out->v_total = mode_in->crtc_vtotal;
6969 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6970 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6971 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6972 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6973 	}
6974 
6975 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6976 
6977 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6978 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6979 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6980 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6981 		    drm_mode_is_420_also(info, mode_in) &&
6982 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6983 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6984 			adjust_colour_depth_from_display_info(timing_out, info);
6985 		}
6986 	}
6987 
6988 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6989 	stream->content_type = get_output_content_type(connector_state);
6990 }
6991 
6992 static void fill_audio_info(struct audio_info *audio_info,
6993 			    const struct drm_connector *drm_connector,
6994 			    const struct dc_sink *dc_sink)
6995 {
6996 	int i = 0;
6997 	int cea_revision = 0;
6998 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6999 
7000 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7001 	audio_info->product_id = edid_caps->product_id;
7002 
7003 	cea_revision = drm_connector->display_info.cea_rev;
7004 
7005 	strscpy(audio_info->display_name,
7006 		edid_caps->display_name,
7007 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7008 
7009 	if (cea_revision >= 3) {
7010 		audio_info->mode_count = edid_caps->audio_mode_count;
7011 
7012 		for (i = 0; i < audio_info->mode_count; ++i) {
7013 			audio_info->modes[i].format_code =
7014 					(enum audio_format_code)
7015 					(edid_caps->audio_modes[i].format_code);
7016 			audio_info->modes[i].channel_count =
7017 					edid_caps->audio_modes[i].channel_count;
7018 			audio_info->modes[i].sample_rates.all =
7019 					edid_caps->audio_modes[i].sample_rate;
7020 			audio_info->modes[i].sample_size =
7021 					edid_caps->audio_modes[i].sample_size;
7022 		}
7023 	}
7024 
7025 	audio_info->flags.all = edid_caps->speaker_flags;
7026 
7027 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7028 	if (drm_connector->latency_present[0]) {
7029 		audio_info->video_latency = drm_connector->video_latency[0];
7030 		audio_info->audio_latency = drm_connector->audio_latency[0];
7031 	}
7032 
7033 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7034 
7035 }
7036 
7037 static void
7038 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7039 				      struct drm_display_mode *dst_mode)
7040 {
7041 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7042 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7043 	dst_mode->crtc_clock = src_mode->crtc_clock;
7044 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7045 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7046 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7047 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7048 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7049 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7050 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7051 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7052 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7053 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7054 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7055 }
7056 
7057 static void
7058 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7059 					const struct drm_display_mode *native_mode,
7060 					bool scale_enabled)
7061 {
7062 	if (scale_enabled || (
7063 	    native_mode->clock == drm_mode->clock &&
7064 	    native_mode->htotal == drm_mode->htotal &&
7065 	    native_mode->vtotal == drm_mode->vtotal)) {
7066 		if (native_mode->crtc_clock)
7067 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7068 	} else {
7069 		/* no scaling nor amdgpu inserted, no need to patch */
7070 	}
7071 }
7072 
7073 static struct dc_sink *
7074 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7075 {
7076 	struct dc_sink_init_data sink_init_data = { 0 };
7077 	struct dc_sink *sink = NULL;
7078 
7079 	sink_init_data.link = link;
7080 	sink_init_data.sink_signal = link->connector_signal;
7081 
7082 	sink = dc_sink_create(&sink_init_data);
7083 	if (!sink) {
7084 		drm_err(dev, "Failed to create sink!\n");
7085 		return NULL;
7086 	}
7087 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7088 
7089 	return sink;
7090 }
7091 
7092 static void set_multisync_trigger_params(
7093 		struct dc_stream_state *stream)
7094 {
7095 	struct dc_stream_state *master = NULL;
7096 
7097 	if (stream->triggered_crtc_reset.enabled) {
7098 		master = stream->triggered_crtc_reset.event_source;
7099 		stream->triggered_crtc_reset.event =
7100 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7101 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7102 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7103 	}
7104 }
7105 
7106 static void set_master_stream(struct dc_stream_state *stream_set[],
7107 			      int stream_count)
7108 {
7109 	int j, highest_rfr = 0, master_stream = 0;
7110 
7111 	for (j = 0;  j < stream_count; j++) {
7112 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7113 			int refresh_rate = 0;
7114 
7115 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7116 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7117 			if (refresh_rate > highest_rfr) {
7118 				highest_rfr = refresh_rate;
7119 				master_stream = j;
7120 			}
7121 		}
7122 	}
7123 	for (j = 0;  j < stream_count; j++) {
7124 		if (stream_set[j])
7125 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7126 	}
7127 }
7128 
7129 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7130 {
7131 	int i = 0;
7132 	struct dc_stream_state *stream;
7133 
7134 	if (context->stream_count < 2)
7135 		return;
7136 	for (i = 0; i < context->stream_count ; i++) {
7137 		if (!context->streams[i])
7138 			continue;
7139 		/*
7140 		 * TODO: add a function to read AMD VSDB bits and set
7141 		 * crtc_sync_master.multi_sync_enabled flag
7142 		 * For now it's set to false
7143 		 */
7144 	}
7145 
7146 	set_master_stream(context->streams, context->stream_count);
7147 
7148 	for (i = 0; i < context->stream_count ; i++) {
7149 		stream = context->streams[i];
7150 
7151 		if (!stream)
7152 			continue;
7153 
7154 		set_multisync_trigger_params(stream);
7155 	}
7156 }
7157 
7158 /**
7159  * DOC: FreeSync Video
7160  *
7161  * When a userspace application wants to play a video, the content follows a
7162  * standard format definition that usually specifies the FPS for that format.
7163  * The below list illustrates some video format and the expected FPS,
7164  * respectively:
7165  *
7166  * - TV/NTSC (23.976 FPS)
7167  * - Cinema (24 FPS)
7168  * - TV/PAL (25 FPS)
7169  * - TV/NTSC (29.97 FPS)
7170  * - TV/NTSC (30 FPS)
7171  * - Cinema HFR (48 FPS)
7172  * - TV/PAL (50 FPS)
7173  * - Commonly used (60 FPS)
7174  * - Multiples of 24 (48,72,96 FPS)
7175  *
7176  * The list of standards video format is not huge and can be added to the
7177  * connector modeset list beforehand. With that, userspace can leverage
7178  * FreeSync to extends the front porch in order to attain the target refresh
7179  * rate. Such a switch will happen seamlessly, without screen blanking or
7180  * reprogramming of the output in any other way. If the userspace requests a
7181  * modesetting change compatible with FreeSync modes that only differ in the
7182  * refresh rate, DC will skip the full update and avoid blink during the
7183  * transition. For example, the video player can change the modesetting from
7184  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7185  * causing any display blink. This same concept can be applied to a mode
7186  * setting change.
7187  */
7188 static struct drm_display_mode *
7189 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7190 		bool use_probed_modes)
7191 {
7192 	struct drm_display_mode *m, *m_pref = NULL;
7193 	u16 current_refresh, highest_refresh;
7194 	struct list_head *list_head = use_probed_modes ?
7195 		&aconnector->base.probed_modes :
7196 		&aconnector->base.modes;
7197 
7198 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7199 		return NULL;
7200 
7201 	if (aconnector->freesync_vid_base.clock != 0)
7202 		return &aconnector->freesync_vid_base;
7203 
7204 	/* Find the preferred mode */
7205 	list_for_each_entry(m, list_head, head) {
7206 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7207 			m_pref = m;
7208 			break;
7209 		}
7210 	}
7211 
7212 	if (!m_pref) {
7213 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7214 		m_pref = list_first_entry_or_null(
7215 				&aconnector->base.modes, struct drm_display_mode, head);
7216 		if (!m_pref) {
7217 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7218 			return NULL;
7219 		}
7220 	}
7221 
7222 	highest_refresh = drm_mode_vrefresh(m_pref);
7223 
7224 	/*
7225 	 * Find the mode with highest refresh rate with same resolution.
7226 	 * For some monitors, preferred mode is not the mode with highest
7227 	 * supported refresh rate.
7228 	 */
7229 	list_for_each_entry(m, list_head, head) {
7230 		current_refresh  = drm_mode_vrefresh(m);
7231 
7232 		if (m->hdisplay == m_pref->hdisplay &&
7233 		    m->vdisplay == m_pref->vdisplay &&
7234 		    highest_refresh < current_refresh) {
7235 			highest_refresh = current_refresh;
7236 			m_pref = m;
7237 		}
7238 	}
7239 
7240 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7241 	return m_pref;
7242 }
7243 
7244 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7245 		struct amdgpu_dm_connector *aconnector)
7246 {
7247 	struct drm_display_mode *high_mode;
7248 	int timing_diff;
7249 
7250 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7251 	if (!high_mode || !mode)
7252 		return false;
7253 
7254 	timing_diff = high_mode->vtotal - mode->vtotal;
7255 
7256 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7257 	    high_mode->hdisplay != mode->hdisplay ||
7258 	    high_mode->vdisplay != mode->vdisplay ||
7259 	    high_mode->hsync_start != mode->hsync_start ||
7260 	    high_mode->hsync_end != mode->hsync_end ||
7261 	    high_mode->htotal != mode->htotal ||
7262 	    high_mode->hskew != mode->hskew ||
7263 	    high_mode->vscan != mode->vscan ||
7264 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7265 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7266 		return false;
7267 	else
7268 		return true;
7269 }
7270 
7271 #if defined(CONFIG_DRM_AMD_DC_FP)
7272 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7273 			    struct dc_sink *sink, struct dc_stream_state *stream,
7274 			    struct dsc_dec_dpcd_caps *dsc_caps)
7275 {
7276 	stream->timing.flags.DSC = 0;
7277 	dsc_caps->is_dsc_supported = false;
7278 
7279 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7280 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7281 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7282 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7283 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7284 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7285 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7286 				dsc_caps);
7287 	}
7288 }
7289 
7290 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7291 				    struct dc_sink *sink, struct dc_stream_state *stream,
7292 				    struct dsc_dec_dpcd_caps *dsc_caps,
7293 				    uint32_t max_dsc_target_bpp_limit_override)
7294 {
7295 	const struct dc_link_settings *verified_link_cap = NULL;
7296 	u32 link_bw_in_kbps;
7297 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7298 	struct dc *dc = sink->ctx->dc;
7299 	struct dc_dsc_bw_range bw_range = {0};
7300 	struct dc_dsc_config dsc_cfg = {0};
7301 	struct dc_dsc_config_options dsc_options = {0};
7302 
7303 	dc_dsc_get_default_config_option(dc, &dsc_options);
7304 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7305 
7306 	verified_link_cap = dc_link_get_link_cap(stream->link);
7307 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7308 	edp_min_bpp_x16 = 8 * 16;
7309 	edp_max_bpp_x16 = 8 * 16;
7310 
7311 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7312 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7313 
7314 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7315 		edp_min_bpp_x16 = edp_max_bpp_x16;
7316 
7317 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7318 				dc->debug.dsc_min_slice_height_override,
7319 				edp_min_bpp_x16, edp_max_bpp_x16,
7320 				dsc_caps,
7321 				&stream->timing,
7322 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7323 				&bw_range)) {
7324 
7325 		if (bw_range.max_kbps < link_bw_in_kbps) {
7326 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7327 					dsc_caps,
7328 					&dsc_options,
7329 					0,
7330 					&stream->timing,
7331 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7332 					&dsc_cfg)) {
7333 				stream->timing.dsc_cfg = dsc_cfg;
7334 				stream->timing.flags.DSC = 1;
7335 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7336 			}
7337 			return;
7338 		}
7339 	}
7340 
7341 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7342 				dsc_caps,
7343 				&dsc_options,
7344 				link_bw_in_kbps,
7345 				&stream->timing,
7346 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7347 				&dsc_cfg)) {
7348 		stream->timing.dsc_cfg = dsc_cfg;
7349 		stream->timing.flags.DSC = 1;
7350 	}
7351 }
7352 
7353 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7354 					struct dc_sink *sink, struct dc_stream_state *stream,
7355 					struct dsc_dec_dpcd_caps *dsc_caps)
7356 {
7357 	struct drm_connector *drm_connector = &aconnector->base;
7358 	u32 link_bandwidth_kbps;
7359 	struct dc *dc = sink->ctx->dc;
7360 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7361 	u32 dsc_max_supported_bw_in_kbps;
7362 	u32 max_dsc_target_bpp_limit_override =
7363 		drm_connector->display_info.max_dsc_bpp;
7364 	struct dc_dsc_config_options dsc_options = {0};
7365 
7366 	dc_dsc_get_default_config_option(dc, &dsc_options);
7367 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7368 
7369 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7370 							dc_link_get_link_cap(aconnector->dc_link));
7371 
7372 	/* Set DSC policy according to dsc_clock_en */
7373 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7374 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7375 
7376 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7377 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7378 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7379 
7380 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7381 
7382 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7383 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7384 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7385 						dsc_caps,
7386 						&dsc_options,
7387 						link_bandwidth_kbps,
7388 						&stream->timing,
7389 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7390 						&stream->timing.dsc_cfg)) {
7391 				stream->timing.flags.DSC = 1;
7392 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7393 							__func__, drm_connector->name);
7394 			}
7395 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7396 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7397 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7398 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7399 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7400 
7401 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7402 					max_supported_bw_in_kbps > 0 &&
7403 					dsc_max_supported_bw_in_kbps > 0)
7404 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7405 						dsc_caps,
7406 						&dsc_options,
7407 						dsc_max_supported_bw_in_kbps,
7408 						&stream->timing,
7409 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7410 						&stream->timing.dsc_cfg)) {
7411 					stream->timing.flags.DSC = 1;
7412 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7413 									 __func__, drm_connector->name);
7414 				}
7415 		}
7416 	}
7417 
7418 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7419 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7420 		stream->timing.flags.DSC = 1;
7421 
7422 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7423 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7424 
7425 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7426 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7427 
7428 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7429 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7430 }
7431 #endif
7432 
7433 static struct dc_stream_state *
7434 create_stream_for_sink(struct drm_connector *connector,
7435 		       const struct drm_display_mode *drm_mode,
7436 		       const struct dm_connector_state *dm_state,
7437 		       const struct dc_stream_state *old_stream,
7438 		       int requested_bpc)
7439 {
7440 	struct drm_device *dev = connector->dev;
7441 	struct amdgpu_dm_connector *aconnector = NULL;
7442 	struct drm_display_mode *preferred_mode = NULL;
7443 	const struct drm_connector_state *con_state = &dm_state->base;
7444 	struct dc_stream_state *stream = NULL;
7445 	struct drm_display_mode mode;
7446 	struct drm_display_mode saved_mode;
7447 	struct drm_display_mode *freesync_mode = NULL;
7448 	bool native_mode_found = false;
7449 	bool recalculate_timing = false;
7450 	bool scale = dm_state->scaling != RMX_OFF;
7451 	int mode_refresh;
7452 	int preferred_refresh = 0;
7453 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7454 #if defined(CONFIG_DRM_AMD_DC_FP)
7455 	struct dsc_dec_dpcd_caps dsc_caps;
7456 #endif
7457 	struct dc_link *link = NULL;
7458 	struct dc_sink *sink = NULL;
7459 
7460 	drm_mode_init(&mode, drm_mode);
7461 	memset(&saved_mode, 0, sizeof(saved_mode));
7462 
7463 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7464 		aconnector = NULL;
7465 		aconnector = to_amdgpu_dm_connector(connector);
7466 		link = aconnector->dc_link;
7467 	} else {
7468 		struct drm_writeback_connector *wbcon = NULL;
7469 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7470 
7471 		wbcon = drm_connector_to_writeback(connector);
7472 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7473 		link = dm_wbcon->link;
7474 	}
7475 
7476 	if (!aconnector || !aconnector->dc_sink) {
7477 		sink = create_fake_sink(dev, link);
7478 		if (!sink)
7479 			return stream;
7480 
7481 	} else {
7482 		sink = aconnector->dc_sink;
7483 		dc_sink_retain(sink);
7484 	}
7485 
7486 	stream = dc_create_stream_for_sink(sink);
7487 
7488 	if (stream == NULL) {
7489 		drm_err(dev, "Failed to create stream for sink!\n");
7490 		goto finish;
7491 	}
7492 
7493 	/* We leave this NULL for writeback connectors */
7494 	stream->dm_stream_context = aconnector;
7495 
7496 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7497 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7498 
7499 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7500 		/* Search for preferred mode */
7501 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7502 			native_mode_found = true;
7503 			break;
7504 		}
7505 	}
7506 	if (!native_mode_found)
7507 		preferred_mode = list_first_entry_or_null(
7508 				&connector->modes,
7509 				struct drm_display_mode,
7510 				head);
7511 
7512 	mode_refresh = drm_mode_vrefresh(&mode);
7513 
7514 	if (preferred_mode == NULL) {
7515 		/*
7516 		 * This may not be an error, the use case is when we have no
7517 		 * usermode calls to reset and set mode upon hotplug. In this
7518 		 * case, we call set mode ourselves to restore the previous mode
7519 		 * and the modelist may not be filled in time.
7520 		 */
7521 		drm_dbg_driver(dev, "No preferred mode found\n");
7522 	} else if (aconnector) {
7523 		recalculate_timing = amdgpu_freesync_vid_mode &&
7524 				 is_freesync_video_mode(&mode, aconnector);
7525 		if (recalculate_timing) {
7526 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7527 			drm_mode_copy(&saved_mode, &mode);
7528 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7529 			drm_mode_copy(&mode, freesync_mode);
7530 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7531 		} else {
7532 			decide_crtc_timing_for_drm_display_mode(
7533 					&mode, preferred_mode, scale);
7534 
7535 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7536 		}
7537 	}
7538 
7539 	if (recalculate_timing)
7540 		drm_mode_set_crtcinfo(&saved_mode, 0);
7541 
7542 	/*
7543 	 * If scaling is enabled and refresh rate didn't change
7544 	 * we copy the vic and polarities of the old timings
7545 	 */
7546 	if (!scale || mode_refresh != preferred_refresh)
7547 		fill_stream_properties_from_drm_display_mode(
7548 			stream, &mode, connector, con_state, NULL,
7549 			requested_bpc);
7550 	else
7551 		fill_stream_properties_from_drm_display_mode(
7552 			stream, &mode, connector, con_state, old_stream,
7553 			requested_bpc);
7554 
7555 	/* The rest isn't needed for writeback connectors */
7556 	if (!aconnector)
7557 		goto finish;
7558 
7559 	if (aconnector->timing_changed) {
7560 		drm_dbg(aconnector->base.dev,
7561 			"overriding timing for automated test, bpc %d, changing to %d\n",
7562 			stream->timing.display_color_depth,
7563 			aconnector->timing_requested->display_color_depth);
7564 		stream->timing = *aconnector->timing_requested;
7565 	}
7566 
7567 #if defined(CONFIG_DRM_AMD_DC_FP)
7568 	/* SST DSC determination policy */
7569 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7570 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7571 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7572 #endif
7573 
7574 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7575 
7576 	fill_audio_info(
7577 		&stream->audio_info,
7578 		connector,
7579 		sink);
7580 
7581 	update_stream_signal(stream, sink);
7582 
7583 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7584 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7585 
7586 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7587 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7588 	    stream->signal == SIGNAL_TYPE_EDP) {
7589 		const struct dc_edid_caps *edid_caps;
7590 		unsigned int disable_colorimetry = 0;
7591 
7592 		if (aconnector->dc_sink) {
7593 			edid_caps = &aconnector->dc_sink->edid_caps;
7594 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7595 		}
7596 
7597 		//
7598 		// should decide stream support vsc sdp colorimetry capability
7599 		// before building vsc info packet
7600 		//
7601 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7602 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7603 						      !disable_colorimetry;
7604 
7605 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7606 			tf = TRANSFER_FUNC_GAMMA_22;
7607 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7608 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7609 
7610 	}
7611 finish:
7612 	dc_sink_release(sink);
7613 
7614 	return stream;
7615 }
7616 
7617 /**
7618  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7619  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7620  * @force: if true, force polling even when DAC load detection was used
7621  *
7622  * Used for connectors that don't support HPD (hotplug detection) to
7623  * periodically check whether the connector is connected to a display.
7624  *
7625  * When connection was determined via DAC load detection, we avoid
7626  * re-running it on normal polls to prevent visible glitches, unless
7627  * @force is set.
7628  *
7629  * Return: The probed connector status (connected/disconnected/unknown).
7630  */
7631 static enum drm_connector_status
7632 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7633 {
7634 	struct drm_connector *connector = &aconnector->base;
7635 	struct drm_device *dev = connector->dev;
7636 	struct amdgpu_device *adev = drm_to_adev(dev);
7637 	struct dc_link *link = aconnector->dc_link;
7638 	enum dc_connection_type conn_type = dc_connection_none;
7639 	enum drm_connector_status status = connector_status_disconnected;
7640 
7641 	/* When we determined the connection using DAC load detection,
7642 	 * do NOT poll the connector do detect disconnect because
7643 	 * that would run DAC load detection again which can cause
7644 	 * visible visual glitches.
7645 	 *
7646 	 * Only allow to poll such a connector again when forcing.
7647 	 */
7648 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7649 		return connector->status;
7650 
7651 	mutex_lock(&aconnector->hpd_lock);
7652 
7653 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7654 	    conn_type != dc_connection_none) {
7655 		mutex_lock(&adev->dm.dc_lock);
7656 
7657 		/* Only call full link detection when a sink isn't created yet,
7658 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7659 		 */
7660 		if (link->local_sink ||
7661 			dc_link_detect(link, DETECT_REASON_HPD))
7662 			status = connector_status_connected;
7663 
7664 		mutex_unlock(&adev->dm.dc_lock);
7665 	}
7666 
7667 	if (connector->status != status) {
7668 		if (status == connector_status_disconnected) {
7669 			if (link->local_sink)
7670 				dc_sink_release(link->local_sink);
7671 
7672 			link->local_sink = NULL;
7673 			link->dpcd_sink_count = 0;
7674 			link->type = dc_connection_none;
7675 		}
7676 
7677 		amdgpu_dm_update_connector_after_detect(aconnector);
7678 	}
7679 
7680 	mutex_unlock(&aconnector->hpd_lock);
7681 	return status;
7682 }
7683 
7684 /**
7685  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7686  *
7687  * A connector is considered connected when it has a sink that is not NULL.
7688  * For connectors that support HPD (hotplug detection), the connection is
7689  * handled in the HPD interrupt.
7690  * For connectors that may not support HPD, such as analog connectors,
7691  * DRM will call this function repeatedly to poll them.
7692  *
7693  * Notes:
7694  * 1. This interface is NOT called in context of HPD irq.
7695  * 2. This interface *is called* in context of user-mode ioctl. Which
7696  *    makes it a bad place for *any* MST-related activity.
7697  *
7698  * @connector: The DRM connector we are checking. We convert it to
7699  *             amdgpu_dm_connector so we can read the DC link and state.
7700  * @force:     If true, do a full detect again. This is used even when
7701  *             a lighter check would normally be used to avoid flicker.
7702  *
7703  * Return: The connector status (connected, disconnected, or unknown).
7704  *
7705  */
7706 static enum drm_connector_status
7707 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7708 {
7709 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7710 
7711 	update_subconnector_property(aconnector);
7712 
7713 	if (aconnector->base.force == DRM_FORCE_ON ||
7714 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7715 		return connector_status_connected;
7716 	else if (aconnector->base.force == DRM_FORCE_OFF)
7717 		return connector_status_disconnected;
7718 
7719 	/* Poll analog connectors and only when either
7720 	 * disconnected or connected to an analog display.
7721 	 */
7722 	if (drm_kms_helper_is_poll_worker() &&
7723 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7724 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7725 		return amdgpu_dm_connector_poll(aconnector, force);
7726 
7727 	return (aconnector->dc_sink ? connector_status_connected :
7728 			connector_status_disconnected);
7729 }
7730 
7731 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7732 					    struct drm_connector_state *connector_state,
7733 					    struct drm_property *property,
7734 					    uint64_t val)
7735 {
7736 	struct drm_device *dev = connector->dev;
7737 	struct amdgpu_device *adev = drm_to_adev(dev);
7738 	struct dm_connector_state *dm_old_state =
7739 		to_dm_connector_state(connector->state);
7740 	struct dm_connector_state *dm_new_state =
7741 		to_dm_connector_state(connector_state);
7742 
7743 	int ret = -EINVAL;
7744 
7745 	if (property == dev->mode_config.scaling_mode_property) {
7746 		enum amdgpu_rmx_type rmx_type;
7747 
7748 		switch (val) {
7749 		case DRM_MODE_SCALE_CENTER:
7750 			rmx_type = RMX_CENTER;
7751 			break;
7752 		case DRM_MODE_SCALE_ASPECT:
7753 			rmx_type = RMX_ASPECT;
7754 			break;
7755 		case DRM_MODE_SCALE_FULLSCREEN:
7756 			rmx_type = RMX_FULL;
7757 			break;
7758 		case DRM_MODE_SCALE_NONE:
7759 		default:
7760 			rmx_type = RMX_OFF;
7761 			break;
7762 		}
7763 
7764 		if (dm_old_state->scaling == rmx_type)
7765 			return 0;
7766 
7767 		dm_new_state->scaling = rmx_type;
7768 		ret = 0;
7769 	} else if (property == adev->mode_info.underscan_hborder_property) {
7770 		dm_new_state->underscan_hborder = val;
7771 		ret = 0;
7772 	} else if (property == adev->mode_info.underscan_vborder_property) {
7773 		dm_new_state->underscan_vborder = val;
7774 		ret = 0;
7775 	} else if (property == adev->mode_info.underscan_property) {
7776 		dm_new_state->underscan_enable = val;
7777 		ret = 0;
7778 	} else if (property == adev->mode_info.abm_level_property) {
7779 		switch (val) {
7780 		case ABM_SYSFS_CONTROL:
7781 			dm_new_state->abm_sysfs_forbidden = false;
7782 			break;
7783 		case ABM_LEVEL_OFF:
7784 			dm_new_state->abm_sysfs_forbidden = true;
7785 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7786 			break;
7787 		default:
7788 			dm_new_state->abm_sysfs_forbidden = true;
7789 			dm_new_state->abm_level = val;
7790 		}
7791 		ret = 0;
7792 	}
7793 
7794 	return ret;
7795 }
7796 
7797 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7798 					    const struct drm_connector_state *state,
7799 					    struct drm_property *property,
7800 					    uint64_t *val)
7801 {
7802 	struct drm_device *dev = connector->dev;
7803 	struct amdgpu_device *adev = drm_to_adev(dev);
7804 	struct dm_connector_state *dm_state =
7805 		to_dm_connector_state(state);
7806 	int ret = -EINVAL;
7807 
7808 	if (property == dev->mode_config.scaling_mode_property) {
7809 		switch (dm_state->scaling) {
7810 		case RMX_CENTER:
7811 			*val = DRM_MODE_SCALE_CENTER;
7812 			break;
7813 		case RMX_ASPECT:
7814 			*val = DRM_MODE_SCALE_ASPECT;
7815 			break;
7816 		case RMX_FULL:
7817 			*val = DRM_MODE_SCALE_FULLSCREEN;
7818 			break;
7819 		case RMX_OFF:
7820 		default:
7821 			*val = DRM_MODE_SCALE_NONE;
7822 			break;
7823 		}
7824 		ret = 0;
7825 	} else if (property == adev->mode_info.underscan_hborder_property) {
7826 		*val = dm_state->underscan_hborder;
7827 		ret = 0;
7828 	} else if (property == adev->mode_info.underscan_vborder_property) {
7829 		*val = dm_state->underscan_vborder;
7830 		ret = 0;
7831 	} else if (property == adev->mode_info.underscan_property) {
7832 		*val = dm_state->underscan_enable;
7833 		ret = 0;
7834 	} else if (property == adev->mode_info.abm_level_property) {
7835 		if (!dm_state->abm_sysfs_forbidden)
7836 			*val = ABM_SYSFS_CONTROL;
7837 		else
7838 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7839 				dm_state->abm_level : 0;
7840 		ret = 0;
7841 	}
7842 
7843 	return ret;
7844 }
7845 
7846 /**
7847  * DOC: panel power savings
7848  *
7849  * The display manager allows you to set your desired **panel power savings**
7850  * level (between 0-4, with 0 representing off), e.g. using the following::
7851  *
7852  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7853  *
7854  * Modifying this value can have implications on color accuracy, so tread
7855  * carefully.
7856  */
7857 
7858 static ssize_t panel_power_savings_show(struct device *device,
7859 					struct device_attribute *attr,
7860 					char *buf)
7861 {
7862 	struct drm_connector *connector = dev_get_drvdata(device);
7863 	struct drm_device *dev = connector->dev;
7864 	u8 val;
7865 
7866 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7867 	val = to_dm_connector_state(connector->state)->abm_level ==
7868 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7869 		to_dm_connector_state(connector->state)->abm_level;
7870 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7871 
7872 	return sysfs_emit(buf, "%u\n", val);
7873 }
7874 
7875 static ssize_t panel_power_savings_store(struct device *device,
7876 					 struct device_attribute *attr,
7877 					 const char *buf, size_t count)
7878 {
7879 	struct drm_connector *connector = dev_get_drvdata(device);
7880 	struct drm_device *dev = connector->dev;
7881 	long val;
7882 	int ret;
7883 
7884 	ret = kstrtol(buf, 0, &val);
7885 
7886 	if (ret)
7887 		return ret;
7888 
7889 	if (val < 0 || val > 4)
7890 		return -EINVAL;
7891 
7892 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7893 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7894 		ret = -EBUSY;
7895 	else
7896 		to_dm_connector_state(connector->state)->abm_level = val ?:
7897 			ABM_LEVEL_IMMEDIATE_DISABLE;
7898 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7899 
7900 	if (ret)
7901 		return ret;
7902 
7903 	drm_kms_helper_hotplug_event(dev);
7904 
7905 	return count;
7906 }
7907 
7908 static DEVICE_ATTR_RW(panel_power_savings);
7909 
7910 static struct attribute *amdgpu_attrs[] = {
7911 	&dev_attr_panel_power_savings.attr,
7912 	NULL
7913 };
7914 
7915 static const struct attribute_group amdgpu_group = {
7916 	.name = "amdgpu",
7917 	.attrs = amdgpu_attrs
7918 };
7919 
7920 static bool
7921 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7922 {
7923 	if (amdgpu_dm_abm_level >= 0)
7924 		return false;
7925 
7926 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7927 		return false;
7928 
7929 	/* check for OLED panels */
7930 	if (amdgpu_dm_connector->bl_idx >= 0) {
7931 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7932 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7933 		struct amdgpu_dm_backlight_caps *caps;
7934 
7935 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7936 		if (caps->aux_support)
7937 			return false;
7938 	}
7939 
7940 	return true;
7941 }
7942 
7943 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7944 {
7945 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7946 
7947 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7948 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7949 
7950 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7951 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7952 }
7953 
7954 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7955 {
7956 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7957 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7958 	struct amdgpu_display_manager *dm = &adev->dm;
7959 
7960 	/*
7961 	 * Call only if mst_mgr was initialized before since it's not done
7962 	 * for all connector types.
7963 	 */
7964 	if (aconnector->mst_mgr.dev)
7965 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7966 
7967 	/* Cancel and flush any pending HDMI HPD debounce work */
7968 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7969 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7970 		if (aconnector->hdmi_prev_sink) {
7971 			dc_sink_release(aconnector->hdmi_prev_sink);
7972 			aconnector->hdmi_prev_sink = NULL;
7973 		}
7974 	}
7975 
7976 	if (aconnector->bl_idx != -1) {
7977 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7978 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7979 	}
7980 
7981 	if (aconnector->dc_em_sink)
7982 		dc_sink_release(aconnector->dc_em_sink);
7983 	aconnector->dc_em_sink = NULL;
7984 	if (aconnector->dc_sink)
7985 		dc_sink_release(aconnector->dc_sink);
7986 	aconnector->dc_sink = NULL;
7987 
7988 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7989 	drm_connector_unregister(connector);
7990 	drm_connector_cleanup(connector);
7991 	kfree(aconnector->dm_dp_aux.aux.name);
7992 
7993 	kfree(connector);
7994 }
7995 
7996 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7997 {
7998 	struct dm_connector_state *state =
7999 		to_dm_connector_state(connector->state);
8000 
8001 	if (connector->state)
8002 		__drm_atomic_helper_connector_destroy_state(connector->state);
8003 
8004 	kfree(state);
8005 
8006 	state = kzalloc_obj(*state);
8007 
8008 	if (state) {
8009 		state->scaling = RMX_OFF;
8010 		state->underscan_enable = false;
8011 		state->underscan_hborder = 0;
8012 		state->underscan_vborder = 0;
8013 		state->base.max_requested_bpc = 8;
8014 		state->vcpi_slots = 0;
8015 		state->pbn = 0;
8016 
8017 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8018 			if (amdgpu_dm_abm_level <= 0)
8019 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8020 			else
8021 				state->abm_level = amdgpu_dm_abm_level;
8022 		}
8023 
8024 		__drm_atomic_helper_connector_reset(connector, &state->base);
8025 	}
8026 }
8027 
8028 struct drm_connector_state *
8029 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8030 {
8031 	struct dm_connector_state *state =
8032 		to_dm_connector_state(connector->state);
8033 
8034 	struct dm_connector_state *new_state =
8035 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8036 
8037 	if (!new_state)
8038 		return NULL;
8039 
8040 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8041 
8042 	new_state->freesync_capable = state->freesync_capable;
8043 	new_state->abm_level = state->abm_level;
8044 	new_state->scaling = state->scaling;
8045 	new_state->underscan_enable = state->underscan_enable;
8046 	new_state->underscan_hborder = state->underscan_hborder;
8047 	new_state->underscan_vborder = state->underscan_vborder;
8048 	new_state->vcpi_slots = state->vcpi_slots;
8049 	new_state->pbn = state->pbn;
8050 	return &new_state->base;
8051 }
8052 
8053 static int
8054 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8055 {
8056 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8057 		to_amdgpu_dm_connector(connector);
8058 	int r;
8059 
8060 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8061 		r = sysfs_create_group(&connector->kdev->kobj,
8062 				       &amdgpu_group);
8063 		if (r)
8064 			return r;
8065 	}
8066 
8067 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8068 
8069 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8070 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8071 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8072 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8073 		if (r)
8074 			return r;
8075 	}
8076 
8077 #if defined(CONFIG_DEBUG_FS)
8078 	connector_debugfs_init(amdgpu_dm_connector);
8079 #endif
8080 
8081 	return 0;
8082 }
8083 
8084 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8085 {
8086 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8087 	struct dc_link *dc_link = aconnector->dc_link;
8088 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8089 	const struct drm_edid *drm_edid;
8090 	struct i2c_adapter *ddc;
8091 	struct drm_device *dev = connector->dev;
8092 
8093 	if (dc_link && dc_link->aux_mode)
8094 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8095 	else
8096 		ddc = &aconnector->i2c->base;
8097 
8098 	drm_edid = drm_edid_read_ddc(connector, ddc);
8099 	drm_edid_connector_update(connector, drm_edid);
8100 	if (!drm_edid) {
8101 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8102 		return;
8103 	}
8104 
8105 	aconnector->drm_edid = drm_edid;
8106 	/* Update emulated (virtual) sink's EDID */
8107 	if (dc_em_sink && dc_link) {
8108 		// FIXME: Get rid of drm_edid_raw()
8109 		const struct edid *edid = drm_edid_raw(drm_edid);
8110 
8111 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8112 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8113 			(edid->extensions + 1) * EDID_LENGTH);
8114 		dm_helpers_parse_edid_caps(
8115 			dc_link,
8116 			&dc_em_sink->dc_edid,
8117 			&dc_em_sink->edid_caps);
8118 	}
8119 }
8120 
8121 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8122 	.reset = amdgpu_dm_connector_funcs_reset,
8123 	.detect = amdgpu_dm_connector_detect,
8124 	.fill_modes = drm_helper_probe_single_connector_modes,
8125 	.destroy = amdgpu_dm_connector_destroy,
8126 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8127 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8128 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8129 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8130 	.late_register = amdgpu_dm_connector_late_register,
8131 	.early_unregister = amdgpu_dm_connector_unregister,
8132 	.force = amdgpu_dm_connector_funcs_force
8133 };
8134 
8135 static int get_modes(struct drm_connector *connector)
8136 {
8137 	return amdgpu_dm_connector_get_modes(connector);
8138 }
8139 
8140 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8141 {
8142 	struct drm_connector *connector = &aconnector->base;
8143 	struct dc_link *dc_link = aconnector->dc_link;
8144 	struct dc_sink_init_data init_params = {
8145 			.link = aconnector->dc_link,
8146 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8147 	};
8148 	const struct drm_edid *drm_edid;
8149 	const struct edid *edid;
8150 	struct i2c_adapter *ddc;
8151 
8152 	if (dc_link && dc_link->aux_mode)
8153 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8154 	else
8155 		ddc = &aconnector->i2c->base;
8156 
8157 	drm_edid = drm_edid_read_ddc(connector, ddc);
8158 	drm_edid_connector_update(connector, drm_edid);
8159 	if (!drm_edid) {
8160 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8161 		return;
8162 	}
8163 
8164 	if (connector->display_info.is_hdmi)
8165 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8166 
8167 	aconnector->drm_edid = drm_edid;
8168 
8169 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8170 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8171 		aconnector->dc_link,
8172 		(uint8_t *)edid,
8173 		(edid->extensions + 1) * EDID_LENGTH,
8174 		&init_params);
8175 
8176 	if (aconnector->base.force == DRM_FORCE_ON) {
8177 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8178 		aconnector->dc_link->local_sink :
8179 		aconnector->dc_em_sink;
8180 		if (aconnector->dc_sink)
8181 			dc_sink_retain(aconnector->dc_sink);
8182 	}
8183 }
8184 
8185 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8186 {
8187 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8188 
8189 	/*
8190 	 * In case of headless boot with force on for DP managed connector
8191 	 * Those settings have to be != 0 to get initial modeset
8192 	 */
8193 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8194 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8195 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8196 	}
8197 
8198 	create_eml_sink(aconnector);
8199 }
8200 
8201 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8202 						struct dc_stream_state *stream)
8203 {
8204 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8205 	struct dc_plane_state *dc_plane_state = NULL;
8206 	struct dc_state *dc_state = NULL;
8207 
8208 	if (!stream)
8209 		goto cleanup;
8210 
8211 	dc_plane_state = dc_create_plane_state(dc);
8212 	if (!dc_plane_state)
8213 		goto cleanup;
8214 
8215 	dc_state = dc_state_create(dc, NULL);
8216 	if (!dc_state)
8217 		goto cleanup;
8218 
8219 	/* populate stream to plane */
8220 	dc_plane_state->src_rect.height  = stream->src.height;
8221 	dc_plane_state->src_rect.width   = stream->src.width;
8222 	dc_plane_state->dst_rect.height  = stream->src.height;
8223 	dc_plane_state->dst_rect.width   = stream->src.width;
8224 	dc_plane_state->clip_rect.height = stream->src.height;
8225 	dc_plane_state->clip_rect.width  = stream->src.width;
8226 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8227 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8228 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8229 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8230 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8231 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8232 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8233 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8234 	dc_plane_state->is_tiling_rotated = false;
8235 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8236 
8237 	dc_result = dc_validate_stream(dc, stream);
8238 	if (dc_result == DC_OK)
8239 		dc_result = dc_validate_plane(dc, dc_plane_state);
8240 
8241 	if (dc_result == DC_OK)
8242 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8243 
8244 	if (dc_result == DC_OK && !dc_state_add_plane(
8245 						dc,
8246 						stream,
8247 						dc_plane_state,
8248 						dc_state))
8249 		dc_result = DC_FAIL_ATTACH_SURFACES;
8250 
8251 	if (dc_result == DC_OK)
8252 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8253 
8254 cleanup:
8255 	if (dc_state)
8256 		dc_state_release(dc_state);
8257 
8258 	if (dc_plane_state)
8259 		dc_plane_state_release(dc_plane_state);
8260 
8261 	return dc_result;
8262 }
8263 
8264 struct dc_stream_state *
8265 create_validate_stream_for_sink(struct drm_connector *connector,
8266 				const struct drm_display_mode *drm_mode,
8267 				const struct dm_connector_state *dm_state,
8268 				const struct dc_stream_state *old_stream)
8269 {
8270 	struct amdgpu_dm_connector *aconnector = NULL;
8271 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8272 	struct dc_stream_state *stream;
8273 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8274 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8275 	enum dc_status dc_result = DC_OK;
8276 	uint8_t bpc_limit = 6;
8277 
8278 	if (!dm_state)
8279 		return NULL;
8280 
8281 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8282 		aconnector = to_amdgpu_dm_connector(connector);
8283 
8284 	if (aconnector &&
8285 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8286 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8287 		bpc_limit = 8;
8288 
8289 	do {
8290 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8291 		stream = create_stream_for_sink(connector, drm_mode,
8292 						dm_state, old_stream,
8293 						requested_bpc);
8294 		if (stream == NULL) {
8295 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8296 			break;
8297 		}
8298 
8299 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8300 
8301 		if (!aconnector) /* writeback connector */
8302 			return stream;
8303 
8304 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8305 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8306 
8307 		if (dc_result == DC_OK)
8308 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8309 
8310 		if (dc_result != DC_OK) {
8311 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8312 				      drm_mode->hdisplay,
8313 				      drm_mode->vdisplay,
8314 				      drm_mode->clock,
8315 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8316 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8317 				      dc_status_to_str(dc_result));
8318 
8319 			dc_stream_release(stream);
8320 			stream = NULL;
8321 			requested_bpc -= 2; /* lower bpc to retry validation */
8322 		}
8323 
8324 	} while (stream == NULL && requested_bpc >= bpc_limit);
8325 
8326 	switch (dc_result) {
8327 	/*
8328 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8329 	 * we try to fallback and configure in order:
8330 	 * YUV422 (8bpc, 6bpc)
8331 	 * YUV420 (8bpc, 6bpc)
8332 	 */
8333 	case DC_FAIL_ENC_VALIDATE:
8334 	case DC_EXCEED_DONGLE_CAP:
8335 	case DC_NO_DP_LINK_BANDWIDTH:
8336 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8337 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8338 			break;
8339 		/* first failure; try YUV422 */
8340 		if (!aconnector->force_yuv422_output) {
8341 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8342 				    __func__, __LINE__, dc_result);
8343 			aconnector->force_yuv422_output = true;
8344 		/* recursively entered and YUV422 failed, try YUV420 */
8345 		} else if (!aconnector->force_yuv420_output) {
8346 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8347 				    __func__, __LINE__, dc_result);
8348 			aconnector->force_yuv420_output = true;
8349 		}
8350 		stream = create_validate_stream_for_sink(connector, drm_mode,
8351 							 dm_state, old_stream);
8352 		aconnector->force_yuv422_output = false;
8353 		aconnector->force_yuv420_output = false;
8354 		break;
8355 	case DC_OK:
8356 		break;
8357 	default:
8358 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8359 			    __func__, __LINE__, dc_result);
8360 		break;
8361 	}
8362 
8363 	return stream;
8364 }
8365 
8366 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8367 				   const struct drm_display_mode *mode)
8368 {
8369 	int result = MODE_ERROR;
8370 	struct dc_sink *dc_sink;
8371 	struct drm_display_mode *test_mode;
8372 	/* TODO: Unhardcode stream count */
8373 	struct dc_stream_state *stream;
8374 	/* we always have an amdgpu_dm_connector here since we got
8375 	 * here via the amdgpu_dm_connector_helper_funcs
8376 	 */
8377 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8378 
8379 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8380 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8381 		return result;
8382 
8383 	/*
8384 	 * Only run this the first time mode_valid is called to initilialize
8385 	 * EDID mgmt
8386 	 */
8387 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8388 		!aconnector->dc_em_sink)
8389 		handle_edid_mgmt(aconnector);
8390 
8391 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8392 
8393 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8394 				aconnector->base.force != DRM_FORCE_ON) {
8395 		drm_err(connector->dev, "dc_sink is NULL!\n");
8396 		goto fail;
8397 	}
8398 
8399 	test_mode = drm_mode_duplicate(connector->dev, mode);
8400 	if (!test_mode)
8401 		goto fail;
8402 
8403 	drm_mode_set_crtcinfo(test_mode, 0);
8404 
8405 	stream = create_validate_stream_for_sink(connector, test_mode,
8406 						 to_dm_connector_state(connector->state),
8407 						 NULL);
8408 	drm_mode_destroy(connector->dev, test_mode);
8409 	if (stream) {
8410 		dc_stream_release(stream);
8411 		result = MODE_OK;
8412 	}
8413 
8414 fail:
8415 	/* TODO: error handling*/
8416 	return result;
8417 }
8418 
8419 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8420 				struct dc_info_packet *out)
8421 {
8422 	struct hdmi_drm_infoframe frame;
8423 	unsigned char buf[30]; /* 26 + 4 */
8424 	ssize_t len;
8425 	int ret, i;
8426 
8427 	memset(out, 0, sizeof(*out));
8428 
8429 	if (!state->hdr_output_metadata)
8430 		return 0;
8431 
8432 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8433 	if (ret)
8434 		return ret;
8435 
8436 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8437 	if (len < 0)
8438 		return (int)len;
8439 
8440 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8441 	if (len != 30)
8442 		return -EINVAL;
8443 
8444 	/* Prepare the infopacket for DC. */
8445 	switch (state->connector->connector_type) {
8446 	case DRM_MODE_CONNECTOR_HDMIA:
8447 		out->hb0 = 0x87; /* type */
8448 		out->hb1 = 0x01; /* version */
8449 		out->hb2 = 0x1A; /* length */
8450 		out->sb[0] = buf[3]; /* checksum */
8451 		i = 1;
8452 		break;
8453 
8454 	case DRM_MODE_CONNECTOR_DisplayPort:
8455 	case DRM_MODE_CONNECTOR_eDP:
8456 		out->hb0 = 0x00; /* sdp id, zero */
8457 		out->hb1 = 0x87; /* type */
8458 		out->hb2 = 0x1D; /* payload len - 1 */
8459 		out->hb3 = (0x13 << 2); /* sdp version */
8460 		out->sb[0] = 0x01; /* version */
8461 		out->sb[1] = 0x1A; /* length */
8462 		i = 2;
8463 		break;
8464 
8465 	default:
8466 		return -EINVAL;
8467 	}
8468 
8469 	memcpy(&out->sb[i], &buf[4], 26);
8470 	out->valid = true;
8471 
8472 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8473 		       sizeof(out->sb), false);
8474 
8475 	return 0;
8476 }
8477 
8478 static int
8479 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8480 				 struct drm_atomic_state *state)
8481 {
8482 	struct drm_connector_state *new_con_state =
8483 		drm_atomic_get_new_connector_state(state, conn);
8484 	struct drm_connector_state *old_con_state =
8485 		drm_atomic_get_old_connector_state(state, conn);
8486 	struct drm_crtc *crtc = new_con_state->crtc;
8487 	struct drm_crtc_state *new_crtc_state;
8488 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8489 	int ret;
8490 
8491 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8492 		return -EINVAL;
8493 
8494 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8495 
8496 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8497 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8498 		if (ret < 0)
8499 			return ret;
8500 	}
8501 
8502 	if (!crtc)
8503 		return 0;
8504 
8505 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8506 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8507 		if (IS_ERR(new_crtc_state))
8508 			return PTR_ERR(new_crtc_state);
8509 
8510 		new_crtc_state->mode_changed = true;
8511 	}
8512 
8513 	if (new_con_state->colorspace != old_con_state->colorspace) {
8514 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8515 		if (IS_ERR(new_crtc_state))
8516 			return PTR_ERR(new_crtc_state);
8517 
8518 		new_crtc_state->mode_changed = true;
8519 	}
8520 
8521 	if (new_con_state->content_type != old_con_state->content_type) {
8522 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8523 		if (IS_ERR(new_crtc_state))
8524 			return PTR_ERR(new_crtc_state);
8525 
8526 		new_crtc_state->mode_changed = true;
8527 	}
8528 
8529 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8530 		struct dc_info_packet hdr_infopacket;
8531 
8532 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8533 		if (ret)
8534 			return ret;
8535 
8536 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8537 		if (IS_ERR(new_crtc_state))
8538 			return PTR_ERR(new_crtc_state);
8539 
8540 		/*
8541 		 * DC considers the stream backends changed if the
8542 		 * static metadata changes. Forcing the modeset also
8543 		 * gives a simple way for userspace to switch from
8544 		 * 8bpc to 10bpc when setting the metadata to enter
8545 		 * or exit HDR.
8546 		 *
8547 		 * Changing the static metadata after it's been
8548 		 * set is permissible, however. So only force a
8549 		 * modeset if we're entering or exiting HDR.
8550 		 */
8551 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8552 			!old_con_state->hdr_output_metadata ||
8553 			!new_con_state->hdr_output_metadata;
8554 	}
8555 
8556 	return 0;
8557 }
8558 
8559 static const struct drm_connector_helper_funcs
8560 amdgpu_dm_connector_helper_funcs = {
8561 	/*
8562 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8563 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8564 	 * are missing after user start lightdm. So we need to renew modes list.
8565 	 * in get_modes call back, not just return the modes count
8566 	 */
8567 	.get_modes = get_modes,
8568 	.mode_valid = amdgpu_dm_connector_mode_valid,
8569 	.atomic_check = amdgpu_dm_connector_atomic_check,
8570 };
8571 
8572 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8573 {
8574 
8575 }
8576 
8577 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8578 {
8579 	switch (display_color_depth) {
8580 	case COLOR_DEPTH_666:
8581 		return 6;
8582 	case COLOR_DEPTH_888:
8583 		return 8;
8584 	case COLOR_DEPTH_101010:
8585 		return 10;
8586 	case COLOR_DEPTH_121212:
8587 		return 12;
8588 	case COLOR_DEPTH_141414:
8589 		return 14;
8590 	case COLOR_DEPTH_161616:
8591 		return 16;
8592 	default:
8593 		break;
8594 	}
8595 	return 0;
8596 }
8597 
8598 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8599 					  struct drm_crtc_state *crtc_state,
8600 					  struct drm_connector_state *conn_state)
8601 {
8602 	struct drm_atomic_state *state = crtc_state->state;
8603 	struct drm_connector *connector = conn_state->connector;
8604 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8605 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8606 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8607 	struct drm_dp_mst_topology_mgr *mst_mgr;
8608 	struct drm_dp_mst_port *mst_port;
8609 	struct drm_dp_mst_topology_state *mst_state;
8610 	enum dc_color_depth color_depth;
8611 	int clock, bpp = 0;
8612 	bool is_y420 = false;
8613 
8614 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8615 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8616 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8617 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8618 		enum drm_mode_status result;
8619 
8620 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8621 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8622 			drm_dbg_driver(encoder->dev,
8623 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8624 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8625 				       drm_mode_vrefresh(adjusted_mode));
8626 			dm_new_connector_state->scaling = RMX_ASPECT;
8627 		}
8628 		return 0;
8629 	}
8630 
8631 	if (!aconnector->mst_output_port)
8632 		return 0;
8633 
8634 	mst_port = aconnector->mst_output_port;
8635 	mst_mgr = &aconnector->mst_root->mst_mgr;
8636 
8637 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8638 		return 0;
8639 
8640 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8641 	if (IS_ERR(mst_state))
8642 		return PTR_ERR(mst_state);
8643 
8644 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8645 
8646 	if (!state->duplicated) {
8647 		int max_bpc = conn_state->max_requested_bpc;
8648 
8649 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8650 			  aconnector->force_yuv420_output;
8651 		color_depth = convert_color_depth_from_display_info(connector,
8652 								    is_y420,
8653 								    max_bpc);
8654 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8655 		clock = adjusted_mode->clock;
8656 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8657 	}
8658 
8659 	dm_new_connector_state->vcpi_slots =
8660 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8661 					      dm_new_connector_state->pbn);
8662 	if (dm_new_connector_state->vcpi_slots < 0) {
8663 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8664 		return dm_new_connector_state->vcpi_slots;
8665 	}
8666 	return 0;
8667 }
8668 
8669 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8670 	.disable = dm_encoder_helper_disable,
8671 	.atomic_check = dm_encoder_helper_atomic_check
8672 };
8673 
8674 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8675 					    struct dc_state *dc_state,
8676 					    struct dsc_mst_fairness_vars *vars)
8677 {
8678 	struct dc_stream_state *stream = NULL;
8679 	struct drm_connector *connector;
8680 	struct drm_connector_state *new_con_state;
8681 	struct amdgpu_dm_connector *aconnector;
8682 	struct dm_connector_state *dm_conn_state;
8683 	int i, j, ret;
8684 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8685 
8686 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8687 
8688 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8689 			continue;
8690 
8691 		aconnector = to_amdgpu_dm_connector(connector);
8692 
8693 		if (!aconnector->mst_output_port)
8694 			continue;
8695 
8696 		if (!new_con_state || !new_con_state->crtc)
8697 			continue;
8698 
8699 		dm_conn_state = to_dm_connector_state(new_con_state);
8700 
8701 		for (j = 0; j < dc_state->stream_count; j++) {
8702 			stream = dc_state->streams[j];
8703 			if (!stream)
8704 				continue;
8705 
8706 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8707 				break;
8708 
8709 			stream = NULL;
8710 		}
8711 
8712 		if (!stream)
8713 			continue;
8714 
8715 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8716 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8717 		for (j = 0; j < dc_state->stream_count; j++) {
8718 			if (vars[j].aconnector == aconnector) {
8719 				pbn = vars[j].pbn;
8720 				break;
8721 			}
8722 		}
8723 
8724 		if (j == dc_state->stream_count || pbn_div == 0)
8725 			continue;
8726 
8727 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8728 
8729 		if (stream->timing.flags.DSC != 1) {
8730 			dm_conn_state->pbn = pbn;
8731 			dm_conn_state->vcpi_slots = slot_num;
8732 
8733 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8734 							   dm_conn_state->pbn, false);
8735 			if (ret < 0)
8736 				return ret;
8737 
8738 			continue;
8739 		}
8740 
8741 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8742 		if (vcpi < 0)
8743 			return vcpi;
8744 
8745 		dm_conn_state->pbn = pbn;
8746 		dm_conn_state->vcpi_slots = vcpi;
8747 	}
8748 	return 0;
8749 }
8750 
8751 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8752 {
8753 	switch (st) {
8754 	case SIGNAL_TYPE_HDMI_TYPE_A:
8755 		return DRM_MODE_CONNECTOR_HDMIA;
8756 	case SIGNAL_TYPE_EDP:
8757 		return DRM_MODE_CONNECTOR_eDP;
8758 	case SIGNAL_TYPE_LVDS:
8759 		return DRM_MODE_CONNECTOR_LVDS;
8760 	case SIGNAL_TYPE_RGB:
8761 		return DRM_MODE_CONNECTOR_VGA;
8762 	case SIGNAL_TYPE_DISPLAY_PORT:
8763 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8764 		/* External DP bridges have a different connector type. */
8765 		if (connector_id == CONNECTOR_ID_VGA)
8766 			return DRM_MODE_CONNECTOR_VGA;
8767 		else if (connector_id == CONNECTOR_ID_LVDS)
8768 			return DRM_MODE_CONNECTOR_LVDS;
8769 
8770 		return DRM_MODE_CONNECTOR_DisplayPort;
8771 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8772 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8773 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8774 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8775 			return DRM_MODE_CONNECTOR_DVII;
8776 
8777 		return DRM_MODE_CONNECTOR_DVID;
8778 	case SIGNAL_TYPE_VIRTUAL:
8779 		return DRM_MODE_CONNECTOR_VIRTUAL;
8780 
8781 	default:
8782 		return DRM_MODE_CONNECTOR_Unknown;
8783 	}
8784 }
8785 
8786 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8787 {
8788 	struct drm_encoder *encoder;
8789 
8790 	/* There is only one encoder per connector */
8791 	drm_connector_for_each_possible_encoder(connector, encoder)
8792 		return encoder;
8793 
8794 	return NULL;
8795 }
8796 
8797 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8798 {
8799 	struct drm_encoder *encoder;
8800 	struct amdgpu_encoder *amdgpu_encoder;
8801 
8802 	encoder = amdgpu_dm_connector_to_encoder(connector);
8803 
8804 	if (encoder == NULL)
8805 		return;
8806 
8807 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8808 
8809 	amdgpu_encoder->native_mode.clock = 0;
8810 
8811 	if (!list_empty(&connector->probed_modes)) {
8812 		struct drm_display_mode *preferred_mode = NULL;
8813 
8814 		list_for_each_entry(preferred_mode,
8815 				    &connector->probed_modes,
8816 				    head) {
8817 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8818 				amdgpu_encoder->native_mode = *preferred_mode;
8819 
8820 			break;
8821 		}
8822 
8823 	}
8824 }
8825 
8826 static struct drm_display_mode *
8827 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8828 			     const char *name,
8829 			     int hdisplay, int vdisplay)
8830 {
8831 	struct drm_device *dev = encoder->dev;
8832 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8833 	struct drm_display_mode *mode = NULL;
8834 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8835 
8836 	mode = drm_mode_duplicate(dev, native_mode);
8837 
8838 	if (mode == NULL)
8839 		return NULL;
8840 
8841 	mode->hdisplay = hdisplay;
8842 	mode->vdisplay = vdisplay;
8843 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8844 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8845 
8846 	return mode;
8847 
8848 }
8849 
8850 static const struct amdgpu_dm_mode_size {
8851 	char name[DRM_DISPLAY_MODE_LEN];
8852 	int w;
8853 	int h;
8854 } common_modes[] = {
8855 	{  "640x480",  640,  480},
8856 	{  "800x600",  800,  600},
8857 	{ "1024x768", 1024,  768},
8858 	{ "1280x720", 1280,  720},
8859 	{ "1280x800", 1280,  800},
8860 	{"1280x1024", 1280, 1024},
8861 	{ "1440x900", 1440,  900},
8862 	{"1680x1050", 1680, 1050},
8863 	{"1600x1200", 1600, 1200},
8864 	{"1920x1080", 1920, 1080},
8865 	{"1920x1200", 1920, 1200}
8866 };
8867 
8868 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8869 						 struct drm_connector *connector)
8870 {
8871 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8872 	struct drm_display_mode *mode = NULL;
8873 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8874 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8875 				to_amdgpu_dm_connector(connector);
8876 	int i;
8877 	int n;
8878 
8879 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8880 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8881 		return;
8882 
8883 	n = ARRAY_SIZE(common_modes);
8884 
8885 	for (i = 0; i < n; i++) {
8886 		struct drm_display_mode *curmode = NULL;
8887 		bool mode_existed = false;
8888 
8889 		if (common_modes[i].w > native_mode->hdisplay ||
8890 		    common_modes[i].h > native_mode->vdisplay ||
8891 		   (common_modes[i].w == native_mode->hdisplay &&
8892 		    common_modes[i].h == native_mode->vdisplay))
8893 			continue;
8894 
8895 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8896 			if (common_modes[i].w == curmode->hdisplay &&
8897 			    common_modes[i].h == curmode->vdisplay) {
8898 				mode_existed = true;
8899 				break;
8900 			}
8901 		}
8902 
8903 		if (mode_existed)
8904 			continue;
8905 
8906 		mode = amdgpu_dm_create_common_mode(encoder,
8907 				common_modes[i].name, common_modes[i].w,
8908 				common_modes[i].h);
8909 		if (!mode)
8910 			continue;
8911 
8912 		drm_mode_probed_add(connector, mode);
8913 		amdgpu_dm_connector->num_modes++;
8914 	}
8915 }
8916 
8917 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8918 {
8919 	struct drm_encoder *encoder;
8920 	struct amdgpu_encoder *amdgpu_encoder;
8921 	const struct drm_display_mode *native_mode;
8922 
8923 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8924 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8925 		return;
8926 
8927 	mutex_lock(&connector->dev->mode_config.mutex);
8928 	amdgpu_dm_connector_get_modes(connector);
8929 	mutex_unlock(&connector->dev->mode_config.mutex);
8930 
8931 	encoder = amdgpu_dm_connector_to_encoder(connector);
8932 	if (!encoder)
8933 		return;
8934 
8935 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8936 
8937 	native_mode = &amdgpu_encoder->native_mode;
8938 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8939 		return;
8940 
8941 	drm_connector_set_panel_orientation_with_quirk(connector,
8942 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8943 						       native_mode->hdisplay,
8944 						       native_mode->vdisplay);
8945 }
8946 
8947 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8948 					      const struct drm_edid *drm_edid)
8949 {
8950 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8951 			to_amdgpu_dm_connector(connector);
8952 
8953 	if (drm_edid) {
8954 		/* empty probed_modes */
8955 		INIT_LIST_HEAD(&connector->probed_modes);
8956 		amdgpu_dm_connector->num_modes =
8957 				drm_edid_connector_add_modes(connector);
8958 
8959 		/* sorting the probed modes before calling function
8960 		 * amdgpu_dm_get_native_mode() since EDID can have
8961 		 * more than one preferred mode. The modes that are
8962 		 * later in the probed mode list could be of higher
8963 		 * and preferred resolution. For example, 3840x2160
8964 		 * resolution in base EDID preferred timing and 4096x2160
8965 		 * preferred resolution in DID extension block later.
8966 		 */
8967 		drm_mode_sort(&connector->probed_modes);
8968 		amdgpu_dm_get_native_mode(connector);
8969 
8970 		/* Freesync capabilities are reset by calling
8971 		 * drm_edid_connector_add_modes() and need to be
8972 		 * restored here.
8973 		 */
8974 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
8975 	} else {
8976 		amdgpu_dm_connector->num_modes = 0;
8977 	}
8978 }
8979 
8980 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8981 			      struct drm_display_mode *mode)
8982 {
8983 	struct drm_display_mode *m;
8984 
8985 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8986 		if (drm_mode_equal(m, mode))
8987 			return true;
8988 	}
8989 
8990 	return false;
8991 }
8992 
8993 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8994 {
8995 	const struct drm_display_mode *m;
8996 	struct drm_display_mode *new_mode;
8997 	uint i;
8998 	u32 new_modes_count = 0;
8999 
9000 	/* Standard FPS values
9001 	 *
9002 	 * 23.976       - TV/NTSC
9003 	 * 24           - Cinema
9004 	 * 25           - TV/PAL
9005 	 * 29.97        - TV/NTSC
9006 	 * 30           - TV/NTSC
9007 	 * 48           - Cinema HFR
9008 	 * 50           - TV/PAL
9009 	 * 60           - Commonly used
9010 	 * 48,72,96,120 - Multiples of 24
9011 	 */
9012 	static const u32 common_rates[] = {
9013 		23976, 24000, 25000, 29970, 30000,
9014 		48000, 50000, 60000, 72000, 96000, 120000
9015 	};
9016 
9017 	/*
9018 	 * Find mode with highest refresh rate with the same resolution
9019 	 * as the preferred mode. Some monitors report a preferred mode
9020 	 * with lower resolution than the highest refresh rate supported.
9021 	 */
9022 
9023 	m = get_highest_refresh_rate_mode(aconnector, true);
9024 	if (!m)
9025 		return 0;
9026 
9027 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9028 		u64 target_vtotal, target_vtotal_diff;
9029 		u64 num, den;
9030 
9031 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9032 			continue;
9033 
9034 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9035 		    common_rates[i] > aconnector->max_vfreq * 1000)
9036 			continue;
9037 
9038 		num = (unsigned long long)m->clock * 1000 * 1000;
9039 		den = common_rates[i] * (unsigned long long)m->htotal;
9040 		target_vtotal = div_u64(num, den);
9041 		target_vtotal_diff = target_vtotal - m->vtotal;
9042 
9043 		/* Check for illegal modes */
9044 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9045 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9046 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9047 			continue;
9048 
9049 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9050 		if (!new_mode)
9051 			goto out;
9052 
9053 		new_mode->vtotal += (u16)target_vtotal_diff;
9054 		new_mode->vsync_start += (u16)target_vtotal_diff;
9055 		new_mode->vsync_end += (u16)target_vtotal_diff;
9056 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9057 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9058 
9059 		if (!is_duplicate_mode(aconnector, new_mode)) {
9060 			drm_mode_probed_add(&aconnector->base, new_mode);
9061 			new_modes_count += 1;
9062 		} else
9063 			drm_mode_destroy(aconnector->base.dev, new_mode);
9064 	}
9065  out:
9066 	return new_modes_count;
9067 }
9068 
9069 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9070 						   const struct drm_edid *drm_edid)
9071 {
9072 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9073 		to_amdgpu_dm_connector(connector);
9074 
9075 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9076 		return;
9077 
9078 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9079 		return;
9080 
9081 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9082 		return;
9083 
9084 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9085 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9086 		return;
9087 
9088 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9089 		amdgpu_dm_connector->num_modes +=
9090 			add_fs_modes(amdgpu_dm_connector);
9091 }
9092 
9093 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9094 {
9095 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9096 			to_amdgpu_dm_connector(connector);
9097 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9098 	struct drm_encoder *encoder;
9099 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9100 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9101 	const struct dc *dc = dc_link->dc;
9102 
9103 	encoder = amdgpu_dm_connector_to_encoder(connector);
9104 
9105 	if (!drm_edid) {
9106 		amdgpu_dm_connector->num_modes =
9107 				drm_add_modes_noedid(connector, 640, 480);
9108 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9109 			amdgpu_dm_connector->num_modes +=
9110 				drm_add_modes_noedid(connector, 1920, 1080);
9111 
9112 		if (amdgpu_dm_connector->dc_sink &&
9113 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9114 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9115 			/* Analog monitor connected by DAC load detection.
9116 			 * Add common modes. It will be up to the user to select one that works.
9117 			 */
9118 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9119 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9120 					connector, common_modes[i].w, common_modes[i].h);
9121 		}
9122 	} else {
9123 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9124 		if (encoder)
9125 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9126 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9127 	}
9128 	amdgpu_dm_fbc_init(connector);
9129 
9130 	return amdgpu_dm_connector->num_modes;
9131 }
9132 
9133 static const u32 supported_colorspaces =
9134 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9135 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9136 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9137 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9138 
9139 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9140 				     struct amdgpu_dm_connector *aconnector,
9141 				     int connector_type,
9142 				     struct dc_link *link,
9143 				     int link_index)
9144 {
9145 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9146 
9147 	/*
9148 	 * Some of the properties below require access to state, like bpc.
9149 	 * Allocate some default initial connector state with our reset helper.
9150 	 */
9151 	if (aconnector->base.funcs->reset)
9152 		aconnector->base.funcs->reset(&aconnector->base);
9153 
9154 	aconnector->connector_id = link_index;
9155 	aconnector->bl_idx = -1;
9156 	aconnector->dc_link = link;
9157 	aconnector->base.interlace_allowed = false;
9158 	aconnector->base.doublescan_allowed = false;
9159 	aconnector->base.stereo_allowed = false;
9160 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9161 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9162 	aconnector->audio_inst = -1;
9163 	aconnector->pack_sdp_v1_3 = false;
9164 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9165 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9166 	mutex_init(&aconnector->hpd_lock);
9167 	mutex_init(&aconnector->handle_mst_msg_ready);
9168 
9169 	/*
9170 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9171 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9172 	 */
9173 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9174 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9175 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9176 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9177 		aconnector->hdmi_prev_sink = NULL;
9178 	} else {
9179 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9180 	}
9181 
9182 	/*
9183 	 * configure support HPD hot plug connector_>polled default value is 0
9184 	 * which means HPD hot plug not supported
9185 	 */
9186 	switch (connector_type) {
9187 	case DRM_MODE_CONNECTOR_HDMIA:
9188 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9189 		aconnector->base.ycbcr_420_allowed =
9190 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9191 		break;
9192 	case DRM_MODE_CONNECTOR_DisplayPort:
9193 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9194 		link->link_enc = link_enc_cfg_get_link_enc(link);
9195 		ASSERT(link->link_enc);
9196 		if (link->link_enc)
9197 			aconnector->base.ycbcr_420_allowed =
9198 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9199 		break;
9200 	case DRM_MODE_CONNECTOR_DVID:
9201 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9202 		break;
9203 	case DRM_MODE_CONNECTOR_DVII:
9204 	case DRM_MODE_CONNECTOR_VGA:
9205 		aconnector->base.polled =
9206 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9207 		break;
9208 	default:
9209 		break;
9210 	}
9211 
9212 	drm_object_attach_property(&aconnector->base.base,
9213 				dm->ddev->mode_config.scaling_mode_property,
9214 				DRM_MODE_SCALE_NONE);
9215 
9216 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9217 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9218 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9219 
9220 	drm_object_attach_property(&aconnector->base.base,
9221 				adev->mode_info.underscan_property,
9222 				UNDERSCAN_OFF);
9223 	drm_object_attach_property(&aconnector->base.base,
9224 				adev->mode_info.underscan_hborder_property,
9225 				0);
9226 	drm_object_attach_property(&aconnector->base.base,
9227 				adev->mode_info.underscan_vborder_property,
9228 				0);
9229 
9230 	if (!aconnector->mst_root)
9231 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9232 
9233 	aconnector->base.state->max_bpc = 16;
9234 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9235 
9236 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9237 		/* Content Type is currently only implemented for HDMI. */
9238 		drm_connector_attach_content_type_property(&aconnector->base);
9239 	}
9240 
9241 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9242 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9243 			drm_connector_attach_colorspace_property(&aconnector->base);
9244 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9245 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9246 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9247 			drm_connector_attach_colorspace_property(&aconnector->base);
9248 	}
9249 
9250 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9251 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9252 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9253 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9254 
9255 		if (!aconnector->mst_root)
9256 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9257 
9258 		if (adev->dm.hdcp_workqueue)
9259 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9260 	}
9261 
9262 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9263 		struct drm_privacy_screen *privacy_screen;
9264 
9265 		drm_connector_attach_panel_type_property(&aconnector->base);
9266 
9267 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9268 		if (!IS_ERR(privacy_screen)) {
9269 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9270 								     privacy_screen);
9271 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9272 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9273 		}
9274 	}
9275 }
9276 
9277 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9278 			      struct i2c_msg *msgs, int num)
9279 {
9280 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9281 	struct ddc_service *ddc_service = i2c->ddc_service;
9282 	struct i2c_command cmd;
9283 	int i;
9284 	int result = -EIO;
9285 
9286 	if (!ddc_service->ddc_pin)
9287 		return result;
9288 
9289 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9290 
9291 	if (!cmd.payloads)
9292 		return result;
9293 
9294 	cmd.number_of_payloads = num;
9295 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9296 	cmd.speed = 100;
9297 
9298 	for (i = 0; i < num; i++) {
9299 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9300 		cmd.payloads[i].address = msgs[i].addr;
9301 		cmd.payloads[i].length = msgs[i].len;
9302 		cmd.payloads[i].data = msgs[i].buf;
9303 	}
9304 
9305 	if (i2c->oem) {
9306 		if (dc_submit_i2c_oem(
9307 			    ddc_service->ctx->dc,
9308 			    &cmd))
9309 			result = num;
9310 	} else {
9311 		if (dc_submit_i2c(
9312 			    ddc_service->ctx->dc,
9313 			    ddc_service->link->link_index,
9314 			    &cmd))
9315 			result = num;
9316 	}
9317 
9318 	kfree(cmd.payloads);
9319 	return result;
9320 }
9321 
9322 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9323 {
9324 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9325 }
9326 
9327 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9328 	.master_xfer = amdgpu_dm_i2c_xfer,
9329 	.functionality = amdgpu_dm_i2c_func,
9330 };
9331 
9332 static struct amdgpu_i2c_adapter *
9333 create_i2c(struct ddc_service *ddc_service, bool oem)
9334 {
9335 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9336 	struct amdgpu_i2c_adapter *i2c;
9337 
9338 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9339 	if (!i2c)
9340 		return NULL;
9341 	i2c->base.owner = THIS_MODULE;
9342 	i2c->base.dev.parent = &adev->pdev->dev;
9343 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9344 	if (oem)
9345 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9346 	else
9347 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9348 			 ddc_service->link->link_index);
9349 	i2c_set_adapdata(&i2c->base, i2c);
9350 	i2c->ddc_service = ddc_service;
9351 	i2c->oem = oem;
9352 
9353 	return i2c;
9354 }
9355 
9356 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9357 {
9358 	struct cec_connector_info conn_info;
9359 	struct drm_device *ddev = aconnector->base.dev;
9360 	struct device *hdmi_dev = ddev->dev;
9361 
9362 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9363 		drm_info(ddev, "HDMI-CEC feature masked\n");
9364 		return -EINVAL;
9365 	}
9366 
9367 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9368 	aconnector->notifier =
9369 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9370 	if (!aconnector->notifier) {
9371 		drm_err(ddev, "Failed to create cec notifier\n");
9372 		return -ENOMEM;
9373 	}
9374 
9375 	return 0;
9376 }
9377 
9378 /*
9379  * Note: this function assumes that dc_link_detect() was called for the
9380  * dc_link which will be represented by this aconnector.
9381  */
9382 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9383 				    struct amdgpu_dm_connector *aconnector,
9384 				    u32 link_index,
9385 				    struct amdgpu_encoder *aencoder)
9386 {
9387 	int res = 0;
9388 	int connector_type;
9389 	struct dc *dc = dm->dc;
9390 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9391 	struct amdgpu_i2c_adapter *i2c;
9392 
9393 	/* Not needed for writeback connector */
9394 	link->priv = aconnector;
9395 
9396 
9397 	i2c = create_i2c(link->ddc, false);
9398 	if (!i2c) {
9399 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9400 		return -ENOMEM;
9401 	}
9402 
9403 	aconnector->i2c = i2c;
9404 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9405 
9406 	if (res) {
9407 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9408 		goto out_free;
9409 	}
9410 
9411 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9412 
9413 	res = drm_connector_init_with_ddc(
9414 			dm->ddev,
9415 			&aconnector->base,
9416 			&amdgpu_dm_connector_funcs,
9417 			connector_type,
9418 			&i2c->base);
9419 
9420 	if (res) {
9421 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9422 		aconnector->connector_id = -1;
9423 		goto out_free;
9424 	}
9425 
9426 	drm_connector_helper_add(
9427 			&aconnector->base,
9428 			&amdgpu_dm_connector_helper_funcs);
9429 
9430 	amdgpu_dm_connector_init_helper(
9431 		dm,
9432 		aconnector,
9433 		connector_type,
9434 		link,
9435 		link_index);
9436 
9437 	drm_connector_attach_encoder(
9438 		&aconnector->base, &aencoder->base);
9439 
9440 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9441 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9442 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9443 
9444 	if (dc_is_dp_signal(link->connector_signal))
9445 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9446 
9447 out_free:
9448 	if (res) {
9449 		kfree(i2c);
9450 		aconnector->i2c = NULL;
9451 	}
9452 	return res;
9453 }
9454 
9455 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9456 {
9457 	switch (adev->mode_info.num_crtc) {
9458 	case 1:
9459 		return 0x1;
9460 	case 2:
9461 		return 0x3;
9462 	case 3:
9463 		return 0x7;
9464 	case 4:
9465 		return 0xf;
9466 	case 5:
9467 		return 0x1f;
9468 	case 6:
9469 	default:
9470 		return 0x3f;
9471 	}
9472 }
9473 
9474 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9475 				  struct amdgpu_encoder *aencoder,
9476 				  uint32_t link_index)
9477 {
9478 	struct amdgpu_device *adev = drm_to_adev(dev);
9479 
9480 	int res = drm_encoder_init(dev,
9481 				   &aencoder->base,
9482 				   &amdgpu_dm_encoder_funcs,
9483 				   DRM_MODE_ENCODER_TMDS,
9484 				   NULL);
9485 
9486 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9487 
9488 	if (!res)
9489 		aencoder->encoder_id = link_index;
9490 	else
9491 		aencoder->encoder_id = -1;
9492 
9493 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9494 
9495 	return res;
9496 }
9497 
9498 static void manage_dm_interrupts(struct amdgpu_device *adev,
9499 				 struct amdgpu_crtc *acrtc,
9500 				 struct dm_crtc_state *acrtc_state)
9501 {	/*
9502 	 * We cannot be sure that the frontend index maps to the same
9503 	 * backend index - some even map to more than one.
9504 	 * So we have to go through the CRTC to find the right IRQ.
9505 	 */
9506 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9507 			adev,
9508 			acrtc->crtc_id);
9509 	struct drm_device *dev = adev_to_drm(adev);
9510 
9511 	struct drm_vblank_crtc_config config = {0};
9512 	struct dc_crtc_timing *timing;
9513 	int offdelay;
9514 
9515 	if (acrtc_state) {
9516 		timing = &acrtc_state->stream->timing;
9517 
9518 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9519 			   IP_VERSION(3, 5, 0) ||
9520 			   !(adev->flags & AMD_IS_APU)) {
9521 			/*
9522 			 * Older HW and DGPU have issues with instant off;
9523 			 * use a 2 frame offdelay.
9524 			 */
9525 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9526 						      timing->v_total *
9527 						      timing->h_total,
9528 						      timing->pix_clk_100hz);
9529 
9530 			config.offdelay_ms = offdelay ?: 30;
9531 		} else {
9532 			/* offdelay_ms = 0 will never disable vblank */
9533 			config.offdelay_ms = 1;
9534 			config.disable_immediate = true;
9535 		}
9536 
9537 		drm_crtc_vblank_on_config(&acrtc->base,
9538 					  &config);
9539 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9540 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9541 		case IP_VERSION(3, 0, 0):
9542 		case IP_VERSION(3, 0, 2):
9543 		case IP_VERSION(3, 0, 3):
9544 		case IP_VERSION(3, 2, 0):
9545 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9546 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9547 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9548 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9549 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9550 #endif
9551 		}
9552 
9553 	} else {
9554 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9555 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9556 		case IP_VERSION(3, 0, 0):
9557 		case IP_VERSION(3, 0, 2):
9558 		case IP_VERSION(3, 0, 3):
9559 		case IP_VERSION(3, 2, 0):
9560 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9561 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9562 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9563 #endif
9564 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9565 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9566 		}
9567 
9568 		drm_crtc_vblank_off(&acrtc->base);
9569 	}
9570 }
9571 
9572 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9573 				      struct amdgpu_crtc *acrtc)
9574 {
9575 	int irq_type =
9576 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9577 
9578 	/**
9579 	 * This reads the current state for the IRQ and force reapplies
9580 	 * the setting to hardware.
9581 	 */
9582 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9583 }
9584 
9585 static bool
9586 is_scaling_state_different(const struct dm_connector_state *dm_state,
9587 			   const struct dm_connector_state *old_dm_state)
9588 {
9589 	if (dm_state->scaling != old_dm_state->scaling)
9590 		return true;
9591 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9592 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9593 			return true;
9594 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9595 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9596 			return true;
9597 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9598 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9599 		return true;
9600 	return false;
9601 }
9602 
9603 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9604 					    struct drm_crtc_state *old_crtc_state,
9605 					    struct drm_connector_state *new_conn_state,
9606 					    struct drm_connector_state *old_conn_state,
9607 					    const struct drm_connector *connector,
9608 					    struct hdcp_workqueue *hdcp_w)
9609 {
9610 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9611 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9612 
9613 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9614 		connector->index, connector->status, connector->dpms);
9615 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9616 		old_conn_state->content_protection, new_conn_state->content_protection);
9617 
9618 	if (old_crtc_state)
9619 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9620 		old_crtc_state->enable,
9621 		old_crtc_state->active,
9622 		old_crtc_state->mode_changed,
9623 		old_crtc_state->active_changed,
9624 		old_crtc_state->connectors_changed);
9625 
9626 	if (new_crtc_state)
9627 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9628 		new_crtc_state->enable,
9629 		new_crtc_state->active,
9630 		new_crtc_state->mode_changed,
9631 		new_crtc_state->active_changed,
9632 		new_crtc_state->connectors_changed);
9633 
9634 	/* hdcp content type change */
9635 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9636 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9637 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9638 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9639 		return true;
9640 	}
9641 
9642 	/* CP is being re enabled, ignore this */
9643 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9644 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9645 		if (new_crtc_state && new_crtc_state->mode_changed) {
9646 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9647 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9648 			return true;
9649 		}
9650 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9651 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9652 		return false;
9653 	}
9654 
9655 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9656 	 *
9657 	 * Handles:	UNDESIRED -> ENABLED
9658 	 */
9659 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9660 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9661 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9662 
9663 	/* Stream removed and re-enabled
9664 	 *
9665 	 * Can sometimes overlap with the HPD case,
9666 	 * thus set update_hdcp to false to avoid
9667 	 * setting HDCP multiple times.
9668 	 *
9669 	 * Handles:	DESIRED -> DESIRED (Special case)
9670 	 */
9671 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9672 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9673 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9674 		dm_con_state->update_hdcp = false;
9675 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9676 			__func__);
9677 		return true;
9678 	}
9679 
9680 	/* Hot-plug, headless s3, dpms
9681 	 *
9682 	 * Only start HDCP if the display is connected/enabled.
9683 	 * update_hdcp flag will be set to false until the next
9684 	 * HPD comes in.
9685 	 *
9686 	 * Handles:	DESIRED -> DESIRED (Special case)
9687 	 */
9688 	if (dm_con_state->update_hdcp &&
9689 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9690 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9691 		dm_con_state->update_hdcp = false;
9692 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9693 			__func__);
9694 		return true;
9695 	}
9696 
9697 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9698 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9699 			if (new_crtc_state && new_crtc_state->mode_changed) {
9700 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9701 					__func__);
9702 				return true;
9703 			}
9704 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9705 				__func__);
9706 			return false;
9707 		}
9708 
9709 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9710 		return false;
9711 	}
9712 
9713 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9714 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9715 			__func__);
9716 		return true;
9717 	}
9718 
9719 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9720 	return false;
9721 }
9722 
9723 static void remove_stream(struct amdgpu_device *adev,
9724 			  struct amdgpu_crtc *acrtc,
9725 			  struct dc_stream_state *stream)
9726 {
9727 	/* this is the update mode case */
9728 
9729 	acrtc->otg_inst = -1;
9730 	acrtc->enabled = false;
9731 }
9732 
9733 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9734 {
9735 
9736 	assert_spin_locked(&acrtc->base.dev->event_lock);
9737 	WARN_ON(acrtc->event);
9738 
9739 	acrtc->event = acrtc->base.state->event;
9740 
9741 	/* Set the flip status */
9742 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9743 
9744 	/* Mark this event as consumed */
9745 	acrtc->base.state->event = NULL;
9746 
9747 	drm_dbg_state(acrtc->base.dev,
9748 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9749 		      acrtc->crtc_id);
9750 }
9751 
9752 static void update_freesync_state_on_stream(
9753 	struct amdgpu_display_manager *dm,
9754 	struct dm_crtc_state *new_crtc_state,
9755 	struct dc_stream_state *new_stream,
9756 	struct dc_plane_state *surface,
9757 	u32 flip_timestamp_in_us)
9758 {
9759 	struct mod_vrr_params vrr_params;
9760 	struct dc_info_packet vrr_infopacket = {0};
9761 	struct amdgpu_device *adev = dm->adev;
9762 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9763 	unsigned long flags;
9764 	bool pack_sdp_v1_3 = false;
9765 	struct amdgpu_dm_connector *aconn;
9766 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9767 
9768 	if (!new_stream)
9769 		return;
9770 
9771 	/*
9772 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9773 	 * For now it's sufficient to just guard against these conditions.
9774 	 */
9775 
9776 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9777 		return;
9778 
9779 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9780 	vrr_params = acrtc->dm_irq_params.vrr_params;
9781 
9782 	if (surface) {
9783 		mod_freesync_handle_preflip(
9784 			dm->freesync_module,
9785 			surface,
9786 			new_stream,
9787 			flip_timestamp_in_us,
9788 			&vrr_params);
9789 
9790 		if (adev->family < AMDGPU_FAMILY_AI &&
9791 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9792 			mod_freesync_handle_v_update(dm->freesync_module,
9793 						     new_stream, &vrr_params);
9794 
9795 			/* Need to call this before the frame ends. */
9796 			dc_stream_adjust_vmin_vmax(dm->dc,
9797 						   new_crtc_state->stream,
9798 						   &vrr_params.adjust);
9799 		}
9800 	}
9801 
9802 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9803 
9804 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9805 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9806 
9807 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9808 			packet_type = PACKET_TYPE_FS_V1;
9809 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9810 			packet_type = PACKET_TYPE_FS_V2;
9811 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9812 			packet_type = PACKET_TYPE_FS_V3;
9813 
9814 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9815 					&new_stream->adaptive_sync_infopacket);
9816 	}
9817 
9818 	mod_freesync_build_vrr_infopacket(
9819 		dm->freesync_module,
9820 		new_stream,
9821 		&vrr_params,
9822 		packet_type,
9823 		TRANSFER_FUNC_UNKNOWN,
9824 		&vrr_infopacket,
9825 		pack_sdp_v1_3);
9826 
9827 	new_crtc_state->freesync_vrr_info_changed |=
9828 		(memcmp(&new_crtc_state->vrr_infopacket,
9829 			&vrr_infopacket,
9830 			sizeof(vrr_infopacket)) != 0);
9831 
9832 	acrtc->dm_irq_params.vrr_params = vrr_params;
9833 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9834 
9835 	new_stream->vrr_infopacket = vrr_infopacket;
9836 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9837 
9838 	if (new_crtc_state->freesync_vrr_info_changed)
9839 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9840 			      new_crtc_state->base.crtc->base.id,
9841 			      (int)new_crtc_state->base.vrr_enabled,
9842 			      (int)vrr_params.state);
9843 
9844 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9845 }
9846 
9847 static void update_stream_irq_parameters(
9848 	struct amdgpu_display_manager *dm,
9849 	struct dm_crtc_state *new_crtc_state)
9850 {
9851 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9852 	struct mod_vrr_params vrr_params;
9853 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9854 	struct amdgpu_device *adev = dm->adev;
9855 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9856 	unsigned long flags;
9857 
9858 	if (!new_stream)
9859 		return;
9860 
9861 	/*
9862 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9863 	 * For now it's sufficient to just guard against these conditions.
9864 	 */
9865 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9866 		return;
9867 
9868 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9869 	vrr_params = acrtc->dm_irq_params.vrr_params;
9870 
9871 	if (new_crtc_state->vrr_supported &&
9872 	    config.min_refresh_in_uhz &&
9873 	    config.max_refresh_in_uhz) {
9874 		/*
9875 		 * if freesync compatible mode was set, config.state will be set
9876 		 * in atomic check
9877 		 */
9878 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9879 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9880 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9881 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9882 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9883 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9884 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9885 		} else {
9886 			config.state = new_crtc_state->base.vrr_enabled ?
9887 						     VRR_STATE_ACTIVE_VARIABLE :
9888 						     VRR_STATE_INACTIVE;
9889 		}
9890 	} else {
9891 		config.state = VRR_STATE_UNSUPPORTED;
9892 	}
9893 
9894 	mod_freesync_build_vrr_params(dm->freesync_module,
9895 				      new_stream,
9896 				      &config, &vrr_params);
9897 
9898 	new_crtc_state->freesync_config = config;
9899 	/* Copy state for access from DM IRQ handler */
9900 	acrtc->dm_irq_params.freesync_config = config;
9901 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9902 	acrtc->dm_irq_params.vrr_params = vrr_params;
9903 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9904 }
9905 
9906 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
9907 					    struct dm_crtc_state *old_state,
9908 					    struct dm_crtc_state *new_state)
9909 {
9910 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9911 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9912 
9913 	if (!old_vrr_active && new_vrr_active) {
9914 		/* Transition VRR inactive -> active:
9915 		 * While VRR is active, we must not disable vblank irq, as a
9916 		 * reenable after disable would compute bogus vblank/pflip
9917 		 * timestamps if it likely happened inside display front-porch.
9918 		 *
9919 		 * We also need vupdate irq for the actual core vblank handling
9920 		 * at end of vblank.
9921 		 */
9922 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9923 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9924 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9925 				 __func__, new_state->base.crtc->base.id);
9926 
9927 		scoped_guard(mutex, &dm->dc_lock) {
9928 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
9929 				psr_event_vrr_transition, true);
9930 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
9931 				replay_event_vrr, true);
9932 		}
9933 	} else if (old_vrr_active && !new_vrr_active) {
9934 		/* Transition VRR active -> inactive:
9935 		 * Allow vblank irq disable again for fixed refresh rate.
9936 		 */
9937 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9938 		drm_crtc_vblank_put(new_state->base.crtc);
9939 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9940 				 __func__, new_state->base.crtc->base.id);
9941 
9942 		scoped_guard(mutex, &dm->dc_lock) {
9943 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
9944 				psr_event_vrr_transition, false);
9945 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
9946 				replay_event_vrr, false);
9947 		}
9948 	}
9949 }
9950 
9951 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9952 {
9953 	struct drm_plane *plane;
9954 	struct drm_plane_state *old_plane_state;
9955 	int i;
9956 
9957 	/*
9958 	 * TODO: Make this per-stream so we don't issue redundant updates for
9959 	 * commits with multiple streams.
9960 	 */
9961 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9962 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9963 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9964 }
9965 
9966 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9967 {
9968 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9969 
9970 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9971 }
9972 
9973 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9974 				    struct drm_plane_state *old_plane_state,
9975 				    struct dc_stream_update *update)
9976 {
9977 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9978 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9979 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9980 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9981 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9982 	uint64_t address = afb ? afb->address : 0;
9983 	struct dc_cursor_position position = {0};
9984 	struct dc_cursor_attributes attributes;
9985 	int ret;
9986 
9987 	if (!plane->state->fb && !old_plane_state->fb)
9988 		return;
9989 
9990 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9991 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9992 		       plane->state->crtc_h);
9993 
9994 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9995 	if (ret)
9996 		return;
9997 
9998 	if (!position.enable) {
9999 		/* turn off cursor */
10000 		if (crtc_state && crtc_state->stream) {
10001 			dc_stream_set_cursor_position(crtc_state->stream,
10002 						      &position);
10003 			update->cursor_position = &crtc_state->stream->cursor_position;
10004 		}
10005 		return;
10006 	}
10007 
10008 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10009 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10010 
10011 	memset(&attributes, 0, sizeof(attributes));
10012 	attributes.address.high_part = upper_32_bits(address);
10013 	attributes.address.low_part  = lower_32_bits(address);
10014 	attributes.width             = plane->state->crtc_w;
10015 	attributes.height            = plane->state->crtc_h;
10016 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10017 	attributes.rotation_angle    = 0;
10018 	attributes.attribute_flags.value = 0;
10019 
10020 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10021 	 * legacy gamma setup.
10022 	 */
10023 	if (crtc_state->cm_is_degamma_srgb &&
10024 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10025 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10026 
10027 	if (afb)
10028 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10029 
10030 	if (crtc_state->stream) {
10031 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10032 						     &attributes))
10033 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10034 
10035 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10036 
10037 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10038 						   &position))
10039 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10040 
10041 		update->cursor_position = &crtc_state->stream->cursor_position;
10042 	}
10043 }
10044 
10045 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10046 					  struct amdgpu_crtc *acrtc_attach,
10047 					  const struct dm_crtc_state *acrtc_state,
10048 					  const u64 current_ts)
10049 {
10050 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10051 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10052 	struct amdgpu_dm_connector *aconn =
10053 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10054 
10055 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10056 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10057 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10058 		if (aconn->sr_skip_count > 0)
10059 			aconn->sr_skip_count--;
10060 
10061 		/* Allow SR when skip count is 0. */
10062 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10063 
10064 		/*
10065 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10066 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10067 		 * can be enabled immediately once OS demonstrates an
10068 		 * adequate number of fast atomic commits to notify KMD
10069 		 * of update events.
10070 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10071 		 */
10072 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10073 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10074 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10075 				psr_event_hw_programming, false);
10076 
10077 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, true,
10078 				replay_event_general_ui, true);
10079 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10080 				replay_event_hw_programming, false);
10081 		}
10082 	} else {
10083 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10084 	}
10085 }
10086 
10087 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
10088 				    struct drm_device *dev,
10089 				    struct amdgpu_display_manager *dm,
10090 				    struct drm_crtc *pcrtc,
10091 				    bool wait_for_vblank)
10092 {
10093 	u32 i;
10094 	u64 timestamp_ns = ktime_get_ns();
10095 	struct drm_plane *plane;
10096 	struct drm_plane_state *old_plane_state, *new_plane_state;
10097 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10098 	struct drm_crtc_state *new_pcrtc_state =
10099 			drm_atomic_get_new_crtc_state(state, pcrtc);
10100 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10101 	struct dm_crtc_state *dm_old_crtc_state =
10102 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10103 	int planes_count = 0, vpos, hpos;
10104 	unsigned long flags;
10105 	u32 target_vblank, last_flip_vblank;
10106 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10107 	bool cursor_update = false;
10108 	bool pflip_present = false;
10109 	bool dirty_rects_changed = false;
10110 	bool updated_planes_and_streams = false;
10111 	struct {
10112 		struct dc_surface_update surface_updates[MAX_SURFACES];
10113 		struct dc_plane_info plane_infos[MAX_SURFACES];
10114 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10115 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10116 		struct dc_stream_update stream_update;
10117 	} *bundle;
10118 
10119 	bundle = kzalloc_obj(*bundle);
10120 
10121 	if (!bundle) {
10122 		drm_err(dev, "Failed to allocate update bundle\n");
10123 		goto cleanup;
10124 	}
10125 
10126 	/*
10127 	 * Disable the cursor first if we're disabling all the planes.
10128 	 * It'll remain on the screen after the planes are re-enabled
10129 	 * if we don't.
10130 	 *
10131 	 * If the cursor is transitioning from native to overlay mode, the
10132 	 * native cursor needs to be disabled first.
10133 	 */
10134 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10135 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10136 		struct dc_cursor_position cursor_position = {0};
10137 
10138 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10139 						   &cursor_position))
10140 			drm_err(dev, "DC failed to disable native cursor\n");
10141 
10142 		bundle->stream_update.cursor_position =
10143 				&acrtc_state->stream->cursor_position;
10144 	}
10145 
10146 	if (acrtc_state->active_planes == 0 &&
10147 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10148 		amdgpu_dm_commit_cursors(state);
10149 
10150 	/* update planes when needed */
10151 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10152 		struct drm_crtc *crtc = new_plane_state->crtc;
10153 		struct drm_crtc_state *new_crtc_state;
10154 		struct drm_framebuffer *fb = new_plane_state->fb;
10155 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10156 		bool plane_needs_flip;
10157 		struct dc_plane_state *dc_plane;
10158 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10159 
10160 		/* Cursor plane is handled after stream updates */
10161 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10162 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10163 			if ((fb && crtc == pcrtc) ||
10164 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10165 				cursor_update = true;
10166 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10167 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10168 			}
10169 
10170 			continue;
10171 		}
10172 
10173 		if (!fb || !crtc || pcrtc != crtc)
10174 			continue;
10175 
10176 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10177 		if (!new_crtc_state->active)
10178 			continue;
10179 
10180 		dc_plane = dm_new_plane_state->dc_state;
10181 		if (!dc_plane)
10182 			continue;
10183 
10184 		bundle->surface_updates[planes_count].surface = dc_plane;
10185 		if (new_pcrtc_state->color_mgmt_changed) {
10186 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10187 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10188 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10189 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10190 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10191 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10192 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10193 		}
10194 
10195 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10196 				     &bundle->scaling_infos[planes_count]);
10197 
10198 		bundle->surface_updates[planes_count].scaling_info =
10199 			&bundle->scaling_infos[planes_count];
10200 
10201 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10202 
10203 		pflip_present = pflip_present || plane_needs_flip;
10204 
10205 		if (!plane_needs_flip) {
10206 			planes_count += 1;
10207 			continue;
10208 		}
10209 
10210 		fill_dc_plane_info_and_addr(
10211 			dm->adev, new_plane_state,
10212 			afb->tiling_flags,
10213 			&bundle->plane_infos[planes_count],
10214 			&bundle->flip_addrs[planes_count].address,
10215 			afb->tmz_surface);
10216 
10217 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10218 				 new_plane_state->plane->index,
10219 				 bundle->plane_infos[planes_count].dcc.enable);
10220 
10221 		bundle->surface_updates[planes_count].plane_info =
10222 			&bundle->plane_infos[planes_count];
10223 
10224 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10225 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10226 			fill_dc_dirty_rects(plane, old_plane_state,
10227 					    new_plane_state, new_crtc_state,
10228 					    &bundle->flip_addrs[planes_count],
10229 					    acrtc_state->stream->link->psr_settings.psr_version ==
10230 					    DC_PSR_VERSION_SU_1,
10231 					    &dirty_rects_changed);
10232 
10233 			/*
10234 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10235 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10236 			 * PSR-SU will be enabled in
10237 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10238 			 * pause the video during the PSR-SU was disabled.
10239 			 */
10240 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10241 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10242 			    dirty_rects_changed) {
10243 				mutex_lock(&dm->dc_lock);
10244 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10245 				timestamp_ns;
10246 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10247 					psr_event_hw_programming, true);
10248 				mutex_unlock(&dm->dc_lock);
10249 			}
10250 		}
10251 
10252 		/*
10253 		 * Only allow immediate flips for fast updates that don't
10254 		 * change memory domain, FB pitch, DCC state, rotation or
10255 		 * mirroring.
10256 		 *
10257 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10258 		 * fast updates.
10259 		 */
10260 		if (crtc->state->async_flip &&
10261 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10262 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10263 			drm_warn_once(state->dev,
10264 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10265 				      plane->base.id, plane->name);
10266 
10267 		bundle->flip_addrs[planes_count].flip_immediate =
10268 			crtc->state->async_flip &&
10269 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10270 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10271 
10272 		timestamp_ns = ktime_get_ns();
10273 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10274 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10275 		bundle->surface_updates[planes_count].surface = dc_plane;
10276 
10277 		if (!bundle->surface_updates[planes_count].surface) {
10278 			drm_err(dev, "No surface for CRTC: id=%d\n",
10279 					acrtc_attach->crtc_id);
10280 			continue;
10281 		}
10282 
10283 		if (plane == pcrtc->primary)
10284 			update_freesync_state_on_stream(
10285 				dm,
10286 				acrtc_state,
10287 				acrtc_state->stream,
10288 				dc_plane,
10289 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10290 
10291 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10292 				 __func__,
10293 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10294 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10295 
10296 		planes_count += 1;
10297 
10298 	}
10299 
10300 	if (pflip_present) {
10301 		if (!vrr_active) {
10302 			/* Use old throttling in non-vrr fixed refresh rate mode
10303 			 * to keep flip scheduling based on target vblank counts
10304 			 * working in a backwards compatible way, e.g., for
10305 			 * clients using the GLX_OML_sync_control extension or
10306 			 * DRI3/Present extension with defined target_msc.
10307 			 */
10308 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10309 		} else {
10310 			/* For variable refresh rate mode only:
10311 			 * Get vblank of last completed flip to avoid > 1 vrr
10312 			 * flips per video frame by use of throttling, but allow
10313 			 * flip programming anywhere in the possibly large
10314 			 * variable vrr vblank interval for fine-grained flip
10315 			 * timing control and more opportunity to avoid stutter
10316 			 * on late submission of flips.
10317 			 */
10318 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10319 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10320 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10321 		}
10322 
10323 		target_vblank = last_flip_vblank + wait_for_vblank;
10324 
10325 		/*
10326 		 * Wait until we're out of the vertical blank period before the one
10327 		 * targeted by the flip
10328 		 */
10329 		while ((acrtc_attach->enabled &&
10330 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10331 							    0, &vpos, &hpos, NULL,
10332 							    NULL, &pcrtc->hwmode)
10333 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10334 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10335 			(int)(target_vblank -
10336 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10337 			usleep_range(1000, 1100);
10338 		}
10339 
10340 		/**
10341 		 * Prepare the flip event for the pageflip interrupt to handle.
10342 		 *
10343 		 * This only works in the case where we've already turned on the
10344 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10345 		 * from 0 -> n planes we have to skip a hardware generated event
10346 		 * and rely on sending it from software.
10347 		 */
10348 		if (acrtc_attach->base.state->event &&
10349 		    acrtc_state->active_planes > 0) {
10350 			drm_crtc_vblank_get(pcrtc);
10351 
10352 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10353 
10354 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10355 			prepare_flip_isr(acrtc_attach);
10356 
10357 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10358 		}
10359 
10360 		if (acrtc_state->stream) {
10361 			if (acrtc_state->freesync_vrr_info_changed)
10362 				bundle->stream_update.vrr_infopacket =
10363 					&acrtc_state->stream->vrr_infopacket;
10364 		}
10365 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10366 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10367 		if (acrtc_attach->base.state->event) {
10368 			drm_crtc_vblank_get(pcrtc);
10369 			acrtc_attach->event = acrtc_attach->base.state->event;
10370 			acrtc_attach->base.state->event = NULL;
10371 		}
10372 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10373 	}
10374 
10375 	/* Update the planes if changed or disable if we don't have any. */
10376 	if ((planes_count || acrtc_state->active_planes == 0) &&
10377 		acrtc_state->stream) {
10378 		/*
10379 		 * If PSR or idle optimizations are enabled then flush out
10380 		 * any pending work before hardware programming.
10381 		 */
10382 		if (dm->vblank_control_workqueue)
10383 			flush_workqueue(dm->vblank_control_workqueue);
10384 
10385 		bundle->stream_update.stream = acrtc_state->stream;
10386 		if (new_pcrtc_state->mode_changed) {
10387 			bundle->stream_update.src = acrtc_state->stream->src;
10388 			bundle->stream_update.dst = acrtc_state->stream->dst;
10389 		}
10390 
10391 		if (new_pcrtc_state->color_mgmt_changed) {
10392 			/*
10393 			 * TODO: This isn't fully correct since we've actually
10394 			 * already modified the stream in place.
10395 			 */
10396 			bundle->stream_update.gamut_remap =
10397 				&acrtc_state->stream->gamut_remap_matrix;
10398 			bundle->stream_update.output_csc_transform =
10399 				&acrtc_state->stream->csc_color_matrix;
10400 			bundle->stream_update.out_transfer_func =
10401 				&acrtc_state->stream->out_transfer_func;
10402 			bundle->stream_update.lut3d_func =
10403 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10404 			bundle->stream_update.func_shaper =
10405 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10406 		}
10407 
10408 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10409 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10410 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10411 
10412 		/*
10413 		 * If FreeSync state on the stream has changed then we need to
10414 		 * re-adjust the min/max bounds now that DC doesn't handle this
10415 		 * as part of commit.
10416 		 */
10417 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10418 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10419 			dc_stream_adjust_vmin_vmax(
10420 				dm->dc, acrtc_state->stream,
10421 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10422 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10423 		}
10424 		mutex_lock(&dm->dc_lock);
10425 		update_planes_and_stream_adapter(dm->dc,
10426 					 acrtc_state->update_type,
10427 					 planes_count,
10428 					 acrtc_state->stream,
10429 					 &bundle->stream_update,
10430 					 bundle->surface_updates);
10431 		updated_planes_and_streams = true;
10432 
10433 		/**
10434 		 * Enable or disable the interrupts on the backend.
10435 		 *
10436 		 * Most pipes are put into power gating when unused.
10437 		 *
10438 		 * When power gating is enabled on a pipe we lose the
10439 		 * interrupt enablement state when power gating is disabled.
10440 		 *
10441 		 * So we need to update the IRQ control state in hardware
10442 		 * whenever the pipe turns on (since it could be previously
10443 		 * power gated) or off (since some pipes can't be power gated
10444 		 * on some ASICs).
10445 		 */
10446 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10447 			dm_update_pflip_irq_state(drm_to_adev(dev),
10448 						  acrtc_attach);
10449 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10450 					      timestamp_ns);
10451 		mutex_unlock(&dm->dc_lock);
10452 	}
10453 
10454 	/*
10455 	 * Update cursor state *after* programming all the planes.
10456 	 * This avoids redundant programming in the case where we're going
10457 	 * to be disabling a single plane - those pipes are being disabled.
10458 	 */
10459 	if (acrtc_state->active_planes &&
10460 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10461 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10462 		amdgpu_dm_commit_cursors(state);
10463 
10464 cleanup:
10465 	kfree(bundle);
10466 }
10467 
10468 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10469 				   struct drm_atomic_state *state)
10470 {
10471 	struct amdgpu_device *adev = drm_to_adev(dev);
10472 	struct amdgpu_dm_connector *aconnector;
10473 	struct drm_connector *connector;
10474 	struct drm_connector_state *old_con_state, *new_con_state;
10475 	struct drm_crtc_state *new_crtc_state;
10476 	struct dm_crtc_state *new_dm_crtc_state;
10477 	const struct dc_stream_status *status;
10478 	int i, inst;
10479 
10480 	/* Notify device removals. */
10481 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10482 		if (old_con_state->crtc != new_con_state->crtc) {
10483 			/* CRTC changes require notification. */
10484 			goto notify;
10485 		}
10486 
10487 		if (!new_con_state->crtc)
10488 			continue;
10489 
10490 		new_crtc_state = drm_atomic_get_new_crtc_state(
10491 			state, new_con_state->crtc);
10492 
10493 		if (!new_crtc_state)
10494 			continue;
10495 
10496 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10497 			continue;
10498 
10499 notify:
10500 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10501 			continue;
10502 
10503 		aconnector = to_amdgpu_dm_connector(connector);
10504 
10505 		mutex_lock(&adev->dm.audio_lock);
10506 		inst = aconnector->audio_inst;
10507 		aconnector->audio_inst = -1;
10508 		mutex_unlock(&adev->dm.audio_lock);
10509 
10510 		amdgpu_dm_audio_eld_notify(adev, inst);
10511 	}
10512 
10513 	/* Notify audio device additions. */
10514 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10515 		if (!new_con_state->crtc)
10516 			continue;
10517 
10518 		new_crtc_state = drm_atomic_get_new_crtc_state(
10519 			state, new_con_state->crtc);
10520 
10521 		if (!new_crtc_state)
10522 			continue;
10523 
10524 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10525 			continue;
10526 
10527 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10528 		if (!new_dm_crtc_state->stream)
10529 			continue;
10530 
10531 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10532 		if (!status)
10533 			continue;
10534 
10535 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10536 			continue;
10537 
10538 		aconnector = to_amdgpu_dm_connector(connector);
10539 
10540 		mutex_lock(&adev->dm.audio_lock);
10541 		inst = status->audio_inst;
10542 		aconnector->audio_inst = inst;
10543 		mutex_unlock(&adev->dm.audio_lock);
10544 
10545 		amdgpu_dm_audio_eld_notify(adev, inst);
10546 	}
10547 }
10548 
10549 /*
10550  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10551  * @crtc_state: the DRM CRTC state
10552  * @stream_state: the DC stream state.
10553  *
10554  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10555  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10556  */
10557 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10558 						struct dc_stream_state *stream_state)
10559 {
10560 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10561 }
10562 
10563 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10564 			      struct dm_crtc_state *crtc_state)
10565 {
10566 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10567 }
10568 
10569 /**
10570  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10571  * @state: the drm atomic state
10572  * @dm: the display manager to update mod_power on
10573  *
10574  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10575  * in preparation for hardware programming. See also
10576  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10577  */
10578 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_state *state,
10579 					       struct amdgpu_display_manager *dm)
10580 {
10581 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10582 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10583 	struct amdgpu_dm_connector *aconnector;
10584 	struct drm_crtc *crtc;
10585 	int i = 0;
10586 
10587 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10588 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10589 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10590 
10591 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10592 			continue;
10593 
10594 		/*
10595 		 * Update mod_power on modeset event in preparation for hw
10596 		 * programming. Always use the old stream, since it would have
10597 		 * been previously added to mod_power. If old stream is null (on
10598 		 * crtc enable, for example), mod_power will no-op, which is the
10599 		 * desried behavior.
10600 		 */
10601 		if (old_crtc_state->active) {
10602 			scoped_guard(mutex, &dm->dc_lock) {
10603 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10604 					psr_event_hw_programming, true);
10605 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10606 					replay_event_hw_programming, true);
10607 			}
10608 		}
10609 
10610 		if (new_crtc_state->active) {
10611 			aconnector = (struct amdgpu_dm_connector *)
10612 				dm_new_crtc_state->stream->dm_stream_context;
10613 			if (old_crtc_state->active) {
10614 				mod_power_replace_stream(dm->power_module,
10615 					dm_old_crtc_state->stream,
10616 					dm_new_crtc_state->stream,
10617 					&aconnector->psr_caps);
10618 			} else {
10619 				mod_power_add_stream(dm->power_module,
10620 					dm_new_crtc_state->stream,
10621 					&aconnector->psr_caps);
10622 			}
10623 		} else if (old_crtc_state->active) {
10624 			mod_power_remove_stream(dm->power_module,
10625 				dm_old_crtc_state->stream);
10626 		}
10627 	}
10628 }
10629 
10630 /**
10631  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10632  * @state: the drm atomic state
10633  * @dm: the display manager to update mod_power on
10634  *
10635  * Notify mod_power of mode_change. This needs to be done after dc_stream
10636  * updates have been committed, and VRR parameters have been updated.
10637  */
10638 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_state *state,
10639 					      struct amdgpu_display_manager *dm)
10640 {
10641 	struct dm_crtc_state *dm_new_crtc_state;
10642 	struct drm_crtc_state *new_crtc_state;
10643 	struct amdgpu_crtc *acrtc;
10644 	struct drm_crtc *crtc;
10645 	int i = 0;
10646 
10647 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10648 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10649 		acrtc = to_amdgpu_crtc(crtc);
10650 
10651 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10652 			continue;
10653 
10654 		if (new_crtc_state->active) {
10655 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10656 					&acrtc->dm_irq_params.vrr_params);
10657 			mod_power_notify_mode_change(dm->power_module,
10658 						dm_new_crtc_state->stream,
10659 						false);
10660 		}
10661 	}
10662 
10663 }
10664 
10665 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10666 					struct dc_state *dc_state)
10667 {
10668 	struct drm_device *dev = state->dev;
10669 	struct amdgpu_device *adev = drm_to_adev(dev);
10670 	struct amdgpu_display_manager *dm = &adev->dm;
10671 	struct drm_crtc *crtc;
10672 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10673 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10674 	struct drm_connector_state *old_con_state;
10675 	struct drm_connector *connector;
10676 	bool mode_set_reset_required = false;
10677 	u32 i;
10678 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10679 	bool set_backlight_level = false;
10680 
10681 	/* Disable writeback */
10682 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10683 		struct dm_connector_state *dm_old_con_state;
10684 		struct amdgpu_crtc *acrtc;
10685 
10686 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10687 			continue;
10688 
10689 		old_crtc_state = NULL;
10690 
10691 		dm_old_con_state = to_dm_connector_state(old_con_state);
10692 		if (!dm_old_con_state->base.crtc)
10693 			continue;
10694 
10695 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10696 		if (acrtc)
10697 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10698 
10699 		if (!acrtc || !acrtc->wb_enabled)
10700 			continue;
10701 
10702 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10703 
10704 		dm_clear_writeback(dm, dm_old_crtc_state);
10705 		acrtc->wb_enabled = false;
10706 	}
10707 
10708 	amdgpu_dm_mod_power_update_streams(state, dm);
10709 
10710 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10711 				      new_crtc_state, i) {
10712 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10713 
10714 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10715 
10716 		if (old_crtc_state->active &&
10717 		    (!new_crtc_state->active ||
10718 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10719 			manage_dm_interrupts(adev, acrtc, NULL);
10720 			dc_stream_release(dm_old_crtc_state->stream);
10721 		}
10722 	}
10723 
10724 	drm_atomic_helper_calc_timestamping_constants(state);
10725 
10726 	/* update changed items */
10727 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10728 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10729 
10730 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10731 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10732 
10733 		drm_dbg_state(state->dev,
10734 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10735 			acrtc->crtc_id,
10736 			new_crtc_state->enable,
10737 			new_crtc_state->active,
10738 			new_crtc_state->planes_changed,
10739 			new_crtc_state->mode_changed,
10740 			new_crtc_state->active_changed,
10741 			new_crtc_state->connectors_changed);
10742 
10743 		/* Disable cursor if disabling crtc */
10744 		if (old_crtc_state->active && !new_crtc_state->active) {
10745 			struct dc_cursor_position position;
10746 
10747 			memset(&position, 0, sizeof(position));
10748 			mutex_lock(&dm->dc_lock);
10749 			dc_exit_ips_for_hw_access(dm->dc);
10750 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10751 			mutex_unlock(&dm->dc_lock);
10752 		}
10753 
10754 		/* Copy all transient state flags into dc state */
10755 		if (dm_new_crtc_state->stream) {
10756 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10757 							    dm_new_crtc_state->stream);
10758 		}
10759 
10760 		/* handles headless hotplug case, updating new_state and
10761 		 * aconnector as needed
10762 		 */
10763 
10764 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10765 
10766 			drm_dbg_atomic(dev,
10767 				       "Atomic commit: SET crtc id %d: [%p]\n",
10768 				       acrtc->crtc_id, acrtc);
10769 
10770 			if (!dm_new_crtc_state->stream) {
10771 				/*
10772 				 * this could happen because of issues with
10773 				 * userspace notifications delivery.
10774 				 * In this case userspace tries to set mode on
10775 				 * display which is disconnected in fact.
10776 				 * dc_sink is NULL in this case on aconnector.
10777 				 * We expect reset mode will come soon.
10778 				 *
10779 				 * This can also happen when unplug is done
10780 				 * during resume sequence ended
10781 				 *
10782 				 * In this case, we want to pretend we still
10783 				 * have a sink to keep the pipe running so that
10784 				 * hw state is consistent with the sw state
10785 				 */
10786 				drm_dbg_atomic(dev,
10787 					       "Failed to create new stream for crtc %d\n",
10788 						acrtc->base.base.id);
10789 				continue;
10790 			}
10791 
10792 			if (dm_old_crtc_state->stream)
10793 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10794 
10795 			pm_runtime_get_noresume(dev->dev);
10796 
10797 			acrtc->enabled = true;
10798 			acrtc->hw_mode = new_crtc_state->mode;
10799 			crtc->hwmode = new_crtc_state->mode;
10800 			mode_set_reset_required = true;
10801 			set_backlight_level = true;
10802 		} else if (modereset_required(new_crtc_state)) {
10803 			drm_dbg_atomic(dev,
10804 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10805 				       acrtc->crtc_id, acrtc);
10806 			/* i.e. reset mode */
10807 			if (dm_old_crtc_state->stream)
10808 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10809 
10810 			mode_set_reset_required = true;
10811 		}
10812 	} /* for_each_crtc_in_state() */
10813 
10814 	/* if there mode set or reset, flush vblank work queue */
10815 	if (mode_set_reset_required) {
10816 		if (dm->vblank_control_workqueue)
10817 			flush_workqueue(dm->vblank_control_workqueue);
10818 	}
10819 
10820 	dm_enable_per_frame_crtc_master_sync(dc_state);
10821 	mutex_lock(&dm->dc_lock);
10822 	dc_exit_ips_for_hw_access(dm->dc);
10823 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10824 
10825 	/* Allow idle optimization when vblank count is 0 for display off */
10826 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10827 		dc_allow_idle_optimizations(dm->dc, true);
10828 	mutex_unlock(&dm->dc_lock);
10829 
10830 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10831 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10832 
10833 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10834 
10835 		if (dm_new_crtc_state->stream != NULL) {
10836 			const struct dc_stream_status *status =
10837 					dc_stream_get_status(dm_new_crtc_state->stream);
10838 
10839 			if (!status)
10840 				status = dc_state_get_stream_status(dc_state,
10841 									 dm_new_crtc_state->stream);
10842 			if (!status)
10843 				drm_err(dev,
10844 					"got no status for stream %p on acrtc%p\n",
10845 					dm_new_crtc_state->stream, acrtc);
10846 			else
10847 				acrtc->otg_inst = status->primary_otg_inst;
10848 		}
10849 	}
10850 
10851 	/* During boot up and resume the DC layer will reset the panel brightness
10852 	 * to fix a flicker issue.
10853 	 * It will cause the dm->actual_brightness is not the current panel brightness
10854 	 * level. (the dm->brightness is the correct panel level)
10855 	 * So we set the backlight level with dm->brightness value after set mode
10856 	 */
10857 	if (set_backlight_level) {
10858 		for (i = 0; i < dm->num_of_edps; i++) {
10859 			if (dm->backlight_dev[i])
10860 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10861 		}
10862 	}
10863 }
10864 
10865 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10866 			      struct dm_crtc_state *crtc_state,
10867 			      struct drm_connector *connector,
10868 			      struct drm_connector_state *new_con_state)
10869 {
10870 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10871 	struct amdgpu_device *adev = dm->adev;
10872 	struct amdgpu_crtc *acrtc;
10873 	struct dc_writeback_info *wb_info;
10874 	struct pipe_ctx *pipe = NULL;
10875 	struct amdgpu_framebuffer *afb;
10876 	int i = 0;
10877 
10878 	wb_info = kzalloc_obj(*wb_info);
10879 	if (!wb_info) {
10880 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10881 		return;
10882 	}
10883 
10884 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10885 	if (!acrtc) {
10886 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10887 		kfree(wb_info);
10888 		return;
10889 	}
10890 
10891 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10892 	if (!afb) {
10893 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10894 		kfree(wb_info);
10895 		return;
10896 	}
10897 
10898 	for (i = 0; i < MAX_PIPES; i++) {
10899 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10900 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10901 			break;
10902 		}
10903 	}
10904 
10905 	/* fill in wb_info */
10906 	wb_info->wb_enabled = true;
10907 
10908 	wb_info->dwb_pipe_inst = 0;
10909 	wb_info->dwb_params.dwbscl_black_color = 0;
10910 	wb_info->dwb_params.hdr_mult = 0x1F000;
10911 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10912 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10913 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10914 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10915 
10916 	/* width & height from crtc */
10917 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10918 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10919 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10920 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10921 
10922 	wb_info->dwb_params.cnv_params.crop_en = false;
10923 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10924 
10925 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10926 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10927 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10928 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10929 
10930 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10931 
10932 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10933 
10934 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10935 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10936 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10937 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10938 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10939 
10940 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10941 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10942 
10943 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10944 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10945 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10946 	}
10947 
10948 	wb_info->mcif_buf_params.p_vmid = 1;
10949 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10950 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10951 		wb_info->mcif_warmup_params.region_size =
10952 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10953 	}
10954 	wb_info->mcif_warmup_params.p_vmid = 1;
10955 	wb_info->writeback_source_plane = pipe->plane_state;
10956 
10957 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10958 
10959 	acrtc->wb_pending = true;
10960 	acrtc->wb_conn = wb_conn;
10961 	drm_writeback_queue_job(wb_conn, new_con_state);
10962 }
10963 
10964 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10965 {
10966 	struct drm_connector_state *old_con_state, *new_con_state;
10967 	struct drm_device *dev = state->dev;
10968 	struct drm_connector *connector;
10969 	struct amdgpu_device *adev = drm_to_adev(dev);
10970 	int i;
10971 
10972 	if (!adev->dm.hdcp_workqueue)
10973 		return;
10974 
10975 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10976 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10977 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10978 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10979 		struct dm_crtc_state *dm_new_crtc_state;
10980 		struct amdgpu_dm_connector *aconnector;
10981 
10982 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10983 			continue;
10984 
10985 		aconnector = to_amdgpu_dm_connector(connector);
10986 
10987 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10988 
10989 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10990 			connector->index, connector->status, connector->dpms);
10991 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10992 			old_con_state->content_protection, new_con_state->content_protection);
10993 
10994 		if (aconnector->dc_sink) {
10995 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10996 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10997 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10998 				aconnector->dc_sink->edid_caps.display_name);
10999 			}
11000 		}
11001 
11002 		new_crtc_state = NULL;
11003 		old_crtc_state = NULL;
11004 
11005 		if (acrtc) {
11006 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11007 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11008 		}
11009 
11010 		if (old_crtc_state)
11011 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11012 			old_crtc_state->enable,
11013 			old_crtc_state->active,
11014 			old_crtc_state->mode_changed,
11015 			old_crtc_state->active_changed,
11016 			old_crtc_state->connectors_changed);
11017 
11018 		if (new_crtc_state)
11019 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11020 			new_crtc_state->enable,
11021 			new_crtc_state->active,
11022 			new_crtc_state->mode_changed,
11023 			new_crtc_state->active_changed,
11024 			new_crtc_state->connectors_changed);
11025 
11026 
11027 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11028 
11029 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11030 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11031 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11032 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11033 			dm_new_con_state->update_hdcp = true;
11034 			continue;
11035 		}
11036 
11037 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11038 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11039 			/* when display is unplugged from mst hub, connctor will
11040 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11041 			 * hdcp perperties, like type, undesired, desired, enabled,
11042 			 * will be lost. So, save hdcp properties into hdcp_work within
11043 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11044 			 * plugged back with same display index, its hdcp properties
11045 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11046 			 */
11047 
11048 			bool enable_encryption = false;
11049 
11050 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11051 				enable_encryption = true;
11052 
11053 			if (aconnector->dc_link && aconnector->dc_sink &&
11054 				aconnector->dc_link->type == dc_connection_mst_branch) {
11055 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11056 				struct hdcp_workqueue *hdcp_w =
11057 					&hdcp_work[aconnector->dc_link->link_index];
11058 
11059 				hdcp_w->hdcp_content_type[connector->index] =
11060 					new_con_state->hdcp_content_type;
11061 				hdcp_w->content_protection[connector->index] =
11062 					new_con_state->content_protection;
11063 			}
11064 
11065 			if (new_crtc_state && new_crtc_state->mode_changed &&
11066 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11067 				enable_encryption = true;
11068 
11069 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11070 
11071 			if (aconnector->dc_link)
11072 				hdcp_update_display(
11073 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11074 					new_con_state->hdcp_content_type, enable_encryption);
11075 		}
11076 	}
11077 }
11078 
11079 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
11080 {
11081 	struct drm_crtc *crtc;
11082 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11083 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11084 	int i, ret;
11085 
11086 	ret = drm_dp_mst_atomic_setup_commit(state);
11087 	if (ret)
11088 		return ret;
11089 
11090 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11091 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11092 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11093 		/*
11094 		 * Color management settings. We also update color properties
11095 		 * when a modeset is needed, to ensure it gets reprogrammed.
11096 		 */
11097 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11098 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11099 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11100 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11101 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11102 			if (ret) {
11103 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11104 				return ret;
11105 			}
11106 		}
11107 	}
11108 
11109 	return 0;
11110 }
11111 
11112 /**
11113  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11114  * @state: The atomic state to commit
11115  *
11116  * This will tell DC to commit the constructed DC state from atomic_check,
11117  * programming the hardware. Any failures here implies a hardware failure, since
11118  * atomic check should have filtered anything non-kosher.
11119  */
11120 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
11121 {
11122 	struct drm_device *dev = state->dev;
11123 	struct amdgpu_device *adev = drm_to_adev(dev);
11124 	struct amdgpu_display_manager *dm = &adev->dm;
11125 	struct dm_atomic_state *dm_state;
11126 	struct dc_state *dc_state = NULL;
11127 	u32 i, j;
11128 	struct drm_crtc *crtc;
11129 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11130 	unsigned long flags;
11131 	bool wait_for_vblank = true;
11132 	struct drm_connector *connector;
11133 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11134 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11135 	int crtc_disable_count = 0;
11136 
11137 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11138 
11139 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11140 	drm_dp_mst_atomic_wait_for_dependencies(state);
11141 
11142 	dm_state = dm_atomic_get_new_state(state);
11143 	if (dm_state && dm_state->context) {
11144 		dc_state = dm_state->context;
11145 		amdgpu_dm_commit_streams(state, dc_state);
11146 	}
11147 
11148 	amdgpu_dm_update_hdcp(state);
11149 
11150 	/* Handle connector state changes */
11151 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11152 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11153 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11154 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11155 		struct dc_surface_update *dummy_updates;
11156 		struct dc_stream_update stream_update;
11157 		struct dc_info_packet hdr_packet;
11158 		struct dc_stream_status *status = NULL;
11159 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11160 
11161 		memset(&stream_update, 0, sizeof(stream_update));
11162 
11163 		if (acrtc) {
11164 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11165 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11166 		}
11167 
11168 		/* Skip any modesets/resets */
11169 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11170 			continue;
11171 
11172 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11173 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11174 
11175 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11176 							     dm_old_con_state);
11177 
11178 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11179 			(dm_old_crtc_state->stream->output_color_space !=
11180 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11181 			output_color_space_changed = true;
11182 
11183 		abm_changed = dm_new_crtc_state->abm_level !=
11184 			      dm_old_crtc_state->abm_level;
11185 
11186 		hdr_changed =
11187 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11188 
11189 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11190 			continue;
11191 
11192 		stream_update.stream = dm_new_crtc_state->stream;
11193 		if (scaling_changed) {
11194 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11195 					dm_new_con_state, dm_new_crtc_state->stream);
11196 
11197 			stream_update.src = dm_new_crtc_state->stream->src;
11198 			stream_update.dst = dm_new_crtc_state->stream->dst;
11199 		}
11200 
11201 		if (output_color_space_changed) {
11202 			dm_new_crtc_state->stream->output_color_space
11203 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11204 
11205 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11206 		}
11207 
11208 		if (abm_changed) {
11209 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11210 
11211 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11212 		}
11213 
11214 		if (hdr_changed) {
11215 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11216 			stream_update.hdr_static_metadata = &hdr_packet;
11217 		}
11218 
11219 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11220 
11221 		if (WARN_ON(!status))
11222 			continue;
11223 
11224 		WARN_ON(!status->plane_count);
11225 
11226 		/*
11227 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11228 		 * Here we create an empty update on each plane.
11229 		 * To fix this, DC should permit updating only stream properties.
11230 		 */
11231 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11232 		if (!dummy_updates) {
11233 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11234 			continue;
11235 		}
11236 		for (j = 0; j < status->plane_count; j++)
11237 			dummy_updates[j].surface = status->plane_states[j];
11238 
11239 		sort(dummy_updates, status->plane_count,
11240 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11241 
11242 		mutex_lock(&dm->dc_lock);
11243 		dc_exit_ips_for_hw_access(dm->dc);
11244 		dc_update_planes_and_stream(dm->dc,
11245 					    dummy_updates,
11246 					    status->plane_count,
11247 					    dm_new_crtc_state->stream,
11248 					    &stream_update);
11249 		mutex_unlock(&dm->dc_lock);
11250 		kfree(dummy_updates);
11251 
11252 		drm_connector_update_privacy_screen(new_con_state);
11253 	}
11254 
11255 	/**
11256 	 * Enable interrupts for CRTCs that are newly enabled or went through
11257 	 * a modeset. It was intentionally deferred until after the front end
11258 	 * state was modified to wait until the OTG was on and so the IRQ
11259 	 * handlers didn't access stale or invalid state.
11260 	 */
11261 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11262 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11263 #ifdef CONFIG_DEBUG_FS
11264 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11265 #endif
11266 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11267 		if (old_crtc_state->active && !new_crtc_state->active)
11268 			crtc_disable_count++;
11269 
11270 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11271 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11272 
11273 		/* For freesync config update on crtc state and params for irq */
11274 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11275 
11276 #ifdef CONFIG_DEBUG_FS
11277 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11278 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11279 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11280 #endif
11281 
11282 		if (new_crtc_state->active &&
11283 		    (!old_crtc_state->active ||
11284 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11285 			dc_stream_retain(dm_new_crtc_state->stream);
11286 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11287 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11288 		}
11289 		/* Handle vrr on->off / off->on transitions */
11290 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11291 
11292 #ifdef CONFIG_DEBUG_FS
11293 		if (new_crtc_state->active &&
11294 		    (!old_crtc_state->active ||
11295 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11296 			/**
11297 			 * Frontend may have changed so reapply the CRC capture
11298 			 * settings for the stream.
11299 			 */
11300 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11301 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11302 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11303 					uint8_t cnt;
11304 
11305 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11306 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11307 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11308 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11309 
11310 							/**
11311 							 * It takes 2 frames for HW to stably generate CRC when
11312 							 * resuming from suspend, so we set skip_frame_cnt 2.
11313 							 */
11314 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11315 						}
11316 					}
11317 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11318 				}
11319 #endif
11320 				if (amdgpu_dm_crtc_configure_crc_source(
11321 					crtc, dm_new_crtc_state, cur_crc_src))
11322 					drm_dbg_atomic(dev, "Failed to configure crc source");
11323 			}
11324 		}
11325 #endif
11326 	}
11327 
11328 	amdgpu_dm_mod_power_setup_streams(state, dm);
11329 
11330 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11331 		if (new_crtc_state->async_flip)
11332 			wait_for_vblank = false;
11333 
11334 	/* update planes when needed per crtc*/
11335 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11336 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11337 
11338 		if (dm_new_crtc_state->stream)
11339 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11340 	}
11341 
11342 	/* Enable writeback */
11343 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11344 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11345 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11346 
11347 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11348 			continue;
11349 
11350 		if (!new_con_state->writeback_job)
11351 			continue;
11352 
11353 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11354 
11355 		if (!new_crtc_state)
11356 			continue;
11357 
11358 		if (acrtc->wb_enabled)
11359 			continue;
11360 
11361 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11362 
11363 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11364 		acrtc->wb_enabled = true;
11365 	}
11366 
11367 	/* Update audio instances for each connector. */
11368 	amdgpu_dm_commit_audio(dev, state);
11369 
11370 	/* restore the backlight level */
11371 	for (i = 0; i < dm->num_of_edps; i++) {
11372 		if (dm->backlight_dev[i] &&
11373 		    (dm->actual_brightness[i] != dm->brightness[i]))
11374 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11375 	}
11376 
11377 	/*
11378 	 * send vblank event on all events not handled in flip and
11379 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11380 	 */
11381 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11382 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11383 
11384 		if (new_crtc_state->event)
11385 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11386 
11387 		new_crtc_state->event = NULL;
11388 	}
11389 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11390 
11391 	/* Signal HW programming completion */
11392 	drm_atomic_helper_commit_hw_done(state);
11393 
11394 	if (wait_for_vblank)
11395 		drm_atomic_helper_wait_for_flip_done(dev, state);
11396 
11397 	drm_atomic_helper_cleanup_planes(dev, state);
11398 
11399 	/* Don't free the memory if we are hitting this as part of suspend.
11400 	 * This way we don't free any memory during suspend; see
11401 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11402 	 * non-suspend modeset or when the driver is torn down.
11403 	 */
11404 	if (!adev->in_suspend) {
11405 		/* return the stolen vga memory back to VRAM */
11406 		if (!adev->mman.keep_stolen_vga_memory)
11407 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11408 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11409 	}
11410 
11411 	/*
11412 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11413 	 * so we can put the GPU into runtime suspend if we're not driving any
11414 	 * displays anymore
11415 	 */
11416 	for (i = 0; i < crtc_disable_count; i++)
11417 		pm_runtime_put_autosuspend(dev->dev);
11418 	pm_runtime_mark_last_busy(dev->dev);
11419 
11420 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11421 }
11422 
11423 static int dm_force_atomic_commit(struct drm_connector *connector)
11424 {
11425 	int ret = 0;
11426 	struct drm_device *ddev = connector->dev;
11427 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11428 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11429 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11430 	struct drm_connector_state *conn_state;
11431 	struct drm_crtc_state *crtc_state;
11432 	struct drm_plane_state *plane_state;
11433 
11434 	if (!state)
11435 		return -ENOMEM;
11436 
11437 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11438 
11439 	/* Construct an atomic state to restore previous display setting */
11440 
11441 	/*
11442 	 * Attach connectors to drm_atomic_state
11443 	 */
11444 	conn_state = drm_atomic_get_connector_state(state, connector);
11445 
11446 	/* Check for error in getting connector state */
11447 	if (IS_ERR(conn_state)) {
11448 		ret = PTR_ERR(conn_state);
11449 		goto out;
11450 	}
11451 
11452 	/* Attach crtc to drm_atomic_state*/
11453 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11454 
11455 	/* Check for error in getting crtc state */
11456 	if (IS_ERR(crtc_state)) {
11457 		ret = PTR_ERR(crtc_state);
11458 		goto out;
11459 	}
11460 
11461 	/* force a restore */
11462 	crtc_state->mode_changed = true;
11463 
11464 	/* Attach plane to drm_atomic_state */
11465 	plane_state = drm_atomic_get_plane_state(state, plane);
11466 
11467 	/* Check for error in getting plane state */
11468 	if (IS_ERR(plane_state)) {
11469 		ret = PTR_ERR(plane_state);
11470 		goto out;
11471 	}
11472 
11473 	/* Call commit internally with the state we just constructed */
11474 	ret = drm_atomic_commit(state);
11475 
11476 out:
11477 	drm_atomic_state_put(state);
11478 	if (ret)
11479 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11480 
11481 	return ret;
11482 }
11483 
11484 /*
11485  * This function handles all cases when set mode does not come upon hotplug.
11486  * This includes when a display is unplugged then plugged back into the
11487  * same port and when running without usermode desktop manager supprot
11488  */
11489 void dm_restore_drm_connector_state(struct drm_device *dev,
11490 				    struct drm_connector *connector)
11491 {
11492 	struct amdgpu_dm_connector *aconnector;
11493 	struct amdgpu_crtc *disconnected_acrtc;
11494 	struct dm_crtc_state *acrtc_state;
11495 
11496 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11497 		return;
11498 
11499 	aconnector = to_amdgpu_dm_connector(connector);
11500 
11501 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11502 		return;
11503 
11504 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11505 	if (!disconnected_acrtc)
11506 		return;
11507 
11508 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11509 	if (!acrtc_state->stream)
11510 		return;
11511 
11512 	/*
11513 	 * If the previous sink is not released and different from the current,
11514 	 * we deduce we are in a state where we can not rely on usermode call
11515 	 * to turn on the display, so we do it here
11516 	 */
11517 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11518 		dm_force_atomic_commit(&aconnector->base);
11519 }
11520 
11521 /*
11522  * Grabs all modesetting locks to serialize against any blocking commits,
11523  * Waits for completion of all non blocking commits.
11524  */
11525 static int do_aquire_global_lock(struct drm_device *dev,
11526 				 struct drm_atomic_state *state)
11527 {
11528 	struct drm_crtc *crtc;
11529 	struct drm_crtc_commit *commit;
11530 	long ret;
11531 
11532 	/*
11533 	 * Adding all modeset locks to aquire_ctx will
11534 	 * ensure that when the framework release it the
11535 	 * extra locks we are locking here will get released to
11536 	 */
11537 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11538 	if (ret)
11539 		return ret;
11540 
11541 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11542 		spin_lock(&crtc->commit_lock);
11543 		commit = list_first_entry_or_null(&crtc->commit_list,
11544 				struct drm_crtc_commit, commit_entry);
11545 		if (commit)
11546 			drm_crtc_commit_get(commit);
11547 		spin_unlock(&crtc->commit_lock);
11548 
11549 		if (!commit)
11550 			continue;
11551 
11552 		/*
11553 		 * Make sure all pending HW programming completed and
11554 		 * page flips done
11555 		 */
11556 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11557 
11558 		if (ret > 0)
11559 			ret = wait_for_completion_interruptible_timeout(
11560 					&commit->flip_done, 10*HZ);
11561 
11562 		if (ret == 0)
11563 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11564 				  crtc->base.id, crtc->name);
11565 
11566 		drm_crtc_commit_put(commit);
11567 	}
11568 
11569 	return ret < 0 ? ret : 0;
11570 }
11571 
11572 static void get_freesync_config_for_crtc(
11573 	struct dm_crtc_state *new_crtc_state,
11574 	struct dm_connector_state *new_con_state)
11575 {
11576 	struct mod_freesync_config config = {0};
11577 	struct amdgpu_dm_connector *aconnector;
11578 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11579 	int vrefresh = drm_mode_vrefresh(mode);
11580 	bool fs_vid_mode = false;
11581 
11582 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11583 		return;
11584 
11585 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11586 
11587 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11588 					vrefresh >= aconnector->min_vfreq &&
11589 					vrefresh <= aconnector->max_vfreq;
11590 
11591 	if (new_crtc_state->vrr_supported) {
11592 		new_crtc_state->stream->ignore_msa_timing_param = true;
11593 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11594 
11595 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11596 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11597 		config.vsif_supported = true;
11598 		config.btr = true;
11599 
11600 		if (fs_vid_mode) {
11601 			config.state = VRR_STATE_ACTIVE_FIXED;
11602 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11603 			goto out;
11604 		} else if (new_crtc_state->base.vrr_enabled) {
11605 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11606 		} else {
11607 			config.state = VRR_STATE_INACTIVE;
11608 		}
11609 	} else {
11610 		config.state = VRR_STATE_UNSUPPORTED;
11611 	}
11612 out:
11613 	new_crtc_state->freesync_config = config;
11614 }
11615 
11616 static void reset_freesync_config_for_crtc(
11617 	struct dm_crtc_state *new_crtc_state)
11618 {
11619 	new_crtc_state->vrr_supported = false;
11620 
11621 	memset(&new_crtc_state->vrr_infopacket, 0,
11622 	       sizeof(new_crtc_state->vrr_infopacket));
11623 }
11624 
11625 static bool
11626 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11627 				 struct drm_crtc_state *new_crtc_state)
11628 {
11629 	const struct drm_display_mode *old_mode, *new_mode;
11630 
11631 	if (!old_crtc_state || !new_crtc_state)
11632 		return false;
11633 
11634 	old_mode = &old_crtc_state->mode;
11635 	new_mode = &new_crtc_state->mode;
11636 
11637 	if (old_mode->clock       == new_mode->clock &&
11638 	    old_mode->hdisplay    == new_mode->hdisplay &&
11639 	    old_mode->vdisplay    == new_mode->vdisplay &&
11640 	    old_mode->htotal      == new_mode->htotal &&
11641 	    old_mode->vtotal      != new_mode->vtotal &&
11642 	    old_mode->hsync_start == new_mode->hsync_start &&
11643 	    old_mode->vsync_start != new_mode->vsync_start &&
11644 	    old_mode->hsync_end   == new_mode->hsync_end &&
11645 	    old_mode->vsync_end   != new_mode->vsync_end &&
11646 	    old_mode->hskew       == new_mode->hskew &&
11647 	    old_mode->vscan       == new_mode->vscan &&
11648 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11649 	    (new_mode->vsync_end - new_mode->vsync_start))
11650 		return true;
11651 
11652 	return false;
11653 }
11654 
11655 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11656 {
11657 	u64 num, den, res;
11658 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11659 
11660 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11661 
11662 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11663 	den = (unsigned long long)new_crtc_state->mode.htotal *
11664 	      (unsigned long long)new_crtc_state->mode.vtotal;
11665 
11666 	res = div_u64(num, den);
11667 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11668 }
11669 
11670 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11671 			 struct drm_atomic_state *state,
11672 			 struct drm_crtc *crtc,
11673 			 struct drm_crtc_state *old_crtc_state,
11674 			 struct drm_crtc_state *new_crtc_state,
11675 			 bool enable,
11676 			 bool *lock_and_validation_needed)
11677 {
11678 	struct dm_atomic_state *dm_state = NULL;
11679 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11680 	struct dc_stream_state *new_stream;
11681 	struct amdgpu_device *adev = dm->adev;
11682 	int ret = 0;
11683 
11684 	/*
11685 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11686 	 * update changed items
11687 	 */
11688 	struct amdgpu_crtc *acrtc = NULL;
11689 	struct drm_connector *connector = NULL;
11690 	struct amdgpu_dm_connector *aconnector = NULL;
11691 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11692 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11693 
11694 	new_stream = NULL;
11695 
11696 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11697 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11698 	acrtc = to_amdgpu_crtc(crtc);
11699 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11700 	if (connector)
11701 		aconnector = to_amdgpu_dm_connector(connector);
11702 
11703 	/* TODO This hack should go away */
11704 	if (connector && enable) {
11705 		/* Make sure fake sink is created in plug-in scenario */
11706 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11707 									connector);
11708 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11709 									connector);
11710 
11711 		if (WARN_ON(!drm_new_conn_state)) {
11712 			ret = -EINVAL;
11713 			goto fail;
11714 		}
11715 
11716 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11717 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11718 
11719 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11720 			goto skip_modeset;
11721 
11722 		new_stream = create_validate_stream_for_sink(connector,
11723 							     &new_crtc_state->mode,
11724 							     dm_new_conn_state,
11725 							     dm_old_crtc_state->stream);
11726 
11727 		/*
11728 		 * we can have no stream on ACTION_SET if a display
11729 		 * was disconnected during S3, in this case it is not an
11730 		 * error, the OS will be updated after detection, and
11731 		 * will do the right thing on next atomic commit
11732 		 */
11733 
11734 		if (!new_stream) {
11735 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11736 					__func__, acrtc->base.base.id);
11737 			ret = -ENOMEM;
11738 			goto fail;
11739 		}
11740 
11741 		/*
11742 		 * TODO: Check VSDB bits to decide whether this should
11743 		 * be enabled or not.
11744 		 */
11745 		new_stream->triggered_crtc_reset.enabled =
11746 			dm->force_timing_sync;
11747 
11748 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11749 
11750 		ret = fill_hdr_info_packet(drm_new_conn_state,
11751 					   &new_stream->hdr_static_metadata);
11752 		if (ret)
11753 			goto fail;
11754 
11755 		/*
11756 		 * If we already removed the old stream from the context
11757 		 * (and set the new stream to NULL) then we can't reuse
11758 		 * the old stream even if the stream and scaling are unchanged.
11759 		 * We'll hit the BUG_ON and black screen.
11760 		 *
11761 		 * TODO: Refactor this function to allow this check to work
11762 		 * in all conditions.
11763 		 */
11764 		if (amdgpu_freesync_vid_mode &&
11765 		    dm_new_crtc_state->stream &&
11766 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11767 			goto skip_modeset;
11768 
11769 		if (dm_new_crtc_state->stream &&
11770 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11771 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11772 			new_crtc_state->mode_changed = false;
11773 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11774 					 new_crtc_state->mode_changed);
11775 		}
11776 	}
11777 
11778 	/* mode_changed flag may get updated above, need to check again */
11779 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11780 		goto skip_modeset;
11781 
11782 	drm_dbg_state(state->dev,
11783 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11784 		acrtc->crtc_id,
11785 		new_crtc_state->enable,
11786 		new_crtc_state->active,
11787 		new_crtc_state->planes_changed,
11788 		new_crtc_state->mode_changed,
11789 		new_crtc_state->active_changed,
11790 		new_crtc_state->connectors_changed);
11791 
11792 	/* Remove stream for any changed/disabled CRTC */
11793 	if (!enable) {
11794 
11795 		if (!dm_old_crtc_state->stream)
11796 			goto skip_modeset;
11797 
11798 		/* Unset freesync video if it was active before */
11799 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11800 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11801 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11802 		}
11803 
11804 		/* Now check if we should set freesync video mode */
11805 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11806 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11807 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11808 		    is_timing_unchanged_for_freesync(new_crtc_state,
11809 						     old_crtc_state)) {
11810 			new_crtc_state->mode_changed = false;
11811 			drm_dbg_driver(adev_to_drm(adev),
11812 				"Mode change not required for front porch change, setting mode_changed to %d",
11813 				new_crtc_state->mode_changed);
11814 
11815 			set_freesync_fixed_config(dm_new_crtc_state);
11816 
11817 			goto skip_modeset;
11818 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11819 			   is_freesync_video_mode(&new_crtc_state->mode,
11820 						  aconnector)) {
11821 			struct drm_display_mode *high_mode;
11822 
11823 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11824 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11825 				set_freesync_fixed_config(dm_new_crtc_state);
11826 		}
11827 
11828 		ret = dm_atomic_get_state(state, &dm_state);
11829 		if (ret)
11830 			goto fail;
11831 
11832 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11833 				crtc->base.id);
11834 
11835 		/* i.e. reset mode */
11836 		if (dc_state_remove_stream(
11837 				dm->dc,
11838 				dm_state->context,
11839 				dm_old_crtc_state->stream) != DC_OK) {
11840 			ret = -EINVAL;
11841 			goto fail;
11842 		}
11843 
11844 		dc_stream_release(dm_old_crtc_state->stream);
11845 		dm_new_crtc_state->stream = NULL;
11846 
11847 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11848 
11849 		*lock_and_validation_needed = true;
11850 
11851 	} else {/* Add stream for any updated/enabled CRTC */
11852 		/*
11853 		 * Quick fix to prevent NULL pointer on new_stream when
11854 		 * added MST connectors not found in existing crtc_state in the chained mode
11855 		 * TODO: need to dig out the root cause of that
11856 		 */
11857 		if (!connector)
11858 			goto skip_modeset;
11859 
11860 		if (modereset_required(new_crtc_state))
11861 			goto skip_modeset;
11862 
11863 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11864 				     dm_old_crtc_state->stream)) {
11865 
11866 			WARN_ON(dm_new_crtc_state->stream);
11867 
11868 			ret = dm_atomic_get_state(state, &dm_state);
11869 			if (ret)
11870 				goto fail;
11871 
11872 			dm_new_crtc_state->stream = new_stream;
11873 
11874 			dc_stream_retain(new_stream);
11875 
11876 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11877 					 crtc->base.id);
11878 
11879 			if (dc_state_add_stream(
11880 					dm->dc,
11881 					dm_state->context,
11882 					dm_new_crtc_state->stream) != DC_OK) {
11883 				ret = -EINVAL;
11884 				goto fail;
11885 			}
11886 
11887 			*lock_and_validation_needed = true;
11888 		}
11889 	}
11890 
11891 skip_modeset:
11892 	/* Release extra reference */
11893 	if (new_stream)
11894 		dc_stream_release(new_stream);
11895 
11896 	/*
11897 	 * We want to do dc stream updates that do not require a
11898 	 * full modeset below.
11899 	 */
11900 	if (!(enable && connector && new_crtc_state->active))
11901 		return 0;
11902 	/*
11903 	 * Given above conditions, the dc state cannot be NULL because:
11904 	 * 1. We're in the process of enabling CRTCs (just been added
11905 	 *    to the dc context, or already is on the context)
11906 	 * 2. Has a valid connector attached, and
11907 	 * 3. Is currently active and enabled.
11908 	 * => The dc stream state currently exists.
11909 	 */
11910 	BUG_ON(dm_new_crtc_state->stream == NULL);
11911 
11912 	/* Scaling or underscan settings */
11913 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11914 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11915 		update_stream_scaling_settings(adev_to_drm(adev),
11916 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11917 
11918 	/* ABM settings */
11919 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11920 
11921 	/*
11922 	 * Color management settings. We also update color properties
11923 	 * when a modeset is needed, to ensure it gets reprogrammed.
11924 	 */
11925 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11926 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11927 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11928 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11929 		if (ret)
11930 			goto fail;
11931 	}
11932 
11933 	/* Update Freesync settings. */
11934 	get_freesync_config_for_crtc(dm_new_crtc_state,
11935 				     dm_new_conn_state);
11936 
11937 	return ret;
11938 
11939 fail:
11940 	if (new_stream)
11941 		dc_stream_release(new_stream);
11942 	return ret;
11943 }
11944 
11945 static bool should_reset_plane(struct drm_atomic_state *state,
11946 			       struct drm_plane *plane,
11947 			       struct drm_plane_state *old_plane_state,
11948 			       struct drm_plane_state *new_plane_state)
11949 {
11950 	struct drm_plane *other;
11951 	struct drm_plane_state *old_other_state, *new_other_state;
11952 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11953 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11954 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11955 	struct drm_connector_state *new_con_state;
11956 	struct drm_connector *connector;
11957 	int i;
11958 
11959 	/*
11960 	 * TODO: Remove this hack for all asics once it proves that the
11961 	 * fast updates works fine on DCN3.2+.
11962 	 */
11963 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11964 	    state->allow_modeset)
11965 		return true;
11966 
11967 	/* Check for writeback commit */
11968 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11969 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11970 			continue;
11971 
11972 		if (new_con_state->writeback_job)
11973 			return true;
11974 	}
11975 
11976 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11977 		return true;
11978 
11979 	/* Exit early if we know that we're adding or removing the plane. */
11980 	if (old_plane_state->crtc != new_plane_state->crtc)
11981 		return true;
11982 
11983 	/* old crtc == new_crtc == NULL, plane not in context. */
11984 	if (!new_plane_state->crtc)
11985 		return false;
11986 
11987 	new_crtc_state =
11988 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11989 	old_crtc_state =
11990 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11991 
11992 	if (!new_crtc_state)
11993 		return true;
11994 
11995 	/*
11996 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11997 	 * released from the state
11998 	 */
11999 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12000 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12001 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12002 	    old_dm_crtc_state != NULL &&
12003 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12004 		return true;
12005 	}
12006 
12007 	/* CRTC Degamma changes currently require us to recreate planes. */
12008 	if (new_crtc_state->color_mgmt_changed)
12009 		return true;
12010 
12011 	/*
12012 	 * On zpos change, planes need to be reordered by removing and re-adding
12013 	 * them one by one to the dc state, in order of descending zpos.
12014 	 *
12015 	 * TODO: We can likely skip bandwidth validation if the only thing that
12016 	 * changed about the plane was it'z z-ordering.
12017 	 */
12018 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12019 		return true;
12020 
12021 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12022 		return true;
12023 
12024 	/*
12025 	 * If there are any new primary or overlay planes being added or
12026 	 * removed then the z-order can potentially change. To ensure
12027 	 * correct z-order and pipe acquisition the current DC architecture
12028 	 * requires us to remove and recreate all existing planes.
12029 	 *
12030 	 * TODO: Come up with a more elegant solution for this.
12031 	 */
12032 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12033 		struct amdgpu_framebuffer *old_afb, *new_afb;
12034 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12035 
12036 		dm_new_other_state = to_dm_plane_state(new_other_state);
12037 		dm_old_other_state = to_dm_plane_state(old_other_state);
12038 
12039 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12040 			continue;
12041 
12042 		if (old_other_state->crtc != new_plane_state->crtc &&
12043 		    new_other_state->crtc != new_plane_state->crtc)
12044 			continue;
12045 
12046 		if (old_other_state->crtc != new_other_state->crtc)
12047 			return true;
12048 
12049 		/* Src/dst size and scaling updates. */
12050 		if (old_other_state->src_w != new_other_state->src_w ||
12051 		    old_other_state->src_h != new_other_state->src_h ||
12052 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12053 		    old_other_state->crtc_h != new_other_state->crtc_h)
12054 			return true;
12055 
12056 		/* Rotation / mirroring updates. */
12057 		if (old_other_state->rotation != new_other_state->rotation)
12058 			return true;
12059 
12060 		/* Blending updates. */
12061 		if (old_other_state->pixel_blend_mode !=
12062 		    new_other_state->pixel_blend_mode)
12063 			return true;
12064 
12065 		/* Alpha updates. */
12066 		if (old_other_state->alpha != new_other_state->alpha)
12067 			return true;
12068 
12069 		/* Colorspace changes. */
12070 		if (old_other_state->color_range != new_other_state->color_range ||
12071 		    old_other_state->color_encoding != new_other_state->color_encoding)
12072 			return true;
12073 
12074 		/* HDR/Transfer Function changes. */
12075 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12076 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12077 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12078 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12079 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12080 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12081 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12082 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12083 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12084 			return true;
12085 
12086 		/* Framebuffer checks fall at the end. */
12087 		if (!old_other_state->fb || !new_other_state->fb)
12088 			continue;
12089 
12090 		/* Pixel format changes can require bandwidth updates. */
12091 		if (old_other_state->fb->format != new_other_state->fb->format)
12092 			return true;
12093 
12094 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12095 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12096 
12097 		/* Tiling and DCC changes also require bandwidth updates. */
12098 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12099 		    old_afb->base.modifier != new_afb->base.modifier)
12100 			return true;
12101 	}
12102 
12103 	return false;
12104 }
12105 
12106 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12107 			      struct drm_plane_state *new_plane_state,
12108 			      struct drm_framebuffer *fb)
12109 {
12110 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12111 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12112 	unsigned int pitch;
12113 	bool linear;
12114 
12115 	if (fb->width > new_acrtc->max_cursor_width ||
12116 	    fb->height > new_acrtc->max_cursor_height) {
12117 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12118 				 new_plane_state->fb->width,
12119 				 new_plane_state->fb->height);
12120 		return -EINVAL;
12121 	}
12122 	if (new_plane_state->src_w != fb->width << 16 ||
12123 	    new_plane_state->src_h != fb->height << 16) {
12124 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12125 		return -EINVAL;
12126 	}
12127 
12128 	/* Pitch in pixels */
12129 	pitch = fb->pitches[0] / fb->format->cpp[0];
12130 
12131 	if (fb->width != pitch) {
12132 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12133 				 fb->width, pitch);
12134 		return -EINVAL;
12135 	}
12136 
12137 	switch (pitch) {
12138 	case 64:
12139 	case 128:
12140 	case 256:
12141 		/* FB pitch is supported by cursor plane */
12142 		break;
12143 	default:
12144 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12145 		return -EINVAL;
12146 	}
12147 
12148 	/* Core DRM takes care of checking FB modifiers, so we only need to
12149 	 * check tiling flags when the FB doesn't have a modifier.
12150 	 */
12151 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12152 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12153 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12154 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12155 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12156 		} else {
12157 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12158 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12159 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12160 		}
12161 		if (!linear) {
12162 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12163 			return -EINVAL;
12164 		}
12165 	}
12166 
12167 	return 0;
12168 }
12169 
12170 /*
12171  * Helper function for checking the cursor in native mode
12172  */
12173 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12174 					struct drm_plane *plane,
12175 					struct drm_plane_state *new_plane_state,
12176 					bool enable)
12177 {
12178 
12179 	struct amdgpu_crtc *new_acrtc;
12180 	int ret;
12181 
12182 	if (!enable || !new_plane_crtc ||
12183 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12184 		return 0;
12185 
12186 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12187 
12188 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12189 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12190 		return -EINVAL;
12191 	}
12192 
12193 	if (new_plane_state->fb) {
12194 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12195 						new_plane_state->fb);
12196 		if (ret)
12197 			return ret;
12198 	}
12199 
12200 	return 0;
12201 }
12202 
12203 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
12204 					   struct drm_crtc *old_plane_crtc,
12205 					   struct drm_crtc *new_plane_crtc,
12206 					   bool enable)
12207 {
12208 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12209 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12210 
12211 	if (!enable) {
12212 		if (old_plane_crtc == NULL)
12213 			return true;
12214 
12215 		old_crtc_state = drm_atomic_get_old_crtc_state(
12216 			state, old_plane_crtc);
12217 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12218 
12219 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12220 	} else {
12221 		if (new_plane_crtc == NULL)
12222 			return true;
12223 
12224 		new_crtc_state = drm_atomic_get_new_crtc_state(
12225 			state, new_plane_crtc);
12226 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12227 
12228 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12229 	}
12230 }
12231 
12232 static int dm_update_plane_state(struct dc *dc,
12233 				 struct drm_atomic_state *state,
12234 				 struct drm_plane *plane,
12235 				 struct drm_plane_state *old_plane_state,
12236 				 struct drm_plane_state *new_plane_state,
12237 				 bool enable,
12238 				 bool *lock_and_validation_needed,
12239 				 bool *is_top_most_overlay)
12240 {
12241 
12242 	struct dm_atomic_state *dm_state = NULL;
12243 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12244 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12245 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12246 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12247 	bool needs_reset, update_native_cursor;
12248 	int ret = 0;
12249 
12250 
12251 	new_plane_crtc = new_plane_state->crtc;
12252 	old_plane_crtc = old_plane_state->crtc;
12253 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12254 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12255 
12256 	update_native_cursor = dm_should_update_native_cursor(state,
12257 							      old_plane_crtc,
12258 							      new_plane_crtc,
12259 							      enable);
12260 
12261 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12262 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12263 						    new_plane_state, enable);
12264 		if (ret)
12265 			return ret;
12266 
12267 		return 0;
12268 	}
12269 
12270 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12271 					 new_plane_state);
12272 
12273 	/* Remove any changed/removed planes */
12274 	if (!enable) {
12275 		if (!needs_reset)
12276 			return 0;
12277 
12278 		if (!old_plane_crtc)
12279 			return 0;
12280 
12281 		old_crtc_state = drm_atomic_get_old_crtc_state(
12282 				state, old_plane_crtc);
12283 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12284 
12285 		if (!dm_old_crtc_state->stream)
12286 			return 0;
12287 
12288 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12289 				plane->base.id, old_plane_crtc->base.id);
12290 
12291 		ret = dm_atomic_get_state(state, &dm_state);
12292 		if (ret)
12293 			return ret;
12294 
12295 		if (!dc_state_remove_plane(
12296 				dc,
12297 				dm_old_crtc_state->stream,
12298 				dm_old_plane_state->dc_state,
12299 				dm_state->context)) {
12300 
12301 			return -EINVAL;
12302 		}
12303 
12304 		if (dm_old_plane_state->dc_state)
12305 			dc_plane_state_release(dm_old_plane_state->dc_state);
12306 
12307 		dm_new_plane_state->dc_state = NULL;
12308 
12309 		*lock_and_validation_needed = true;
12310 
12311 	} else { /* Add new planes */
12312 		struct dc_plane_state *dc_new_plane_state;
12313 
12314 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12315 			return 0;
12316 
12317 		if (!new_plane_crtc)
12318 			return 0;
12319 
12320 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12321 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12322 
12323 		if (!dm_new_crtc_state->stream)
12324 			return 0;
12325 
12326 		if (!needs_reset)
12327 			return 0;
12328 
12329 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12330 		if (ret)
12331 			goto out;
12332 
12333 		WARN_ON(dm_new_plane_state->dc_state);
12334 
12335 		dc_new_plane_state = dc_create_plane_state(dc);
12336 		if (!dc_new_plane_state) {
12337 			ret = -ENOMEM;
12338 			goto out;
12339 		}
12340 
12341 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12342 				 plane->base.id, new_plane_crtc->base.id);
12343 
12344 		ret = fill_dc_plane_attributes(
12345 			drm_to_adev(new_plane_crtc->dev),
12346 			dc_new_plane_state,
12347 			new_plane_state,
12348 			new_crtc_state);
12349 		if (ret) {
12350 			dc_plane_state_release(dc_new_plane_state);
12351 			goto out;
12352 		}
12353 
12354 		ret = dm_atomic_get_state(state, &dm_state);
12355 		if (ret) {
12356 			dc_plane_state_release(dc_new_plane_state);
12357 			goto out;
12358 		}
12359 
12360 		/*
12361 		 * Any atomic check errors that occur after this will
12362 		 * not need a release. The plane state will be attached
12363 		 * to the stream, and therefore part of the atomic
12364 		 * state. It'll be released when the atomic state is
12365 		 * cleaned.
12366 		 */
12367 		if (!dc_state_add_plane(
12368 				dc,
12369 				dm_new_crtc_state->stream,
12370 				dc_new_plane_state,
12371 				dm_state->context)) {
12372 
12373 			dc_plane_state_release(dc_new_plane_state);
12374 			ret = -EINVAL;
12375 			goto out;
12376 		}
12377 
12378 		dm_new_plane_state->dc_state = dc_new_plane_state;
12379 
12380 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12381 
12382 		/* Tell DC to do a full surface update every time there
12383 		 * is a plane change. Inefficient, but works for now.
12384 		 */
12385 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12386 
12387 		*lock_and_validation_needed = true;
12388 	}
12389 
12390 out:
12391 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12392 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12393 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12394 						    new_plane_state, enable);
12395 		if (ret)
12396 			return ret;
12397 
12398 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12399 	}
12400 
12401 	return ret;
12402 }
12403 
12404 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12405 				       int *src_w, int *src_h)
12406 {
12407 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12408 	case DRM_MODE_ROTATE_90:
12409 	case DRM_MODE_ROTATE_270:
12410 		*src_w = plane_state->src_h >> 16;
12411 		*src_h = plane_state->src_w >> 16;
12412 		break;
12413 	case DRM_MODE_ROTATE_0:
12414 	case DRM_MODE_ROTATE_180:
12415 	default:
12416 		*src_w = plane_state->src_w >> 16;
12417 		*src_h = plane_state->src_h >> 16;
12418 		break;
12419 	}
12420 }
12421 
12422 static void
12423 dm_get_plane_scale(struct drm_plane_state *plane_state,
12424 		   int *out_plane_scale_w, int *out_plane_scale_h)
12425 {
12426 	int plane_src_w, plane_src_h;
12427 
12428 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12429 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12430 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12431 }
12432 
12433 /*
12434  * The normalized_zpos value cannot be used by this iterator directly. It's only
12435  * calculated for enabled planes, potentially causing normalized_zpos collisions
12436  * between enabled/disabled planes in the atomic state. We need a unique value
12437  * so that the iterator will not generate the same object twice, or loop
12438  * indefinitely.
12439  */
12440 static inline struct __drm_planes_state *__get_next_zpos(
12441 	struct drm_atomic_state *state,
12442 	struct __drm_planes_state *prev)
12443 {
12444 	unsigned int highest_zpos = 0, prev_zpos = 256;
12445 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12446 	struct drm_plane_state *new_plane_state;
12447 	struct drm_plane *plane;
12448 	int i, highest_i = -1;
12449 
12450 	if (prev != NULL) {
12451 		prev_zpos = prev->new_state->zpos;
12452 		prev_id = prev->ptr->base.id;
12453 	}
12454 
12455 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12456 		/* Skip planes with higher zpos than the previously returned */
12457 		if (new_plane_state->zpos > prev_zpos ||
12458 		    (new_plane_state->zpos == prev_zpos &&
12459 		     plane->base.id >= prev_id))
12460 			continue;
12461 
12462 		/* Save the index of the plane with highest zpos */
12463 		if (new_plane_state->zpos > highest_zpos ||
12464 		    (new_plane_state->zpos == highest_zpos &&
12465 		     plane->base.id > highest_id)) {
12466 			highest_zpos = new_plane_state->zpos;
12467 			highest_id = plane->base.id;
12468 			highest_i = i;
12469 		}
12470 	}
12471 
12472 	if (highest_i < 0)
12473 		return NULL;
12474 
12475 	return &state->planes[highest_i];
12476 }
12477 
12478 /*
12479  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12480  * by descending zpos, as read from the new plane state. This is the same
12481  * ordering as defined by drm_atomic_normalize_zpos().
12482  */
12483 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12484 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12485 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12486 		for_each_if(((plane) = __i->ptr,				\
12487 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12488 			     (old_plane_state) = __i->old_state,		\
12489 			     (new_plane_state) = __i->new_state, 1))
12490 
12491 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12492 {
12493 	struct drm_connector *connector;
12494 	struct drm_connector_state *conn_state, *old_conn_state;
12495 	struct amdgpu_dm_connector *aconnector = NULL;
12496 	int i;
12497 
12498 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12499 		if (!conn_state->crtc)
12500 			conn_state = old_conn_state;
12501 
12502 		if (conn_state->crtc != crtc)
12503 			continue;
12504 
12505 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12506 			continue;
12507 
12508 		aconnector = to_amdgpu_dm_connector(connector);
12509 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12510 			aconnector = NULL;
12511 		else
12512 			break;
12513 	}
12514 
12515 	if (!aconnector)
12516 		return 0;
12517 
12518 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12519 }
12520 
12521 /**
12522  * DOC: Cursor Modes - Native vs Overlay
12523  *
12524  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12525  * plane. It does not require a dedicated hw plane to enable, but it is
12526  * subjected to the same z-order and scaling as the hw plane. It also has format
12527  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12528  * hw plane.
12529  *
12530  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12531  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12532  * cursor behavior more akin to a DRM client's expectations. However, it does
12533  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12534  * available.
12535  */
12536 
12537 /**
12538  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12539  * @state: DRM atomic state
12540  * @plane: DRM plane to check
12541  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12542  *
12543  * A color pipeline may be selected (color_pipeline != NULL) but still is
12544  * inactive if every colorop in the chain is bypassed.  Only return
12545  * true when at least one colorop has bypass == false, meaning the cursor
12546  * would be subjected to the transformation in native mode.
12547  *
12548  * Return: true if the pipeline modifies pixels, false otherwise.
12549  */
12550 static bool dm_plane_color_pipeline_active(struct drm_atomic_state *state,
12551 					   struct drm_plane *plane,
12552 					   bool use_old)
12553 {
12554 	struct drm_colorop *colorop;
12555 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12556 	int i;
12557 
12558 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12559 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12560 
12561 		if (cstate->colorop->plane != plane)
12562 			continue;
12563 		if (!cstate->bypass)
12564 			return true;
12565 	}
12566 	return false;
12567 }
12568 
12569 /**
12570  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12571  * @adev: amdgpu device
12572  * @state: DRM atomic state
12573  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12574  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12575  *
12576  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12577  * the dm_crtc_state.
12578  *
12579  * The cursor should be enabled in overlay mode if there exists an underlying
12580  * plane - on which the cursor may be blended - that is either YUV formatted,
12581  * scaled differently from the cursor, or has a color pipeline active.
12582  *
12583  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12584  * calling this function.
12585  *
12586  * Return: 0 on success, or an error code if getting the cursor plane state
12587  * failed.
12588  */
12589 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12590 				   struct drm_atomic_state *state,
12591 				   struct dm_crtc_state *dm_crtc_state,
12592 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12593 {
12594 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12595 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12596 	struct drm_plane *plane;
12597 	bool consider_mode_change = false;
12598 	bool entire_crtc_covered = false;
12599 	bool cursor_changed = false;
12600 	int underlying_scale_w, underlying_scale_h;
12601 	int cursor_scale_w, cursor_scale_h;
12602 	int i;
12603 
12604 	/* Overlay cursor not supported on HW before DCN
12605 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12606 	 * as previous DCN generations, so enable native mode on DCN401/420
12607 	 */
12608 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12609 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0)) {
12610 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12611 		return 0;
12612 	}
12613 
12614 	/* Init cursor_mode to be the same as current */
12615 	*cursor_mode = dm_crtc_state->cursor_mode;
12616 
12617 	/*
12618 	 * Cursor mode can change if a plane's format changes, scale changes, is
12619 	 * enabled/disabled, z-order changes, or color management properties change.
12620 	 */
12621 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12622 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12623 
12624 		/* Only care about planes on this CRTC */
12625 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12626 			continue;
12627 
12628 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12629 			cursor_changed = true;
12630 
12631 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12632 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12633 		    old_plane_state->fb->format != plane_state->fb->format) {
12634 			consider_mode_change = true;
12635 			break;
12636 		}
12637 
12638 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12639 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12640 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12641 			consider_mode_change = true;
12642 			break;
12643 		}
12644 
12645 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12646 		    dm_plane_color_pipeline_active(state, plane, false)) {
12647 			consider_mode_change = true;
12648 			break;
12649 		}
12650 	}
12651 
12652 	if (!consider_mode_change && !crtc_state->zpos_changed)
12653 		return 0;
12654 
12655 	/*
12656 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12657 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12658 	 * state.
12659 	 */
12660 	if (!cursor_changed &&
12661 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12662 		return 0;
12663 	}
12664 
12665 	cursor_state = drm_atomic_get_plane_state(state,
12666 						  crtc_state->crtc->cursor);
12667 	if (IS_ERR(cursor_state))
12668 		return PTR_ERR(cursor_state);
12669 
12670 	/* Cursor is disabled */
12671 	if (!cursor_state->fb)
12672 		return 0;
12673 
12674 	/* For all planes in descending z-order (all of which are below cursor
12675 	 * as per zpos definitions), check their scaling and format
12676 	 */
12677 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12678 
12679 		/* Only care about non-cursor planes on this CRTC */
12680 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12681 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12682 			continue;
12683 
12684 		/* Underlying plane is YUV format - use overlay cursor */
12685 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12686 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12687 			return 0;
12688 		}
12689 
12690 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12691 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12692 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12693 			return 0;
12694 		}
12695 
12696 		dm_get_plane_scale(plane_state,
12697 				   &underlying_scale_w, &underlying_scale_h);
12698 		dm_get_plane_scale(cursor_state,
12699 				   &cursor_scale_w, &cursor_scale_h);
12700 
12701 		/* Underlying plane has different scale - use overlay cursor */
12702 		if (cursor_scale_w != underlying_scale_w &&
12703 		    cursor_scale_h != underlying_scale_h) {
12704 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12705 			return 0;
12706 		}
12707 
12708 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12709 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12710 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12711 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12712 			entire_crtc_covered = true;
12713 			break;
12714 		}
12715 	}
12716 
12717 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12718 	 * cursor over holes
12719 	 */
12720 	if (entire_crtc_covered)
12721 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12722 	else
12723 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12724 
12725 	return 0;
12726 }
12727 
12728 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12729 					    struct drm_atomic_state *state,
12730 					    struct drm_crtc_state *crtc_state)
12731 {
12732 	struct drm_plane *plane;
12733 	struct drm_plane_state *new_plane_state, *old_plane_state;
12734 
12735 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12736 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12737 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12738 
12739 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12740 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12741 			return false;
12742 		}
12743 
12744 		if (old_plane_state->fb && new_plane_state->fb &&
12745 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12746 			return true;
12747 	}
12748 
12749 	return false;
12750 }
12751 
12752 /**
12753  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12754  *
12755  * @dev: The DRM device
12756  * @state: The atomic state to commit
12757  *
12758  * Validate that the given atomic state is programmable by DC into hardware.
12759  * This involves constructing a &struct dc_state reflecting the new hardware
12760  * state we wish to commit, then querying DC to see if it is programmable. It's
12761  * important not to modify the existing DC state. Otherwise, atomic_check
12762  * may unexpectedly commit hardware changes.
12763  *
12764  * When validating the DC state, it's important that the right locks are
12765  * acquired. For full updates case which removes/adds/updates streams on one
12766  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12767  * that any such full update commit will wait for completion of any outstanding
12768  * flip using DRMs synchronization events.
12769  *
12770  * Note that DM adds the affected connectors for all CRTCs in state, when that
12771  * might not seem necessary. This is because DC stream creation requires the
12772  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12773  * be possible but non-trivial - a possible TODO item.
12774  *
12775  * Return: -Error code if validation failed.
12776  */
12777 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12778 				  struct drm_atomic_state *state)
12779 {
12780 	struct amdgpu_device *adev = drm_to_adev(dev);
12781 	struct dm_atomic_state *dm_state = NULL;
12782 	struct dc *dc = adev->dm.dc;
12783 	struct drm_connector *connector;
12784 	struct drm_connector_state *old_con_state, *new_con_state;
12785 	struct drm_crtc *crtc;
12786 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12787 	struct drm_plane *plane;
12788 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12789 	enum dc_status status;
12790 	int ret, i;
12791 	bool lock_and_validation_needed = false;
12792 	bool is_top_most_overlay = true;
12793 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12794 	struct drm_dp_mst_topology_mgr *mgr;
12795 	struct drm_dp_mst_topology_state *mst_state;
12796 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12797 
12798 	trace_amdgpu_dm_atomic_check_begin(state);
12799 
12800 	ret = drm_atomic_helper_check_modeset(dev, state);
12801 	if (ret) {
12802 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12803 		goto fail;
12804 	}
12805 
12806 	/* Check connector changes */
12807 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12808 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12809 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12810 
12811 		/* Skip connectors that are disabled or part of modeset already. */
12812 		if (!new_con_state->crtc)
12813 			continue;
12814 
12815 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12816 		if (IS_ERR(new_crtc_state)) {
12817 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12818 			ret = PTR_ERR(new_crtc_state);
12819 			goto fail;
12820 		}
12821 
12822 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12823 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12824 			new_crtc_state->connectors_changed = true;
12825 	}
12826 
12827 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12828 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12829 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12830 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
12831 		}
12832 
12833 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12834 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12835 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12836 				if (ret) {
12837 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12838 					goto fail;
12839 				}
12840 			}
12841 		}
12842 	}
12843 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12844 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12845 
12846 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12847 		    !new_crtc_state->color_mgmt_changed &&
12848 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12849 			dm_old_crtc_state->dsc_force_changed == false)
12850 			continue;
12851 
12852 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12853 		if (ret) {
12854 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12855 			goto fail;
12856 		}
12857 
12858 		if (!new_crtc_state->enable)
12859 			continue;
12860 
12861 		ret = drm_atomic_add_affected_connectors(state, crtc);
12862 		if (ret) {
12863 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12864 			goto fail;
12865 		}
12866 
12867 		ret = drm_atomic_add_affected_planes(state, crtc);
12868 		if (ret) {
12869 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12870 			goto fail;
12871 		}
12872 
12873 		if (dm_old_crtc_state->dsc_force_changed)
12874 			new_crtc_state->mode_changed = true;
12875 	}
12876 
12877 	/*
12878 	 * Add all primary and overlay planes on the CRTC to the state
12879 	 * whenever a plane is enabled to maintain correct z-ordering
12880 	 * and to enable fast surface updates.
12881 	 */
12882 	drm_for_each_crtc(crtc, dev) {
12883 		bool modified = false;
12884 
12885 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12886 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12887 				continue;
12888 
12889 			if (new_plane_state->crtc == crtc ||
12890 			    old_plane_state->crtc == crtc) {
12891 				modified = true;
12892 				break;
12893 			}
12894 		}
12895 
12896 		if (!modified)
12897 			continue;
12898 
12899 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12900 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12901 				continue;
12902 
12903 			new_plane_state =
12904 				drm_atomic_get_plane_state(state, plane);
12905 
12906 			if (IS_ERR(new_plane_state)) {
12907 				ret = PTR_ERR(new_plane_state);
12908 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12909 				goto fail;
12910 			}
12911 		}
12912 	}
12913 
12914 	/*
12915 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12916 	 * hw plane on which to enable the hw cursor (see
12917 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12918 	 * atomic state, so call drm helper to normalize zpos.
12919 	 */
12920 	ret = drm_atomic_normalize_zpos(dev, state);
12921 	if (ret) {
12922 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12923 		goto fail;
12924 	}
12925 
12926 	/*
12927 	 * Determine whether cursors on each CRTC should be enabled in native or
12928 	 * overlay mode.
12929 	 */
12930 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12931 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12932 
12933 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12934 					      &dm_new_crtc_state->cursor_mode);
12935 		if (ret) {
12936 			drm_dbg(dev, "Failed to determine cursor mode\n");
12937 			goto fail;
12938 		}
12939 
12940 		/*
12941 		 * If overlay cursor is needed, DC cannot go through the
12942 		 * native cursor update path. All enabled planes on the CRTC
12943 		 * need to be added for DC to not disable a plane by mistake
12944 		 */
12945 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12946 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
12947 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
12948 				ret = -EINVAL;
12949 				goto fail;
12950 			}
12951 
12952 			ret = drm_atomic_add_affected_planes(state, crtc);
12953 			if (ret)
12954 				goto fail;
12955 		}
12956 	}
12957 
12958 	/* Remove exiting planes if they are modified */
12959 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12960 
12961 		ret = dm_update_plane_state(dc, state, plane,
12962 					    old_plane_state,
12963 					    new_plane_state,
12964 					    false,
12965 					    &lock_and_validation_needed,
12966 					    &is_top_most_overlay);
12967 		if (ret) {
12968 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12969 			goto fail;
12970 		}
12971 	}
12972 
12973 	/* Disable all crtcs which require disable */
12974 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12975 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12976 					   old_crtc_state,
12977 					   new_crtc_state,
12978 					   false,
12979 					   &lock_and_validation_needed);
12980 		if (ret) {
12981 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12982 			goto fail;
12983 		}
12984 	}
12985 
12986 	/* Enable all crtcs which require enable */
12987 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12988 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12989 					   old_crtc_state,
12990 					   new_crtc_state,
12991 					   true,
12992 					   &lock_and_validation_needed);
12993 		if (ret) {
12994 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12995 			goto fail;
12996 		}
12997 	}
12998 
12999 	/* Add new/modified planes */
13000 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13001 		ret = dm_update_plane_state(dc, state, plane,
13002 					    old_plane_state,
13003 					    new_plane_state,
13004 					    true,
13005 					    &lock_and_validation_needed,
13006 					    &is_top_most_overlay);
13007 		if (ret) {
13008 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13009 			goto fail;
13010 		}
13011 	}
13012 
13013 #if defined(CONFIG_DRM_AMD_DC_FP)
13014 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13015 		ret = pre_validate_dsc(state, &dm_state, vars);
13016 		if (ret != 0)
13017 			goto fail;
13018 	}
13019 #endif
13020 
13021 	/* Run this here since we want to validate the streams we created */
13022 	ret = drm_atomic_helper_check_planes(dev, state);
13023 	if (ret) {
13024 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13025 		goto fail;
13026 	}
13027 
13028 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13029 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13030 		if (dm_new_crtc_state->mpo_requested)
13031 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13032 	}
13033 
13034 	/* Check cursor restrictions */
13035 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13036 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13037 		int is_rotated, is_scaled;
13038 
13039 		/* Overlay cusor not subject to native cursor restrictions */
13040 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13041 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13042 			continue;
13043 
13044 		/* Check if rotation or scaling is enabled on DCN401 */
13045 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
13046 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13047 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13048 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13049 
13050 			is_rotated = new_cursor_state &&
13051 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13052 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13053 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13054 
13055 			if (is_rotated || is_scaled) {
13056 				drm_dbg_driver(
13057 					crtc->dev,
13058 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13059 					crtc->base.id, crtc->name);
13060 				ret = -EINVAL;
13061 				goto fail;
13062 			}
13063 		}
13064 
13065 		/* If HW can only do native cursor, check restrictions again */
13066 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13067 					      &required_cursor_mode);
13068 		if (ret) {
13069 			drm_dbg_driver(crtc->dev,
13070 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13071 				       crtc->base.id, crtc->name);
13072 			goto fail;
13073 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13074 			drm_dbg_driver(crtc->dev,
13075 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13076 				       crtc->base.id, crtc->name);
13077 			ret = -EINVAL;
13078 			goto fail;
13079 		}
13080 	}
13081 
13082 	if (state->legacy_cursor_update) {
13083 		/*
13084 		 * This is a fast cursor update coming from the plane update
13085 		 * helper, check if it can be done asynchronously for better
13086 		 * performance.
13087 		 */
13088 		state->async_update =
13089 			!drm_atomic_helper_async_check(dev, state);
13090 
13091 		/*
13092 		 * Skip the remaining global validation if this is an async
13093 		 * update. Cursor updates can be done without affecting
13094 		 * state or bandwidth calcs and this avoids the performance
13095 		 * penalty of locking the private state object and
13096 		 * allocating a new dc_state.
13097 		 */
13098 		if (state->async_update)
13099 			return 0;
13100 	}
13101 
13102 	/* Check scaling and underscan changes*/
13103 	/* TODO Removed scaling changes validation due to inability to commit
13104 	 * new stream into context w\o causing full reset. Need to
13105 	 * decide how to handle.
13106 	 */
13107 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13108 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13109 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13110 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13111 
13112 		/* Skip any modesets/resets */
13113 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13114 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13115 			continue;
13116 
13117 		/* Skip any thing not scale or underscan changes */
13118 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13119 			continue;
13120 
13121 		lock_and_validation_needed = true;
13122 	}
13123 
13124 	/* set the slot info for each mst_state based on the link encoding format */
13125 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13126 		struct amdgpu_dm_connector *aconnector;
13127 		struct drm_connector *connector;
13128 		struct drm_connector_list_iter iter;
13129 		u8 link_coding_cap;
13130 
13131 		drm_connector_list_iter_begin(dev, &iter);
13132 		drm_for_each_connector_iter(connector, &iter) {
13133 			if (connector->index == mst_state->mgr->conn_base_id) {
13134 				aconnector = to_amdgpu_dm_connector(connector);
13135 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13136 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13137 
13138 				break;
13139 			}
13140 		}
13141 		drm_connector_list_iter_end(&iter);
13142 	}
13143 
13144 	/**
13145 	 * Streams and planes are reset when there are changes that affect
13146 	 * bandwidth. Anything that affects bandwidth needs to go through
13147 	 * DC global validation to ensure that the configuration can be applied
13148 	 * to hardware.
13149 	 *
13150 	 * We have to currently stall out here in atomic_check for outstanding
13151 	 * commits to finish in this case because our IRQ handlers reference
13152 	 * DRM state directly - we can end up disabling interrupts too early
13153 	 * if we don't.
13154 	 *
13155 	 * TODO: Remove this stall and drop DM state private objects.
13156 	 */
13157 	if (lock_and_validation_needed) {
13158 		ret = dm_atomic_get_state(state, &dm_state);
13159 		if (ret) {
13160 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13161 			goto fail;
13162 		}
13163 
13164 		ret = do_aquire_global_lock(dev, state);
13165 		if (ret) {
13166 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13167 			goto fail;
13168 		}
13169 
13170 #if defined(CONFIG_DRM_AMD_DC_FP)
13171 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13172 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13173 			if (ret) {
13174 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13175 				ret = -EINVAL;
13176 				goto fail;
13177 			}
13178 		}
13179 #endif
13180 
13181 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13182 		if (ret) {
13183 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13184 			goto fail;
13185 		}
13186 
13187 		/*
13188 		 * Perform validation of MST topology in the state:
13189 		 * We need to perform MST atomic check before calling
13190 		 * dc_validate_global_state(), or there is a chance
13191 		 * to get stuck in an infinite loop and hang eventually.
13192 		 */
13193 		ret = drm_dp_mst_atomic_check(state);
13194 		if (ret) {
13195 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13196 			goto fail;
13197 		}
13198 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13199 		if (status != DC_OK) {
13200 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13201 				       dc_status_to_str(status), status);
13202 			ret = -EINVAL;
13203 			goto fail;
13204 		}
13205 	} else {
13206 		/*
13207 		 * The commit is a fast update. Fast updates shouldn't change
13208 		 * the DC context, affect global validation, and can have their
13209 		 * commit work done in parallel with other commits not touching
13210 		 * the same resource. If we have a new DC context as part of
13211 		 * the DM atomic state from validation we need to free it and
13212 		 * retain the existing one instead.
13213 		 *
13214 		 * Furthermore, since the DM atomic state only contains the DC
13215 		 * context and can safely be annulled, we can free the state
13216 		 * and clear the associated private object now to free
13217 		 * some memory and avoid a possible use-after-free later.
13218 		 */
13219 
13220 		for (i = 0; i < state->num_private_objs; i++) {
13221 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13222 
13223 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13224 				int j = state->num_private_objs-1;
13225 
13226 				dm_atomic_destroy_state(obj,
13227 						state->private_objs[i].state_to_destroy);
13228 
13229 				/* If i is not at the end of the array then the
13230 				 * last element needs to be moved to where i was
13231 				 * before the array can safely be truncated.
13232 				 */
13233 				if (i != j)
13234 					state->private_objs[i] =
13235 						state->private_objs[j];
13236 
13237 				state->private_objs[j].ptr = NULL;
13238 				state->private_objs[j].state_to_destroy = NULL;
13239 				state->private_objs[j].old_state = NULL;
13240 				state->private_objs[j].new_state = NULL;
13241 
13242 				state->num_private_objs = j;
13243 				break;
13244 			}
13245 		}
13246 	}
13247 
13248 	/* Store the overall update type for use later in atomic check. */
13249 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13250 		struct dm_crtc_state *dm_new_crtc_state =
13251 			to_dm_crtc_state(new_crtc_state);
13252 
13253 		/*
13254 		 * Only allow async flips for fast updates that don't change
13255 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13256 		 */
13257 		if (new_crtc_state->async_flip &&
13258 		    (lock_and_validation_needed ||
13259 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13260 			drm_dbg_atomic(crtc->dev,
13261 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13262 				       crtc->base.id, crtc->name);
13263 			ret = -EINVAL;
13264 			goto fail;
13265 		}
13266 
13267 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13268 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13269 	}
13270 
13271 	/* Must be success */
13272 	WARN_ON(ret);
13273 
13274 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13275 
13276 	return ret;
13277 
13278 fail:
13279 	if (ret == -EDEADLK)
13280 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13281 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13282 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13283 	else
13284 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13285 
13286 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13287 
13288 	return ret;
13289 }
13290 
13291 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13292 		unsigned int offset,
13293 		unsigned int total_length,
13294 		u8 *data,
13295 		unsigned int length,
13296 		struct amdgpu_hdmi_vsdb_info *vsdb)
13297 {
13298 	bool res;
13299 	union dmub_rb_cmd cmd;
13300 	struct dmub_cmd_send_edid_cea *input;
13301 	struct dmub_cmd_edid_cea_output *output;
13302 
13303 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13304 		return false;
13305 
13306 	memset(&cmd, 0, sizeof(cmd));
13307 
13308 	input = &cmd.edid_cea.data.input;
13309 
13310 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13311 	cmd.edid_cea.header.sub_type = 0;
13312 	cmd.edid_cea.header.payload_bytes =
13313 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13314 	input->offset = offset;
13315 	input->length = length;
13316 	input->cea_total_length = total_length;
13317 	memcpy(input->payload, data, length);
13318 
13319 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13320 	if (!res) {
13321 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13322 		return false;
13323 	}
13324 
13325 	output = &cmd.edid_cea.data.output;
13326 
13327 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13328 		if (!output->ack.success) {
13329 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13330 					output->ack.offset);
13331 		}
13332 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13333 		if (!output->amd_vsdb.vsdb_found)
13334 			return false;
13335 
13336 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13337 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13338 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13339 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13340 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13341 	} else {
13342 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13343 		return false;
13344 	}
13345 
13346 	return true;
13347 }
13348 
13349 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13350 		u8 *edid_ext, int len,
13351 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13352 {
13353 	int i;
13354 
13355 	/* send extension block to DMCU for parsing */
13356 	for (i = 0; i < len; i += 8) {
13357 		bool res;
13358 		int offset;
13359 
13360 		/* send 8 bytes a time */
13361 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13362 			return false;
13363 
13364 		if (i+8 == len) {
13365 			/* EDID block sent completed, expect result */
13366 			int version, min_rate, max_rate;
13367 
13368 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13369 			if (res) {
13370 				/* amd vsdb found */
13371 				vsdb_info->freesync_supported = 1;
13372 				vsdb_info->amd_vsdb_version = version;
13373 				vsdb_info->min_refresh_rate_hz = min_rate;
13374 				vsdb_info->max_refresh_rate_hz = max_rate;
13375 				/* Not enabled on DMCU*/
13376 				vsdb_info->freesync_mccs_vcp_code = 0;
13377 				return true;
13378 			}
13379 			/* not amd vsdb */
13380 			return false;
13381 		}
13382 
13383 		/* check for ack*/
13384 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13385 		if (!res)
13386 			return false;
13387 	}
13388 
13389 	return false;
13390 }
13391 
13392 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13393 		u8 *edid_ext, int len,
13394 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13395 {
13396 	int i;
13397 
13398 	/* send extension block to DMCU for parsing */
13399 	for (i = 0; i < len; i += 8) {
13400 		/* send 8 bytes a time */
13401 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13402 			return false;
13403 	}
13404 
13405 	return vsdb_info->freesync_supported;
13406 }
13407 
13408 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13409 		u8 *edid_ext, int len,
13410 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13411 {
13412 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13413 	bool ret;
13414 
13415 	mutex_lock(&adev->dm.dc_lock);
13416 	if (adev->dm.dmub_srv)
13417 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13418 	else
13419 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13420 	mutex_unlock(&adev->dm.dc_lock);
13421 	return ret;
13422 }
13423 
13424 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13425 				     const struct edid *edid)
13426 {
13427 	u8 *edid_ext = NULL;
13428 	int i;
13429 	int j = 0;
13430 	u16 min_vfreq;
13431 	u16 max_vfreq;
13432 
13433 	if (!edid || !edid->extensions)
13434 		return;
13435 
13436 	/* Find DisplayID extension */
13437 	for (i = 0; i < edid->extensions; i++) {
13438 		edid_ext = (void *)(edid + (i + 1));
13439 		if (edid_ext[0] == DISPLAYID_EXT)
13440 			break;
13441 	}
13442 
13443 	if (i == edid->extensions)
13444 		return;
13445 
13446 	while (j < EDID_LENGTH) {
13447 		/* Get dynamic video timing range from DisplayID if available */
13448 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13449 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13450 			min_vfreq = edid_ext[j+9];
13451 			if (edid_ext[j+1] & 7)
13452 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13453 			else
13454 				max_vfreq = edid_ext[j+10];
13455 
13456 			if (max_vfreq && min_vfreq) {
13457 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13458 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13459 
13460 				return;
13461 			}
13462 		}
13463 		j++;
13464 	}
13465 }
13466 
13467 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13468 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13469 {
13470 	struct drm_connector *connector = &aconnector->base;
13471 
13472 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13473 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13474 
13475 	return connector->display_info.amd_vsdb.version != 0;
13476 }
13477 
13478 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13479 			       const struct edid *edid,
13480 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13481 {
13482 	u8 *edid_ext = NULL;
13483 	int i;
13484 	bool valid_vsdb_found = false;
13485 
13486 	/*----- drm_find_cea_extension() -----*/
13487 	/* No EDID or EDID extensions */
13488 	if (edid == NULL || edid->extensions == 0)
13489 		return -ENODEV;
13490 
13491 	/* Find CEA extension */
13492 	for (i = 0; i < edid->extensions; i++) {
13493 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13494 		if (edid_ext[0] == CEA_EXT)
13495 			break;
13496 	}
13497 
13498 	if (i == edid->extensions)
13499 		return -ENODEV;
13500 
13501 	/*----- cea_db_offsets() -----*/
13502 	if (edid_ext[0] != CEA_EXT)
13503 		return -ENODEV;
13504 
13505 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13506 
13507 	return valid_vsdb_found ? i : -ENODEV;
13508 }
13509 
13510 /**
13511  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13512  *
13513  * @connector: Connector to query.
13514  * @drm_edid: DRM EDID from monitor
13515  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13516  *	      DDC (Display Data Channel) transactions are performed. When true,
13517  *	      the driver queries the monitor to get or update additional FreeSync
13518  *	      capability information. When false, these transactions are skipped.
13519  *
13520  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13521  * track of some of the display information in the internal data struct used by
13522  * amdgpu_dm. This function checks which type of connector we need to set the
13523  * FreeSync parameters.
13524  */
13525 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13526 				    const struct drm_edid *drm_edid, bool do_mccs)
13527 {
13528 	int i = 0;
13529 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13530 			to_amdgpu_dm_connector(connector);
13531 	struct dm_connector_state *dm_con_state = NULL;
13532 	struct dc_sink *sink;
13533 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13534 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13535 	const struct edid *edid;
13536 	bool freesync_capable = false;
13537 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13538 
13539 	if (!connector->state) {
13540 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13541 		goto update;
13542 	}
13543 
13544 	sink = amdgpu_dm_connector->dc_sink ?
13545 		amdgpu_dm_connector->dc_sink :
13546 		amdgpu_dm_connector->dc_em_sink;
13547 
13548 	drm_edid_connector_update(connector, drm_edid);
13549 
13550 	if (!drm_edid || !sink) {
13551 		dm_con_state = to_dm_connector_state(connector->state);
13552 
13553 		amdgpu_dm_connector->min_vfreq = 0;
13554 		amdgpu_dm_connector->max_vfreq = 0;
13555 		freesync_capable = false;
13556 
13557 		goto update;
13558 	}
13559 
13560 	dm_con_state = to_dm_connector_state(connector->state);
13561 
13562 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13563 		goto update;
13564 
13565 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13566 
13567 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13568 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13569 	     connector->display_info.monitor_range.max_vfreq == 0))
13570 		parse_edid_displayid_vrr(connector, edid);
13571 
13572 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13573 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13574 		if (amdgpu_dm_connector->dc_link &&
13575 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13576 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13577 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13578 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13579 				freesync_capable = true;
13580 		}
13581 
13582 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13583 
13584 		if (vsdb_info.replay_mode) {
13585 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13586 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13587 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13588 		}
13589 
13590 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13591 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13592 		if (i >= 0) {
13593 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13594 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13595 
13596 			if (vsdb_info.freesync_supported) {
13597 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13598 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13599 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13600 					freesync_capable = true;
13601 
13602 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13603 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13604 			}
13605 		}
13606 	}
13607 
13608 	if (amdgpu_dm_connector->dc_link)
13609 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13610 
13611 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13612 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13613 		if (i >= 0) {
13614 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13615 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13616 
13617 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13618 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13619 				amdgpu_dm_connector->as_type = as_type;
13620 
13621 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13622 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13623 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13624 					freesync_capable = true;
13625 
13626 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13627 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13628 			}
13629 		}
13630 	}
13631 
13632 	/* Handle MCCS */
13633 	if (do_mccs)
13634 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13635 
13636 	if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
13637 		as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) &&
13638 		(!sink->edid_caps.freesync_vcp_code ||
13639 		(sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)))
13640 		freesync_capable = false;
13641 
13642 	if (do_mccs && sink->mccs_caps.freesync_supported && freesync_capable)
13643 		dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13644 
13645 update:
13646 	if (dm_con_state)
13647 		dm_con_state->freesync_capable = freesync_capable;
13648 
13649 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13650 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13651 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13652 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13653 	}
13654 
13655 	if (connector->vrr_capable_property)
13656 		drm_connector_set_vrr_capable_property(connector,
13657 						       freesync_capable);
13658 }
13659 
13660 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13661 {
13662 	struct amdgpu_device *adev = drm_to_adev(dev);
13663 	struct dc *dc = adev->dm.dc;
13664 	int i;
13665 
13666 	mutex_lock(&adev->dm.dc_lock);
13667 	if (dc->current_state) {
13668 		for (i = 0; i < dc->current_state->stream_count; ++i)
13669 			dc->current_state->streams[i]
13670 				->triggered_crtc_reset.enabled =
13671 				adev->dm.force_timing_sync;
13672 
13673 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13674 		dc_trigger_sync(dc, dc->current_state);
13675 	}
13676 	mutex_unlock(&adev->dm.dc_lock);
13677 }
13678 
13679 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13680 {
13681 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13682 		dc_exit_ips_for_hw_access(dc);
13683 }
13684 
13685 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13686 		       u32 value, const char *func_name)
13687 {
13688 #ifdef DM_CHECK_ADDR_0
13689 	if (address == 0) {
13690 		drm_err(adev_to_drm(ctx->driver_context),
13691 			"invalid register write. address = 0");
13692 		return;
13693 	}
13694 #endif
13695 
13696 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13697 	cgs_write_register(ctx->cgs_device, address, value);
13698 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13699 }
13700 
13701 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13702 			  const char *func_name)
13703 {
13704 	u32 value;
13705 #ifdef DM_CHECK_ADDR_0
13706 	if (address == 0) {
13707 		drm_err(adev_to_drm(ctx->driver_context),
13708 			"invalid register read; address = 0\n");
13709 		return 0;
13710 	}
13711 #endif
13712 
13713 	if (ctx->dmub_srv &&
13714 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13715 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13716 		ASSERT(false);
13717 		return 0;
13718 	}
13719 
13720 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13721 
13722 	value = cgs_read_register(ctx->cgs_device, address);
13723 
13724 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13725 
13726 	return value;
13727 }
13728 
13729 int amdgpu_dm_process_dmub_aux_transfer_sync(
13730 		struct dc_context *ctx,
13731 		unsigned int link_index,
13732 		struct aux_payload *payload,
13733 		enum aux_return_code_type *operation_result)
13734 {
13735 	struct amdgpu_device *adev = ctx->driver_context;
13736 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13737 	int ret = -1;
13738 
13739 	mutex_lock(&adev->dm.dpia_aux_lock);
13740 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13741 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13742 		goto out;
13743 	}
13744 
13745 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13746 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13747 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13748 		goto out;
13749 	}
13750 
13751 	if (p_notify->result != AUX_RET_SUCCESS) {
13752 		/*
13753 		 * Transient states before tunneling is enabled could
13754 		 * lead to this error. We can ignore this for now.
13755 		 */
13756 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13757 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13758 					payload->address, payload->length,
13759 					p_notify->result);
13760 		}
13761 		*operation_result = p_notify->result;
13762 		goto out;
13763 	}
13764 
13765 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13766 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13767 		/* The reply is stored in the top nibble of the command. */
13768 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13769 
13770 	/*write req may receive a byte indicating partially written number as well*/
13771 	if (p_notify->aux_reply.length)
13772 		memcpy(payload->data, p_notify->aux_reply.data,
13773 				p_notify->aux_reply.length);
13774 
13775 	/* success */
13776 	ret = p_notify->aux_reply.length;
13777 	*operation_result = p_notify->result;
13778 out:
13779 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13780 	mutex_unlock(&adev->dm.dpia_aux_lock);
13781 	return ret;
13782 }
13783 
13784 static void abort_fused_io(
13785 		struct dc_context *ctx,
13786 		const struct dmub_cmd_fused_request *request
13787 )
13788 {
13789 	union dmub_rb_cmd command = { 0 };
13790 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13791 
13792 	io->header.type = DMUB_CMD__FUSED_IO;
13793 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13794 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13795 	io->request = *request;
13796 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13797 }
13798 
13799 static bool execute_fused_io(
13800 		struct amdgpu_device *dev,
13801 		struct dc_context *ctx,
13802 		union dmub_rb_cmd *commands,
13803 		uint8_t count,
13804 		uint32_t timeout_us
13805 )
13806 {
13807 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13808 
13809 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13810 		return false;
13811 
13812 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13813 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13814 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13815 			&& first->header.ret_status
13816 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13817 
13818 	if (!result)
13819 		return false;
13820 
13821 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13822 		reinit_completion(&sync->replied);
13823 
13824 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13825 
13826 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13827 
13828 		if (reply->identifier == first->request.identifier) {
13829 			first->request = *reply;
13830 			return true;
13831 		}
13832 	}
13833 
13834 	reinit_completion(&sync->replied);
13835 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13836 	abort_fused_io(ctx, &first->request);
13837 	return false;
13838 }
13839 
13840 bool amdgpu_dm_execute_fused_io(
13841 		struct amdgpu_device *dev,
13842 		struct dc_link *link,
13843 		union dmub_rb_cmd *commands,
13844 		uint8_t count,
13845 		uint32_t timeout_us)
13846 {
13847 	struct amdgpu_display_manager *dm = &dev->dm;
13848 
13849 	mutex_lock(&dm->dpia_aux_lock);
13850 
13851 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13852 
13853 	mutex_unlock(&dm->dpia_aux_lock);
13854 	return result;
13855 }
13856 
13857 int amdgpu_dm_process_dmub_set_config_sync(
13858 		struct dc_context *ctx,
13859 		unsigned int link_index,
13860 		struct set_config_cmd_payload *payload,
13861 		enum set_config_status *operation_result)
13862 {
13863 	struct amdgpu_device *adev = ctx->driver_context;
13864 	bool is_cmd_complete;
13865 	int ret;
13866 
13867 	mutex_lock(&adev->dm.dpia_aux_lock);
13868 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13869 			link_index, payload, adev->dm.dmub_notify);
13870 
13871 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13872 		ret = 0;
13873 		*operation_result = adev->dm.dmub_notify->sc_status;
13874 	} else {
13875 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13876 		ret = -1;
13877 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13878 	}
13879 
13880 	if (!is_cmd_complete)
13881 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13882 	mutex_unlock(&adev->dm.dpia_aux_lock);
13883 	return ret;
13884 }
13885 
13886 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13887 {
13888 	struct amdgpu_device *adev = ctx->driver_context;
13889 
13890 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13891 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13892 }
13893 
13894 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)
13895 {
13896 	struct amdgpu_device *adev = ctx->driver_context;
13897 
13898 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13899 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13900 }
13901 
13902 void dm_acpi_process_phy_transition_interlock(
13903 	const struct dc_context *ctx,
13904 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13905 {
13906 	// Not yet implemented
13907 }
13908