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