2 * drm_irq.c IRQ and vblank support
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_modeset_helper_vtables.h>
34 #include <drm/drm_print.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.
74 * Drivers for hardware without support for vertical-blanking interrupts
75 * must not call drm_vblank_init(). For such drivers, atomic helpers will
76 * automatically generate fake vblank events as part of the display update.
77 * This functionality also can be controlled by the driver by enabling and
78 * disabling struct drm_crtc_state.no_vblank.
81 /* Retry timestamp calculation up to 3 times to satisfy
82 * drm_timestamp_precision before giving up.
84 #define DRM_TIMESTAMP_MAXRETRIES 3
86 /* Threshold in nanoseconds for detection of redundant
87 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
89 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
92 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
93 ktime_t *tvblank, bool in_vblank_irq);
95 static unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
97 static int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
99 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
100 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
101 MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
102 MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
104 static void store_vblank(struct drm_device *dev, unsigned int pipe,
105 u32 vblank_count_inc,
106 ktime_t t_vblank, u32 last)
108 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
110 assert_spin_locked(&dev->vblank_time_lock);
114 write_seqlock(&vblank->seqlock);
115 vblank->time = t_vblank;
116 atomic64_add(vblank_count_inc, &vblank->count);
117 write_sequnlock(&vblank->seqlock);
120 static u32 drm_max_vblank_count(struct drm_device *dev, unsigned int pipe)
122 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
124 return vblank->max_vblank_count ?: dev->max_vblank_count;
128 * "No hw counter" fallback implementation of .get_vblank_counter() hook,
129 * if there is no useable hardware frame counter available.
131 static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
133 WARN_ON_ONCE(drm_max_vblank_count(dev, pipe) != 0);
137 static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
139 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
140 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
145 if (crtc->funcs->get_vblank_counter)
146 return crtc->funcs->get_vblank_counter(crtc);
147 } else if (dev->driver->get_vblank_counter) {
148 return dev->driver->get_vblank_counter(dev, pipe);
151 return drm_vblank_no_hw_counter(dev, pipe);
155 * Reset the stored timestamp for the current vblank count to correspond
156 * to the last vblank occurred.
158 * Only to be called from drm_crtc_vblank_on().
160 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
161 * device vblank fields.
163 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
168 int count = DRM_TIMESTAMP_MAXRETRIES;
170 spin_lock(&dev->vblank_time_lock);
173 * sample the current counter to avoid random jumps
174 * when drm_vblank_enable() applies the diff
177 cur_vblank = __get_vblank_counter(dev, pipe);
178 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
179 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
182 * Only reinitialize corresponding vblank timestamp if high-precision query
183 * available and didn't fail. Otherwise reinitialize delayed at next vblank
184 * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
190 * +1 to make sure user will never see the same
191 * vblank counter value before and after a modeset
193 store_vblank(dev, pipe, 1, t_vblank, cur_vblank);
195 spin_unlock(&dev->vblank_time_lock);
199 * Call back into the driver to update the appropriate vblank counter
200 * (specified by @pipe). Deal with wraparound, if it occurred, and
201 * update the last read value so we can deal with wraparound on the next
204 * Only necessary when going from off->on, to account for frames we
205 * didn't get an interrupt for.
207 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
208 * device vblank fields.
210 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
213 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
214 u32 cur_vblank, diff;
217 int count = DRM_TIMESTAMP_MAXRETRIES;
218 int framedur_ns = vblank->framedur_ns;
219 u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
222 * Interrupts were disabled prior to this call, so deal with counter
224 * NOTE! It's possible we lost a full dev->max_vblank_count + 1 events
225 * here if the register is small or we had vblank interrupts off for
228 * We repeat the hardware vblank counter & timestamp query until
229 * we get consistent results. This to prevent races between gpu
230 * updating its hardware counter while we are retrieving the
231 * corresponding vblank timestamp.
234 cur_vblank = __get_vblank_counter(dev, pipe);
235 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, in_vblank_irq);
236 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
238 if (max_vblank_count) {
239 /* trust the hw counter when it's around */
240 diff = (cur_vblank - vblank->last) & max_vblank_count;
241 } else if (rc && framedur_ns) {
242 u64 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
245 * Figure out how many vblanks we've missed based
246 * on the difference in the timestamps and the
247 * frame/field duration.
250 DRM_DEBUG_VBL("crtc %u: Calculating number of vblanks."
251 " diff_ns = %lld, framedur_ns = %d)\n",
252 pipe, (long long) diff_ns, framedur_ns);
254 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
256 if (diff == 0 && in_vblank_irq)
257 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored\n",
260 /* some kind of default for drivers w/o accurate vbl timestamping */
261 diff = in_vblank_irq ? 1 : 0;
265 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
266 * interval? If so then vblank irqs keep running and it will likely
267 * happen that the hardware vblank counter is not trustworthy as it
268 * might reset at some point in that interval and vblank timestamps
269 * are not trustworthy either in that interval. Iow. this can result
270 * in a bogus diff >> 1 which must be avoided as it would cause
271 * random large forward jumps of the software vblank counter.
273 if (diff > 1 && (vblank->inmodeset & 0x2)) {
274 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
275 " due to pre-modeset.\n", pipe, diff);
279 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
280 " current=%llu, diff=%u, hw=%u hw_last=%u\n",
281 pipe, atomic64_read(&vblank->count), diff,
282 cur_vblank, vblank->last);
285 WARN_ON_ONCE(cur_vblank != vblank->last);
290 * Only reinitialize corresponding vblank timestamp if high-precision query
291 * available and didn't fail, or we were called from the vblank interrupt.
292 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
293 * for now, to mark the vblanktimestamp as invalid.
295 if (!rc && !in_vblank_irq)
298 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
301 static u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
303 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
306 if (WARN_ON(pipe >= dev->num_crtcs))
309 count = atomic64_read(&vblank->count);
312 * This read barrier corresponds to the implicit write barrier of the
313 * write seqlock in store_vblank(). Note that this is the only place
314 * where we need an explicit barrier, since all other access goes
315 * through drm_vblank_count_and_time(), which already has the required
316 * read barrier curtesy of the read seqlock.
324 * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
325 * @crtc: which counter to retrieve
327 * This function is similar to drm_crtc_vblank_count() but this function
328 * interpolates to handle a race with vblank interrupts using the high precision
329 * timestamping support.
331 * This is mostly useful for hardware that can obtain the scanout position, but
332 * doesn't have a hardware frame counter.
334 u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
336 struct drm_device *dev = crtc->dev;
337 unsigned int pipe = drm_crtc_index(crtc);
341 WARN_ONCE(drm_debug_enabled(DRM_UT_VBL) &&
342 !crtc->funcs->get_vblank_timestamp,
343 "This function requires support for accurate vblank timestamps.");
345 spin_lock_irqsave(&dev->vblank_time_lock, flags);
347 drm_update_vblank_count(dev, pipe, false);
348 vblank = drm_vblank_count(dev, pipe);
350 spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
354 EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
356 static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
358 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
359 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
364 if (crtc->funcs->disable_vblank)
365 crtc->funcs->disable_vblank(crtc);
367 dev->driver->disable_vblank(dev, pipe);
372 * Disable vblank irq's on crtc, make sure that last vblank count
373 * of hardware and corresponding consistent software vblank counter
374 * are preserved, even if there are any spurious vblank irq's after
377 void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
379 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
380 unsigned long irqflags;
382 assert_spin_locked(&dev->vbl_lock);
384 /* Prevent vblank irq processing while disabling vblank irqs,
385 * so no updates of timestamps or count can happen after we've
386 * disabled. Needed to prevent races in case of delayed irq's.
388 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
391 * Update vblank count and disable vblank interrupts only if the
392 * interrupts were enabled. This avoids calling the ->disable_vblank()
393 * operation in atomic context with the hardware potentially runtime
396 if (!vblank->enabled)
400 * Update the count and timestamp to maintain the
401 * appearance that the counter has been ticking all along until
402 * this time. This makes the count account for the entire time
403 * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
405 drm_update_vblank_count(dev, pipe, false);
406 __disable_vblank(dev, pipe);
407 vblank->enabled = false;
410 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
413 static void vblank_disable_fn(struct timer_list *t)
415 struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
416 struct drm_device *dev = vblank->dev;
417 unsigned int pipe = vblank->pipe;
418 unsigned long irqflags;
420 spin_lock_irqsave(&dev->vbl_lock, irqflags);
421 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
422 DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
423 drm_vblank_disable_and_save(dev, pipe);
425 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
428 void drm_vblank_cleanup(struct drm_device *dev)
432 /* Bail if the driver didn't call drm_vblank_init() */
433 if (dev->num_crtcs == 0)
436 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
437 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
439 WARN_ON(READ_ONCE(vblank->enabled) &&
440 drm_core_check_feature(dev, DRIVER_MODESET));
442 del_timer_sync(&vblank->disable_timer);
451 * drm_vblank_init - initialize vblank support
453 * @num_crtcs: number of CRTCs supported by @dev
455 * This function initializes vblank support for @num_crtcs display pipelines.
456 * Cleanup is handled by the DRM core, or through calling drm_dev_fini() for
457 * drivers with a &drm_driver.release callback.
460 * Zero on success or a negative error code on failure.
462 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
467 spin_lock_init(&dev->vbl_lock);
468 spin_lock_init(&dev->vblank_time_lock);
470 dev->num_crtcs = num_crtcs;
472 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
476 for (i = 0; i < num_crtcs; i++) {
477 struct drm_vblank_crtc *vblank = &dev->vblank[i];
481 init_waitqueue_head(&vblank->queue);
482 timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
483 seqlock_init(&vblank->seqlock);
486 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
494 EXPORT_SYMBOL(drm_vblank_init);
497 * drm_dev_has_vblank - test if vblanking has been initialized for
501 * Drivers may call this function to test if vblank support is
502 * initialized for a device. For most hardware this means that vblanking
503 * can also be enabled.
505 * Atomic helpers use this function to initialize
506 * &drm_crtc_state.no_vblank. See also drm_atomic_helper_check_modeset().
509 * True if vblanking has been initialized for the given device, false
512 bool drm_dev_has_vblank(const struct drm_device *dev)
514 return dev->num_crtcs != 0;
516 EXPORT_SYMBOL(drm_dev_has_vblank);
519 * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
520 * @crtc: which CRTC's vblank waitqueue to retrieve
522 * This function returns a pointer to the vblank waitqueue for the CRTC.
523 * Drivers can use this to implement vblank waits using wait_event() and related
526 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
528 return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
530 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
534 * drm_calc_timestamping_constants - calculate vblank timestamp constants
535 * @crtc: drm_crtc whose timestamp constants should be updated.
536 * @mode: display mode containing the scanout timings
538 * Calculate and store various constants which are later needed by vblank and
539 * swap-completion timestamping, e.g, by
540 * drm_crtc_vblank_helper_get_vblank_timestamp(). They are derived from
541 * CRTC's true scanout timing, so they take things like panel scaling or
542 * other adjustments into account.
544 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
545 const struct drm_display_mode *mode)
547 struct drm_device *dev = crtc->dev;
548 unsigned int pipe = drm_crtc_index(crtc);
549 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
550 int linedur_ns = 0, framedur_ns = 0;
551 int dotclock = mode->crtc_clock;
556 if (WARN_ON(pipe >= dev->num_crtcs))
559 /* Valid dotclock? */
561 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
564 * Convert scanline length in pixels and video
565 * dot clock to line duration and frame duration
568 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
569 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
572 * Fields of interlaced scanout modes are only half a frame duration.
574 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
577 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
580 vblank->linedur_ns = linedur_ns;
581 vblank->framedur_ns = framedur_ns;
582 vblank->hwmode = *mode;
584 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
585 crtc->base.id, mode->crtc_htotal,
586 mode->crtc_vtotal, mode->crtc_vdisplay);
587 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
588 crtc->base.id, dotclock, framedur_ns, linedur_ns);
590 EXPORT_SYMBOL(drm_calc_timestamping_constants);
593 * drm_crtc_vblank_helper_get_vblank_timestamp_internal - precise vblank
595 * @crtc: CRTC whose vblank timestamp to retrieve
596 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
597 * On return contains true maximum error of timestamp
598 * @vblank_time: Pointer to time which should receive the timestamp
600 * True when called from drm_crtc_handle_vblank(). Some drivers
601 * need to apply some workarounds for gpu-specific vblank irq quirks
603 * @get_scanout_position:
604 * Callback function to retrieve the scanout position. See
605 * @struct drm_crtc_helper_funcs.get_scanout_position.
607 * Implements calculation of exact vblank timestamps from given drm_display_mode
608 * timings and current video scanout position of a CRTC.
610 * The current implementation only handles standard video modes. For double scan
611 * and interlaced modes the driver is supposed to adjust the hardware mode
612 * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
613 * match the scanout position reported.
615 * Note that atomic drivers must call drm_calc_timestamping_constants() before
616 * enabling a CRTC. The atomic helpers already take care of that in
617 * drm_atomic_helper_update_legacy_modeset_state().
621 * Returns true on success, and false on failure, i.e. when no accurate
622 * timestamp could be acquired.
625 drm_crtc_vblank_helper_get_vblank_timestamp_internal(
626 struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time,
628 drm_vblank_get_scanout_position_func get_scanout_position)
630 struct drm_device *dev = crtc->dev;
631 unsigned int pipe = crtc->index;
632 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
633 struct timespec64 ts_etime, ts_vblank_time;
634 ktime_t stime, etime;
636 const struct drm_display_mode *mode;
638 int delta_ns, duration_ns;
640 if (pipe >= dev->num_crtcs) {
641 DRM_ERROR("Invalid crtc %u\n", pipe);
645 /* Scanout position query not supported? Should not happen. */
646 if (!get_scanout_position) {
647 DRM_ERROR("Called from CRTC w/o get_scanout_position()!?\n");
651 if (drm_drv_uses_atomic_modeset(dev))
652 mode = &vblank->hwmode;
654 mode = &crtc->hwmode;
656 /* If mode timing undefined, just return as no-op:
657 * Happens during initial modesetting of a crtc.
659 if (mode->crtc_clock == 0) {
660 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
661 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
665 /* Get current scanout position with system timestamp.
666 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
667 * if single query takes longer than max_error nanoseconds.
669 * This guarantees a tight bound on maximum error if
670 * code gets preempted or delayed for some reason.
672 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
674 * Get vertical and horizontal scanout position vpos, hpos,
675 * and bounding timestamps stime, etime, pre/post query.
677 vbl_status = get_scanout_position(crtc, in_vblank_irq,
682 /* Return as no-op if scanout query unsupported or failed. */
684 DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
689 /* Compute uncertainty in timestamp of scanout position query. */
690 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
692 /* Accept result with < max_error nsecs timing uncertainty. */
693 if (duration_ns <= *max_error)
697 /* Noisy system timing? */
698 if (i == DRM_TIMESTAMP_MAXRETRIES) {
699 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
700 pipe, duration_ns/1000, *max_error/1000, i);
703 /* Return upper bound of timestamp precision error. */
704 *max_error = duration_ns;
706 /* Convert scanout position into elapsed time at raw_time query
707 * since start of scanout at first display scanline. delta_ns
708 * can be negative if start of scanout hasn't happened yet.
710 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
713 /* Subtract time delta from raw timestamp to get final
714 * vblank_time timestamp for end of vblank.
716 *vblank_time = ktime_sub_ns(etime, delta_ns);
718 if (!drm_debug_enabled(DRM_UT_VBL))
721 ts_etime = ktime_to_timespec64(etime);
722 ts_vblank_time = ktime_to_timespec64(*vblank_time);
724 DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
726 (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
727 (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
728 duration_ns / 1000, i);
732 EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp_internal);
735 * drm_crtc_vblank_helper_get_vblank_timestamp - precise vblank timestamp
737 * @crtc: CRTC whose vblank timestamp to retrieve
738 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
739 * On return contains true maximum error of timestamp
740 * @vblank_time: Pointer to time which should receive the timestamp
742 * True when called from drm_crtc_handle_vblank(). Some drivers
743 * need to apply some workarounds for gpu-specific vblank irq quirks
746 * Implements calculation of exact vblank timestamps from given drm_display_mode
747 * timings and current video scanout position of a CRTC. This can be directly
748 * used as the &drm_crtc_funcs.get_vblank_timestamp implementation of a kms
749 * driver if &drm_crtc_helper_funcs.get_scanout_position is implemented.
751 * The current implementation only handles standard video modes. For double scan
752 * and interlaced modes the driver is supposed to adjust the hardware mode
753 * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
754 * match the scanout position reported.
756 * Note that atomic drivers must call drm_calc_timestamping_constants() before
757 * enabling a CRTC. The atomic helpers already take care of that in
758 * drm_atomic_helper_update_legacy_modeset_state().
762 * Returns true on success, and false on failure, i.e. when no accurate
763 * timestamp could be acquired.
765 bool drm_crtc_vblank_helper_get_vblank_timestamp(struct drm_crtc *crtc,
767 ktime_t *vblank_time,
770 return drm_crtc_vblank_helper_get_vblank_timestamp_internal(
771 crtc, max_error, vblank_time, in_vblank_irq,
772 crtc->helper_private->get_scanout_position);
774 EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp);
777 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
780 * @pipe: index of CRTC whose vblank timestamp to retrieve
781 * @tvblank: Pointer to target time which should receive the timestamp
783 * True when called from drm_crtc_handle_vblank(). Some drivers
784 * need to apply some workarounds for gpu-specific vblank irq quirks
787 * Fetches the system timestamp corresponding to the time of the most recent
788 * vblank interval on specified CRTC. May call into kms-driver to
789 * compute the timestamp with a high-precision GPU specific method.
791 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
792 * call, i.e., it isn't very precisely locked to the true vblank.
795 * True if timestamp is considered to be very precise, false otherwise.
798 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
799 ktime_t *tvblank, bool in_vblank_irq)
801 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
804 /* Define requested maximum error on timestamps (nanoseconds). */
805 int max_error = (int) drm_timestamp_precision * 1000;
807 /* Query driver if possible and precision timestamping enabled. */
808 if (crtc && crtc->funcs->get_vblank_timestamp && max_error > 0) {
809 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
811 ret = crtc->funcs->get_vblank_timestamp(crtc, &max_error,
812 tvblank, in_vblank_irq);
815 /* GPU high precision timestamp query unsupported or failed.
816 * Return current monotonic/gettimeofday timestamp as best estimate.
819 *tvblank = ktime_get();
825 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
826 * @crtc: which counter to retrieve
828 * Fetches the "cooked" vblank count value that represents the number of
829 * vblank events since the system was booted, including lost events due to
830 * modesetting activity. Note that this timer isn't correct against a racing
831 * vblank interrupt (since it only reports the software vblank counter), see
832 * drm_crtc_accurate_vblank_count() for such use-cases.
834 * Note that for a given vblank counter value drm_crtc_handle_vblank()
835 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
836 * provide a barrier: Any writes done before calling
837 * drm_crtc_handle_vblank() will be visible to callers of the later
838 * functions, iff the vblank count is the same or a later one.
840 * See also &drm_vblank_crtc.count.
843 * The software vblank counter.
845 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
847 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
849 EXPORT_SYMBOL(drm_crtc_vblank_count);
852 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
853 * system timestamp corresponding to that vblank counter value.
855 * @pipe: index of CRTC whose counter to retrieve
856 * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
858 * Fetches the "cooked" vblank count value that represents the number of
859 * vblank events since the system was booted, including lost events due to
860 * modesetting activity. Returns corresponding system timestamp of the time
861 * of the vblank interval that corresponds to the current vblank counter value.
863 * This is the legacy version of drm_crtc_vblank_count_and_time().
865 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
868 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
872 if (WARN_ON(pipe >= dev->num_crtcs)) {
878 seq = read_seqbegin(&vblank->seqlock);
879 vblank_count = atomic64_read(&vblank->count);
880 *vblanktime = vblank->time;
881 } while (read_seqretry(&vblank->seqlock, seq));
887 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
888 * and the system timestamp corresponding to that vblank counter value
889 * @crtc: which counter to retrieve
890 * @vblanktime: Pointer to time to receive the vblank timestamp.
892 * Fetches the "cooked" vblank count value that represents the number of
893 * vblank events since the system was booted, including lost events due to
894 * modesetting activity. Returns corresponding system timestamp of the time
895 * of the vblank interval that corresponds to the current vblank counter value.
897 * Note that for a given vblank counter value drm_crtc_handle_vblank()
898 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
899 * provide a barrier: Any writes done before calling
900 * drm_crtc_handle_vblank() will be visible to callers of the later
901 * functions, iff the vblank count is the same or a later one.
903 * See also &drm_vblank_crtc.count.
905 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
908 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
911 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
913 static void send_vblank_event(struct drm_device *dev,
914 struct drm_pending_vblank_event *e,
915 u64 seq, ktime_t now)
917 struct timespec64 tv;
919 switch (e->event.base.type) {
920 case DRM_EVENT_VBLANK:
921 case DRM_EVENT_FLIP_COMPLETE:
922 tv = ktime_to_timespec64(now);
923 e->event.vbl.sequence = seq;
925 * e->event is a user space structure, with hardcoded unsigned
926 * 32-bit seconds/microseconds. This is safe as we always use
927 * monotonic timestamps since linux-4.15
929 e->event.vbl.tv_sec = tv.tv_sec;
930 e->event.vbl.tv_usec = tv.tv_nsec / 1000;
932 case DRM_EVENT_CRTC_SEQUENCE:
934 e->event.seq.sequence = seq;
935 e->event.seq.time_ns = ktime_to_ns(now);
938 trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
939 drm_send_event_locked(dev, &e->base);
943 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
944 * @crtc: the source CRTC of the vblank event
945 * @e: the event to send
947 * A lot of drivers need to generate vblank events for the very next vblank
948 * interrupt. For example when the page flip interrupt happens when the page
949 * flip gets armed, but not when it actually executes within the next vblank
950 * period. This helper function implements exactly the required vblank arming
953 * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
954 * atomic commit must ensure that the next vblank happens at exactly the same
955 * time as the atomic commit is committed to the hardware. This function itself
956 * does **not** protect against the next vblank interrupt racing with either this
957 * function call or the atomic commit operation. A possible sequence could be:
959 * 1. Driver commits new hardware state into vblank-synchronized registers.
960 * 2. A vblank happens, committing the hardware state. Also the corresponding
961 * vblank interrupt is fired off and fully processed by the interrupt
963 * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
964 * 4. The event is only send out for the next vblank, which is wrong.
966 * An equivalent race can happen when the driver calls
967 * drm_crtc_arm_vblank_event() before writing out the new hardware state.
969 * The only way to make this work safely is to prevent the vblank from firing
970 * (and the hardware from committing anything else) until the entire atomic
971 * commit sequence has run to completion. If the hardware does not have such a
972 * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
973 * Instead drivers need to manually send out the event from their interrupt
974 * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
975 * possible race with the hardware committing the atomic update.
977 * Caller must hold a vblank reference for the event @e acquired by a
978 * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
980 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
981 struct drm_pending_vblank_event *e)
983 struct drm_device *dev = crtc->dev;
984 unsigned int pipe = drm_crtc_index(crtc);
986 assert_spin_locked(&dev->event_lock);
989 e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
990 list_add_tail(&e->base.link, &dev->vblank_event_list);
992 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
995 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
996 * @crtc: the source CRTC of the vblank event
997 * @e: the event to send
999 * Updates sequence # and timestamp on event for the most recently processed
1000 * vblank, and sends it to userspace. Caller must hold event lock.
1002 * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
1003 * situation, especially to send out events for atomic commit operations.
1005 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
1006 struct drm_pending_vblank_event *e)
1008 struct drm_device *dev = crtc->dev;
1010 unsigned int pipe = drm_crtc_index(crtc);
1013 if (dev->num_crtcs > 0) {
1014 seq = drm_vblank_count_and_time(dev, pipe, &now);
1021 send_vblank_event(dev, e, seq, now);
1023 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
1025 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
1027 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1028 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1033 if (crtc->funcs->enable_vblank)
1034 return crtc->funcs->enable_vblank(crtc);
1035 } else if (dev->driver->enable_vblank) {
1036 return dev->driver->enable_vblank(dev, pipe);
1042 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
1044 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1047 assert_spin_locked(&dev->vbl_lock);
1049 spin_lock(&dev->vblank_time_lock);
1051 if (!vblank->enabled) {
1053 * Enable vblank irqs under vblank_time_lock protection.
1054 * All vblank count & timestamp updates are held off
1055 * until we are done reinitializing master counter and
1056 * timestamps. Filtercode in drm_handle_vblank() will
1057 * prevent double-accounting of same vblank interval.
1059 ret = __enable_vblank(dev, pipe);
1060 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
1062 atomic_dec(&vblank->refcount);
1064 drm_update_vblank_count(dev, pipe, 0);
1065 /* drm_update_vblank_count() includes a wmb so we just
1066 * need to ensure that the compiler emits the write
1067 * to mark the vblank as enabled after the call
1068 * to drm_update_vblank_count().
1070 WRITE_ONCE(vblank->enabled, true);
1074 spin_unlock(&dev->vblank_time_lock);
1079 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
1081 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1082 unsigned long irqflags;
1085 if (!dev->num_crtcs)
1088 if (WARN_ON(pipe >= dev->num_crtcs))
1091 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1092 /* Going from 0->1 means we have to enable interrupts again */
1093 if (atomic_add_return(1, &vblank->refcount) == 1) {
1094 ret = drm_vblank_enable(dev, pipe);
1096 if (!vblank->enabled) {
1097 atomic_dec(&vblank->refcount);
1101 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1107 * drm_crtc_vblank_get - get a reference count on vblank events
1108 * @crtc: which CRTC to own
1110 * Acquire a reference count on vblank events to avoid having them disabled
1114 * Zero on success or a negative error code on failure.
1116 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1118 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1120 EXPORT_SYMBOL(drm_crtc_vblank_get);
1122 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1124 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1126 if (WARN_ON(pipe >= dev->num_crtcs))
1129 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1132 /* Last user schedules interrupt disable */
1133 if (atomic_dec_and_test(&vblank->refcount)) {
1134 if (drm_vblank_offdelay == 0)
1136 else if (drm_vblank_offdelay < 0)
1137 vblank_disable_fn(&vblank->disable_timer);
1138 else if (!dev->vblank_disable_immediate)
1139 mod_timer(&vblank->disable_timer,
1140 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1145 * drm_crtc_vblank_put - give up ownership of vblank events
1146 * @crtc: which counter to give up
1148 * Release ownership of a given vblank counter, turning off interrupts
1149 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1151 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1153 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1155 EXPORT_SYMBOL(drm_crtc_vblank_put);
1158 * drm_wait_one_vblank - wait for one vblank
1162 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1163 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1164 * due to lack of driver support or because the crtc is off.
1166 * This is the legacy version of drm_crtc_wait_one_vblank().
1168 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1170 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1174 if (WARN_ON(pipe >= dev->num_crtcs))
1177 ret = drm_vblank_get(dev, pipe);
1178 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1181 last = drm_vblank_count(dev, pipe);
1183 ret = wait_event_timeout(vblank->queue,
1184 last != drm_vblank_count(dev, pipe),
1185 msecs_to_jiffies(100));
1187 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1189 drm_vblank_put(dev, pipe);
1191 EXPORT_SYMBOL(drm_wait_one_vblank);
1194 * drm_crtc_wait_one_vblank - wait for one vblank
1197 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1198 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1199 * due to lack of driver support or because the crtc is off.
1201 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1203 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1205 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1208 * drm_crtc_vblank_off - disable vblank events on a CRTC
1209 * @crtc: CRTC in question
1211 * Drivers can use this function to shut down the vblank interrupt handling when
1212 * disabling a crtc. This function ensures that the latest vblank frame count is
1213 * stored so that drm_vblank_on can restore it again.
1215 * Drivers must use this function when the hardware vblank counter can get
1216 * reset, e.g. when suspending or disabling the @crtc in general.
1218 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1220 struct drm_device *dev = crtc->dev;
1221 unsigned int pipe = drm_crtc_index(crtc);
1222 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1223 struct drm_pending_vblank_event *e, *t;
1226 unsigned long irqflags;
1229 if (WARN_ON(pipe >= dev->num_crtcs))
1232 spin_lock_irqsave(&dev->event_lock, irqflags);
1234 spin_lock(&dev->vbl_lock);
1235 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1236 pipe, vblank->enabled, vblank->inmodeset);
1238 /* Avoid redundant vblank disables without previous
1239 * drm_crtc_vblank_on(). */
1240 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1241 drm_vblank_disable_and_save(dev, pipe);
1243 wake_up(&vblank->queue);
1246 * Prevent subsequent drm_vblank_get() from re-enabling
1247 * the vblank interrupt by bumping the refcount.
1249 if (!vblank->inmodeset) {
1250 atomic_inc(&vblank->refcount);
1251 vblank->inmodeset = 1;
1253 spin_unlock(&dev->vbl_lock);
1255 /* Send any queued vblank events, lest the natives grow disquiet */
1256 seq = drm_vblank_count_and_time(dev, pipe, &now);
1258 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1259 if (e->pipe != pipe)
1261 DRM_DEBUG("Sending premature vblank event on disable: "
1262 "wanted %llu, current %llu\n",
1264 list_del(&e->base.link);
1265 drm_vblank_put(dev, pipe);
1266 send_vblank_event(dev, e, seq, now);
1268 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1270 /* Will be reset by the modeset helpers when re-enabling the crtc by
1271 * calling drm_calc_timestamping_constants(). */
1272 vblank->hwmode.crtc_clock = 0;
1274 EXPORT_SYMBOL(drm_crtc_vblank_off);
1277 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1278 * @crtc: CRTC in question
1280 * Drivers can use this function to reset the vblank state to off at load time.
1281 * Drivers should use this together with the drm_crtc_vblank_off() and
1282 * drm_crtc_vblank_on() functions. The difference compared to
1283 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1284 * and hence doesn't need to call any driver hooks.
1286 * This is useful for recovering driver state e.g. on driver load, or on resume.
1288 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1290 struct drm_device *dev = crtc->dev;
1291 unsigned long irqflags;
1292 unsigned int pipe = drm_crtc_index(crtc);
1293 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1295 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1297 * Prevent subsequent drm_vblank_get() from enabling the vblank
1298 * interrupt by bumping the refcount.
1300 if (!vblank->inmodeset) {
1301 atomic_inc(&vblank->refcount);
1302 vblank->inmodeset = 1;
1304 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1306 WARN_ON(!list_empty(&dev->vblank_event_list));
1308 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1311 * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1312 * @crtc: CRTC in question
1313 * @max_vblank_count: max hardware vblank counter value
1315 * Update the maximum hardware vblank counter value for @crtc
1316 * at runtime. Useful for hardware where the operation of the
1317 * hardware vblank counter depends on the currently active
1318 * display configuration.
1320 * For example, if the hardware vblank counter does not work
1321 * when a specific connector is active the maximum can be set
1322 * to zero. And when that specific connector isn't active the
1323 * maximum can again be set to the appropriate non-zero value.
1325 * If used, must be called before drm_vblank_on().
1327 void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1328 u32 max_vblank_count)
1330 struct drm_device *dev = crtc->dev;
1331 unsigned int pipe = drm_crtc_index(crtc);
1332 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1334 WARN_ON(dev->max_vblank_count);
1335 WARN_ON(!READ_ONCE(vblank->inmodeset));
1337 vblank->max_vblank_count = max_vblank_count;
1339 EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1342 * drm_crtc_vblank_on - enable vblank events on a CRTC
1343 * @crtc: CRTC in question
1345 * This functions restores the vblank interrupt state captured with
1346 * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1347 * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1348 * unbalanced and so can also be unconditionally called in driver load code to
1349 * reflect the current hardware state of the crtc.
1351 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1353 struct drm_device *dev = crtc->dev;
1354 unsigned int pipe = drm_crtc_index(crtc);
1355 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1356 unsigned long irqflags;
1358 if (WARN_ON(pipe >= dev->num_crtcs))
1361 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1362 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1363 pipe, vblank->enabled, vblank->inmodeset);
1365 /* Drop our private "prevent drm_vblank_get" refcount */
1366 if (vblank->inmodeset) {
1367 atomic_dec(&vblank->refcount);
1368 vblank->inmodeset = 0;
1371 drm_reset_vblank_timestamp(dev, pipe);
1374 * re-enable interrupts if there are users left, or the
1375 * user wishes vblank interrupts to be enabled all the time.
1377 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1378 WARN_ON(drm_vblank_enable(dev, pipe));
1379 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1381 EXPORT_SYMBOL(drm_crtc_vblank_on);
1384 * drm_vblank_restore - estimate missed vblanks and update vblank count.
1388 * Power manamement features can cause frame counter resets between vblank
1389 * disable and enable. Drivers can use this function in their
1390 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1391 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1394 * This function is the legacy version of drm_crtc_vblank_restore().
1396 void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1399 struct drm_vblank_crtc *vblank;
1402 u32 cur_vblank, diff = 1;
1403 int count = DRM_TIMESTAMP_MAXRETRIES;
1405 if (WARN_ON(pipe >= dev->num_crtcs))
1408 assert_spin_locked(&dev->vbl_lock);
1409 assert_spin_locked(&dev->vblank_time_lock);
1411 vblank = &dev->vblank[pipe];
1412 WARN_ONCE(drm_debug_enabled(DRM_UT_VBL) && !vblank->framedur_ns,
1413 "Cannot compute missed vblanks without frame duration\n");
1414 framedur_ns = vblank->framedur_ns;
1417 cur_vblank = __get_vblank_counter(dev, pipe);
1418 drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1419 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1421 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1423 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1426 DRM_DEBUG_VBL("missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
1427 diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
1428 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
1430 EXPORT_SYMBOL(drm_vblank_restore);
1433 * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1434 * @crtc: CRTC in question
1436 * Power manamement features can cause frame counter resets between vblank
1437 * disable and enable. Drivers can use this function in their
1438 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1439 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1442 void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1444 drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1446 EXPORT_SYMBOL(drm_crtc_vblank_restore);
1448 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1451 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1453 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1454 if (!dev->num_crtcs)
1457 if (WARN_ON(pipe >= dev->num_crtcs))
1461 * To avoid all the problems that might happen if interrupts
1462 * were enabled/disabled around or between these calls, we just
1463 * have the kernel take a reference on the CRTC (just once though
1464 * to avoid corrupting the count if multiple, mismatch calls occur),
1465 * so that interrupts remain enabled in the interim.
1467 if (!vblank->inmodeset) {
1468 vblank->inmodeset = 0x1;
1469 if (drm_vblank_get(dev, pipe) == 0)
1470 vblank->inmodeset |= 0x2;
1474 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1477 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1478 unsigned long irqflags;
1480 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1481 if (!dev->num_crtcs)
1484 if (WARN_ON(pipe >= dev->num_crtcs))
1487 if (vblank->inmodeset) {
1488 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1489 drm_reset_vblank_timestamp(dev, pipe);
1490 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1492 if (vblank->inmodeset & 0x2)
1493 drm_vblank_put(dev, pipe);
1495 vblank->inmodeset = 0;
1499 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1500 struct drm_file *file_priv)
1502 struct drm_modeset_ctl *modeset = data;
1505 /* If drm_vblank_init() hasn't been called yet, just no-op */
1506 if (!dev->num_crtcs)
1509 /* KMS drivers handle this internally */
1510 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1513 pipe = modeset->crtc;
1514 if (pipe >= dev->num_crtcs)
1517 switch (modeset->cmd) {
1518 case _DRM_PRE_MODESET:
1519 drm_legacy_vblank_pre_modeset(dev, pipe);
1521 case _DRM_POST_MODESET:
1522 drm_legacy_vblank_post_modeset(dev, pipe);
1531 static inline bool vblank_passed(u64 seq, u64 ref)
1533 return (seq - ref) <= (1 << 23);
1536 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1538 union drm_wait_vblank *vblwait,
1539 struct drm_file *file_priv)
1541 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1542 struct drm_pending_vblank_event *e;
1544 unsigned long flags;
1548 e = kzalloc(sizeof(*e), GFP_KERNEL);
1555 e->event.base.type = DRM_EVENT_VBLANK;
1556 e->event.base.length = sizeof(e->event.vbl);
1557 e->event.vbl.user_data = vblwait->request.signal;
1558 e->event.vbl.crtc_id = 0;
1559 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1560 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1562 e->event.vbl.crtc_id = crtc->base.id;
1565 spin_lock_irqsave(&dev->event_lock, flags);
1568 * drm_crtc_vblank_off() might have been called after we called
1569 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1570 * vblank disable, so no need for further locking. The reference from
1571 * drm_vblank_get() protects against vblank disable from another source.
1573 if (!READ_ONCE(vblank->enabled)) {
1578 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1584 seq = drm_vblank_count_and_time(dev, pipe, &now);
1586 DRM_DEBUG("event on vblank count %llu, current %llu, crtc %u\n",
1587 req_seq, seq, pipe);
1589 trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1591 e->sequence = req_seq;
1592 if (vblank_passed(seq, req_seq)) {
1593 drm_vblank_put(dev, pipe);
1594 send_vblank_event(dev, e, seq, now);
1595 vblwait->reply.sequence = seq;
1597 /* drm_handle_vblank_events will call drm_vblank_put */
1598 list_add_tail(&e->base.link, &dev->vblank_event_list);
1599 vblwait->reply.sequence = req_seq;
1602 spin_unlock_irqrestore(&dev->event_lock, flags);
1607 spin_unlock_irqrestore(&dev->event_lock, flags);
1610 drm_vblank_put(dev, pipe);
1614 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1616 if (vblwait->request.sequence)
1619 return _DRM_VBLANK_RELATIVE ==
1620 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1622 _DRM_VBLANK_NEXTONMISS));
1626 * Widen a 32-bit param to 64-bits.
1628 * \param narrow 32-bit value (missing upper 32 bits)
1629 * \param near 64-bit value that should be 'close' to near
1631 * This function returns a 64-bit value using the lower 32-bits from
1632 * 'narrow' and constructing the upper 32-bits so that the result is
1633 * as close as possible to 'near'.
1636 static u64 widen_32_to_64(u32 narrow, u64 near)
1638 return near + (s32) (narrow - near);
1641 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1642 struct drm_wait_vblank_reply *reply)
1645 struct timespec64 ts;
1648 * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1649 * to store the seconds. This is safe as we always use monotonic
1650 * timestamps since linux-4.15.
1652 reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1653 ts = ktime_to_timespec64(now);
1654 reply->tval_sec = (u32)ts.tv_sec;
1655 reply->tval_usec = ts.tv_nsec / 1000;
1658 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1659 struct drm_file *file_priv)
1661 struct drm_crtc *crtc;
1662 struct drm_vblank_crtc *vblank;
1663 union drm_wait_vblank *vblwait = data;
1666 unsigned int pipe_index;
1667 unsigned int flags, pipe, high_pipe;
1669 if (!dev->irq_enabled)
1672 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1675 if (vblwait->request.type &
1676 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1677 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1678 DRM_DEBUG("Unsupported type value 0x%x, supported mask 0x%x\n",
1679 vblwait->request.type,
1680 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1681 _DRM_VBLANK_HIGH_CRTC_MASK));
1685 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1686 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1688 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1690 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1692 /* Convert lease-relative crtc index into global crtc index */
1693 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1695 drm_for_each_crtc(crtc, dev) {
1696 if (drm_lease_held(file_priv, crtc->base.id)) {
1697 if (pipe_index == 0)
1707 if (pipe >= dev->num_crtcs)
1710 vblank = &dev->vblank[pipe];
1712 /* If the counter is currently enabled and accurate, short-circuit
1713 * queries to return the cached timestamp of the last vblank.
1715 if (dev->vblank_disable_immediate &&
1716 drm_wait_vblank_is_query(vblwait) &&
1717 READ_ONCE(vblank->enabled)) {
1718 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1722 ret = drm_vblank_get(dev, pipe);
1724 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1727 seq = drm_vblank_count(dev, pipe);
1729 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1730 case _DRM_VBLANK_RELATIVE:
1731 req_seq = seq + vblwait->request.sequence;
1732 vblwait->request.sequence = req_seq;
1733 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1735 case _DRM_VBLANK_ABSOLUTE:
1736 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1743 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1744 vblank_passed(seq, req_seq)) {
1746 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1747 vblwait->request.sequence = req_seq;
1750 if (flags & _DRM_VBLANK_EVENT) {
1751 /* must hold on to the vblank ref until the event fires
1752 * drm_vblank_put will be called asynchronously
1754 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1757 if (req_seq != seq) {
1760 DRM_DEBUG("waiting on vblank count %llu, crtc %u\n",
1762 wait = wait_event_interruptible_timeout(vblank->queue,
1763 vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
1764 !READ_ONCE(vblank->enabled),
1765 msecs_to_jiffies(3000));
1773 /* interrupted by signal */
1782 if (ret != -EINTR) {
1783 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1785 DRM_DEBUG("crtc %d returning %u to client\n",
1786 pipe, vblwait->reply.sequence);
1788 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1792 drm_vblank_put(dev, pipe);
1796 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1798 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1799 bool high_prec = false;
1800 struct drm_pending_vblank_event *e, *t;
1804 assert_spin_locked(&dev->event_lock);
1806 seq = drm_vblank_count_and_time(dev, pipe, &now);
1808 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1809 if (e->pipe != pipe)
1811 if (!vblank_passed(seq, e->sequence))
1814 DRM_DEBUG("vblank event on %llu, current %llu\n",
1817 list_del(&e->base.link);
1818 drm_vblank_put(dev, pipe);
1819 send_vblank_event(dev, e, seq, now);
1822 if (crtc && crtc->funcs->get_vblank_timestamp)
1825 trace_drm_vblank_event(pipe, seq, now, high_prec);
1829 * drm_handle_vblank - handle a vblank event
1831 * @pipe: index of CRTC where this event occurred
1833 * Drivers should call this routine in their vblank interrupt handlers to
1834 * update the vblank counter and send any signals that may be pending.
1836 * This is the legacy version of drm_crtc_handle_vblank().
1838 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1840 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1841 unsigned long irqflags;
1844 if (WARN_ON_ONCE(!dev->num_crtcs))
1847 if (WARN_ON(pipe >= dev->num_crtcs))
1850 spin_lock_irqsave(&dev->event_lock, irqflags);
1852 /* Need timestamp lock to prevent concurrent execution with
1853 * vblank enable/disable, as this would cause inconsistent
1854 * or corrupted timestamps and vblank counts.
1856 spin_lock(&dev->vblank_time_lock);
1858 /* Vblank irq handling disabled. Nothing to do. */
1859 if (!vblank->enabled) {
1860 spin_unlock(&dev->vblank_time_lock);
1861 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1865 drm_update_vblank_count(dev, pipe, true);
1867 spin_unlock(&dev->vblank_time_lock);
1869 wake_up(&vblank->queue);
1871 /* With instant-off, we defer disabling the interrupt until after
1872 * we finish processing the following vblank after all events have
1873 * been signaled. The disable has to be last (after
1874 * drm_handle_vblank_events) so that the timestamp is always accurate.
1876 disable_irq = (dev->vblank_disable_immediate &&
1877 drm_vblank_offdelay > 0 &&
1878 !atomic_read(&vblank->refcount));
1880 drm_handle_vblank_events(dev, pipe);
1882 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1885 vblank_disable_fn(&vblank->disable_timer);
1889 EXPORT_SYMBOL(drm_handle_vblank);
1892 * drm_crtc_handle_vblank - handle a vblank event
1893 * @crtc: where this event occurred
1895 * Drivers should call this routine in their vblank interrupt handlers to
1896 * update the vblank counter and send any signals that may be pending.
1898 * This is the native KMS version of drm_handle_vblank().
1900 * Note that for a given vblank counter value drm_crtc_handle_vblank()
1901 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
1902 * provide a barrier: Any writes done before calling
1903 * drm_crtc_handle_vblank() will be visible to callers of the later
1904 * functions, iff the vblank count is the same or a later one.
1906 * See also &drm_vblank_crtc.count.
1909 * True if the event was successfully handled, false on failure.
1911 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1913 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1915 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1918 * Get crtc VBLANK count.
1920 * \param dev DRM device
1921 * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1922 * \param file_priv drm file private for the user's open file descriptor
1925 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1926 struct drm_file *file_priv)
1928 struct drm_crtc *crtc;
1929 struct drm_vblank_crtc *vblank;
1931 struct drm_crtc_get_sequence *get_seq = data;
1933 bool vblank_enabled;
1936 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1939 if (!dev->irq_enabled)
1942 crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
1946 pipe = drm_crtc_index(crtc);
1948 vblank = &dev->vblank[pipe];
1949 vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
1951 if (!vblank_enabled) {
1952 ret = drm_crtc_vblank_get(crtc);
1954 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1958 drm_modeset_lock(&crtc->mutex, NULL);
1960 get_seq->active = crtc->state->enable;
1962 get_seq->active = crtc->enabled;
1963 drm_modeset_unlock(&crtc->mutex);
1964 get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1965 get_seq->sequence_ns = ktime_to_ns(now);
1966 if (!vblank_enabled)
1967 drm_crtc_vblank_put(crtc);
1972 * Queue a event for VBLANK sequence
1974 * \param dev DRM device
1975 * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
1976 * \param file_priv drm file private for the user's open file descriptor
1979 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
1980 struct drm_file *file_priv)
1982 struct drm_crtc *crtc;
1983 struct drm_vblank_crtc *vblank;
1985 struct drm_crtc_queue_sequence *queue_seq = data;
1987 struct drm_pending_vblank_event *e;
1992 unsigned long spin_flags;
1994 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1997 if (!dev->irq_enabled)
2000 crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
2004 flags = queue_seq->flags;
2005 /* Check valid flag bits */
2006 if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
2007 DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
2010 pipe = drm_crtc_index(crtc);
2012 vblank = &dev->vblank[pipe];
2014 e = kzalloc(sizeof(*e), GFP_KERNEL);
2018 ret = drm_crtc_vblank_get(crtc);
2020 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
2024 seq = drm_vblank_count_and_time(dev, pipe, &now);
2025 req_seq = queue_seq->sequence;
2027 if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
2030 if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
2034 e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
2035 e->event.base.length = sizeof(e->event.seq);
2036 e->event.seq.user_data = queue_seq->user_data;
2038 spin_lock_irqsave(&dev->event_lock, spin_flags);
2041 * drm_crtc_vblank_off() might have been called after we called
2042 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
2043 * vblank disable, so no need for further locking. The reference from
2044 * drm_crtc_vblank_get() protects against vblank disable from another source.
2046 if (!READ_ONCE(vblank->enabled)) {
2051 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
2057 e->sequence = req_seq;
2059 if (vblank_passed(seq, req_seq)) {
2060 drm_crtc_vblank_put(crtc);
2061 send_vblank_event(dev, e, seq, now);
2062 queue_seq->sequence = seq;
2064 /* drm_handle_vblank_events will call drm_vblank_put */
2065 list_add_tail(&e->base.link, &dev->vblank_event_list);
2066 queue_seq->sequence = req_seq;
2069 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2073 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2074 drm_crtc_vblank_put(crtc);