xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_display.c (revision 5027ec19f1049a07df5b0a37b1f462514cf2724b)
1 /*
2  * Copyright 2007-8 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Dave Airlie
24  *          Alex Deucher
25  */
26 
27 #include <drm/amdgpu_drm.h>
28 #include "amdgpu.h"
29 #include "amdgpu_i2c.h"
30 #include "atom.h"
31 #include "amdgpu_connectors.h"
32 #include "amdgpu_display.h"
33 #include "soc15_common.h"
34 #include "gc/gc_11_0_0_offset.h"
35 #include "gc/gc_11_0_0_sh_mask.h"
36 #include <asm/div64.h>
37 
38 #include <linux/pci.h>
39 #include <linux/pm_runtime.h>
40 #include <drm/drm_crtc_helper.h>
41 #include <drm/drm_damage_helper.h>
42 #include <drm/drm_drv.h>
43 #include <drm/drm_edid.h>
44 #include <drm/drm_fb_helper.h>
45 #include <drm/drm_gem_framebuffer_helper.h>
46 #include <drm/drm_fourcc.h>
47 #include <drm/drm_modeset_helper.h>
48 #include <drm/drm_vblank.h>
49 
50 /**
51  * amdgpu_display_hotplug_work_func - work handler for display hotplug event
52  *
53  * @work: work struct pointer
54  *
55  * This is the hotplug event work handler (all ASICs).
56  * The work gets scheduled from the IRQ handler if there
57  * was a hotplug interrupt.  It walks through the connector table
58  * and calls hotplug handler for each connector. After this, it sends
59  * a DRM hotplug event to alert userspace.
60  *
61  * This design approach is required in order to defer hotplug event handling
62  * from the IRQ handler to a work handler because hotplug handler has to use
63  * mutexes which cannot be locked in an IRQ handler (since &mutex_lock may
64  * sleep).
65  */
66 void amdgpu_display_hotplug_work_func(struct work_struct *work)
67 {
68 	struct amdgpu_device *adev = container_of(work, struct amdgpu_device,
69 						  hotplug_work.work);
70 	struct drm_device *dev = adev_to_drm(adev);
71 	struct drm_mode_config *mode_config = &dev->mode_config;
72 	struct drm_connector *connector;
73 	struct drm_connector_list_iter iter;
74 
75 	mutex_lock(&mode_config->mutex);
76 	drm_connector_list_iter_begin(dev, &iter);
77 	drm_for_each_connector_iter(connector, &iter)
78 		amdgpu_connector_hotplug(connector);
79 	drm_connector_list_iter_end(&iter);
80 	mutex_unlock(&mode_config->mutex);
81 	/* Just fire off a uevent and let userspace tell us what to do */
82 	drm_helper_hpd_irq_event(dev);
83 }
84 
85 static int amdgpu_display_framebuffer_init(struct drm_device *dev,
86 					   struct amdgpu_framebuffer *rfb,
87 					   const struct drm_mode_fb_cmd2 *mode_cmd,
88 					   struct drm_gem_object *obj);
89 
90 static void amdgpu_display_flip_callback(struct dma_fence *f,
91 					 struct dma_fence_cb *cb)
92 {
93 	struct amdgpu_flip_work *work =
94 		container_of(cb, struct amdgpu_flip_work, cb);
95 
96 	dma_fence_put(f);
97 	schedule_work(&work->flip_work.work);
98 }
99 
100 static bool amdgpu_display_flip_handle_fence(struct amdgpu_flip_work *work,
101 					     struct dma_fence **f)
102 {
103 	struct dma_fence *fence = *f;
104 
105 	if (fence == NULL)
106 		return false;
107 
108 	*f = NULL;
109 
110 	if (!dma_fence_add_callback(fence, &work->cb,
111 				    amdgpu_display_flip_callback))
112 		return true;
113 
114 	dma_fence_put(fence);
115 	return false;
116 }
117 
118 static void amdgpu_display_flip_work_func(struct work_struct *__work)
119 {
120 	struct delayed_work *delayed_work =
121 		container_of(__work, struct delayed_work, work);
122 	struct amdgpu_flip_work *work =
123 		container_of(delayed_work, struct amdgpu_flip_work, flip_work);
124 	struct amdgpu_device *adev = work->adev;
125 	struct amdgpu_crtc *amdgpu_crtc = adev->mode_info.crtcs[work->crtc_id];
126 
127 	struct drm_crtc *crtc = &amdgpu_crtc->base;
128 	unsigned long flags;
129 	unsigned int i;
130 	int vpos, hpos;
131 
132 	for (i = 0; i < work->shared_count; ++i)
133 		if (amdgpu_display_flip_handle_fence(work, &work->shared[i]))
134 			return;
135 
136 	/* Wait until we're out of the vertical blank period before the one
137 	 * targeted by the flip
138 	 */
139 	if (amdgpu_crtc->enabled &&
140 	    (amdgpu_display_get_crtc_scanoutpos(adev_to_drm(adev), work->crtc_id, 0,
141 						&vpos, &hpos, NULL, NULL,
142 						&crtc->hwmode)
143 	     & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
144 	    (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
145 	    (int)(work->target_vblank -
146 		  amdgpu_get_vblank_counter_kms(crtc)) > 0) {
147 		schedule_delayed_work(&work->flip_work, usecs_to_jiffies(1000));
148 		return;
149 	}
150 
151 	/* We borrow the event spin lock for protecting flip_status */
152 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
153 
154 	/* Do the flip (mmio) */
155 	adev->mode_info.funcs->page_flip(adev, work->crtc_id, work->base, work->async);
156 
157 	/* Set the flip status */
158 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
159 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
160 
161 
162 	drm_dbg_vbl(adev_to_drm(adev),
163 		    "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_SUBMITTED, work: %p,\n",
164 		    amdgpu_crtc->crtc_id, amdgpu_crtc, work);
165 
166 }
167 
168 /*
169  * Handle unpin events outside the interrupt handler proper.
170  */
171 static void amdgpu_display_unpin_work_func(struct work_struct *__work)
172 {
173 	struct amdgpu_flip_work *work =
174 		container_of(__work, struct amdgpu_flip_work, unpin_work);
175 	int r;
176 
177 	/* unpin of the old buffer */
178 	r = amdgpu_bo_reserve(work->old_abo, true);
179 	if (likely(r == 0)) {
180 		amdgpu_bo_unpin(work->old_abo);
181 		amdgpu_bo_unreserve(work->old_abo);
182 	} else
183 		DRM_ERROR("failed to reserve buffer after flip\n");
184 
185 	amdgpu_bo_unref(&work->old_abo);
186 	kfree(work->shared);
187 	kfree(work);
188 }
189 
190 int amdgpu_display_crtc_page_flip_target(struct drm_crtc *crtc,
191 				struct drm_framebuffer *fb,
192 				struct drm_pending_vblank_event *event,
193 				uint32_t page_flip_flags, uint32_t target,
194 				struct drm_modeset_acquire_ctx *ctx)
195 {
196 	struct drm_device *dev = crtc->dev;
197 	struct amdgpu_device *adev = drm_to_adev(dev);
198 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
199 	struct drm_gem_object *obj;
200 	struct amdgpu_flip_work *work;
201 	struct amdgpu_bo *new_abo;
202 	unsigned long flags;
203 	u64 tiling_flags;
204 	int i, r;
205 
206 	work = kzalloc(sizeof(*work), GFP_KERNEL);
207 	if (work == NULL)
208 		return -ENOMEM;
209 
210 	INIT_DELAYED_WORK(&work->flip_work, amdgpu_display_flip_work_func);
211 	INIT_WORK(&work->unpin_work, amdgpu_display_unpin_work_func);
212 
213 	work->event = event;
214 	work->adev = adev;
215 	work->crtc_id = amdgpu_crtc->crtc_id;
216 	work->async = (page_flip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
217 
218 	/* schedule unpin of the old buffer */
219 	obj = crtc->primary->fb->obj[0];
220 
221 	/* take a reference to the old object */
222 	work->old_abo = gem_to_amdgpu_bo(obj);
223 	amdgpu_bo_ref(work->old_abo);
224 
225 	obj = fb->obj[0];
226 	new_abo = gem_to_amdgpu_bo(obj);
227 
228 	/* pin the new buffer */
229 	r = amdgpu_bo_reserve(new_abo, false);
230 	if (unlikely(r != 0)) {
231 		DRM_ERROR("failed to reserve new abo buffer before flip\n");
232 		goto cleanup;
233 	}
234 
235 	if (!adev->enable_virtual_display) {
236 		r = amdgpu_bo_pin(new_abo,
237 				  amdgpu_display_supported_domains(adev, new_abo->flags));
238 		if (unlikely(r != 0)) {
239 			DRM_ERROR("failed to pin new abo buffer before flip\n");
240 			goto unreserve;
241 		}
242 	}
243 
244 	r = amdgpu_ttm_alloc_gart(&new_abo->tbo);
245 	if (unlikely(r != 0)) {
246 		DRM_ERROR("%p bind failed\n", new_abo);
247 		goto unpin;
248 	}
249 
250 	r = dma_resv_get_fences(new_abo->tbo.base.resv, DMA_RESV_USAGE_WRITE,
251 				&work->shared_count,
252 				&work->shared);
253 	if (unlikely(r != 0)) {
254 		DRM_ERROR("failed to get fences for buffer\n");
255 		goto unpin;
256 	}
257 
258 	amdgpu_bo_get_tiling_flags(new_abo, &tiling_flags);
259 	amdgpu_bo_unreserve(new_abo);
260 
261 	if (!adev->enable_virtual_display)
262 		work->base = amdgpu_bo_gpu_offset(new_abo);
263 	work->target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
264 		amdgpu_get_vblank_counter_kms(crtc);
265 
266 	/* we borrow the event spin lock for protecting flip_wrok */
267 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
268 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_NONE) {
269 		DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
270 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
271 		r = -EBUSY;
272 		goto pflip_cleanup;
273 	}
274 
275 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_PENDING;
276 	amdgpu_crtc->pflip_works = work;
277 
278 
279 	DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_PENDING, work: %p,\n",
280 					 amdgpu_crtc->crtc_id, amdgpu_crtc, work);
281 	/* update crtc fb */
282 	crtc->primary->fb = fb;
283 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
284 	amdgpu_display_flip_work_func(&work->flip_work.work);
285 	return 0;
286 
287 pflip_cleanup:
288 	if (unlikely(amdgpu_bo_reserve(new_abo, false) != 0)) {
289 		DRM_ERROR("failed to reserve new abo in error path\n");
290 		goto cleanup;
291 	}
292 unpin:
293 	if (!adev->enable_virtual_display)
294 		amdgpu_bo_unpin(new_abo);
295 
296 unreserve:
297 	amdgpu_bo_unreserve(new_abo);
298 
299 cleanup:
300 	amdgpu_bo_unref(&work->old_abo);
301 	for (i = 0; i < work->shared_count; ++i)
302 		dma_fence_put(work->shared[i]);
303 	kfree(work->shared);
304 	kfree(work);
305 
306 	return r;
307 }
308 
309 int amdgpu_display_crtc_set_config(struct drm_mode_set *set,
310 				   struct drm_modeset_acquire_ctx *ctx)
311 {
312 	struct drm_device *dev;
313 	struct amdgpu_device *adev;
314 	struct drm_crtc *crtc;
315 	bool active = false;
316 	int ret;
317 
318 	if (!set || !set->crtc)
319 		return -EINVAL;
320 
321 	dev = set->crtc->dev;
322 
323 	ret = pm_runtime_get_sync(dev->dev);
324 	if (ret < 0)
325 		goto out;
326 
327 	ret = drm_crtc_helper_set_config(set, ctx);
328 
329 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
330 		if (crtc->enabled)
331 			active = true;
332 
333 	pm_runtime_mark_last_busy(dev->dev);
334 
335 	adev = drm_to_adev(dev);
336 	/* if we have active crtcs and we don't have a power ref,
337 	 * take the current one
338 	 */
339 	if (active && !adev->have_disp_power_ref) {
340 		adev->have_disp_power_ref = true;
341 		return ret;
342 	}
343 	/* if we have no active crtcs, then drop the power ref
344 	 * we got before
345 	 */
346 	if (!active && adev->have_disp_power_ref) {
347 		pm_runtime_put_autosuspend(dev->dev);
348 		adev->have_disp_power_ref = false;
349 	}
350 
351 out:
352 	/* drop the power reference we got coming in here */
353 	pm_runtime_put_autosuspend(dev->dev);
354 	return ret;
355 }
356 
357 static const char *encoder_names[41] = {
358 	"NONE",
359 	"INTERNAL_LVDS",
360 	"INTERNAL_TMDS1",
361 	"INTERNAL_TMDS2",
362 	"INTERNAL_DAC1",
363 	"INTERNAL_DAC2",
364 	"INTERNAL_SDVOA",
365 	"INTERNAL_SDVOB",
366 	"SI170B",
367 	"CH7303",
368 	"CH7301",
369 	"INTERNAL_DVO1",
370 	"EXTERNAL_SDVOA",
371 	"EXTERNAL_SDVOB",
372 	"TITFP513",
373 	"INTERNAL_LVTM1",
374 	"VT1623",
375 	"HDMI_SI1930",
376 	"HDMI_INTERNAL",
377 	"INTERNAL_KLDSCP_TMDS1",
378 	"INTERNAL_KLDSCP_DVO1",
379 	"INTERNAL_KLDSCP_DAC1",
380 	"INTERNAL_KLDSCP_DAC2",
381 	"SI178",
382 	"MVPU_FPGA",
383 	"INTERNAL_DDI",
384 	"VT1625",
385 	"HDMI_SI1932",
386 	"DP_AN9801",
387 	"DP_DP501",
388 	"INTERNAL_UNIPHY",
389 	"INTERNAL_KLDSCP_LVTMA",
390 	"INTERNAL_UNIPHY1",
391 	"INTERNAL_UNIPHY2",
392 	"NUTMEG",
393 	"TRAVIS",
394 	"INTERNAL_VCE",
395 	"INTERNAL_UNIPHY3",
396 	"HDMI_ANX9805",
397 	"INTERNAL_AMCLK",
398 	"VIRTUAL",
399 };
400 
401 static const char *hpd_names[6] = {
402 	"HPD1",
403 	"HPD2",
404 	"HPD3",
405 	"HPD4",
406 	"HPD5",
407 	"HPD6",
408 };
409 
410 void amdgpu_display_print_display_setup(struct drm_device *dev)
411 {
412 	struct drm_connector *connector;
413 	struct amdgpu_connector *amdgpu_connector;
414 	struct drm_encoder *encoder;
415 	struct amdgpu_encoder *amdgpu_encoder;
416 	struct drm_connector_list_iter iter;
417 	uint32_t devices;
418 	int i = 0;
419 
420 	drm_connector_list_iter_begin(dev, &iter);
421 	DRM_INFO("AMDGPU Display Connectors\n");
422 	drm_for_each_connector_iter(connector, &iter) {
423 		amdgpu_connector = to_amdgpu_connector(connector);
424 		DRM_INFO("Connector %d:\n", i);
425 		DRM_INFO("  %s\n", connector->name);
426 		if (amdgpu_connector->hpd.hpd != AMDGPU_HPD_NONE)
427 			DRM_INFO("  %s\n", hpd_names[amdgpu_connector->hpd.hpd]);
428 		if (amdgpu_connector->ddc_bus) {
429 			DRM_INFO("  DDC: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
430 				 amdgpu_connector->ddc_bus->rec.mask_clk_reg,
431 				 amdgpu_connector->ddc_bus->rec.mask_data_reg,
432 				 amdgpu_connector->ddc_bus->rec.a_clk_reg,
433 				 amdgpu_connector->ddc_bus->rec.a_data_reg,
434 				 amdgpu_connector->ddc_bus->rec.en_clk_reg,
435 				 amdgpu_connector->ddc_bus->rec.en_data_reg,
436 				 amdgpu_connector->ddc_bus->rec.y_clk_reg,
437 				 amdgpu_connector->ddc_bus->rec.y_data_reg);
438 			if (amdgpu_connector->router.ddc_valid)
439 				DRM_INFO("  DDC Router 0x%x/0x%x\n",
440 					 amdgpu_connector->router.ddc_mux_control_pin,
441 					 amdgpu_connector->router.ddc_mux_state);
442 			if (amdgpu_connector->router.cd_valid)
443 				DRM_INFO("  Clock/Data Router 0x%x/0x%x\n",
444 					 amdgpu_connector->router.cd_mux_control_pin,
445 					 amdgpu_connector->router.cd_mux_state);
446 		} else {
447 			if (connector->connector_type == DRM_MODE_CONNECTOR_VGA ||
448 			    connector->connector_type == DRM_MODE_CONNECTOR_DVII ||
449 			    connector->connector_type == DRM_MODE_CONNECTOR_DVID ||
450 			    connector->connector_type == DRM_MODE_CONNECTOR_DVIA ||
451 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIA ||
452 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIB)
453 				DRM_INFO("  DDC: no ddc bus - possible BIOS bug - please report to xorg-driver-ati@lists.x.org\n");
454 		}
455 		DRM_INFO("  Encoders:\n");
456 		list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
457 			amdgpu_encoder = to_amdgpu_encoder(encoder);
458 			devices = amdgpu_encoder->devices & amdgpu_connector->devices;
459 			if (devices) {
460 				if (devices & ATOM_DEVICE_CRT1_SUPPORT)
461 					DRM_INFO("    CRT1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
462 				if (devices & ATOM_DEVICE_CRT2_SUPPORT)
463 					DRM_INFO("    CRT2: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
464 				if (devices & ATOM_DEVICE_LCD1_SUPPORT)
465 					DRM_INFO("    LCD1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
466 				if (devices & ATOM_DEVICE_DFP1_SUPPORT)
467 					DRM_INFO("    DFP1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
468 				if (devices & ATOM_DEVICE_DFP2_SUPPORT)
469 					DRM_INFO("    DFP2: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
470 				if (devices & ATOM_DEVICE_DFP3_SUPPORT)
471 					DRM_INFO("    DFP3: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
472 				if (devices & ATOM_DEVICE_DFP4_SUPPORT)
473 					DRM_INFO("    DFP4: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
474 				if (devices & ATOM_DEVICE_DFP5_SUPPORT)
475 					DRM_INFO("    DFP5: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
476 				if (devices & ATOM_DEVICE_DFP6_SUPPORT)
477 					DRM_INFO("    DFP6: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
478 				if (devices & ATOM_DEVICE_TV1_SUPPORT)
479 					DRM_INFO("    TV1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
480 				if (devices & ATOM_DEVICE_CV_SUPPORT)
481 					DRM_INFO("    CV: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
482 			}
483 		}
484 		i++;
485 	}
486 	drm_connector_list_iter_end(&iter);
487 }
488 
489 bool amdgpu_display_ddc_probe(struct amdgpu_connector *amdgpu_connector,
490 			      bool use_aux)
491 {
492 	u8 out = 0x0;
493 	u8 buf[8];
494 	int ret;
495 	struct i2c_msg msgs[] = {
496 		{
497 			.addr = DDC_ADDR,
498 			.flags = 0,
499 			.len = 1,
500 			.buf = &out,
501 		},
502 		{
503 			.addr = DDC_ADDR,
504 			.flags = I2C_M_RD,
505 			.len = 8,
506 			.buf = buf,
507 		}
508 	};
509 
510 	/* on hw with routers, select right port */
511 	if (amdgpu_connector->router.ddc_valid)
512 		amdgpu_i2c_router_select_ddc_port(amdgpu_connector);
513 
514 	if (use_aux)
515 		ret = i2c_transfer(&amdgpu_connector->ddc_bus->aux.ddc, msgs, 2);
516 	else
517 		ret = i2c_transfer(&amdgpu_connector->ddc_bus->adapter, msgs, 2);
518 
519 	if (ret != 2)
520 		/* Couldn't find an accessible DDC on this connector */
521 		return false;
522 	/* Probe also for valid EDID header
523 	 * EDID header starts with:
524 	 * 0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00.
525 	 * Only the first 6 bytes must be valid as
526 	 * drm_edid_block_valid() can fix the last 2 bytes
527 	 */
528 	if (drm_edid_header_is_valid(buf) < 6) {
529 		/* Couldn't find an accessible EDID on this
530 		 * connector
531 		 */
532 		return false;
533 	}
534 	return true;
535 }
536 
537 static int amdgpu_dirtyfb(struct drm_framebuffer *fb, struct drm_file *file,
538 			  unsigned int flags, unsigned int color,
539 			  struct drm_clip_rect *clips, unsigned int num_clips)
540 {
541 
542 	if (file)
543 		return -ENOSYS;
544 
545 	return drm_atomic_helper_dirtyfb(fb, file, flags, color, clips,
546 					 num_clips);
547 }
548 
549 static const struct drm_framebuffer_funcs amdgpu_fb_funcs = {
550 	.destroy = drm_gem_fb_destroy,
551 	.create_handle = drm_gem_fb_create_handle,
552 };
553 
554 static const struct drm_framebuffer_funcs amdgpu_fb_funcs_atomic = {
555 	.destroy = drm_gem_fb_destroy,
556 	.create_handle = drm_gem_fb_create_handle,
557 	.dirty = amdgpu_dirtyfb
558 };
559 
560 uint32_t amdgpu_display_supported_domains(struct amdgpu_device *adev,
561 					  uint64_t bo_flags)
562 {
563 	uint32_t domain = AMDGPU_GEM_DOMAIN_VRAM;
564 
565 #if defined(CONFIG_DRM_AMD_DC)
566 	/*
567 	 * if amdgpu_bo_support_uswc returns false it means that USWC mappings
568 	 * is not supported for this board. But this mapping is required
569 	 * to avoid hang caused by placement of scanout BO in GTT on certain
570 	 * APUs. So force the BO placement to VRAM in case this architecture
571 	 * will not allow USWC mappings.
572 	 * Also, don't allow GTT domain if the BO doesn't have USWC flag set.
573 	 */
574 	if ((bo_flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC) &&
575 	    amdgpu_bo_support_uswc(bo_flags) &&
576 	    adev->dc_enabled &&
577 	    adev->mode_info.gpu_vm_support)
578 		domain |= AMDGPU_GEM_DOMAIN_GTT;
579 #endif
580 
581 	return domain;
582 }
583 
584 static const struct drm_format_info dcc_formats[] = {
585 	{ .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2,
586 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
587 	 { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2,
588 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
589 	{ .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2,
590 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
591 	   .has_alpha = true, },
592 	{ .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2,
593 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
594 	  .has_alpha = true, },
595 	{ .format = DRM_FORMAT_BGRA8888, .depth = 32, .num_planes = 2,
596 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
597 	  .has_alpha = true, },
598 	{ .format = DRM_FORMAT_XRGB2101010, .depth = 30, .num_planes = 2,
599 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
600 	{ .format = DRM_FORMAT_XBGR2101010, .depth = 30, .num_planes = 2,
601 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
602 	{ .format = DRM_FORMAT_ARGB2101010, .depth = 30, .num_planes = 2,
603 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
604 	  .has_alpha = true, },
605 	{ .format = DRM_FORMAT_ABGR2101010, .depth = 30, .num_planes = 2,
606 	  .cpp = { 4, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
607 	  .has_alpha = true, },
608 	{ .format = DRM_FORMAT_RGB565, .depth = 16, .num_planes = 2,
609 	  .cpp = { 2, 0, }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
610 };
611 
612 static const struct drm_format_info dcc_retile_formats[] = {
613 	{ .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 3,
614 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
615 	 { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 3,
616 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
617 	{ .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 3,
618 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
619 	   .has_alpha = true, },
620 	{ .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 3,
621 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
622 	  .has_alpha = true, },
623 	{ .format = DRM_FORMAT_BGRA8888, .depth = 32, .num_planes = 3,
624 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
625 	  .has_alpha = true, },
626 	{ .format = DRM_FORMAT_XRGB2101010, .depth = 30, .num_planes = 3,
627 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
628 	{ .format = DRM_FORMAT_XBGR2101010, .depth = 30, .num_planes = 3,
629 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
630 	{ .format = DRM_FORMAT_ARGB2101010, .depth = 30, .num_planes = 3,
631 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
632 	  .has_alpha = true, },
633 	{ .format = DRM_FORMAT_ABGR2101010, .depth = 30, .num_planes = 3,
634 	  .cpp = { 4, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1,
635 	  .has_alpha = true, },
636 	{ .format = DRM_FORMAT_RGB565, .depth = 16, .num_planes = 3,
637 	  .cpp = { 2, 0, 0 }, .block_w = {1, 1, 1}, .block_h = {1, 1, 1}, .hsub = 1, .vsub = 1, },
638 };
639 
640 static const struct drm_format_info *
641 lookup_format_info(const struct drm_format_info formats[],
642 		  int num_formats, u32 format)
643 {
644 	int i;
645 
646 	for (i = 0; i < num_formats; i++) {
647 		if (formats[i].format == format)
648 			return &formats[i];
649 	}
650 
651 	return NULL;
652 }
653 
654 const struct drm_format_info *
655 amdgpu_lookup_format_info(u32 format, uint64_t modifier)
656 {
657 	if (!IS_AMD_FMT_MOD(modifier))
658 		return NULL;
659 
660 	if (AMD_FMT_MOD_GET(DCC_RETILE, modifier))
661 		return lookup_format_info(dcc_retile_formats,
662 					  ARRAY_SIZE(dcc_retile_formats),
663 					  format);
664 
665 	if (AMD_FMT_MOD_GET(DCC, modifier))
666 		return lookup_format_info(dcc_formats, ARRAY_SIZE(dcc_formats),
667 					  format);
668 
669 	/* returning NULL will cause the default format structs to be used. */
670 	return NULL;
671 }
672 
673 
674 /*
675  * Tries to extract the renderable DCC offset from the opaque metadata attached
676  * to the buffer.
677  */
678 static int
679 extract_render_dcc_offset(struct amdgpu_device *adev,
680 			  struct drm_gem_object *obj,
681 			  uint64_t *offset)
682 {
683 	struct amdgpu_bo *rbo;
684 	int r = 0;
685 	uint32_t metadata[10]; /* Something that fits a descriptor + header. */
686 	uint32_t size;
687 
688 	rbo = gem_to_amdgpu_bo(obj);
689 	r = amdgpu_bo_reserve(rbo, false);
690 
691 	if (unlikely(r)) {
692 		/* Don't show error message when returning -ERESTARTSYS */
693 		if (r != -ERESTARTSYS)
694 			DRM_ERROR("Unable to reserve buffer: %d\n", r);
695 		return r;
696 	}
697 
698 	r = amdgpu_bo_get_metadata(rbo, metadata, sizeof(metadata), &size, NULL);
699 	amdgpu_bo_unreserve(rbo);
700 
701 	if (r)
702 		return r;
703 
704 	/*
705 	 * The first word is the metadata version, and we need space for at least
706 	 * the version + pci vendor+device id + 8 words for a descriptor.
707 	 */
708 	if (size < 40  || metadata[0] != 1)
709 		return -EINVAL;
710 
711 	if (adev->family >= AMDGPU_FAMILY_NV) {
712 		/* resource word 6/7 META_DATA_ADDRESS{_LO} */
713 		*offset = ((u64)metadata[9] << 16u) |
714 			  ((metadata[8] & 0xFF000000u) >> 16);
715 	} else {
716 		/* resource word 5/7 META_DATA_ADDRESS */
717 		*offset = ((u64)metadata[9] << 8u) |
718 			  ((u64)(metadata[7] & 0x1FE0000u) << 23);
719 	}
720 
721 	return 0;
722 }
723 
724 static int convert_tiling_flags_to_modifier(struct amdgpu_framebuffer *afb)
725 {
726 	struct amdgpu_device *adev = drm_to_adev(afb->base.dev);
727 	uint64_t modifier = 0;
728 	int num_pipes = 0;
729 	int num_pkrs = 0;
730 
731 	num_pkrs = adev->gfx.config.gb_addr_config_fields.num_pkrs;
732 	num_pipes = adev->gfx.config.gb_addr_config_fields.num_pipes;
733 
734 	if (!afb->tiling_flags || !AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE)) {
735 		modifier = DRM_FORMAT_MOD_LINEAR;
736 	} else {
737 		int swizzle = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE);
738 		bool has_xor = swizzle >= 16;
739 		int block_size_bits;
740 		int version;
741 		int pipe_xor_bits = 0;
742 		int bank_xor_bits = 0;
743 		int packers = 0;
744 		int rb = 0;
745 		int pipes = ilog2(num_pipes);
746 		uint32_t dcc_offset = AMDGPU_TILING_GET(afb->tiling_flags, DCC_OFFSET_256B);
747 
748 		switch (swizzle >> 2) {
749 		case 0: /* 256B */
750 			block_size_bits = 8;
751 			break;
752 		case 1: /* 4KiB */
753 		case 5: /* 4KiB _X */
754 			block_size_bits = 12;
755 			break;
756 		case 2: /* 64KiB */
757 		case 4: /* 64 KiB _T */
758 		case 6: /* 64 KiB _X */
759 			block_size_bits = 16;
760 			break;
761 		case 7: /* 256 KiB */
762 			block_size_bits = 18;
763 			break;
764 		default:
765 			/* RESERVED or VAR */
766 			return -EINVAL;
767 		}
768 
769 		if (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0))
770 			version = AMD_FMT_MOD_TILE_VER_GFX11;
771 		else if (amdgpu_ip_version(adev, GC_HWIP, 0) >=
772 			 IP_VERSION(10, 3, 0))
773 			version = AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS;
774 		else if (amdgpu_ip_version(adev, GC_HWIP, 0) >=
775 			 IP_VERSION(10, 0, 0))
776 			version = AMD_FMT_MOD_TILE_VER_GFX10;
777 		else
778 			version = AMD_FMT_MOD_TILE_VER_GFX9;
779 
780 		switch (swizzle & 3) {
781 		case 0: /* Z microtiling */
782 			return -EINVAL;
783 		case 1: /* S microtiling */
784 			if (amdgpu_ip_version(adev, GC_HWIP, 0) <
785 			    IP_VERSION(11, 0, 0)) {
786 				if (!has_xor)
787 					version = AMD_FMT_MOD_TILE_VER_GFX9;
788 			}
789 			break;
790 		case 2:
791 			if (amdgpu_ip_version(adev, GC_HWIP, 0) <
792 			    IP_VERSION(11, 0, 0)) {
793 				if (!has_xor && afb->base.format->cpp[0] != 4)
794 					version = AMD_FMT_MOD_TILE_VER_GFX9;
795 			}
796 			break;
797 		case 3:
798 			break;
799 		}
800 
801 		if (has_xor) {
802 			if (num_pipes == num_pkrs && num_pkrs == 0) {
803 				DRM_ERROR("invalid number of pipes and packers\n");
804 				return -EINVAL;
805 			}
806 
807 			switch (version) {
808 			case AMD_FMT_MOD_TILE_VER_GFX11:
809 				pipe_xor_bits = min(block_size_bits - 8, pipes);
810 				packers = ilog2(adev->gfx.config.gb_addr_config_fields.num_pkrs);
811 				break;
812 			case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
813 				pipe_xor_bits = min(block_size_bits - 8, pipes);
814 				packers = min(block_size_bits - 8 - pipe_xor_bits,
815 					      ilog2(adev->gfx.config.gb_addr_config_fields.num_pkrs));
816 				break;
817 			case AMD_FMT_MOD_TILE_VER_GFX10:
818 				pipe_xor_bits = min(block_size_bits - 8, pipes);
819 				break;
820 			case AMD_FMT_MOD_TILE_VER_GFX9:
821 				rb = ilog2(adev->gfx.config.gb_addr_config_fields.num_se) +
822 				     ilog2(adev->gfx.config.gb_addr_config_fields.num_rb_per_se);
823 				pipe_xor_bits = min(block_size_bits - 8, pipes +
824 						    ilog2(adev->gfx.config.gb_addr_config_fields.num_se));
825 				bank_xor_bits = min(block_size_bits - 8 - pipe_xor_bits,
826 						    ilog2(adev->gfx.config.gb_addr_config_fields.num_banks));
827 				break;
828 			}
829 		}
830 
831 		modifier = AMD_FMT_MOD |
832 			   AMD_FMT_MOD_SET(TILE, AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE)) |
833 			   AMD_FMT_MOD_SET(TILE_VERSION, version) |
834 			   AMD_FMT_MOD_SET(PIPE_XOR_BITS, pipe_xor_bits) |
835 			   AMD_FMT_MOD_SET(BANK_XOR_BITS, bank_xor_bits) |
836 			   AMD_FMT_MOD_SET(PACKERS, packers);
837 
838 		if (dcc_offset != 0) {
839 			bool dcc_i64b = AMDGPU_TILING_GET(afb->tiling_flags, DCC_INDEPENDENT_64B) != 0;
840 			bool dcc_i128b = version >= AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS;
841 			const struct drm_format_info *format_info;
842 			u64 render_dcc_offset;
843 
844 			/* Enable constant encode on RAVEN2 and later. */
845 			bool dcc_constant_encode =
846 				(adev->asic_type > CHIP_RAVEN ||
847 				 (adev->asic_type == CHIP_RAVEN &&
848 				  adev->external_rev_id >= 0x81)) &&
849 				amdgpu_ip_version(adev, GC_HWIP, 0) <
850 					IP_VERSION(11, 0, 0);
851 
852 			int max_cblock_size = dcc_i64b ? AMD_FMT_MOD_DCC_BLOCK_64B :
853 					      dcc_i128b ? AMD_FMT_MOD_DCC_BLOCK_128B :
854 					      AMD_FMT_MOD_DCC_BLOCK_256B;
855 
856 			modifier |= AMD_FMT_MOD_SET(DCC, 1) |
857 				    AMD_FMT_MOD_SET(DCC_CONSTANT_ENCODE, dcc_constant_encode) |
858 				    AMD_FMT_MOD_SET(DCC_INDEPENDENT_64B, dcc_i64b) |
859 				    AMD_FMT_MOD_SET(DCC_INDEPENDENT_128B, dcc_i128b) |
860 				    AMD_FMT_MOD_SET(DCC_MAX_COMPRESSED_BLOCK, max_cblock_size);
861 
862 			afb->base.offsets[1] = dcc_offset * 256 + afb->base.offsets[0];
863 			afb->base.pitches[1] =
864 				AMDGPU_TILING_GET(afb->tiling_flags, DCC_PITCH_MAX) + 1;
865 
866 			/*
867 			 * If the userspace driver uses retiling the tiling flags do not contain
868 			 * info on the renderable DCC buffer. Luckily the opaque metadata contains
869 			 * the info so we can try to extract it. The kernel does not use this info
870 			 * but we should convert it to a modifier plane for getfb2, so the
871 			 * userspace driver that gets it doesn't have to juggle around another DCC
872 			 * plane internally.
873 			 */
874 			if (extract_render_dcc_offset(adev, afb->base.obj[0],
875 						      &render_dcc_offset) == 0 &&
876 			    render_dcc_offset != 0 &&
877 			    render_dcc_offset != afb->base.offsets[1] &&
878 			    render_dcc_offset < UINT_MAX) {
879 				uint32_t dcc_block_bits;  /* of base surface data */
880 
881 				modifier |= AMD_FMT_MOD_SET(DCC_RETILE, 1);
882 				afb->base.offsets[2] = render_dcc_offset;
883 
884 				if (adev->family >= AMDGPU_FAMILY_NV) {
885 					int extra_pipe = 0;
886 
887 					if ((amdgpu_ip_version(adev, GC_HWIP,
888 							       0) >=
889 					     IP_VERSION(10, 3, 0)) &&
890 					    pipes == packers && pipes > 1)
891 						extra_pipe = 1;
892 
893 					dcc_block_bits = max(20, 16 + pipes + extra_pipe);
894 				} else {
895 					modifier |= AMD_FMT_MOD_SET(RB, rb) |
896 						    AMD_FMT_MOD_SET(PIPE, pipes);
897 					dcc_block_bits = max(20, 18 + rb);
898 				}
899 
900 				dcc_block_bits -= ilog2(afb->base.format->cpp[0]);
901 				afb->base.pitches[2] = ALIGN(afb->base.width,
902 							     1u << ((dcc_block_bits + 1) / 2));
903 			}
904 			format_info = amdgpu_lookup_format_info(afb->base.format->format,
905 								modifier);
906 			if (!format_info)
907 				return -EINVAL;
908 
909 			afb->base.format = format_info;
910 		}
911 	}
912 
913 	afb->base.modifier = modifier;
914 	afb->base.flags |= DRM_MODE_FB_MODIFIERS;
915 	return 0;
916 }
917 
918 /* Mirrors the is_displayable check in radeonsi's gfx6_compute_surface */
919 static int check_tiling_flags_gfx6(struct amdgpu_framebuffer *afb)
920 {
921 	u64 micro_tile_mode;
922 
923 	/* Zero swizzle mode means linear */
924 	if (AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0)
925 		return 0;
926 
927 	micro_tile_mode = AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE);
928 	switch (micro_tile_mode) {
929 	case 0: /* DISPLAY */
930 	case 3: /* RENDER */
931 		return 0;
932 	default:
933 		drm_dbg_kms(afb->base.dev,
934 			    "Micro tile mode %llu not supported for scanout\n",
935 			    micro_tile_mode);
936 		return -EINVAL;
937 	}
938 }
939 
940 static void get_block_dimensions(unsigned int block_log2, unsigned int cpp,
941 				 unsigned int *width, unsigned int *height)
942 {
943 	unsigned int cpp_log2 = ilog2(cpp);
944 	unsigned int pixel_log2 = block_log2 - cpp_log2;
945 	unsigned int width_log2 = (pixel_log2 + 1) / 2;
946 	unsigned int height_log2 = pixel_log2 - width_log2;
947 
948 	*width = 1 << width_log2;
949 	*height = 1 << height_log2;
950 }
951 
952 static unsigned int get_dcc_block_size(uint64_t modifier, bool rb_aligned,
953 				       bool pipe_aligned)
954 {
955 	unsigned int ver = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
956 
957 	switch (ver) {
958 	case AMD_FMT_MOD_TILE_VER_GFX9: {
959 		/*
960 		 * TODO: for pipe aligned we may need to check the alignment of the
961 		 * total size of the surface, which may need to be bigger than the
962 		 * natural alignment due to some HW workarounds
963 		 */
964 		return max(10 + (rb_aligned ? (int)AMD_FMT_MOD_GET(RB, modifier) : 0), 12);
965 	}
966 	case AMD_FMT_MOD_TILE_VER_GFX10:
967 	case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
968 	case AMD_FMT_MOD_TILE_VER_GFX11: {
969 		int pipes_log2 = AMD_FMT_MOD_GET(PIPE_XOR_BITS, modifier);
970 
971 		if (ver >= AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS && pipes_log2 > 1 &&
972 		    AMD_FMT_MOD_GET(PACKERS, modifier) == pipes_log2)
973 			++pipes_log2;
974 
975 		return max(8 + (pipe_aligned ? pipes_log2 : 0), 12);
976 	}
977 	default:
978 		return 0;
979 	}
980 }
981 
982 static int amdgpu_display_verify_plane(struct amdgpu_framebuffer *rfb, int plane,
983 				       const struct drm_format_info *format,
984 				       unsigned int block_width, unsigned int block_height,
985 				       unsigned int block_size_log2)
986 {
987 	unsigned int width = rfb->base.width /
988 		((plane && plane < format->num_planes) ? format->hsub : 1);
989 	unsigned int height = rfb->base.height /
990 		((plane && plane < format->num_planes) ? format->vsub : 1);
991 	unsigned int cpp = plane < format->num_planes ? format->cpp[plane] : 1;
992 	unsigned int block_pitch = block_width * cpp;
993 	unsigned int min_pitch = ALIGN(width * cpp, block_pitch);
994 	unsigned int block_size = 1 << block_size_log2;
995 	uint64_t size;
996 
997 	if (rfb->base.pitches[plane] % block_pitch) {
998 		drm_dbg_kms(rfb->base.dev,
999 			    "pitch %d for plane %d is not a multiple of block pitch %d\n",
1000 			    rfb->base.pitches[plane], plane, block_pitch);
1001 		return -EINVAL;
1002 	}
1003 	if (rfb->base.pitches[plane] < min_pitch) {
1004 		drm_dbg_kms(rfb->base.dev,
1005 			    "pitch %d for plane %d is less than minimum pitch %d\n",
1006 			    rfb->base.pitches[plane], plane, min_pitch);
1007 		return -EINVAL;
1008 	}
1009 
1010 	/* Force at least natural alignment. */
1011 	if (rfb->base.offsets[plane] % block_size) {
1012 		drm_dbg_kms(rfb->base.dev,
1013 			    "offset 0x%x for plane %d is not a multiple of block pitch 0x%x\n",
1014 			    rfb->base.offsets[plane], plane, block_size);
1015 		return -EINVAL;
1016 	}
1017 
1018 	size = rfb->base.offsets[plane] +
1019 		(uint64_t)rfb->base.pitches[plane] / block_pitch *
1020 		block_size * DIV_ROUND_UP(height, block_height);
1021 
1022 	if (rfb->base.obj[0]->size < size) {
1023 		drm_dbg_kms(rfb->base.dev,
1024 			    "BO size 0x%zx is less than 0x%llx required for plane %d\n",
1025 			    rfb->base.obj[0]->size, size, plane);
1026 		return -EINVAL;
1027 	}
1028 
1029 	return 0;
1030 }
1031 
1032 
1033 static int amdgpu_display_verify_sizes(struct amdgpu_framebuffer *rfb)
1034 {
1035 	const struct drm_format_info *format_info = drm_format_info(rfb->base.format->format);
1036 	uint64_t modifier = rfb->base.modifier;
1037 	int ret;
1038 	unsigned int i, block_width, block_height, block_size_log2;
1039 
1040 	if (rfb->base.dev->mode_config.fb_modifiers_not_supported)
1041 		return 0;
1042 
1043 	for (i = 0; i < format_info->num_planes; ++i) {
1044 		if (modifier == DRM_FORMAT_MOD_LINEAR) {
1045 			block_width = 256 / format_info->cpp[i];
1046 			block_height = 1;
1047 			block_size_log2 = 8;
1048 		} else {
1049 			int swizzle = AMD_FMT_MOD_GET(TILE, modifier);
1050 
1051 			switch ((swizzle & ~3) + 1) {
1052 			case DC_SW_256B_S:
1053 				block_size_log2 = 8;
1054 				break;
1055 			case DC_SW_4KB_S:
1056 			case DC_SW_4KB_S_X:
1057 				block_size_log2 = 12;
1058 				break;
1059 			case DC_SW_64KB_S:
1060 			case DC_SW_64KB_S_T:
1061 			case DC_SW_64KB_S_X:
1062 				block_size_log2 = 16;
1063 				break;
1064 			case DC_SW_VAR_S_X:
1065 				block_size_log2 = 18;
1066 				break;
1067 			default:
1068 				drm_dbg_kms(rfb->base.dev,
1069 					    "Swizzle mode with unknown block size: %d\n", swizzle);
1070 				return -EINVAL;
1071 			}
1072 
1073 			get_block_dimensions(block_size_log2, format_info->cpp[i],
1074 					     &block_width, &block_height);
1075 		}
1076 
1077 		ret = amdgpu_display_verify_plane(rfb, i, format_info,
1078 						  block_width, block_height, block_size_log2);
1079 		if (ret)
1080 			return ret;
1081 	}
1082 
1083 	if (AMD_FMT_MOD_GET(DCC, modifier)) {
1084 		if (AMD_FMT_MOD_GET(DCC_RETILE, modifier)) {
1085 			block_size_log2 = get_dcc_block_size(modifier, false, false);
1086 			get_block_dimensions(block_size_log2 + 8, format_info->cpp[0],
1087 					     &block_width, &block_height);
1088 			ret = amdgpu_display_verify_plane(rfb, i, format_info,
1089 							  block_width, block_height,
1090 							  block_size_log2);
1091 			if (ret)
1092 				return ret;
1093 
1094 			++i;
1095 			block_size_log2 = get_dcc_block_size(modifier, true, true);
1096 		} else {
1097 			bool pipe_aligned = AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier);
1098 
1099 			block_size_log2 = get_dcc_block_size(modifier, true, pipe_aligned);
1100 		}
1101 		get_block_dimensions(block_size_log2 + 8, format_info->cpp[0],
1102 				     &block_width, &block_height);
1103 		ret = amdgpu_display_verify_plane(rfb, i, format_info,
1104 						  block_width, block_height, block_size_log2);
1105 		if (ret)
1106 			return ret;
1107 	}
1108 
1109 	return 0;
1110 }
1111 
1112 static int amdgpu_display_get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
1113 				      uint64_t *tiling_flags, bool *tmz_surface)
1114 {
1115 	struct amdgpu_bo *rbo;
1116 	int r;
1117 
1118 	if (!amdgpu_fb) {
1119 		*tiling_flags = 0;
1120 		*tmz_surface = false;
1121 		return 0;
1122 	}
1123 
1124 	rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
1125 	r = amdgpu_bo_reserve(rbo, false);
1126 
1127 	if (unlikely(r)) {
1128 		/* Don't show error message when returning -ERESTARTSYS */
1129 		if (r != -ERESTARTSYS)
1130 			DRM_ERROR("Unable to reserve buffer: %d\n", r);
1131 		return r;
1132 	}
1133 
1134 	if (tiling_flags)
1135 		amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
1136 
1137 	if (tmz_surface)
1138 		*tmz_surface = amdgpu_bo_encrypted(rbo);
1139 
1140 	amdgpu_bo_unreserve(rbo);
1141 
1142 	return r;
1143 }
1144 
1145 static int amdgpu_display_gem_fb_verify_and_init(struct drm_device *dev,
1146 						 struct amdgpu_framebuffer *rfb,
1147 						 struct drm_file *file_priv,
1148 						 const struct drm_mode_fb_cmd2 *mode_cmd,
1149 						 struct drm_gem_object *obj)
1150 {
1151 	int ret;
1152 
1153 	rfb->base.obj[0] = obj;
1154 	drm_helper_mode_fill_fb_struct(dev, &rfb->base, mode_cmd);
1155 	/* Verify that the modifier is supported. */
1156 	if (!drm_any_plane_has_format(dev, mode_cmd->pixel_format,
1157 				      mode_cmd->modifier[0])) {
1158 		drm_dbg_kms(dev,
1159 			    "unsupported pixel format %p4cc / modifier 0x%llx\n",
1160 			    &mode_cmd->pixel_format, mode_cmd->modifier[0]);
1161 
1162 		ret = -EINVAL;
1163 		goto err;
1164 	}
1165 
1166 	ret = amdgpu_display_framebuffer_init(dev, rfb, mode_cmd, obj);
1167 	if (ret)
1168 		goto err;
1169 
1170 	if (drm_drv_uses_atomic_modeset(dev))
1171 		ret = drm_framebuffer_init(dev, &rfb->base,
1172 					   &amdgpu_fb_funcs_atomic);
1173 	else
1174 		ret = drm_framebuffer_init(dev, &rfb->base, &amdgpu_fb_funcs);
1175 
1176 	if (ret)
1177 		goto err;
1178 
1179 	return 0;
1180 err:
1181 	drm_dbg_kms(dev, "Failed to verify and init gem fb: %d\n", ret);
1182 	rfb->base.obj[0] = NULL;
1183 	return ret;
1184 }
1185 
1186 static int amdgpu_display_framebuffer_init(struct drm_device *dev,
1187 					   struct amdgpu_framebuffer *rfb,
1188 					   const struct drm_mode_fb_cmd2 *mode_cmd,
1189 					   struct drm_gem_object *obj)
1190 {
1191 	struct amdgpu_device *adev = drm_to_adev(dev);
1192 	int ret, i;
1193 
1194 	/*
1195 	 * This needs to happen before modifier conversion as that might change
1196 	 * the number of planes.
1197 	 */
1198 	for (i = 1; i < rfb->base.format->num_planes; ++i) {
1199 		if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
1200 			drm_dbg_kms(dev, "Plane 0 and %d have different BOs: %u vs. %u\n",
1201 				    i, mode_cmd->handles[0], mode_cmd->handles[i]);
1202 			ret = -EINVAL;
1203 			return ret;
1204 		}
1205 	}
1206 
1207 	ret = amdgpu_display_get_fb_info(rfb, &rfb->tiling_flags, &rfb->tmz_surface);
1208 	if (ret)
1209 		return ret;
1210 
1211 	if (dev->mode_config.fb_modifiers_not_supported && !adev->enable_virtual_display) {
1212 		drm_WARN_ONCE(dev, adev->family >= AMDGPU_FAMILY_AI,
1213 			      "GFX9+ requires FB check based on format modifier\n");
1214 		ret = check_tiling_flags_gfx6(rfb);
1215 		if (ret)
1216 			return ret;
1217 	}
1218 
1219 	if (!dev->mode_config.fb_modifiers_not_supported &&
1220 	    !(rfb->base.flags & DRM_MODE_FB_MODIFIERS)) {
1221 		ret = convert_tiling_flags_to_modifier(rfb);
1222 		if (ret) {
1223 			drm_dbg_kms(dev, "Failed to convert tiling flags 0x%llX to a modifier",
1224 				    rfb->tiling_flags);
1225 			return ret;
1226 		}
1227 	}
1228 
1229 	ret = amdgpu_display_verify_sizes(rfb);
1230 	if (ret)
1231 		return ret;
1232 
1233 	for (i = 0; i < rfb->base.format->num_planes; ++i) {
1234 		drm_gem_object_get(rfb->base.obj[0]);
1235 		rfb->base.obj[i] = rfb->base.obj[0];
1236 	}
1237 
1238 	return 0;
1239 }
1240 
1241 struct drm_framebuffer *
1242 amdgpu_display_user_framebuffer_create(struct drm_device *dev,
1243 				       struct drm_file *file_priv,
1244 				       const struct drm_mode_fb_cmd2 *mode_cmd)
1245 {
1246 	struct amdgpu_framebuffer *amdgpu_fb;
1247 	struct drm_gem_object *obj;
1248 	struct amdgpu_bo *bo;
1249 	uint32_t domains;
1250 	int ret;
1251 
1252 	obj = drm_gem_object_lookup(file_priv, mode_cmd->handles[0]);
1253 	if (obj ==  NULL) {
1254 		drm_dbg_kms(dev,
1255 			    "No GEM object associated to handle 0x%08X, can't create framebuffer\n",
1256 			    mode_cmd->handles[0]);
1257 
1258 		return ERR_PTR(-ENOENT);
1259 	}
1260 
1261 	/* Handle is imported dma-buf, so cannot be migrated to VRAM for scanout */
1262 	bo = gem_to_amdgpu_bo(obj);
1263 	domains = amdgpu_display_supported_domains(drm_to_adev(dev), bo->flags);
1264 	if (obj->import_attach && !(domains & AMDGPU_GEM_DOMAIN_GTT)) {
1265 		drm_dbg_kms(dev, "Cannot create framebuffer from imported dma_buf\n");
1266 		drm_gem_object_put(obj);
1267 		return ERR_PTR(-EINVAL);
1268 	}
1269 
1270 	amdgpu_fb = kzalloc(sizeof(*amdgpu_fb), GFP_KERNEL);
1271 	if (amdgpu_fb == NULL) {
1272 		drm_gem_object_put(obj);
1273 		return ERR_PTR(-ENOMEM);
1274 	}
1275 
1276 	ret = amdgpu_display_gem_fb_verify_and_init(dev, amdgpu_fb, file_priv,
1277 						    mode_cmd, obj);
1278 	if (ret) {
1279 		kfree(amdgpu_fb);
1280 		drm_gem_object_put(obj);
1281 		return ERR_PTR(ret);
1282 	}
1283 
1284 	drm_gem_object_put(obj);
1285 	return &amdgpu_fb->base;
1286 }
1287 
1288 const struct drm_mode_config_funcs amdgpu_mode_funcs = {
1289 	.fb_create = amdgpu_display_user_framebuffer_create,
1290 };
1291 
1292 static const struct drm_prop_enum_list amdgpu_underscan_enum_list[] = {
1293 	{ UNDERSCAN_OFF, "off" },
1294 	{ UNDERSCAN_ON, "on" },
1295 	{ UNDERSCAN_AUTO, "auto" },
1296 };
1297 
1298 static const struct drm_prop_enum_list amdgpu_audio_enum_list[] = {
1299 	{ AMDGPU_AUDIO_DISABLE, "off" },
1300 	{ AMDGPU_AUDIO_ENABLE, "on" },
1301 	{ AMDGPU_AUDIO_AUTO, "auto" },
1302 };
1303 
1304 /* XXX support different dither options? spatial, temporal, both, etc. */
1305 static const struct drm_prop_enum_list amdgpu_dither_enum_list[] = {
1306 	{ AMDGPU_FMT_DITHER_DISABLE, "off" },
1307 	{ AMDGPU_FMT_DITHER_ENABLE, "on" },
1308 };
1309 
1310 int amdgpu_display_modeset_create_props(struct amdgpu_device *adev)
1311 {
1312 	int sz;
1313 
1314 	adev->mode_info.coherent_mode_property =
1315 		drm_property_create_range(adev_to_drm(adev), 0, "coherent", 0, 1);
1316 	if (!adev->mode_info.coherent_mode_property)
1317 		return -ENOMEM;
1318 
1319 	adev->mode_info.load_detect_property =
1320 		drm_property_create_range(adev_to_drm(adev), 0, "load detection", 0, 1);
1321 	if (!adev->mode_info.load_detect_property)
1322 		return -ENOMEM;
1323 
1324 	drm_mode_create_scaling_mode_property(adev_to_drm(adev));
1325 
1326 	sz = ARRAY_SIZE(amdgpu_underscan_enum_list);
1327 	adev->mode_info.underscan_property =
1328 		drm_property_create_enum(adev_to_drm(adev), 0,
1329 					 "underscan",
1330 					 amdgpu_underscan_enum_list, sz);
1331 
1332 	adev->mode_info.underscan_hborder_property =
1333 		drm_property_create_range(adev_to_drm(adev), 0,
1334 					  "underscan hborder", 0, 128);
1335 	if (!adev->mode_info.underscan_hborder_property)
1336 		return -ENOMEM;
1337 
1338 	adev->mode_info.underscan_vborder_property =
1339 		drm_property_create_range(adev_to_drm(adev), 0,
1340 					  "underscan vborder", 0, 128);
1341 	if (!adev->mode_info.underscan_vborder_property)
1342 		return -ENOMEM;
1343 
1344 	sz = ARRAY_SIZE(amdgpu_audio_enum_list);
1345 	adev->mode_info.audio_property =
1346 		drm_property_create_enum(adev_to_drm(adev), 0,
1347 					 "audio",
1348 					 amdgpu_audio_enum_list, sz);
1349 
1350 	sz = ARRAY_SIZE(amdgpu_dither_enum_list);
1351 	adev->mode_info.dither_property =
1352 		drm_property_create_enum(adev_to_drm(adev), 0,
1353 					 "dither",
1354 					 amdgpu_dither_enum_list, sz);
1355 
1356 	if (adev->dc_enabled) {
1357 		adev->mode_info.abm_level_property =
1358 			drm_property_create_range(adev_to_drm(adev), 0,
1359 						  "abm level", 0, 4);
1360 		if (!adev->mode_info.abm_level_property)
1361 			return -ENOMEM;
1362 	}
1363 
1364 	return 0;
1365 }
1366 
1367 void amdgpu_display_update_priority(struct amdgpu_device *adev)
1368 {
1369 	/* adjustment options for the display watermarks */
1370 	if ((amdgpu_disp_priority == 0) || (amdgpu_disp_priority > 2))
1371 		adev->mode_info.disp_priority = 0;
1372 	else
1373 		adev->mode_info.disp_priority = amdgpu_disp_priority;
1374 
1375 }
1376 
1377 static bool amdgpu_display_is_hdtv_mode(const struct drm_display_mode *mode)
1378 {
1379 	/* try and guess if this is a tv or a monitor */
1380 	if ((mode->vdisplay == 480 && mode->hdisplay == 720) || /* 480p */
1381 	    (mode->vdisplay == 576) || /* 576p */
1382 	    (mode->vdisplay == 720) || /* 720p */
1383 	    (mode->vdisplay == 1080)) /* 1080p */
1384 		return true;
1385 	else
1386 		return false;
1387 }
1388 
1389 bool amdgpu_display_crtc_scaling_mode_fixup(struct drm_crtc *crtc,
1390 					const struct drm_display_mode *mode,
1391 					struct drm_display_mode *adjusted_mode)
1392 {
1393 	struct drm_device *dev = crtc->dev;
1394 	struct drm_encoder *encoder;
1395 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
1396 	struct amdgpu_encoder *amdgpu_encoder;
1397 	struct drm_connector *connector;
1398 	u32 src_v = 1, dst_v = 1;
1399 	u32 src_h = 1, dst_h = 1;
1400 
1401 	amdgpu_crtc->h_border = 0;
1402 	amdgpu_crtc->v_border = 0;
1403 
1404 	list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
1405 		if (encoder->crtc != crtc)
1406 			continue;
1407 		amdgpu_encoder = to_amdgpu_encoder(encoder);
1408 		connector = amdgpu_get_connector_for_encoder(encoder);
1409 
1410 		/* set scaling */
1411 		if (amdgpu_encoder->rmx_type == RMX_OFF)
1412 			amdgpu_crtc->rmx_type = RMX_OFF;
1413 		else if (mode->hdisplay < amdgpu_encoder->native_mode.hdisplay ||
1414 			 mode->vdisplay < amdgpu_encoder->native_mode.vdisplay)
1415 			amdgpu_crtc->rmx_type = amdgpu_encoder->rmx_type;
1416 		else
1417 			amdgpu_crtc->rmx_type = RMX_OFF;
1418 		/* copy native mode */
1419 		memcpy(&amdgpu_crtc->native_mode,
1420 		       &amdgpu_encoder->native_mode,
1421 		       sizeof(struct drm_display_mode));
1422 		src_v = crtc->mode.vdisplay;
1423 		dst_v = amdgpu_crtc->native_mode.vdisplay;
1424 		src_h = crtc->mode.hdisplay;
1425 		dst_h = amdgpu_crtc->native_mode.hdisplay;
1426 
1427 		/* fix up for overscan on hdmi */
1428 		if ((!(mode->flags & DRM_MODE_FLAG_INTERLACE)) &&
1429 		    ((amdgpu_encoder->underscan_type == UNDERSCAN_ON) ||
1430 		     ((amdgpu_encoder->underscan_type == UNDERSCAN_AUTO) &&
1431 		      connector->display_info.is_hdmi &&
1432 		      amdgpu_display_is_hdtv_mode(mode)))) {
1433 			if (amdgpu_encoder->underscan_hborder != 0)
1434 				amdgpu_crtc->h_border = amdgpu_encoder->underscan_hborder;
1435 			else
1436 				amdgpu_crtc->h_border = (mode->hdisplay >> 5) + 16;
1437 			if (amdgpu_encoder->underscan_vborder != 0)
1438 				amdgpu_crtc->v_border = amdgpu_encoder->underscan_vborder;
1439 			else
1440 				amdgpu_crtc->v_border = (mode->vdisplay >> 5) + 16;
1441 			amdgpu_crtc->rmx_type = RMX_FULL;
1442 			src_v = crtc->mode.vdisplay;
1443 			dst_v = crtc->mode.vdisplay - (amdgpu_crtc->v_border * 2);
1444 			src_h = crtc->mode.hdisplay;
1445 			dst_h = crtc->mode.hdisplay - (amdgpu_crtc->h_border * 2);
1446 		}
1447 	}
1448 	if (amdgpu_crtc->rmx_type != RMX_OFF) {
1449 		fixed20_12 a, b;
1450 
1451 		a.full = dfixed_const(src_v);
1452 		b.full = dfixed_const(dst_v);
1453 		amdgpu_crtc->vsc.full = dfixed_div(a, b);
1454 		a.full = dfixed_const(src_h);
1455 		b.full = dfixed_const(dst_h);
1456 		amdgpu_crtc->hsc.full = dfixed_div(a, b);
1457 	} else {
1458 		amdgpu_crtc->vsc.full = dfixed_const(1);
1459 		amdgpu_crtc->hsc.full = dfixed_const(1);
1460 	}
1461 	return true;
1462 }
1463 
1464 /*
1465  * Retrieve current video scanout position of crtc on a given gpu, and
1466  * an optional accurate timestamp of when query happened.
1467  *
1468  * \param dev Device to query.
1469  * \param pipe Crtc to query.
1470  * \param flags from caller (DRM_CALLED_FROM_VBLIRQ or 0).
1471  *              For driver internal use only also supports these flags:
1472  *
1473  *              USE_REAL_VBLANKSTART to use the real start of vblank instead
1474  *              of a fudged earlier start of vblank.
1475  *
1476  *              GET_DISTANCE_TO_VBLANKSTART to return distance to the
1477  *              fudged earlier start of vblank in *vpos and the distance
1478  *              to true start of vblank in *hpos.
1479  *
1480  * \param *vpos Location where vertical scanout position should be stored.
1481  * \param *hpos Location where horizontal scanout position should go.
1482  * \param *stime Target location for timestamp taken immediately before
1483  *               scanout position query. Can be NULL to skip timestamp.
1484  * \param *etime Target location for timestamp taken immediately after
1485  *               scanout position query. Can be NULL to skip timestamp.
1486  *
1487  * Returns vpos as a positive number while in active scanout area.
1488  * Returns vpos as a negative number inside vblank, counting the number
1489  * of scanlines to go until end of vblank, e.g., -1 means "one scanline
1490  * until start of active scanout / end of vblank."
1491  *
1492  * \return Flags, or'ed together as follows:
1493  *
1494  * DRM_SCANOUTPOS_VALID = Query successful.
1495  * DRM_SCANOUTPOS_INVBL = Inside vblank.
1496  * DRM_SCANOUTPOS_ACCURATE = Returned position is accurate. A lack of
1497  * this flag means that returned position may be offset by a constant but
1498  * unknown small number of scanlines wrt. real scanout position.
1499  *
1500  */
1501 int amdgpu_display_get_crtc_scanoutpos(struct drm_device *dev,
1502 			unsigned int pipe, unsigned int flags, int *vpos,
1503 			int *hpos, ktime_t *stime, ktime_t *etime,
1504 			const struct drm_display_mode *mode)
1505 {
1506 	u32 vbl = 0, position = 0;
1507 	int vbl_start, vbl_end, vtotal, ret = 0;
1508 	bool in_vbl = true;
1509 
1510 	struct amdgpu_device *adev = drm_to_adev(dev);
1511 
1512 	/* preempt_disable_rt() should go right here in PREEMPT_RT patchset. */
1513 
1514 	/* Get optional system timestamp before query. */
1515 	if (stime)
1516 		*stime = ktime_get();
1517 
1518 	if (amdgpu_display_page_flip_get_scanoutpos(adev, pipe, &vbl, &position) == 0)
1519 		ret |= DRM_SCANOUTPOS_VALID;
1520 
1521 	/* Get optional system timestamp after query. */
1522 	if (etime)
1523 		*etime = ktime_get();
1524 
1525 	/* preempt_enable_rt() should go right here in PREEMPT_RT patchset. */
1526 
1527 	/* Decode into vertical and horizontal scanout position. */
1528 	*vpos = position & 0x1fff;
1529 	*hpos = (position >> 16) & 0x1fff;
1530 
1531 	/* Valid vblank area boundaries from gpu retrieved? */
1532 	if (vbl > 0) {
1533 		/* Yes: Decode. */
1534 		ret |= DRM_SCANOUTPOS_ACCURATE;
1535 		vbl_start = vbl & 0x1fff;
1536 		vbl_end = (vbl >> 16) & 0x1fff;
1537 	} else {
1538 		/* No: Fake something reasonable which gives at least ok results. */
1539 		vbl_start = mode->crtc_vdisplay;
1540 		vbl_end = 0;
1541 	}
1542 
1543 	/* Called from driver internal vblank counter query code? */
1544 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
1545 		/* Caller wants distance from real vbl_start in *hpos */
1546 		*hpos = *vpos - vbl_start;
1547 	}
1548 
1549 	/* Fudge vblank to start a few scanlines earlier to handle the
1550 	 * problem that vblank irqs fire a few scanlines before start
1551 	 * of vblank. Some driver internal callers need the true vblank
1552 	 * start to be used and signal this via the USE_REAL_VBLANKSTART flag.
1553 	 *
1554 	 * The cause of the "early" vblank irq is that the irq is triggered
1555 	 * by the line buffer logic when the line buffer read position enters
1556 	 * the vblank, whereas our crtc scanout position naturally lags the
1557 	 * line buffer read position.
1558 	 */
1559 	if (!(flags & USE_REAL_VBLANKSTART))
1560 		vbl_start -= adev->mode_info.crtcs[pipe]->lb_vblank_lead_lines;
1561 
1562 	/* Test scanout position against vblank region. */
1563 	if ((*vpos < vbl_start) && (*vpos >= vbl_end))
1564 		in_vbl = false;
1565 
1566 	/* In vblank? */
1567 	if (in_vbl)
1568 		ret |= DRM_SCANOUTPOS_IN_VBLANK;
1569 
1570 	/* Called from driver internal vblank counter query code? */
1571 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
1572 		/* Caller wants distance from fudged earlier vbl_start */
1573 		*vpos -= vbl_start;
1574 		return ret;
1575 	}
1576 
1577 	/* Check if inside vblank area and apply corrective offsets:
1578 	 * vpos will then be >=0 in video scanout area, but negative
1579 	 * within vblank area, counting down the number of lines until
1580 	 * start of scanout.
1581 	 */
1582 
1583 	/* Inside "upper part" of vblank area? Apply corrective offset if so: */
1584 	if (in_vbl && (*vpos >= vbl_start)) {
1585 		vtotal = mode->crtc_vtotal;
1586 
1587 		/* With variable refresh rate displays the vpos can exceed
1588 		 * the vtotal value. Clamp to 0 to return -vbl_end instead
1589 		 * of guessing the remaining number of lines until scanout.
1590 		 */
1591 		*vpos = (*vpos < vtotal) ? (*vpos - vtotal) : 0;
1592 	}
1593 
1594 	/* Correct for shifted end of vbl at vbl_end. */
1595 	*vpos = *vpos - vbl_end;
1596 
1597 	return ret;
1598 }
1599 
1600 int amdgpu_display_crtc_idx_to_irq_type(struct amdgpu_device *adev, int crtc)
1601 {
1602 	if (crtc < 0 || crtc >= adev->mode_info.num_crtc)
1603 		return AMDGPU_CRTC_IRQ_NONE;
1604 
1605 	switch (crtc) {
1606 	case 0:
1607 		return AMDGPU_CRTC_IRQ_VBLANK1;
1608 	case 1:
1609 		return AMDGPU_CRTC_IRQ_VBLANK2;
1610 	case 2:
1611 		return AMDGPU_CRTC_IRQ_VBLANK3;
1612 	case 3:
1613 		return AMDGPU_CRTC_IRQ_VBLANK4;
1614 	case 4:
1615 		return AMDGPU_CRTC_IRQ_VBLANK5;
1616 	case 5:
1617 		return AMDGPU_CRTC_IRQ_VBLANK6;
1618 	default:
1619 		return AMDGPU_CRTC_IRQ_NONE;
1620 	}
1621 }
1622 
1623 bool amdgpu_crtc_get_scanout_position(struct drm_crtc *crtc,
1624 			bool in_vblank_irq, int *vpos,
1625 			int *hpos, ktime_t *stime, ktime_t *etime,
1626 			const struct drm_display_mode *mode)
1627 {
1628 	struct drm_device *dev = crtc->dev;
1629 	unsigned int pipe = crtc->index;
1630 
1631 	return amdgpu_display_get_crtc_scanoutpos(dev, pipe, 0, vpos, hpos,
1632 						  stime, etime, mode);
1633 }
1634 
1635 static bool
1636 amdgpu_display_robj_is_fb(struct amdgpu_device *adev, struct amdgpu_bo *robj)
1637 {
1638 	struct drm_device *dev = adev_to_drm(adev);
1639 	struct drm_fb_helper *fb_helper = dev->fb_helper;
1640 
1641 	if (!fb_helper || !fb_helper->buffer)
1642 		return false;
1643 
1644 	if (gem_to_amdgpu_bo(fb_helper->buffer->gem) != robj)
1645 		return false;
1646 
1647 	return true;
1648 }
1649 
1650 int amdgpu_display_suspend_helper(struct amdgpu_device *adev)
1651 {
1652 	struct drm_device *dev = adev_to_drm(adev);
1653 	struct drm_crtc *crtc;
1654 	struct drm_connector *connector;
1655 	struct drm_connector_list_iter iter;
1656 	int r;
1657 
1658 	drm_kms_helper_poll_disable(dev);
1659 
1660 	/* turn off display hw */
1661 	drm_modeset_lock_all(dev);
1662 	drm_connector_list_iter_begin(dev, &iter);
1663 	drm_for_each_connector_iter(connector, &iter)
1664 		drm_helper_connector_dpms(connector,
1665 					  DRM_MODE_DPMS_OFF);
1666 	drm_connector_list_iter_end(&iter);
1667 	drm_modeset_unlock_all(dev);
1668 	/* unpin the front buffers and cursors */
1669 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
1670 		struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
1671 		struct drm_framebuffer *fb = crtc->primary->fb;
1672 		struct amdgpu_bo *robj;
1673 
1674 		if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
1675 			struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
1676 
1677 			r = amdgpu_bo_reserve(aobj, true);
1678 			if (r == 0) {
1679 				amdgpu_bo_unpin(aobj);
1680 				amdgpu_bo_unreserve(aobj);
1681 			}
1682 		}
1683 
1684 		if (!fb || !fb->obj[0])
1685 			continue;
1686 
1687 		robj = gem_to_amdgpu_bo(fb->obj[0]);
1688 		if (!amdgpu_display_robj_is_fb(adev, robj)) {
1689 			r = amdgpu_bo_reserve(robj, true);
1690 			if (r == 0) {
1691 				amdgpu_bo_unpin(robj);
1692 				amdgpu_bo_unreserve(robj);
1693 			}
1694 		}
1695 	}
1696 	return 0;
1697 }
1698 
1699 int amdgpu_display_resume_helper(struct amdgpu_device *adev)
1700 {
1701 	struct drm_device *dev = adev_to_drm(adev);
1702 	struct drm_connector *connector;
1703 	struct drm_connector_list_iter iter;
1704 	struct drm_crtc *crtc;
1705 	int r;
1706 
1707 	/* pin cursors */
1708 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
1709 		struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
1710 
1711 		if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
1712 			struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
1713 
1714 			r = amdgpu_bo_reserve(aobj, true);
1715 			if (r == 0) {
1716 				r = amdgpu_bo_pin(aobj, AMDGPU_GEM_DOMAIN_VRAM);
1717 				if (r != 0)
1718 					dev_err(adev->dev, "Failed to pin cursor BO (%d)\n", r);
1719 				amdgpu_crtc->cursor_addr = amdgpu_bo_gpu_offset(aobj);
1720 				amdgpu_bo_unreserve(aobj);
1721 			}
1722 		}
1723 	}
1724 
1725 	drm_helper_resume_force_mode(dev);
1726 
1727 	/* turn on display hw */
1728 	drm_modeset_lock_all(dev);
1729 
1730 	drm_connector_list_iter_begin(dev, &iter);
1731 	drm_for_each_connector_iter(connector, &iter)
1732 		drm_helper_connector_dpms(connector,
1733 					  DRM_MODE_DPMS_ON);
1734 	drm_connector_list_iter_end(&iter);
1735 
1736 	drm_modeset_unlock_all(dev);
1737 
1738 	drm_kms_helper_poll_enable(dev);
1739 
1740 	return 0;
1741 }
1742 
1743