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