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