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