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 "dev/drm/drmP.h"
35 #include "dev/drm/drm.h"
37 MALLOC_DEFINE(DRM_MEM_VBLANK, "drm_vblank", "DRM VBLANK Handling Data");
39 /* Access macro for slots in vblank timestamp ringbuffer. */
40 #define vblanktimestamp(dev, crtc, count) ( \
41 (dev)->_vblank_time[(crtc) * DRM_VBLANKTIME_RBSIZE + \
42 ((count) % DRM_VBLANKTIME_RBSIZE)])
44 /* Retry timestamp calculation up to 3 times to satisfy
45 * drm_timestamp_precision before giving up.
47 #define DRM_TIMESTAMP_MAXRETRIES 3
49 /* Threshold in nanoseconds for detection of redundant
50 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
52 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
54 int drm_irq_by_busid(struct drm_device *dev, void *data,
55 struct drm_file *file_priv)
57 struct drm_irq_busid *irq = data;
59 if ((irq->busnum >> 8) != dev->pci_domain ||
60 (irq->busnum & 0xff) != dev->pci_bus ||
61 irq->devnum != dev->pci_slot ||
62 irq->funcnum != dev->pci_func)
67 DRM_DEBUG("%d:%d:%d => IRQ %d\n",
68 irq->busnum, irq->devnum, irq->funcnum, irq->irq);
74 drm_irq_install(struct drm_device *dev)
78 if (dev->irq == 0 || dev->dev_private == NULL)
81 DRM_DEBUG("irq=%d\n", dev->irq);
84 if (dev->irq_enabled) {
90 dev->context_flag = 0;
92 /* Before installing handler */
93 if (dev->driver->irq_preinstall)
94 dev->driver->irq_preinstall(dev);
98 retcode = bus_setup_intr(dev->device, dev->irqr, INTR_MPSAFE,
99 dev->driver->irq_handler, dev, &dev->irqh, &dev->irq_lock);
103 /* After installing handler */
105 if (dev->driver->irq_postinstall)
106 dev->driver->irq_postinstall(dev);
111 device_printf(dev->device, "Error setting interrupt: %d\n", retcode);
112 dev->irq_enabled = 0;
117 int drm_irq_uninstall(struct drm_device *dev)
121 if (!dev->irq_enabled)
124 dev->irq_enabled = 0;
127 * Wake up any waiters so they don't hang.
129 if (dev->num_crtcs) {
130 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
131 for (i = 0; i < dev->num_crtcs; i++) {
132 wakeup(&dev->_vblank_count[i]);
133 dev->vblank_enabled[i] = 0;
134 dev->last_vblank[i] =
135 dev->driver->get_vblank_counter(dev, i);
137 lockmgr(&dev->vbl_lock, LK_RELEASE);
140 DRM_DEBUG("irq=%d\n", dev->irq);
142 if (dev->driver->irq_uninstall)
143 dev->driver->irq_uninstall(dev);
146 bus_teardown_intr(dev->device, dev->irqr, dev->irqh);
152 int drm_control(struct drm_device *dev, void *data, struct drm_file *file_priv)
154 struct drm_control *ctl = data;
158 case DRM_INST_HANDLER:
159 /* Handle drivers whose DRM used to require IRQ setup but the
162 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
164 if (drm_core_check_feature(dev, DRIVER_MODESET))
166 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
167 ctl->irq != dev->irq)
169 return drm_irq_install(dev);
170 case DRM_UNINST_HANDLER:
171 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
173 if (drm_core_check_feature(dev, DRIVER_MODESET))
176 err = drm_irq_uninstall(dev);
184 #define NSEC_PER_USEC 1000L
185 #define NSEC_PER_SEC 1000000000L
188 timeval_to_ns(const struct timeval *tv)
190 return ((int64_t)tv->tv_sec * NSEC_PER_SEC) +
191 tv->tv_usec * NSEC_PER_USEC;
195 ns_to_timeval(const int64_t nsec)
206 tv.tv_sec = nsec / NSEC_PER_SEC;
207 rem = nsec % NSEC_PER_SEC;
212 tv.tv_usec = rem / 1000;
217 * Clear vblank timestamp buffer for a crtc.
219 static void clear_vblank_timestamps(struct drm_device *dev, int crtc)
221 memset(&dev->_vblank_time[crtc * DRM_VBLANKTIME_RBSIZE], 0,
222 DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval));
229 return (x < 0 ? -x : x);
233 * Disable vblank irq's on crtc, make sure that last vblank count
234 * of hardware and corresponding consistent software vblank counter
235 * are preserved, even if there are any spurious vblank irq's after
238 static void vblank_disable_and_save(struct drm_device *dev, int crtc)
243 struct timeval tvblank;
245 /* Prevent vblank irq processing while disabling vblank irqs,
246 * so no updates of timestamps or count can happen after we've
247 * disabled. Needed to prevent races in case of delayed irq's.
249 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
251 dev->driver->disable_vblank(dev, crtc);
252 dev->vblank_enabled[crtc] = 0;
254 /* No further vblank irq's will be processed after
255 * this point. Get current hardware vblank count and
256 * vblank timestamp, repeat until they are consistent.
258 * FIXME: There is still a race condition here and in
259 * drm_update_vblank_count() which can cause off-by-one
260 * reinitialization of software vblank counter. If gpu
261 * vblank counter doesn't increment exactly at the leading
262 * edge of a vblank interval, then we can lose 1 count if
263 * we happen to execute between start of vblank and the
264 * delayed gpu counter increment.
267 dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc);
268 vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
269 } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc));
271 /* Compute time difference to stored timestamp of last vblank
272 * as updated by last invocation of drm_handle_vblank() in vblank irq.
274 vblcount = atomic_read(&dev->_vblank_count[crtc]);
275 diff_ns = timeval_to_ns(&tvblank) -
276 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
278 /* If there is at least 1 msec difference between the last stored
279 * timestamp and tvblank, then we are currently executing our
280 * disable inside a new vblank interval, the tvblank timestamp
281 * corresponds to this new vblank interval and the irq handler
282 * for this vblank didn't run yet and won't run due to our disable.
283 * Therefore we need to do the job of drm_handle_vblank() and
284 * increment the vblank counter by one to account for this vblank.
286 * Skip this step if there isn't any high precision timestamp
287 * available. In that case we can't account for this and just
290 if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
291 atomic_inc(&dev->_vblank_count[crtc]);
294 /* Invalidate all timestamps while vblank irq's are off. */
295 clear_vblank_timestamps(dev, crtc);
297 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
300 static void vblank_disable_fn(void * arg)
302 struct drm_device *dev = (struct drm_device *)arg;
305 if (!dev->vblank_disable_allowed)
308 for (i = 0; i < dev->num_crtcs; i++) {
309 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
310 if (atomic_read(&dev->vblank_refcount[i]) == 0 &&
311 dev->vblank_enabled[i]) {
312 DRM_DEBUG("disabling vblank on crtc %d\n", i);
313 vblank_disable_and_save(dev, i);
315 lockmgr(&dev->vbl_lock, LK_RELEASE);
319 void drm_vblank_cleanup(struct drm_device *dev)
321 /* Bail if the driver didn't call drm_vblank_init() */
322 if (dev->num_crtcs == 0)
325 callout_stop(&dev->vblank_disable_callout);
327 vblank_disable_fn(dev);
329 drm_free(dev->_vblank_count, DRM_MEM_VBLANK);
330 drm_free(dev->vblank_refcount, DRM_MEM_VBLANK);
331 drm_free(dev->vblank_enabled, DRM_MEM_VBLANK);
332 drm_free(dev->last_vblank, DRM_MEM_VBLANK);
333 drm_free(dev->last_vblank_wait, DRM_MEM_VBLANK);
334 drm_free(dev->vblank_inmodeset, DRM_MEM_VBLANK);
335 drm_free(dev->_vblank_time, DRM_MEM_VBLANK);
340 int drm_vblank_init(struct drm_device *dev, int num_crtcs)
344 callout_init_mp(&dev->vblank_disable_callout);
346 mtx_init(&dev->vbl_lock, "drmvbl", NULL, MTX_DEF);
348 lockinit(&dev->vblank_time_lock, "drmvtl", 0, LK_CANRECURSE);
350 dev->num_crtcs = num_crtcs;
352 dev->_vblank_count = kmalloc(sizeof(atomic_t) * num_crtcs,
353 DRM_MEM_VBLANK, M_WAITOK);
354 dev->vblank_refcount = kmalloc(sizeof(atomic_t) * num_crtcs,
355 DRM_MEM_VBLANK, M_WAITOK);
356 dev->vblank_enabled = kmalloc(num_crtcs * sizeof(int),
357 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
358 dev->last_vblank = kmalloc(num_crtcs * sizeof(u32),
359 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
360 dev->last_vblank_wait = kmalloc(num_crtcs * sizeof(u32),
361 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
362 dev->vblank_inmodeset = kmalloc(num_crtcs * sizeof(int),
363 DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
364 dev->_vblank_time = kmalloc(num_crtcs * DRM_VBLANKTIME_RBSIZE *
365 sizeof(struct timeval), DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
366 DRM_INFO("Supports vblank timestamp caching Rev 1 (10.10.2010).\n");
368 /* Driver specific high-precision vblank timestamping supported? */
369 if (dev->driver->get_vblank_timestamp)
370 DRM_INFO("Driver supports precise vblank timestamp query.\n");
372 DRM_INFO("No driver support for vblank timestamp query.\n");
374 /* Zero per-crtc vblank stuff */
375 for (i = 0; i < num_crtcs; i++) {
376 atomic_set(&dev->_vblank_count[i], 0);
377 atomic_set(&dev->vblank_refcount[i], 0);
380 dev->vblank_disable_allowed = 0;
385 drm_calc_timestamping_constants(struct drm_crtc *crtc)
387 int64_t linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
390 /* Dot clock in Hz: */
391 dotclock = (uint64_t) crtc->hwmode.clock * 1000;
393 /* Fields of interlaced scanout modes are only halve a frame duration.
394 * Double the dotclock to get halve the frame-/line-/pixelduration.
396 if (crtc->hwmode.flags & DRM_MODE_FLAG_INTERLACE)
399 /* Valid dotclock? */
401 /* Convert scanline length in pixels and video dot clock to
402 * line duration, frame duration and pixel duration in
405 pixeldur_ns = (int64_t)1000000000 / dotclock;
406 linedur_ns = ((uint64_t)crtc->hwmode.crtc_htotal *
407 1000000000) / dotclock;
408 framedur_ns = (int64_t)crtc->hwmode.crtc_vtotal * linedur_ns;
410 DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
413 crtc->pixeldur_ns = pixeldur_ns;
414 crtc->linedur_ns = linedur_ns;
415 crtc->framedur_ns = framedur_ns;
417 DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
418 crtc->base.id, crtc->hwmode.crtc_htotal,
419 crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay);
420 DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
421 crtc->base.id, (int) dotclock/1000, (int) framedur_ns,
422 (int) linedur_ns, (int) pixeldur_ns);
426 * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
427 * drivers. Implements calculation of exact vblank timestamps from
428 * given drm_display_mode timings and current video scanout position
429 * of a crtc. This can be called from within get_vblank_timestamp()
430 * implementation of a kms driver to implement the actual timestamping.
432 * Should return timestamps conforming to the OML_sync_control OpenML
433 * extension specification. The timestamp corresponds to the end of
434 * the vblank interval, aka start of scanout of topmost-leftmost display
435 * pixel in the following video frame.
437 * Requires support for optional dev->driver->get_scanout_position()
438 * in kms driver, plus a bit of setup code to provide a drm_display_mode
439 * that corresponds to the true scanout timing.
441 * The current implementation only handles standard video modes. It
442 * returns as no operation if a doublescan or interlaced video mode is
443 * active. Higher level code is expected to handle this.
446 * @crtc: Which crtc's vblank timestamp to retrieve.
447 * @max_error: Desired maximum allowable error in timestamps (nanosecs).
448 * On return contains true maximum error of timestamp.
449 * @vblank_time: Pointer to struct timeval which should receive the timestamp.
450 * @flags: Flags to pass to driver:
452 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
453 * @refcrtc: drm_crtc* of crtc which defines scanout timing.
455 * Returns negative value on error, failure or if not supported in current
458 * -EINVAL - Invalid crtc.
459 * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
460 * -ENOTSUPP - Function not supported in current display mode.
461 * -EIO - Failed, e.g., due to failed scanout position query.
463 * Returns or'ed positive status flags on success:
465 * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
466 * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
470 drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
471 int *max_error, struct timeval *vblank_time, unsigned flags,
472 struct drm_crtc *refcrtc)
474 struct timeval stime, raw_time;
475 struct drm_display_mode *mode;
476 int vbl_status, vtotal, vdisplay;
478 int64_t framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
481 if (crtc < 0 || crtc >= dev->num_crtcs) {
482 DRM_ERROR("Invalid crtc %d\n", crtc);
486 /* Scanout position query not supported? Should not happen. */
487 if (!dev->driver->get_scanout_position) {
488 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
492 mode = &refcrtc->hwmode;
493 vtotal = mode->crtc_vtotal;
494 vdisplay = mode->crtc_vdisplay;
496 /* Durations of frames, lines, pixels in nanoseconds. */
497 framedur_ns = refcrtc->framedur_ns;
498 linedur_ns = refcrtc->linedur_ns;
499 pixeldur_ns = refcrtc->pixeldur_ns;
501 /* If mode timing undefined, just return as no-op:
502 * Happens during initial modesetting of a crtc.
504 if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) {
505 DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
509 /* Get current scanout position with system timestamp.
510 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
511 * if single query takes longer than max_error nanoseconds.
513 * This guarantees a tight bound on maximum error if
514 * code gets preempted or delayed for some reason.
516 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
517 /* Disable preemption to make it very likely to
518 * succeed in the first iteration.
522 /* Get system timestamp before query. */
523 getmicrouptime(&stime);
525 /* Get vertical and horizontal scanout pos. vpos, hpos. */
526 vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos);
528 /* Get system timestamp after query. */
529 getmicrouptime(&raw_time);
533 /* Return as no-op if scanout query unsupported or failed. */
534 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
535 DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
540 duration_ns = timeval_to_ns(&raw_time) - timeval_to_ns(&stime);
542 /* Accept result with < max_error nsecs timing uncertainty. */
543 if (duration_ns <= (int64_t) *max_error)
547 /* Noisy system timing? */
548 if (i == DRM_TIMESTAMP_MAXRETRIES) {
549 DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
550 crtc, (int) duration_ns/1000, *max_error/1000, i);
553 /* Return upper bound of timestamp precision error. */
554 *max_error = (int) duration_ns;
556 /* Check if in vblank area:
557 * vpos is >=0 in video scanout area, but negative
558 * within vblank area, counting down the number of lines until
561 invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
563 /* Convert scanout position into elapsed time at raw_time query
564 * since start of scanout at first display scanline. delta_ns
565 * can be negative if start of scanout hasn't happened yet.
567 delta_ns = (int64_t)vpos * linedur_ns + (int64_t)hpos * pixeldur_ns;
569 /* Is vpos outside nominal vblank area, but less than
570 * 1/100 of a frame height away from start of vblank?
571 * If so, assume this isn't a massively delayed vblank
572 * interrupt, but a vblank interrupt that fired a few
573 * microseconds before true start of vblank. Compensate
574 * by adding a full frame duration to the final timestamp.
575 * Happens, e.g., on ATI R500, R600.
577 * We only do this if DRM_CALLED_FROM_VBLIRQ.
579 if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl &&
580 ((vdisplay - vpos) < vtotal / 100)) {
581 delta_ns = delta_ns - framedur_ns;
583 /* Signal this correction as "applied". */
587 /* Subtract time delta from raw timestamp to get final
588 * vblank_time timestamp for end of vblank.
590 *vblank_time = ns_to_timeval(timeval_to_ns(&raw_time) - delta_ns);
592 DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %jd.%jd -> %jd.%jd [e %d us, %d rep]\n",
593 crtc, (int)vbl_status, hpos, vpos, (uintmax_t)raw_time.tv_sec,
594 (uintmax_t)raw_time.tv_usec, (uintmax_t)vblank_time->tv_sec,
595 (uintmax_t)vblank_time->tv_usec, (int)duration_ns/1000, i);
597 vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
599 vbl_status |= DRM_VBLANKTIME_INVBL;
605 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
609 * @crtc: which crtc's vblank timestamp to retrieve
610 * @tvblank: Pointer to target struct timeval which should receive the timestamp
611 * @flags: Flags to pass to driver:
613 * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
615 * Fetches the system timestamp corresponding to the time of the most recent
616 * vblank interval on specified crtc. May call into kms-driver to
617 * compute the timestamp with a high-precision GPU specific method.
619 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
620 * call, i.e., it isn't very precisely locked to the true vblank.
622 * Returns non-zero if timestamp is considered to be very precise.
624 u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
625 struct timeval *tvblank, unsigned flags)
629 /* Define requested maximum error on timestamps (nanoseconds). */
630 int max_error = (int) drm_timestamp_precision * 1000;
632 /* Query driver if possible and precision timestamping enabled. */
633 if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
634 ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
640 /* GPU high precision timestamp query unsupported or failed.
641 * Return gettimeofday timestamp as best estimate.
649 * drm_vblank_count - retrieve "cooked" vblank counter value
651 * @crtc: which counter to retrieve
653 * Fetches the "cooked" vblank count value that represents the number of
654 * vblank events since the system was booted, including lost events due to
655 * modesetting activity.
657 u32 drm_vblank_count(struct drm_device *dev, int crtc)
659 return atomic_read(&dev->_vblank_count[crtc]);
663 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
664 * and the system timestamp corresponding to that vblank counter value.
667 * @crtc: which counter to retrieve
668 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
670 * Fetches the "cooked" vblank count value that represents the number of
671 * vblank events since the system was booted, including lost events due to
672 * modesetting activity. Returns corresponding system timestamp of the time
673 * of the vblank interval that corresponds to the current value vblank counter
676 u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
677 struct timeval *vblanktime)
681 /* Read timestamp from slot of _vblank_time ringbuffer
682 * that corresponds to current vblank count. Retry if
683 * count has incremented during readout. This works like
687 cur_vblank = atomic_read(&dev->_vblank_count[crtc]);
688 *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
690 } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc]));
696 * drm_update_vblank_count - update the master vblank counter
698 * @crtc: counter to update
700 * Call back into the driver to update the appropriate vblank counter
701 * (specified by @crtc). Deal with wraparound, if it occurred, and
702 * update the last read value so we can deal with wraparound on the next
705 * Only necessary when going from off->on, to account for frames we
706 * didn't get an interrupt for.
708 * Note: caller must hold dev->vbl_lock since this reads & writes
709 * device vblank fields.
711 static void drm_update_vblank_count(struct drm_device *dev, int crtc)
713 u32 cur_vblank, diff, tslot, rc;
714 struct timeval t_vblank;
717 * Interrupts were disabled prior to this call, so deal with counter
719 * NOTE! It's possible we lost a full dev->max_vblank_count events
720 * here if the register is small or we had vblank interrupts off for
723 * We repeat the hardware vblank counter & timestamp query until
724 * we get consistent results. This to prevent races between gpu
725 * updating its hardware counter while we are retrieving the
726 * corresponding vblank timestamp.
729 cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
730 rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
731 } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
733 /* Deal with counter wrap */
734 diff = cur_vblank - dev->last_vblank[crtc];
735 if (cur_vblank < dev->last_vblank[crtc]) {
736 diff += dev->max_vblank_count;
738 DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
739 crtc, dev->last_vblank[crtc], cur_vblank, diff);
742 DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
745 /* Reinitialize corresponding vblank timestamp if high-precision query
746 * available. Skip this step if query unsupported or failed. Will
747 * reinitialize delayed at next vblank interrupt in that case.
750 tslot = atomic_read(&dev->_vblank_count[crtc]) + diff;
751 vblanktimestamp(dev, crtc, tslot) = t_vblank;
754 atomic_add(diff, &dev->_vblank_count[crtc]);
758 * drm_vblank_get - get a reference count on vblank events
760 * @crtc: which CRTC to own
762 * Acquire a reference count on vblank events to avoid having them disabled
766 * Zero on success, nonzero on failure.
768 int drm_vblank_get(struct drm_device *dev, int crtc)
772 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
773 /* Going from 0->1 means we have to enable interrupts again */
774 if (atomic_fetchadd_int(&dev->vblank_refcount[crtc], 1) == 0) {
775 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
776 if (!dev->vblank_enabled[crtc]) {
777 /* Enable vblank irqs under vblank_time_lock protection.
778 * All vblank count & timestamp updates are held off
779 * until we are done reinitializing master counter and
780 * timestamps. Filtercode in drm_handle_vblank() will
781 * prevent double-accounting of same vblank interval.
783 ret = -dev->driver->enable_vblank(dev, crtc);
784 DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
787 atomic_dec(&dev->vblank_refcount[crtc]);
789 dev->vblank_enabled[crtc] = 1;
790 drm_update_vblank_count(dev, crtc);
793 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
795 if (!dev->vblank_enabled[crtc]) {
796 atomic_dec(&dev->vblank_refcount[crtc]);
800 lockmgr(&dev->vbl_lock, LK_RELEASE);
806 * drm_vblank_put - give up ownership of vblank events
808 * @crtc: which counter to give up
810 * Release ownership of a given vblank counter, turning off interrupts
811 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
813 void drm_vblank_put(struct drm_device *dev, int crtc)
815 KASSERT(atomic_read(&dev->vblank_refcount[crtc]) != 0,
816 ("Too many drm_vblank_put for crtc %d", crtc));
818 /* Last user schedules interrupt disable */
819 if (atomic_fetchadd_int(&dev->vblank_refcount[crtc], -1) == 1 &&
820 (drm_vblank_offdelay > 0))
821 callout_reset(&dev->vblank_disable_callout,
822 (drm_vblank_offdelay * DRM_HZ) / 1000,
823 vblank_disable_fn, dev);
826 void drm_vblank_off(struct drm_device *dev, int crtc)
828 struct drm_pending_vblank_event *e, *t;
832 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
833 vblank_disable_and_save(dev, crtc);
834 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
835 wakeup(&dev->_vblank_count[crtc]);
837 /* Send any queued vblank events, lest the natives grow disquiet */
838 seq = drm_vblank_count_and_time(dev, crtc, &now);
839 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
842 DRM_DEBUG("Sending premature vblank event on disable: \
843 wanted %d, current %d\n",
844 e->event.sequence, seq);
846 e->event.sequence = seq;
847 e->event.tv_sec = now.tv_sec;
848 e->event.tv_usec = now.tv_usec;
849 drm_vblank_put(dev, e->pipe);
850 list_move_tail(&e->base.link, &e->base.file_priv->event_list);
851 drm_event_wakeup(&e->base);
854 lockmgr(&dev->event_lock, LK_RELEASE);
855 lockmgr(&dev->vbl_lock, LK_RELEASE);
859 * drm_vblank_pre_modeset - account for vblanks across mode sets
861 * @crtc: CRTC in question
862 * @post: post or pre mode set?
864 * Account for vblank events across mode setting events, which will likely
865 * reset the hardware frame counter.
867 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
869 /* vblank is not initialized (IRQ not installed ?) */
873 * To avoid all the problems that might happen if interrupts
874 * were enabled/disabled around or between these calls, we just
875 * have the kernel take a reference on the CRTC (just once though
876 * to avoid corrupting the count if multiple, mismatch calls occur),
877 * so that interrupts remain enabled in the interim.
879 if (!dev->vblank_inmodeset[crtc]) {
880 dev->vblank_inmodeset[crtc] = 0x1;
881 if (drm_vblank_get(dev, crtc) == 0)
882 dev->vblank_inmodeset[crtc] |= 0x2;
886 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
889 if (dev->vblank_inmodeset[crtc]) {
890 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
891 dev->vblank_disable_allowed = 1;
892 lockmgr(&dev->vbl_lock, LK_RELEASE);
894 if (dev->vblank_inmodeset[crtc] & 0x2)
895 drm_vblank_put(dev, crtc);
897 dev->vblank_inmodeset[crtc] = 0;
902 * drm_modeset_ctl - handle vblank event counter changes across mode switch
903 * @DRM_IOCTL_ARGS: standard ioctl arguments
905 * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
906 * ioctls around modesetting so that any lost vblank events are accounted for.
908 * Generally the counter will reset across mode sets. If interrupts are
909 * enabled around this call, we don't have to do anything since the counter
910 * will have already been incremented.
912 int drm_modeset_ctl(struct drm_device *dev, void *data,
913 struct drm_file *file_priv)
915 struct drm_modeset_ctl *modeset = data;
919 /* If drm_vblank_init() hasn't been called yet, just no-op */
923 crtc = modeset->crtc;
924 if (crtc >= dev->num_crtcs) {
929 switch (modeset->cmd) {
930 case _DRM_PRE_MODESET:
931 drm_vblank_pre_modeset(dev, crtc);
933 case _DRM_POST_MODESET:
934 drm_vblank_post_modeset(dev, crtc);
946 drm_vblank_event_destroy(struct drm_pending_event *e)
949 drm_free(e, DRM_MEM_VBLANK);
952 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
953 union drm_wait_vblank *vblwait,
954 struct drm_file *file_priv)
956 struct drm_pending_vblank_event *e;
961 e = kmalloc(sizeof *e, DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
964 e->base.pid = curproc->p_pid;
965 e->event.base.type = DRM_EVENT_VBLANK;
966 e->event.base.length = sizeof e->event;
967 e->event.user_data = vblwait->request.signal;
968 e->base.event = &e->event.base;
969 e->base.file_priv = file_priv;
970 e->base.destroy = drm_vblank_event_destroy;
972 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
974 if (file_priv->event_space < sizeof e->event) {
979 file_priv->event_space -= sizeof e->event;
980 seq = drm_vblank_count_and_time(dev, pipe, &now);
982 if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
983 (seq - vblwait->request.sequence) <= (1 << 23)) {
984 vblwait->request.sequence = seq + 1;
985 vblwait->reply.sequence = vblwait->request.sequence;
988 DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
989 vblwait->request.sequence, seq, pipe);
991 e->event.sequence = vblwait->request.sequence;
992 if ((seq - vblwait->request.sequence) <= (1 << 23)) {
993 e->event.sequence = seq;
994 e->event.tv_sec = now.tv_sec;
995 e->event.tv_usec = now.tv_usec;
996 drm_vblank_put(dev, pipe);
997 list_add_tail(&e->base.link, &e->base.file_priv->event_list);
998 drm_event_wakeup(&e->base);
999 vblwait->reply.sequence = seq;
1001 /* drm_handle_vblank_events will call drm_vblank_put */
1002 list_add_tail(&e->base.link, &dev->vblank_event_list);
1003 vblwait->reply.sequence = vblwait->request.sequence;
1006 lockmgr(&dev->event_lock, LK_RELEASE);
1011 lockmgr(&dev->event_lock, LK_RELEASE);
1012 drm_free(e, DRM_MEM_VBLANK);
1013 drm_vblank_put(dev, pipe);
1020 * \param inode device inode.
1021 * \param file_priv DRM file private.
1022 * \param cmd command.
1023 * \param data user argument, pointing to a drm_wait_vblank structure.
1024 * \return zero on success or a negative number on failure.
1026 * This function enables the vblank interrupt on the pipe requested, then
1027 * sleeps waiting for the requested sequence number to occur, and drops
1028 * the vblank interrupt refcount afterwards. (vblank irq disable follows that
1029 * after a timeout with no further vblank waits scheduled).
1031 int drm_wait_vblank(struct drm_device *dev, void *data,
1032 struct drm_file *file_priv)
1034 union drm_wait_vblank *vblwait = data;
1036 unsigned int flags, seq, crtc, high_crtc;
1038 if (/*(!drm_dev_to_irq(dev)) || */(!dev->irq_enabled))
1041 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1044 if (vblwait->request.type &
1045 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1046 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1047 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1048 vblwait->request.type,
1049 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1050 _DRM_VBLANK_HIGH_CRTC_MASK));
1054 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1055 high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1057 crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1059 crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1060 if (crtc >= dev->num_crtcs)
1063 ret = drm_vblank_get(dev, crtc);
1065 DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1068 seq = drm_vblank_count(dev, crtc);
1070 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1071 case _DRM_VBLANK_RELATIVE:
1072 vblwait->request.sequence += seq;
1073 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1074 case _DRM_VBLANK_ABSOLUTE:
1081 if (flags & _DRM_VBLANK_EVENT) {
1082 /* must hold on to the vblank ref until the event fires
1083 * drm_vblank_put will be called asynchronously
1085 return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
1088 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1089 (seq - vblwait->request.sequence) <= (1<<23)) {
1090 vblwait->request.sequence = seq + 1;
1093 dev->last_vblank_wait[crtc] = vblwait->request.sequence;
1094 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1095 while (((drm_vblank_count(dev, crtc) - vblwait->request.sequence) >
1096 (1 << 23)) && dev->irq_enabled) {
1098 * The wakeups from the drm_irq_uninstall() and
1099 * drm_vblank_off() may be lost there since vbl_lock
1100 * is not held. Then, the timeout will wake us; the 3
1101 * seconds delay should not be a problem for
1102 * application when crtc is disabled or irq
1103 * uninstalled anyway.
1105 ret = lksleep(&dev->_vblank_count[crtc], &dev->vblank_time_lock,
1106 PCATCH, "drmvbl", 3 * hz);
1110 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1115 reply_seq = drm_vblank_count_and_time(dev, crtc, &now);
1116 vblwait->reply.sequence = reply_seq;
1117 vblwait->reply.tval_sec = now.tv_sec;
1118 vblwait->reply.tval_usec = now.tv_usec;
1122 drm_vblank_put(dev, crtc);
1126 void drm_handle_vblank_events(struct drm_device *dev, int crtc)
1128 struct drm_pending_vblank_event *e, *t;
1132 seq = drm_vblank_count_and_time(dev, crtc, &now);
1134 lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1136 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1137 if (e->pipe != crtc)
1139 if ((seq - e->event.sequence) > (1<<23))
1142 e->event.sequence = seq;
1143 e->event.tv_sec = now.tv_sec;
1144 e->event.tv_usec = now.tv_usec;
1145 drm_vblank_put(dev, e->pipe);
1146 list_move_tail(&e->base.link, &e->base.file_priv->event_list);
1147 drm_event_wakeup(&e->base);
1150 lockmgr(&dev->event_lock, LK_RELEASE);
1154 * drm_handle_vblank - handle a vblank event
1156 * @crtc: where this event occurred
1158 * Drivers should call this routine in their vblank interrupt handlers to
1159 * update the vblank counter and send any signals that may be pending.
1161 bool drm_handle_vblank(struct drm_device *dev, int crtc)
1165 struct timeval tvblank;
1167 if (!dev->num_crtcs)
1170 /* Need timestamp lock to prevent concurrent execution with
1171 * vblank enable/disable, as this would cause inconsistent
1172 * or corrupted timestamps and vblank counts.
1174 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1176 /* Vblank irq handling disabled. Nothing to do. */
1177 if (!dev->vblank_enabled[crtc]) {
1178 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1182 /* Fetch corresponding timestamp for this vblank interval from
1183 * driver and store it in proper slot of timestamp ringbuffer.
1186 /* Get current timestamp and count. */
1187 vblcount = atomic_read(&dev->_vblank_count[crtc]);
1188 drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1190 /* Compute time difference to timestamp of last vblank */
1191 diff_ns = timeval_to_ns(&tvblank) -
1192 timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1194 /* Update vblank timestamp and count if at least
1195 * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1196 * difference between last stored timestamp and current
1197 * timestamp. A smaller difference means basically
1198 * identical timestamps. Happens if this vblank has
1199 * been already processed and this is a redundant call,
1200 * e.g., due to spurious vblank interrupts. We need to
1201 * ignore those for accounting.
1203 if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
1204 /* Store new timestamp in ringbuffer. */
1205 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
1207 /* Increment cooked vblank count. This also atomically commits
1208 * the timestamp computed above.
1210 atomic_inc(&dev->_vblank_count[crtc]);
1212 DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1213 crtc, (int) diff_ns);
1216 wakeup(&dev->_vblank_count[crtc]);
1217 drm_handle_vblank_events(dev, crtc);
1219 lockmgr(&dev->vblank_time_lock, LK_RELEASE);