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