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