2 * drm_irq.c IRQ and vblank support
4 * \author Rickard E. (Rik) Faith <faith@valinux.com>
5 * \author Gareth Hughes <gareth@valinux.com>
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
27 #include <linux/export.h>
28 #include <linux/moduleparam.h>
30 #include <drm/drm_crtc.h>
31 #include <drm/drm_drv.h>
32 #include <drm/drm_framebuffer.h>
33 #include <drm/drm_print.h>
34 #include <drm/drm_os_linux.h>
35 #include <drm/drm_vblank.h>
37 #include "drm_internal.h"
38 #include "drm_trace.h"
41 * DOC: vblank handling
43 * Vertical blanking plays a major role in graphics rendering. To achieve
44 * tear-free display, users must synchronize page flips and/or rendering to
45 * vertical blanking. The DRM API offers ioctls to perform page flips
46 * synchronized to vertical blanking and wait for vertical blanking.
48 * The DRM core handles most of the vertical blanking management logic, which
49 * involves filtering out spurious interrupts, keeping race-free blanking
50 * counters, coping with counter wrap-around and resets and keeping use counts.
51 * It relies on the driver to generate vertical blanking interrupts and
52 * optionally provide a hardware vertical blanking counter.
54 * Drivers must initialize the vertical blanking handling core with a call to
55 * drm_vblank_init(). Minimally, a driver needs to implement
56 * &drm_crtc_funcs.enable_vblank and &drm_crtc_funcs.disable_vblank plus call
57 * drm_crtc_handle_vblank() in its vblank interrupt handler for working vblank
60 * Vertical blanking interrupts can be enabled by the DRM core or by drivers
61 * themselves (for instance to handle page flipping operations). The DRM core
62 * maintains a vertical blanking use count to ensure that the interrupts are not
63 * disabled while a user still needs them. To increment the use count, drivers
64 * call drm_crtc_vblank_get() and release the vblank reference again with
65 * drm_crtc_vblank_put(). In between these two calls vblank interrupts are
66 * guaranteed to be enabled.
68 * On many hardware disabling the vblank interrupt cannot be done in a race-free
69 * manner, see &drm_driver.vblank_disable_immediate and
70 * &drm_driver.max_vblank_count. In that case the vblank core only disables the
71 * vblanks after a timer has expired, which can be configured through the
72 * ``vblankoffdelay`` module parameter.
75 /* Retry timestamp calculation up to 3 times to satisfy
76 * drm_timestamp_precision before giving up.
78 #define DRM_TIMESTAMP_MAXRETRIES 3
80 /* Threshold in nanoseconds for detection of redundant
81 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
83 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
86 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
87 ktime_t *tvblank, bool in_vblank_irq);
89 static unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
91 static int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
93 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
94 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
95 MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
96 MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
98 static void store_vblank(struct drm_device *dev, unsigned int pipe,
100 ktime_t t_vblank, u32 last)
102 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
104 assert_spin_locked(&dev->vblank_time_lock);
108 write_seqlock(&vblank->seqlock);
109 vblank->time = t_vblank;
110 vblank->count += vblank_count_inc;
111 write_sequnlock(&vblank->seqlock);
114 static u32 drm_max_vblank_count(struct drm_device *dev, unsigned int pipe)
116 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
118 return vblank->max_vblank_count ?: dev->max_vblank_count;
122 * "No hw counter" fallback implementation of .get_vblank_counter() hook,
123 * if there is no useable hardware frame counter available.
125 static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
127 WARN_ON_ONCE(drm_max_vblank_count(dev, pipe) != 0);
131 static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
133 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
134 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
139 if (crtc->funcs->get_vblank_counter)
140 return crtc->funcs->get_vblank_counter(crtc);
143 if (dev->driver->get_vblank_counter)
144 return dev->driver->get_vblank_counter(dev, pipe);
146 return drm_vblank_no_hw_counter(dev, pipe);
150 * Reset the stored timestamp for the current vblank count to correspond
151 * to the last vblank occurred.
153 * Only to be called from drm_crtc_vblank_on().
155 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
156 * device vblank fields.
158 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
163 int count = DRM_TIMESTAMP_MAXRETRIES;
165 spin_lock(&dev->vblank_time_lock);
168 * sample the current counter to avoid random jumps
169 * when drm_vblank_enable() applies the diff
172 cur_vblank = __get_vblank_counter(dev, pipe);
173 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
174 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
177 * Only reinitialize corresponding vblank timestamp if high-precision query
178 * available and didn't fail. Otherwise reinitialize delayed at next vblank
179 * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
185 * +1 to make sure user will never see the same
186 * vblank counter value before and after a modeset
188 store_vblank(dev, pipe, 1, t_vblank, cur_vblank);
190 spin_unlock(&dev->vblank_time_lock);
194 * Call back into the driver to update the appropriate vblank counter
195 * (specified by @pipe). Deal with wraparound, if it occurred, and
196 * update the last read value so we can deal with wraparound on the next
199 * Only necessary when going from off->on, to account for frames we
200 * didn't get an interrupt for.
202 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
203 * device vblank fields.
205 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
208 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
209 u32 cur_vblank, diff;
212 int count = DRM_TIMESTAMP_MAXRETRIES;
213 int framedur_ns = vblank->framedur_ns;
214 u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
217 * Interrupts were disabled prior to this call, so deal with counter
219 * NOTE! It's possible we lost a full dev->max_vblank_count + 1 events
220 * here if the register is small or we had vblank interrupts off for
223 * We repeat the hardware vblank counter & timestamp query until
224 * we get consistent results. This to prevent races between gpu
225 * updating its hardware counter while we are retrieving the
226 * corresponding vblank timestamp.
229 cur_vblank = __get_vblank_counter(dev, pipe);
230 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, in_vblank_irq);
231 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
233 if (max_vblank_count) {
234 /* trust the hw counter when it's around */
235 diff = (cur_vblank - vblank->last) & max_vblank_count;
236 } else if (rc && framedur_ns) {
237 u64 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
240 * Figure out how many vblanks we've missed based
241 * on the difference in the timestamps and the
242 * frame/field duration.
244 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
246 if (diff == 0 && in_vblank_irq)
247 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored."
248 " diff_ns = %lld, framedur_ns = %d)\n",
249 pipe, (long long) diff_ns, framedur_ns);
251 /* some kind of default for drivers w/o accurate vbl timestamping */
252 diff = in_vblank_irq ? 1 : 0;
256 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
257 * interval? If so then vblank irqs keep running and it will likely
258 * happen that the hardware vblank counter is not trustworthy as it
259 * might reset at some point in that interval and vblank timestamps
260 * are not trustworthy either in that interval. Iow. this can result
261 * in a bogus diff >> 1 which must be avoided as it would cause
262 * random large forward jumps of the software vblank counter.
264 if (diff > 1 && (vblank->inmodeset & 0x2)) {
265 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
266 " due to pre-modeset.\n", pipe, diff);
270 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
271 " current=%llu, diff=%u, hw=%u hw_last=%u\n",
272 pipe, vblank->count, diff, cur_vblank, vblank->last);
275 WARN_ON_ONCE(cur_vblank != vblank->last);
280 * Only reinitialize corresponding vblank timestamp if high-precision query
281 * available and didn't fail, or we were called from the vblank interrupt.
282 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
283 * for now, to mark the vblanktimestamp as invalid.
285 if (!rc && !in_vblank_irq)
288 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
291 static u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
293 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
295 if (WARN_ON(pipe >= dev->num_crtcs))
298 return vblank->count;
302 * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
303 * @crtc: which counter to retrieve
305 * This function is similar to drm_crtc_vblank_count() but this function
306 * interpolates to handle a race with vblank interrupts using the high precision
307 * timestamping support.
309 * This is mostly useful for hardware that can obtain the scanout position, but
310 * doesn't have a hardware frame counter.
312 u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
314 struct drm_device *dev = crtc->dev;
315 unsigned int pipe = drm_crtc_index(crtc);
319 WARN_ONCE(drm_debug & DRM_UT_VBL && !dev->driver->get_vblank_timestamp,
320 "This function requires support for accurate vblank timestamps.");
322 spin_lock_irqsave(&dev->vblank_time_lock, flags);
324 drm_update_vblank_count(dev, pipe, false);
325 vblank = drm_vblank_count(dev, pipe);
327 spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
331 EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
333 static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
335 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
336 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
341 if (crtc->funcs->disable_vblank) {
342 crtc->funcs->disable_vblank(crtc);
347 dev->driver->disable_vblank(dev, pipe);
351 * Disable vblank irq's on crtc, make sure that last vblank count
352 * of hardware and corresponding consistent software vblank counter
353 * are preserved, even if there are any spurious vblank irq's after
356 void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
358 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
359 unsigned long irqflags;
361 assert_spin_locked(&dev->vbl_lock);
363 /* Prevent vblank irq processing while disabling vblank irqs,
364 * so no updates of timestamps or count can happen after we've
365 * disabled. Needed to prevent races in case of delayed irq's.
367 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
370 * Update vblank count and disable vblank interrupts only if the
371 * interrupts were enabled. This avoids calling the ->disable_vblank()
372 * operation in atomic context with the hardware potentially runtime
375 if (!vblank->enabled)
379 * Update the count and timestamp to maintain the
380 * appearance that the counter has been ticking all along until
381 * this time. This makes the count account for the entire time
382 * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
384 drm_update_vblank_count(dev, pipe, false);
385 __disable_vblank(dev, pipe);
386 vblank->enabled = false;
389 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
392 static void vblank_disable_fn(struct timer_list *t)
394 struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
395 struct drm_device *dev = vblank->dev;
396 unsigned int pipe = vblank->pipe;
397 unsigned long irqflags;
399 spin_lock_irqsave(&dev->vbl_lock, irqflags);
400 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
401 DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
402 drm_vblank_disable_and_save(dev, pipe);
404 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
407 void drm_vblank_cleanup(struct drm_device *dev)
411 /* Bail if the driver didn't call drm_vblank_init() */
412 if (dev->num_crtcs == 0)
415 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
416 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
418 WARN_ON(READ_ONCE(vblank->enabled) &&
419 drm_core_check_feature(dev, DRIVER_MODESET));
421 del_timer_sync(&vblank->disable_timer);
430 * drm_vblank_init - initialize vblank support
432 * @num_crtcs: number of CRTCs supported by @dev
434 * This function initializes vblank support for @num_crtcs display pipelines.
435 * Cleanup is handled by the DRM core, or through calling drm_dev_fini() for
436 * drivers with a &drm_driver.release callback.
439 * Zero on success or a negative error code on failure.
441 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
446 spin_lock_init(&dev->vbl_lock);
447 spin_lock_init(&dev->vblank_time_lock);
449 dev->num_crtcs = num_crtcs;
451 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
455 for (i = 0; i < num_crtcs; i++) {
456 struct drm_vblank_crtc *vblank = &dev->vblank[i];
460 init_waitqueue_head(&vblank->queue);
461 timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
462 seqlock_init(&vblank->seqlock);
465 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
467 /* Driver specific high-precision vblank timestamping supported? */
468 if (dev->driver->get_vblank_timestamp)
469 DRM_INFO("Driver supports precise vblank timestamp query.\n");
471 DRM_INFO("No driver support for vblank timestamp query.\n");
473 /* Must have precise timestamping for reliable vblank instant disable */
474 if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
475 dev->vblank_disable_immediate = false;
476 DRM_INFO("Setting vblank_disable_immediate to false because "
477 "get_vblank_timestamp == NULL\n");
486 EXPORT_SYMBOL(drm_vblank_init);
489 * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
490 * @crtc: which CRTC's vblank waitqueue to retrieve
492 * This function returns a pointer to the vblank waitqueue for the CRTC.
493 * Drivers can use this to implement vblank waits using wait_event() and related
496 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
498 return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
500 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
504 * drm_calc_timestamping_constants - calculate vblank timestamp constants
505 * @crtc: drm_crtc whose timestamp constants should be updated.
506 * @mode: display mode containing the scanout timings
508 * Calculate and store various constants which are later needed by vblank and
509 * swap-completion timestamping, e.g, by
510 * drm_calc_vbltimestamp_from_scanoutpos(). They are derived from CRTC's true
511 * scanout timing, so they take things like panel scaling or other adjustments
514 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
515 const struct drm_display_mode *mode)
517 struct drm_device *dev = crtc->dev;
518 unsigned int pipe = drm_crtc_index(crtc);
519 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
520 int linedur_ns = 0, framedur_ns = 0;
521 int dotclock = mode->crtc_clock;
526 if (WARN_ON(pipe >= dev->num_crtcs))
529 /* Valid dotclock? */
531 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
534 * Convert scanline length in pixels and video
535 * dot clock to line duration and frame duration
538 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
539 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
542 * Fields of interlaced scanout modes are only half a frame duration.
544 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
547 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
550 vblank->linedur_ns = linedur_ns;
551 vblank->framedur_ns = framedur_ns;
552 vblank->hwmode = *mode;
554 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
555 crtc->base.id, mode->crtc_htotal,
556 mode->crtc_vtotal, mode->crtc_vdisplay);
557 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
558 crtc->base.id, dotclock, framedur_ns, linedur_ns);
560 EXPORT_SYMBOL(drm_calc_timestamping_constants);
563 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
565 * @pipe: index of CRTC whose vblank timestamp to retrieve
566 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
567 * On return contains true maximum error of timestamp
568 * @vblank_time: Pointer to time which should receive the timestamp
570 * True when called from drm_crtc_handle_vblank(). Some drivers
571 * need to apply some workarounds for gpu-specific vblank irq quirks
574 * Implements calculation of exact vblank timestamps from given drm_display_mode
575 * timings and current video scanout position of a CRTC. This can be directly
576 * used as the &drm_driver.get_vblank_timestamp implementation of a kms driver
577 * if &drm_driver.get_scanout_position is implemented.
579 * The current implementation only handles standard video modes. For double scan
580 * and interlaced modes the driver is supposed to adjust the hardware mode
581 * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
582 * match the scanout position reported.
584 * Note that atomic drivers must call drm_calc_timestamping_constants() before
585 * enabling a CRTC. The atomic helpers already take care of that in
586 * drm_atomic_helper_update_legacy_modeset_state().
590 * Returns true on success, and false on failure, i.e. when no accurate
591 * timestamp could be acquired.
593 bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
596 ktime_t *vblank_time,
599 struct timespec64 ts_etime, ts_vblank_time;
600 ktime_t stime, etime;
602 struct drm_crtc *crtc;
603 const struct drm_display_mode *mode;
604 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
606 int delta_ns, duration_ns;
608 if (!drm_core_check_feature(dev, DRIVER_MODESET))
611 crtc = drm_crtc_from_index(dev, pipe);
613 if (pipe >= dev->num_crtcs || !crtc) {
614 DRM_ERROR("Invalid crtc %u\n", pipe);
618 /* Scanout position query not supported? Should not happen. */
619 if (!dev->driver->get_scanout_position) {
620 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
624 if (drm_drv_uses_atomic_modeset(dev))
625 mode = &vblank->hwmode;
627 mode = &crtc->hwmode;
629 /* If mode timing undefined, just return as no-op:
630 * Happens during initial modesetting of a crtc.
632 if (mode->crtc_clock == 0) {
633 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
634 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
639 /* Get current scanout position with system timestamp.
640 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
641 * if single query takes longer than max_error nanoseconds.
643 * This guarantees a tight bound on maximum error if
644 * code gets preempted or delayed for some reason.
646 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
648 * Get vertical and horizontal scanout position vpos, hpos,
649 * and bounding timestamps stime, etime, pre/post query.
651 vbl_status = dev->driver->get_scanout_position(dev, pipe,
657 /* Return as no-op if scanout query unsupported or failed. */
659 DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
664 /* Compute uncertainty in timestamp of scanout position query. */
665 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
667 /* Accept result with < max_error nsecs timing uncertainty. */
668 if (duration_ns <= *max_error)
672 /* Noisy system timing? */
673 if (i == DRM_TIMESTAMP_MAXRETRIES) {
674 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
675 pipe, duration_ns/1000, *max_error/1000, i);
678 /* Return upper bound of timestamp precision error. */
679 *max_error = duration_ns;
681 /* Convert scanout position into elapsed time at raw_time query
682 * since start of scanout at first display scanline. delta_ns
683 * can be negative if start of scanout hasn't happened yet.
685 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
688 /* Subtract time delta from raw timestamp to get final
689 * vblank_time timestamp for end of vblank.
691 *vblank_time = ktime_sub_ns(etime, delta_ns);
693 if ((drm_debug & DRM_UT_VBL) == 0)
696 ts_etime = ktime_to_timespec64(etime);
697 ts_vblank_time = ktime_to_timespec64(*vblank_time);
699 DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
701 (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
702 (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
703 duration_ns / 1000, i);
707 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
710 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
713 * @pipe: index of CRTC whose vblank timestamp to retrieve
714 * @tvblank: Pointer to target time which should receive the timestamp
716 * True when called from drm_crtc_handle_vblank(). Some drivers
717 * need to apply some workarounds for gpu-specific vblank irq quirks
720 * Fetches the system timestamp corresponding to the time of the most recent
721 * vblank interval on specified CRTC. May call into kms-driver to
722 * compute the timestamp with a high-precision GPU specific method.
724 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
725 * call, i.e., it isn't very precisely locked to the true vblank.
728 * True if timestamp is considered to be very precise, false otherwise.
731 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
732 ktime_t *tvblank, bool in_vblank_irq)
736 /* Define requested maximum error on timestamps (nanoseconds). */
737 int max_error = (int) drm_timestamp_precision * 1000;
739 /* Query driver if possible and precision timestamping enabled. */
740 if (dev->driver->get_vblank_timestamp && (max_error > 0))
741 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
742 tvblank, in_vblank_irq);
744 /* GPU high precision timestamp query unsupported or failed.
745 * Return current monotonic/gettimeofday timestamp as best estimate.
748 *tvblank = ktime_get();
754 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
755 * @crtc: which counter to retrieve
757 * Fetches the "cooked" vblank count value that represents the number of
758 * vblank events since the system was booted, including lost events due to
759 * modesetting activity. Note that this timer isn't correct against a racing
760 * vblank interrupt (since it only reports the software vblank counter), see
761 * drm_crtc_accurate_vblank_count() for such use-cases.
764 * The software vblank counter.
766 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
768 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
770 EXPORT_SYMBOL(drm_crtc_vblank_count);
773 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
774 * system timestamp corresponding to that vblank counter value.
776 * @pipe: index of CRTC whose counter to retrieve
777 * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
779 * Fetches the "cooked" vblank count value that represents the number of
780 * vblank events since the system was booted, including lost events due to
781 * modesetting activity. Returns corresponding system timestamp of the time
782 * of the vblank interval that corresponds to the current vblank counter value.
784 * This is the legacy version of drm_crtc_vblank_count_and_time().
786 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
789 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
793 if (WARN_ON(pipe >= dev->num_crtcs)) {
799 seq = read_seqbegin(&vblank->seqlock);
800 vblank_count = vblank->count;
801 *vblanktime = vblank->time;
802 } while (read_seqretry(&vblank->seqlock, seq));
808 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
809 * and the system timestamp corresponding to that vblank counter value
810 * @crtc: which counter to retrieve
811 * @vblanktime: Pointer to time to receive the vblank timestamp.
813 * Fetches the "cooked" vblank count value that represents the number of
814 * vblank events since the system was booted, including lost events due to
815 * modesetting activity. Returns corresponding system timestamp of the time
816 * of the vblank interval that corresponds to the current vblank counter value.
818 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
821 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
824 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
826 static void send_vblank_event(struct drm_device *dev,
827 struct drm_pending_vblank_event *e,
828 u64 seq, ktime_t now)
830 struct timespec64 tv;
832 switch (e->event.base.type) {
833 case DRM_EVENT_VBLANK:
834 case DRM_EVENT_FLIP_COMPLETE:
835 tv = ktime_to_timespec64(now);
836 e->event.vbl.sequence = seq;
838 * e->event is a user space structure, with hardcoded unsigned
839 * 32-bit seconds/microseconds. This is safe as we always use
840 * monotonic timestamps since linux-4.15
842 e->event.vbl.tv_sec = tv.tv_sec;
843 e->event.vbl.tv_usec = tv.tv_nsec / 1000;
845 case DRM_EVENT_CRTC_SEQUENCE:
847 e->event.seq.sequence = seq;
848 e->event.seq.time_ns = ktime_to_ns(now);
851 trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
852 drm_send_event_locked(dev, &e->base);
856 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
857 * @crtc: the source CRTC of the vblank event
858 * @e: the event to send
860 * A lot of drivers need to generate vblank events for the very next vblank
861 * interrupt. For example when the page flip interrupt happens when the page
862 * flip gets armed, but not when it actually executes within the next vblank
863 * period. This helper function implements exactly the required vblank arming
866 * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
867 * atomic commit must ensure that the next vblank happens at exactly the same
868 * time as the atomic commit is committed to the hardware. This function itself
869 * does **not** protect against the next vblank interrupt racing with either this
870 * function call or the atomic commit operation. A possible sequence could be:
872 * 1. Driver commits new hardware state into vblank-synchronized registers.
873 * 2. A vblank happens, committing the hardware state. Also the corresponding
874 * vblank interrupt is fired off and fully processed by the interrupt
876 * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
877 * 4. The event is only send out for the next vblank, which is wrong.
879 * An equivalent race can happen when the driver calls
880 * drm_crtc_arm_vblank_event() before writing out the new hardware state.
882 * The only way to make this work safely is to prevent the vblank from firing
883 * (and the hardware from committing anything else) until the entire atomic
884 * commit sequence has run to completion. If the hardware does not have such a
885 * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
886 * Instead drivers need to manually send out the event from their interrupt
887 * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
888 * possible race with the hardware committing the atomic update.
890 * Caller must hold a vblank reference for the event @e acquired by a
891 * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
893 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
894 struct drm_pending_vblank_event *e)
896 struct drm_device *dev = crtc->dev;
897 unsigned int pipe = drm_crtc_index(crtc);
899 assert_spin_locked(&dev->event_lock);
902 e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
903 list_add_tail(&e->base.link, &dev->vblank_event_list);
905 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
908 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
909 * @crtc: the source CRTC of the vblank event
910 * @e: the event to send
912 * Updates sequence # and timestamp on event for the most recently processed
913 * vblank, and sends it to userspace. Caller must hold event lock.
915 * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
916 * situation, especially to send out events for atomic commit operations.
918 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
919 struct drm_pending_vblank_event *e)
921 struct drm_device *dev = crtc->dev;
923 unsigned int pipe = drm_crtc_index(crtc);
926 if (dev->num_crtcs > 0) {
927 seq = drm_vblank_count_and_time(dev, pipe, &now);
934 send_vblank_event(dev, e, seq, now);
936 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
938 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
940 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
941 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
946 if (crtc->funcs->enable_vblank)
947 return crtc->funcs->enable_vblank(crtc);
950 return dev->driver->enable_vblank(dev, pipe);
953 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
955 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
958 assert_spin_locked(&dev->vbl_lock);
960 spin_lock(&dev->vblank_time_lock);
962 if (!vblank->enabled) {
964 * Enable vblank irqs under vblank_time_lock protection.
965 * All vblank count & timestamp updates are held off
966 * until we are done reinitializing master counter and
967 * timestamps. Filtercode in drm_handle_vblank() will
968 * prevent double-accounting of same vblank interval.
970 ret = __enable_vblank(dev, pipe);
971 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
973 atomic_dec(&vblank->refcount);
975 drm_update_vblank_count(dev, pipe, 0);
976 /* drm_update_vblank_count() includes a wmb so we just
977 * need to ensure that the compiler emits the write
978 * to mark the vblank as enabled after the call
979 * to drm_update_vblank_count().
981 WRITE_ONCE(vblank->enabled, true);
985 spin_unlock(&dev->vblank_time_lock);
990 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
992 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
993 unsigned long irqflags;
999 if (WARN_ON(pipe >= dev->num_crtcs))
1002 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1003 /* Going from 0->1 means we have to enable interrupts again */
1004 if (atomic_add_return(1, &vblank->refcount) == 1) {
1005 ret = drm_vblank_enable(dev, pipe);
1007 if (!vblank->enabled) {
1008 atomic_dec(&vblank->refcount);
1012 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1018 * drm_crtc_vblank_get - get a reference count on vblank events
1019 * @crtc: which CRTC to own
1021 * Acquire a reference count on vblank events to avoid having them disabled
1025 * Zero on success or a negative error code on failure.
1027 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1029 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1031 EXPORT_SYMBOL(drm_crtc_vblank_get);
1033 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1035 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1037 if (WARN_ON(pipe >= dev->num_crtcs))
1040 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1043 /* Last user schedules interrupt disable */
1044 if (atomic_dec_and_test(&vblank->refcount)) {
1045 if (drm_vblank_offdelay == 0)
1047 else if (drm_vblank_offdelay < 0)
1048 vblank_disable_fn(&vblank->disable_timer);
1049 else if (!dev->vblank_disable_immediate)
1050 mod_timer(&vblank->disable_timer,
1051 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1056 * drm_crtc_vblank_put - give up ownership of vblank events
1057 * @crtc: which counter to give up
1059 * Release ownership of a given vblank counter, turning off interrupts
1060 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1062 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1064 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1066 EXPORT_SYMBOL(drm_crtc_vblank_put);
1069 * drm_wait_one_vblank - wait for one vblank
1073 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1074 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1075 * due to lack of driver support or because the crtc is off.
1077 * This is the legacy version of drm_crtc_wait_one_vblank().
1079 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1081 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1085 if (WARN_ON(pipe >= dev->num_crtcs))
1088 ret = drm_vblank_get(dev, pipe);
1089 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1092 last = drm_vblank_count(dev, pipe);
1094 ret = wait_event_timeout(vblank->queue,
1095 last != drm_vblank_count(dev, pipe),
1096 msecs_to_jiffies(100));
1098 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1100 drm_vblank_put(dev, pipe);
1102 EXPORT_SYMBOL(drm_wait_one_vblank);
1105 * drm_crtc_wait_one_vblank - wait for one vblank
1108 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1109 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1110 * due to lack of driver support or because the crtc is off.
1112 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1114 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1116 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1119 * drm_crtc_vblank_off - disable vblank events on a CRTC
1120 * @crtc: CRTC in question
1122 * Drivers can use this function to shut down the vblank interrupt handling when
1123 * disabling a crtc. This function ensures that the latest vblank frame count is
1124 * stored so that drm_vblank_on can restore it again.
1126 * Drivers must use this function when the hardware vblank counter can get
1127 * reset, e.g. when suspending or disabling the @crtc in general.
1129 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1131 struct drm_device *dev = crtc->dev;
1132 unsigned int pipe = drm_crtc_index(crtc);
1133 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1134 struct drm_pending_vblank_event *e, *t;
1137 unsigned long irqflags;
1140 if (WARN_ON(pipe >= dev->num_crtcs))
1143 spin_lock_irqsave(&dev->event_lock, irqflags);
1145 spin_lock(&dev->vbl_lock);
1146 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1147 pipe, vblank->enabled, vblank->inmodeset);
1149 /* Avoid redundant vblank disables without previous
1150 * drm_crtc_vblank_on(). */
1151 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1152 drm_vblank_disable_and_save(dev, pipe);
1154 wake_up(&vblank->queue);
1157 * Prevent subsequent drm_vblank_get() from re-enabling
1158 * the vblank interrupt by bumping the refcount.
1160 if (!vblank->inmodeset) {
1161 atomic_inc(&vblank->refcount);
1162 vblank->inmodeset = 1;
1164 spin_unlock(&dev->vbl_lock);
1166 /* Send any queued vblank events, lest the natives grow disquiet */
1167 seq = drm_vblank_count_and_time(dev, pipe, &now);
1169 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1170 if (e->pipe != pipe)
1172 DRM_DEBUG("Sending premature vblank event on disable: "
1173 "wanted %llu, current %llu\n",
1175 list_del(&e->base.link);
1176 drm_vblank_put(dev, pipe);
1177 send_vblank_event(dev, e, seq, now);
1179 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1181 /* Will be reset by the modeset helpers when re-enabling the crtc by
1182 * calling drm_calc_timestamping_constants(). */
1183 vblank->hwmode.crtc_clock = 0;
1185 EXPORT_SYMBOL(drm_crtc_vblank_off);
1188 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1189 * @crtc: CRTC in question
1191 * Drivers can use this function to reset the vblank state to off at load time.
1192 * Drivers should use this together with the drm_crtc_vblank_off() and
1193 * drm_crtc_vblank_on() functions. The difference compared to
1194 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1195 * and hence doesn't need to call any driver hooks.
1197 * This is useful for recovering driver state e.g. on driver load, or on resume.
1199 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1201 struct drm_device *dev = crtc->dev;
1202 unsigned long irqflags;
1203 unsigned int pipe = drm_crtc_index(crtc);
1204 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1206 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1208 * Prevent subsequent drm_vblank_get() from enabling the vblank
1209 * interrupt by bumping the refcount.
1211 if (!vblank->inmodeset) {
1212 atomic_inc(&vblank->refcount);
1213 vblank->inmodeset = 1;
1215 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1217 WARN_ON(!list_empty(&dev->vblank_event_list));
1219 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1222 * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1223 * @crtc: CRTC in question
1224 * @max_vblank_count: max hardware vblank counter value
1226 * Update the maximum hardware vblank counter value for @crtc
1227 * at runtime. Useful for hardware where the operation of the
1228 * hardware vblank counter depends on the currently active
1229 * display configuration.
1231 * For example, if the hardware vblank counter does not work
1232 * when a specific connector is active the maximum can be set
1233 * to zero. And when that specific connector isn't active the
1234 * maximum can again be set to the appropriate non-zero value.
1236 * If used, must be called before drm_vblank_on().
1238 void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1239 u32 max_vblank_count)
1241 struct drm_device *dev = crtc->dev;
1242 unsigned int pipe = drm_crtc_index(crtc);
1243 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1245 WARN_ON(dev->max_vblank_count);
1246 WARN_ON(!READ_ONCE(vblank->inmodeset));
1248 vblank->max_vblank_count = max_vblank_count;
1250 EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1253 * drm_crtc_vblank_on - enable vblank events on a CRTC
1254 * @crtc: CRTC in question
1256 * This functions restores the vblank interrupt state captured with
1257 * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1258 * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1259 * unbalanced and so can also be unconditionally called in driver load code to
1260 * reflect the current hardware state of the crtc.
1262 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1264 struct drm_device *dev = crtc->dev;
1265 unsigned int pipe = drm_crtc_index(crtc);
1266 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1267 unsigned long irqflags;
1269 if (WARN_ON(pipe >= dev->num_crtcs))
1272 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1273 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1274 pipe, vblank->enabled, vblank->inmodeset);
1276 /* Drop our private "prevent drm_vblank_get" refcount */
1277 if (vblank->inmodeset) {
1278 atomic_dec(&vblank->refcount);
1279 vblank->inmodeset = 0;
1282 drm_reset_vblank_timestamp(dev, pipe);
1285 * re-enable interrupts if there are users left, or the
1286 * user wishes vblank interrupts to be enabled all the time.
1288 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1289 WARN_ON(drm_vblank_enable(dev, pipe));
1290 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1292 EXPORT_SYMBOL(drm_crtc_vblank_on);
1295 * drm_vblank_restore - estimate missed vblanks and update vblank count.
1299 * Power manamement features can cause frame counter resets between vblank
1300 * disable and enable. Drivers can use this function in their
1301 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1302 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1305 * This function is the legacy version of drm_crtc_vblank_restore().
1307 void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1310 struct drm_vblank_crtc *vblank;
1313 u32 cur_vblank, diff = 1;
1314 int count = DRM_TIMESTAMP_MAXRETRIES;
1316 if (WARN_ON(pipe >= dev->num_crtcs))
1319 assert_spin_locked(&dev->vbl_lock);
1320 assert_spin_locked(&dev->vblank_time_lock);
1322 vblank = &dev->vblank[pipe];
1323 WARN_ONCE((drm_debug & DRM_UT_VBL) && !vblank->framedur_ns,
1324 "Cannot compute missed vblanks without frame duration\n");
1325 framedur_ns = vblank->framedur_ns;
1328 cur_vblank = __get_vblank_counter(dev, pipe);
1329 drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1330 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1332 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1334 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1337 DRM_DEBUG_VBL("missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
1338 diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
1339 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
1341 EXPORT_SYMBOL(drm_vblank_restore);
1344 * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1345 * @crtc: CRTC in question
1347 * Power manamement features can cause frame counter resets between vblank
1348 * disable and enable. Drivers can use this function in their
1349 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1350 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1353 void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1355 drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1357 EXPORT_SYMBOL(drm_crtc_vblank_restore);
1359 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1362 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1364 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1365 if (!dev->num_crtcs)
1368 if (WARN_ON(pipe >= dev->num_crtcs))
1372 * To avoid all the problems that might happen if interrupts
1373 * were enabled/disabled around or between these calls, we just
1374 * have the kernel take a reference on the CRTC (just once though
1375 * to avoid corrupting the count if multiple, mismatch calls occur),
1376 * so that interrupts remain enabled in the interim.
1378 if (!vblank->inmodeset) {
1379 vblank->inmodeset = 0x1;
1380 if (drm_vblank_get(dev, pipe) == 0)
1381 vblank->inmodeset |= 0x2;
1385 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1388 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1389 unsigned long irqflags;
1391 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1392 if (!dev->num_crtcs)
1395 if (WARN_ON(pipe >= dev->num_crtcs))
1398 if (vblank->inmodeset) {
1399 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1400 drm_reset_vblank_timestamp(dev, pipe);
1401 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1403 if (vblank->inmodeset & 0x2)
1404 drm_vblank_put(dev, pipe);
1406 vblank->inmodeset = 0;
1410 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1411 struct drm_file *file_priv)
1413 struct drm_modeset_ctl *modeset = data;
1416 /* If drm_vblank_init() hasn't been called yet, just no-op */
1417 if (!dev->num_crtcs)
1420 /* KMS drivers handle this internally */
1421 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1424 pipe = modeset->crtc;
1425 if (pipe >= dev->num_crtcs)
1428 switch (modeset->cmd) {
1429 case _DRM_PRE_MODESET:
1430 drm_legacy_vblank_pre_modeset(dev, pipe);
1432 case _DRM_POST_MODESET:
1433 drm_legacy_vblank_post_modeset(dev, pipe);
1442 static inline bool vblank_passed(u64 seq, u64 ref)
1444 return (seq - ref) <= (1 << 23);
1447 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1449 union drm_wait_vblank *vblwait,
1450 struct drm_file *file_priv)
1452 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1453 struct drm_pending_vblank_event *e;
1455 unsigned long flags;
1459 e = kzalloc(sizeof(*e), GFP_KERNEL);
1466 e->event.base.type = DRM_EVENT_VBLANK;
1467 e->event.base.length = sizeof(e->event.vbl);
1468 e->event.vbl.user_data = vblwait->request.signal;
1469 e->event.vbl.crtc_id = 0;
1470 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1471 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1473 e->event.vbl.crtc_id = crtc->base.id;
1476 spin_lock_irqsave(&dev->event_lock, flags);
1479 * drm_crtc_vblank_off() might have been called after we called
1480 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1481 * vblank disable, so no need for further locking. The reference from
1482 * drm_vblank_get() protects against vblank disable from another source.
1484 if (!READ_ONCE(vblank->enabled)) {
1489 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1495 seq = drm_vblank_count_and_time(dev, pipe, &now);
1497 DRM_DEBUG("event on vblank count %llu, current %llu, crtc %u\n",
1498 req_seq, seq, pipe);
1500 trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1502 e->sequence = req_seq;
1503 if (vblank_passed(seq, req_seq)) {
1504 drm_vblank_put(dev, pipe);
1505 send_vblank_event(dev, e, seq, now);
1506 vblwait->reply.sequence = seq;
1508 /* drm_handle_vblank_events will call drm_vblank_put */
1509 list_add_tail(&e->base.link, &dev->vblank_event_list);
1510 vblwait->reply.sequence = req_seq;
1513 spin_unlock_irqrestore(&dev->event_lock, flags);
1518 spin_unlock_irqrestore(&dev->event_lock, flags);
1521 drm_vblank_put(dev, pipe);
1525 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1527 if (vblwait->request.sequence)
1530 return _DRM_VBLANK_RELATIVE ==
1531 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1533 _DRM_VBLANK_NEXTONMISS));
1537 * Widen a 32-bit param to 64-bits.
1539 * \param narrow 32-bit value (missing upper 32 bits)
1540 * \param near 64-bit value that should be 'close' to near
1542 * This function returns a 64-bit value using the lower 32-bits from
1543 * 'narrow' and constructing the upper 32-bits so that the result is
1544 * as close as possible to 'near'.
1547 static u64 widen_32_to_64(u32 narrow, u64 near)
1549 return near + (s32) (narrow - near);
1552 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1553 struct drm_wait_vblank_reply *reply)
1556 struct timespec64 ts;
1559 * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1560 * to store the seconds. This is safe as we always use monotonic
1561 * timestamps since linux-4.15.
1563 reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1564 ts = ktime_to_timespec64(now);
1565 reply->tval_sec = (u32)ts.tv_sec;
1566 reply->tval_usec = ts.tv_nsec / 1000;
1569 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1570 struct drm_file *file_priv)
1572 struct drm_crtc *crtc;
1573 struct drm_vblank_crtc *vblank;
1574 union drm_wait_vblank *vblwait = data;
1577 unsigned int pipe_index;
1578 unsigned int flags, pipe, high_pipe;
1580 if (!dev->irq_enabled)
1583 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1586 if (vblwait->request.type &
1587 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1588 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1589 DRM_DEBUG("Unsupported type value 0x%x, supported mask 0x%x\n",
1590 vblwait->request.type,
1591 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1592 _DRM_VBLANK_HIGH_CRTC_MASK));
1596 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1597 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1599 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1601 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1603 /* Convert lease-relative crtc index into global crtc index */
1604 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1606 drm_for_each_crtc(crtc, dev) {
1607 if (drm_lease_held(file_priv, crtc->base.id)) {
1608 if (pipe_index == 0)
1618 if (pipe >= dev->num_crtcs)
1621 vblank = &dev->vblank[pipe];
1623 /* If the counter is currently enabled and accurate, short-circuit
1624 * queries to return the cached timestamp of the last vblank.
1626 if (dev->vblank_disable_immediate &&
1627 drm_wait_vblank_is_query(vblwait) &&
1628 READ_ONCE(vblank->enabled)) {
1629 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1633 ret = drm_vblank_get(dev, pipe);
1635 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1638 seq = drm_vblank_count(dev, pipe);
1640 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1641 case _DRM_VBLANK_RELATIVE:
1642 req_seq = seq + vblwait->request.sequence;
1643 vblwait->request.sequence = req_seq;
1644 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1646 case _DRM_VBLANK_ABSOLUTE:
1647 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1654 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1655 vblank_passed(seq, req_seq)) {
1657 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1658 vblwait->request.sequence = req_seq;
1661 if (flags & _DRM_VBLANK_EVENT) {
1662 /* must hold on to the vblank ref until the event fires
1663 * drm_vblank_put will be called asynchronously
1665 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1668 if (req_seq != seq) {
1669 DRM_DEBUG("waiting on vblank count %llu, crtc %u\n",
1671 DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1672 vblank_passed(drm_vblank_count(dev, pipe),
1674 !READ_ONCE(vblank->enabled));
1677 if (ret != -EINTR) {
1678 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1680 DRM_DEBUG("crtc %d returning %u to client\n",
1681 pipe, vblwait->reply.sequence);
1683 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1687 drm_vblank_put(dev, pipe);
1691 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1693 struct drm_pending_vblank_event *e, *t;
1697 assert_spin_locked(&dev->event_lock);
1699 seq = drm_vblank_count_and_time(dev, pipe, &now);
1701 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1702 if (e->pipe != pipe)
1704 if (!vblank_passed(seq, e->sequence))
1707 DRM_DEBUG("vblank event on %llu, current %llu\n",
1710 list_del(&e->base.link);
1711 drm_vblank_put(dev, pipe);
1712 send_vblank_event(dev, e, seq, now);
1715 trace_drm_vblank_event(pipe, seq);
1719 * drm_handle_vblank - handle a vblank event
1721 * @pipe: index of CRTC where this event occurred
1723 * Drivers should call this routine in their vblank interrupt handlers to
1724 * update the vblank counter and send any signals that may be pending.
1726 * This is the legacy version of drm_crtc_handle_vblank().
1728 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1730 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1731 unsigned long irqflags;
1734 if (WARN_ON_ONCE(!dev->num_crtcs))
1737 if (WARN_ON(pipe >= dev->num_crtcs))
1740 spin_lock_irqsave(&dev->event_lock, irqflags);
1742 /* Need timestamp lock to prevent concurrent execution with
1743 * vblank enable/disable, as this would cause inconsistent
1744 * or corrupted timestamps and vblank counts.
1746 spin_lock(&dev->vblank_time_lock);
1748 /* Vblank irq handling disabled. Nothing to do. */
1749 if (!vblank->enabled) {
1750 spin_unlock(&dev->vblank_time_lock);
1751 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1755 drm_update_vblank_count(dev, pipe, true);
1757 spin_unlock(&dev->vblank_time_lock);
1759 wake_up(&vblank->queue);
1761 /* With instant-off, we defer disabling the interrupt until after
1762 * we finish processing the following vblank after all events have
1763 * been signaled. The disable has to be last (after
1764 * drm_handle_vblank_events) so that the timestamp is always accurate.
1766 disable_irq = (dev->vblank_disable_immediate &&
1767 drm_vblank_offdelay > 0 &&
1768 !atomic_read(&vblank->refcount));
1770 drm_handle_vblank_events(dev, pipe);
1772 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1775 vblank_disable_fn(&vblank->disable_timer);
1779 EXPORT_SYMBOL(drm_handle_vblank);
1782 * drm_crtc_handle_vblank - handle a vblank event
1783 * @crtc: where this event occurred
1785 * Drivers should call this routine in their vblank interrupt handlers to
1786 * update the vblank counter and send any signals that may be pending.
1788 * This is the native KMS version of drm_handle_vblank().
1791 * True if the event was successfully handled, false on failure.
1793 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1795 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1797 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1800 * Get crtc VBLANK count.
1802 * \param dev DRM device
1803 * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1804 * \param file_priv drm file private for the user's open file descriptor
1807 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1808 struct drm_file *file_priv)
1810 struct drm_crtc *crtc;
1811 struct drm_vblank_crtc *vblank;
1813 struct drm_crtc_get_sequence *get_seq = data;
1815 bool vblank_enabled;
1818 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1821 if (!dev->irq_enabled)
1824 crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
1828 pipe = drm_crtc_index(crtc);
1830 vblank = &dev->vblank[pipe];
1831 vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
1833 if (!vblank_enabled) {
1834 ret = drm_crtc_vblank_get(crtc);
1836 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1840 drm_modeset_lock(&crtc->mutex, NULL);
1842 get_seq->active = crtc->state->enable;
1844 get_seq->active = crtc->enabled;
1845 drm_modeset_unlock(&crtc->mutex);
1846 get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1847 get_seq->sequence_ns = ktime_to_ns(now);
1848 if (!vblank_enabled)
1849 drm_crtc_vblank_put(crtc);
1854 * Queue a event for VBLANK sequence
1856 * \param dev DRM device
1857 * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
1858 * \param file_priv drm file private for the user's open file descriptor
1861 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
1862 struct drm_file *file_priv)
1864 struct drm_crtc *crtc;
1865 struct drm_vblank_crtc *vblank;
1867 struct drm_crtc_queue_sequence *queue_seq = data;
1869 struct drm_pending_vblank_event *e;
1874 unsigned long spin_flags;
1876 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1879 if (!dev->irq_enabled)
1882 crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
1886 flags = queue_seq->flags;
1887 /* Check valid flag bits */
1888 if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
1889 DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
1892 pipe = drm_crtc_index(crtc);
1894 vblank = &dev->vblank[pipe];
1896 e = kzalloc(sizeof(*e), GFP_KERNEL);
1900 ret = drm_crtc_vblank_get(crtc);
1902 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1906 seq = drm_vblank_count_and_time(dev, pipe, &now);
1907 req_seq = queue_seq->sequence;
1909 if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
1912 if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
1916 e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
1917 e->event.base.length = sizeof(e->event.seq);
1918 e->event.seq.user_data = queue_seq->user_data;
1920 spin_lock_irqsave(&dev->event_lock, spin_flags);
1923 * drm_crtc_vblank_off() might have been called after we called
1924 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1925 * vblank disable, so no need for further locking. The reference from
1926 * drm_crtc_vblank_get() protects against vblank disable from another source.
1928 if (!READ_ONCE(vblank->enabled)) {
1933 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1939 e->sequence = req_seq;
1941 if (vblank_passed(seq, req_seq)) {
1942 drm_crtc_vblank_put(crtc);
1943 send_vblank_event(dev, e, seq, now);
1944 queue_seq->sequence = seq;
1946 /* drm_handle_vblank_events will call drm_vblank_put */
1947 list_add_tail(&e->base.link, &dev->vblank_event_list);
1948 queue_seq->sequence = req_seq;
1951 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1955 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1956 drm_crtc_vblank_put(crtc);