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