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