2 * drm_irq.c IRQ and vblank support
4 * \author Rickard E. (Rik) Faith <faith@valinux.com>
5 * \author Gareth Hughes <gareth@valinux.com>
9 * Created: Fri Mar 19 14:30:16 1999 by faith@valinux.com
11 * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
12 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
13 * All Rights Reserved.
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:
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
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.
36 #include "drm_trace.h"
37 #include "drm_internal.h"
39 #include <linux/slab.h>
41 #include <linux/export.h>
43 /* Access macro for slots in vblank timestamp ringbuffer. */
44 #define vblanktimestamp(dev, pipe, count) \
45 ((dev)->vblank[pipe].time[(count) % DRM_VBLANKTIME_RBSIZE])
47 /* Retry timestamp calculation up to 3 times to satisfy
48 * drm_timestamp_precision before giving up.
50 #define DRM_TIMESTAMP_MAXRETRIES 3
52 /* Threshold in nanoseconds for detection of redundant
53 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
55 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
58 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
59 struct timeval *tvblank, unsigned flags);
61 unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
64 * Default to use monotonic timestamps for wait-for-vblank and page-flip
67 unsigned int drm_timestamp_monotonic = 1;
69 int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
71 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
72 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
73 module_param_named(timestamp_monotonic, drm_timestamp_monotonic, int, 0600);
74 MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
75 MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
76 MODULE_PARM_DESC(timestamp_monotonic, "Use monotonic timestamps");
78 static void store_vblank(struct drm_device *dev, unsigned int pipe,
80 struct timeval *t_vblank, u32 last)
82 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
85 assert_spin_locked(&dev->vblank_time_lock);
89 /* All writers hold the spinlock, but readers are serialized by
90 * the latching of vblank->count below.
92 tslot = vblank->count + vblank_count_inc;
93 vblanktimestamp(dev, pipe, tslot) = *t_vblank;
96 * vblank timestamp updates are protected on the write side with
97 * vblank_time_lock, but on the read side done locklessly using a
98 * sequence-lock on the vblank counter. Ensure correct ordering using
99 * memory barrriers. We need the barrier both before and also after the
100 * counter update to synchronize with the next timestamp write.
101 * The read-side barriers for this are in drm_vblank_count_and_time.
104 vblank->count += vblank_count_inc;
109 * drm_reset_vblank_timestamp - reset the last timestamp to the last vblank
111 * @pipe: index of CRTC for which to reset the timestamp
113 * Reset the stored timestamp for the current vblank count to correspond
114 * to the last vblank occurred.
116 * Only to be called from drm_vblank_on().
118 * Note: caller must hold dev->vbl_lock since this reads & writes
119 * device vblank fields.
121 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
125 struct timeval t_vblank;
126 int count = DRM_TIMESTAMP_MAXRETRIES;
128 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
131 * sample the current counter to avoid random jumps
132 * when drm_vblank_enable() applies the diff
135 cur_vblank = dev->driver->get_vblank_counter(dev, pipe);
136 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, 0);
137 } while (cur_vblank != dev->driver->get_vblank_counter(dev, pipe) && --count > 0);
140 * Only reinitialize corresponding vblank timestamp if high-precision query
141 * available and didn't fail. Otherwise reinitialize delayed at next vblank
142 * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
145 t_vblank = (struct timeval) {0, 0};
148 * +1 to make sure user will never see the same
149 * vblank counter value before and after a modeset
151 store_vblank(dev, pipe, 1, &t_vblank, cur_vblank);
153 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
157 * drm_update_vblank_count - update the master vblank counter
159 * @pipe: counter to update
161 * Call back into the driver to update the appropriate vblank counter
162 * (specified by @pipe). Deal with wraparound, if it occurred, and
163 * update the last read value so we can deal with wraparound on the next
166 * Only necessary when going from off->on, to account for frames we
167 * didn't get an interrupt for.
169 * Note: caller must hold dev->vbl_lock since this reads & writes
170 * device vblank fields.
172 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
175 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
176 u32 cur_vblank, diff;
178 struct timeval t_vblank;
179 int count = DRM_TIMESTAMP_MAXRETRIES;
180 int framedur_ns = vblank->framedur_ns;
183 * Interrupts were disabled prior to this call, so deal with counter
185 * NOTE! It's possible we lost a full dev->max_vblank_count + 1 events
186 * here if the register is small or we had vblank interrupts off for
189 * We repeat the hardware vblank counter & timestamp query until
190 * we get consistent results. This to prevent races between gpu
191 * updating its hardware counter while we are retrieving the
192 * corresponding vblank timestamp.
195 cur_vblank = dev->driver->get_vblank_counter(dev, pipe);
196 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, flags);
197 } while (cur_vblank != dev->driver->get_vblank_counter(dev, pipe) && --count > 0);
199 if (dev->max_vblank_count != 0) {
200 /* trust the hw counter when it's around */
201 diff = (cur_vblank - vblank->last) & dev->max_vblank_count;
202 } else if (rc && framedur_ns) {
203 const struct timeval *t_old;
206 t_old = &vblanktimestamp(dev, pipe, vblank->count);
207 diff_ns = timeval_to_ns(&t_vblank) - timeval_to_ns(t_old);
210 * Figure out how many vblanks we've missed based
211 * on the difference in the timestamps and the
212 * frame/field duration.
214 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
216 if (diff == 0 && flags & DRM_CALLED_FROM_VBLIRQ)
217 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored."
218 " diff_ns = %lld, framedur_ns = %d)\n",
219 pipe, (long long) diff_ns, framedur_ns);
221 /* some kind of default for drivers w/o accurate vbl timestamping */
222 diff = (flags & DRM_CALLED_FROM_VBLIRQ) != 0;
226 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
227 * interval? If so then vblank irqs keep running and it will likely
228 * happen that the hardware vblank counter is not trustworthy as it
229 * might reset at some point in that interval and vblank timestamps
230 * are not trustworthy either in that interval. Iow. this can result
231 * in a bogus diff >> 1 which must be avoided as it would cause
232 * random large forward jumps of the software vblank counter.
234 if (diff > 1 && (vblank->inmodeset & 0x2)) {
235 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
236 " due to pre-modeset.\n", pipe, diff);
241 * FIMXE: Need to replace this hack with proper seqlocks.
243 * Restrict the bump of the software vblank counter to a safe maximum
244 * value of +1 whenever there is the possibility that concurrent readers
245 * of vblank timestamps could be active at the moment, as the current
246 * implementation of the timestamp caching and updating is not safe
247 * against concurrent readers for calls to store_vblank() with a bump
248 * of anything but +1. A bump != 1 would very likely return corrupted
249 * timestamps to userspace, because the same slot in the cache could
250 * be concurrently written by store_vblank() and read by one of those
251 * readers without the read-retry logic detecting the collision.
253 * Concurrent readers can exist when we are called from the
254 * drm_vblank_off() or drm_vblank_on() functions and other non-vblank-
255 * irq callers. However, all those calls to us are happening with the
256 * vbl_lock locked to prevent drm_vblank_get(), so the vblank refcount
257 * can't increase while we are executing. Therefore a zero refcount at
258 * this point is safe for arbitrary counter bumps if we are called
259 * outside vblank irq, a non-zero count is not 100% safe. Unfortunately
260 * we must also accept a refcount of 1, as whenever we are called from
261 * drm_vblank_get() -> drm_vblank_enable() the refcount will be 1 and
262 * we must let that one pass through in order to not lose vblank counts
263 * during vblank irq off - which would completely defeat the whole
264 * point of this routine.
266 * Whenever we are called from vblank irq, we have to assume concurrent
267 * readers exist or can show up any time during our execution, even if
268 * the refcount is currently zero, as vblank irqs are usually only
269 * enabled due to the presence of readers, and because when we are called
270 * from vblank irq we can't hold the vbl_lock to protect us from sudden
271 * bumps in vblank refcount. Therefore also restrict bumps to +1 when
272 * called from vblank irq.
274 if ((diff > 1) && (atomic_read(&vblank->refcount) > 1 ||
275 (flags & DRM_CALLED_FROM_VBLIRQ))) {
276 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u "
277 "refcount %u, vblirq %u\n", pipe, diff,
278 atomic_read(&vblank->refcount),
279 (flags & DRM_CALLED_FROM_VBLIRQ) != 0);
283 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
284 " current=%u, diff=%u, hw=%u hw_last=%u\n",
285 pipe, vblank->count, diff, cur_vblank, vblank->last);
288 WARN_ON_ONCE(cur_vblank != vblank->last);
293 * Only reinitialize corresponding vblank timestamp if high-precision query
294 * available and didn't fail, or we were called from the vblank interrupt.
295 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
296 * for now, to mark the vblanktimestamp as invalid.
298 if (!rc && (flags & DRM_CALLED_FROM_VBLIRQ) == 0)
299 t_vblank = (struct timeval) {0, 0};
301 store_vblank(dev, pipe, diff, &t_vblank, cur_vblank);
305 * Disable vblank irq's on crtc, make sure that last vblank count
306 * of hardware and corresponding consistent software vblank counter
307 * are preserved, even if there are any spurious vblank irq's after
310 static void vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
312 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
313 unsigned long irqflags;
315 /* Prevent vblank irq processing while disabling vblank irqs,
316 * so no updates of timestamps or count can happen after we've
317 * disabled. Needed to prevent races in case of delayed irq's.
319 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
322 * Only disable vblank interrupts if they're enabled. This avoids
323 * calling the ->disable_vblank() operation in atomic context with the
324 * hardware potentially runtime suspended.
326 if (vblank->enabled) {
327 dev->driver->disable_vblank(dev, pipe);
328 vblank->enabled = false;
332 * Always update the count and timestamp to maintain the
333 * appearance that the counter has been ticking all along until
334 * this time. This makes the count account for the entire time
335 * between drm_vblank_on() and drm_vblank_off().
337 drm_update_vblank_count(dev, pipe, 0);
339 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
342 static void vblank_disable_fn(unsigned long arg)
344 struct drm_vblank_crtc *vblank = (void *)arg;
345 struct drm_device *dev = vblank->dev;
346 unsigned int pipe = vblank->pipe;
347 unsigned long irqflags;
349 if (!dev->vblank_disable_allowed)
352 spin_lock_irqsave(&dev->vbl_lock, irqflags);
353 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
354 DRM_DEBUG_VBLANK("disabling vblank on crtc %u\n", pipe);
355 vblank_disable_and_save(dev, pipe);
357 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
361 * drm_vblank_cleanup - cleanup vblank support
364 * This function cleans up any resources allocated in drm_vblank_init.
366 void drm_vblank_cleanup(struct drm_device *dev)
370 /* Bail if the driver didn't call drm_vblank_init() */
371 if (dev->num_crtcs == 0)
374 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
375 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
377 WARN_ON(vblank->enabled &&
378 drm_core_check_feature(dev, DRIVER_MODESET));
380 del_timer_sync(&vblank->disable_timer);
387 EXPORT_SYMBOL(drm_vblank_cleanup);
390 * drm_vblank_init - initialize vblank support
392 * @num_crtcs: number of CRTCs supported by @dev
394 * This function initializes vblank support for @num_crtcs display pipelines.
397 * Zero on success or a negative error code on failure.
399 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
404 lockinit(&dev->vbl_lock, "drmvbl", 0, LK_CANRECURSE);
405 lockinit(&dev->vblank_time_lock, "drmvtl", 0, LK_CANRECURSE);
407 dev->num_crtcs = num_crtcs;
409 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
413 for (i = 0; i < num_crtcs; i++) {
414 struct drm_vblank_crtc *vblank = &dev->vblank[i];
418 init_waitqueue_head(&vblank->queue);
419 setup_timer(&vblank->disable_timer, vblank_disable_fn,
420 (unsigned long)vblank);
423 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
425 /* Driver specific high-precision vblank timestamping supported? */
426 if (dev->driver->get_vblank_timestamp)
427 DRM_INFO("Driver supports precise vblank timestamp query.\n");
429 DRM_INFO("No driver support for vblank timestamp query.\n");
431 /* Must have precise timestamping for reliable vblank instant disable */
432 if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
433 dev->vblank_disable_immediate = false;
434 DRM_INFO("Setting vblank_disable_immediate to false because "
435 "get_vblank_timestamp == NULL\n");
438 dev->vblank_disable_allowed = false;
446 EXPORT_SYMBOL(drm_vblank_init);
449 static void drm_irq_vgaarb_nokms(void *cookie, bool state)
451 struct drm_device *dev = cookie;
453 if (dev->driver->vgaarb_irq) {
454 dev->driver->vgaarb_irq(dev, state);
458 if (!dev->irq_enabled)
462 if (dev->driver->irq_uninstall)
463 dev->driver->irq_uninstall(dev);
465 if (dev->driver->irq_preinstall)
466 dev->driver->irq_preinstall(dev);
467 if (dev->driver->irq_postinstall)
468 dev->driver->irq_postinstall(dev);
474 * drm_irq_install - install IRQ handler
476 * @irq: IRQ number to install the handler for
478 * Initializes the IRQ related data. Installs the handler, calling the driver
479 * irq_preinstall() and irq_postinstall() functions before and after the
482 * This is the simplified helper interface provided for drivers with no special
483 * needs. Drivers which need to install interrupt handlers for multiple
484 * interrupts must instead set drm_device->irq_enabled to signal the DRM core
485 * that vblank interrupts are available.
488 * Zero on success or a negative error code on failure.
490 int drm_irq_install(struct drm_device *dev, int irq)
494 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
500 /* Driver must have been initialized */
501 if (!dev->dev_private)
504 if (dev->irq_enabled)
506 dev->irq_enabled = true;
508 DRM_DEBUG("irq=%d\n", irq);
510 /* Before installing handler */
511 if (dev->driver->irq_preinstall)
512 dev->driver->irq_preinstall(dev);
514 /* Install handler */
515 ret = -bus_setup_intr(dev->dev->bsddev, dev->irqr, INTR_MPSAFE,
516 dev->driver->irq_handler, dev, &dev->irqh, &dev->irq_lock);
519 dev->irq_enabled = false;
523 /* After installing handler */
524 if (dev->driver->irq_postinstall)
525 ret = dev->driver->irq_postinstall(dev);
528 dev->irq_enabled = false;
529 bus_teardown_intr(dev->dev->bsddev, dev->irqr, dev->irqh);
536 EXPORT_SYMBOL(drm_irq_install);
539 * drm_irq_uninstall - uninstall the IRQ handler
542 * Calls the driver's irq_uninstall() function and unregisters the IRQ handler.
543 * This should only be called by drivers which used drm_irq_install() to set up
544 * their interrupt handler. Other drivers must only reset
545 * drm_device->irq_enabled to false.
547 * Note that for kernel modesetting drivers it is a bug if this function fails.
548 * The sanity checks are only to catch buggy user modesetting drivers which call
549 * the same function through an ioctl.
552 * Zero on success or a negative error code on failure.
554 int drm_irq_uninstall(struct drm_device *dev)
556 unsigned long irqflags;
560 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
563 irq_enabled = dev->irq_enabled;
564 dev->irq_enabled = false;
567 * Wake up any waiters so they don't hang. This is just to paper over
568 * isssues for UMS drivers which aren't in full control of their
569 * vblank/irq handling. KMS drivers must ensure that vblanks are all
570 * disabled when uninstalling the irq handler.
572 if (dev->num_crtcs) {
573 spin_lock_irqsave(&dev->vbl_lock, irqflags);
574 for (i = 0; i < dev->num_crtcs; i++) {
575 struct drm_vblank_crtc *vblank = &dev->vblank[i];
577 if (!vblank->enabled)
580 WARN_ON(drm_core_check_feature(dev, DRIVER_MODESET));
582 vblank_disable_and_save(dev, i);
583 wake_up(&vblank->queue);
585 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
591 DRM_DEBUG("irq=%d\n", dev->irq);
593 if (dev->driver->irq_uninstall)
594 dev->driver->irq_uninstall(dev);
596 bus_teardown_intr(dev->dev->bsddev, dev->irqr, dev->irqh);
600 EXPORT_SYMBOL(drm_irq_uninstall);
605 * \param inode device inode.
606 * \param file_priv DRM file private.
607 * \param cmd command.
608 * \param arg user argument, pointing to a drm_control structure.
609 * \return zero on success or a negative number on failure.
611 * Calls irq_install() or irq_uninstall() according to \p arg.
613 int drm_control(struct drm_device *dev, void *data,
614 struct drm_file *file_priv)
616 struct drm_control *ctl = data;
619 /* if we haven't irq we fallback for compatibility reasons -
620 * this used to be a separate function in drm_dma.h
623 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
625 if (drm_core_check_feature(dev, DRIVER_MODESET))
627 /* UMS was only ever support on pci devices. */
628 if (WARN_ON(!dev->pdev))
632 case DRM_INST_HANDLER:
635 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
638 mutex_lock(&dev->struct_mutex);
639 ret = drm_irq_install(dev, irq);
640 mutex_unlock(&dev->struct_mutex);
643 case DRM_UNINST_HANDLER:
644 mutex_lock(&dev->struct_mutex);
645 ret = drm_irq_uninstall(dev);
646 mutex_unlock(&dev->struct_mutex);
655 * drm_calc_timestamping_constants - calculate vblank timestamp constants
656 * @crtc: drm_crtc whose timestamp constants should be updated.
657 * @mode: display mode containing the scanout timings
659 * Calculate and store various constants which are later
660 * needed by vblank and swap-completion timestamping, e.g,
661 * by drm_calc_vbltimestamp_from_scanoutpos(). They are
662 * derived from CRTC's true scanout timing, so they take
663 * things like panel scaling or other adjustments into account.
665 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
666 const struct drm_display_mode *mode)
668 struct drm_device *dev = crtc->dev;
669 unsigned int pipe = drm_crtc_index(crtc);
670 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
671 int linedur_ns = 0, framedur_ns = 0;
672 int dotclock = mode->crtc_clock;
677 if (WARN_ON(pipe >= dev->num_crtcs))
680 /* Valid dotclock? */
682 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
685 * Convert scanline length in pixels and video
686 * dot clock to line duration and frame duration
689 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
690 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
693 * Fields of interlaced scanout modes are only half a frame duration.
695 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
698 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
701 vblank->linedur_ns = linedur_ns;
702 vblank->framedur_ns = framedur_ns;
704 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
705 crtc->base.id, mode->crtc_htotal,
706 mode->crtc_vtotal, mode->crtc_vdisplay);
707 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
708 crtc->base.id, dotclock, framedur_ns, linedur_ns);
710 EXPORT_SYMBOL(drm_calc_timestamping_constants);
713 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
715 * @pipe: index of CRTC whose vblank timestamp to retrieve
716 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
717 * On return contains true maximum error of timestamp
718 * @vblank_time: Pointer to struct timeval which should receive the timestamp
719 * @flags: Flags to pass to driver:
721 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
722 * @mode: mode which defines the scanout timings
724 * Implements calculation of exact vblank timestamps from given drm_display_mode
725 * timings and current video scanout position of a CRTC. This can be called from
726 * within get_vblank_timestamp() implementation of a kms driver to implement the
727 * actual timestamping.
729 * Should return timestamps conforming to the OML_sync_control OpenML
730 * extension specification. The timestamp corresponds to the end of
731 * the vblank interval, aka start of scanout of topmost-leftmost display
732 * pixel in the following video frame.
734 * Requires support for optional dev->driver->get_scanout_position()
735 * in kms driver, plus a bit of setup code to provide a drm_display_mode
736 * that corresponds to the true scanout timing.
738 * The current implementation only handles standard video modes. It
739 * returns as no operation if a doublescan or interlaced video mode is
740 * active. Higher level code is expected to handle this.
743 * Negative value on error, failure or if not supported in current
746 * -EINVAL - Invalid CRTC.
747 * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
748 * -ENOTSUPP - Function not supported in current display mode.
749 * -EIO - Failed, e.g., due to failed scanout position query.
751 * Returns or'ed positive status flags on success:
753 * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
754 * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
757 int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
760 struct timeval *vblank_time,
762 const struct drm_display_mode *mode)
764 struct timeval tv_etime;
765 ktime_t stime, etime;
766 unsigned int vbl_status;
767 int ret = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
769 int delta_ns, duration_ns;
771 if (pipe >= dev->num_crtcs) {
772 DRM_ERROR("Invalid crtc %u\n", pipe);
776 /* Scanout position query not supported? Should not happen. */
777 if (!dev->driver->get_scanout_position) {
778 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
782 /* If mode timing undefined, just return as no-op:
783 * Happens during initial modesetting of a crtc.
785 if (mode->crtc_clock == 0) {
786 DRM_DEBUG_VBLANK("crtc %u: Noop due to uninitialized mode.\n", pipe);
790 /* Get current scanout position with system timestamp.
791 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
792 * if single query takes longer than max_error nanoseconds.
794 * This guarantees a tight bound on maximum error if
795 * code gets preempted or delayed for some reason.
797 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
799 * Get vertical and horizontal scanout position vpos, hpos,
800 * and bounding timestamps stime, etime, pre/post query.
802 vbl_status = dev->driver->get_scanout_position(dev, pipe, flags,
807 /* Return as no-op if scanout query unsupported or failed. */
808 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
809 DRM_DEBUG_VBLANK("crtc %u : scanoutpos query failed [0x%x].\n",
814 /* Compute uncertainty in timestamp of scanout position query. */
815 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
817 /* Accept result with < max_error nsecs timing uncertainty. */
818 if (duration_ns <= *max_error)
822 /* Noisy system timing? */
823 if (i == DRM_TIMESTAMP_MAXRETRIES) {
824 DRM_DEBUG_VBLANK("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
825 pipe, duration_ns/1000, *max_error/1000, i);
828 /* Return upper bound of timestamp precision error. */
829 *max_error = duration_ns;
831 /* Check if in vblank area:
832 * vpos is >=0 in video scanout area, but negative
833 * within vblank area, counting down the number of lines until
836 if (vbl_status & DRM_SCANOUTPOS_IN_VBLANK)
837 ret |= DRM_VBLANKTIME_IN_VBLANK;
839 /* Convert scanout position into elapsed time at raw_time query
840 * since start of scanout at first display scanline. delta_ns
841 * can be negative if start of scanout hasn't happened yet.
843 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
846 if (!drm_timestamp_monotonic)
847 etime = ktime_mono_to_real(etime);
849 /* save this only for debugging purposes */
850 tv_etime = ktime_to_timeval(etime);
851 /* Subtract time delta from raw timestamp to get final
852 * vblank_time timestamp for end of vblank.
855 etime = ktime_add_ns(etime, -delta_ns);
857 etime = ktime_sub_ns(etime, delta_ns);
858 *vblank_time = ktime_to_timeval(etime);
860 DRM_DEBUG_VBLANK("crtc %u : v 0x%x p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
861 pipe, vbl_status, hpos, vpos,
862 (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
863 (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
864 duration_ns/1000, i);
868 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
870 static struct timeval get_drm_timestamp(void)
874 now = drm_timestamp_monotonic ? ktime_get() : ktime_get_real();
875 return ktime_to_timeval(now);
879 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
882 * @pipe: index of CRTC whose vblank timestamp to retrieve
883 * @tvblank: Pointer to target struct timeval which should receive the timestamp
884 * @flags: Flags to pass to driver:
886 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
888 * Fetches the system timestamp corresponding to the time of the most recent
889 * vblank interval on specified CRTC. May call into kms-driver to
890 * compute the timestamp with a high-precision GPU specific method.
892 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
893 * call, i.e., it isn't very precisely locked to the true vblank.
896 * True if timestamp is considered to be very precise, false otherwise.
899 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
900 struct timeval *tvblank, unsigned flags)
904 /* Define requested maximum error on timestamps (nanoseconds). */
905 int max_error = (int) drm_timestamp_precision * 1000;
907 /* Query driver if possible and precision timestamping enabled. */
908 if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
909 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
915 /* GPU high precision timestamp query unsupported or failed.
916 * Return current monotonic/gettimeofday timestamp as best estimate.
918 *tvblank = get_drm_timestamp();
924 * drm_vblank_count - retrieve "cooked" vblank counter value
926 * @pipe: index of CRTC for which to retrieve the counter
928 * Fetches the "cooked" vblank count value that represents the number of
929 * vblank events since the system was booted, including lost events due to
930 * modesetting activity.
932 * This is the legacy version of drm_crtc_vblank_count().
935 * The software vblank counter.
937 u32 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
939 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
941 if (WARN_ON(pipe >= dev->num_crtcs))
944 return vblank->count;
946 EXPORT_SYMBOL(drm_vblank_count);
949 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
950 * @crtc: which counter to retrieve
952 * Fetches the "cooked" vblank count value that represents the number of
953 * vblank events since the system was booted, including lost events due to
954 * modesetting activity.
956 * This is the native KMS version of drm_vblank_count().
959 * The software vblank counter.
961 u32 drm_crtc_vblank_count(struct drm_crtc *crtc)
963 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
965 EXPORT_SYMBOL(drm_crtc_vblank_count);
968 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
969 * system timestamp corresponding to that vblank counter value.
971 * @pipe: index of CRTC whose counter to retrieve
972 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
974 * Fetches the "cooked" vblank count value that represents the number of
975 * vblank events since the system was booted, including lost events due to
976 * modesetting activity. Returns corresponding system timestamp of the time
977 * of the vblank interval that corresponds to the current vblank counter value.
979 * This is the legacy version of drm_crtc_vblank_count_and_time().
981 u32 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
982 struct timeval *vblanktime)
984 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
985 int count = DRM_TIMESTAMP_MAXRETRIES;
988 vblanktime->tv_sec = 0; /* silence gcc warning */
989 vblanktime->tv_usec = 0; /* silence gcc warning */
990 if (WARN_ON(pipe >= dev->num_crtcs))
994 * Vblank timestamps are read lockless. To ensure consistency the vblank
995 * counter is rechecked and ordering is ensured using memory barriers.
996 * This works like a seqlock. The write-side barriers are in store_vblank.
999 cur_vblank = vblank->count;
1001 *vblanktime = vblanktimestamp(dev, pipe, cur_vblank);
1003 } while (cur_vblank != vblank->count && --count > 0);
1007 EXPORT_SYMBOL(drm_vblank_count_and_time);
1010 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
1011 * and the system timestamp corresponding to that vblank counter value
1012 * @crtc: which counter to retrieve
1013 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
1015 * Fetches the "cooked" vblank count value that represents the number of
1016 * vblank events since the system was booted, including lost events due to
1017 * modesetting activity. Returns corresponding system timestamp of the time
1018 * of the vblank interval that corresponds to the current vblank counter value.
1020 * This is the native KMS version of drm_vblank_count_and_time().
1022 u32 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
1023 struct timeval *vblanktime)
1025 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
1028 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
1030 static void send_vblank_event(struct drm_device *dev,
1031 struct drm_pending_vblank_event *e,
1032 unsigned long seq, struct timeval *now)
1034 e->event.sequence = seq;
1035 e->event.tv_sec = now->tv_sec;
1036 e->event.tv_usec = now->tv_usec;
1038 drm_send_event_locked(dev, &e->base);
1040 trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
1045 * drm_arm_vblank_event - arm vblank event after pageflip
1048 * @e: the event to prepare to send
1050 * A lot of drivers need to generate vblank events for the very next vblank
1051 * interrupt. For example when the page flip interrupt happens when the page
1052 * flip gets armed, but not when it actually executes within the next vblank
1053 * period. This helper function implements exactly the required vblank arming
1056 * Caller must hold event lock. Caller must also hold a vblank reference for
1057 * the event @e, which will be dropped when the next vblank arrives.
1059 * This is the legacy version of drm_crtc_arm_vblank_event().
1061 void drm_arm_vblank_event(struct drm_device *dev, unsigned int pipe,
1062 struct drm_pending_vblank_event *e)
1064 assert_spin_locked(&dev->event_lock);
1067 e->event.sequence = drm_vblank_count(dev, pipe);
1068 list_add_tail(&e->base.link, &dev->vblank_event_list);
1070 EXPORT_SYMBOL(drm_arm_vblank_event);
1073 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
1074 * @crtc: the source CRTC of the vblank event
1075 * @e: the event to send
1077 * A lot of drivers need to generate vblank events for the very next vblank
1078 * interrupt. For example when the page flip interrupt happens when the page
1079 * flip gets armed, but not when it actually executes within the next vblank
1080 * period. This helper function implements exactly the required vblank arming
1083 * Caller must hold event lock. Caller must also hold a vblank reference for
1084 * the event @e, which will be dropped when the next vblank arrives.
1086 * This is the native KMS version of drm_arm_vblank_event().
1088 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
1089 struct drm_pending_vblank_event *e)
1091 drm_arm_vblank_event(crtc->dev, drm_crtc_index(crtc), e);
1093 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
1096 * drm_send_vblank_event - helper to send vblank event after pageflip
1099 * @e: the event to send
1101 * Updates sequence # and timestamp on event, and sends it to userspace.
1102 * Caller must hold event lock.
1104 * This is the legacy version of drm_crtc_send_vblank_event().
1106 void drm_send_vblank_event(struct drm_device *dev, unsigned int pipe,
1107 struct drm_pending_vblank_event *e)
1112 if (dev->num_crtcs > 0) {
1113 seq = drm_vblank_count_and_time(dev, pipe, &now);
1117 now = get_drm_timestamp();
1120 send_vblank_event(dev, e, seq, &now);
1122 EXPORT_SYMBOL(drm_send_vblank_event);
1125 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
1126 * @crtc: the source CRTC of the vblank event
1127 * @e: the event to send
1129 * Updates sequence # and timestamp on event, and sends it to userspace.
1130 * Caller must hold event lock.
1132 * This is the native KMS version of drm_send_vblank_event().
1134 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
1135 struct drm_pending_vblank_event *e)
1137 drm_send_vblank_event(crtc->dev, drm_crtc_index(crtc), e);
1139 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
1142 * drm_vblank_enable - enable the vblank interrupt on a CRTC
1147 * Zero on success or a negative error code on failure.
1149 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
1151 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1154 assert_spin_locked(&dev->vbl_lock);
1156 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1158 if (!vblank->enabled) {
1160 * Enable vblank irqs under vblank_time_lock protection.
1161 * All vblank count & timestamp updates are held off
1162 * until we are done reinitializing master counter and
1163 * timestamps. Filtercode in drm_handle_vblank() will
1164 * prevent double-accounting of same vblank interval.
1166 ret = dev->driver->enable_vblank(dev, pipe);
1167 DRM_DEBUG_VBLANK("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
1169 atomic_dec(&vblank->refcount);
1171 vblank->enabled = true;
1172 drm_update_vblank_count(dev, pipe, 0);
1176 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1182 * drm_vblank_get - get a reference count on vblank events
1184 * @pipe: index of CRTC to own
1186 * Acquire a reference count on vblank events to avoid having them disabled
1189 * This is the legacy version of drm_crtc_vblank_get().
1192 * Zero on success or a negative error code on failure.
1194 int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
1196 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1197 unsigned long irqflags;
1200 if (!dev->num_crtcs)
1203 if (WARN_ON(pipe >= dev->num_crtcs))
1206 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1207 /* Going from 0->1 means we have to enable interrupts again */
1208 if (atomic_add_return(1, &vblank->refcount) == 1) {
1209 ret = drm_vblank_enable(dev, pipe);
1211 if (!vblank->enabled) {
1212 atomic_dec(&vblank->refcount);
1216 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1220 EXPORT_SYMBOL(drm_vblank_get);
1223 * drm_crtc_vblank_get - get a reference count on vblank events
1224 * @crtc: which CRTC to own
1226 * Acquire a reference count on vblank events to avoid having them disabled
1229 * This is the native kms version of drm_vblank_get().
1232 * Zero on success or a negative error code on failure.
1234 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1236 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1238 EXPORT_SYMBOL(drm_crtc_vblank_get);
1241 * drm_vblank_put - release ownership of vblank events
1243 * @pipe: index of CRTC to release
1245 * Release ownership of a given vblank counter, turning off interrupts
1246 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1248 * This is the legacy version of drm_crtc_vblank_put().
1250 void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1252 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1254 if (WARN_ON(pipe >= dev->num_crtcs))
1257 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1260 /* Last user schedules interrupt disable */
1261 if (atomic_dec_and_test(&vblank->refcount)) {
1262 if (drm_vblank_offdelay == 0)
1264 else if (dev->vblank_disable_immediate || drm_vblank_offdelay < 0)
1265 vblank_disable_fn((unsigned long)vblank);
1267 mod_timer(&vblank->disable_timer,
1268 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1271 EXPORT_SYMBOL(drm_vblank_put);
1274 * drm_crtc_vblank_put - give up ownership of vblank events
1275 * @crtc: which counter to give up
1277 * Release ownership of a given vblank counter, turning off interrupts
1278 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1280 * This is the native kms version of drm_vblank_put().
1282 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1284 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1286 EXPORT_SYMBOL(drm_crtc_vblank_put);
1289 * drm_wait_one_vblank - wait for one vblank
1293 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1294 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1295 * due to lack of driver support or because the crtc is off.
1297 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1299 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1303 if (WARN_ON(pipe >= dev->num_crtcs))
1306 ret = drm_vblank_get(dev, pipe);
1307 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1310 last = drm_vblank_count(dev, pipe);
1312 ret = wait_event_timeout(vblank->queue,
1313 last != drm_vblank_count(dev, pipe),
1314 msecs_to_jiffies(100));
1316 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1318 drm_vblank_put(dev, pipe);
1320 EXPORT_SYMBOL(drm_wait_one_vblank);
1323 * drm_crtc_wait_one_vblank - wait for one vblank
1326 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1327 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1328 * due to lack of driver support or because the crtc is off.
1330 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1332 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1334 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1337 * drm_vblank_off - disable vblank events on a CRTC
1341 * Drivers can use this function to shut down the vblank interrupt handling when
1342 * disabling a crtc. This function ensures that the latest vblank frame count is
1343 * stored so that drm_vblank_on() can restore it again.
1345 * Drivers must use this function when the hardware vblank counter can get
1346 * reset, e.g. when suspending.
1348 * This is the legacy version of drm_crtc_vblank_off().
1350 void drm_vblank_off(struct drm_device *dev, unsigned int pipe)
1352 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1353 struct drm_pending_vblank_event *e, *t;
1355 unsigned long irqflags;
1358 if (WARN_ON(pipe >= dev->num_crtcs))
1361 spin_lock_irqsave(&dev->event_lock, irqflags);
1363 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
1364 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1365 pipe, vblank->enabled, vblank->inmodeset);
1367 /* Avoid redundant vblank disables without previous drm_vblank_on(). */
1368 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1369 vblank_disable_and_save(dev, pipe);
1371 wake_up(&vblank->queue);
1374 * Prevent subsequent drm_vblank_get() from re-enabling
1375 * the vblank interrupt by bumping the refcount.
1377 if (!vblank->inmodeset) {
1378 atomic_inc(&vblank->refcount);
1379 vblank->inmodeset = 1;
1381 lockmgr(&dev->vbl_lock, LK_RELEASE);
1383 /* Send any queued vblank events, lest the natives grow disquiet */
1384 seq = drm_vblank_count_and_time(dev, pipe, &now);
1386 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1387 if (e->pipe != pipe)
1389 DRM_DEBUG_VBLANK("Sending premature vblank event on disable: \
1390 wanted %d, current %d\n",
1391 e->event.sequence, seq);
1392 list_del(&e->base.link);
1393 drm_vblank_put(dev, pipe);
1394 send_vblank_event(dev, e, seq, &now);
1396 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1398 EXPORT_SYMBOL(drm_vblank_off);
1401 * drm_crtc_vblank_off - disable vblank events on a CRTC
1402 * @crtc: CRTC in question
1404 * Drivers can use this function to shut down the vblank interrupt handling when
1405 * disabling a crtc. This function ensures that the latest vblank frame count is
1406 * stored so that drm_vblank_on can restore it again.
1408 * Drivers must use this function when the hardware vblank counter can get
1409 * reset, e.g. when suspending.
1411 * This is the native kms version of drm_vblank_off().
1413 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1415 drm_vblank_off(crtc->dev, drm_crtc_index(crtc));
1417 EXPORT_SYMBOL(drm_crtc_vblank_off);
1420 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1421 * @crtc: CRTC in question
1423 * Drivers can use this function to reset the vblank state to off at load time.
1424 * Drivers should use this together with the drm_crtc_vblank_off() and
1425 * drm_crtc_vblank_on() functions. The difference compared to
1426 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1427 * and hence doesn't need to call any driver hooks.
1429 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1431 struct drm_device *dev = crtc->dev;
1432 unsigned long irqflags;
1433 unsigned int pipe = drm_crtc_index(crtc);
1434 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1436 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1438 * Prevent subsequent drm_vblank_get() from enabling the vblank
1439 * interrupt by bumping the refcount.
1441 if (!vblank->inmodeset) {
1442 atomic_inc(&vblank->refcount);
1443 vblank->inmodeset = 1;
1445 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1447 WARN_ON(!list_empty(&dev->vblank_event_list));
1449 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1452 * drm_vblank_on - enable vblank events on a CRTC
1456 * This functions restores the vblank interrupt state captured with
1457 * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1458 * drm_vblank_off() can be unbalanced and so can also be unconditionally called
1459 * in driver load code to reflect the current hardware state of the crtc.
1461 * This is the legacy version of drm_crtc_vblank_on().
1463 void drm_vblank_on(struct drm_device *dev, unsigned int pipe)
1465 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1466 unsigned long irqflags;
1468 if (WARN_ON(pipe >= dev->num_crtcs))
1471 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1472 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1473 pipe, vblank->enabled, vblank->inmodeset);
1475 /* Drop our private "prevent drm_vblank_get" refcount */
1476 if (vblank->inmodeset) {
1477 atomic_dec(&vblank->refcount);
1478 vblank->inmodeset = 0;
1481 drm_reset_vblank_timestamp(dev, pipe);
1484 * re-enable interrupts if there are users left, or the
1485 * user wishes vblank interrupts to be enabled all the time.
1487 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1488 WARN_ON(drm_vblank_enable(dev, pipe));
1489 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1491 EXPORT_SYMBOL(drm_vblank_on);
1494 * drm_crtc_vblank_on - enable vblank events on a CRTC
1495 * @crtc: CRTC in question
1497 * This functions restores the vblank interrupt state captured with
1498 * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1499 * drm_vblank_off() can be unbalanced and so can also be unconditionally called
1500 * in driver load code to reflect the current hardware state of the crtc.
1502 * This is the native kms version of drm_vblank_on().
1504 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1506 drm_vblank_on(crtc->dev, drm_crtc_index(crtc));
1508 EXPORT_SYMBOL(drm_crtc_vblank_on);
1511 * drm_vblank_pre_modeset - account for vblanks across mode sets
1515 * Account for vblank events across mode setting events, which will likely
1516 * reset the hardware frame counter.
1518 * This is done by grabbing a temporary vblank reference to ensure that the
1519 * vblank interrupt keeps running across the modeset sequence. With this the
1520 * software-side vblank frame counting will ensure that there are no jumps or
1523 * Unfortunately this approach is racy and also doesn't work when the vblank
1524 * interrupt stops running, e.g. across system suspend resume. It is therefore
1525 * highly recommended that drivers use the newer drm_vblank_off() and
1526 * drm_vblank_on() instead. drm_vblank_pre_modeset() only works correctly when
1527 * using "cooked" software vblank frame counters and not relying on any hardware
1530 * Drivers must call drm_vblank_post_modeset() when re-enabling the same crtc
1533 void drm_vblank_pre_modeset(struct drm_device *dev, unsigned int pipe)
1535 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1537 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1538 if (!dev->num_crtcs)
1541 if (WARN_ON(pipe >= dev->num_crtcs))
1545 * To avoid all the problems that might happen if interrupts
1546 * were enabled/disabled around or between these calls, we just
1547 * have the kernel take a reference on the CRTC (just once though
1548 * to avoid corrupting the count if multiple, mismatch calls occur),
1549 * so that interrupts remain enabled in the interim.
1551 if (!vblank->inmodeset) {
1552 vblank->inmodeset = 0x1;
1553 if (drm_vblank_get(dev, pipe) == 0)
1554 vblank->inmodeset |= 0x2;
1557 EXPORT_SYMBOL(drm_vblank_pre_modeset);
1560 * drm_vblank_post_modeset - undo drm_vblank_pre_modeset changes
1564 * This function again drops the temporary vblank reference acquired in
1565 * drm_vblank_pre_modeset.
1567 void drm_vblank_post_modeset(struct drm_device *dev, unsigned int pipe)
1569 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1570 unsigned long irqflags;
1572 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1573 if (!dev->num_crtcs)
1576 if (WARN_ON(pipe >= dev->num_crtcs))
1579 if (vblank->inmodeset) {
1580 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1581 dev->vblank_disable_allowed = true;
1582 drm_reset_vblank_timestamp(dev, pipe);
1583 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1585 if (vblank->inmodeset & 0x2)
1586 drm_vblank_put(dev, pipe);
1588 vblank->inmodeset = 0;
1591 EXPORT_SYMBOL(drm_vblank_post_modeset);
1594 * drm_modeset_ctl - handle vblank event counter changes across mode switch
1595 * @DRM_IOCTL_ARGS: standard ioctl arguments
1597 * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
1598 * ioctls around modesetting so that any lost vblank events are accounted for.
1600 * Generally the counter will reset across mode sets. If interrupts are
1601 * enabled around this call, we don't have to do anything since the counter
1602 * will have already been incremented.
1604 int drm_modeset_ctl(struct drm_device *dev, void *data,
1605 struct drm_file *file_priv)
1607 struct drm_modeset_ctl *modeset = data;
1610 /* If drm_vblank_init() hasn't been called yet, just no-op */
1611 if (!dev->num_crtcs)
1614 /* KMS drivers handle this internally */
1615 if (drm_core_check_feature(dev, DRIVER_MODESET))
1618 pipe = modeset->crtc;
1619 if (pipe >= dev->num_crtcs)
1622 switch (modeset->cmd) {
1623 case _DRM_PRE_MODESET:
1624 drm_vblank_pre_modeset(dev, pipe);
1626 case _DRM_POST_MODESET:
1627 drm_vblank_post_modeset(dev, pipe);
1636 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1637 union drm_wait_vblank *vblwait,
1638 struct drm_file *file_priv)
1640 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1641 struct drm_pending_vblank_event *e;
1643 unsigned long flags;
1647 e = kzalloc(sizeof(*e), GFP_KERNEL);
1654 e->base.pid = curproc->p_pid;
1655 e->event.base.type = DRM_EVENT_VBLANK;
1656 e->event.base.length = sizeof(e->event);
1657 e->event.user_data = vblwait->request.signal;
1659 spin_lock_irqsave(&dev->event_lock, flags);
1662 * drm_vblank_off() might have been called after we called
1663 * drm_vblank_get(). drm_vblank_off() holds event_lock
1664 * around the vblank disable, so no need for further locking.
1665 * The reference from drm_vblank_get() protects against
1666 * vblank disable from another source.
1668 if (!vblank->enabled) {
1673 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1679 seq = drm_vblank_count_and_time(dev, pipe, &now);
1681 if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1682 (seq - vblwait->request.sequence) <= (1 << 23)) {
1683 vblwait->request.sequence = seq + 1;
1684 vblwait->reply.sequence = vblwait->request.sequence;
1687 DRM_DEBUG_VBLANK("event on vblank count %d, current %d, crtc %u\n",
1688 vblwait->request.sequence, seq, pipe);
1690 trace_drm_vblank_event_queued(current->pid, pipe,
1691 vblwait->request.sequence);
1693 e->event.sequence = vblwait->request.sequence;
1694 if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1695 drm_vblank_put(dev, pipe);
1696 send_vblank_event(dev, e, seq, &now);
1697 vblwait->reply.sequence = seq;
1699 /* drm_handle_vblank_events will call drm_vblank_put */
1700 list_add_tail(&e->base.link, &dev->vblank_event_list);
1701 vblwait->reply.sequence = vblwait->request.sequence;
1704 spin_unlock_irqrestore(&dev->event_lock, flags);
1709 spin_unlock_irqrestore(&dev->event_lock, flags);
1712 drm_vblank_put(dev, pipe);
1719 * \param inode device inode.
1720 * \param file_priv DRM file private.
1721 * \param cmd command.
1722 * \param data user argument, pointing to a drm_wait_vblank structure.
1723 * \return zero on success or a negative number on failure.
1725 * This function enables the vblank interrupt on the pipe requested, then
1726 * sleeps waiting for the requested sequence number to occur, and drops
1727 * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
1728 * after a timeout with no further vblank waits scheduled).
1730 int drm_wait_vblank(struct drm_device *dev, void *data,
1731 struct drm_file *file_priv)
1733 struct drm_vblank_crtc *vblank;
1734 union drm_wait_vblank *vblwait = data;
1736 unsigned int flags, seq, pipe, high_pipe;
1738 if (!dev->irq_enabled)
1741 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1744 if (vblwait->request.type &
1745 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1746 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1747 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1748 vblwait->request.type,
1749 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1750 _DRM_VBLANK_HIGH_CRTC_MASK));
1754 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1755 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1757 pipe = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1759 pipe = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1760 if (pipe >= dev->num_crtcs)
1763 vblank = &dev->vblank[pipe];
1765 ret = drm_vblank_get(dev, pipe);
1767 DRM_DEBUG_VBLANK("failed to acquire vblank counter, %d\n", ret);
1770 seq = drm_vblank_count(dev, pipe);
1772 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1773 case _DRM_VBLANK_RELATIVE:
1774 vblwait->request.sequence += seq;
1775 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1776 case _DRM_VBLANK_ABSOLUTE:
1783 if (flags & _DRM_VBLANK_EVENT) {
1784 /* must hold on to the vblank ref until the event fires
1785 * drm_vblank_put will be called asynchronously
1787 return drm_queue_vblank_event(dev, pipe, vblwait, file_priv);
1790 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1791 (seq - vblwait->request.sequence) <= (1<<23)) {
1792 vblwait->request.sequence = seq + 1;
1795 DRM_DEBUG_VBLANK("waiting on vblank count %d, crtc %u\n",
1796 vblwait->request.sequence, pipe);
1797 vblank->last_wait = vblwait->request.sequence;
1798 DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1799 (((drm_vblank_count(dev, pipe) -
1800 vblwait->request.sequence) <= (1 << 23)) ||
1802 !dev->irq_enabled));
1804 if (ret != -EINTR) {
1807 vblwait->reply.sequence = drm_vblank_count_and_time(dev, pipe, &now);
1808 vblwait->reply.tval_sec = now.tv_sec;
1809 vblwait->reply.tval_usec = now.tv_usec;
1811 DRM_DEBUG_VBLANK("returning %d to client\n",
1812 vblwait->reply.sequence);
1814 DRM_DEBUG_VBLANK("vblank wait interrupted by signal\n");
1818 drm_vblank_put(dev, pipe);
1822 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1824 struct drm_pending_vblank_event *e, *t;
1828 assert_spin_locked(&dev->event_lock);
1830 seq = drm_vblank_count_and_time(dev, pipe, &now);
1832 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1833 if (e->pipe != pipe)
1835 if ((seq - e->event.sequence) > (1<<23))
1838 DRM_DEBUG_VBLANK("vblank event on %d, current %d\n",
1839 e->event.sequence, seq);
1841 list_del(&e->base.link);
1842 drm_vblank_put(dev, pipe);
1843 send_vblank_event(dev, e, seq, &now);
1846 trace_drm_vblank_event(pipe, seq);
1850 * drm_handle_vblank - handle a vblank event
1852 * @pipe: index of CRTC where this event occurred
1854 * Drivers should call this routine in their vblank interrupt handlers to
1855 * update the vblank counter and send any signals that may be pending.
1857 * This is the legacy version of drm_crtc_handle_vblank().
1859 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1861 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1862 unsigned long irqflags;
1864 if (WARN_ON_ONCE(!dev->num_crtcs))
1867 if (WARN_ON(pipe >= dev->num_crtcs))
1870 spin_lock_irqsave(&dev->event_lock, irqflags);
1872 /* Need timestamp lock to prevent concurrent execution with
1873 * vblank enable/disable, as this would cause inconsistent
1874 * or corrupted timestamps and vblank counts.
1876 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1878 /* Vblank irq handling disabled. Nothing to do. */
1879 if (!vblank->enabled) {
1880 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1881 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1885 drm_update_vblank_count(dev, pipe, DRM_CALLED_FROM_VBLIRQ);
1887 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1889 wake_up(&vblank->queue);
1890 drm_handle_vblank_events(dev, pipe);
1892 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1896 EXPORT_SYMBOL(drm_handle_vblank);
1899 * drm_crtc_handle_vblank - handle a vblank event
1900 * @crtc: where this event occurred
1902 * Drivers should call this routine in their vblank interrupt handlers to
1903 * update the vblank counter and send any signals that may be pending.
1905 * This is the native KMS version of drm_handle_vblank().
1908 * True if the event was successfully handled, false on failure.
1910 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1912 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1914 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1917 * drm_vblank_no_hw_counter - "No hw counter" implementation of .get_vblank_counter()
1919 * @pipe: CRTC for which to read the counter
1921 * Drivers can plug this into the .get_vblank_counter() function if
1922 * there is no useable hardware frame counter available.
1927 u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
1931 EXPORT_SYMBOL(drm_vblank_no_hw_counter);