drm_vblank.c revision 1.5 1 /* $NetBSD: drm_vblank.c,v 1.5 2021/12/19 09:52:34 riastradh Exp $ */
2
3 /*
4 * drm_irq.c IRQ and vblank support
5 *
6 * \author Rickard E. (Rik) Faith <faith (at) valinux.com>
7 * \author Gareth Hughes <gareth (at) valinux.com>
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice (including the next
17 * paragraph) shall be included in all copies or substantial portions of the
18 * Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
24 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26 * OTHER DEALINGS IN THE SOFTWARE.
27 */
28
29 #include <sys/cdefs.h>
30 __KERNEL_RCSID(0, "$NetBSD: drm_vblank.c,v 1.5 2021/12/19 09:52:34 riastradh Exp $");
31
32 #include <linux/export.h>
33 #include <linux/moduleparam.h>
34 #include <linux/math64.h>
35
36 #include <drm/drm_crtc.h>
37 #include <drm/drm_drv.h>
38 #include <drm/drm_framebuffer.h>
39 #include <drm/drm_print.h>
40 #include <drm/drm_vblank.h>
41
42 #include "drm_internal.h"
43 #include "drm_trace.h"
44
45 /**
46 * DOC: vblank handling
47 *
48 * Vertical blanking plays a major role in graphics rendering. To achieve
49 * tear-free display, users must synchronize page flips and/or rendering to
50 * vertical blanking. The DRM API offers ioctls to perform page flips
51 * synchronized to vertical blanking and wait for vertical blanking.
52 *
53 * The DRM core handles most of the vertical blanking management logic, which
54 * involves filtering out spurious interrupts, keeping race-free blanking
55 * counters, coping with counter wrap-around and resets and keeping use counts.
56 * It relies on the driver to generate vertical blanking interrupts and
57 * optionally provide a hardware vertical blanking counter.
58 *
59 * Drivers must initialize the vertical blanking handling core with a call to
60 * drm_vblank_init(). Minimally, a driver needs to implement
61 * &drm_crtc_funcs.enable_vblank and &drm_crtc_funcs.disable_vblank plus call
62 * drm_crtc_handle_vblank() in its vblank interrupt handler for working vblank
63 * support.
64 *
65 * Vertical blanking interrupts can be enabled by the DRM core or by drivers
66 * themselves (for instance to handle page flipping operations). The DRM core
67 * maintains a vertical blanking use count to ensure that the interrupts are not
68 * disabled while a user still needs them. To increment the use count, drivers
69 * call drm_crtc_vblank_get() and release the vblank reference again with
70 * drm_crtc_vblank_put(). In between these two calls vblank interrupts are
71 * guaranteed to be enabled.
72 *
73 * On many hardware disabling the vblank interrupt cannot be done in a race-free
74 * manner, see &drm_driver.vblank_disable_immediate and
75 * &drm_driver.max_vblank_count. In that case the vblank core only disables the
76 * vblanks after a timer has expired, which can be configured through the
77 * ``vblankoffdelay`` module parameter.
78 */
79
80 /* Retry timestamp calculation up to 3 times to satisfy
81 * drm_timestamp_precision before giving up.
82 */
83 #define DRM_TIMESTAMP_MAXRETRIES 3
84
85 /* Threshold in nanoseconds for detection of redundant
86 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
87 */
88 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
89
90 static bool
91 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
92 ktime_t *tvblank, bool in_vblank_irq);
93
94 static unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
95
96 static int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
97
98 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
99 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
100 MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
101 MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
102
103 static void store_vblank(struct drm_device *dev, unsigned int pipe,
104 u32 vblank_count_inc,
105 ktime_t t_vblank, u32 last)
106 {
107 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
108
109 assert_spin_locked(&dev->vblank_time_lock);
110
111 vblank->last = last;
112
113 write_seqlock(&vblank->seqlock);
114 vblank->time = t_vblank;
115 atomic64_add(vblank_count_inc, &vblank->count);
116 write_sequnlock(&vblank->seqlock);
117 }
118
119 static u32 drm_max_vblank_count(struct drm_device *dev, unsigned int pipe)
120 {
121 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
122
123 return vblank->max_vblank_count ?: dev->max_vblank_count;
124 }
125
126 /*
127 * "No hw counter" fallback implementation of .get_vblank_counter() hook,
128 * if there is no useable hardware frame counter available.
129 */
130 static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
131 {
132 WARN_ON_ONCE(drm_max_vblank_count(dev, pipe) != 0);
133 return 0;
134 }
135
136 static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
137 {
138 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
139 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
140
141 if (WARN_ON(!crtc))
142 return 0;
143
144 if (crtc->funcs->get_vblank_counter)
145 return crtc->funcs->get_vblank_counter(crtc);
146 }
147
148 if (dev->driver->get_vblank_counter)
149 return dev->driver->get_vblank_counter(dev, pipe);
150
151 return drm_vblank_no_hw_counter(dev, pipe);
152 }
153
154 /*
155 * Reset the stored timestamp for the current vblank count to correspond
156 * to the last vblank occurred.
157 *
158 * Only to be called from drm_crtc_vblank_on().
159 *
160 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
161 * device vblank fields.
162 */
163 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
164 {
165 u32 cur_vblank;
166 bool rc;
167 ktime_t t_vblank;
168 int count = DRM_TIMESTAMP_MAXRETRIES;
169
170 spin_lock(&dev->vblank_time_lock);
171
172 /*
173 * sample the current counter to avoid random jumps
174 * when drm_vblank_enable() applies the diff
175 */
176 do {
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);
180
181 /*
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.
185 */
186 if (!rc)
187 t_vblank = 0;
188
189 /*
190 * +1 to make sure user will never see the same
191 * vblank counter value before and after a modeset
192 */
193 store_vblank(dev, pipe, 1, t_vblank, cur_vblank);
194
195 spin_unlock(&dev->vblank_time_lock);
196 }
197
198 /*
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
202 * call if necessary.
203 *
204 * Only necessary when going from off->on, to account for frames we
205 * didn't get an interrupt for.
206 *
207 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
208 * device vblank fields.
209 */
210 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
211 bool in_vblank_irq)
212 {
213 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
214 u32 cur_vblank, diff;
215 bool rc;
216 ktime_t t_vblank;
217 int count = DRM_TIMESTAMP_MAXRETRIES;
218 int framedur_ns = vblank->framedur_ns;
219 u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
220
221 /*
222 * Interrupts were disabled prior to this call, so deal with counter
223 * wrap if needed.
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
226 * a long time.
227 *
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.
232 */
233 do {
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);
237
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));
243
244 /*
245 * Figure out how many vblanks we've missed based
246 * on the difference in the timestamps and the
247 * frame/field duration.
248 */
249
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);
253
254 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
255
256 if (diff == 0 && in_vblank_irq)
257 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored\n",
258 pipe);
259 } else {
260 /* some kind of default for drivers w/o accurate vbl timestamping */
261 diff = in_vblank_irq ? 1 : 0;
262 }
263
264 /*
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.
272 */
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);
276 diff = 1;
277 }
278
279 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
280 " current=%"PRIu64", diff=%u, hw=%u hw_last=%u\n",
281 pipe, atomic64_read(&vblank->count), diff,
282 cur_vblank, vblank->last);
283
284 if (diff == 0) {
285 WARN_ON_ONCE(cur_vblank != vblank->last);
286 return;
287 }
288
289 /*
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.
294 */
295 if (!rc && !in_vblank_irq)
296 t_vblank = 0;
297
298 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
299 }
300
301 static u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
302 {
303 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
304 u64 count;
305
306 if (WARN_ON(pipe >= dev->num_crtcs))
307 return 0;
308
309 count = atomic64_read(&vblank->count);
310
311 /*
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.
317 */
318 smp_rmb();
319
320 return count;
321 }
322
323 /**
324 * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
325 * @crtc: which counter to retrieve
326 *
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.
330 *
331 * This is mostly useful for hardware that can obtain the scanout position, but
332 * doesn't have a hardware frame counter.
333 */
334 u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
335 {
336 struct drm_device *dev = crtc->dev;
337 unsigned int pipe = drm_crtc_index(crtc);
338 u64 vblank;
339 unsigned long flags;
340
341 WARN_ONCE(drm_debug_enabled(DRM_UT_VBL) && !dev->driver->get_vblank_timestamp,
342 "This function requires support for accurate vblank timestamps.");
343
344 spin_lock_irqsave(&dev->vblank_time_lock, flags);
345
346 drm_update_vblank_count(dev, pipe, false);
347 vblank = drm_vblank_count(dev, pipe);
348
349 spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
350
351 return vblank;
352 }
353 EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
354
355 static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
356 {
357 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
358 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
359
360 if (WARN_ON(!crtc))
361 return;
362
363 if (crtc->funcs->disable_vblank) {
364 crtc->funcs->disable_vblank(crtc);
365 return;
366 }
367 }
368
369 dev->driver->disable_vblank(dev, pipe);
370 }
371
372 /*
373 * Disable vblank irq's on crtc, make sure that last vblank count
374 * of hardware and corresponding consistent software vblank counter
375 * are preserved, even if there are any spurious vblank irq's after
376 * disable.
377 */
378 void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
379 {
380 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
381 unsigned long irqflags;
382
383 assert_spin_locked(&dev->vbl_lock);
384
385 /* Prevent vblank irq processing while disabling vblank irqs,
386 * so no updates of timestamps or count can happen after we've
387 * disabled. Needed to prevent races in case of delayed irq's.
388 */
389 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
390
391 /*
392 * Update vblank count and disable vblank interrupts only if the
393 * interrupts were enabled. This avoids calling the ->disable_vblank()
394 * operation in atomic context with the hardware potentially runtime
395 * suspended.
396 */
397 if (!vblank->enabled)
398 goto out;
399
400 /*
401 * Update the count and timestamp to maintain the
402 * appearance that the counter has been ticking all along until
403 * this time. This makes the count account for the entire time
404 * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
405 */
406 drm_update_vblank_count(dev, pipe, false);
407 __disable_vblank(dev, pipe);
408 vblank->enabled = false;
409
410 out:
411 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
412 }
413
414 static void vblank_disable_fn(struct timer_list *t)
415 {
416 struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
417 struct drm_device *dev = vblank->dev;
418 unsigned int pipe = vblank->pipe;
419 unsigned long irqflags;
420
421 spin_lock_irqsave(&dev->vbl_lock, irqflags);
422 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
423 DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
424 drm_vblank_disable_and_save(dev, pipe);
425 }
426 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
427 }
428
429 void drm_vblank_cleanup(struct drm_device *dev)
430 {
431 unsigned int pipe;
432
433 /* Bail if the driver didn't call drm_vblank_init() */
434 if (dev->num_crtcs == 0)
435 return;
436
437 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
438 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
439
440 WARN_ON(READ_ONCE(vblank->enabled) &&
441 drm_core_check_feature(dev, DRIVER_MODESET));
442
443 del_timer_sync(&vblank->disable_timer);
444 #ifdef __NetBSD__
445 teardown_timer(&vblank->disable_timer);
446 seqlock_destroy(&vblank->seqlock);
447 #endif
448 }
449
450 kfree(dev->vblank);
451
452 dev->num_crtcs = 0;
453 }
454
455 /**
456 * drm_vblank_init - initialize vblank support
457 * @dev: DRM device
458 * @num_crtcs: number of CRTCs supported by @dev
459 *
460 * This function initializes vblank support for @num_crtcs display pipelines.
461 * Cleanup is handled by the DRM core, or through calling drm_dev_fini() for
462 * drivers with a &drm_driver.release callback.
463 *
464 * Returns:
465 * Zero on success or a negative error code on failure.
466 */
467 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
468 {
469 int ret = -ENOMEM;
470 unsigned int i;
471
472 spin_lock_init(&dev->vbl_lock);
473 spin_lock_init(&dev->vblank_time_lock);
474
475 dev->num_crtcs = num_crtcs;
476
477 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
478 if (!dev->vblank)
479 goto err;
480
481 for (i = 0; i < num_crtcs; i++) {
482 struct drm_vblank_crtc *vblank = &dev->vblank[i];
483
484 vblank->dev = dev;
485 vblank->pipe = i;
486 #ifdef __NetBSD__
487 DRM_INIT_WAITQUEUE(&vblank->queue, "drmvblnq");
488 #else
489 init_waitqueue_head(&vblank->queue);
490 #endif
491 timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
492 seqlock_init(&vblank->seqlock);
493 }
494
495 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
496
497 /* Driver specific high-precision vblank timestamping supported? */
498 if (dev->driver->get_vblank_timestamp)
499 DRM_INFO("Driver supports precise vblank timestamp query.\n");
500 else
501 DRM_INFO("No driver support for vblank timestamp query.\n");
502
503 /* Must have precise timestamping for reliable vblank instant disable */
504 if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
505 dev->vblank_disable_immediate = false;
506 DRM_INFO("Setting vblank_disable_immediate to false because "
507 "get_vblank_timestamp == NULL\n");
508 }
509
510 return 0;
511
512 err:
513 dev->num_crtcs = 0;
514 return ret;
515 }
516 EXPORT_SYMBOL(drm_vblank_init);
517
518 /**
519 * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
520 * @crtc: which CRTC's vblank waitqueue to retrieve
521 *
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
524 * functions.
525 */
526 #ifdef __NetBSD__
527 drm_waitqueue_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
528 #else
529 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
530 #endif
531 {
532 return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
533 }
534 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
535
536
537 /**
538 * drm_calc_timestamping_constants - calculate vblank timestamp constants
539 * @crtc: drm_crtc whose timestamp constants should be updated.
540 * @mode: display mode containing the scanout timings
541 *
542 * Calculate and store various constants which are later needed by vblank and
543 * swap-completion timestamping, e.g, by
544 * drm_calc_vbltimestamp_from_scanoutpos(). They are derived from CRTC's true
545 * scanout timing, so they take things like panel scaling or other adjustments
546 * into account.
547 */
548 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
549 const struct drm_display_mode *mode)
550 {
551 struct drm_device *dev = crtc->dev;
552 unsigned int pipe = drm_crtc_index(crtc);
553 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
554 int linedur_ns = 0, framedur_ns = 0;
555 int dotclock = mode->crtc_clock;
556
557 if (!dev->num_crtcs)
558 return;
559
560 if (WARN_ON(pipe >= dev->num_crtcs))
561 return;
562
563 /* Valid dotclock? */
564 if (dotclock > 0) {
565 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
566
567 /*
568 * Convert scanline length in pixels and video
569 * dot clock to line duration and frame duration
570 * in nanoseconds:
571 */
572 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
573 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
574
575 /*
576 * Fields of interlaced scanout modes are only half a frame duration.
577 */
578 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
579 framedur_ns /= 2;
580 } else
581 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
582 crtc->base.id);
583
584 vblank->linedur_ns = linedur_ns;
585 vblank->framedur_ns = framedur_ns;
586 vblank->hwmode = *mode;
587
588 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
589 crtc->base.id, mode->crtc_htotal,
590 mode->crtc_vtotal, mode->crtc_vdisplay);
591 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
592 crtc->base.id, dotclock, framedur_ns, linedur_ns);
593 }
594 EXPORT_SYMBOL(drm_calc_timestamping_constants);
595
596 /**
597 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
598 * @dev: DRM device
599 * @pipe: index of CRTC whose vblank timestamp to retrieve
600 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
601 * On return contains true maximum error of timestamp
602 * @vblank_time: Pointer to time which should receive the timestamp
603 * @in_vblank_irq:
604 * True when called from drm_crtc_handle_vblank(). Some drivers
605 * need to apply some workarounds for gpu-specific vblank irq quirks
606 * if flag is set.
607 *
608 * Implements calculation of exact vblank timestamps from given drm_display_mode
609 * timings and current video scanout position of a CRTC. This can be directly
610 * used as the &drm_driver.get_vblank_timestamp implementation of a kms driver
611 * if &drm_driver.get_scanout_position is implemented.
612 *
613 * The current implementation only handles standard video modes. For double scan
614 * and interlaced modes the driver is supposed to adjust the hardware mode
615 * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
616 * match the scanout position reported.
617 *
618 * Note that atomic drivers must call drm_calc_timestamping_constants() before
619 * enabling a CRTC. The atomic helpers already take care of that in
620 * drm_atomic_helper_update_legacy_modeset_state().
621 *
622 * Returns:
623 *
624 * Returns true on success, and false on failure, i.e. when no accurate
625 * timestamp could be acquired.
626 */
627 bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
628 unsigned int pipe,
629 int *max_error,
630 ktime_t *vblank_time,
631 bool in_vblank_irq)
632 {
633 struct timespec64 ts_etime, ts_vblank_time;
634 ktime_t stime, etime;
635 bool vbl_status;
636 struct drm_crtc *crtc;
637 const struct drm_display_mode *mode;
638 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
639 int vpos, hpos, i;
640 int delta_ns, duration_ns;
641
642 if (!drm_core_check_feature(dev, DRIVER_MODESET))
643 return false;
644
645 crtc = drm_crtc_from_index(dev, pipe);
646
647 if (pipe >= dev->num_crtcs || !crtc) {
648 DRM_ERROR("Invalid crtc %u\n", pipe);
649 return false;
650 }
651
652 /* Scanout position query not supported? Should not happen. */
653 if (!dev->driver->get_scanout_position) {
654 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
655 return false;
656 }
657
658 if (drm_drv_uses_atomic_modeset(dev))
659 mode = &vblank->hwmode;
660 else
661 mode = &crtc->hwmode;
662
663 /* If mode timing undefined, just return as no-op:
664 * Happens during initial modesetting of a crtc.
665 */
666 if (mode->crtc_clock == 0) {
667 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
668 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
669
670 return false;
671 }
672
673 /* Get current scanout position with system timestamp.
674 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
675 * if single query takes longer than max_error nanoseconds.
676 *
677 * This guarantees a tight bound on maximum error if
678 * code gets preempted or delayed for some reason.
679 */
680 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
681 /*
682 * Get vertical and horizontal scanout position vpos, hpos,
683 * and bounding timestamps stime, etime, pre/post query.
684 */
685 vbl_status = dev->driver->get_scanout_position(dev, pipe,
686 in_vblank_irq,
687 &vpos, &hpos,
688 &stime, &etime,
689 mode);
690
691 /* Return as no-op if scanout query unsupported or failed. */
692 if (!vbl_status) {
693 DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
694 pipe);
695 return false;
696 }
697
698 /* Compute uncertainty in timestamp of scanout position query. */
699 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
700
701 /* Accept result with < max_error nsecs timing uncertainty. */
702 if (duration_ns <= *max_error)
703 break;
704 }
705
706 /* Noisy system timing? */
707 if (i == DRM_TIMESTAMP_MAXRETRIES) {
708 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
709 pipe, duration_ns/1000, *max_error/1000, i);
710 }
711
712 /* Return upper bound of timestamp precision error. */
713 *max_error = duration_ns;
714
715 /* Convert scanout position into elapsed time at raw_time query
716 * since start of scanout at first display scanline. delta_ns
717 * can be negative if start of scanout hasn't happened yet.
718 */
719 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
720 mode->crtc_clock);
721
722 /* Subtract time delta from raw timestamp to get final
723 * vblank_time timestamp for end of vblank.
724 */
725 *vblank_time = ktime_sub_ns(etime, delta_ns);
726
727 if (!drm_debug_enabled(DRM_UT_VBL))
728 return true;
729
730 ts_etime = ktime_to_timespec64(etime);
731 ts_vblank_time = ktime_to_timespec64(*vblank_time);
732
733 DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %"PRId64".%06ld -> %"PRId64".%06ld [e %d us, %d rep]\n",
734 pipe, hpos, vpos,
735 (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
736 (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
737 duration_ns / 1000, i);
738
739 return true;
740 }
741 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
742
743 /**
744 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
745 * vblank interval
746 * @dev: DRM device
747 * @pipe: index of CRTC whose vblank timestamp to retrieve
748 * @tvblank: Pointer to target time which should receive the timestamp
749 * @in_vblank_irq:
750 * True when called from drm_crtc_handle_vblank(). Some drivers
751 * need to apply some workarounds for gpu-specific vblank irq quirks
752 * if flag is set.
753 *
754 * Fetches the system timestamp corresponding to the time of the most recent
755 * vblank interval on specified CRTC. May call into kms-driver to
756 * compute the timestamp with a high-precision GPU specific method.
757 *
758 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
759 * call, i.e., it isn't very precisely locked to the true vblank.
760 *
761 * Returns:
762 * True if timestamp is considered to be very precise, false otherwise.
763 */
764 static bool
765 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
766 ktime_t *tvblank, bool in_vblank_irq)
767 {
768 bool ret = false;
769
770 /* Define requested maximum error on timestamps (nanoseconds). */
771 int max_error = (int) drm_timestamp_precision * 1000;
772
773 /* Query driver if possible and precision timestamping enabled. */
774 if (dev->driver->get_vblank_timestamp && (max_error > 0))
775 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
776 tvblank, in_vblank_irq);
777
778 /* GPU high precision timestamp query unsupported or failed.
779 * Return current monotonic/gettimeofday timestamp as best estimate.
780 */
781 if (!ret)
782 *tvblank = ktime_get();
783
784 return ret;
785 }
786
787 /**
788 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
789 * @crtc: which counter to retrieve
790 *
791 * Fetches the "cooked" vblank count value that represents the number of
792 * vblank events since the system was booted, including lost events due to
793 * modesetting activity. Note that this timer isn't correct against a racing
794 * vblank interrupt (since it only reports the software vblank counter), see
795 * drm_crtc_accurate_vblank_count() for such use-cases.
796 *
797 * Note that for a given vblank counter value drm_crtc_handle_vblank()
798 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
799 * provide a barrier: Any writes done before calling
800 * drm_crtc_handle_vblank() will be visible to callers of the later
801 * functions, iff the vblank count is the same or a later one.
802 *
803 * See also &drm_vblank_crtc.count.
804 *
805 * Returns:
806 * The software vblank counter.
807 */
808 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
809 {
810 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
811 }
812 EXPORT_SYMBOL(drm_crtc_vblank_count);
813
814 /**
815 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
816 * system timestamp corresponding to that vblank counter value.
817 * @dev: DRM device
818 * @pipe: index of CRTC whose counter to retrieve
819 * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
820 *
821 * Fetches the "cooked" vblank count value that represents the number of
822 * vblank events since the system was booted, including lost events due to
823 * modesetting activity. Returns corresponding system timestamp of the time
824 * of the vblank interval that corresponds to the current vblank counter value.
825 *
826 * This is the legacy version of drm_crtc_vblank_count_and_time().
827 */
828 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
829 ktime_t *vblanktime)
830 {
831 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
832 u64 vblank_count;
833 unsigned int seq;
834
835 if (WARN_ON(pipe >= dev->num_crtcs)) {
836 *vblanktime = 0;
837 return 0;
838 }
839
840 do {
841 seq = read_seqbegin(&vblank->seqlock);
842 vblank_count = atomic64_read(&vblank->count);
843 *vblanktime = vblank->time;
844 } while (read_seqretry(&vblank->seqlock, seq));
845
846 return vblank_count;
847 }
848
849 /**
850 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
851 * and the system timestamp corresponding to that vblank counter value
852 * @crtc: which counter to retrieve
853 * @vblanktime: Pointer to time to receive the vblank timestamp.
854 *
855 * Fetches the "cooked" vblank count value that represents the number of
856 * vblank events since the system was booted, including lost events due to
857 * modesetting activity. Returns corresponding system timestamp of the time
858 * of the vblank interval that corresponds to the current vblank counter value.
859 *
860 * Note that for a given vblank counter value drm_crtc_handle_vblank()
861 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
862 * provide a barrier: Any writes done before calling
863 * drm_crtc_handle_vblank() will be visible to callers of the later
864 * functions, iff the vblank count is the same or a later one.
865 *
866 * See also &drm_vblank_crtc.count.
867 */
868 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
869 ktime_t *vblanktime)
870 {
871 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
872 vblanktime);
873 }
874 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
875
876 static void send_vblank_event(struct drm_device *dev,
877 struct drm_pending_vblank_event *e,
878 u64 seq, ktime_t now)
879 {
880 struct timespec64 tv;
881
882 switch (e->event.base.type) {
883 case DRM_EVENT_VBLANK:
884 case DRM_EVENT_FLIP_COMPLETE:
885 tv = ktime_to_timespec64(now);
886 e->event.vbl.sequence = seq;
887 /*
888 * e->event is a user space structure, with hardcoded unsigned
889 * 32-bit seconds/microseconds. This is safe as we always use
890 * monotonic timestamps since linux-4.15
891 */
892 e->event.vbl.tv_sec = tv.tv_sec;
893 e->event.vbl.tv_usec = tv.tv_nsec / 1000;
894 break;
895 case DRM_EVENT_CRTC_SEQUENCE:
896 if (seq)
897 e->event.seq.sequence = seq;
898 e->event.seq.time_ns = ktime_to_ns(now);
899 break;
900 }
901 trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
902 drm_send_event_locked(dev, &e->base);
903 }
904
905 /**
906 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
907 * @crtc: the source CRTC of the vblank event
908 * @e: the event to send
909 *
910 * A lot of drivers need to generate vblank events for the very next vblank
911 * interrupt. For example when the page flip interrupt happens when the page
912 * flip gets armed, but not when it actually executes within the next vblank
913 * period. This helper function implements exactly the required vblank arming
914 * behaviour.
915 *
916 * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
917 * atomic commit must ensure that the next vblank happens at exactly the same
918 * time as the atomic commit is committed to the hardware. This function itself
919 * does **not** protect against the next vblank interrupt racing with either this
920 * function call or the atomic commit operation. A possible sequence could be:
921 *
922 * 1. Driver commits new hardware state into vblank-synchronized registers.
923 * 2. A vblank happens, committing the hardware state. Also the corresponding
924 * vblank interrupt is fired off and fully processed by the interrupt
925 * handler.
926 * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
927 * 4. The event is only send out for the next vblank, which is wrong.
928 *
929 * An equivalent race can happen when the driver calls
930 * drm_crtc_arm_vblank_event() before writing out the new hardware state.
931 *
932 * The only way to make this work safely is to prevent the vblank from firing
933 * (and the hardware from committing anything else) until the entire atomic
934 * commit sequence has run to completion. If the hardware does not have such a
935 * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
936 * Instead drivers need to manually send out the event from their interrupt
937 * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
938 * possible race with the hardware committing the atomic update.
939 *
940 * Caller must hold a vblank reference for the event @e acquired by a
941 * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
942 */
943 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
944 struct drm_pending_vblank_event *e)
945 {
946 struct drm_device *dev = crtc->dev;
947 unsigned int pipe = drm_crtc_index(crtc);
948
949 assert_spin_locked(&dev->event_lock);
950
951 e->pipe = pipe;
952 e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
953 list_add_tail(&e->base.link, &dev->vblank_event_list);
954 }
955 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
956
957 /**
958 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
959 * @crtc: the source CRTC of the vblank event
960 * @e: the event to send
961 *
962 * Updates sequence # and timestamp on event for the most recently processed
963 * vblank, and sends it to userspace. Caller must hold event lock.
964 *
965 * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
966 * situation, especially to send out events for atomic commit operations.
967 */
968 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
969 struct drm_pending_vblank_event *e)
970 {
971 struct drm_device *dev = crtc->dev;
972 u64 seq;
973 unsigned int pipe = drm_crtc_index(crtc);
974 ktime_t now;
975
976 if (dev->num_crtcs > 0) {
977 seq = drm_vblank_count_and_time(dev, pipe, &now);
978 } else {
979 seq = 0;
980
981 now = ktime_get();
982 }
983 e->pipe = pipe;
984 send_vblank_event(dev, e, seq, now);
985 }
986 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
987
988 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
989 {
990 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
991 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
992
993 if (WARN_ON(!crtc))
994 return 0;
995
996 if (crtc->funcs->enable_vblank)
997 return crtc->funcs->enable_vblank(crtc);
998 }
999
1000 return dev->driver->enable_vblank(dev, pipe);
1001 }
1002
1003 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
1004 {
1005 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1006 int ret = 0;
1007
1008 assert_spin_locked(&dev->vbl_lock);
1009
1010 spin_lock(&dev->vblank_time_lock);
1011
1012 if (!vblank->enabled) {
1013 /*
1014 * Enable vblank irqs under vblank_time_lock protection.
1015 * All vblank count & timestamp updates are held off
1016 * until we are done reinitializing master counter and
1017 * timestamps. Filtercode in drm_handle_vblank() will
1018 * prevent double-accounting of same vblank interval.
1019 */
1020 ret = __enable_vblank(dev, pipe);
1021 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
1022 if (ret) {
1023 atomic_dec(&vblank->refcount);
1024 } else {
1025 drm_update_vblank_count(dev, pipe, 0);
1026 /* drm_update_vblank_count() includes a wmb so we just
1027 * need to ensure that the compiler emits the write
1028 * to mark the vblank as enabled after the call
1029 * to drm_update_vblank_count().
1030 */
1031 WRITE_ONCE(vblank->enabled, true);
1032 }
1033 }
1034
1035 spin_unlock(&dev->vblank_time_lock);
1036
1037 return ret;
1038 }
1039
1040 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
1041 {
1042 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1043 unsigned long irqflags;
1044 int ret = 0;
1045
1046 if (!dev->num_crtcs)
1047 return -EINVAL;
1048
1049 if (WARN_ON(pipe >= dev->num_crtcs))
1050 return -EINVAL;
1051
1052 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1053 /* Going from 0->1 means we have to enable interrupts again */
1054 if (atomic_add_return(1, &vblank->refcount) == 1) {
1055 ret = drm_vblank_enable(dev, pipe);
1056 } else {
1057 if (!vblank->enabled) {
1058 atomic_dec(&vblank->refcount);
1059 ret = -EINVAL;
1060 }
1061 }
1062 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1063
1064 return ret;
1065 }
1066
1067 /**
1068 * drm_crtc_vblank_get - get a reference count on vblank events
1069 * @crtc: which CRTC to own
1070 *
1071 * Acquire a reference count on vblank events to avoid having them disabled
1072 * while in use.
1073 *
1074 * Returns:
1075 * Zero on success or a negative error code on failure.
1076 */
1077 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1078 {
1079 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1080 }
1081 EXPORT_SYMBOL(drm_crtc_vblank_get);
1082
1083 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1084 {
1085 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1086
1087 if (WARN_ON(pipe >= dev->num_crtcs))
1088 return;
1089
1090 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1091 return;
1092
1093 /* Last user schedules interrupt disable */
1094 if (atomic_dec_and_test(&vblank->refcount)) {
1095 if (drm_vblank_offdelay == 0)
1096 return;
1097 else if (drm_vblank_offdelay < 0)
1098 vblank_disable_fn(&vblank->disable_timer);
1099 else if (!dev->vblank_disable_immediate)
1100 mod_timer(&vblank->disable_timer,
1101 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1102 }
1103 }
1104
1105 /**
1106 * drm_crtc_vblank_put - give up ownership of vblank events
1107 * @crtc: which counter to give up
1108 *
1109 * Release ownership of a given vblank counter, turning off interrupts
1110 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1111 */
1112 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1113 {
1114 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1115 }
1116 EXPORT_SYMBOL(drm_crtc_vblank_put);
1117
1118 /**
1119 * drm_wait_one_vblank - wait for one vblank
1120 * @dev: DRM device
1121 * @pipe: CRTC index
1122 *
1123 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1124 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1125 * due to lack of driver support or because the crtc is off.
1126 *
1127 * This is the legacy version of drm_crtc_wait_one_vblank().
1128 */
1129 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1130 {
1131 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1132 int ret;
1133 u64 last;
1134
1135 if (WARN_ON(pipe >= dev->num_crtcs))
1136 return;
1137
1138 ret = drm_vblank_get(dev, pipe);
1139 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1140 return;
1141
1142 #ifdef __NetBSD__
1143 spin_lock(&dev->vbl_lock);
1144 last = drm_vblank_count(dev, pipe);
1145 DRM_SPIN_TIMED_WAIT_UNTIL(ret, &vblank->queue, &dev->vbl_lock,
1146 msecs_to_jiffies(100),
1147 last != drm_vblank_count(dev, pipe));
1148 spin_unlock(&dev->vbl_lock);
1149 #else
1150 last = drm_vblank_count(dev, pipe);
1151
1152 ret = wait_event_timeout(vblank->queue,
1153 last != drm_vblank_count(dev, pipe),
1154 msecs_to_jiffies(100));
1155 #endif
1156
1157 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1158
1159 drm_vblank_put(dev, pipe);
1160 }
1161 EXPORT_SYMBOL(drm_wait_one_vblank);
1162
1163 /**
1164 * drm_crtc_wait_one_vblank - wait for one vblank
1165 * @crtc: DRM crtc
1166 *
1167 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1168 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1169 * due to lack of driver support or because the crtc is off.
1170 */
1171 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1172 {
1173 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1174 }
1175 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1176
1177 /**
1178 * drm_crtc_vblank_off - disable vblank events on a CRTC
1179 * @crtc: CRTC in question
1180 *
1181 * Drivers can use this function to shut down the vblank interrupt handling when
1182 * disabling a crtc. This function ensures that the latest vblank frame count is
1183 * stored so that drm_vblank_on can restore it again.
1184 *
1185 * Drivers must use this function when the hardware vblank counter can get
1186 * reset, e.g. when suspending or disabling the @crtc in general.
1187 */
1188 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1189 {
1190 struct drm_device *dev = crtc->dev;
1191 unsigned int pipe = drm_crtc_index(crtc);
1192 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1193 struct drm_pending_vblank_event *e, *t;
1194
1195 ktime_t now;
1196 unsigned long irqflags;
1197 u64 seq;
1198
1199 if (WARN_ON(pipe >= dev->num_crtcs))
1200 return;
1201
1202 spin_lock_irqsave(&dev->event_lock, irqflags);
1203
1204 spin_lock(&dev->vbl_lock);
1205 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1206 pipe, vblank->enabled, vblank->inmodeset);
1207
1208 /* Avoid redundant vblank disables without previous
1209 * drm_crtc_vblank_on(). */
1210 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1211 drm_vblank_disable_and_save(dev, pipe);
1212
1213 #ifdef __NetBSD__
1214 DRM_SPIN_WAKEUP_ONE(&vblank->queue, &dev->vbl_lock);
1215 #else
1216 wake_up(&vblank->queue);
1217 #endif
1218
1219 /*
1220 * Prevent subsequent drm_vblank_get() from re-enabling
1221 * the vblank interrupt by bumping the refcount.
1222 */
1223 if (!vblank->inmodeset) {
1224 atomic_inc(&vblank->refcount);
1225 vblank->inmodeset = 1;
1226 }
1227 spin_unlock(&dev->vbl_lock);
1228
1229 /* Send any queued vblank events, lest the natives grow disquiet */
1230 seq = drm_vblank_count_and_time(dev, pipe, &now);
1231
1232 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1233 if (e->pipe != pipe)
1234 continue;
1235 DRM_DEBUG("Sending premature vblank event on disable: "
1236 "wanted %"PRIu64", current %"PRIu64"\n",
1237 e->sequence, seq);
1238 list_del(&e->base.link);
1239 drm_vblank_put(dev, pipe);
1240 send_vblank_event(dev, e, seq, now);
1241 }
1242 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1243
1244 /* Will be reset by the modeset helpers when re-enabling the crtc by
1245 * calling drm_calc_timestamping_constants(). */
1246 vblank->hwmode.crtc_clock = 0;
1247 }
1248 EXPORT_SYMBOL(drm_crtc_vblank_off);
1249
1250 /**
1251 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1252 * @crtc: CRTC in question
1253 *
1254 * Drivers can use this function to reset the vblank state to off at load time.
1255 * Drivers should use this together with the drm_crtc_vblank_off() and
1256 * drm_crtc_vblank_on() functions. The difference compared to
1257 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1258 * and hence doesn't need to call any driver hooks.
1259 *
1260 * This is useful for recovering driver state e.g. on driver load, or on resume.
1261 */
1262 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1263 {
1264 struct drm_device *dev = crtc->dev;
1265 unsigned long irqflags;
1266 unsigned int pipe = drm_crtc_index(crtc);
1267 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1268
1269 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1270 /*
1271 * Prevent subsequent drm_vblank_get() from enabling the vblank
1272 * interrupt by bumping the refcount.
1273 */
1274 if (!vblank->inmodeset) {
1275 atomic_inc(&vblank->refcount);
1276 vblank->inmodeset = 1;
1277 }
1278 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1279
1280 WARN_ON(!list_empty(&dev->vblank_event_list));
1281 }
1282 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1283
1284 /**
1285 * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1286 * @crtc: CRTC in question
1287 * @max_vblank_count: max hardware vblank counter value
1288 *
1289 * Update the maximum hardware vblank counter value for @crtc
1290 * at runtime. Useful for hardware where the operation of the
1291 * hardware vblank counter depends on the currently active
1292 * display configuration.
1293 *
1294 * For example, if the hardware vblank counter does not work
1295 * when a specific connector is active the maximum can be set
1296 * to zero. And when that specific connector isn't active the
1297 * maximum can again be set to the appropriate non-zero value.
1298 *
1299 * If used, must be called before drm_vblank_on().
1300 */
1301 void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1302 u32 max_vblank_count)
1303 {
1304 struct drm_device *dev = crtc->dev;
1305 unsigned int pipe = drm_crtc_index(crtc);
1306 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1307
1308 WARN_ON(dev->max_vblank_count);
1309 WARN_ON(!READ_ONCE(vblank->inmodeset));
1310
1311 vblank->max_vblank_count = max_vblank_count;
1312 }
1313 EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1314
1315 /**
1316 * drm_crtc_vblank_on - enable vblank events on a CRTC
1317 * @crtc: CRTC in question
1318 *
1319 * This functions restores the vblank interrupt state captured with
1320 * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1321 * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1322 * unbalanced and so can also be unconditionally called in driver load code to
1323 * reflect the current hardware state of the crtc.
1324 */
1325 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1326 {
1327 struct drm_device *dev = crtc->dev;
1328 unsigned int pipe = drm_crtc_index(crtc);
1329 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1330 unsigned long irqflags;
1331
1332 if (WARN_ON(pipe >= dev->num_crtcs))
1333 return;
1334
1335 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1336 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1337 pipe, vblank->enabled, vblank->inmodeset);
1338
1339 /* Drop our private "prevent drm_vblank_get" refcount */
1340 if (vblank->inmodeset) {
1341 atomic_dec(&vblank->refcount);
1342 vblank->inmodeset = 0;
1343 }
1344
1345 drm_reset_vblank_timestamp(dev, pipe);
1346
1347 /*
1348 * re-enable interrupts if there are users left, or the
1349 * user wishes vblank interrupts to be enabled all the time.
1350 */
1351 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1352 WARN_ON(drm_vblank_enable(dev, pipe));
1353 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1354 }
1355 EXPORT_SYMBOL(drm_crtc_vblank_on);
1356
1357 /**
1358 * drm_vblank_restore - estimate missed vblanks and update vblank count.
1359 * @dev: DRM device
1360 * @pipe: CRTC index
1361 *
1362 * Power manamement features can cause frame counter resets between vblank
1363 * disable and enable. Drivers can use this function in their
1364 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1365 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1366 * vblank counter.
1367 *
1368 * This function is the legacy version of drm_crtc_vblank_restore().
1369 */
1370 void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1371 {
1372 ktime_t t_vblank;
1373 struct drm_vblank_crtc *vblank;
1374 int framedur_ns;
1375 u64 diff_ns;
1376 u32 cur_vblank, diff = 1;
1377 int count = DRM_TIMESTAMP_MAXRETRIES;
1378
1379 if (WARN_ON(pipe >= dev->num_crtcs))
1380 return;
1381
1382 assert_spin_locked(&dev->vbl_lock);
1383 assert_spin_locked(&dev->vblank_time_lock);
1384
1385 vblank = &dev->vblank[pipe];
1386 WARN_ONCE(drm_debug_enabled(DRM_UT_VBL) && !vblank->framedur_ns,
1387 "Cannot compute missed vblanks without frame duration\n");
1388 framedur_ns = vblank->framedur_ns;
1389
1390 do {
1391 cur_vblank = __get_vblank_counter(dev, pipe);
1392 drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1393 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1394
1395 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1396 if (framedur_ns)
1397 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1398
1399
1400 DRM_DEBUG_VBL("missed %d vblanks in %"PRId64" ns, frame duration=%d ns, hw_diff=%d\n",
1401 diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
1402 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
1403 }
1404 EXPORT_SYMBOL(drm_vblank_restore);
1405
1406 /**
1407 * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1408 * @crtc: CRTC in question
1409 *
1410 * Power manamement features can cause frame counter resets between vblank
1411 * disable and enable. Drivers can use this function in their
1412 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1413 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1414 * vblank counter.
1415 */
1416 void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1417 {
1418 drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1419 }
1420 EXPORT_SYMBOL(drm_crtc_vblank_restore);
1421
1422 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1423 unsigned int pipe)
1424 {
1425 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1426
1427 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1428 if (!dev->num_crtcs)
1429 return;
1430
1431 if (WARN_ON(pipe >= dev->num_crtcs))
1432 return;
1433
1434 /*
1435 * To avoid all the problems that might happen if interrupts
1436 * were enabled/disabled around or between these calls, we just
1437 * have the kernel take a reference on the CRTC (just once though
1438 * to avoid corrupting the count if multiple, mismatch calls occur),
1439 * so that interrupts remain enabled in the interim.
1440 */
1441 if (!vblank->inmodeset) {
1442 vblank->inmodeset = 0x1;
1443 if (drm_vblank_get(dev, pipe) == 0)
1444 vblank->inmodeset |= 0x2;
1445 }
1446 }
1447
1448 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1449 unsigned int pipe)
1450 {
1451 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1452 unsigned long irqflags;
1453
1454 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1455 if (!dev->num_crtcs)
1456 return;
1457
1458 if (WARN_ON(pipe >= dev->num_crtcs))
1459 return;
1460
1461 if (vblank->inmodeset) {
1462 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1463 drm_reset_vblank_timestamp(dev, pipe);
1464 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1465
1466 if (vblank->inmodeset & 0x2)
1467 drm_vblank_put(dev, pipe);
1468
1469 vblank->inmodeset = 0;
1470 }
1471 }
1472
1473 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1474 struct drm_file *file_priv)
1475 {
1476 struct drm_modeset_ctl *modeset = data;
1477 unsigned int pipe;
1478
1479 /* If drm_vblank_init() hasn't been called yet, just no-op */
1480 if (!dev->num_crtcs)
1481 return 0;
1482
1483 /* KMS drivers handle this internally */
1484 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1485 return 0;
1486
1487 pipe = modeset->crtc;
1488 if (pipe >= dev->num_crtcs)
1489 return -EINVAL;
1490
1491 switch (modeset->cmd) {
1492 case _DRM_PRE_MODESET:
1493 drm_legacy_vblank_pre_modeset(dev, pipe);
1494 break;
1495 case _DRM_POST_MODESET:
1496 drm_legacy_vblank_post_modeset(dev, pipe);
1497 break;
1498 default:
1499 return -EINVAL;
1500 }
1501
1502 return 0;
1503 }
1504
1505 static inline bool vblank_passed(u64 seq, u64 ref)
1506 {
1507 return (seq - ref) <= (1 << 23);
1508 }
1509
1510 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1511 u64 req_seq,
1512 union drm_wait_vblank *vblwait,
1513 struct drm_file *file_priv)
1514 {
1515 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1516 struct drm_pending_vblank_event *e;
1517 ktime_t now;
1518 unsigned long flags;
1519 u64 seq;
1520 int ret;
1521
1522 e = kzalloc(sizeof(*e), GFP_KERNEL);
1523 if (e == NULL) {
1524 ret = -ENOMEM;
1525 goto err_put;
1526 }
1527
1528 e->pipe = pipe;
1529 e->event.base.type = DRM_EVENT_VBLANK;
1530 e->event.base.length = sizeof(e->event.vbl);
1531 e->event.vbl.user_data = vblwait->request.signal;
1532 e->event.vbl.crtc_id = 0;
1533 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1534 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1535 if (crtc)
1536 e->event.vbl.crtc_id = crtc->base.id;
1537 }
1538
1539 spin_lock_irqsave(&dev->event_lock, flags);
1540
1541 /*
1542 * drm_crtc_vblank_off() might have been called after we called
1543 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1544 * vblank disable, so no need for further locking. The reference from
1545 * drm_vblank_get() protects against vblank disable from another source.
1546 */
1547 if (!READ_ONCE(vblank->enabled)) {
1548 ret = -EINVAL;
1549 goto err_unlock;
1550 }
1551
1552 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1553 &e->event.base);
1554
1555 if (ret)
1556 goto err_unlock;
1557
1558 seq = drm_vblank_count_and_time(dev, pipe, &now);
1559
1560 DRM_DEBUG("event on vblank count %"PRIu64", current %"PRIu64", crtc %u\n",
1561 req_seq, seq, pipe);
1562
1563 trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1564
1565 e->sequence = req_seq;
1566 if (vblank_passed(seq, req_seq)) {
1567 drm_vblank_put(dev, pipe);
1568 send_vblank_event(dev, e, seq, now);
1569 vblwait->reply.sequence = seq;
1570 } else {
1571 /* drm_handle_vblank_events will call drm_vblank_put */
1572 list_add_tail(&e->base.link, &dev->vblank_event_list);
1573 vblwait->reply.sequence = req_seq;
1574 }
1575
1576 spin_unlock_irqrestore(&dev->event_lock, flags);
1577
1578 return 0;
1579
1580 err_unlock:
1581 spin_unlock_irqrestore(&dev->event_lock, flags);
1582 kfree(e);
1583 err_put:
1584 drm_vblank_put(dev, pipe);
1585 return ret;
1586 }
1587
1588 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1589 {
1590 if (vblwait->request.sequence)
1591 return false;
1592
1593 return _DRM_VBLANK_RELATIVE ==
1594 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1595 _DRM_VBLANK_EVENT |
1596 _DRM_VBLANK_NEXTONMISS));
1597 }
1598
1599 /*
1600 * Widen a 32-bit param to 64-bits.
1601 *
1602 * \param narrow 32-bit value (missing upper 32 bits)
1603 * \param near 64-bit value that should be 'close' to near
1604 *
1605 * This function returns a 64-bit value using the lower 32-bits from
1606 * 'narrow' and constructing the upper 32-bits so that the result is
1607 * as close as possible to 'near'.
1608 */
1609
1610 static u64 widen_32_to_64(u32 narrow, u64 near)
1611 {
1612 return near + (s32) (narrow - near);
1613 }
1614
1615 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1616 struct drm_wait_vblank_reply *reply)
1617 {
1618 ktime_t now;
1619 struct timespec64 ts;
1620
1621 /*
1622 * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1623 * to store the seconds. This is safe as we always use monotonic
1624 * timestamps since linux-4.15.
1625 */
1626 reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1627 ts = ktime_to_timespec64(now);
1628 reply->tval_sec = (u32)ts.tv_sec;
1629 reply->tval_usec = ts.tv_nsec / 1000;
1630 }
1631
1632 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1633 struct drm_file *file_priv)
1634 {
1635 struct drm_crtc *crtc;
1636 struct drm_vblank_crtc *vblank;
1637 union drm_wait_vblank *vblwait = data;
1638 int ret;
1639 u64 req_seq, seq;
1640 unsigned int pipe_index;
1641 unsigned int flags, pipe, high_pipe;
1642
1643 if (!dev->irq_enabled)
1644 return -EOPNOTSUPP;
1645
1646 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1647 return -EINVAL;
1648
1649 if (vblwait->request.type &
1650 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1651 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1652 DRM_DEBUG("Unsupported type value 0x%x, supported mask 0x%x\n",
1653 vblwait->request.type,
1654 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1655 _DRM_VBLANK_HIGH_CRTC_MASK));
1656 return -EINVAL;
1657 }
1658
1659 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1660 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1661 if (high_pipe)
1662 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1663 else
1664 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1665
1666 /* Convert lease-relative crtc index into global crtc index */
1667 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1668 pipe = 0;
1669 drm_for_each_crtc(crtc, dev) {
1670 if (drm_lease_held(file_priv, crtc->base.id)) {
1671 if (pipe_index == 0)
1672 break;
1673 pipe_index--;
1674 }
1675 pipe++;
1676 }
1677 } else {
1678 pipe = pipe_index;
1679 }
1680
1681 if (pipe >= dev->num_crtcs)
1682 return -EINVAL;
1683
1684 vblank = &dev->vblank[pipe];
1685
1686 /* If the counter is currently enabled and accurate, short-circuit
1687 * queries to return the cached timestamp of the last vblank.
1688 */
1689 if (dev->vblank_disable_immediate &&
1690 drm_wait_vblank_is_query(vblwait) &&
1691 READ_ONCE(vblank->enabled)) {
1692 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1693 return 0;
1694 }
1695
1696 ret = drm_vblank_get(dev, pipe);
1697 if (ret) {
1698 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1699 return ret;
1700 }
1701 seq = drm_vblank_count(dev, pipe);
1702
1703 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1704 case _DRM_VBLANK_RELATIVE:
1705 req_seq = seq + vblwait->request.sequence;
1706 vblwait->request.sequence = req_seq;
1707 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1708 break;
1709 case _DRM_VBLANK_ABSOLUTE:
1710 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1711 break;
1712 default:
1713 ret = -EINVAL;
1714 goto done;
1715 }
1716
1717 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1718 vblank_passed(seq, req_seq)) {
1719 req_seq = seq + 1;
1720 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1721 vblwait->request.sequence = req_seq;
1722 }
1723
1724 if (flags & _DRM_VBLANK_EVENT) {
1725 /* must hold on to the vblank ref until the event fires
1726 * drm_vblank_put will be called asynchronously
1727 */
1728 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1729 }
1730
1731 if (req_seq != seq) {
1732 int wait;
1733
1734 DRM_DEBUG("waiting on vblank count %"PRIu64", crtc %u\n",
1735 req_seq, pipe);
1736 #ifdef __NetBSD__
1737 DRM_SPIN_TIMED_WAIT_UNTIL(wait, &vblank->queue,
1738 &dev->vbl_lock, msecs_to_jiffies(3000),
1739 vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
1740 !READ_ONCE(vblank->enabled));
1741 #else
1742 wait = wait_event_interruptible_timeout(vblank->queue,
1743 vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
1744 !READ_ONCE(vblank->enabled),
1745 msecs_to_jiffies(3000));
1746 #endif
1747
1748 switch (wait) {
1749 case 0:
1750 /* timeout */
1751 ret = -EBUSY;
1752 break;
1753 case -ERESTARTSYS:
1754 /* interrupted by signal */
1755 ret = -EINTR;
1756 break;
1757 default:
1758 ret = 0;
1759 break;
1760 }
1761 }
1762
1763 if (ret != -EINTR) {
1764 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1765
1766 DRM_DEBUG("crtc %d returning %u to client\n",
1767 pipe, vblwait->reply.sequence);
1768 } else {
1769 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1770 }
1771
1772 done:
1773 drm_vblank_put(dev, pipe);
1774 return ret;
1775 }
1776
1777 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1778 {
1779 struct drm_pending_vblank_event *e, *t;
1780 ktime_t now;
1781 u64 seq;
1782
1783 assert_spin_locked(&dev->event_lock);
1784
1785 seq = drm_vblank_count_and_time(dev, pipe, &now);
1786
1787 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1788 if (e->pipe != pipe)
1789 continue;
1790 if (!vblank_passed(seq, e->sequence))
1791 continue;
1792
1793 DRM_DEBUG("vblank event on %"PRIu64", current %"PRIu64"\n",
1794 e->sequence, seq);
1795
1796 list_del(&e->base.link);
1797 drm_vblank_put(dev, pipe);
1798 send_vblank_event(dev, e, seq, now);
1799 }
1800
1801 trace_drm_vblank_event(pipe, seq, now,
1802 dev->driver->get_vblank_timestamp != NULL);
1803 }
1804
1805 /**
1806 * drm_handle_vblank - handle a vblank event
1807 * @dev: DRM device
1808 * @pipe: index of CRTC where this event occurred
1809 *
1810 * Drivers should call this routine in their vblank interrupt handlers to
1811 * update the vblank counter and send any signals that may be pending.
1812 *
1813 * This is the legacy version of drm_crtc_handle_vblank().
1814 */
1815 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1816 {
1817 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1818 unsigned long irqflags;
1819 bool disable_irq;
1820
1821 if (WARN_ON_ONCE(!dev->num_crtcs))
1822 return false;
1823
1824 if (WARN_ON(pipe >= dev->num_crtcs))
1825 return false;
1826
1827 spin_lock_irqsave(&dev->event_lock, irqflags);
1828
1829 /* Need timestamp lock to prevent concurrent execution with
1830 * vblank enable/disable, as this would cause inconsistent
1831 * or corrupted timestamps and vblank counts.
1832 */
1833 spin_lock(&dev->vblank_time_lock);
1834
1835 /* Vblank irq handling disabled. Nothing to do. */
1836 if (!vblank->enabled) {
1837 spin_unlock(&dev->vblank_time_lock);
1838 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1839 return false;
1840 }
1841
1842 drm_update_vblank_count(dev, pipe, true);
1843
1844 spin_unlock(&dev->vblank_time_lock);
1845
1846 #ifdef __NetBSD__
1847 DRM_SPIN_WAKEUP_ONE(&vblank->queue, &dev->vbl_lock);
1848 #else
1849 wake_up(&vblank->queue);
1850 #endif
1851
1852 /* With instant-off, we defer disabling the interrupt until after
1853 * we finish processing the following vblank after all events have
1854 * been signaled. The disable has to be last (after
1855 * drm_handle_vblank_events) so that the timestamp is always accurate.
1856 */
1857 disable_irq = (dev->vblank_disable_immediate &&
1858 drm_vblank_offdelay > 0 &&
1859 !atomic_read(&vblank->refcount));
1860
1861 drm_handle_vblank_events(dev, pipe);
1862
1863 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1864
1865 if (disable_irq)
1866 vblank_disable_fn(&vblank->disable_timer);
1867
1868 return true;
1869 }
1870 EXPORT_SYMBOL(drm_handle_vblank);
1871
1872 /**
1873 * drm_crtc_handle_vblank - handle a vblank event
1874 * @crtc: where this event occurred
1875 *
1876 * Drivers should call this routine in their vblank interrupt handlers to
1877 * update the vblank counter and send any signals that may be pending.
1878 *
1879 * This is the native KMS version of drm_handle_vblank().
1880 *
1881 * Note that for a given vblank counter value drm_crtc_handle_vblank()
1882 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
1883 * provide a barrier: Any writes done before calling
1884 * drm_crtc_handle_vblank() will be visible to callers of the later
1885 * functions, iff the vblank count is the same or a later one.
1886 *
1887 * See also &drm_vblank_crtc.count.
1888 *
1889 * Returns:
1890 * True if the event was successfully handled, false on failure.
1891 */
1892 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1893 {
1894 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1895 }
1896 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1897
1898 /*
1899 * Get crtc VBLANK count.
1900 *
1901 * \param dev DRM device
1902 * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1903 * \param file_priv drm file private for the user's open file descriptor
1904 */
1905
1906 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1907 struct drm_file *file_priv)
1908 {
1909 struct drm_crtc *crtc;
1910 struct drm_vblank_crtc *vblank;
1911 int pipe;
1912 struct drm_crtc_get_sequence *get_seq = data;
1913 ktime_t now;
1914 bool vblank_enabled;
1915 int ret;
1916
1917 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1918 return -EOPNOTSUPP;
1919
1920 if (!dev->irq_enabled)
1921 return -EOPNOTSUPP;
1922
1923 crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
1924 if (!crtc)
1925 return -ENOENT;
1926
1927 pipe = drm_crtc_index(crtc);
1928
1929 vblank = &dev->vblank[pipe];
1930 vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
1931
1932 if (!vblank_enabled) {
1933 ret = drm_crtc_vblank_get(crtc);
1934 if (ret) {
1935 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1936 return ret;
1937 }
1938 }
1939 drm_modeset_lock(&crtc->mutex, NULL);
1940 if (crtc->state)
1941 get_seq->active = crtc->state->enable;
1942 else
1943 get_seq->active = crtc->enabled;
1944 drm_modeset_unlock(&crtc->mutex);
1945 get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1946 get_seq->sequence_ns = ktime_to_ns(now);
1947 if (!vblank_enabled)
1948 drm_crtc_vblank_put(crtc);
1949 return 0;
1950 }
1951
1952 /*
1953 * Queue a event for VBLANK sequence
1954 *
1955 * \param dev DRM device
1956 * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
1957 * \param file_priv drm file private for the user's open file descriptor
1958 */
1959
1960 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
1961 struct drm_file *file_priv)
1962 {
1963 struct drm_crtc *crtc;
1964 struct drm_vblank_crtc *vblank;
1965 int pipe;
1966 struct drm_crtc_queue_sequence *queue_seq = data;
1967 ktime_t now;
1968 struct drm_pending_vblank_event *e;
1969 u32 flags;
1970 u64 seq;
1971 u64 req_seq;
1972 int ret;
1973 unsigned long spin_flags;
1974
1975 if (!drm_core_check_feature(dev, DRIVER_MODESET))
1976 return -EOPNOTSUPP;
1977
1978 if (!dev->irq_enabled)
1979 return -EOPNOTSUPP;
1980
1981 crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
1982 if (!crtc)
1983 return -ENOENT;
1984
1985 flags = queue_seq->flags;
1986 /* Check valid flag bits */
1987 if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
1988 DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
1989 return -EINVAL;
1990
1991 pipe = drm_crtc_index(crtc);
1992
1993 vblank = &dev->vblank[pipe];
1994
1995 e = kzalloc(sizeof(*e), GFP_KERNEL);
1996 if (e == NULL)
1997 return -ENOMEM;
1998
1999 ret = drm_crtc_vblank_get(crtc);
2000 if (ret) {
2001 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
2002 goto err_free;
2003 }
2004
2005 seq = drm_vblank_count_and_time(dev, pipe, &now);
2006 req_seq = queue_seq->sequence;
2007
2008 if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
2009 req_seq += seq;
2010
2011 if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
2012 req_seq = seq + 1;
2013
2014 e->pipe = pipe;
2015 e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
2016 e->event.base.length = sizeof(e->event.seq);
2017 e->event.seq.user_data = queue_seq->user_data;
2018
2019 spin_lock_irqsave(&dev->event_lock, spin_flags);
2020
2021 /*
2022 * drm_crtc_vblank_off() might have been called after we called
2023 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
2024 * vblank disable, so no need for further locking. The reference from
2025 * drm_crtc_vblank_get() protects against vblank disable from another source.
2026 */
2027 if (!READ_ONCE(vblank->enabled)) {
2028 ret = -EINVAL;
2029 goto err_unlock;
2030 }
2031
2032 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
2033 &e->event.base);
2034
2035 if (ret)
2036 goto err_unlock;
2037
2038 e->sequence = req_seq;
2039
2040 if (vblank_passed(seq, req_seq)) {
2041 drm_crtc_vblank_put(crtc);
2042 send_vblank_event(dev, e, seq, now);
2043 queue_seq->sequence = seq;
2044 } else {
2045 /* drm_handle_vblank_events will call drm_vblank_put */
2046 list_add_tail(&e->base.link, &dev->vblank_event_list);
2047 queue_seq->sequence = req_seq;
2048 }
2049
2050 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2051 return 0;
2052
2053 err_unlock:
2054 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2055 drm_crtc_vblank_put(crtc);
2056 err_free:
2057 kfree(e);
2058 return ret;
2059 }
2060