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