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