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