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