2 * Copyright 2003 Eric Anholt
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * ERIC ANHOLT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 * Eric Anholt <anholt@FreeBSD.org>
26 * $FreeBSD: src/sys/dev/drm2/drm_irq.c,v 1.1 2012/05/22 11:07:44 kib Exp $
30 * Support code for handling setup/teardown of interrupt handlers and
31 * handing interrupt handlers off to the drivers.
34 #include <linux/export.h>
35 #include <linux/mutex.h>
36 #include <linux/timer.h>
39 MALLOC_DEFINE(DRM_MEM_VBLANK, "drm_vblank", "DRM VBLANK Handling Data");
41 /* Access macro for slots in vblank timestamp ringbuffer. */
42 #define vblanktimestamp(dev, crtc, count) ( \
43 (dev)->_vblank_time[(crtc) * DRM_VBLANKTIME_RBSIZE + \
44 ((count) % DRM_VBLANKTIME_RBSIZE)])
46 /* Retry timestamp calculation up to 3 times to satisfy
47 * drm_timestamp_precision before giving up.
49 #define DRM_TIMESTAMP_MAXRETRIES 3
51 /* Threshold in nanoseconds for detection of redundant
52 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
54 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
56 int drm_irq_by_busid(struct drm_device *dev, void *data,
57 struct drm_file *file_priv)
59 struct drm_irq_busid *irq = data;
61 if ((irq->busnum >> 8) != dev->pci_domain ||
62 (irq->busnum & 0xff) != dev->pci_bus ||
63 irq->devnum != dev->pci_slot ||
64 irq->funcnum != dev->pci_func)
69 DRM_DEBUG("%d:%d:%d => IRQ %d\n",
70 irq->busnum, irq->devnum, irq->funcnum, irq->irq);
76 drm_irq_install(struct drm_device *dev)
80 if (dev->irq == 0 || dev->dev_private == NULL)
83 DRM_DEBUG("irq=%d\n", dev->irq);
86 if (dev->irq_enabled) {
92 dev->context_flag = 0;
94 /* Before installing handler */
95 if (dev->driver->irq_preinstall)
96 dev->driver->irq_preinstall(dev);
100 retcode = bus_setup_intr(dev->dev, dev->irqr, INTR_MPSAFE,
101 dev->driver->irq_handler, dev, &dev->irqh, &dev->irq_lock);
105 /* After installing handler */
107 if (dev->driver->irq_postinstall)
108 dev->driver->irq_postinstall(dev);
113 device_printf(dev->dev, "Error setting interrupt: %d\n", retcode);
114 dev->irq_enabled = 0;
119 int drm_irq_uninstall(struct drm_device *dev)
123 if (!dev->irq_enabled)
126 dev->irq_enabled = 0;
129 * Wake up any waiters so they don't hang.
131 if (dev->num_crtcs) {
132 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
133 for (i = 0; i < dev->num_crtcs; i++) {
134 wakeup(&dev->_vblank_count[i]);
135 dev->vblank_enabled[i] = 0;
136 dev->last_vblank[i] =
137 dev->driver->get_vblank_counter(dev, i);
139 lockmgr(&dev->vbl_lock, LK_RELEASE);
142 DRM_DEBUG("irq=%d\n", dev->irq);
144 if (dev->driver->irq_uninstall)
145 dev->driver->irq_uninstall(dev);
148 bus_teardown_intr(dev->dev, dev->irqr, dev->irqh);
154 int drm_control(struct drm_device *dev, void *data, struct drm_file *file_priv)
156 struct drm_control *ctl = data;
160 case DRM_INST_HANDLER:
161 /* Handle drivers whose DRM used to require IRQ setup but the
164 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
166 if (drm_core_check_feature(dev, DRIVER_MODESET))
168 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
169 ctl->irq != dev->irq)
171 return drm_irq_install(dev);
172 case DRM_UNINST_HANDLER:
173 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
175 if (drm_core_check_feature(dev, DRIVER_MODESET))
178 err = drm_irq_uninstall(dev);
186 #define NSEC_PER_USEC 1000L
187 #define NSEC_PER_SEC 1000000000L
190 timeval_to_ns(const struct timeval *tv)
192 return ((int64_t)tv->tv_sec * NSEC_PER_SEC) +
193 tv->tv_usec * NSEC_PER_USEC;
197 ns_to_timeval(const int64_t nsec)
208 tv.tv_sec = nsec / NSEC_PER_SEC;
209 rem = nsec % NSEC_PER_SEC;
214 tv.tv_usec = rem / 1000;
219 * Clear vblank timestamp buffer for a crtc.
221 static void clear_vblank_timestamps(struct drm_device *dev, int crtc)
223 memset(&dev->_vblank_time[crtc * DRM_VBLANKTIME_RBSIZE], 0,
224 DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval));
231 return (x < 0 ? -x : x);
235 * Disable vblank irq's on crtc, make sure that last vblank count
236 * of hardware and corresponding consistent software vblank counter
237 * are preserved, even if there are any spurious vblank irq's after
240 static void vblank_disable_and_save(struct drm_device *dev, int crtc)
245 struct timeval tvblank;
247 /* Prevent vblank irq processing while disabling vblank irqs,
248 * so no updates of timestamps or count can happen after we've
249 * disabled. Needed to prevent races in case of delayed irq's.
251 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
253 dev->driver->disable_vblank(dev, crtc);
254 dev->vblank_enabled[crtc] = 0;
256 /* No further vblank irq's will be processed after
257 * this point. Get current hardware vblank count and
258 * vblank timestamp, repeat until they are consistent.
260 * FIXME: There is still a race condition here and in
261 * drm_update_vblank_count() which can cause off-by-one
262 * reinitialization of software vblank counter. If gpu
263 * vblank counter doesn't increment exactly at the leading
264 * edge of a vblank interval, then we can lose 1 count if
265 * we happen to execute between start of vblank and the
266 * delayed gpu counter increment.
269 dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc);
270 vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
271 } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc));
273 /* Compute time difference to stored timestamp of last vblank
274 * as updated by last invocation of drm_handle_vblank() in vblank irq.
276 vblcount = atomic_read(&dev->_vblank_count[crtc]);
277 diff_ns = timeval_to_ns(&tvblank) -
278 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
280 /* If there is at least 1 msec difference between the last stored
281 * timestamp and tvblank, then we are currently executing our
282 * disable inside a new vblank interval, the tvblank timestamp
283 * corresponds to this new vblank interval and the irq handler
284 * for this vblank didn't run yet and won't run due to our disable.
285 * Therefore we need to do the job of drm_handle_vblank() and
286 * increment the vblank counter by one to account for this vblank.
288 * Skip this step if there isn't any high precision timestamp
289 * available. In that case we can't account for this and just
292 if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
293 atomic_inc(&dev->_vblank_count[crtc]);
296 /* Invalidate all timestamps while vblank irq's are off. */
297 clear_vblank_timestamps(dev, crtc);
299 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
302 static void vblank_disable_fn(unsigned long arg)
304 struct drm_device *dev = (struct drm_device *)arg;
307 if (!dev->vblank_disable_allowed)
310 for (i = 0; i < dev->num_crtcs; i++) {
311 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
312 if (atomic_read(&dev->vblank_refcount[i]) == 0 &&
313 dev->vblank_enabled[i]) {
314 DRM_DEBUG("disabling vblank on crtc %d\n", i);
315 vblank_disable_and_save(dev, i);
317 lockmgr(&dev->vbl_lock, LK_RELEASE);
321 void drm_vblank_cleanup(struct drm_device *dev)
323 /* Bail if the driver didn't call drm_vblank_init() */
324 if (dev->num_crtcs == 0)
327 del_timer_sync(&dev->vblank_disable_timer);
329 vblank_disable_fn((unsigned long)dev);
331 drm_free(dev->_vblank_count, DRM_MEM_VBLANK);
332 drm_free(dev->vblank_refcount, DRM_MEM_VBLANK);
333 drm_free(dev->vblank_enabled, DRM_MEM_VBLANK);
334 drm_free(dev->last_vblank, DRM_MEM_VBLANK);
335 drm_free(dev->last_vblank_wait, DRM_MEM_VBLANK);
336 drm_free(dev->vblank_inmodeset, DRM_MEM_VBLANK);
337 drm_free(dev->_vblank_time, DRM_MEM_VBLANK);
341 EXPORT_SYMBOL(drm_vblank_cleanup);
343 int drm_vblank_init(struct drm_device *dev, int num_crtcs)
347 setup_timer(&dev->vblank_disable_timer, vblank_disable_fn,
349 lockinit(&dev->vblank_time_lock, "drmvtl", 0, LK_CANRECURSE);
351 dev->num_crtcs = num_crtcs;
353 dev->vbl_queue = kmalloc(sizeof(wait_queue_head_t) * num_crtcs,
354 DRM_MEM_VBLANK, M_WAITOK);
356 dev->_vblank_count = kmalloc(sizeof(atomic_t) * num_crtcs,
357 DRM_MEM_VBLANK, M_WAITOK);
358 dev->vblank_refcount = kmalloc(sizeof(atomic_t) * num_crtcs,
359 DRM_MEM_VBLANK, M_WAITOK);
360 dev->vblank_enabled = kmalloc(num_crtcs * sizeof(int),
361 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
362 dev->last_vblank = kmalloc(num_crtcs * sizeof(u32),
363 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
364 dev->last_vblank_wait = kmalloc(num_crtcs * sizeof(u32),
365 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
366 dev->vblank_inmodeset = kmalloc(num_crtcs * sizeof(int),
367 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
368 dev->_vblank_time = kmalloc(num_crtcs * DRM_VBLANKTIME_RBSIZE *
369 sizeof(struct timeval), DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
370 DRM_INFO("Supports vblank timestamp caching Rev 1 (10.10.2010).\n");
372 /* Driver specific high-precision vblank timestamping supported? */
373 if (dev->driver->get_vblank_timestamp)
374 DRM_INFO("Driver supports precise vblank timestamp query.\n");
376 DRM_INFO("No driver support for vblank timestamp query.\n");
378 /* Zero per-crtc vblank stuff */
379 for (i = 0; i < num_crtcs; i++) {
380 init_waitqueue_head(&dev->vbl_queue[i]);
381 atomic_set(&dev->_vblank_count[i], 0);
382 atomic_set(&dev->vblank_refcount[i], 0);
385 dev->vblank_disable_allowed = 0;
388 EXPORT_SYMBOL(drm_vblank_init);
391 drm_calc_timestamping_constants(struct drm_crtc *crtc)
393 int64_t linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
396 /* Dot clock in Hz: */
397 dotclock = (uint64_t) crtc->hwmode.clock * 1000;
399 /* Fields of interlaced scanout modes are only halve a frame duration.
400 * Double the dotclock to get halve the frame-/line-/pixelduration.
402 if (crtc->hwmode.flags & DRM_MODE_FLAG_INTERLACE)
405 /* Valid dotclock? */
407 /* Convert scanline length in pixels and video dot clock to
408 * line duration, frame duration and pixel duration in
411 pixeldur_ns = (int64_t)1000000000 / dotclock;
412 linedur_ns = ((uint64_t)crtc->hwmode.crtc_htotal *
413 1000000000) / dotclock;
414 framedur_ns = (int64_t)crtc->hwmode.crtc_vtotal * linedur_ns;
416 DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
419 crtc->pixeldur_ns = pixeldur_ns;
420 crtc->linedur_ns = linedur_ns;
421 crtc->framedur_ns = framedur_ns;
423 DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
424 crtc->base.id, crtc->hwmode.crtc_htotal,
425 crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay);
426 DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
427 crtc->base.id, (int) dotclock/1000, (int) framedur_ns,
428 (int) linedur_ns, (int) pixeldur_ns);
432 * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
433 * drivers. Implements calculation of exact vblank timestamps from
434 * given drm_display_mode timings and current video scanout position
435 * of a crtc. This can be called from within get_vblank_timestamp()
436 * implementation of a kms driver to implement the actual timestamping.
438 * Should return timestamps conforming to the OML_sync_control OpenML
439 * extension specification. The timestamp corresponds to the end of
440 * the vblank interval, aka start of scanout of topmost-leftmost display
441 * pixel in the following video frame.
443 * Requires support for optional dev->driver->get_scanout_position()
444 * in kms driver, plus a bit of setup code to provide a drm_display_mode
445 * that corresponds to the true scanout timing.
447 * The current implementation only handles standard video modes. It
448 * returns as no operation if a doublescan or interlaced video mode is
449 * active. Higher level code is expected to handle this.
452 * @crtc: Which crtc's vblank timestamp to retrieve.
453 * @max_error: Desired maximum allowable error in timestamps (nanosecs).
454 * On return contains true maximum error of timestamp.
455 * @vblank_time: Pointer to struct timeval which should receive the timestamp.
456 * @flags: Flags to pass to driver:
458 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
459 * @refcrtc: drm_crtc* of crtc which defines scanout timing.
461 * Returns negative value on error, failure or if not supported in current
464 * -EINVAL - Invalid crtc.
465 * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
466 * -ENOTSUPP - Function not supported in current display mode.
467 * -EIO - Failed, e.g., due to failed scanout position query.
469 * Returns or'ed positive status flags on success:
471 * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
472 * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
476 drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
477 int *max_error, struct timeval *vblank_time, unsigned flags,
478 struct drm_crtc *refcrtc)
480 struct timeval stime, raw_time;
481 struct drm_display_mode *mode;
482 int vbl_status, vtotal, vdisplay;
484 int64_t framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
487 if (crtc < 0 || crtc >= dev->num_crtcs) {
488 DRM_ERROR("Invalid crtc %d\n", crtc);
492 /* Scanout position query not supported? Should not happen. */
493 if (!dev->driver->get_scanout_position) {
494 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
498 mode = &refcrtc->hwmode;
499 vtotal = mode->crtc_vtotal;
500 vdisplay = mode->crtc_vdisplay;
502 /* Durations of frames, lines, pixels in nanoseconds. */
503 framedur_ns = refcrtc->framedur_ns;
504 linedur_ns = refcrtc->linedur_ns;
505 pixeldur_ns = refcrtc->pixeldur_ns;
507 /* If mode timing undefined, just return as no-op:
508 * Happens during initial modesetting of a crtc.
510 if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) {
511 DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
515 /* Get current scanout position with system timestamp.
516 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
517 * if single query takes longer than max_error nanoseconds.
519 * This guarantees a tight bound on maximum error if
520 * code gets preempted or delayed for some reason.
522 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
523 /* Disable preemption to make it very likely to
524 * succeed in the first iteration.
528 /* Get system timestamp before query. */
529 getmicrouptime(&stime);
531 /* Get vertical and horizontal scanout pos. vpos, hpos. */
532 vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos);
534 /* Get system timestamp after query. */
535 getmicrouptime(&raw_time);
539 /* Return as no-op if scanout query unsupported or failed. */
540 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
541 DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
546 duration_ns = timeval_to_ns(&raw_time) - timeval_to_ns(&stime);
548 /* Accept result with < max_error nsecs timing uncertainty. */
549 if (duration_ns <= (int64_t) *max_error)
553 /* Noisy system timing? */
554 if (i == DRM_TIMESTAMP_MAXRETRIES) {
555 DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
556 crtc, (int) duration_ns/1000, *max_error/1000, i);
559 /* Return upper bound of timestamp precision error. */
560 *max_error = (int) duration_ns;
562 /* Check if in vblank area:
563 * vpos is >=0 in video scanout area, but negative
564 * within vblank area, counting down the number of lines until
567 invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
569 /* Convert scanout position into elapsed time at raw_time query
570 * since start of scanout at first display scanline. delta_ns
571 * can be negative if start of scanout hasn't happened yet.
573 delta_ns = (int64_t)vpos * linedur_ns + (int64_t)hpos * pixeldur_ns;
575 /* Is vpos outside nominal vblank area, but less than
576 * 1/100 of a frame height away from start of vblank?
577 * If so, assume this isn't a massively delayed vblank
578 * interrupt, but a vblank interrupt that fired a few
579 * microseconds before true start of vblank. Compensate
580 * by adding a full frame duration to the final timestamp.
581 * Happens, e.g., on ATI R500, R600.
583 * We only do this if DRM_CALLED_FROM_VBLIRQ.
585 if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl &&
586 ((vdisplay - vpos) < vtotal / 100)) {
587 delta_ns = delta_ns - framedur_ns;
589 /* Signal this correction as "applied". */
593 /* Subtract time delta from raw timestamp to get final
594 * vblank_time timestamp for end of vblank.
596 *vblank_time = ns_to_timeval(timeval_to_ns(&raw_time) - delta_ns);
598 DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %jd.%jd -> %jd.%jd [e %d us, %d rep]\n",
599 crtc, (int)vbl_status, hpos, vpos, (uintmax_t)raw_time.tv_sec,
600 (uintmax_t)raw_time.tv_usec, (uintmax_t)vblank_time->tv_sec,
601 (uintmax_t)vblank_time->tv_usec, (int)duration_ns/1000, i);
603 vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
605 vbl_status |= DRM_VBLANKTIME_INVBL;
610 static struct timeval get_drm_timestamp(void)
614 getmicrouptime(&now);
620 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
624 * @crtc: which crtc's vblank timestamp to retrieve
625 * @tvblank: Pointer to target struct timeval which should receive the timestamp
626 * @flags: Flags to pass to driver:
628 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
630 * Fetches the system timestamp corresponding to the time of the most recent
631 * vblank interval on specified crtc. May call into kms-driver to
632 * compute the timestamp with a high-precision GPU specific method.
634 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
635 * call, i.e., it isn't very precisely locked to the true vblank.
637 * Returns non-zero if timestamp is considered to be very precise.
639 u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
640 struct timeval *tvblank, unsigned flags)
644 /* Define requested maximum error on timestamps (nanoseconds). */
645 int max_error = (int) drm_timestamp_precision * 1000;
647 /* Query driver if possible and precision timestamping enabled. */
648 if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
649 ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
655 /* GPU high precision timestamp query unsupported or failed.
656 * Return gettimeofday timestamp as best estimate.
664 * drm_vblank_count - retrieve "cooked" vblank counter value
666 * @crtc: which counter to retrieve
668 * Fetches the "cooked" vblank count value that represents the number of
669 * vblank events since the system was booted, including lost events due to
670 * modesetting activity.
672 u32 drm_vblank_count(struct drm_device *dev, int crtc)
674 return atomic_read(&dev->_vblank_count[crtc]);
678 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
679 * and the system timestamp corresponding to that vblank counter value.
682 * @crtc: which counter to retrieve
683 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
685 * Fetches the "cooked" vblank count value that represents the number of
686 * vblank events since the system was booted, including lost events due to
687 * modesetting activity. Returns corresponding system timestamp of the time
688 * of the vblank interval that corresponds to the current value vblank counter
691 u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
692 struct timeval *vblanktime)
696 /* Read timestamp from slot of _vblank_time ringbuffer
697 * that corresponds to current vblank count. Retry if
698 * count has incremented during readout. This works like
702 cur_vblank = atomic_read(&dev->_vblank_count[crtc]);
703 *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
705 } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc]));
710 static void send_vblank_event(struct drm_device *dev,
711 struct drm_pending_vblank_event *e,
712 unsigned long seq, struct timeval *now)
714 KKASSERT(mutex_is_locked(&dev->event_lock));
715 e->event.sequence = seq;
716 e->event.tv_sec = now->tv_sec;
717 e->event.tv_usec = now->tv_usec;
719 list_add_tail(&e->base.link,
720 &e->base.file_priv->event_list);
721 wakeup(&e->base.file_priv->event_list);
723 trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
729 * drm_send_vblank_event - helper to send vblank event after pageflip
731 * @crtc: CRTC in question
732 * @e: the event to send
734 * Updates sequence # and timestamp on event, and sends it to userspace.
735 * Caller must hold event lock.
737 void drm_send_vblank_event(struct drm_device *dev, int crtc,
738 struct drm_pending_vblank_event *e)
743 seq = drm_vblank_count_and_time(dev, crtc, &now);
747 now = get_drm_timestamp();
750 send_vblank_event(dev, e, seq, &now);
752 EXPORT_SYMBOL(drm_send_vblank_event);
755 * drm_update_vblank_count - update the master vblank counter
757 * @crtc: counter to update
759 * Call back into the driver to update the appropriate vblank counter
760 * (specified by @crtc). Deal with wraparound, if it occurred, and
761 * update the last read value so we can deal with wraparound on the next
764 * Only necessary when going from off->on, to account for frames we
765 * didn't get an interrupt for.
767 * Note: caller must hold dev->vbl_lock since this reads & writes
768 * device vblank fields.
770 static void drm_update_vblank_count(struct drm_device *dev, int crtc)
772 u32 cur_vblank, diff, tslot, rc;
773 struct timeval t_vblank;
776 * Interrupts were disabled prior to this call, so deal with counter
778 * NOTE! It's possible we lost a full dev->max_vblank_count events
779 * here if the register is small or we had vblank interrupts off for
782 * We repeat the hardware vblank counter & timestamp query until
783 * we get consistent results. This to prevent races between gpu
784 * updating its hardware counter while we are retrieving the
785 * corresponding vblank timestamp.
788 cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
789 rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
790 } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
792 /* Deal with counter wrap */
793 diff = cur_vblank - dev->last_vblank[crtc];
794 if (cur_vblank < dev->last_vblank[crtc]) {
795 diff += dev->max_vblank_count;
797 DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
798 crtc, dev->last_vblank[crtc], cur_vblank, diff);
801 DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
804 /* Reinitialize corresponding vblank timestamp if high-precision query
805 * available. Skip this step if query unsupported or failed. Will
806 * reinitialize delayed at next vblank interrupt in that case.
809 tslot = atomic_read(&dev->_vblank_count[crtc]) + diff;
810 vblanktimestamp(dev, crtc, tslot) = t_vblank;
813 atomic_add(diff, &dev->_vblank_count[crtc]);
817 * drm_vblank_get - get a reference count on vblank events
819 * @crtc: which CRTC to own
821 * Acquire a reference count on vblank events to avoid having them disabled
825 * Zero on success, nonzero on failure.
827 int drm_vblank_get(struct drm_device *dev, int crtc)
831 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
832 /* Going from 0->1 means we have to enable interrupts again */
833 if (atomic_add_return(1, &dev->vblank_refcount[crtc]) == 1) {
834 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
835 if (!dev->vblank_enabled[crtc]) {
836 /* Enable vblank irqs under vblank_time_lock protection.
837 * All vblank count & timestamp updates are held off
838 * until we are done reinitializing master counter and
839 * timestamps. Filtercode in drm_handle_vblank() will
840 * prevent double-accounting of same vblank interval.
842 ret = -dev->driver->enable_vblank(dev, crtc);
843 DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
846 atomic_dec(&dev->vblank_refcount[crtc]);
848 dev->vblank_enabled[crtc] = 1;
849 drm_update_vblank_count(dev, crtc);
852 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
854 if (!dev->vblank_enabled[crtc]) {
855 atomic_dec(&dev->vblank_refcount[crtc]);
859 lockmgr(&dev->vbl_lock, LK_RELEASE);
865 * drm_vblank_put - give up ownership of vblank events
867 * @crtc: which counter to give up
869 * Release ownership of a given vblank counter, turning off interrupts
870 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
872 void drm_vblank_put(struct drm_device *dev, int crtc)
874 BUG_ON(atomic_read(&dev->vblank_refcount[crtc]) == 0);
876 /* Last user schedules interrupt disable */
877 if (atomic_dec_and_test(&dev->vblank_refcount[crtc]) &&
878 (drm_vblank_offdelay > 0))
879 mod_timer(&dev->vblank_disable_timer,
880 jiffies + ((drm_vblank_offdelay * DRM_HZ)/1000));
882 EXPORT_SYMBOL(drm_vblank_put);
884 void drm_vblank_off(struct drm_device *dev, int crtc)
886 struct drm_pending_vblank_event *e, *t;
890 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
891 vblank_disable_and_save(dev, crtc);
892 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
893 wakeup(&dev->_vblank_count[crtc]);
895 /* Send any queued vblank events, lest the natives grow disquiet */
896 seq = drm_vblank_count_and_time(dev, crtc, &now);
897 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
900 DRM_DEBUG("Sending premature vblank event on disable: \
901 wanted %d, current %d\n",
902 e->event.sequence, seq);
903 list_del(&e->base.link);
904 drm_vblank_put(dev, e->pipe);
905 send_vblank_event(dev, e, seq, &now);
908 lockmgr(&dev->event_lock, LK_RELEASE);
909 lockmgr(&dev->vbl_lock, LK_RELEASE);
913 * drm_vblank_pre_modeset - account for vblanks across mode sets
915 * @crtc: CRTC in question
916 * @post: post or pre mode set?
918 * Account for vblank events across mode setting events, which will likely
919 * reset the hardware frame counter.
921 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
923 /* vblank is not initialized (IRQ not installed ?) */
927 * To avoid all the problems that might happen if interrupts
928 * were enabled/disabled around or between these calls, we just
929 * have the kernel take a reference on the CRTC (just once though
930 * to avoid corrupting the count if multiple, mismatch calls occur),
931 * so that interrupts remain enabled in the interim.
933 if (!dev->vblank_inmodeset[crtc]) {
934 dev->vblank_inmodeset[crtc] = 0x1;
935 if (drm_vblank_get(dev, crtc) == 0)
936 dev->vblank_inmodeset[crtc] |= 0x2;
940 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
943 if (dev->vblank_inmodeset[crtc]) {
944 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
945 dev->vblank_disable_allowed = 1;
946 lockmgr(&dev->vbl_lock, LK_RELEASE);
948 if (dev->vblank_inmodeset[crtc] & 0x2)
949 drm_vblank_put(dev, crtc);
951 dev->vblank_inmodeset[crtc] = 0;
956 * drm_modeset_ctl - handle vblank event counter changes across mode switch
957 * @DRM_IOCTL_ARGS: standard ioctl arguments
959 * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
960 * ioctls around modesetting so that any lost vblank events are accounted for.
962 * Generally the counter will reset across mode sets. If interrupts are
963 * enabled around this call, we don't have to do anything since the counter
964 * will have already been incremented.
966 int drm_modeset_ctl(struct drm_device *dev, void *data,
967 struct drm_file *file_priv)
969 struct drm_modeset_ctl *modeset = data;
973 /* If drm_vblank_init() hasn't been called yet, just no-op */
977 crtc = modeset->crtc;
978 if (crtc >= dev->num_crtcs) {
983 switch (modeset->cmd) {
984 case _DRM_PRE_MODESET:
985 drm_vblank_pre_modeset(dev, crtc);
987 case _DRM_POST_MODESET:
988 drm_vblank_post_modeset(dev, crtc);
1000 drm_vblank_event_destroy(struct drm_pending_event *e)
1003 drm_free(e, DRM_MEM_VBLANK);
1006 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
1007 union drm_wait_vblank *vblwait,
1008 struct drm_file *file_priv)
1010 struct drm_pending_vblank_event *e;
1015 e = kmalloc(sizeof *e, DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
1018 e->base.pid = curproc->p_pid;
1019 e->event.base.type = DRM_EVENT_VBLANK;
1020 e->event.base.length = sizeof e->event;
1021 e->event.user_data = vblwait->request.signal;
1022 e->base.event = &e->event.base;
1023 e->base.file_priv = file_priv;
1024 e->base.destroy = drm_vblank_event_destroy;
1026 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1028 if (file_priv->event_space < sizeof e->event) {
1033 file_priv->event_space -= sizeof e->event;
1034 seq = drm_vblank_count_and_time(dev, pipe, &now);
1036 if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1037 (seq - vblwait->request.sequence) <= (1 << 23)) {
1038 vblwait->request.sequence = seq + 1;
1039 vblwait->reply.sequence = vblwait->request.sequence;
1042 DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
1043 vblwait->request.sequence, seq, pipe);
1045 e->event.sequence = vblwait->request.sequence;
1046 if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1047 drm_vblank_put(dev, pipe);
1048 send_vblank_event(dev, e, seq, &now);
1049 vblwait->reply.sequence = seq;
1051 /* drm_handle_vblank_events will call drm_vblank_put */
1052 list_add_tail(&e->base.link, &dev->vblank_event_list);
1053 vblwait->reply.sequence = vblwait->request.sequence;
1056 lockmgr(&dev->event_lock, LK_RELEASE);
1061 lockmgr(&dev->event_lock, LK_RELEASE);
1062 drm_free(e, DRM_MEM_VBLANK);
1063 drm_vblank_put(dev, pipe);
1070 * \param inode device inode.
1071 * \param file_priv DRM file private.
1072 * \param cmd command.
1073 * \param data user argument, pointing to a drm_wait_vblank structure.
1074 * \return zero on success or a negative number on failure.
1076 * This function enables the vblank interrupt on the pipe requested, then
1077 * sleeps waiting for the requested sequence number to occur, and drops
1078 * the vblank interrupt refcount afterwards. (vblank irq disable follows that
1079 * after a timeout with no further vblank waits scheduled).
1081 int drm_wait_vblank(struct drm_device *dev, void *data,
1082 struct drm_file *file_priv)
1084 union drm_wait_vblank *vblwait = data;
1086 unsigned int flags, seq, crtc, high_crtc;
1088 if (/*(!drm_dev_to_irq(dev)) || */(!dev->irq_enabled))
1091 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1094 if (vblwait->request.type &
1095 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1096 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1097 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1098 vblwait->request.type,
1099 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1100 _DRM_VBLANK_HIGH_CRTC_MASK));
1104 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1105 high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1107 crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1109 crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1110 if (crtc >= dev->num_crtcs)
1113 ret = drm_vblank_get(dev, crtc);
1115 DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1118 seq = drm_vblank_count(dev, crtc);
1120 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1121 case _DRM_VBLANK_RELATIVE:
1122 vblwait->request.sequence += seq;
1123 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1124 case _DRM_VBLANK_ABSOLUTE:
1131 if (flags & _DRM_VBLANK_EVENT) {
1132 /* must hold on to the vblank ref until the event fires
1133 * drm_vblank_put will be called asynchronously
1135 return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
1138 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1139 (seq - vblwait->request.sequence) <= (1<<23)) {
1140 vblwait->request.sequence = seq + 1;
1143 dev->last_vblank_wait[crtc] = vblwait->request.sequence;
1144 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1145 while (((drm_vblank_count(dev, crtc) - vblwait->request.sequence) >
1146 (1 << 23)) && dev->irq_enabled) {
1148 * The wakeups from the drm_irq_uninstall() and
1149 * drm_vblank_off() may be lost there since vbl_lock
1150 * is not held. Then, the timeout will wake us; the 3
1151 * seconds delay should not be a problem for
1152 * application when crtc is disabled or irq
1153 * uninstalled anyway.
1155 ret = lksleep(&dev->_vblank_count[crtc], &dev->vblank_time_lock,
1156 PCATCH, "drmvbl", 3 * hz);
1160 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1165 reply_seq = drm_vblank_count_and_time(dev, crtc, &now);
1166 vblwait->reply.sequence = reply_seq;
1167 vblwait->reply.tval_sec = now.tv_sec;
1168 vblwait->reply.tval_usec = now.tv_usec;
1172 drm_vblank_put(dev, crtc);
1176 void drm_handle_vblank_events(struct drm_device *dev, int crtc)
1178 struct drm_pending_vblank_event *e, *t;
1182 seq = drm_vblank_count_and_time(dev, crtc, &now);
1184 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1186 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1187 if (e->pipe != crtc)
1189 if ((seq - e->event.sequence) > (1<<23))
1192 DRM_DEBUG("vblank event on %d, current %d\n",
1193 e->event.sequence, seq);
1195 list_del(&e->base.link);
1196 drm_vblank_put(dev, e->pipe);
1197 send_vblank_event(dev, e, seq, &now);
1200 lockmgr(&dev->event_lock, LK_RELEASE);
1204 * drm_handle_vblank - handle a vblank event
1206 * @crtc: where this event occurred
1208 * Drivers should call this routine in their vblank interrupt handlers to
1209 * update the vblank counter and send any signals that may be pending.
1211 bool drm_handle_vblank(struct drm_device *dev, int crtc)
1215 struct timeval tvblank;
1217 if (!dev->num_crtcs)
1220 /* Need timestamp lock to prevent concurrent execution with
1221 * vblank enable/disable, as this would cause inconsistent
1222 * or corrupted timestamps and vblank counts.
1224 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1226 /* Vblank irq handling disabled. Nothing to do. */
1227 if (!dev->vblank_enabled[crtc]) {
1228 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1232 /* Fetch corresponding timestamp for this vblank interval from
1233 * driver and store it in proper slot of timestamp ringbuffer.
1236 /* Get current timestamp and count. */
1237 vblcount = atomic_read(&dev->_vblank_count[crtc]);
1238 drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1240 /* Compute time difference to timestamp of last vblank */
1241 diff_ns = timeval_to_ns(&tvblank) -
1242 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1244 /* Update vblank timestamp and count if at least
1245 * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1246 * difference between last stored timestamp and current
1247 * timestamp. A smaller difference means basically
1248 * identical timestamps. Happens if this vblank has
1249 * been already processed and this is a redundant call,
1250 * e.g., due to spurious vblank interrupts. We need to
1251 * ignore those for accounting.
1253 if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
1254 /* Store new timestamp in ringbuffer. */
1255 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
1257 /* Increment cooked vblank count. This also atomically commits
1258 * the timestamp computed above.
1260 atomic_inc(&dev->_vblank_count[crtc]);
1262 DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1263 crtc, (int) diff_ns);
1266 wakeup(&dev->_vblank_count[crtc]);
1267 drm_handle_vblank_events(dev, crtc);
1269 lockmgr(&dev->vblank_time_lock, LK_RELEASE);