blob: 630dc26379b70cc1fde1db602fe29ce18bc24fdc [file] [log] [blame]
Daniel Vetter3ed43512017-05-31 11:21:46 +02001/*
2 * drm_irq.c IRQ and vblank support
3 *
4 * \author Rickard E. (Rik) Faith <faith@valinux.com>
5 * \author Gareth Hughes <gareth@valinux.com>
6 *
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:
13 *
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
16 * Software.
17 *
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.
25 */
26
27#include <drm/drm_vblank.h>
28#include <drm/drmP.h>
29#include <linux/export.h>
30
31#include "drm_trace.h"
32#include "drm_internal.h"
33
34/* Retry timestamp calculation up to 3 times to satisfy
35 * drm_timestamp_precision before giving up.
36 */
37#define DRM_TIMESTAMP_MAXRETRIES 3
38
39/* Threshold in nanoseconds for detection of redundant
40 * vblank irq in drm_handle_vblank(). 1 msec should be ok.
41 */
42#define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
43
44static bool
45drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
46 struct timeval *tvblank, bool in_vblank_irq);
47
48static unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
49
50/*
51 * Default to use monotonic timestamps for wait-for-vblank and page-flip
52 * complete events.
53 */
54unsigned int drm_timestamp_monotonic = 1;
55
56static int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
57
58module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
59module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
60module_param_named(timestamp_monotonic, drm_timestamp_monotonic, int, 0600);
61MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
62MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
63MODULE_PARM_DESC(timestamp_monotonic, "Use monotonic timestamps");
64
65static void store_vblank(struct drm_device *dev, unsigned int pipe,
66 u32 vblank_count_inc,
67 struct timeval *t_vblank, u32 last)
68{
69 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
70
71 assert_spin_locked(&dev->vblank_time_lock);
72
73 vblank->last = last;
74
75 write_seqlock(&vblank->seqlock);
76 vblank->time = *t_vblank;
77 vblank->count += vblank_count_inc;
78 write_sequnlock(&vblank->seqlock);
79}
80
81/*
82 * "No hw counter" fallback implementation of .get_vblank_counter() hook,
83 * if there is no useable hardware frame counter available.
84 */
85static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
86{
87 WARN_ON_ONCE(dev->max_vblank_count != 0);
88 return 0;
89}
90
91static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
92{
93 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
94 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
95
96 if (crtc->funcs->get_vblank_counter)
97 return crtc->funcs->get_vblank_counter(crtc);
98 }
99
100 if (dev->driver->get_vblank_counter)
101 return dev->driver->get_vblank_counter(dev, pipe);
102
103 return drm_vblank_no_hw_counter(dev, pipe);
104}
105
106/*
107 * Reset the stored timestamp for the current vblank count to correspond
108 * to the last vblank occurred.
109 *
110 * Only to be called from drm_crtc_vblank_on().
111 *
112 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
113 * device vblank fields.
114 */
115static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
116{
117 u32 cur_vblank;
118 bool rc;
119 struct timeval t_vblank;
120 int count = DRM_TIMESTAMP_MAXRETRIES;
121
122 spin_lock(&dev->vblank_time_lock);
123
124 /*
125 * sample the current counter to avoid random jumps
126 * when drm_vblank_enable() applies the diff
127 */
128 do {
129 cur_vblank = __get_vblank_counter(dev, pipe);
130 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
131 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
132
133 /*
134 * Only reinitialize corresponding vblank timestamp if high-precision query
135 * available and didn't fail. Otherwise reinitialize delayed at next vblank
136 * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
137 */
138 if (!rc)
139 t_vblank = (struct timeval) {0, 0};
140
141 /*
142 * +1 to make sure user will never see the same
143 * vblank counter value before and after a modeset
144 */
145 store_vblank(dev, pipe, 1, &t_vblank, cur_vblank);
146
147 spin_unlock(&dev->vblank_time_lock);
148}
149
150/*
151 * Call back into the driver to update the appropriate vblank counter
152 * (specified by @pipe). Deal with wraparound, if it occurred, and
153 * update the last read value so we can deal with wraparound on the next
154 * call if necessary.
155 *
156 * Only necessary when going from off->on, to account for frames we
157 * didn't get an interrupt for.
158 *
159 * Note: caller must hold &drm_device.vbl_lock since this reads & writes
160 * device vblank fields.
161 */
162static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
163 bool in_vblank_irq)
164{
165 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
166 u32 cur_vblank, diff;
167 bool rc;
168 struct timeval t_vblank;
169 int count = DRM_TIMESTAMP_MAXRETRIES;
170 int framedur_ns = vblank->framedur_ns;
171
172 /*
173 * Interrupts were disabled prior to this call, so deal with counter
174 * wrap if needed.
175 * NOTE! It's possible we lost a full dev->max_vblank_count + 1 events
176 * here if the register is small or we had vblank interrupts off for
177 * a long time.
178 *
179 * We repeat the hardware vblank counter & timestamp query until
180 * we get consistent results. This to prevent races between gpu
181 * updating its hardware counter while we are retrieving the
182 * corresponding vblank timestamp.
183 */
184 do {
185 cur_vblank = __get_vblank_counter(dev, pipe);
186 rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, in_vblank_irq);
187 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
188
189 if (dev->max_vblank_count != 0) {
190 /* trust the hw counter when it's around */
191 diff = (cur_vblank - vblank->last) & dev->max_vblank_count;
192 } else if (rc && framedur_ns) {
193 const struct timeval *t_old;
194 u64 diff_ns;
195
196 t_old = &vblank->time;
197 diff_ns = timeval_to_ns(&t_vblank) - timeval_to_ns(t_old);
198
199 /*
200 * Figure out how many vblanks we've missed based
201 * on the difference in the timestamps and the
202 * frame/field duration.
203 */
204 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
205
206 if (diff == 0 && in_vblank_irq)
207 DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored."
208 " diff_ns = %lld, framedur_ns = %d)\n",
209 pipe, (long long) diff_ns, framedur_ns);
210 } else {
211 /* some kind of default for drivers w/o accurate vbl timestamping */
212 diff = in_vblank_irq ? 1 : 0;
213 }
214
215 /*
216 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
217 * interval? If so then vblank irqs keep running and it will likely
218 * happen that the hardware vblank counter is not trustworthy as it
219 * might reset at some point in that interval and vblank timestamps
220 * are not trustworthy either in that interval. Iow. this can result
221 * in a bogus diff >> 1 which must be avoided as it would cause
222 * random large forward jumps of the software vblank counter.
223 */
224 if (diff > 1 && (vblank->inmodeset & 0x2)) {
225 DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
226 " due to pre-modeset.\n", pipe, diff);
227 diff = 1;
228 }
229
230 DRM_DEBUG_VBL("updating vblank count on crtc %u:"
231 " current=%u, diff=%u, hw=%u hw_last=%u\n",
232 pipe, vblank->count, diff, cur_vblank, vblank->last);
233
234 if (diff == 0) {
235 WARN_ON_ONCE(cur_vblank != vblank->last);
236 return;
237 }
238
239 /*
240 * Only reinitialize corresponding vblank timestamp if high-precision query
241 * available and didn't fail, or we were called from the vblank interrupt.
242 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
243 * for now, to mark the vblanktimestamp as invalid.
244 */
245 if (!rc && in_vblank_irq)
246 t_vblank = (struct timeval) {0, 0};
247
248 store_vblank(dev, pipe, diff, &t_vblank, cur_vblank);
249}
250
251static u32 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
252{
253 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
254
255 if (WARN_ON(pipe >= dev->num_crtcs))
256 return 0;
257
258 return vblank->count;
259}
260
261/**
262 * drm_accurate_vblank_count - retrieve the master vblank counter
263 * @crtc: which counter to retrieve
264 *
265 * This function is similar to @drm_crtc_vblank_count but this
266 * function interpolates to handle a race with vblank irq's.
267 *
268 * This is mostly useful for hardware that can obtain the scanout
269 * position, but doesn't have a frame counter.
270 */
271u32 drm_accurate_vblank_count(struct drm_crtc *crtc)
272{
273 struct drm_device *dev = crtc->dev;
274 unsigned int pipe = drm_crtc_index(crtc);
275 u32 vblank;
276 unsigned long flags;
277
278 WARN(!dev->driver->get_vblank_timestamp,
279 "This function requires support for accurate vblank timestamps.");
280
281 spin_lock_irqsave(&dev->vblank_time_lock, flags);
282
283 drm_update_vblank_count(dev, pipe, false);
284 vblank = drm_vblank_count(dev, pipe);
285
286 spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
287
288 return vblank;
289}
290EXPORT_SYMBOL(drm_accurate_vblank_count);
291
292static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
293{
294 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
295 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
296
297 if (crtc->funcs->disable_vblank) {
298 crtc->funcs->disable_vblank(crtc);
299 return;
300 }
301 }
302
303 dev->driver->disable_vblank(dev, pipe);
304}
305
306/*
307 * Disable vblank irq's on crtc, make sure that last vblank count
308 * of hardware and corresponding consistent software vblank counter
309 * are preserved, even if there are any spurious vblank irq's after
310 * disable.
311 */
312void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
313{
314 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
315 unsigned long irqflags;
316
317 assert_spin_locked(&dev->vbl_lock);
318
319 /* Prevent vblank irq processing while disabling vblank irqs,
320 * so no updates of timestamps or count can happen after we've
321 * disabled. Needed to prevent races in case of delayed irq's.
322 */
323 spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
324
325 /*
326 * Only disable vblank interrupts if they're enabled. This avoids
327 * calling the ->disable_vblank() operation in atomic context with the
328 * hardware potentially runtime suspended.
329 */
330 if (vblank->enabled) {
331 __disable_vblank(dev, pipe);
332 vblank->enabled = false;
333 }
334
335 /*
336 * Always update the count and timestamp to maintain the
337 * appearance that the counter has been ticking all along until
338 * this time. This makes the count account for the entire time
339 * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
340 */
341 drm_update_vblank_count(dev, pipe, false);
342
343 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
344}
345
346static void vblank_disable_fn(unsigned long arg)
347{
348 struct drm_vblank_crtc *vblank = (void *)arg;
349 struct drm_device *dev = vblank->dev;
350 unsigned int pipe = vblank->pipe;
351 unsigned long irqflags;
352
353 spin_lock_irqsave(&dev->vbl_lock, irqflags);
354 if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
355 DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
356 drm_vblank_disable_and_save(dev, pipe);
357 }
358 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
359}
360
361/**
362 * drm_vblank_cleanup - cleanup vblank support
363 * @dev: DRM device
364 *
365 * This function cleans up any resources allocated in drm_vblank_init.
366 */
367void drm_vblank_cleanup(struct drm_device *dev)
368{
369 unsigned int pipe;
370
371 /* Bail if the driver didn't call drm_vblank_init() */
372 if (dev->num_crtcs == 0)
373 return;
374
375 for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
376 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
377
378 WARN_ON(READ_ONCE(vblank->enabled) &&
379 drm_core_check_feature(dev, DRIVER_MODESET));
380
381 del_timer_sync(&vblank->disable_timer);
382 }
383
384 kfree(dev->vblank);
385
386 dev->num_crtcs = 0;
387}
388EXPORT_SYMBOL(drm_vblank_cleanup);
389
390/**
391 * drm_vblank_init - initialize vblank support
392 * @dev: DRM device
393 * @num_crtcs: number of CRTCs supported by @dev
394 *
395 * This function initializes vblank support for @num_crtcs display pipelines.
396 *
397 * Returns:
398 * Zero on success or a negative error code on failure.
399 */
400int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
401{
402 int ret = -ENOMEM;
403 unsigned int i;
404
405 spin_lock_init(&dev->vbl_lock);
406 spin_lock_init(&dev->vblank_time_lock);
407
408 dev->num_crtcs = num_crtcs;
409
410 dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
411 if (!dev->vblank)
412 goto err;
413
414 for (i = 0; i < num_crtcs; i++) {
415 struct drm_vblank_crtc *vblank = &dev->vblank[i];
416
417 vblank->dev = dev;
418 vblank->pipe = i;
419 init_waitqueue_head(&vblank->queue);
420 setup_timer(&vblank->disable_timer, vblank_disable_fn,
421 (unsigned long)vblank);
422 seqlock_init(&vblank->seqlock);
423 }
424
425 DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
426
427 /* Driver specific high-precision vblank timestamping supported? */
428 if (dev->driver->get_vblank_timestamp)
429 DRM_INFO("Driver supports precise vblank timestamp query.\n");
430 else
431 DRM_INFO("No driver support for vblank timestamp query.\n");
432
433 /* Must have precise timestamping for reliable vblank instant disable */
434 if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
435 dev->vblank_disable_immediate = false;
436 DRM_INFO("Setting vblank_disable_immediate to false because "
437 "get_vblank_timestamp == NULL\n");
438 }
439
440 return 0;
441
442err:
443 dev->num_crtcs = 0;
444 return ret;
445}
446EXPORT_SYMBOL(drm_vblank_init);
447
448/**
449 * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
450 * @crtc: which CRTC's vblank waitqueue to retrieve
451 *
452 * This function returns a pointer to the vblank waitqueue for the CRTC.
453 * Drivers can use this to implement vblank waits using wait_event() and related
454 * functions.
455 */
456wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
457{
458 return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
459}
460EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
461
462
463/**
464 * drm_calc_timestamping_constants - calculate vblank timestamp constants
465 * @crtc: drm_crtc whose timestamp constants should be updated.
466 * @mode: display mode containing the scanout timings
467 *
468 * Calculate and store various constants which are later
469 * needed by vblank and swap-completion timestamping, e.g,
470 * by drm_calc_vbltimestamp_from_scanoutpos(). They are
471 * derived from CRTC's true scanout timing, so they take
472 * things like panel scaling or other adjustments into account.
473 */
474void drm_calc_timestamping_constants(struct drm_crtc *crtc,
475 const struct drm_display_mode *mode)
476{
477 struct drm_device *dev = crtc->dev;
478 unsigned int pipe = drm_crtc_index(crtc);
479 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
480 int linedur_ns = 0, framedur_ns = 0;
481 int dotclock = mode->crtc_clock;
482
483 if (!dev->num_crtcs)
484 return;
485
486 if (WARN_ON(pipe >= dev->num_crtcs))
487 return;
488
489 /* Valid dotclock? */
490 if (dotclock > 0) {
491 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
492
493 /*
494 * Convert scanline length in pixels and video
495 * dot clock to line duration and frame duration
496 * in nanoseconds:
497 */
498 linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
499 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
500
501 /*
502 * Fields of interlaced scanout modes are only half a frame duration.
503 */
504 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
505 framedur_ns /= 2;
506 } else
507 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
508 crtc->base.id);
509
510 vblank->linedur_ns = linedur_ns;
511 vblank->framedur_ns = framedur_ns;
512 vblank->hwmode = *mode;
513
514 DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
515 crtc->base.id, mode->crtc_htotal,
516 mode->crtc_vtotal, mode->crtc_vdisplay);
517 DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
518 crtc->base.id, dotclock, framedur_ns, linedur_ns);
519}
520EXPORT_SYMBOL(drm_calc_timestamping_constants);
521
522/**
523 * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
524 * @dev: DRM device
525 * @pipe: index of CRTC whose vblank timestamp to retrieve
526 * @max_error: Desired maximum allowable error in timestamps (nanosecs)
527 * On return contains true maximum error of timestamp
528 * @vblank_time: Pointer to struct timeval which should receive the timestamp
529 * @in_vblank_irq:
530 * True when called from drm_crtc_handle_vblank(). Some drivers
531 * need to apply some workarounds for gpu-specific vblank irq quirks
532 * if flag is set.
533 *
534 * Implements calculation of exact vblank timestamps from given drm_display_mode
535 * timings and current video scanout position of a CRTC. This can be called from
536 * within get_vblank_timestamp() implementation of a kms driver to implement the
537 * actual timestamping.
538 *
539 * Should return timestamps conforming to the OML_sync_control OpenML
540 * extension specification. The timestamp corresponds to the end of
541 * the vblank interval, aka start of scanout of topmost-leftmost display
542 * pixel in the following video frame.
543 *
544 * Requires support for optional dev->driver->get_scanout_position()
545 * in kms driver, plus a bit of setup code to provide a drm_display_mode
546 * that corresponds to the true scanout timing.
547 *
548 * The current implementation only handles standard video modes. It
549 * returns as no operation if a doublescan or interlaced video mode is
550 * active. Higher level code is expected to handle this.
551 *
552 * This function can be used to implement the &drm_driver.get_vblank_timestamp
553 * directly, if the driver implements the &drm_driver.get_scanout_position hook.
554 *
555 * Note that atomic drivers must call drm_calc_timestamping_constants() before
556 * enabling a CRTC. The atomic helpers already take care of that in
557 * drm_atomic_helper_update_legacy_modeset_state().
558 *
559 * Returns:
560 *
561 * Returns true on success, and false on failure, i.e. when no accurate
562 * timestamp could be acquired.
563 */
564bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
565 unsigned int pipe,
566 int *max_error,
567 struct timeval *vblank_time,
568 bool in_vblank_irq)
569{
570 struct timeval tv_etime;
571 ktime_t stime, etime;
572 bool vbl_status;
573 struct drm_crtc *crtc;
574 const struct drm_display_mode *mode;
575 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
576 int vpos, hpos, i;
577 int delta_ns, duration_ns;
578
579 if (!drm_core_check_feature(dev, DRIVER_MODESET))
580 return false;
581
582 crtc = drm_crtc_from_index(dev, pipe);
583
584 if (pipe >= dev->num_crtcs || !crtc) {
585 DRM_ERROR("Invalid crtc %u\n", pipe);
586 return false;
587 }
588
589 /* Scanout position query not supported? Should not happen. */
590 if (!dev->driver->get_scanout_position) {
591 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
592 return false;
593 }
594
595 if (drm_drv_uses_atomic_modeset(dev))
596 mode = &vblank->hwmode;
597 else
598 mode = &crtc->hwmode;
599
600 /* If mode timing undefined, just return as no-op:
601 * Happens during initial modesetting of a crtc.
602 */
603 if (mode->crtc_clock == 0) {
604 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
605 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
606
607 return false;
608 }
609
610 /* Get current scanout position with system timestamp.
611 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
612 * if single query takes longer than max_error nanoseconds.
613 *
614 * This guarantees a tight bound on maximum error if
615 * code gets preempted or delayed for some reason.
616 */
617 for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
618 /*
619 * Get vertical and horizontal scanout position vpos, hpos,
620 * and bounding timestamps stime, etime, pre/post query.
621 */
622 vbl_status = dev->driver->get_scanout_position(dev, pipe,
623 in_vblank_irq,
624 &vpos, &hpos,
625 &stime, &etime,
626 mode);
627
628 /* Return as no-op if scanout query unsupported or failed. */
629 if (!vbl_status) {
630 DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
631 pipe);
632 return false;
633 }
634
635 /* Compute uncertainty in timestamp of scanout position query. */
636 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
637
638 /* Accept result with < max_error nsecs timing uncertainty. */
639 if (duration_ns <= *max_error)
640 break;
641 }
642
643 /* Noisy system timing? */
644 if (i == DRM_TIMESTAMP_MAXRETRIES) {
645 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
646 pipe, duration_ns/1000, *max_error/1000, i);
647 }
648
649 /* Return upper bound of timestamp precision error. */
650 *max_error = duration_ns;
651
652 /* Convert scanout position into elapsed time at raw_time query
653 * since start of scanout at first display scanline. delta_ns
654 * can be negative if start of scanout hasn't happened yet.
655 */
656 delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
657 mode->crtc_clock);
658
659 if (!drm_timestamp_monotonic)
660 etime = ktime_mono_to_real(etime);
661
662 /* save this only for debugging purposes */
663 tv_etime = ktime_to_timeval(etime);
664 /* Subtract time delta from raw timestamp to get final
665 * vblank_time timestamp for end of vblank.
666 */
667 etime = ktime_sub_ns(etime, delta_ns);
668 *vblank_time = ktime_to_timeval(etime);
669
670 DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
671 pipe, hpos, vpos,
672 (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
673 (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
674 duration_ns/1000, i);
675
676 return true;
677}
678EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
679
680static struct timeval get_drm_timestamp(void)
681{
682 ktime_t now;
683
684 now = drm_timestamp_monotonic ? ktime_get() : ktime_get_real();
685 return ktime_to_timeval(now);
686}
687
688/**
689 * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
690 * vblank interval
691 * @dev: DRM device
692 * @pipe: index of CRTC whose vblank timestamp to retrieve
693 * @tvblank: Pointer to target struct timeval which should receive the timestamp
694 * @in_vblank_irq:
695 * True when called from drm_crtc_handle_vblank(). Some drivers
696 * need to apply some workarounds for gpu-specific vblank irq quirks
697 * if flag is set.
698 *
699 * Fetches the system timestamp corresponding to the time of the most recent
700 * vblank interval on specified CRTC. May call into kms-driver to
701 * compute the timestamp with a high-precision GPU specific method.
702 *
703 * Returns zero if timestamp originates from uncorrected do_gettimeofday()
704 * call, i.e., it isn't very precisely locked to the true vblank.
705 *
706 * Returns:
707 * True if timestamp is considered to be very precise, false otherwise.
708 */
709static bool
710drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
711 struct timeval *tvblank, bool in_vblank_irq)
712{
713 bool ret = false;
714
715 /* Define requested maximum error on timestamps (nanoseconds). */
716 int max_error = (int) drm_timestamp_precision * 1000;
717
718 /* Query driver if possible and precision timestamping enabled. */
719 if (dev->driver->get_vblank_timestamp && (max_error > 0))
720 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
721 tvblank, in_vblank_irq);
722
723 /* GPU high precision timestamp query unsupported or failed.
724 * Return current monotonic/gettimeofday timestamp as best estimate.
725 */
726 if (!ret)
727 *tvblank = get_drm_timestamp();
728
729 return ret;
730}
731
732/**
733 * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
734 * @crtc: which counter to retrieve
735 *
736 * Fetches the "cooked" vblank count value that represents the number of
737 * vblank events since the system was booted, including lost events due to
738 * modesetting activity.
739 *
740 * Returns:
741 * The software vblank counter.
742 */
743u32 drm_crtc_vblank_count(struct drm_crtc *crtc)
744{
745 return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
746}
747EXPORT_SYMBOL(drm_crtc_vblank_count);
748
749/**
750 * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
751 * system timestamp corresponding to that vblank counter value.
752 * @dev: DRM device
753 * @pipe: index of CRTC whose counter to retrieve
754 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
755 *
756 * Fetches the "cooked" vblank count value that represents the number of
757 * vblank events since the system was booted, including lost events due to
758 * modesetting activity. Returns corresponding system timestamp of the time
759 * of the vblank interval that corresponds to the current vblank counter value.
760 *
761 * This is the legacy version of drm_crtc_vblank_count_and_time().
762 */
763static u32 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
764 struct timeval *vblanktime)
765{
766 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
767 u32 vblank_count;
768 unsigned int seq;
769
770 if (WARN_ON(pipe >= dev->num_crtcs)) {
771 *vblanktime = (struct timeval) { 0 };
772 return 0;
773 }
774
775 do {
776 seq = read_seqbegin(&vblank->seqlock);
777 vblank_count = vblank->count;
778 *vblanktime = vblank->time;
779 } while (read_seqretry(&vblank->seqlock, seq));
780
781 return vblank_count;
782}
783
784/**
785 * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
786 * and the system timestamp corresponding to that vblank counter value
787 * @crtc: which counter to retrieve
788 * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
789 *
790 * Fetches the "cooked" vblank count value that represents the number of
791 * vblank events since the system was booted, including lost events due to
792 * modesetting activity. Returns corresponding system timestamp of the time
793 * of the vblank interval that corresponds to the current vblank counter value.
794 */
795u32 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
796 struct timeval *vblanktime)
797{
798 return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
799 vblanktime);
800}
801EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
802
803static void send_vblank_event(struct drm_device *dev,
804 struct drm_pending_vblank_event *e,
805 unsigned long seq, struct timeval *now)
806{
807 e->event.sequence = seq;
808 e->event.tv_sec = now->tv_sec;
809 e->event.tv_usec = now->tv_usec;
810
811 trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe,
812 e->event.sequence);
813
814 drm_send_event_locked(dev, &e->base);
815}
816
817/**
818 * drm_crtc_arm_vblank_event - arm vblank event after pageflip
819 * @crtc: the source CRTC of the vblank event
820 * @e: the event to send
821 *
822 * A lot of drivers need to generate vblank events for the very next vblank
823 * interrupt. For example when the page flip interrupt happens when the page
824 * flip gets armed, but not when it actually executes within the next vblank
825 * period. This helper function implements exactly the required vblank arming
826 * behaviour.
827 *
828 * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
829 * atomic commit must ensure that the next vblank happens at exactly the same
830 * time as the atomic commit is committed to the hardware. This function itself
831 * does **not** protect again the next vblank interrupt racing with either this
832 * function call or the atomic commit operation. A possible sequence could be:
833 *
834 * 1. Driver commits new hardware state into vblank-synchronized registers.
835 * 2. A vblank happens, committing the hardware state. Also the corresponding
836 * vblank interrupt is fired off and fully processed by the interrupt
837 * handler.
838 * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
839 * 4. The event is only send out for the next vblank, which is wrong.
840 *
841 * An equivalent race can happen when the driver calls
842 * drm_crtc_arm_vblank_event() before writing out the new hardware state.
843 *
844 * The only way to make this work safely is to prevent the vblank from firing
845 * (and the hardware from committing anything else) until the entire atomic
846 * commit sequence has run to completion. If the hardware does not have such a
847 * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
848 * Instead drivers need to manually send out the event from their interrupt
849 * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
850 * possible race with the hardware committing the atomic update.
851 *
852 * Caller must hold event lock. Caller must also hold a vblank reference for
853 * the event @e, which will be dropped when the next vblank arrives.
854 */
855void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
856 struct drm_pending_vblank_event *e)
857{
858 struct drm_device *dev = crtc->dev;
859 unsigned int pipe = drm_crtc_index(crtc);
860
861 assert_spin_locked(&dev->event_lock);
862
863 e->pipe = pipe;
864 e->event.sequence = drm_vblank_count(dev, pipe);
865 e->event.crtc_id = crtc->base.id;
866 list_add_tail(&e->base.link, &dev->vblank_event_list);
867}
868EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
869
870/**
871 * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
872 * @crtc: the source CRTC of the vblank event
873 * @e: the event to send
874 *
875 * Updates sequence # and timestamp on event for the most recently processed
876 * vblank, and sends it to userspace. Caller must hold event lock.
877 *
878 * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
879 * situation, especially to send out events for atomic commit operations.
880 */
881void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
882 struct drm_pending_vblank_event *e)
883{
884 struct drm_device *dev = crtc->dev;
885 unsigned int seq, pipe = drm_crtc_index(crtc);
886 struct timeval now;
887
888 if (dev->num_crtcs > 0) {
889 seq = drm_vblank_count_and_time(dev, pipe, &now);
890 } else {
891 seq = 0;
892
893 now = get_drm_timestamp();
894 }
895 e->pipe = pipe;
896 e->event.crtc_id = crtc->base.id;
897 send_vblank_event(dev, e, seq, &now);
898}
899EXPORT_SYMBOL(drm_crtc_send_vblank_event);
900
901static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
902{
903 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
904 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
905
906 if (crtc->funcs->enable_vblank)
907 return crtc->funcs->enable_vblank(crtc);
908 }
909
910 return dev->driver->enable_vblank(dev, pipe);
911}
912
913/**
914 * drm_vblank_enable - enable the vblank interrupt on a CRTC
915 * @dev: DRM device
916 * @pipe: CRTC index
917 *
918 * Returns:
919 * Zero on success or a negative error code on failure.
920 */
921static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
922{
923 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
924 int ret = 0;
925
926 assert_spin_locked(&dev->vbl_lock);
927
928 spin_lock(&dev->vblank_time_lock);
929
930 if (!vblank->enabled) {
931 /*
932 * Enable vblank irqs under vblank_time_lock protection.
933 * All vblank count & timestamp updates are held off
934 * until we are done reinitializing master counter and
935 * timestamps. Filtercode in drm_handle_vblank() will
936 * prevent double-accounting of same vblank interval.
937 */
938 ret = __enable_vblank(dev, pipe);
939 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
940 if (ret) {
941 atomic_dec(&vblank->refcount);
942 } else {
943 drm_update_vblank_count(dev, pipe, 0);
944 /* drm_update_vblank_count() includes a wmb so we just
945 * need to ensure that the compiler emits the write
946 * to mark the vblank as enabled after the call
947 * to drm_update_vblank_count().
948 */
949 WRITE_ONCE(vblank->enabled, true);
950 }
951 }
952
953 spin_unlock(&dev->vblank_time_lock);
954
955 return ret;
956}
957
958/**
959 * drm_vblank_get - get a reference count on vblank events
960 * @dev: DRM device
961 * @pipe: index of CRTC to own
962 *
963 * Acquire a reference count on vblank events to avoid having them disabled
964 * while in use.
965 *
966 * This is the legacy version of drm_crtc_vblank_get().
967 *
968 * Returns:
969 * Zero on success or a negative error code on failure.
970 */
971static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
972{
973 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
974 unsigned long irqflags;
975 int ret = 0;
976
977 if (!dev->num_crtcs)
978 return -EINVAL;
979
980 if (WARN_ON(pipe >= dev->num_crtcs))
981 return -EINVAL;
982
983 spin_lock_irqsave(&dev->vbl_lock, irqflags);
984 /* Going from 0->1 means we have to enable interrupts again */
985 if (atomic_add_return(1, &vblank->refcount) == 1) {
986 ret = drm_vblank_enable(dev, pipe);
987 } else {
988 if (!vblank->enabled) {
989 atomic_dec(&vblank->refcount);
990 ret = -EINVAL;
991 }
992 }
993 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
994
995 return ret;
996}
997
998/**
999 * drm_crtc_vblank_get - get a reference count on vblank events
1000 * @crtc: which CRTC to own
1001 *
1002 * Acquire a reference count on vblank events to avoid having them disabled
1003 * while in use.
1004 *
1005 * Returns:
1006 * Zero on success or a negative error code on failure.
1007 */
1008int drm_crtc_vblank_get(struct drm_crtc *crtc)
1009{
1010 return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1011}
1012EXPORT_SYMBOL(drm_crtc_vblank_get);
1013
1014/**
1015 * drm_vblank_put - release ownership of vblank events
1016 * @dev: DRM device
1017 * @pipe: index of CRTC to release
1018 *
1019 * Release ownership of a given vblank counter, turning off interrupts
1020 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1021 *
1022 * This is the legacy version of drm_crtc_vblank_put().
1023 */
1024static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1025{
1026 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1027
1028 if (WARN_ON(pipe >= dev->num_crtcs))
1029 return;
1030
1031 if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1032 return;
1033
1034 /* Last user schedules interrupt disable */
1035 if (atomic_dec_and_test(&vblank->refcount)) {
1036 if (drm_vblank_offdelay == 0)
1037 return;
1038 else if (drm_vblank_offdelay < 0)
1039 vblank_disable_fn((unsigned long)vblank);
1040 else if (!dev->vblank_disable_immediate)
1041 mod_timer(&vblank->disable_timer,
1042 jiffies + ((drm_vblank_offdelay * HZ)/1000));
1043 }
1044}
1045
1046/**
1047 * drm_crtc_vblank_put - give up ownership of vblank events
1048 * @crtc: which counter to give up
1049 *
1050 * Release ownership of a given vblank counter, turning off interrupts
1051 * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1052 */
1053void drm_crtc_vblank_put(struct drm_crtc *crtc)
1054{
1055 drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1056}
1057EXPORT_SYMBOL(drm_crtc_vblank_put);
1058
1059/**
1060 * drm_wait_one_vblank - wait for one vblank
1061 * @dev: DRM device
1062 * @pipe: CRTC index
1063 *
1064 * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1065 * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1066 * due to lack of driver support or because the crtc is off.
1067 */
1068void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1069{
1070 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1071 int ret;
1072 u32 last;
1073
1074 if (WARN_ON(pipe >= dev->num_crtcs))
1075 return;
1076
1077 ret = drm_vblank_get(dev, pipe);
1078 if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1079 return;
1080
1081 last = drm_vblank_count(dev, pipe);
1082
1083 ret = wait_event_timeout(vblank->queue,
1084 last != drm_vblank_count(dev, pipe),
1085 msecs_to_jiffies(100));
1086
1087 WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1088
1089 drm_vblank_put(dev, pipe);
1090}
1091EXPORT_SYMBOL(drm_wait_one_vblank);
1092
1093/**
1094 * drm_crtc_wait_one_vblank - wait for one vblank
1095 * @crtc: DRM crtc
1096 *
1097 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1098 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1099 * due to lack of driver support or because the crtc is off.
1100 */
1101void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1102{
1103 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1104}
1105EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1106
1107/**
1108 * drm_crtc_vblank_off - disable vblank events on a CRTC
1109 * @crtc: CRTC in question
1110 *
1111 * Drivers can use this function to shut down the vblank interrupt handling when
1112 * disabling a crtc. This function ensures that the latest vblank frame count is
1113 * stored so that drm_vblank_on can restore it again.
1114 *
1115 * Drivers must use this function when the hardware vblank counter can get
1116 * reset, e.g. when suspending.
1117 */
1118void drm_crtc_vblank_off(struct drm_crtc *crtc)
1119{
1120 struct drm_device *dev = crtc->dev;
1121 unsigned int pipe = drm_crtc_index(crtc);
1122 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1123 struct drm_pending_vblank_event *e, *t;
1124 struct timeval now;
1125 unsigned long irqflags;
1126 unsigned int seq;
1127
1128 if (WARN_ON(pipe >= dev->num_crtcs))
1129 return;
1130
1131 spin_lock_irqsave(&dev->event_lock, irqflags);
1132
1133 spin_lock(&dev->vbl_lock);
1134 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1135 pipe, vblank->enabled, vblank->inmodeset);
1136
1137 /* Avoid redundant vblank disables without previous
1138 * drm_crtc_vblank_on(). */
1139 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1140 drm_vblank_disable_and_save(dev, pipe);
1141
1142 wake_up(&vblank->queue);
1143
1144 /*
1145 * Prevent subsequent drm_vblank_get() from re-enabling
1146 * the vblank interrupt by bumping the refcount.
1147 */
1148 if (!vblank->inmodeset) {
1149 atomic_inc(&vblank->refcount);
1150 vblank->inmodeset = 1;
1151 }
1152 spin_unlock(&dev->vbl_lock);
1153
1154 /* Send any queued vblank events, lest the natives grow disquiet */
1155 seq = drm_vblank_count_and_time(dev, pipe, &now);
1156
1157 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1158 if (e->pipe != pipe)
1159 continue;
1160 DRM_DEBUG("Sending premature vblank event on disable: "
1161 "wanted %u, current %u\n",
1162 e->event.sequence, seq);
1163 list_del(&e->base.link);
1164 drm_vblank_put(dev, pipe);
1165 send_vblank_event(dev, e, seq, &now);
1166 }
1167 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1168
1169 /* Will be reset by the modeset helpers when re-enabling the crtc by
1170 * calling drm_calc_timestamping_constants(). */
1171 vblank->hwmode.crtc_clock = 0;
1172}
1173EXPORT_SYMBOL(drm_crtc_vblank_off);
1174
1175/**
1176 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1177 * @crtc: CRTC in question
1178 *
1179 * Drivers can use this function to reset the vblank state to off at load time.
1180 * Drivers should use this together with the drm_crtc_vblank_off() and
1181 * drm_crtc_vblank_on() functions. The difference compared to
1182 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1183 * and hence doesn't need to call any driver hooks.
1184 */
1185void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1186{
1187 struct drm_device *dev = crtc->dev;
1188 unsigned long irqflags;
1189 unsigned int pipe = drm_crtc_index(crtc);
1190 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1191
1192 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1193 /*
1194 * Prevent subsequent drm_vblank_get() from enabling the vblank
1195 * interrupt by bumping the refcount.
1196 */
1197 if (!vblank->inmodeset) {
1198 atomic_inc(&vblank->refcount);
1199 vblank->inmodeset = 1;
1200 }
1201 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1202
1203 WARN_ON(!list_empty(&dev->vblank_event_list));
1204}
1205EXPORT_SYMBOL(drm_crtc_vblank_reset);
1206
1207/**
1208 * drm_crtc_vblank_on - enable vblank events on a CRTC
1209 * @crtc: CRTC in question
1210 *
1211 * This functions restores the vblank interrupt state captured with
1212 * drm_crtc_vblank_off() again. Note that calls to drm_crtc_vblank_on() and
1213 * drm_crtc_vblank_off() can be unbalanced and so can also be unconditionally called
1214 * in driver load code to reflect the current hardware state of the crtc.
1215 */
1216void drm_crtc_vblank_on(struct drm_crtc *crtc)
1217{
1218 struct drm_device *dev = crtc->dev;
1219 unsigned int pipe = drm_crtc_index(crtc);
1220 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1221 unsigned long irqflags;
1222
1223 if (WARN_ON(pipe >= dev->num_crtcs))
1224 return;
1225
1226 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1227 DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1228 pipe, vblank->enabled, vblank->inmodeset);
1229
1230 /* Drop our private "prevent drm_vblank_get" refcount */
1231 if (vblank->inmodeset) {
1232 atomic_dec(&vblank->refcount);
1233 vblank->inmodeset = 0;
1234 }
1235
1236 drm_reset_vblank_timestamp(dev, pipe);
1237
1238 /*
1239 * re-enable interrupts if there are users left, or the
1240 * user wishes vblank interrupts to be enabled all the time.
1241 */
1242 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1243 WARN_ON(drm_vblank_enable(dev, pipe));
1244 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1245}
1246EXPORT_SYMBOL(drm_crtc_vblank_on);
1247
1248static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1249 unsigned int pipe)
1250{
1251 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1252
1253 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1254 if (!dev->num_crtcs)
1255 return;
1256
1257 if (WARN_ON(pipe >= dev->num_crtcs))
1258 return;
1259
1260 /*
1261 * To avoid all the problems that might happen if interrupts
1262 * were enabled/disabled around or between these calls, we just
1263 * have the kernel take a reference on the CRTC (just once though
1264 * to avoid corrupting the count if multiple, mismatch calls occur),
1265 * so that interrupts remain enabled in the interim.
1266 */
1267 if (!vblank->inmodeset) {
1268 vblank->inmodeset = 0x1;
1269 if (drm_vblank_get(dev, pipe) == 0)
1270 vblank->inmodeset |= 0x2;
1271 }
1272}
1273
1274static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1275 unsigned int pipe)
1276{
1277 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1278 unsigned long irqflags;
1279
1280 /* vblank is not initialized (IRQ not installed ?), or has been freed */
1281 if (!dev->num_crtcs)
1282 return;
1283
1284 if (WARN_ON(pipe >= dev->num_crtcs))
1285 return;
1286
1287 if (vblank->inmodeset) {
1288 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1289 drm_reset_vblank_timestamp(dev, pipe);
1290 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1291
1292 if (vblank->inmodeset & 0x2)
1293 drm_vblank_put(dev, pipe);
1294
1295 vblank->inmodeset = 0;
1296 }
1297}
1298
1299int drm_legacy_modeset_ctl(struct drm_device *dev, void *data,
1300 struct drm_file *file_priv)
1301{
1302 struct drm_modeset_ctl *modeset = data;
1303 unsigned int pipe;
1304
1305 /* If drm_vblank_init() hasn't been called yet, just no-op */
1306 if (!dev->num_crtcs)
1307 return 0;
1308
1309 /* KMS drivers handle this internally */
1310 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1311 return 0;
1312
1313 pipe = modeset->crtc;
1314 if (pipe >= dev->num_crtcs)
1315 return -EINVAL;
1316
1317 switch (modeset->cmd) {
1318 case _DRM_PRE_MODESET:
1319 drm_legacy_vblank_pre_modeset(dev, pipe);
1320 break;
1321 case _DRM_POST_MODESET:
1322 drm_legacy_vblank_post_modeset(dev, pipe);
1323 break;
1324 default:
1325 return -EINVAL;
1326 }
1327
1328 return 0;
1329}
1330
1331static inline bool vblank_passed(u32 seq, u32 ref)
1332{
1333 return (seq - ref) <= (1 << 23);
1334}
1335
1336static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1337 union drm_wait_vblank *vblwait,
1338 struct drm_file *file_priv)
1339{
1340 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1341 struct drm_pending_vblank_event *e;
1342 struct timeval now;
1343 unsigned long flags;
1344 unsigned int seq;
1345 int ret;
1346
1347 e = kzalloc(sizeof(*e), GFP_KERNEL);
1348 if (e == NULL) {
1349 ret = -ENOMEM;
1350 goto err_put;
1351 }
1352
1353 e->pipe = pipe;
1354 e->event.base.type = DRM_EVENT_VBLANK;
1355 e->event.base.length = sizeof(e->event);
1356 e->event.user_data = vblwait->request.signal;
1357
1358 spin_lock_irqsave(&dev->event_lock, flags);
1359
1360 /*
1361 * drm_crtc_vblank_off() might have been called after we called
1362 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1363 * vblank disable, so no need for further locking. The reference from
1364 * drm_vblank_get() protects against vblank disable from another source.
1365 */
1366 if (!READ_ONCE(vblank->enabled)) {
1367 ret = -EINVAL;
1368 goto err_unlock;
1369 }
1370
1371 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1372 &e->event.base);
1373
1374 if (ret)
1375 goto err_unlock;
1376
1377 seq = drm_vblank_count_and_time(dev, pipe, &now);
1378
1379 DRM_DEBUG("event on vblank count %u, current %u, crtc %u\n",
1380 vblwait->request.sequence, seq, pipe);
1381
1382 trace_drm_vblank_event_queued(file_priv, pipe,
1383 vblwait->request.sequence);
1384
1385 e->event.sequence = vblwait->request.sequence;
1386 if (vblank_passed(seq, vblwait->request.sequence)) {
1387 drm_vblank_put(dev, pipe);
1388 send_vblank_event(dev, e, seq, &now);
1389 vblwait->reply.sequence = seq;
1390 } else {
1391 /* drm_handle_vblank_events will call drm_vblank_put */
1392 list_add_tail(&e->base.link, &dev->vblank_event_list);
1393 vblwait->reply.sequence = vblwait->request.sequence;
1394 }
1395
1396 spin_unlock_irqrestore(&dev->event_lock, flags);
1397
1398 return 0;
1399
1400err_unlock:
1401 spin_unlock_irqrestore(&dev->event_lock, flags);
1402 kfree(e);
1403err_put:
1404 drm_vblank_put(dev, pipe);
1405 return ret;
1406}
1407
1408static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1409{
1410 if (vblwait->request.sequence)
1411 return false;
1412
1413 return _DRM_VBLANK_RELATIVE ==
1414 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1415 _DRM_VBLANK_EVENT |
1416 _DRM_VBLANK_NEXTONMISS));
1417}
1418
1419/*
1420 * Wait for VBLANK.
1421 *
1422 * \param inode device inode.
1423 * \param file_priv DRM file private.
1424 * \param cmd command.
1425 * \param data user argument, pointing to a drm_wait_vblank structure.
1426 * \return zero on success or a negative number on failure.
1427 *
1428 * This function enables the vblank interrupt on the pipe requested, then
1429 * sleeps waiting for the requested sequence number to occur, and drops
1430 * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
1431 * after a timeout with no further vblank waits scheduled).
1432 */
1433int drm_wait_vblank(struct drm_device *dev, void *data,
1434 struct drm_file *file_priv)
1435{
1436 struct drm_vblank_crtc *vblank;
1437 union drm_wait_vblank *vblwait = data;
1438 int ret;
1439 unsigned int flags, seq, pipe, high_pipe;
1440
1441 if (!dev->irq_enabled)
1442 return -EINVAL;
1443
1444 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1445 return -EINVAL;
1446
1447 if (vblwait->request.type &
1448 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1449 _DRM_VBLANK_HIGH_CRTC_MASK)) {
1450 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1451 vblwait->request.type,
1452 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1453 _DRM_VBLANK_HIGH_CRTC_MASK));
1454 return -EINVAL;
1455 }
1456
1457 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1458 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1459 if (high_pipe)
1460 pipe = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1461 else
1462 pipe = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1463 if (pipe >= dev->num_crtcs)
1464 return -EINVAL;
1465
1466 vblank = &dev->vblank[pipe];
1467
1468 /* If the counter is currently enabled and accurate, short-circuit
1469 * queries to return the cached timestamp of the last vblank.
1470 */
1471 if (dev->vblank_disable_immediate &&
1472 drm_wait_vblank_is_query(vblwait) &&
1473 READ_ONCE(vblank->enabled)) {
1474 struct timeval now;
1475
1476 vblwait->reply.sequence =
1477 drm_vblank_count_and_time(dev, pipe, &now);
1478 vblwait->reply.tval_sec = now.tv_sec;
1479 vblwait->reply.tval_usec = now.tv_usec;
1480 return 0;
1481 }
1482
1483 ret = drm_vblank_get(dev, pipe);
1484 if (ret) {
1485 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1486 return ret;
1487 }
1488 seq = drm_vblank_count(dev, pipe);
1489
1490 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1491 case _DRM_VBLANK_RELATIVE:
1492 vblwait->request.sequence += seq;
1493 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1494 case _DRM_VBLANK_ABSOLUTE:
1495 break;
1496 default:
1497 ret = -EINVAL;
1498 goto done;
1499 }
1500
1501 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1502 vblank_passed(seq, vblwait->request.sequence))
1503 vblwait->request.sequence = seq + 1;
1504
1505 if (flags & _DRM_VBLANK_EVENT) {
1506 /* must hold on to the vblank ref until the event fires
1507 * drm_vblank_put will be called asynchronously
1508 */
1509 return drm_queue_vblank_event(dev, pipe, vblwait, file_priv);
1510 }
1511
1512 if (vblwait->request.sequence != seq) {
1513 DRM_DEBUG("waiting on vblank count %u, crtc %u\n",
1514 vblwait->request.sequence, pipe);
1515 DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1516 vblank_passed(drm_vblank_count(dev, pipe),
1517 vblwait->request.sequence) ||
1518 !READ_ONCE(vblank->enabled));
1519 }
1520
1521 if (ret != -EINTR) {
1522 struct timeval now;
1523
1524 vblwait->reply.sequence = drm_vblank_count_and_time(dev, pipe, &now);
1525 vblwait->reply.tval_sec = now.tv_sec;
1526 vblwait->reply.tval_usec = now.tv_usec;
1527
1528 DRM_DEBUG("crtc %d returning %u to client\n",
1529 pipe, vblwait->reply.sequence);
1530 } else {
1531 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1532 }
1533
1534done:
1535 drm_vblank_put(dev, pipe);
1536 return ret;
1537}
1538
1539static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1540{
1541 struct drm_pending_vblank_event *e, *t;
1542 struct timeval now;
1543 unsigned int seq;
1544
1545 assert_spin_locked(&dev->event_lock);
1546
1547 seq = drm_vblank_count_and_time(dev, pipe, &now);
1548
1549 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1550 if (e->pipe != pipe)
1551 continue;
1552 if (!vblank_passed(seq, e->event.sequence))
1553 continue;
1554
1555 DRM_DEBUG("vblank event on %u, current %u\n",
1556 e->event.sequence, seq);
1557
1558 list_del(&e->base.link);
1559 drm_vblank_put(dev, pipe);
1560 send_vblank_event(dev, e, seq, &now);
1561 }
1562
1563 trace_drm_vblank_event(pipe, seq);
1564}
1565
1566/**
1567 * drm_handle_vblank - handle a vblank event
1568 * @dev: DRM device
1569 * @pipe: index of CRTC where this event occurred
1570 *
1571 * Drivers should call this routine in their vblank interrupt handlers to
1572 * update the vblank counter and send any signals that may be pending.
1573 *
1574 * This is the legacy version of drm_crtc_handle_vblank().
1575 */
1576bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1577{
1578 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1579 unsigned long irqflags;
1580 bool disable_irq;
1581
1582 if (WARN_ON_ONCE(!dev->num_crtcs))
1583 return false;
1584
1585 if (WARN_ON(pipe >= dev->num_crtcs))
1586 return false;
1587
1588 spin_lock_irqsave(&dev->event_lock, irqflags);
1589
1590 /* Need timestamp lock to prevent concurrent execution with
1591 * vblank enable/disable, as this would cause inconsistent
1592 * or corrupted timestamps and vblank counts.
1593 */
1594 spin_lock(&dev->vblank_time_lock);
1595
1596 /* Vblank irq handling disabled. Nothing to do. */
1597 if (!vblank->enabled) {
1598 spin_unlock(&dev->vblank_time_lock);
1599 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1600 return false;
1601 }
1602
1603 drm_update_vblank_count(dev, pipe, true);
1604
1605 spin_unlock(&dev->vblank_time_lock);
1606
1607 wake_up(&vblank->queue);
1608
1609 /* With instant-off, we defer disabling the interrupt until after
1610 * we finish processing the following vblank after all events have
1611 * been signaled. The disable has to be last (after
1612 * drm_handle_vblank_events) so that the timestamp is always accurate.
1613 */
1614 disable_irq = (dev->vblank_disable_immediate &&
1615 drm_vblank_offdelay > 0 &&
1616 !atomic_read(&vblank->refcount));
1617
1618 drm_handle_vblank_events(dev, pipe);
1619
1620 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1621
1622 if (disable_irq)
1623 vblank_disable_fn((unsigned long)vblank);
1624
1625 return true;
1626}
1627EXPORT_SYMBOL(drm_handle_vblank);
1628
1629/**
1630 * drm_crtc_handle_vblank - handle a vblank event
1631 * @crtc: where this event occurred
1632 *
1633 * Drivers should call this routine in their vblank interrupt handlers to
1634 * update the vblank counter and send any signals that may be pending.
1635 *
1636 * This is the native KMS version of drm_handle_vblank().
1637 *
1638 * Returns:
1639 * True if the event was successfully handled, false on failure.
1640 */
1641bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1642{
1643 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1644}
1645EXPORT_SYMBOL(drm_crtc_handle_vblank);