xref: /netbsd-src/sys/external/bsd/drm2/dist/drm/amd/amdgpu/amdgpu_display.c (revision f3cfa6f6ce31685c6c4a758bc430e69eb99f50a4)
1 /*	$NetBSD: amdgpu_display.c,v 1.5 2019/02/23 19:56:51 kamil Exp $	*/
2 
3 /*
4  * Copyright 2007-8 Advanced Micro Devices, Inc.
5  * Copyright 2008 Red Hat Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
21  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23  * OTHER DEALINGS IN THE SOFTWARE.
24  *
25  * Authors: Dave Airlie
26  *          Alex Deucher
27  */
28 #include <sys/cdefs.h>
29 __KERNEL_RCSID(0, "$NetBSD: amdgpu_display.c,v 1.5 2019/02/23 19:56:51 kamil Exp $");
30 
31 #include <drm/drmP.h>
32 #include <drm/amdgpu_drm.h>
33 #include "amdgpu.h"
34 #include "amdgpu_i2c.h"
35 #include "atom.h"
36 #include "amdgpu_connectors.h"
37 #include <asm/div64.h>
38 
39 #include <linux/pm_runtime.h>
40 #include <drm/drm_crtc_helper.h>
41 #include <drm/drm_edid.h>
42 
43 static void amdgpu_flip_wait_fence(struct amdgpu_device *adev,
44 				   struct fence **f)
45 {
46 	struct amdgpu_fence *fence;
47 	long r;
48 
49 	if (*f == NULL)
50 		return;
51 
52 	fence = to_amdgpu_fence(*f);
53 	if (fence) {
54 		r = fence_wait(&fence->base, false);
55 		if (r == -EDEADLK)
56 			r = amdgpu_gpu_reset(adev);
57 	} else
58 		r = fence_wait(*f, false);
59 
60 	if (r)
61 		DRM_ERROR("failed to wait on page flip fence (%ld)!\n", r);
62 
63 	/* We continue with the page flip even if we failed to wait on
64 	 * the fence, otherwise the DRM core and userspace will be
65 	 * confused about which BO the CRTC is scanning out
66 	 */
67 	fence_put(*f);
68 	*f = NULL;
69 }
70 
71 static void amdgpu_flip_work_func(struct work_struct *__work)
72 {
73 	struct amdgpu_flip_work *work =
74 		container_of(__work, struct amdgpu_flip_work, flip_work);
75 	struct amdgpu_device *adev = work->adev;
76 	struct amdgpu_crtc *amdgpuCrtc = adev->mode_info.crtcs[work->crtc_id];
77 
78 	struct drm_crtc *crtc = &amdgpuCrtc->base;
79 	unsigned long flags;
80 	unsigned i, repcnt = 4;
81 	int vpos, hpos, stat, min_udelay = 0;
82 	struct drm_vblank_crtc *vblank = &crtc->dev->vblank[work->crtc_id];
83 
84 	amdgpu_flip_wait_fence(adev, &work->excl);
85 	for (i = 0; i < work->shared_count; ++i)
86 		amdgpu_flip_wait_fence(adev, &work->shared[i]);
87 
88 	/* We borrow the event spin lock for protecting flip_status */
89 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
90 
91 	/* If this happens to execute within the "virtually extended" vblank
92 	 * interval before the start of the real vblank interval then it needs
93 	 * to delay programming the mmio flip until the real vblank is entered.
94 	 * This prevents completing a flip too early due to the way we fudge
95 	 * our vblank counter and vblank timestamps in order to work around the
96 	 * problem that the hw fires vblank interrupts before actual start of
97 	 * vblank (when line buffer refilling is done for a frame). It
98 	 * complements the fudging logic in amdgpu_get_crtc_scanoutpos() for
99 	 * timestamping and amdgpu_get_vblank_counter_kms() for vblank counts.
100 	 *
101 	 * In practice this won't execute very often unless on very fast
102 	 * machines because the time window for this to happen is very small.
103 	 */
104 	if (amdgpuCrtc->enabled) {
105 	while (--repcnt) {
106 		/* GET_DISTANCE_TO_VBLANKSTART returns distance to real vblank
107 		 * start in hpos, and to the "fudged earlier" vblank start in
108 		 * vpos.
109 		 */
110 		stat = amdgpu_get_crtc_scanoutpos(adev->ddev, work->crtc_id,
111 						  GET_DISTANCE_TO_VBLANKSTART,
112 						  &vpos, &hpos, NULL, NULL,
113 						  &crtc->hwmode);
114 
115 		if ((stat & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_ACCURATE)) !=
116 		    (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_ACCURATE) ||
117 		    !(vpos >= 0 && hpos <= 0))
118 			break;
119 
120 		/* Sleep at least until estimated real start of hw vblank */
121 		min_udelay = (-hpos + 1) * max(vblank->linedur_ns / 1000, 5);
122 		if (min_udelay > vblank->framedur_ns / 2000) {
123 			/* Don't wait ridiculously long - something is wrong */
124 			repcnt = 0;
125 			break;
126 		}
127 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
128 		usleep_range(min_udelay, 2 * min_udelay);
129 		spin_lock_irqsave(&crtc->dev->event_lock, flags);
130 	};
131 
132 	if (!repcnt)
133 		DRM_DEBUG_DRIVER("Delay problem on crtc %d: min_udelay %d, "
134 				 "framedur %d, linedur %d, stat %d, vpos %d, "
135 				 "hpos %d\n", work->crtc_id, min_udelay,
136 				 vblank->framedur_ns / 1000,
137 				 vblank->linedur_ns / 1000, stat, vpos, hpos);
138 	}
139 
140 	/* do the flip (mmio) */
141 	adev->mode_info.funcs->page_flip(adev, work->crtc_id, work->base);
142 	/* set the flip status */
143 	amdgpuCrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
144 
145 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
146 }
147 
148 /*
149  * Handle unpin events outside the interrupt handler proper.
150  */
151 static void amdgpu_unpin_work_func(struct work_struct *__work)
152 {
153 	struct amdgpu_flip_work *work =
154 		container_of(__work, struct amdgpu_flip_work, unpin_work);
155 	int r;
156 
157 	/* unpin of the old buffer */
158 	r = amdgpu_bo_reserve(work->old_rbo, false);
159 	if (likely(r == 0)) {
160 		r = amdgpu_bo_unpin(work->old_rbo);
161 		if (unlikely(r != 0)) {
162 			DRM_ERROR("failed to unpin buffer after flip\n");
163 		}
164 		amdgpu_bo_unreserve(work->old_rbo);
165 	} else
166 		DRM_ERROR("failed to reserve buffer after flip\n");
167 
168 	amdgpu_bo_unref(&work->old_rbo);
169 	kfree(work->shared);
170 	kfree(work);
171 }
172 
173 int amdgpu_crtc_page_flip(struct drm_crtc *crtc,
174 			  struct drm_framebuffer *fb,
175 			  struct drm_pending_vblank_event *event,
176 			  uint32_t page_flip_flags)
177 {
178 	struct drm_device *dev = crtc->dev;
179 	struct amdgpu_device *adev = dev->dev_private;
180 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
181 	struct amdgpu_framebuffer *old_amdgpu_fb;
182 	struct amdgpu_framebuffer *new_amdgpu_fb;
183 	struct drm_gem_object *obj;
184 	struct amdgpu_flip_work *work;
185 	struct amdgpu_bo *new_rbo;
186 	unsigned long flags;
187 	u64 tiling_flags;
188 	u64 base;
189 	int i, r;
190 
191 	work = kzalloc(sizeof *work, GFP_KERNEL);
192 	if (work == NULL)
193 		return -ENOMEM;
194 
195 	INIT_WORK(&work->flip_work, amdgpu_flip_work_func);
196 	INIT_WORK(&work->unpin_work, amdgpu_unpin_work_func);
197 
198 	work->event = event;
199 	work->adev = adev;
200 	work->crtc_id = amdgpu_crtc->crtc_id;
201 
202 	/* schedule unpin of the old buffer */
203 	old_amdgpu_fb = to_amdgpu_framebuffer(crtc->primary->fb);
204 	obj = old_amdgpu_fb->obj;
205 
206 	/* take a reference to the old object */
207 	work->old_rbo = gem_to_amdgpu_bo(obj);
208 	amdgpu_bo_ref(work->old_rbo);
209 
210 	new_amdgpu_fb = to_amdgpu_framebuffer(fb);
211 	obj = new_amdgpu_fb->obj;
212 	new_rbo = gem_to_amdgpu_bo(obj);
213 
214 	/* pin the new buffer */
215 	r = amdgpu_bo_reserve(new_rbo, false);
216 	if (unlikely(r != 0)) {
217 		DRM_ERROR("failed to reserve new rbo buffer before flip\n");
218 		goto cleanup;
219 	}
220 
221 	r = amdgpu_bo_pin_restricted(new_rbo, AMDGPU_GEM_DOMAIN_VRAM, 0, 0, &base);
222 	if (unlikely(r != 0)) {
223 		amdgpu_bo_unreserve(new_rbo);
224 		r = -EINVAL;
225 		DRM_ERROR("failed to pin new rbo buffer before flip\n");
226 		goto cleanup;
227 	}
228 
229 	r = reservation_object_get_fences_rcu(new_rbo->tbo.resv, &work->excl,
230 					      &work->shared_count,
231 					      &work->shared);
232 	if (unlikely(r != 0)) {
233 		amdgpu_bo_unreserve(new_rbo);
234 		DRM_ERROR("failed to get fences for buffer\n");
235 		goto cleanup;
236 	}
237 
238 	amdgpu_bo_get_tiling_flags(new_rbo, &tiling_flags);
239 	amdgpu_bo_unreserve(new_rbo);
240 
241 	work->base = base;
242 
243 	r = drm_vblank_get(crtc->dev, amdgpu_crtc->crtc_id);
244 	if (r) {
245 		DRM_ERROR("failed to get vblank before flip\n");
246 		goto pflip_cleanup;
247 	}
248 
249 	/* we borrow the event spin lock for protecting flip_wrok */
250 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
251 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_NONE) {
252 		DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
253 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
254 		r = -EBUSY;
255 		goto vblank_cleanup;
256 	}
257 
258 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_PENDING;
259 	amdgpu_crtc->pflip_works = work;
260 
261 	/* update crtc fb */
262 	crtc->primary->fb = fb;
263 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
264 	queue_work(amdgpu_crtc->pflip_queue, &work->flip_work);
265 	return 0;
266 
267 vblank_cleanup:
268 	drm_vblank_put(crtc->dev, amdgpu_crtc->crtc_id);
269 
270 pflip_cleanup:
271 	if (unlikely(amdgpu_bo_reserve(new_rbo, false) != 0)) {
272 		DRM_ERROR("failed to reserve new rbo in error path\n");
273 		goto cleanup;
274 	}
275 	if (unlikely(amdgpu_bo_unpin(new_rbo) != 0)) {
276 		DRM_ERROR("failed to unpin new rbo in error path\n");
277 	}
278 	amdgpu_bo_unreserve(new_rbo);
279 
280 cleanup:
281 	amdgpu_bo_unref(&work->old_rbo);
282 	fence_put(work->excl);
283 	for (i = 0; i < work->shared_count; ++i)
284 		fence_put(work->shared[i]);
285 	kfree(work->shared);
286 	kfree(work);
287 
288 	return r;
289 }
290 
291 int amdgpu_crtc_set_config(struct drm_mode_set *set)
292 {
293 	struct drm_device *dev;
294 	struct amdgpu_device *adev;
295 	struct drm_crtc *crtc;
296 	bool active = false;
297 	int ret;
298 
299 	if (!set || !set->crtc)
300 		return -EINVAL;
301 
302 	dev = set->crtc->dev;
303 
304 	ret = pm_runtime_get_sync(dev->dev);
305 	if (ret < 0)
306 		return ret;
307 
308 	ret = drm_crtc_helper_set_config(set);
309 
310 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
311 		if (crtc->enabled)
312 			active = true;
313 
314 	pm_runtime_mark_last_busy(dev->dev);
315 
316 	adev = dev->dev_private;
317 	/* if we have active crtcs and we don't have a power ref,
318 	   take the current one */
319 	if (active && !adev->have_disp_power_ref) {
320 		adev->have_disp_power_ref = true;
321 		return ret;
322 	}
323 	/* if we have no active crtcs, then drop the power ref
324 	   we got before */
325 	if (!active && adev->have_disp_power_ref) {
326 		pm_runtime_put_autosuspend(dev->dev);
327 		adev->have_disp_power_ref = false;
328 	}
329 
330 	/* drop the power reference we got coming in here */
331 	pm_runtime_put_autosuspend(dev->dev);
332 	return ret;
333 }
334 
335 static const char *encoder_names[38] = {
336 	"NONE",
337 	"INTERNAL_LVDS",
338 	"INTERNAL_TMDS1",
339 	"INTERNAL_TMDS2",
340 	"INTERNAL_DAC1",
341 	"INTERNAL_DAC2",
342 	"INTERNAL_SDVOA",
343 	"INTERNAL_SDVOB",
344 	"SI170B",
345 	"CH7303",
346 	"CH7301",
347 	"INTERNAL_DVO1",
348 	"EXTERNAL_SDVOA",
349 	"EXTERNAL_SDVOB",
350 	"TITFP513",
351 	"INTERNAL_LVTM1",
352 	"VT1623",
353 	"HDMI_SI1930",
354 	"HDMI_INTERNAL",
355 	"INTERNAL_KLDSCP_TMDS1",
356 	"INTERNAL_KLDSCP_DVO1",
357 	"INTERNAL_KLDSCP_DAC1",
358 	"INTERNAL_KLDSCP_DAC2",
359 	"SI178",
360 	"MVPU_FPGA",
361 	"INTERNAL_DDI",
362 	"VT1625",
363 	"HDMI_SI1932",
364 	"DP_AN9801",
365 	"DP_DP501",
366 	"INTERNAL_UNIPHY",
367 	"INTERNAL_KLDSCP_LVTMA",
368 	"INTERNAL_UNIPHY1",
369 	"INTERNAL_UNIPHY2",
370 	"NUTMEG",
371 	"TRAVIS",
372 	"INTERNAL_VCE",
373 	"INTERNAL_UNIPHY3",
374 };
375 
376 static const char *hpd_names[6] = {
377 	"HPD1",
378 	"HPD2",
379 	"HPD3",
380 	"HPD4",
381 	"HPD5",
382 	"HPD6",
383 };
384 
385 void amdgpu_print_display_setup(struct drm_device *dev)
386 {
387 	struct drm_connector *connector;
388 	struct amdgpu_connector *amdgpu_connector;
389 	struct drm_encoder *encoder;
390 	struct amdgpu_encoder *amdgpu_encoder;
391 	uint32_t devices;
392 	int i = 0;
393 
394 	DRM_INFO("AMDGPU Display Connectors\n");
395 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
396 		amdgpu_connector = to_amdgpu_connector(connector);
397 		DRM_INFO("Connector %d:\n", i);
398 		DRM_INFO("  %s\n", connector->name);
399 		if (amdgpu_connector->hpd.hpd != AMDGPU_HPD_NONE)
400 			DRM_INFO("  %s\n", hpd_names[amdgpu_connector->hpd.hpd]);
401 		if (amdgpu_connector->ddc_bus) {
402 			DRM_INFO("  DDC: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
403 				 amdgpu_connector->ddc_bus->rec.mask_clk_reg,
404 				 amdgpu_connector->ddc_bus->rec.mask_data_reg,
405 				 amdgpu_connector->ddc_bus->rec.a_clk_reg,
406 				 amdgpu_connector->ddc_bus->rec.a_data_reg,
407 				 amdgpu_connector->ddc_bus->rec.en_clk_reg,
408 				 amdgpu_connector->ddc_bus->rec.en_data_reg,
409 				 amdgpu_connector->ddc_bus->rec.y_clk_reg,
410 				 amdgpu_connector->ddc_bus->rec.y_data_reg);
411 			if (amdgpu_connector->router.ddc_valid)
412 				DRM_INFO("  DDC Router 0x%x/0x%x\n",
413 					 amdgpu_connector->router.ddc_mux_control_pin,
414 					 amdgpu_connector->router.ddc_mux_state);
415 			if (amdgpu_connector->router.cd_valid)
416 				DRM_INFO("  Clock/Data Router 0x%x/0x%x\n",
417 					 amdgpu_connector->router.cd_mux_control_pin,
418 					 amdgpu_connector->router.cd_mux_state);
419 		} else {
420 			if (connector->connector_type == DRM_MODE_CONNECTOR_VGA ||
421 			    connector->connector_type == DRM_MODE_CONNECTOR_DVII ||
422 			    connector->connector_type == DRM_MODE_CONNECTOR_DVID ||
423 			    connector->connector_type == DRM_MODE_CONNECTOR_DVIA ||
424 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIA ||
425 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIB)
426 				DRM_INFO("  DDC: no ddc bus - possible BIOS bug - please report to xorg-driver-ati@lists.x.org\n");
427 		}
428 		DRM_INFO("  Encoders:\n");
429 		list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
430 			amdgpu_encoder = to_amdgpu_encoder(encoder);
431 			devices = amdgpu_encoder->devices & amdgpu_connector->devices;
432 			if (devices) {
433 				if (devices & ATOM_DEVICE_CRT1_SUPPORT)
434 					DRM_INFO("    CRT1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
435 				if (devices & ATOM_DEVICE_CRT2_SUPPORT)
436 					DRM_INFO("    CRT2: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
437 				if (devices & ATOM_DEVICE_LCD1_SUPPORT)
438 					DRM_INFO("    LCD1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
439 				if (devices & ATOM_DEVICE_DFP1_SUPPORT)
440 					DRM_INFO("    DFP1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
441 				if (devices & ATOM_DEVICE_DFP2_SUPPORT)
442 					DRM_INFO("    DFP2: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
443 				if (devices & ATOM_DEVICE_DFP3_SUPPORT)
444 					DRM_INFO("    DFP3: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
445 				if (devices & ATOM_DEVICE_DFP4_SUPPORT)
446 					DRM_INFO("    DFP4: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
447 				if (devices & ATOM_DEVICE_DFP5_SUPPORT)
448 					DRM_INFO("    DFP5: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
449 				if (devices & ATOM_DEVICE_DFP6_SUPPORT)
450 					DRM_INFO("    DFP6: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
451 				if (devices & ATOM_DEVICE_TV1_SUPPORT)
452 					DRM_INFO("    TV1: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
453 				if (devices & ATOM_DEVICE_CV_SUPPORT)
454 					DRM_INFO("    CV: %s\n", encoder_names[amdgpu_encoder->encoder_id]);
455 			}
456 		}
457 		i++;
458 	}
459 }
460 
461 /**
462  * amdgpu_ddc_probe
463  *
464  */
465 bool amdgpu_ddc_probe(struct amdgpu_connector *amdgpu_connector,
466 		       bool use_aux)
467 {
468 	u8 out = 0x0;
469 	u8 buf[8];
470 	int ret;
471 	struct i2c_msg msgs[] = {
472 		{
473 			.addr = DDC_ADDR,
474 			.flags = 0,
475 			.len = 1,
476 			.buf = &out,
477 		},
478 		{
479 			.addr = DDC_ADDR,
480 			.flags = I2C_M_RD,
481 			.len = 8,
482 			.buf = buf,
483 		}
484 	};
485 
486 	/* on hw with routers, select right port */
487 	if (amdgpu_connector->router.ddc_valid)
488 		amdgpu_i2c_router_select_ddc_port(amdgpu_connector);
489 
490 	if (use_aux) {
491 		ret = i2c_transfer(&amdgpu_connector->ddc_bus->aux.ddc, msgs, 2);
492 	} else {
493 		ret = i2c_transfer(&amdgpu_connector->ddc_bus->adapter, msgs, 2);
494 	}
495 
496 	if (ret != 2)
497 		/* Couldn't find an accessible DDC on this connector */
498 		return false;
499 	/* Probe also for valid EDID header
500 	 * EDID header starts with:
501 	 * 0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00.
502 	 * Only the first 6 bytes must be valid as
503 	 * drm_edid_block_valid() can fix the last 2 bytes */
504 	if (drm_edid_header_is_valid(buf) < 6) {
505 		/* Couldn't find an accessible EDID on this
506 		 * connector */
507 		return false;
508 	}
509 	return true;
510 }
511 
512 static void amdgpu_user_framebuffer_destroy(struct drm_framebuffer *fb)
513 {
514 	struct amdgpu_framebuffer *amdgpu_fb = to_amdgpu_framebuffer(fb);
515 
516 	if (amdgpu_fb->obj) {
517 		drm_gem_object_unreference_unlocked(amdgpu_fb->obj);
518 	}
519 	drm_framebuffer_cleanup(fb);
520 	kfree(amdgpu_fb);
521 }
522 
523 static int amdgpu_user_framebuffer_create_handle(struct drm_framebuffer *fb,
524 						  struct drm_file *file_priv,
525 						  unsigned int *handle)
526 {
527 	struct amdgpu_framebuffer *amdgpu_fb = to_amdgpu_framebuffer(fb);
528 
529 	return drm_gem_handle_create(file_priv, amdgpu_fb->obj, handle);
530 }
531 
532 static const struct drm_framebuffer_funcs amdgpu_fb_funcs = {
533 	.destroy = amdgpu_user_framebuffer_destroy,
534 	.create_handle = amdgpu_user_framebuffer_create_handle,
535 };
536 
537 int
538 amdgpu_framebuffer_init(struct drm_device *dev,
539 			struct amdgpu_framebuffer *rfb,
540 			struct drm_mode_fb_cmd2 *mode_cmd,
541 			struct drm_gem_object *obj)
542 {
543 	int ret;
544 	rfb->obj = obj;
545 	drm_helper_mode_fill_fb_struct(&rfb->base, mode_cmd);
546 	ret = drm_framebuffer_init(dev, &rfb->base, &amdgpu_fb_funcs);
547 	if (ret) {
548 		rfb->obj = NULL;
549 		return ret;
550 	}
551 	return 0;
552 }
553 
554 static struct drm_framebuffer *
555 amdgpu_user_framebuffer_create(struct drm_device *dev,
556 			       struct drm_file *file_priv,
557 			       struct drm_mode_fb_cmd2 *mode_cmd)
558 {
559 	struct drm_gem_object *obj;
560 	struct amdgpu_framebuffer *amdgpu_fb;
561 	int ret;
562 
563 	obj = drm_gem_object_lookup(dev, file_priv, mode_cmd->handles[0]);
564 	if (obj ==  NULL) {
565 		dev_err(pci_dev_dev(dev->pdev), "No GEM object associated to handle 0x%08X, "
566 			"can't create framebuffer\n", mode_cmd->handles[0]);
567 		return ERR_PTR(-ENOENT);
568 	}
569 
570 	/* Handle is imported dma-buf, so cannot be migrated to VRAM for scanout */
571 	if (obj->import_attach) {
572 		DRM_DEBUG_KMS("Cannot create framebuffer from imported dma_buf\n");
573 		return ERR_PTR(-EINVAL);
574 	}
575 
576 	amdgpu_fb = kzalloc(sizeof(*amdgpu_fb), GFP_KERNEL);
577 	if (amdgpu_fb == NULL) {
578 		drm_gem_object_unreference_unlocked(obj);
579 		return ERR_PTR(-ENOMEM);
580 	}
581 
582 	ret = amdgpu_framebuffer_init(dev, amdgpu_fb, mode_cmd, obj);
583 	if (ret) {
584 		kfree(amdgpu_fb);
585 		drm_gem_object_unreference_unlocked(obj);
586 		return ERR_PTR(ret);
587 	}
588 
589 	return &amdgpu_fb->base;
590 }
591 
592 static void amdgpu_output_poll_changed(struct drm_device *dev)
593 {
594 	struct amdgpu_device *adev = dev->dev_private;
595 	amdgpu_fb_output_poll_changed(adev);
596 }
597 
598 const struct drm_mode_config_funcs amdgpu_mode_funcs = {
599 	.fb_create = amdgpu_user_framebuffer_create,
600 	.output_poll_changed = amdgpu_output_poll_changed
601 };
602 
603 static struct drm_prop_enum_list amdgpu_underscan_enum_list[] =
604 {	{ UNDERSCAN_OFF, "off" },
605 	{ UNDERSCAN_ON, "on" },
606 	{ UNDERSCAN_AUTO, "auto" },
607 };
608 
609 static struct drm_prop_enum_list amdgpu_audio_enum_list[] =
610 {	{ AMDGPU_AUDIO_DISABLE, "off" },
611 	{ AMDGPU_AUDIO_ENABLE, "on" },
612 	{ AMDGPU_AUDIO_AUTO, "auto" },
613 };
614 
615 /* XXX support different dither options? spatial, temporal, both, etc. */
616 static struct drm_prop_enum_list amdgpu_dither_enum_list[] =
617 {	{ AMDGPU_FMT_DITHER_DISABLE, "off" },
618 	{ AMDGPU_FMT_DITHER_ENABLE, "on" },
619 };
620 
621 int amdgpu_modeset_create_props(struct amdgpu_device *adev)
622 {
623 	int sz;
624 
625 	if (adev->is_atom_bios) {
626 		adev->mode_info.coherent_mode_property =
627 			drm_property_create_range(adev->ddev, 0 , "coherent", 0, 1);
628 		if (!adev->mode_info.coherent_mode_property)
629 			return -ENOMEM;
630 	}
631 
632 	adev->mode_info.load_detect_property =
633 		drm_property_create_range(adev->ddev, 0, "load detection", 0, 1);
634 	if (!adev->mode_info.load_detect_property)
635 		return -ENOMEM;
636 
637 	drm_mode_create_scaling_mode_property(adev->ddev);
638 
639 	sz = ARRAY_SIZE(amdgpu_underscan_enum_list);
640 	adev->mode_info.underscan_property =
641 		drm_property_create_enum(adev->ddev, 0,
642 				    "underscan",
643 				    amdgpu_underscan_enum_list, sz);
644 
645 	adev->mode_info.underscan_hborder_property =
646 		drm_property_create_range(adev->ddev, 0,
647 					"underscan hborder", 0, 128);
648 	if (!adev->mode_info.underscan_hborder_property)
649 		return -ENOMEM;
650 
651 	adev->mode_info.underscan_vborder_property =
652 		drm_property_create_range(adev->ddev, 0,
653 					"underscan vborder", 0, 128);
654 	if (!adev->mode_info.underscan_vborder_property)
655 		return -ENOMEM;
656 
657 	sz = ARRAY_SIZE(amdgpu_audio_enum_list);
658 	adev->mode_info.audio_property =
659 		drm_property_create_enum(adev->ddev, 0,
660 					 "audio",
661 					 amdgpu_audio_enum_list, sz);
662 
663 	sz = ARRAY_SIZE(amdgpu_dither_enum_list);
664 	adev->mode_info.dither_property =
665 		drm_property_create_enum(adev->ddev, 0,
666 					 "dither",
667 					 amdgpu_dither_enum_list, sz);
668 
669 	return 0;
670 }
671 
672 void amdgpu_update_display_priority(struct amdgpu_device *adev)
673 {
674 	/* adjustment options for the display watermarks */
675 	if ((amdgpu_disp_priority == 0) || (amdgpu_disp_priority > 2))
676 		adev->mode_info.disp_priority = 0;
677 	else
678 		adev->mode_info.disp_priority = amdgpu_disp_priority;
679 
680 }
681 
682 static bool is_hdtv_mode(const struct drm_display_mode *mode)
683 {
684 	/* try and guess if this is a tv or a monitor */
685 	if ((mode->vdisplay == 480 && mode->hdisplay == 720) || /* 480p */
686 	    (mode->vdisplay == 576) || /* 576p */
687 	    (mode->vdisplay == 720) || /* 720p */
688 	    (mode->vdisplay == 1080)) /* 1080p */
689 		return true;
690 	else
691 		return false;
692 }
693 
694 bool amdgpu_crtc_scaling_mode_fixup(struct drm_crtc *crtc,
695 				    const struct drm_display_mode *mode,
696 				    struct drm_display_mode *adjusted_mode)
697 {
698 	struct drm_device *dev = crtc->dev;
699 	struct drm_encoder *encoder;
700 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
701 	struct amdgpu_encoder *amdgpu_encoder;
702 	struct drm_connector *connector;
703 	struct amdgpu_connector *amdgpu_connector __unused;
704 	u32 src_v = 1, dst_v = 1;
705 	u32 src_h = 1, dst_h = 1;
706 
707 	amdgpu_crtc->h_border = 0;
708 	amdgpu_crtc->v_border = 0;
709 
710 	list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
711 		if (encoder->crtc != crtc)
712 			continue;
713 		amdgpu_encoder = to_amdgpu_encoder(encoder);
714 		connector = amdgpu_get_connector_for_encoder(encoder);
715 		amdgpu_connector = to_amdgpu_connector(connector);
716 
717 		/* set scaling */
718 		if (amdgpu_encoder->rmx_type == RMX_OFF)
719 			amdgpu_crtc->rmx_type = RMX_OFF;
720 		else if (mode->hdisplay < amdgpu_encoder->native_mode.hdisplay ||
721 			 mode->vdisplay < amdgpu_encoder->native_mode.vdisplay)
722 			amdgpu_crtc->rmx_type = amdgpu_encoder->rmx_type;
723 		else
724 			amdgpu_crtc->rmx_type = RMX_OFF;
725 		/* copy native mode */
726 		memcpy(&amdgpu_crtc->native_mode,
727 		       &amdgpu_encoder->native_mode,
728 		       sizeof(struct drm_display_mode));
729 		src_v = crtc->mode.vdisplay;
730 		dst_v = amdgpu_crtc->native_mode.vdisplay;
731 		src_h = crtc->mode.hdisplay;
732 		dst_h = amdgpu_crtc->native_mode.hdisplay;
733 
734 		/* fix up for overscan on hdmi */
735 		if ((!(mode->flags & DRM_MODE_FLAG_INTERLACE)) &&
736 		    ((amdgpu_encoder->underscan_type == UNDERSCAN_ON) ||
737 		     ((amdgpu_encoder->underscan_type == UNDERSCAN_AUTO) &&
738 		      drm_detect_hdmi_monitor(amdgpu_connector_edid(connector)) &&
739 		      is_hdtv_mode(mode)))) {
740 			if (amdgpu_encoder->underscan_hborder != 0)
741 				amdgpu_crtc->h_border = amdgpu_encoder->underscan_hborder;
742 			else
743 				amdgpu_crtc->h_border = (mode->hdisplay >> 5) + 16;
744 			if (amdgpu_encoder->underscan_vborder != 0)
745 				amdgpu_crtc->v_border = amdgpu_encoder->underscan_vborder;
746 			else
747 				amdgpu_crtc->v_border = (mode->vdisplay >> 5) + 16;
748 			amdgpu_crtc->rmx_type = RMX_FULL;
749 			src_v = crtc->mode.vdisplay;
750 			dst_v = crtc->mode.vdisplay - (amdgpu_crtc->v_border * 2);
751 			src_h = crtc->mode.hdisplay;
752 			dst_h = crtc->mode.hdisplay - (amdgpu_crtc->h_border * 2);
753 		}
754 	}
755 	if (amdgpu_crtc->rmx_type != RMX_OFF) {
756 		fixed20_12 a, b;
757 		a.full = dfixed_const(src_v);
758 		b.full = dfixed_const(dst_v);
759 		amdgpu_crtc->vsc.full = dfixed_div(a, b);
760 		a.full = dfixed_const(src_h);
761 		b.full = dfixed_const(dst_h);
762 		amdgpu_crtc->hsc.full = dfixed_div(a, b);
763 	} else {
764 		amdgpu_crtc->vsc.full = dfixed_const(1);
765 		amdgpu_crtc->hsc.full = dfixed_const(1);
766 	}
767 	return true;
768 }
769 
770 /*
771  * Retrieve current video scanout position of crtc on a given gpu, and
772  * an optional accurate timestamp of when query happened.
773  *
774  * \param dev Device to query.
775  * \param pipe Crtc to query.
776  * \param flags Flags from caller (DRM_CALLED_FROM_VBLIRQ or 0).
777  *              For driver internal use only also supports these flags:
778  *
779  *              USE_REAL_VBLANKSTART to use the real start of vblank instead
780  *              of a fudged earlier start of vblank.
781  *
782  *              GET_DISTANCE_TO_VBLANKSTART to return distance to the
783  *              fudged earlier start of vblank in *vpos and the distance
784  *              to true start of vblank in *hpos.
785  *
786  * \param *vpos Location where vertical scanout position should be stored.
787  * \param *hpos Location where horizontal scanout position should go.
788  * \param *stime Target location for timestamp taken immediately before
789  *               scanout position query. Can be NULL to skip timestamp.
790  * \param *etime Target location for timestamp taken immediately after
791  *               scanout position query. Can be NULL to skip timestamp.
792  *
793  * Returns vpos as a positive number while in active scanout area.
794  * Returns vpos as a negative number inside vblank, counting the number
795  * of scanlines to go until end of vblank, e.g., -1 means "one scanline
796  * until start of active scanout / end of vblank."
797  *
798  * \return Flags, or'ed together as follows:
799  *
800  * DRM_SCANOUTPOS_VALID = Query successful.
801  * DRM_SCANOUTPOS_INVBL = Inside vblank.
802  * DRM_SCANOUTPOS_ACCURATE = Returned position is accurate. A lack of
803  * this flag means that returned position may be offset by a constant but
804  * unknown small number of scanlines wrt. real scanout position.
805  *
806  */
807 int amdgpu_get_crtc_scanoutpos(struct drm_device *dev, unsigned int pipe,
808 			       unsigned int flags, int *vpos, int *hpos,
809 			       ktime_t *stime, ktime_t *etime,
810 			       const struct drm_display_mode *mode)
811 {
812 	u32 vbl = 0, position = 0;
813 	int vbl_start, vbl_end, vtotal, ret = 0;
814 	bool in_vbl = true;
815 
816 	struct amdgpu_device *adev = dev->dev_private;
817 
818 	/* preempt_disable_rt() should go right here in PREEMPT_RT patchset. */
819 
820 	/* Get optional system timestamp before query. */
821 	if (stime)
822 		*stime = ktime_get();
823 
824 	if (amdgpu_display_page_flip_get_scanoutpos(adev, pipe, &vbl, &position) == 0)
825 		ret |= DRM_SCANOUTPOS_VALID;
826 
827 	/* Get optional system timestamp after query. */
828 	if (etime)
829 		*etime = ktime_get();
830 
831 	/* preempt_enable_rt() should go right here in PREEMPT_RT patchset. */
832 
833 	/* Decode into vertical and horizontal scanout position. */
834 	*vpos = position & 0x1fff;
835 	*hpos = (position >> 16) & 0x1fff;
836 
837 	/* Valid vblank area boundaries from gpu retrieved? */
838 	if (vbl > 0) {
839 		/* Yes: Decode. */
840 		ret |= DRM_SCANOUTPOS_ACCURATE;
841 		vbl_start = vbl & 0x1fff;
842 		vbl_end = (vbl >> 16) & 0x1fff;
843 	}
844 	else {
845 		/* No: Fake something reasonable which gives at least ok results. */
846 		vbl_start = mode->crtc_vdisplay;
847 		vbl_end = 0;
848 	}
849 
850 	/* Called from driver internal vblank counter query code? */
851 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
852 	    /* Caller wants distance from real vbl_start in *hpos */
853 	    *hpos = *vpos - vbl_start;
854 	}
855 
856 	/* Fudge vblank to start a few scanlines earlier to handle the
857 	 * problem that vblank irqs fire a few scanlines before start
858 	 * of vblank. Some driver internal callers need the true vblank
859 	 * start to be used and signal this via the USE_REAL_VBLANKSTART flag.
860 	 *
861 	 * The cause of the "early" vblank irq is that the irq is triggered
862 	 * by the line buffer logic when the line buffer read position enters
863 	 * the vblank, whereas our crtc scanout position naturally lags the
864 	 * line buffer read position.
865 	 */
866 	if (!(flags & USE_REAL_VBLANKSTART))
867 		vbl_start -= adev->mode_info.crtcs[pipe]->lb_vblank_lead_lines;
868 
869 	/* Test scanout position against vblank region. */
870 	if ((*vpos < vbl_start) && (*vpos >= vbl_end))
871 		in_vbl = false;
872 
873 	/* In vblank? */
874 	if (in_vbl)
875 	    ret |= DRM_SCANOUTPOS_IN_VBLANK;
876 
877 	/* Called from driver internal vblank counter query code? */
878 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
879 		/* Caller wants distance from fudged earlier vbl_start */
880 		*vpos -= vbl_start;
881 		return ret;
882 	}
883 
884 	/* Check if inside vblank area and apply corrective offsets:
885 	 * vpos will then be >=0 in video scanout area, but negative
886 	 * within vblank area, counting down the number of lines until
887 	 * start of scanout.
888 	 */
889 
890 	/* Inside "upper part" of vblank area? Apply corrective offset if so: */
891 	if (in_vbl && (*vpos >= vbl_start)) {
892 		vtotal = mode->crtc_vtotal;
893 		*vpos = *vpos - vtotal;
894 	}
895 
896 	/* Correct for shifted end of vbl at vbl_end. */
897 	*vpos = *vpos - vbl_end;
898 
899 	return ret;
900 }
901 
902 int amdgpu_crtc_idx_to_irq_type(struct amdgpu_device *adev, int crtc)
903 {
904 	if (crtc < 0 || crtc >= adev->mode_info.num_crtc)
905 		return AMDGPU_CRTC_IRQ_NONE;
906 
907 	switch (crtc) {
908 	case 0:
909 		return AMDGPU_CRTC_IRQ_VBLANK1;
910 	case 1:
911 		return AMDGPU_CRTC_IRQ_VBLANK2;
912 	case 2:
913 		return AMDGPU_CRTC_IRQ_VBLANK3;
914 	case 3:
915 		return AMDGPU_CRTC_IRQ_VBLANK4;
916 	case 4:
917 		return AMDGPU_CRTC_IRQ_VBLANK5;
918 	case 5:
919 		return AMDGPU_CRTC_IRQ_VBLANK6;
920 	default:
921 		return AMDGPU_CRTC_IRQ_NONE;
922 	}
923 }
924