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