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_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.
245 DRM_DEBUG_VBL("crtc %u: Calculating number of vblanks."
246 " diff_ns = %lld, framedur_ns = %d)\n",
247 pipe, (long long) diff_ns, framedur_ns);
249 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
251 if (diff == 0 && in_vblank_irq)
252 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored\n",
255 /* some kind of default for drivers w/o accurate vbl timestamping */
256 diff = in_vblank_irq ? 1 : 0;
260 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
261 * interval? If so then vblank irqs keep running and it will likely
262 * happen that the hardware vblank counter is not trustworthy as it
263 * might reset at some point in that interval and vblank timestamps
264 * are not trustworthy either in that interval. Iow. this can result
265 * in a bogus diff >> 1 which must be avoided as it would cause
266 * random large forward jumps of the software vblank counter.
268 if (diff > 1 && (vblank->inmodeset & 0x2)) {
269 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
270 " due to pre-modeset.\n", pipe, diff);
274 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
275 " current=%llu, diff=%u, hw=%u hw_last=%u\n",
276 pipe, vblank->count, diff, cur_vblank, vblank->last);
279 WARN_ON_ONCE(cur_vblank != vblank->last);
284 * Only reinitialize corresponding vblank timestamp if high-precision query
285 * available and didn't fail, or we were called from the vblank interrupt.
286 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
287 * for now, to mark the vblanktimestamp as invalid.
289 if (!rc && !in_vblank_irq)
292 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
295 static u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
297 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
299 if (WARN_ON(pipe >= dev->num_crtcs))
302 return vblank->count;
306 * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
307 * @crtc: which counter to retrieve
309 * This function is similar to drm_crtc_vblank_count() but this function
310 * interpolates to handle a race with vblank interrupts using the high precision
311 * timestamping support.
313 * This is mostly useful for hardware that can obtain the scanout position, but
314 * doesn't have a hardware frame counter.
316 u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
318 struct drm_device *dev = crtc->dev;
319 unsigned int pipe = drm_crtc_index(crtc);
323 WARN_ONCE(drm_debug & DRM_UT_VBL && !dev->driver->get_vblank_timestamp,
324 "This function requires support for accurate vblank timestamps.");
326 spin_lock_irqsave(&dev->vblank_time_lock, flags);
328 drm_update_vblank_count(dev, pipe, false);
329 vblank = drm_vblank_count(dev, pipe);
331 spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
335 EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
337 static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
339 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
340 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
345 if (crtc->funcs->disable_vblank) {
346 crtc->funcs->disable_vblank(crtc);
351 dev->driver->disable_vblank(dev, pipe);
355 * Disable vblank irq's on crtc, make sure that last vblank count
356 * of hardware and corresponding consistent software vblank counter
357 * are preserved, even if there are any spurious vblank irq's after
360 void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
362 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
363 unsigned long irqflags;
365 assert_spin_locked(&dev->vbl_lock);
367 /* Prevent vblank irq processing while disabling vblank irqs,
368 * so no updates of timestamps or count can happen after we've
369 * disabled. Needed to prevent races in case of delayed irq's.
371 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
374 * Update vblank count and disable vblank interrupts only if the
375 * interrupts were enabled. This avoids calling the ->disable_vblank()
376 * operation in atomic context with the hardware potentially runtime
379 if (!vblank->enabled)
383 * Update the count and timestamp to maintain the
384 * appearance that the counter has been ticking all along until
385 * this time. This makes the count account for the entire time
386 * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
388 drm_update_vblank_count(dev, pipe, false);
389 __disable_vblank(dev, pipe);
390 vblank->enabled = false;
393 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
396 static void vblank_disable_fn(struct timer_list *t)
398 struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
399 struct drm_device *dev = vblank->dev;
400 unsigned int pipe = vblank->pipe;
401 unsigned long irqflags;
403 spin_lock_irqsave(&dev->vbl_lock, irqflags);
404 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
405 DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
406 drm_vblank_disable_and_save(dev, pipe);
408 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
411 void drm_vblank_cleanup(struct drm_device *dev)
415 /* Bail if the driver didn't call drm_vblank_init() */
416 if (dev->num_crtcs == 0)
419 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
420 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
422 WARN_ON(READ_ONCE(vblank->enabled) &&
423 drm_core_check_feature(dev, DRIVER_MODESET));
425 del_timer_sync(&vblank->disable_timer);
434 * drm_vblank_init - initialize vblank support
436 * @num_crtcs: number of CRTCs supported by @dev
438 * This function initializes vblank support for @num_crtcs display pipelines.
439 * Cleanup is handled by the DRM core, or through calling drm_dev_fini() for
440 * drivers with a &drm_driver.release callback.
443 * Zero on success or a negative error code on failure.
445 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
450 spin_lock_init(&dev->vbl_lock);
451 spin_lock_init(&dev->vblank_time_lock);
453 dev->num_crtcs = num_crtcs;
455 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
459 for (i = 0; i < num_crtcs; i++) {
460 struct drm_vblank_crtc *vblank = &dev->vblank[i];
464 init_waitqueue_head(&vblank->queue);
465 timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
466 seqlock_init(&vblank->seqlock);
469 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
471 /* Driver specific high-precision vblank timestamping supported? */
472 if (dev->driver->get_vblank_timestamp)
473 DRM_INFO("Driver supports precise vblank timestamp query.\n");
475 DRM_INFO("No driver support for vblank timestamp query.\n");
477 /* Must have precise timestamping for reliable vblank instant disable */
478 if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
479 dev->vblank_disable_immediate = false;
480 DRM_INFO("Setting vblank_disable_immediate to false because "
481 "get_vblank_timestamp == NULL\n");
490 EXPORT_SYMBOL(drm_vblank_init);
493 * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
494 * @crtc: which CRTC's vblank waitqueue to retrieve
496 * This function returns a pointer to the vblank waitqueue for the CRTC.
497 * Drivers can use this to implement vblank waits using wait_event() and related
500 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
502 return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
504 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
508 * drm_calc_timestamping_constants - calculate vblank timestamp constants
509 * @crtc: drm_crtc whose timestamp constants should be updated.
510 * @mode: display mode containing the scanout timings
512 * Calculate and store various constants which are later needed by vblank and
513 * swap-completion timestamping, e.g, by
514 * drm_calc_vbltimestamp_from_scanoutpos(). They are derived from CRTC's true
515 * scanout timing, so they take things like panel scaling or other adjustments
518 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
519 const struct drm_display_mode *mode)
521 struct drm_device *dev = crtc->dev;
522 unsigned int pipe = drm_crtc_index(crtc);
523 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
524 int linedur_ns = 0, framedur_ns = 0;
525 int dotclock = mode->crtc_clock;
530 if (WARN_ON(pipe >= dev->num_crtcs))
533 /* Valid dotclock? */
535 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
538 * Convert scanline length in pixels and video
539 * dot clock to line duration and frame duration
542 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
543 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
546 * Fields of interlaced scanout modes are only half a frame duration.
548 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
551 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
554 vblank->linedur_ns = linedur_ns;
555 vblank->framedur_ns = framedur_ns;
556 vblank->hwmode = *mode;
558 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
559 crtc->base.id, mode->crtc_htotal,
560 mode->crtc_vtotal, mode->crtc_vdisplay);
561 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
562 crtc->base.id, dotclock, framedur_ns, linedur_ns);
564 EXPORT_SYMBOL(drm_calc_timestamping_constants);
567 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
569 * @pipe: index of CRTC whose vblank timestamp to retrieve
570 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
571 * On return contains true maximum error of timestamp
572 * @vblank_time: Pointer to time which should receive the timestamp
574 * True when called from drm_crtc_handle_vblank(). Some drivers
575 * need to apply some workarounds for gpu-specific vblank irq quirks
578 * Implements calculation of exact vblank timestamps from given drm_display_mode
579 * timings and current video scanout position of a CRTC. This can be directly
580 * used as the &drm_driver.get_vblank_timestamp implementation of a kms driver
581 * if &drm_driver.get_scanout_position is implemented.
583 * The current implementation only handles standard video modes. For double scan
584 * and interlaced modes the driver is supposed to adjust the hardware mode
585 * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
586 * match the scanout position reported.
588 * Note that atomic drivers must call drm_calc_timestamping_constants() before
589 * enabling a CRTC. The atomic helpers already take care of that in
590 * drm_atomic_helper_update_legacy_modeset_state().
594 * Returns true on success, and false on failure, i.e. when no accurate
595 * timestamp could be acquired.
597 bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
600 ktime_t *vblank_time,
603 struct timespec64 ts_etime, ts_vblank_time;
604 ktime_t stime, etime;
606 struct drm_crtc *crtc;
607 const struct drm_display_mode *mode;
608 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
610 int delta_ns, duration_ns;
612 if (!drm_core_check_feature(dev, DRIVER_MODESET))
615 crtc = drm_crtc_from_index(dev, pipe);
617 if (pipe >= dev->num_crtcs || !crtc) {
618 DRM_ERROR("Invalid crtc %u\n", pipe);
622 /* Scanout position query not supported? Should not happen. */
623 if (!dev->driver->get_scanout_position) {
624 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
628 if (drm_drv_uses_atomic_modeset(dev))
629 mode = &vblank->hwmode;
631 mode = &crtc->hwmode;
633 /* If mode timing undefined, just return as no-op:
634 * Happens during initial modesetting of a crtc.
636 if (mode->crtc_clock == 0) {
637 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
638 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
643 /* Get current scanout position with system timestamp.
644 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
645 * if single query takes longer than max_error nanoseconds.
647 * This guarantees a tight bound on maximum error if
648 * code gets preempted or delayed for some reason.
650 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
652 * Get vertical and horizontal scanout position vpos, hpos,
653 * and bounding timestamps stime, etime, pre/post query.
655 vbl_status = dev->driver->get_scanout_position(dev, pipe,
661 /* Return as no-op if scanout query unsupported or failed. */
663 DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
668 /* Compute uncertainty in timestamp of scanout position query. */
669 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
671 /* Accept result with < max_error nsecs timing uncertainty. */
672 if (duration_ns <= *max_error)
676 /* Noisy system timing? */
677 if (i == DRM_TIMESTAMP_MAXRETRIES) {
678 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
679 pipe, duration_ns/1000, *max_error/1000, i);
682 /* Return upper bound of timestamp precision error. */
683 *max_error = duration_ns;
685 /* Convert scanout position into elapsed time at raw_time query
686 * since start of scanout at first display scanline. delta_ns
687 * can be negative if start of scanout hasn't happened yet.
689 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
692 /* Subtract time delta from raw timestamp to get final
693 * vblank_time timestamp for end of vblank.
695 *vblank_time = ktime_sub_ns(etime, delta_ns);
697 if ((drm_debug & DRM_UT_VBL) == 0)
700 ts_etime = ktime_to_timespec64(etime);
701 ts_vblank_time = ktime_to_timespec64(*vblank_time);
703 DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
705 (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
706 (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
707 duration_ns / 1000, i);
711 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
714 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
717 * @pipe: index of CRTC whose vblank timestamp to retrieve
718 * @tvblank: Pointer to target time which should receive the timestamp
720 * True when called from drm_crtc_handle_vblank(). Some drivers
721 * need to apply some workarounds for gpu-specific vblank irq quirks
724 * Fetches the system timestamp corresponding to the time of the most recent
725 * vblank interval on specified CRTC. May call into kms-driver to
726 * compute the timestamp with a high-precision GPU specific method.
728 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
729 * call, i.e., it isn't very precisely locked to the true vblank.
732 * True if timestamp is considered to be very precise, false otherwise.
735 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
736 ktime_t *tvblank, bool in_vblank_irq)
740 /* Define requested maximum error on timestamps (nanoseconds). */
741 int max_error = (int) drm_timestamp_precision * 1000;
743 /* Query driver if possible and precision timestamping enabled. */
744 if (dev->driver->get_vblank_timestamp && (max_error > 0))
745 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
746 tvblank, in_vblank_irq);
748 /* GPU high precision timestamp query unsupported or failed.
749 * Return current monotonic/gettimeofday timestamp as best estimate.
752 *tvblank = ktime_get();
758 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
759 * @crtc: which counter to retrieve
761 * Fetches the "cooked" vblank count value that represents the number of
762 * vblank events since the system was booted, including lost events due to
763 * modesetting activity. Note that this timer isn't correct against a racing
764 * vblank interrupt (since it only reports the software vblank counter), see
765 * drm_crtc_accurate_vblank_count() for such use-cases.
768 * The software vblank counter.
770 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
772 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
774 EXPORT_SYMBOL(drm_crtc_vblank_count);
777 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
778 * system timestamp corresponding to that vblank counter value.
780 * @pipe: index of CRTC whose counter to retrieve
781 * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
783 * Fetches the "cooked" vblank count value that represents the number of
784 * vblank events since the system was booted, including lost events due to
785 * modesetting activity. Returns corresponding system timestamp of the time
786 * of the vblank interval that corresponds to the current vblank counter value.
788 * This is the legacy version of drm_crtc_vblank_count_and_time().
790 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
793 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
797 if (WARN_ON(pipe >= dev->num_crtcs)) {
803 seq = read_seqbegin(&vblank->seqlock);
804 vblank_count = vblank->count;
805 *vblanktime = vblank->time;
806 } while (read_seqretry(&vblank->seqlock, seq));
812 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
813 * and the system timestamp corresponding to that vblank counter value
814 * @crtc: which counter to retrieve
815 * @vblanktime: Pointer to time to receive the vblank timestamp.
817 * Fetches the "cooked" vblank count value that represents the number of
818 * vblank events since the system was booted, including lost events due to
819 * modesetting activity. Returns corresponding system timestamp of the time
820 * of the vblank interval that corresponds to the current vblank counter value.
822 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
825 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
828 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
830 static void send_vblank_event(struct drm_device *dev,
831 struct drm_pending_vblank_event *e,
832 u64 seq, ktime_t now)
834 struct timespec64 tv;
836 switch (e->event.base.type) {
837 case DRM_EVENT_VBLANK:
838 case DRM_EVENT_FLIP_COMPLETE:
839 tv = ktime_to_timespec64(now);
840 e->event.vbl.sequence = seq;
842 * e->event is a user space structure, with hardcoded unsigned
843 * 32-bit seconds/microseconds. This is safe as we always use
844 * monotonic timestamps since linux-4.15
846 e->event.vbl.tv_sec = tv.tv_sec;
847 e->event.vbl.tv_usec = tv.tv_nsec / 1000;
849 case DRM_EVENT_CRTC_SEQUENCE:
851 e->event.seq.sequence = seq;
852 e->event.seq.time_ns = ktime_to_ns(now);
855 trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
856 drm_send_event_locked(dev, &e->base);
860 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
861 * @crtc: the source CRTC of the vblank event
862 * @e: the event to send
864 * A lot of drivers need to generate vblank events for the very next vblank
865 * interrupt. For example when the page flip interrupt happens when the page
866 * flip gets armed, but not when it actually executes within the next vblank
867 * period. This helper function implements exactly the required vblank arming
870 * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
871 * atomic commit must ensure that the next vblank happens at exactly the same
872 * time as the atomic commit is committed to the hardware. This function itself
873 * does **not** protect against the next vblank interrupt racing with either this
874 * function call or the atomic commit operation. A possible sequence could be:
876 * 1. Driver commits new hardware state into vblank-synchronized registers.
877 * 2. A vblank happens, committing the hardware state. Also the corresponding
878 * vblank interrupt is fired off and fully processed by the interrupt
880 * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
881 * 4. The event is only send out for the next vblank, which is wrong.
883 * An equivalent race can happen when the driver calls
884 * drm_crtc_arm_vblank_event() before writing out the new hardware state.
886 * The only way to make this work safely is to prevent the vblank from firing
887 * (and the hardware from committing anything else) until the entire atomic
888 * commit sequence has run to completion. If the hardware does not have such a
889 * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
890 * Instead drivers need to manually send out the event from their interrupt
891 * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
892 * possible race with the hardware committing the atomic update.
894 * Caller must hold a vblank reference for the event @e acquired by a
895 * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
897 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
898 struct drm_pending_vblank_event *e)
900 struct drm_device *dev = crtc->dev;
901 unsigned int pipe = drm_crtc_index(crtc);
903 assert_spin_locked(&dev->event_lock);
906 e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
907 list_add_tail(&e->base.link, &dev->vblank_event_list);
909 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
912 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
913 * @crtc: the source CRTC of the vblank event
914 * @e: the event to send
916 * Updates sequence # and timestamp on event for the most recently processed
917 * vblank, and sends it to userspace. Caller must hold event lock.
919 * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
920 * situation, especially to send out events for atomic commit operations.
922 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
923 struct drm_pending_vblank_event *e)
925 struct drm_device *dev = crtc->dev;
927 unsigned int pipe = drm_crtc_index(crtc);
930 if (dev->num_crtcs > 0) {
931 seq = drm_vblank_count_and_time(dev, pipe, &now);
938 send_vblank_event(dev, e, seq, now);
940 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
942 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
944 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
945 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
950 if (crtc->funcs->enable_vblank)
951 return crtc->funcs->enable_vblank(crtc);
954 return dev->driver->enable_vblank(dev, pipe);
957 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
959 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
962 assert_spin_locked(&dev->vbl_lock);
964 spin_lock(&dev->vblank_time_lock);
966 if (!vblank->enabled) {
968 * Enable vblank irqs under vblank_time_lock protection.
969 * All vblank count & timestamp updates are held off
970 * until we are done reinitializing master counter and
971 * timestamps. Filtercode in drm_handle_vblank() will
972 * prevent double-accounting of same vblank interval.
974 ret = __enable_vblank(dev, pipe);
975 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
977 atomic_dec(&vblank->refcount);
979 drm_update_vblank_count(dev, pipe, 0);
980 /* drm_update_vblank_count() includes a wmb so we just
981 * need to ensure that the compiler emits the write
982 * to mark the vblank as enabled after the call
983 * to drm_update_vblank_count().
985 WRITE_ONCE(vblank->enabled, true);
989 spin_unlock(&dev->vblank_time_lock);
994 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
996 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
997 unsigned long irqflags;
1000 if (!dev->num_crtcs)
1003 if (WARN_ON(pipe >= dev->num_crtcs))
1006 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1007 /* Going from 0->1 means we have to enable interrupts again */
1008 if (atomic_add_return(1, &vblank->refcount) == 1) {
1009 ret = drm_vblank_enable(dev, pipe);
1011 if (!vblank->enabled) {
1012 atomic_dec(&vblank->refcount);
1016 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1022 * drm_crtc_vblank_get - get a reference count on vblank events
1023 * @crtc: which CRTC to own
1025 * Acquire a reference count on vblank events to avoid having them disabled
1029 * Zero on success or a negative error code on failure.
1031 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1033 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1035 EXPORT_SYMBOL(drm_crtc_vblank_get);
1037 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1039 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1041 if (WARN_ON(pipe >= dev->num_crtcs))
1044 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1047 /* Last user schedules interrupt disable */
1048 if (atomic_dec_and_test(&vblank->refcount)) {
1049 if (drm_vblank_offdelay == 0)
1051 else if (drm_vblank_offdelay < 0)
1052 vblank_disable_fn(&vblank->disable_timer);
1053 else if (!dev->vblank_disable_immediate)
1054 mod_timer(&vblank->disable_timer,
1055 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1060 * drm_crtc_vblank_put - give up ownership of vblank events
1061 * @crtc: which counter to give up
1063 * Release ownership of a given vblank counter, turning off interrupts
1064 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1066 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1068 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1070 EXPORT_SYMBOL(drm_crtc_vblank_put);
1073 * drm_wait_one_vblank - wait for one vblank
1077 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1078 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1079 * due to lack of driver support or because the crtc is off.
1081 * This is the legacy version of drm_crtc_wait_one_vblank().
1083 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1085 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1089 if (WARN_ON(pipe >= dev->num_crtcs))
1092 ret = drm_vblank_get(dev, pipe);
1093 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1096 last = drm_vblank_count(dev, pipe);
1098 ret = wait_event_timeout(vblank->queue,
1099 last != drm_vblank_count(dev, pipe),
1100 msecs_to_jiffies(100));
1102 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1104 drm_vblank_put(dev, pipe);
1106 EXPORT_SYMBOL(drm_wait_one_vblank);
1109 * drm_crtc_wait_one_vblank - wait for one vblank
1112 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1113 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1114 * due to lack of driver support or because the crtc is off.
1116 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1118 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1120 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1123 * drm_crtc_vblank_off - disable vblank events on a CRTC
1124 * @crtc: CRTC in question
1126 * Drivers can use this function to shut down the vblank interrupt handling when
1127 * disabling a crtc. This function ensures that the latest vblank frame count is
1128 * stored so that drm_vblank_on can restore it again.
1130 * Drivers must use this function when the hardware vblank counter can get
1131 * reset, e.g. when suspending or disabling the @crtc in general.
1133 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1135 struct drm_device *dev = crtc->dev;
1136 unsigned int pipe = drm_crtc_index(crtc);
1137 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1138 struct drm_pending_vblank_event *e, *t;
1141 unsigned long irqflags;
1144 if (WARN_ON(pipe >= dev->num_crtcs))
1147 spin_lock_irqsave(&dev->event_lock, irqflags);
1149 spin_lock(&dev->vbl_lock);
1150 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1151 pipe, vblank->enabled, vblank->inmodeset);
1153 /* Avoid redundant vblank disables without previous
1154 * drm_crtc_vblank_on(). */
1155 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1156 drm_vblank_disable_and_save(dev, pipe);
1158 wake_up(&vblank->queue);
1161 * Prevent subsequent drm_vblank_get() from re-enabling
1162 * the vblank interrupt by bumping the refcount.
1164 if (!vblank->inmodeset) {
1165 atomic_inc(&vblank->refcount);
1166 vblank->inmodeset = 1;
1168 spin_unlock(&dev->vbl_lock);
1170 /* Send any queued vblank events, lest the natives grow disquiet */
1171 seq = drm_vblank_count_and_time(dev, pipe, &now);
1173 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1174 if (e->pipe != pipe)
1176 DRM_DEBUG("Sending premature vblank event on disable: "
1177 "wanted %llu, current %llu\n",
1179 list_del(&e->base.link);
1180 drm_vblank_put(dev, pipe);
1181 send_vblank_event(dev, e, seq, now);
1183 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1185 /* Will be reset by the modeset helpers when re-enabling the crtc by
1186 * calling drm_calc_timestamping_constants(). */
1187 vblank->hwmode.crtc_clock = 0;
1189 EXPORT_SYMBOL(drm_crtc_vblank_off);
1192 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1193 * @crtc: CRTC in question
1195 * Drivers can use this function to reset the vblank state to off at load time.
1196 * Drivers should use this together with the drm_crtc_vblank_off() and
1197 * drm_crtc_vblank_on() functions. The difference compared to
1198 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1199 * and hence doesn't need to call any driver hooks.
1201 * This is useful for recovering driver state e.g. on driver load, or on resume.
1203 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1205 struct drm_device *dev = crtc->dev;
1206 unsigned long irqflags;
1207 unsigned int pipe = drm_crtc_index(crtc);
1208 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1210 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1212 * Prevent subsequent drm_vblank_get() from enabling the vblank
1213 * interrupt by bumping the refcount.
1215 if (!vblank->inmodeset) {
1216 atomic_inc(&vblank->refcount);
1217 vblank->inmodeset = 1;
1219 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1221 WARN_ON(!list_empty(&dev->vblank_event_list));
1223 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1226 * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1227 * @crtc: CRTC in question
1228 * @max_vblank_count: max hardware vblank counter value
1230 * Update the maximum hardware vblank counter value for @crtc
1231 * at runtime. Useful for hardware where the operation of the
1232 * hardware vblank counter depends on the currently active
1233 * display configuration.
1235 * For example, if the hardware vblank counter does not work
1236 * when a specific connector is active the maximum can be set
1237 * to zero. And when that specific connector isn't active the
1238 * maximum can again be set to the appropriate non-zero value.
1240 * If used, must be called before drm_vblank_on().
1242 void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1243 u32 max_vblank_count)
1245 struct drm_device *dev = crtc->dev;
1246 unsigned int pipe = drm_crtc_index(crtc);
1247 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1249 WARN_ON(dev->max_vblank_count);
1250 WARN_ON(!READ_ONCE(vblank->inmodeset));
1252 vblank->max_vblank_count = max_vblank_count;
1254 EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1257 * drm_crtc_vblank_on - enable vblank events on a CRTC
1258 * @crtc: CRTC in question
1260 * This functions restores the vblank interrupt state captured with
1261 * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1262 * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1263 * unbalanced and so can also be unconditionally called in driver load code to
1264 * reflect the current hardware state of the crtc.
1266 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1268 struct drm_device *dev = crtc->dev;
1269 unsigned int pipe = drm_crtc_index(crtc);
1270 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1271 unsigned long irqflags;
1273 if (WARN_ON(pipe >= dev->num_crtcs))
1276 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1277 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1278 pipe, vblank->enabled, vblank->inmodeset);
1280 /* Drop our private "prevent drm_vblank_get" refcount */
1281 if (vblank->inmodeset) {
1282 atomic_dec(&vblank->refcount);
1283 vblank->inmodeset = 0;
1286 drm_reset_vblank_timestamp(dev, pipe);
1289 * re-enable interrupts if there are users left, or the
1290 * user wishes vblank interrupts to be enabled all the time.
1292 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1293 WARN_ON(drm_vblank_enable(dev, pipe));
1294 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1296 EXPORT_SYMBOL(drm_crtc_vblank_on);
1299 * drm_vblank_restore - estimate missed vblanks and update vblank count.
1303 * Power manamement features can cause frame counter resets between vblank
1304 * disable and enable. Drivers can use this function in their
1305 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1306 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1309 * This function is the legacy version of drm_crtc_vblank_restore().
1311 void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1314 struct drm_vblank_crtc *vblank;
1317 u32 cur_vblank, diff = 1;
1318 int count = DRM_TIMESTAMP_MAXRETRIES;
1320 if (WARN_ON(pipe >= dev->num_crtcs))
1323 assert_spin_locked(&dev->vbl_lock);
1324 assert_spin_locked(&dev->vblank_time_lock);
1326 vblank = &dev->vblank[pipe];
1327 WARN_ONCE((drm_debug & DRM_UT_VBL) && !vblank->framedur_ns,
1328 "Cannot compute missed vblanks without frame duration\n");
1329 framedur_ns = vblank->framedur_ns;
1332 cur_vblank = __get_vblank_counter(dev, pipe);
1333 drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1334 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1336 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1338 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1341 DRM_DEBUG_VBL("missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
1342 diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
1343 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
1345 EXPORT_SYMBOL(drm_vblank_restore);
1348 * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1349 * @crtc: CRTC in question
1351 * Power manamement features can cause frame counter resets between vblank
1352 * disable and enable. Drivers can use this function in their
1353 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1354 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1357 void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1359 drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1361 EXPORT_SYMBOL(drm_crtc_vblank_restore);
1363 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1366 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1368 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1369 if (!dev->num_crtcs)
1372 if (WARN_ON(pipe >= dev->num_crtcs))
1376 * To avoid all the problems that might happen if interrupts
1377 * were enabled/disabled around or between these calls, we just
1378 * have the kernel take a reference on the CRTC (just once though
1379 * to avoid corrupting the count if multiple, mismatch calls occur),
1380 * so that interrupts remain enabled in the interim.
1382 if (!vblank->inmodeset) {
1383 vblank->inmodeset = 0x1;
1384 if (drm_vblank_get(dev, pipe) == 0)
1385 vblank->inmodeset |= 0x2;
1389 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1392 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1393 unsigned long irqflags;
1395 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1396 if (!dev->num_crtcs)
1399 if (WARN_ON(pipe >= dev->num_crtcs))
1402 if (vblank->inmodeset) {
1403 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1404 drm_reset_vblank_timestamp(dev, pipe);
1405 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1407 if (vblank->inmodeset & 0x2)
1408 drm_vblank_put(dev, pipe);
1410 vblank->inmodeset = 0;
1414 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1415 struct drm_file *file_priv)
1417 struct drm_modeset_ctl *modeset = data;
1420 /* If drm_vblank_init() hasn't been called yet, just no-op */
1421 if (!dev->num_crtcs)
1424 /* KMS drivers handle this internally */
1425 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1428 pipe = modeset->crtc;
1429 if (pipe >= dev->num_crtcs)
1432 switch (modeset->cmd) {
1433 case _DRM_PRE_MODESET:
1434 drm_legacy_vblank_pre_modeset(dev, pipe);
1436 case _DRM_POST_MODESET:
1437 drm_legacy_vblank_post_modeset(dev, pipe);
1446 static inline bool vblank_passed(u64 seq, u64 ref)
1448 return (seq - ref) <= (1 << 23);
1451 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1453 union drm_wait_vblank *vblwait,
1454 struct drm_file *file_priv)
1456 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1457 struct drm_pending_vblank_event *e;
1459 unsigned long flags;
1463 e = kzalloc(sizeof(*e), GFP_KERNEL);
1470 e->event.base.type = DRM_EVENT_VBLANK;
1471 e->event.base.length = sizeof(e->event.vbl);
1472 e->event.vbl.user_data = vblwait->request.signal;
1473 e->event.vbl.crtc_id = 0;
1474 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1475 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1477 e->event.vbl.crtc_id = crtc->base.id;
1480 spin_lock_irqsave(&dev->event_lock, flags);
1483 * drm_crtc_vblank_off() might have been called after we called
1484 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1485 * vblank disable, so no need for further locking. The reference from
1486 * drm_vblank_get() protects against vblank disable from another source.
1488 if (!READ_ONCE(vblank->enabled)) {
1493 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1499 seq = drm_vblank_count_and_time(dev, pipe, &now);
1501 DRM_DEBUG("event on vblank count %llu, current %llu, crtc %u\n",
1502 req_seq, seq, pipe);
1504 trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1506 e->sequence = req_seq;
1507 if (vblank_passed(seq, req_seq)) {
1508 drm_vblank_put(dev, pipe);
1509 send_vblank_event(dev, e, seq, now);
1510 vblwait->reply.sequence = seq;
1512 /* drm_handle_vblank_events will call drm_vblank_put */
1513 list_add_tail(&e->base.link, &dev->vblank_event_list);
1514 vblwait->reply.sequence = req_seq;
1517 spin_unlock_irqrestore(&dev->event_lock, flags);
1522 spin_unlock_irqrestore(&dev->event_lock, flags);
1525 drm_vblank_put(dev, pipe);
1529 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1531 if (vblwait->request.sequence)
1534 return _DRM_VBLANK_RELATIVE ==
1535 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1537 _DRM_VBLANK_NEXTONMISS));
1541 * Widen a 32-bit param to 64-bits.
1543 * \param narrow 32-bit value (missing upper 32 bits)
1544 * \param near 64-bit value that should be 'close' to near
1546 * This function returns a 64-bit value using the lower 32-bits from
1547 * 'narrow' and constructing the upper 32-bits so that the result is
1548 * as close as possible to 'near'.
1551 static u64 widen_32_to_64(u32 narrow, u64 near)
1553 return near + (s32) (narrow - near);
1556 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1557 struct drm_wait_vblank_reply *reply)
1560 struct timespec64 ts;
1563 * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1564 * to store the seconds. This is safe as we always use monotonic
1565 * timestamps since linux-4.15.
1567 reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1568 ts = ktime_to_timespec64(now);
1569 reply->tval_sec = (u32)ts.tv_sec;
1570 reply->tval_usec = ts.tv_nsec / 1000;
1573 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1574 struct drm_file *file_priv)
1576 struct drm_crtc *crtc;
1577 struct drm_vblank_crtc *vblank;
1578 union drm_wait_vblank *vblwait = data;
1581 unsigned int pipe_index;
1582 unsigned int flags, pipe, high_pipe;
1584 if (!dev->irq_enabled)
1587 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1590 if (vblwait->request.type &
1591 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1592 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1593 DRM_DEBUG("Unsupported type value 0x%x, supported mask 0x%x\n",
1594 vblwait->request.type,
1595 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1596 _DRM_VBLANK_HIGH_CRTC_MASK));
1600 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1601 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1603 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1605 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1607 /* Convert lease-relative crtc index into global crtc index */
1608 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1610 drm_for_each_crtc(crtc, dev) {
1611 if (drm_lease_held(file_priv, crtc->base.id)) {
1612 if (pipe_index == 0)
1622 if (pipe >= dev->num_crtcs)
1625 vblank = &dev->vblank[pipe];
1627 /* If the counter is currently enabled and accurate, short-circuit
1628 * queries to return the cached timestamp of the last vblank.
1630 if (dev->vblank_disable_immediate &&
1631 drm_wait_vblank_is_query(vblwait) &&
1632 READ_ONCE(vblank->enabled)) {
1633 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1637 ret = drm_vblank_get(dev, pipe);
1639 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1642 seq = drm_vblank_count(dev, pipe);
1644 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1645 case _DRM_VBLANK_RELATIVE:
1646 req_seq = seq + vblwait->request.sequence;
1647 vblwait->request.sequence = req_seq;
1648 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1650 case _DRM_VBLANK_ABSOLUTE:
1651 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1658 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1659 vblank_passed(seq, req_seq)) {
1661 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1662 vblwait->request.sequence = req_seq;
1665 if (flags & _DRM_VBLANK_EVENT) {
1666 /* must hold on to the vblank ref until the event fires
1667 * drm_vblank_put will be called asynchronously
1669 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1672 if (req_seq != seq) {
1673 DRM_DEBUG("waiting on vblank count %llu, crtc %u\n",
1675 DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1676 vblank_passed(drm_vblank_count(dev, pipe),
1678 !READ_ONCE(vblank->enabled));
1681 if (ret != -EINTR) {
1682 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1684 DRM_DEBUG("crtc %d returning %u to client\n",
1685 pipe, vblwait->reply.sequence);
1687 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1691 drm_vblank_put(dev, pipe);
1695 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1697 struct drm_pending_vblank_event *e, *t;
1701 assert_spin_locked(&dev->event_lock);
1703 seq = drm_vblank_count_and_time(dev, pipe, &now);
1705 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1706 if (e->pipe != pipe)
1708 if (!vblank_passed(seq, e->sequence))
1711 DRM_DEBUG("vblank event on %llu, current %llu\n",
1714 list_del(&e->base.link);
1715 drm_vblank_put(dev, pipe);
1716 send_vblank_event(dev, e, seq, now);
1719 trace_drm_vblank_event(pipe, seq);
1723 * drm_handle_vblank - handle a vblank event
1725 * @pipe: index of CRTC where this event occurred
1727 * Drivers should call this routine in their vblank interrupt handlers to
1728 * update the vblank counter and send any signals that may be pending.
1730 * This is the legacy version of drm_crtc_handle_vblank().
1732 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1734 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1735 unsigned long irqflags;
1738 if (WARN_ON_ONCE(!dev->num_crtcs))
1741 if (WARN_ON(pipe >= dev->num_crtcs))
1744 spin_lock_irqsave(&dev->event_lock, irqflags);
1746 /* Need timestamp lock to prevent concurrent execution with
1747 * vblank enable/disable, as this would cause inconsistent
1748 * or corrupted timestamps and vblank counts.
1750 spin_lock(&dev->vblank_time_lock);
1752 /* Vblank irq handling disabled. Nothing to do. */
1753 if (!vblank->enabled) {
1754 spin_unlock(&dev->vblank_time_lock);
1755 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1759 drm_update_vblank_count(dev, pipe, true);
1761 spin_unlock(&dev->vblank_time_lock);
1763 wake_up(&vblank->queue);
1765 /* With instant-off, we defer disabling the interrupt until after
1766 * we finish processing the following vblank after all events have
1767 * been signaled. The disable has to be last (after
1768 * drm_handle_vblank_events) so that the timestamp is always accurate.
1770 disable_irq = (dev->vblank_disable_immediate &&
1771 drm_vblank_offdelay > 0 &&
1772 !atomic_read(&vblank->refcount));
1774 drm_handle_vblank_events(dev, pipe);
1776 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1779 vblank_disable_fn(&vblank->disable_timer);
1783 EXPORT_SYMBOL(drm_handle_vblank);
1786 * drm_crtc_handle_vblank - handle a vblank event
1787 * @crtc: where this event occurred
1789 * Drivers should call this routine in their vblank interrupt handlers to
1790 * update the vblank counter and send any signals that may be pending.
1792 * This is the native KMS version of drm_handle_vblank().
1795 * True if the event was successfully handled, false on failure.
1797 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1799 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1801 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1804 * Get crtc VBLANK count.
1806 * \param dev DRM device
1807 * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1808 * \param file_priv drm file private for the user's open file descriptor
1811 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1812 struct drm_file *file_priv)
1814 struct drm_crtc *crtc;
1815 struct drm_vblank_crtc *vblank;
1817 struct drm_crtc_get_sequence *get_seq = data;
1819 bool vblank_enabled;
1822 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1825 if (!dev->irq_enabled)
1828 crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
1832 pipe = drm_crtc_index(crtc);
1834 vblank = &dev->vblank[pipe];
1835 vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
1837 if (!vblank_enabled) {
1838 ret = drm_crtc_vblank_get(crtc);
1840 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1844 drm_modeset_lock(&crtc->mutex, NULL);
1846 get_seq->active = crtc->state->enable;
1848 get_seq->active = crtc->enabled;
1849 drm_modeset_unlock(&crtc->mutex);
1850 get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1851 get_seq->sequence_ns = ktime_to_ns(now);
1852 if (!vblank_enabled)
1853 drm_crtc_vblank_put(crtc);
1858 * Queue a event for VBLANK sequence
1860 * \param dev DRM device
1861 * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
1862 * \param file_priv drm file private for the user's open file descriptor
1865 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
1866 struct drm_file *file_priv)
1868 struct drm_crtc *crtc;
1869 struct drm_vblank_crtc *vblank;
1871 struct drm_crtc_queue_sequence *queue_seq = data;
1873 struct drm_pending_vblank_event *e;
1878 unsigned long spin_flags;
1880 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1883 if (!dev->irq_enabled)
1886 crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
1890 flags = queue_seq->flags;
1891 /* Check valid flag bits */
1892 if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
1893 DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
1896 pipe = drm_crtc_index(crtc);
1898 vblank = &dev->vblank[pipe];
1900 e = kzalloc(sizeof(*e), GFP_KERNEL);
1904 ret = drm_crtc_vblank_get(crtc);
1906 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1910 seq = drm_vblank_count_and_time(dev, pipe, &now);
1911 req_seq = queue_seq->sequence;
1913 if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
1916 if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
1920 e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
1921 e->event.base.length = sizeof(e->event.seq);
1922 e->event.seq.user_data = queue_seq->user_data;
1924 spin_lock_irqsave(&dev->event_lock, spin_flags);
1927 * drm_crtc_vblank_off() might have been called after we called
1928 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1929 * vblank disable, so no need for further locking. The reference from
1930 * drm_crtc_vblank_get() protects against vblank disable from another source.
1932 if (!READ_ONCE(vblank->enabled)) {
1937 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1943 e->sequence = req_seq;
1945 if (vblank_passed(seq, req_seq)) {
1946 drm_crtc_vblank_put(crtc);
1947 send_vblank_event(dev, e, seq, now);
1948 queue_seq->sequence = seq;
1950 /* drm_handle_vblank_events will call drm_vblank_put */
1951 list_add_tail(&e->base.link, &dev->vblank_event_list);
1952 queue_seq->sequence = req_seq;
1955 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1959 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1960 drm_crtc_vblank_put(crtc);