drm: Move drm_update_vblank_count()
[deliverable/linux.git] / drivers / gpu / drm / drm_irq.c
CommitLineData
f5752b38
DV
1/*
2 * drm_irq.c IRQ and vblank support
1da177e4
LT
3 *
4 * \author Rickard E. (Rik) Faith <faith@valinux.com>
5 * \author Gareth Hughes <gareth@valinux.com>
6 */
7
8/*
9 * Created: Fri Mar 19 14:30:16 1999 by faith@valinux.com
10 *
11 * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
12 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
13 * All Rights Reserved.
14 *
15 * Permission is hereby granted, free of charge, to any person obtaining a
16 * copy of this software and associated documentation files (the "Software"),
17 * to deal in the Software without restriction, including without limitation
18 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19 * and/or sell copies of the Software, and to permit persons to whom the
20 * Software is furnished to do so, subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice (including the next
23 * paragraph) shall be included in all copies or substantial portions of the
24 * Software.
25 *
26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
29 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
30 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
31 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
32 * OTHER DEALINGS IN THE SOFTWARE.
33 */
34
760285e7 35#include <drm/drmP.h>
ac2874b9 36#include "drm_trace.h"
1da177e4
LT
37
38#include <linux/interrupt.h> /* For task queue support */
5a0e3ad6 39#include <linux/slab.h>
1da177e4 40
28d52043 41#include <linux/vgaarb.h>
2d1a8a48 42#include <linux/export.h>
27641c3f
MK
43
44/* Access macro for slots in vblank timestamp ringbuffer. */
5380e929
VS
45#define vblanktimestamp(dev, crtc, count) \
46 ((dev)->vblank[crtc].time[(count) % DRM_VBLANKTIME_RBSIZE])
27641c3f
MK
47
48/* Retry timestamp calculation up to 3 times to satisfy
49 * drm_timestamp_precision before giving up.
50 */
51#define DRM_TIMESTAMP_MAXRETRIES 3
52
53/* Threshold in nanoseconds for detection of redundant
54 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
55 */
56#define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
57
13b030af
VS
58/**
59 * drm_update_vblank_count - update the master vblank counter
60 * @dev: DRM device
61 * @crtc: counter to update
62 *
63 * Call back into the driver to update the appropriate vblank counter
64 * (specified by @crtc). Deal with wraparound, if it occurred, and
65 * update the last read value so we can deal with wraparound on the next
66 * call if necessary.
67 *
68 * Only necessary when going from off->on, to account for frames we
69 * didn't get an interrupt for.
70 *
71 * Note: caller must hold dev->vbl_lock since this reads & writes
72 * device vblank fields.
73 */
74static void drm_update_vblank_count(struct drm_device *dev, int crtc)
75{
76 u32 cur_vblank, diff, tslot, rc;
77 struct timeval t_vblank;
78
79 /*
80 * Interrupts were disabled prior to this call, so deal with counter
81 * wrap if needed.
82 * NOTE! It's possible we lost a full dev->max_vblank_count events
83 * here if the register is small or we had vblank interrupts off for
84 * a long time.
85 *
86 * We repeat the hardware vblank counter & timestamp query until
87 * we get consistent results. This to prevent races between gpu
88 * updating its hardware counter while we are retrieving the
89 * corresponding vblank timestamp.
90 */
91 do {
92 cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
93 rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
94 } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
95
96 /* Deal with counter wrap */
97 diff = cur_vblank - dev->vblank[crtc].last;
98 if (cur_vblank < dev->vblank[crtc].last) {
99 diff += dev->max_vblank_count;
100
101 DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
102 crtc, dev->vblank[crtc].last, cur_vblank, diff);
103 }
104
105 DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
106 crtc, diff);
107
108 /* Reinitialize corresponding vblank timestamp if high-precision query
109 * available. Skip this step if query unsupported or failed. Will
110 * reinitialize delayed at next vblank interrupt in that case.
111 */
112 if (rc) {
113 tslot = atomic_read(&dev->vblank[crtc].count) + diff;
114 vblanktimestamp(dev, crtc, tslot) = t_vblank;
115 }
116
117 smp_mb__before_atomic();
118 atomic_add(diff, &dev->vblank[crtc].count);
119 smp_mb__after_atomic();
120}
121
27641c3f
MK
122/*
123 * Disable vblank irq's on crtc, make sure that last vblank count
124 * of hardware and corresponding consistent software vblank counter
125 * are preserved, even if there are any spurious vblank irq's after
126 * disable.
127 */
128static void vblank_disable_and_save(struct drm_device *dev, int crtc)
129{
130 unsigned long irqflags;
131 u32 vblcount;
132 s64 diff_ns;
133 int vblrc;
134 struct timeval tvblank;
0355cf3a 135 int count = DRM_TIMESTAMP_MAXRETRIES;
27641c3f
MK
136
137 /* Prevent vblank irq processing while disabling vblank irqs,
138 * so no updates of timestamps or count can happen after we've
139 * disabled. Needed to prevent races in case of delayed irq's.
27641c3f 140 */
27641c3f
MK
141 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
142
143 dev->driver->disable_vblank(dev, crtc);
5380e929 144 dev->vblank[crtc].enabled = false;
27641c3f
MK
145
146 /* No further vblank irq's will be processed after
147 * this point. Get current hardware vblank count and
148 * vblank timestamp, repeat until they are consistent.
149 *
150 * FIXME: There is still a race condition here and in
151 * drm_update_vblank_count() which can cause off-by-one
152 * reinitialization of software vblank counter. If gpu
153 * vblank counter doesn't increment exactly at the leading
154 * edge of a vblank interval, then we can lose 1 count if
155 * we happen to execute between start of vblank and the
156 * delayed gpu counter increment.
157 */
158 do {
5380e929 159 dev->vblank[crtc].last = dev->driver->get_vblank_counter(dev, crtc);
27641c3f 160 vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
5380e929 161 } while (dev->vblank[crtc].last != dev->driver->get_vblank_counter(dev, crtc) && (--count) && vblrc);
0355cf3a
EE
162
163 if (!count)
164 vblrc = 0;
27641c3f
MK
165
166 /* Compute time difference to stored timestamp of last vblank
167 * as updated by last invocation of drm_handle_vblank() in vblank irq.
168 */
5380e929 169 vblcount = atomic_read(&dev->vblank[crtc].count);
27641c3f
MK
170 diff_ns = timeval_to_ns(&tvblank) -
171 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
172
173 /* If there is at least 1 msec difference between the last stored
174 * timestamp and tvblank, then we are currently executing our
175 * disable inside a new vblank interval, the tvblank timestamp
176 * corresponds to this new vblank interval and the irq handler
177 * for this vblank didn't run yet and won't run due to our disable.
178 * Therefore we need to do the job of drm_handle_vblank() and
179 * increment the vblank counter by one to account for this vblank.
180 *
181 * Skip this step if there isn't any high precision timestamp
182 * available. In that case we can't account for this and just
183 * hope for the best.
184 */
bc215128 185 if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
5380e929 186 atomic_inc(&dev->vblank[crtc].count);
4e857c58 187 smp_mb__after_atomic();
bc215128 188 }
27641c3f 189
27641c3f 190 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
27641c3f
MK
191}
192
0a3e67a4
JB
193static void vblank_disable_fn(unsigned long arg)
194{
e69595c2
VS
195 struct drm_vblank_crtc *vblank = (void *)arg;
196 struct drm_device *dev = vblank->dev;
0a3e67a4 197 unsigned long irqflags;
e69595c2 198 int crtc = vblank->crtc;
0a3e67a4
JB
199
200 if (!dev->vblank_disable_allowed)
201 return;
202
e69595c2
VS
203 spin_lock_irqsave(&dev->vbl_lock, irqflags);
204 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
205 DRM_DEBUG("disabling vblank on crtc %d\n", crtc);
206 vblank_disable_and_save(dev, crtc);
0a3e67a4 207 }
e69595c2 208 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
0a3e67a4
JB
209}
210
f5752b38
DV
211/**
212 * drm_vblank_cleanup - cleanup vblank support
213 * @dev: DRM device
214 *
215 * This function cleans up any resources allocated in drm_vblank_init.
216 */
52440211 217void drm_vblank_cleanup(struct drm_device *dev)
0a3e67a4 218{
e69595c2
VS
219 int crtc;
220
0a3e67a4
JB
221 /* Bail if the driver didn't call drm_vblank_init() */
222 if (dev->num_crtcs == 0)
223 return;
224
e69595c2
VS
225 for (crtc = 0; crtc < dev->num_crtcs; crtc++) {
226 del_timer_sync(&dev->vblank[crtc].disable_timer);
227 vblank_disable_fn((unsigned long)&dev->vblank[crtc]);
228 }
0a3e67a4 229
5380e929 230 kfree(dev->vblank);
0a3e67a4
JB
231
232 dev->num_crtcs = 0;
233}
e77cef9c 234EXPORT_SYMBOL(drm_vblank_cleanup);
0a3e67a4 235
f5752b38
DV
236/**
237 * drm_vblank_init - initialize vblank support
238 * @dev: drm_device
239 * @num_crtcs: number of crtcs supported by @dev
240 *
241 * This function initializes vblank support for @num_crtcs display pipelines.
242 *
243 * Returns:
244 * Zero on success or a negative error code on failure.
245 */
0a3e67a4
JB
246int drm_vblank_init(struct drm_device *dev, int num_crtcs)
247{
248 int i, ret = -ENOMEM;
249
0a3e67a4 250 spin_lock_init(&dev->vbl_lock);
27641c3f
MK
251 spin_lock_init(&dev->vblank_time_lock);
252
0a3e67a4
JB
253 dev->num_crtcs = num_crtcs;
254
5380e929
VS
255 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
256 if (!dev->vblank)
0a3e67a4
JB
257 goto err;
258
e69595c2
VS
259 for (i = 0; i < num_crtcs; i++) {
260 dev->vblank[i].dev = dev;
261 dev->vblank[i].crtc = i;
5380e929 262 init_waitqueue_head(&dev->vblank[i].queue);
e69595c2
VS
263 setup_timer(&dev->vblank[i].disable_timer, vblank_disable_fn,
264 (unsigned long)&dev->vblank[i]);
265 }
27641c3f 266
8f6fce03 267 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
27641c3f
MK
268
269 /* Driver specific high-precision vblank timestamping supported? */
270 if (dev->driver->get_vblank_timestamp)
271 DRM_INFO("Driver supports precise vblank timestamp query.\n");
272 else
273 DRM_INFO("No driver support for vblank timestamp query.\n");
274
ba0bf120
VS
275 dev->vblank_disable_allowed = false;
276
0a3e67a4
JB
277 return 0;
278
279err:
280 drm_vblank_cleanup(dev);
281 return ret;
282}
283EXPORT_SYMBOL(drm_vblank_init);
284
28d52043
DA
285static void drm_irq_vgaarb_nokms(void *cookie, bool state)
286{
287 struct drm_device *dev = cookie;
288
289 if (dev->driver->vgaarb_irq) {
290 dev->driver->vgaarb_irq(dev, state);
291 return;
292 }
293
294 if (!dev->irq_enabled)
295 return;
296
5037f8ac
JS
297 if (state) {
298 if (dev->driver->irq_uninstall)
299 dev->driver->irq_uninstall(dev);
300 } else {
301 if (dev->driver->irq_preinstall)
302 dev->driver->irq_preinstall(dev);
303 if (dev->driver->irq_postinstall)
304 dev->driver->irq_postinstall(dev);
28d52043
DA
305 }
306}
307
1da177e4 308/**
f5752b38
DV
309 * drm_irq_install - install IRQ handler
310 * @dev: DRM device
311 * @irq: IRQ number to install the handler for
1da177e4 312 *
0a3e67a4 313 * Initializes the IRQ related data. Installs the handler, calling the driver
f5752b38
DV
314 * irq_preinstall() and irq_postinstall() functions before and after the
315 * installation.
316 *
317 * This is the simplified helper interface provided for drivers with no special
318 * needs. Drivers which need to install interrupt handlers for multiple
319 * interrupts must instead set drm_device->irq_enabled to signal the DRM core
320 * that vblank interrupts are available.
321 *
322 * Returns:
323 * Zero on success or a negative error code on failure.
1da177e4 324 */
bb0f1b5c 325int drm_irq_install(struct drm_device *dev, int irq)
1da177e4 326{
4a1b0714 327 int ret;
b5e89ed5 328 unsigned long sh_flags = 0;
1da177e4
LT
329
330 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
331 return -EINVAL;
332
7c1a38e3 333 if (irq == 0)
1da177e4
LT
334 return -EINVAL;
335
1da177e4 336 /* Driver must have been initialized */
e090c53b 337 if (!dev->dev_private)
1da177e4 338 return -EINVAL;
1da177e4 339
e090c53b 340 if (dev->irq_enabled)
1da177e4 341 return -EBUSY;
4423843c 342 dev->irq_enabled = true;
1da177e4 343
7c1a38e3 344 DRM_DEBUG("irq=%d\n", irq);
1da177e4 345
b5e89ed5 346 /* Before installing handler */
5037f8ac
JS
347 if (dev->driver->irq_preinstall)
348 dev->driver->irq_preinstall(dev);
1da177e4 349
b5e89ed5 350 /* Install handler */
1da177e4 351 if (drm_core_check_feature(dev, DRIVER_IRQ_SHARED))
935f6e3a 352 sh_flags = IRQF_SHARED;
b5e89ed5 353
7c1a38e3 354 ret = request_irq(irq, dev->driver->irq_handler,
5829d183 355 sh_flags, dev->driver->name, dev);
9bfbd5cb 356
b5e89ed5 357 if (ret < 0) {
4423843c 358 dev->irq_enabled = false;
1da177e4
LT
359 return ret;
360 }
361
28d52043
DA
362 if (!drm_core_check_feature(dev, DRIVER_MODESET))
363 vga_client_register(dev->pdev, (void *)dev, drm_irq_vgaarb_nokms, NULL);
364
b5e89ed5 365 /* After installing handler */
5037f8ac
JS
366 if (dev->driver->irq_postinstall)
367 ret = dev->driver->irq_postinstall(dev);
368
0a3e67a4 369 if (ret < 0) {
4423843c 370 dev->irq_enabled = false;
e1c44acc
JS
371 if (!drm_core_check_feature(dev, DRIVER_MODESET))
372 vga_client_register(dev->pdev, NULL, NULL, NULL);
7c1a38e3
DV
373 free_irq(irq, dev);
374 } else {
375 dev->irq = irq;
0a3e67a4 376 }
1da177e4 377
0a3e67a4 378 return ret;
1da177e4 379}
0a3e67a4 380EXPORT_SYMBOL(drm_irq_install);
1da177e4
LT
381
382/**
f5752b38
DV
383 * drm_irq_uninstall - uninstall the IRQ handler
384 * @dev: DRM device
385 *
386 * Calls the driver's irq_uninstall() function and unregisters the IRQ handler.
387 * This should only be called by drivers which used drm_irq_install() to set up
388 * their interrupt handler. Other drivers must only reset
389 * drm_device->irq_enabled to false.
1da177e4 390 *
f5752b38
DV
391 * Note that for kernel modesetting drivers it is a bug if this function fails.
392 * The sanity checks are only to catch buggy user modesetting drivers which call
393 * the same function through an ioctl.
1da177e4 394 *
f5752b38
DV
395 * Returns:
396 * Zero on success or a negative error code on failure.
1da177e4 397 */
27641c3f 398int drm_irq_uninstall(struct drm_device *dev)
1da177e4 399{
dc1336ff 400 unsigned long irqflags;
4423843c
VS
401 bool irq_enabled;
402 int i;
1da177e4
LT
403
404 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
405 return -EINVAL;
406
1da177e4 407 irq_enabled = dev->irq_enabled;
4423843c 408 dev->irq_enabled = false;
1da177e4 409
dc1336ff
JB
410 /*
411 * Wake up any waiters so they don't hang.
412 */
bde4889a
BS
413 if (dev->num_crtcs) {
414 spin_lock_irqsave(&dev->vbl_lock, irqflags);
415 for (i = 0; i < dev->num_crtcs; i++) {
57ed0f7b 416 wake_up(&dev->vblank[i].queue);
5380e929
VS
417 dev->vblank[i].enabled = false;
418 dev->vblank[i].last =
bde4889a
BS
419 dev->driver->get_vblank_counter(dev, i);
420 }
421 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
dc1336ff 422 }
dc1336ff 423
b5e89ed5 424 if (!irq_enabled)
1da177e4
LT
425 return -EINVAL;
426
7c1a38e3 427 DRM_DEBUG("irq=%d\n", dev->irq);
1da177e4 428
28d52043
DA
429 if (!drm_core_check_feature(dev, DRIVER_MODESET))
430 vga_client_register(dev->pdev, NULL, NULL, NULL);
431
5037f8ac
JS
432 if (dev->driver->irq_uninstall)
433 dev->driver->irq_uninstall(dev);
1da177e4 434
7c1a38e3 435 free_irq(dev->irq, dev);
1da177e4
LT
436
437 return 0;
438}
439EXPORT_SYMBOL(drm_irq_uninstall);
440
f5752b38 441/*
1da177e4
LT
442 * IRQ control ioctl.
443 *
444 * \param inode device inode.
6c340eac 445 * \param file_priv DRM file private.
1da177e4
LT
446 * \param cmd command.
447 * \param arg user argument, pointing to a drm_control structure.
448 * \return zero on success or a negative number on failure.
449 *
450 * Calls irq_install() or irq_uninstall() according to \p arg.
451 */
c153f45f
EA
452int drm_control(struct drm_device *dev, void *data,
453 struct drm_file *file_priv)
1da177e4 454{
c153f45f 455 struct drm_control *ctl = data;
a319c1a4 456 int ret = 0, irq;
b5e89ed5 457
27641c3f
MK
458 /* if we haven't irq we fallback for compatibility reasons -
459 * this used to be a separate function in drm_dma.h
460 */
1da177e4 461
22471cf6
DV
462 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
463 return 0;
464 if (drm_core_check_feature(dev, DRIVER_MODESET))
465 return 0;
466 /* UMS was only ever support on pci devices. */
467 if (WARN_ON(!dev->pdev))
468 return -EINVAL;
1da177e4 469
c153f45f 470 switch (ctl->func) {
1da177e4 471 case DRM_INST_HANDLER:
a319c1a4
DV
472 irq = dev->pdev->irq;
473
1da177e4 474 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
a319c1a4 475 ctl->irq != irq)
1da177e4 476 return -EINVAL;
e090c53b 477 mutex_lock(&dev->struct_mutex);
bb0f1b5c 478 ret = drm_irq_install(dev, irq);
e090c53b
DV
479 mutex_unlock(&dev->struct_mutex);
480
481 return ret;
1da177e4 482 case DRM_UNINST_HANDLER:
e090c53b
DV
483 mutex_lock(&dev->struct_mutex);
484 ret = drm_irq_uninstall(dev);
485 mutex_unlock(&dev->struct_mutex);
486
487 return ret;
1da177e4
LT
488 default:
489 return -EINVAL;
490 }
491}
492
27641c3f 493/**
f5752b38
DV
494 * drm_calc_timestamping_constants - calculate vblank timestamp constants
495 * @crtc: drm_crtc whose timestamp constants should be updated.
496 * @mode: display mode containing the scanout timings
27641c3f 497 *
21b21560
VS
498 * Calculate and store various constants which are later
499 * needed by vblank and swap-completion timestamping, e.g,
500 * by drm_calc_vbltimestamp_from_scanoutpos(). They are
f5752b38 501 * derived from CRTC's true scanout timing, so they take
21b21560 502 * things like panel scaling or other adjustments into account.
27641c3f 503 */
545cdd55
VS
504void drm_calc_timestamping_constants(struct drm_crtc *crtc,
505 const struct drm_display_mode *mode)
27641c3f 506{
3c184f69 507 int linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
77666b72 508 int dotclock = mode->crtc_clock;
27641c3f
MK
509
510 /* Valid dotclock? */
511 if (dotclock > 0) {
0dae35a3
VS
512 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
513
514 /*
515 * Convert scanline length in pixels and video
516 * dot clock to line duration, frame duration
517 * and pixel duration in nanoseconds:
27641c3f 518 */
0dae35a3
VS
519 pixeldur_ns = 1000000 / dotclock;
520 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
521 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
c0ae24c1
VS
522
523 /*
524 * Fields of interlaced scanout modes are only half a frame duration.
525 */
526 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
527 framedur_ns /= 2;
27641c3f
MK
528 } else
529 DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
530 crtc->base.id);
531
532 crtc->pixeldur_ns = pixeldur_ns;
533 crtc->linedur_ns = linedur_ns;
534 crtc->framedur_ns = framedur_ns;
535
536 DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
545cdd55
VS
537 crtc->base.id, mode->crtc_htotal,
538 mode->crtc_vtotal, mode->crtc_vdisplay);
27641c3f 539 DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
3c184f69
VS
540 crtc->base.id, dotclock, framedur_ns,
541 linedur_ns, pixeldur_ns);
27641c3f
MK
542}
543EXPORT_SYMBOL(drm_calc_timestamping_constants);
544
545/**
f5752b38
DV
546 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
547 * @dev: DRM device
548 * @crtc: Which CRTC's vblank timestamp to retrieve
549 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
550 * On return contains true maximum error of timestamp
551 * @vblank_time: Pointer to struct timeval which should receive the timestamp
552 * @flags: Flags to pass to driver:
553 * 0 = Default,
554 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
555 * @refcrtc: CRTC which defines scanout timing
556 * @mode: mode which defines the scanout timings
557 *
558 * Implements calculation of exact vblank timestamps from given drm_display_mode
559 * timings and current video scanout position of a CRTC. This can be called from
560 * within get_vblank_timestamp() implementation of a kms driver to implement the
561 * actual timestamping.
27641c3f
MK
562 *
563 * Should return timestamps conforming to the OML_sync_control OpenML
564 * extension specification. The timestamp corresponds to the end of
565 * the vblank interval, aka start of scanout of topmost-leftmost display
566 * pixel in the following video frame.
567 *
568 * Requires support for optional dev->driver->get_scanout_position()
569 * in kms driver, plus a bit of setup code to provide a drm_display_mode
570 * that corresponds to the true scanout timing.
571 *
572 * The current implementation only handles standard video modes. It
573 * returns as no operation if a doublescan or interlaced video mode is
574 * active. Higher level code is expected to handle this.
575 *
f5752b38
DV
576 * Returns:
577 * Negative value on error, failure or if not supported in current
27641c3f
MK
578 * video mode:
579 *
f5752b38 580 * -EINVAL - Invalid CRTC.
27641c3f
MK
581 * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
582 * -ENOTSUPP - Function not supported in current display mode.
583 * -EIO - Failed, e.g., due to failed scanout position query.
584 *
585 * Returns or'ed positive status flags on success:
586 *
587 * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
588 * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
589 *
590 */
591int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
592 int *max_error,
593 struct timeval *vblank_time,
594 unsigned flags,
7da903ef
VS
595 const struct drm_crtc *refcrtc,
596 const struct drm_display_mode *mode)
27641c3f 597{
e62f2f5a
ID
598 ktime_t stime, etime, mono_time_offset;
599 struct timeval tv_etime;
8072bfa6 600 int vbl_status;
27641c3f 601 int vpos, hpos, i;
3c184f69 602 int framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
27641c3f
MK
603 bool invbl;
604
605 if (crtc < 0 || crtc >= dev->num_crtcs) {
606 DRM_ERROR("Invalid crtc %d\n", crtc);
607 return -EINVAL;
608 }
609
610 /* Scanout position query not supported? Should not happen. */
611 if (!dev->driver->get_scanout_position) {
612 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
613 return -EIO;
614 }
615
27641c3f
MK
616 /* Durations of frames, lines, pixels in nanoseconds. */
617 framedur_ns = refcrtc->framedur_ns;
618 linedur_ns = refcrtc->linedur_ns;
619 pixeldur_ns = refcrtc->pixeldur_ns;
620
621 /* If mode timing undefined, just return as no-op:
622 * Happens during initial modesetting of a crtc.
623 */
8072bfa6 624 if (framedur_ns == 0) {
27641c3f
MK
625 DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
626 return -EAGAIN;
627 }
628
27641c3f
MK
629 /* Get current scanout position with system timestamp.
630 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
631 * if single query takes longer than max_error nanoseconds.
632 *
633 * This guarantees a tight bound on maximum error if
634 * code gets preempted or delayed for some reason.
635 */
636 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
8f6fce03
MK
637 /*
638 * Get vertical and horizontal scanout position vpos, hpos,
639 * and bounding timestamps stime, etime, pre/post query.
640 */
abca9e45 641 vbl_status = dev->driver->get_scanout_position(dev, crtc, flags, &vpos,
8f6fce03 642 &hpos, &stime, &etime);
27641c3f 643
8f6fce03
MK
644 /*
645 * Get correction for CLOCK_MONOTONIC -> CLOCK_REALTIME if
646 * CLOCK_REALTIME is requested.
647 */
c61eef72
ID
648 if (!drm_timestamp_monotonic)
649 mono_time_offset = ktime_get_monotonic_offset();
27641c3f 650
27641c3f
MK
651 /* Return as no-op if scanout query unsupported or failed. */
652 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
653 DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
654 crtc, vbl_status);
655 return -EIO;
656 }
657
8f6fce03 658 /* Compute uncertainty in timestamp of scanout position query. */
e62f2f5a 659 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
27641c3f
MK
660
661 /* Accept result with < max_error nsecs timing uncertainty. */
3c184f69 662 if (duration_ns <= *max_error)
27641c3f
MK
663 break;
664 }
665
666 /* Noisy system timing? */
667 if (i == DRM_TIMESTAMP_MAXRETRIES) {
668 DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
3c184f69 669 crtc, duration_ns/1000, *max_error/1000, i);
27641c3f
MK
670 }
671
672 /* Return upper bound of timestamp precision error. */
3c184f69 673 *max_error = duration_ns;
27641c3f
MK
674
675 /* Check if in vblank area:
676 * vpos is >=0 in video scanout area, but negative
677 * within vblank area, counting down the number of lines until
678 * start of scanout.
679 */
680 invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
681
682 /* Convert scanout position into elapsed time at raw_time query
683 * since start of scanout at first display scanline. delta_ns
684 * can be negative if start of scanout hasn't happened yet.
685 */
3c184f69 686 delta_ns = vpos * linedur_ns + hpos * pixeldur_ns;
27641c3f 687
c61eef72
ID
688 if (!drm_timestamp_monotonic)
689 etime = ktime_sub(etime, mono_time_offset);
690
e62f2f5a
ID
691 /* save this only for debugging purposes */
692 tv_etime = ktime_to_timeval(etime);
27641c3f
MK
693 /* Subtract time delta from raw timestamp to get final
694 * vblank_time timestamp for end of vblank.
695 */
e91abf80
MD
696 if (delta_ns < 0)
697 etime = ktime_add_ns(etime, -delta_ns);
698 else
699 etime = ktime_sub_ns(etime, delta_ns);
e62f2f5a 700 *vblank_time = ktime_to_timeval(etime);
27641c3f 701
bbb0aef5
JP
702 DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
703 crtc, (int)vbl_status, hpos, vpos,
e62f2f5a 704 (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
bbb0aef5 705 (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
3c184f69 706 duration_ns/1000, i);
27641c3f
MK
707
708 vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
709 if (invbl)
710 vbl_status |= DRM_VBLANKTIME_INVBL;
711
712 return vbl_status;
713}
714EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
715
c61eef72
ID
716static struct timeval get_drm_timestamp(void)
717{
718 ktime_t now;
719
720 now = ktime_get();
721 if (!drm_timestamp_monotonic)
722 now = ktime_sub(now, ktime_get_monotonic_offset());
723
724 return ktime_to_timeval(now);
725}
726
27641c3f
MK
727/**
728 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
f5752b38 729 * vblank interval
27641c3f 730 * @dev: DRM device
f5752b38 731 * @crtc: which CRTC's vblank timestamp to retrieve
27641c3f
MK
732 * @tvblank: Pointer to target struct timeval which should receive the timestamp
733 * @flags: Flags to pass to driver:
f5752b38
DV
734 * 0 = Default,
735 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
27641c3f
MK
736 *
737 * Fetches the system timestamp corresponding to the time of the most recent
f5752b38 738 * vblank interval on specified CRTC. May call into kms-driver to
27641c3f
MK
739 * compute the timestamp with a high-precision GPU specific method.
740 *
741 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
742 * call, i.e., it isn't very precisely locked to the true vblank.
743 *
f5752b38
DV
744 * Returns:
745 * Non-zero if timestamp is considered to be very precise, zero otherwise.
27641c3f
MK
746 */
747u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
748 struct timeval *tvblank, unsigned flags)
749{
4a1b0714 750 int ret;
27641c3f
MK
751
752 /* Define requested maximum error on timestamps (nanoseconds). */
753 int max_error = (int) drm_timestamp_precision * 1000;
754
755 /* Query driver if possible and precision timestamping enabled. */
756 if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
757 ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
758 tvblank, flags);
759 if (ret > 0)
760 return (u32) ret;
761 }
762
763 /* GPU high precision timestamp query unsupported or failed.
c61eef72 764 * Return current monotonic/gettimeofday timestamp as best estimate.
27641c3f 765 */
c61eef72 766 *tvblank = get_drm_timestamp();
27641c3f
MK
767
768 return 0;
769}
770EXPORT_SYMBOL(drm_get_last_vbltimestamp);
771
0a3e67a4
JB
772/**
773 * drm_vblank_count - retrieve "cooked" vblank counter value
774 * @dev: DRM device
775 * @crtc: which counter to retrieve
776 *
777 * Fetches the "cooked" vblank count value that represents the number of
778 * vblank events since the system was booted, including lost events due to
779 * modesetting activity.
f5752b38
DV
780 *
781 * Returns:
782 * The software vblank counter.
0a3e67a4
JB
783 */
784u32 drm_vblank_count(struct drm_device *dev, int crtc)
785{
5380e929 786 return atomic_read(&dev->vblank[crtc].count);
0a3e67a4
JB
787}
788EXPORT_SYMBOL(drm_vblank_count);
789
27641c3f
MK
790/**
791 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
792 * and the system timestamp corresponding to that vblank counter value.
793 *
794 * @dev: DRM device
795 * @crtc: which counter to retrieve
796 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
797 *
798 * Fetches the "cooked" vblank count value that represents the number of
799 * vblank events since the system was booted, including lost events due to
800 * modesetting activity. Returns corresponding system timestamp of the time
f5752b38 801 * of the vblank interval that corresponds to the current vblank counter value.
27641c3f
MK
802 */
803u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
804 struct timeval *vblanktime)
805{
806 u32 cur_vblank;
807
808 /* Read timestamp from slot of _vblank_time ringbuffer
809 * that corresponds to current vblank count. Retry if
810 * count has incremented during readout. This works like
811 * a seqlock.
812 */
813 do {
5380e929 814 cur_vblank = atomic_read(&dev->vblank[crtc].count);
27641c3f
MK
815 *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
816 smp_rmb();
5380e929 817 } while (cur_vblank != atomic_read(&dev->vblank[crtc].count));
27641c3f
MK
818
819 return cur_vblank;
820}
821EXPORT_SYMBOL(drm_vblank_count_and_time);
822
c6eefa17
RC
823static void send_vblank_event(struct drm_device *dev,
824 struct drm_pending_vblank_event *e,
825 unsigned long seq, struct timeval *now)
826{
827 WARN_ON_SMP(!spin_is_locked(&dev->event_lock));
828 e->event.sequence = seq;
829 e->event.tv_sec = now->tv_sec;
830 e->event.tv_usec = now->tv_usec;
831
832 list_add_tail(&e->base.link,
833 &e->base.file_priv->event_list);
834 wake_up_interruptible(&e->base.file_priv->event_wait);
835 trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
836 e->event.sequence);
837}
838
839/**
840 * drm_send_vblank_event - helper to send vblank event after pageflip
841 * @dev: DRM device
842 * @crtc: CRTC in question
843 * @e: the event to send
844 *
845 * Updates sequence # and timestamp on event, and sends it to userspace.
846 * Caller must hold event lock.
847 */
848void drm_send_vblank_event(struct drm_device *dev, int crtc,
849 struct drm_pending_vblank_event *e)
850{
851 struct timeval now;
852 unsigned int seq;
853 if (crtc >= 0) {
854 seq = drm_vblank_count_and_time(dev, crtc, &now);
855 } else {
856 seq = 0;
c61eef72
ID
857
858 now = get_drm_timestamp();
c6eefa17 859 }
21a245d2 860 e->pipe = crtc;
c6eefa17
RC
861 send_vblank_event(dev, e, seq, &now);
862}
863EXPORT_SYMBOL(drm_send_vblank_event);
864
f2752282
VS
865/**
866 * drm_vblank_enable - enable the vblank interrupt on a CRTC
867 * @dev: DRM device
868 * @crtc: CRTC in question
869 */
870static int drm_vblank_enable(struct drm_device *dev, int crtc)
871{
872 int ret = 0;
873
874 assert_spin_locked(&dev->vbl_lock);
875
876 spin_lock(&dev->vblank_time_lock);
877
878 if (!dev->vblank[crtc].enabled) {
1cfb80b1
DV
879 /*
880 * Enable vblank irqs under vblank_time_lock protection.
f2752282
VS
881 * All vblank count & timestamp updates are held off
882 * until we are done reinitializing master counter and
883 * timestamps. Filtercode in drm_handle_vblank() will
884 * prevent double-accounting of same vblank interval.
885 */
886 ret = dev->driver->enable_vblank(dev, crtc);
887 DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n", crtc, ret);
888 if (ret)
889 atomic_dec(&dev->vblank[crtc].refcount);
890 else {
891 dev->vblank[crtc].enabled = true;
892 drm_update_vblank_count(dev, crtc);
893 }
894 }
895
896 spin_unlock(&dev->vblank_time_lock);
897
898 return ret;
899}
900
0a3e67a4
JB
901/**
902 * drm_vblank_get - get a reference count on vblank events
903 * @dev: DRM device
904 * @crtc: which CRTC to own
905 *
906 * Acquire a reference count on vblank events to avoid having them disabled
907 * while in use.
908 *
89dd6a4b
DV
909 * This is the legacy version of drm_crtc_vblank_get().
910 *
f5752b38 911 * Returns:
0a3e67a4
JB
912 * Zero on success, nonzero on failure.
913 */
914int drm_vblank_get(struct drm_device *dev, int crtc)
915{
97cbc883 916 unsigned long irqflags;
0a3e67a4
JB
917 int ret = 0;
918
919 spin_lock_irqsave(&dev->vbl_lock, irqflags);
920 /* Going from 0->1 means we have to enable interrupts again */
5380e929 921 if (atomic_add_return(1, &dev->vblank[crtc].refcount) == 1) {
f2752282 922 ret = drm_vblank_enable(dev, crtc);
778c9026 923 } else {
5380e929
VS
924 if (!dev->vblank[crtc].enabled) {
925 atomic_dec(&dev->vblank[crtc].refcount);
778c9026 926 ret = -EINVAL;
0a3e67a4
JB
927 }
928 }
929 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
930
931 return ret;
932}
933EXPORT_SYMBOL(drm_vblank_get);
934
89dd6a4b
DV
935/**
936 * drm_crtc_vblank_get - get a reference count on vblank events
937 * @crtc: which CRTC to own
938 *
939 * Acquire a reference count on vblank events to avoid having them disabled
940 * while in use.
941 *
942 * This is the native kms version of drm_vblank_off().
943 *
944 * Returns:
945 * Zero on success, nonzero on failure.
946 */
947int drm_crtc_vblank_get(struct drm_crtc *crtc)
948{
949 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
950}
951EXPORT_SYMBOL(drm_crtc_vblank_get);
952
0a3e67a4
JB
953/**
954 * drm_vblank_put - give up ownership of vblank events
955 * @dev: DRM device
956 * @crtc: which counter to give up
957 *
958 * Release ownership of a given vblank counter, turning off interrupts
27641c3f 959 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
89dd6a4b
DV
960 *
961 * This is the legacy version of drm_crtc_vblank_put().
0a3e67a4
JB
962 */
963void drm_vblank_put(struct drm_device *dev, int crtc)
964{
5380e929 965 BUG_ON(atomic_read(&dev->vblank[crtc].refcount) == 0);
b3f5e732 966
0a3e67a4 967 /* Last user schedules interrupt disable */
5380e929 968 if (atomic_dec_and_test(&dev->vblank[crtc].refcount) &&
27641c3f 969 (drm_vblank_offdelay > 0))
e69595c2 970 mod_timer(&dev->vblank[crtc].disable_timer,
bfd8303a 971 jiffies + ((drm_vblank_offdelay * HZ)/1000));
0a3e67a4
JB
972}
973EXPORT_SYMBOL(drm_vblank_put);
974
89dd6a4b
DV
975/**
976 * drm_crtc_vblank_put - give up ownership of vblank events
977 * @crtc: which counter to give up
978 *
979 * Release ownership of a given vblank counter, turning off interrupts
980 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
981 *
982 * This is the native kms version of drm_vblank_put().
983 */
984void drm_crtc_vblank_put(struct drm_crtc *crtc)
985{
986 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
987}
988EXPORT_SYMBOL(drm_crtc_vblank_put);
989
c6eefa17
RC
990/**
991 * drm_vblank_off - disable vblank events on a CRTC
992 * @dev: DRM device
993 * @crtc: CRTC in question
994 *
f5752b38
DV
995 * Drivers can use this function to shut down the vblank interrupt handling when
996 * disabling a crtc. This function ensures that the latest vblank frame count is
997 * stored so that drm_vblank_on() can restore it again.
998 *
999 * Drivers must use this function when the hardware vblank counter can get
1000 * reset, e.g. when suspending.
89dd6a4b
DV
1001 *
1002 * This is the legacy version of drm_crtc_vblank_off().
c6eefa17 1003 */
778c9026
LP
1004void drm_vblank_off(struct drm_device *dev, int crtc)
1005{
498548ec
CJHR
1006 struct drm_pending_vblank_event *e, *t;
1007 struct timeval now;
778c9026 1008 unsigned long irqflags;
498548ec 1009 unsigned int seq;
778c9026
LP
1010
1011 spin_lock_irqsave(&dev->vbl_lock, irqflags);
27641c3f 1012 vblank_disable_and_save(dev, crtc);
57ed0f7b 1013 wake_up(&dev->vblank[crtc].queue);
498548ec
CJHR
1014
1015 /* Send any queued vblank events, lest the natives grow disquiet */
1016 seq = drm_vblank_count_and_time(dev, crtc, &now);
e7783ba3
ID
1017
1018 spin_lock(&dev->event_lock);
498548ec
CJHR
1019 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1020 if (e->pipe != crtc)
1021 continue;
1022 DRM_DEBUG("Sending premature vblank event on disable: \
1023 wanted %d, current %d\n",
1024 e->event.sequence, seq);
c6eefa17 1025 list_del(&e->base.link);
498548ec 1026 drm_vblank_put(dev, e->pipe);
c6eefa17 1027 send_vblank_event(dev, e, seq, &now);
498548ec 1028 }
e7783ba3 1029 spin_unlock(&dev->event_lock);
498548ec 1030
7ffd7a68
VS
1031 /*
1032 * Prevent subsequent drm_vblank_get() from re-enabling
1033 * the vblank interrupt by bumping the refcount.
1034 */
1035 if (!dev->vblank[crtc].inmodeset) {
1036 atomic_inc(&dev->vblank[crtc].refcount);
1037 dev->vblank[crtc].inmodeset = 1;
1038 }
1039
778c9026
LP
1040 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1041}
1042EXPORT_SYMBOL(drm_vblank_off);
1043
89dd6a4b
DV
1044/**
1045 * drm_crtc_vblank_off - disable vblank events on a CRTC
1046 * @crtc: CRTC in question
1047 *
1048 * Drivers can use this function to shut down the vblank interrupt handling when
1049 * disabling a crtc. This function ensures that the latest vblank frame count is
1050 * stored so that drm_vblank_on can restore it again.
1051 *
1052 * Drivers must use this function when the hardware vblank counter can get
1053 * reset, e.g. when suspending.
1054 *
1055 * This is the native kms version of drm_vblank_off().
1056 */
1057void drm_crtc_vblank_off(struct drm_crtc *crtc)
1058{
1059 drm_vblank_off(crtc->dev, drm_crtc_index(crtc));
1060}
1061EXPORT_SYMBOL(drm_crtc_vblank_off);
1062
f2752282
VS
1063/**
1064 * drm_vblank_on - enable vblank events on a CRTC
1065 * @dev: DRM device
1066 * @crtc: CRTC in question
f5752b38
DV
1067 *
1068 * This functions restores the vblank interrupt state captured with
1069 * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1070 * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1071 * in driver load code to reflect the current hardware state of the crtc.
89dd6a4b
DV
1072 *
1073 * This is the legacy version of drm_crtc_vblank_on().
f2752282
VS
1074 */
1075void drm_vblank_on(struct drm_device *dev, int crtc)
1076{
1077 unsigned long irqflags;
1078
1079 spin_lock_irqsave(&dev->vbl_lock, irqflags);
7ffd7a68
VS
1080 /* Drop our private "prevent drm_vblank_get" refcount */
1081 if (dev->vblank[crtc].inmodeset) {
1082 atomic_dec(&dev->vblank[crtc].refcount);
1083 dev->vblank[crtc].inmodeset = 0;
1084 }
f2752282
VS
1085 /* re-enable interrupts if there's are users left */
1086 if (atomic_read(&dev->vblank[crtc].refcount) != 0)
1087 WARN_ON(drm_vblank_enable(dev, crtc));
1088 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1089}
1090EXPORT_SYMBOL(drm_vblank_on);
1091
89dd6a4b
DV
1092/**
1093 * drm_crtc_vblank_on - enable vblank events on a CRTC
1094 * @crtc: CRTC in question
1095 *
1096 * This functions restores the vblank interrupt state captured with
1097 * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1098 * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1099 * in driver load code to reflect the current hardware state of the crtc.
1100 *
1101 * This is the native kms version of drm_vblank_on().
1102 */
1103void drm_crtc_vblank_on(struct drm_crtc *crtc)
1104{
1105 drm_vblank_on(crtc->dev, drm_crtc_index(crtc));
1106}
1107EXPORT_SYMBOL(drm_crtc_vblank_on);
1108
f453ba04
DA
1109/**
1110 * drm_vblank_pre_modeset - account for vblanks across mode sets
1111 * @dev: DRM device
1112 * @crtc: CRTC in question
f453ba04
DA
1113 *
1114 * Account for vblank events across mode setting events, which will likely
1115 * reset the hardware frame counter.
f5752b38
DV
1116 *
1117 * This is done by grabbing a temporary vblank reference to ensure that the
1118 * vblank interrupt keeps running across the modeset sequence. With this the
1119 * software-side vblank frame counting will ensure that there are no jumps or
1120 * discontinuities.
1121 *
1122 * Unfortunately this approach is racy and also doesn't work when the vblank
1123 * interrupt stops running, e.g. across system suspend resume. It is therefore
1124 * highly recommended that drivers use the newer drm_vblank_off() and
1125 * drm_vblank_on() instead. drm_vblank_pre_modeset() only works correctly when
1126 * using "cooked" software vblank frame counters and not relying on any hardware
1127 * counters.
1128 *
1129 * Drivers must call drm_vblank_post_modeset() when re-enabling the same crtc
1130 * again.
f453ba04
DA
1131 */
1132void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
1133{
b7ea85a4 1134 /* vblank is not initialized (IRQ not installed ?), or has been freed */
e77cef9c
JG
1135 if (!dev->num_crtcs)
1136 return;
f453ba04
DA
1137 /*
1138 * To avoid all the problems that might happen if interrupts
1139 * were enabled/disabled around or between these calls, we just
1140 * have the kernel take a reference on the CRTC (just once though
1141 * to avoid corrupting the count if multiple, mismatch calls occur),
1142 * so that interrupts remain enabled in the interim.
1143 */
5380e929
VS
1144 if (!dev->vblank[crtc].inmodeset) {
1145 dev->vblank[crtc].inmodeset = 0x1;
b3f5e732 1146 if (drm_vblank_get(dev, crtc) == 0)
5380e929 1147 dev->vblank[crtc].inmodeset |= 0x2;
f453ba04
DA
1148 }
1149}
1150EXPORT_SYMBOL(drm_vblank_pre_modeset);
1151
f5752b38
DV
1152/**
1153 * drm_vblank_post_modeset - undo drm_vblank_pre_modeset changes
1154 * @dev: DRM device
1155 * @crtc: CRTC in question
1156 *
1157 * This function again drops the temporary vblank reference acquired in
1158 * drm_vblank_pre_modeset.
1159 */
f453ba04
DA
1160void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
1161{
1162 unsigned long irqflags;
1163
b7ea85a4
HC
1164 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1165 if (!dev->num_crtcs)
1166 return;
1167
5380e929 1168 if (dev->vblank[crtc].inmodeset) {
f453ba04 1169 spin_lock_irqsave(&dev->vbl_lock, irqflags);
ba0bf120 1170 dev->vblank_disable_allowed = true;
f453ba04 1171 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
b3f5e732 1172
5380e929 1173 if (dev->vblank[crtc].inmodeset & 0x2)
b3f5e732
CW
1174 drm_vblank_put(dev, crtc);
1175
5380e929 1176 dev->vblank[crtc].inmodeset = 0;
f453ba04
DA
1177 }
1178}
1179EXPORT_SYMBOL(drm_vblank_post_modeset);
1180
f5752b38 1181/*
0a3e67a4
JB
1182 * drm_modeset_ctl - handle vblank event counter changes across mode switch
1183 * @DRM_IOCTL_ARGS: standard ioctl arguments
1184 *
1185 * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
1186 * ioctls around modesetting so that any lost vblank events are accounted for.
1187 *
1188 * Generally the counter will reset across mode sets. If interrupts are
1189 * enabled around this call, we don't have to do anything since the counter
1190 * will have already been incremented.
1191 */
1192int drm_modeset_ctl(struct drm_device *dev, void *data,
1193 struct drm_file *file_priv)
1194{
1195 struct drm_modeset_ctl *modeset = data;
19227561 1196 unsigned int crtc;
0a3e67a4
JB
1197
1198 /* If drm_vblank_init() hasn't been called yet, just no-op */
1199 if (!dev->num_crtcs)
4a1b0714 1200 return 0;
0a3e67a4 1201
29935554
LP
1202 /* KMS drivers handle this internally */
1203 if (drm_core_check_feature(dev, DRIVER_MODESET))
1204 return 0;
1205
0a3e67a4 1206 crtc = modeset->crtc;
4a1b0714
LP
1207 if (crtc >= dev->num_crtcs)
1208 return -EINVAL;
0a3e67a4 1209
0a3e67a4
JB
1210 switch (modeset->cmd) {
1211 case _DRM_PRE_MODESET:
f453ba04 1212 drm_vblank_pre_modeset(dev, crtc);
0a3e67a4
JB
1213 break;
1214 case _DRM_POST_MODESET:
f453ba04 1215 drm_vblank_post_modeset(dev, crtc);
0a3e67a4
JB
1216 break;
1217 default:
4a1b0714 1218 return -EINVAL;
0a3e67a4
JB
1219 }
1220
4a1b0714 1221 return 0;
0a3e67a4
JB
1222}
1223
c9a9c5e0
KH
1224static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
1225 union drm_wait_vblank *vblwait,
1226 struct drm_file *file_priv)
1227{
1228 struct drm_pending_vblank_event *e;
1229 struct timeval now;
1230 unsigned long flags;
1231 unsigned int seq;
ea5d552c 1232 int ret;
c9a9c5e0
KH
1233
1234 e = kzalloc(sizeof *e, GFP_KERNEL);
ea5d552c
CW
1235 if (e == NULL) {
1236 ret = -ENOMEM;
1237 goto err_put;
1238 }
c9a9c5e0
KH
1239
1240 e->pipe = pipe;
b9c2c9ae 1241 e->base.pid = current->pid;
c9a9c5e0
KH
1242 e->event.base.type = DRM_EVENT_VBLANK;
1243 e->event.base.length = sizeof e->event;
1244 e->event.user_data = vblwait->request.signal;
1245 e->base.event = &e->event.base;
1246 e->base.file_priv = file_priv;
1247 e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
1248
c9a9c5e0
KH
1249 spin_lock_irqsave(&dev->event_lock, flags);
1250
1251 if (file_priv->event_space < sizeof e->event) {
ea5d552c
CW
1252 ret = -EBUSY;
1253 goto err_unlock;
c9a9c5e0
KH
1254 }
1255
1256 file_priv->event_space -= sizeof e->event;
27641c3f
MK
1257 seq = drm_vblank_count_and_time(dev, pipe, &now);
1258
c9a9c5e0
KH
1259 if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1260 (seq - vblwait->request.sequence) <= (1 << 23)) {
1261 vblwait->request.sequence = seq + 1;
4a921645 1262 vblwait->reply.sequence = vblwait->request.sequence;
c9a9c5e0
KH
1263 }
1264
1265 DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
1266 vblwait->request.sequence, seq, pipe);
1267
b9c2c9ae
JB
1268 trace_drm_vblank_event_queued(current->pid, pipe,
1269 vblwait->request.sequence);
1270
c9a9c5e0
KH
1271 e->event.sequence = vblwait->request.sequence;
1272 if ((seq - vblwait->request.sequence) <= (1 << 23)) {
6f331623 1273 drm_vblank_put(dev, pipe);
c6eefa17 1274 send_vblank_event(dev, e, seq, &now);
000fa7cf 1275 vblwait->reply.sequence = seq;
c9a9c5e0 1276 } else {
a6778e9e 1277 /* drm_handle_vblank_events will call drm_vblank_put */
c9a9c5e0 1278 list_add_tail(&e->base.link, &dev->vblank_event_list);
000fa7cf 1279 vblwait->reply.sequence = vblwait->request.sequence;
c9a9c5e0
KH
1280 }
1281
1282 spin_unlock_irqrestore(&dev->event_lock, flags);
1283
1284 return 0;
ea5d552c
CW
1285
1286err_unlock:
1287 spin_unlock_irqrestore(&dev->event_lock, flags);
1288 kfree(e);
1289err_put:
6f331623 1290 drm_vblank_put(dev, pipe);
ea5d552c 1291 return ret;
c9a9c5e0
KH
1292}
1293
f5752b38 1294/*
1da177e4
LT
1295 * Wait for VBLANK.
1296 *
1297 * \param inode device inode.
6c340eac 1298 * \param file_priv DRM file private.
1da177e4
LT
1299 * \param cmd command.
1300 * \param data user argument, pointing to a drm_wait_vblank structure.
1301 * \return zero on success or a negative number on failure.
1302 *
30b23634
EA
1303 * This function enables the vblank interrupt on the pipe requested, then
1304 * sleeps waiting for the requested sequence number to occur, and drops
f5752b38 1305 * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
30b23634 1306 * after a timeout with no further vblank waits scheduled).
1da177e4 1307 */
0a3e67a4
JB
1308int drm_wait_vblank(struct drm_device *dev, void *data,
1309 struct drm_file *file_priv)
1da177e4 1310{
c153f45f 1311 union drm_wait_vblank *vblwait = data;
4a1b0714 1312 int ret;
19b01b5f 1313 unsigned int flags, seq, crtc, high_crtc;
1da177e4 1314
4984979b
DV
1315 if (!dev->irq_enabled)
1316 return -EINVAL;
1da177e4 1317
30b23634
EA
1318 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1319 return -EINVAL;
1320
c153f45f 1321 if (vblwait->request.type &
19b01b5f
IH
1322 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1323 _DRM_VBLANK_HIGH_CRTC_MASK)) {
776c9443 1324 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
c153f45f 1325 vblwait->request.type,
19b01b5f
IH
1326 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1327 _DRM_VBLANK_HIGH_CRTC_MASK));
776c9443
MCA
1328 return -EINVAL;
1329 }
1330
c153f45f 1331 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
19b01b5f
IH
1332 high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1333 if (high_crtc)
1334 crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1335 else
1336 crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
0a3e67a4 1337 if (crtc >= dev->num_crtcs)
776c9443
MCA
1338 return -EINVAL;
1339
0a3e67a4
JB
1340 ret = drm_vblank_get(dev, crtc);
1341 if (ret) {
8d3457ec 1342 DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
0a3e67a4
JB
1343 return ret;
1344 }
1345 seq = drm_vblank_count(dev, crtc);
776c9443 1346
c153f45f 1347 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1da177e4 1348 case _DRM_VBLANK_RELATIVE:
c153f45f
EA
1349 vblwait->request.sequence += seq;
1350 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1da177e4
LT
1351 case _DRM_VBLANK_ABSOLUTE:
1352 break;
1353 default:
0a3e67a4
JB
1354 ret = -EINVAL;
1355 goto done;
1da177e4
LT
1356 }
1357
a6778e9e
IH
1358 if (flags & _DRM_VBLANK_EVENT) {
1359 /* must hold on to the vblank ref until the event fires
1360 * drm_vblank_put will be called asynchronously
1361 */
c9a9c5e0 1362 return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
a6778e9e 1363 }
c9a9c5e0 1364
ab285d74 1365 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
c153f45f
EA
1366 (seq - vblwait->request.sequence) <= (1<<23)) {
1367 vblwait->request.sequence = seq + 1;
ab285d74
MCA
1368 }
1369
30b23634
EA
1370 DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
1371 vblwait->request.sequence, crtc);
5380e929 1372 dev->vblank[crtc].last_wait = vblwait->request.sequence;
bfd8303a 1373 DRM_WAIT_ON(ret, dev->vblank[crtc].queue, 3 * HZ,
30b23634
EA
1374 (((drm_vblank_count(dev, crtc) -
1375 vblwait->request.sequence) <= (1 << 23)) ||
3212a22f 1376 !dev->vblank[crtc].enabled ||
30b23634 1377 !dev->irq_enabled));
1da177e4 1378
30b23634
EA
1379 if (ret != -EINTR) {
1380 struct timeval now;
1da177e4 1381
27641c3f 1382 vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
30b23634
EA
1383 vblwait->reply.tval_sec = now.tv_sec;
1384 vblwait->reply.tval_usec = now.tv_usec;
27641c3f 1385
30b23634
EA
1386 DRM_DEBUG("returning %d to client\n",
1387 vblwait->reply.sequence);
1da177e4 1388 } else {
30b23634 1389 DRM_DEBUG("vblank wait interrupted by signal\n");
1da177e4
LT
1390 }
1391
0a3e67a4
JB
1392done:
1393 drm_vblank_put(dev, crtc);
1da177e4
LT
1394 return ret;
1395}
1396
ea7f7abc 1397static void drm_handle_vblank_events(struct drm_device *dev, int crtc)
c9a9c5e0
KH
1398{
1399 struct drm_pending_vblank_event *e, *t;
1400 struct timeval now;
1401 unsigned long flags;
1402 unsigned int seq;
1403
27641c3f 1404 seq = drm_vblank_count_and_time(dev, crtc, &now);
c9a9c5e0
KH
1405
1406 spin_lock_irqsave(&dev->event_lock, flags);
1407
1408 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1409 if (e->pipe != crtc)
1410 continue;
1411 if ((seq - e->event.sequence) > (1<<23))
1412 continue;
1413
1414 DRM_DEBUG("vblank event on %d, current %d\n",
1415 e->event.sequence, seq);
1416
c6eefa17 1417 list_del(&e->base.link);
c9a9c5e0 1418 drm_vblank_put(dev, e->pipe);
c6eefa17 1419 send_vblank_event(dev, e, seq, &now);
c9a9c5e0
KH
1420 }
1421
1422 spin_unlock_irqrestore(&dev->event_lock, flags);
ac2874b9
JB
1423
1424 trace_drm_vblank_event(crtc, seq);
c9a9c5e0
KH
1425}
1426
0a3e67a4
JB
1427/**
1428 * drm_handle_vblank - handle a vblank event
1429 * @dev: DRM device
1430 * @crtc: where this event occurred
1431 *
1432 * Drivers should call this routine in their vblank interrupt handlers to
1433 * update the vblank counter and send any signals that may be pending.
1434 */
78c6e170 1435bool drm_handle_vblank(struct drm_device *dev, int crtc)
0a3e67a4 1436{
27641c3f
MK
1437 u32 vblcount;
1438 s64 diff_ns;
1439 struct timeval tvblank;
1440 unsigned long irqflags;
1441
c9a9c5e0 1442 if (!dev->num_crtcs)
78c6e170 1443 return false;
c9a9c5e0 1444
27641c3f
MK
1445 /* Need timestamp lock to prevent concurrent execution with
1446 * vblank enable/disable, as this would cause inconsistent
1447 * or corrupted timestamps and vblank counts.
1448 */
1449 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
1450
1451 /* Vblank irq handling disabled. Nothing to do. */
5380e929 1452 if (!dev->vblank[crtc].enabled) {
27641c3f 1453 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
78c6e170 1454 return false;
27641c3f
MK
1455 }
1456
1457 /* Fetch corresponding timestamp for this vblank interval from
1458 * driver and store it in proper slot of timestamp ringbuffer.
1459 */
1460
1461 /* Get current timestamp and count. */
5380e929 1462 vblcount = atomic_read(&dev->vblank[crtc].count);
27641c3f
MK
1463 drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1464
1465 /* Compute time difference to timestamp of last vblank */
1466 diff_ns = timeval_to_ns(&tvblank) -
1467 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1468
1469 /* Update vblank timestamp and count if at least
1470 * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1471 * difference between last stored timestamp and current
1472 * timestamp. A smaller difference means basically
1473 * identical timestamps. Happens if this vblank has
1474 * been already processed and this is a redundant call,
1475 * e.g., due to spurious vblank interrupts. We need to
1476 * ignore those for accounting.
1477 */
c4cc3839 1478 if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
27641c3f
MK
1479 /* Store new timestamp in ringbuffer. */
1480 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
27641c3f
MK
1481
1482 /* Increment cooked vblank count. This also atomically commits
1483 * the timestamp computed above.
1484 */
4e857c58 1485 smp_mb__before_atomic();
5380e929 1486 atomic_inc(&dev->vblank[crtc].count);
4e857c58 1487 smp_mb__after_atomic();
27641c3f
MK
1488 } else {
1489 DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1490 crtc, (int) diff_ns);
1491 }
1492
57ed0f7b 1493 wake_up(&dev->vblank[crtc].queue);
c9a9c5e0 1494 drm_handle_vblank_events(dev, crtc);
27641c3f
MK
1495
1496 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
78c6e170 1497 return true;
0a3e67a4
JB
1498}
1499EXPORT_SYMBOL(drm_handle_vblank);
This page took 1.020821 seconds and 5 git commands to generate.