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