Merge branch 'vendor/TNFTP'
[dragonfly.git] / sys / dev / drm / drm_irq.c
1 /*-
2  * Copyright 2003 Eric Anholt
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * ERIC ANHOLT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <anholt@FreeBSD.org>
25  *
26  * $FreeBSD: src/sys/dev/drm2/drm_irq.c,v 1.1 2012/05/22 11:07:44 kib Exp $
27  */
28
29 /** @file drm_irq.c
30  * Support code for handling setup/teardown of interrupt handlers and
31  * handing interrupt handlers off to the drivers.
32  */
33
34 #include <linux/export.h>
35 #include <linux/mutex.h>
36 #include <linux/timer.h>
37 #include <drm/drmP.h>
38
39 MALLOC_DEFINE(DRM_MEM_VBLANK, "drm_vblank", "DRM VBLANK Handling Data");
40
41 /* Access macro for slots in vblank timestamp ringbuffer. */
42 #define vblanktimestamp(dev, crtc, count) ( \
43         (dev)->_vblank_time[(crtc) * DRM_VBLANKTIME_RBSIZE + \
44         ((count) % DRM_VBLANKTIME_RBSIZE)])
45
46 /* Retry timestamp calculation up to 3 times to satisfy
47  * drm_timestamp_precision before giving up.
48  */
49 #define DRM_TIMESTAMP_MAXRETRIES 3
50
51 /* Threshold in nanoseconds for detection of redundant
52  * vblank irq in drm_handle_vblank(). 1 msec should be ok.
53  */
54 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
55
56 int drm_irq_by_busid(struct drm_device *dev, void *data,
57                      struct drm_file *file_priv)
58 {
59         struct drm_irq_busid *irq = data;
60
61         if ((irq->busnum >> 8) != dev->pci_domain ||
62             (irq->busnum & 0xff) != dev->pci_bus ||
63             irq->devnum != dev->pci_slot ||
64             irq->funcnum != dev->pci_func)
65                 return EINVAL;
66
67         irq->irq = dev->irq;
68
69         DRM_DEBUG("%d:%d:%d => IRQ %d\n",
70             irq->busnum, irq->devnum, irq->funcnum, irq->irq);
71
72         return 0;
73 }
74
75 int
76 drm_irq_install(struct drm_device *dev)
77 {
78         int retcode;
79
80         if (dev->irq == 0 || dev->dev_private == NULL)
81                 return (EINVAL);
82
83         DRM_DEBUG("irq=%d\n", dev->irq);
84
85         DRM_LOCK(dev);
86         if (dev->irq_enabled) {
87                 DRM_UNLOCK(dev);
88                 return EBUSY;
89         }
90         dev->irq_enabled = 1;
91
92         dev->context_flag = 0;
93
94         /* Before installing handler */
95         if (dev->driver->irq_preinstall)
96                 dev->driver->irq_preinstall(dev);
97         DRM_UNLOCK(dev);
98
99         /* Install handler */
100         retcode = bus_setup_intr(dev->dev, dev->irqr, INTR_MPSAFE,
101             dev->driver->irq_handler, dev, &dev->irqh, &dev->irq_lock);
102         if (retcode != 0)
103                 goto err;
104
105         /* After installing handler */
106         DRM_LOCK(dev);
107         if (dev->driver->irq_postinstall)
108                 dev->driver->irq_postinstall(dev);
109         DRM_UNLOCK(dev);
110
111         return (0);
112 err:
113         device_printf(dev->dev, "Error setting interrupt: %d\n", retcode);
114         dev->irq_enabled = 0;
115
116         return (retcode);
117 }
118
119 int drm_irq_uninstall(struct drm_device *dev)
120 {
121         int i;
122
123         if (!dev->irq_enabled)
124                 return EINVAL;
125
126         dev->irq_enabled = 0;
127
128         /*
129         * Wake up any waiters so they don't hang.
130         */
131         if (dev->num_crtcs) {
132                 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
133                 for (i = 0; i < dev->num_crtcs; i++) {
134                         wakeup(&dev->_vblank_count[i]);
135                         dev->vblank_enabled[i] = 0;
136                         dev->last_vblank[i] =
137                                 dev->driver->get_vblank_counter(dev, i);
138                 }
139                 lockmgr(&dev->vbl_lock, LK_RELEASE);
140         }
141
142         DRM_DEBUG("irq=%d\n", dev->irq);
143
144         if (dev->driver->irq_uninstall)
145                 dev->driver->irq_uninstall(dev);
146
147         DRM_UNLOCK(dev);
148         bus_teardown_intr(dev->dev, dev->irqr, dev->irqh);
149         DRM_LOCK(dev);
150
151         return 0;
152 }
153
154 int drm_control(struct drm_device *dev, void *data, struct drm_file *file_priv)
155 {
156         struct drm_control *ctl = data;
157         int err;
158
159         switch (ctl->func) {
160         case DRM_INST_HANDLER:
161                 /* Handle drivers whose DRM used to require IRQ setup but the
162                  * no longer does.
163                  */
164                 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
165                         return 0;
166                 if (drm_core_check_feature(dev, DRIVER_MODESET))
167                         return 0;
168                 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
169                     ctl->irq != dev->irq)
170                         return EINVAL;
171                 return drm_irq_install(dev);
172         case DRM_UNINST_HANDLER:
173                 if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
174                         return 0;
175                 if (drm_core_check_feature(dev, DRIVER_MODESET))
176                         return 0;
177                 DRM_LOCK(dev);
178                 err = drm_irq_uninstall(dev);
179                 DRM_UNLOCK(dev);
180                 return err;
181         default:
182                 return EINVAL;
183         }
184 }
185
186 #define NSEC_PER_USEC   1000L
187 #define NSEC_PER_SEC    1000000000L
188
189 int64_t
190 timeval_to_ns(const struct timeval *tv)
191 {
192         return ((int64_t)tv->tv_sec * NSEC_PER_SEC) +
193                 tv->tv_usec * NSEC_PER_USEC;
194 }
195
196 struct timeval
197 ns_to_timeval(const int64_t nsec)
198 {
199         struct timeval tv;
200         long rem;
201
202         if (nsec == 0) {
203                 tv.tv_sec = 0;
204                 tv.tv_usec = 0;
205                 return (tv);
206         }
207
208         tv.tv_sec = nsec / NSEC_PER_SEC;
209         rem = nsec % NSEC_PER_SEC;
210         if (rem < 0) {
211                 tv.tv_sec--;
212                 rem += NSEC_PER_SEC;
213         }
214         tv.tv_usec = rem / 1000;
215         return (tv);
216 }
217
218 /*
219  * Clear vblank timestamp buffer for a crtc.
220  */
221 static void clear_vblank_timestamps(struct drm_device *dev, int crtc)
222 {
223         memset(&dev->_vblank_time[crtc * DRM_VBLANKTIME_RBSIZE], 0,
224                 DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval));
225 }
226
227 static int64_t
228 abs64(int64_t x)
229 {
230
231         return (x < 0 ? -x : x);
232 }
233
234 /*
235  * Disable vblank irq's on crtc, make sure that last vblank count
236  * of hardware and corresponding consistent software vblank counter
237  * are preserved, even if there are any spurious vblank irq's after
238  * disable.
239  */
240 static void vblank_disable_and_save(struct drm_device *dev, int crtc)
241 {
242         u32 vblcount;
243         int64_t diff_ns;
244         int vblrc;
245         struct timeval tvblank;
246
247         /* Prevent vblank irq processing while disabling vblank irqs,
248          * so no updates of timestamps or count can happen after we've
249          * disabled. Needed to prevent races in case of delayed irq's.
250          */
251         lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
252
253         dev->driver->disable_vblank(dev, crtc);
254         dev->vblank_enabled[crtc] = 0;
255
256         /* No further vblank irq's will be processed after
257          * this point. Get current hardware vblank count and
258          * vblank timestamp, repeat until they are consistent.
259          *
260          * FIXME: There is still a race condition here and in
261          * drm_update_vblank_count() which can cause off-by-one
262          * reinitialization of software vblank counter. If gpu
263          * vblank counter doesn't increment exactly at the leading
264          * edge of a vblank interval, then we can lose 1 count if
265          * we happen to execute between start of vblank and the
266          * delayed gpu counter increment.
267          */
268         do {
269                 dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc);
270                 vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
271         } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc));
272
273         /* Compute time difference to stored timestamp of last vblank
274          * as updated by last invocation of drm_handle_vblank() in vblank irq.
275          */
276         vblcount = atomic_read(&dev->_vblank_count[crtc]);
277         diff_ns = timeval_to_ns(&tvblank) -
278                   timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
279
280         /* If there is at least 1 msec difference between the last stored
281          * timestamp and tvblank, then we are currently executing our
282          * disable inside a new vblank interval, the tvblank timestamp
283          * corresponds to this new vblank interval and the irq handler
284          * for this vblank didn't run yet and won't run due to our disable.
285          * Therefore we need to do the job of drm_handle_vblank() and
286          * increment the vblank counter by one to account for this vblank.
287          *
288          * Skip this step if there isn't any high precision timestamp
289          * available. In that case we can't account for this and just
290          * hope for the best.
291          */
292         if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
293                 atomic_inc(&dev->_vblank_count[crtc]);
294         }
295
296         /* Invalidate all timestamps while vblank irq's are off. */
297         clear_vblank_timestamps(dev, crtc);
298
299         lockmgr(&dev->vblank_time_lock, LK_RELEASE);
300 }
301
302 static void vblank_disable_fn(unsigned long arg)
303 {
304         struct drm_device *dev = (struct drm_device *)arg;
305         int i;
306
307         if (!dev->vblank_disable_allowed)
308                 return;
309
310         for (i = 0; i < dev->num_crtcs; i++) {
311                 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
312                 if (atomic_read(&dev->vblank_refcount[i]) == 0 &&
313                     dev->vblank_enabled[i]) {
314                         DRM_DEBUG("disabling vblank on crtc %d\n", i);
315                         vblank_disable_and_save(dev, i);
316                 }
317                 lockmgr(&dev->vbl_lock, LK_RELEASE);
318         }
319 }
320
321 void drm_vblank_cleanup(struct drm_device *dev)
322 {
323         /* Bail if the driver didn't call drm_vblank_init() */
324         if (dev->num_crtcs == 0)
325                 return;
326
327         del_timer_sync(&dev->vblank_disable_timer);
328
329         vblank_disable_fn((unsigned long)dev);
330
331         drm_free(dev->_vblank_count, DRM_MEM_VBLANK);
332         drm_free(dev->vblank_refcount, DRM_MEM_VBLANK);
333         drm_free(dev->vblank_enabled, DRM_MEM_VBLANK);
334         drm_free(dev->last_vblank, DRM_MEM_VBLANK);
335         drm_free(dev->last_vblank_wait, DRM_MEM_VBLANK);
336         drm_free(dev->vblank_inmodeset, DRM_MEM_VBLANK);
337         drm_free(dev->_vblank_time, DRM_MEM_VBLANK);
338
339         dev->num_crtcs = 0;
340 }
341 EXPORT_SYMBOL(drm_vblank_cleanup);
342
343 int drm_vblank_init(struct drm_device *dev, int num_crtcs)
344 {
345         int i;
346
347         setup_timer(&dev->vblank_disable_timer, vblank_disable_fn,
348                     (unsigned long)dev);
349         lockinit(&dev->vblank_time_lock, "drmvtl", 0, LK_CANRECURSE);
350
351         dev->num_crtcs = num_crtcs;
352
353         dev->vbl_queue = kmalloc(sizeof(wait_queue_head_t) * num_crtcs,
354             DRM_MEM_VBLANK, M_WAITOK);
355
356         dev->_vblank_count = kmalloc(sizeof(atomic_t) * num_crtcs,
357             DRM_MEM_VBLANK, M_WAITOK);
358         dev->vblank_refcount = kmalloc(sizeof(atomic_t) * num_crtcs,
359             DRM_MEM_VBLANK, M_WAITOK);
360         dev->vblank_enabled = kmalloc(num_crtcs * sizeof(int),
361             DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
362         dev->last_vblank = kmalloc(num_crtcs * sizeof(u32),
363             DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
364         dev->last_vblank_wait = kmalloc(num_crtcs * sizeof(u32),
365             DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
366         dev->vblank_inmodeset = kmalloc(num_crtcs * sizeof(int),
367             DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
368         dev->_vblank_time = kmalloc(num_crtcs * DRM_VBLANKTIME_RBSIZE *
369             sizeof(struct timeval), DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
370         DRM_INFO("Supports vblank timestamp caching Rev 1 (10.10.2010).\n");
371
372         /* Driver specific high-precision vblank timestamping supported? */
373         if (dev->driver->get_vblank_timestamp)
374                 DRM_INFO("Driver supports precise vblank timestamp query.\n");
375         else
376                 DRM_INFO("No driver support for vblank timestamp query.\n");
377
378         /* Zero per-crtc vblank stuff */
379         for (i = 0; i < num_crtcs; i++) {
380                 init_waitqueue_head(&dev->vbl_queue[i]);
381                 atomic_set(&dev->_vblank_count[i], 0);
382                 atomic_set(&dev->vblank_refcount[i], 0);
383         }
384
385         dev->vblank_disable_allowed = 0;
386         return 0;
387 }
388 EXPORT_SYMBOL(drm_vblank_init);
389
390 void
391 drm_calc_timestamping_constants(struct drm_crtc *crtc)
392 {
393         int64_t linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
394         uint64_t dotclock;
395
396         /* Dot clock in Hz: */
397         dotclock = (uint64_t) crtc->hwmode.clock * 1000;
398
399         /* Fields of interlaced scanout modes are only halve a frame duration.
400          * Double the dotclock to get halve the frame-/line-/pixelduration.
401          */
402         if (crtc->hwmode.flags & DRM_MODE_FLAG_INTERLACE)
403                 dotclock *= 2;
404
405         /* Valid dotclock? */
406         if (dotclock > 0) {
407                 /* Convert scanline length in pixels and video dot clock to
408                  * line duration, frame duration and pixel duration in
409                  * nanoseconds:
410                  */
411                 pixeldur_ns = (int64_t)1000000000 / dotclock;
412                 linedur_ns  = ((uint64_t)crtc->hwmode.crtc_htotal *
413                     1000000000) / dotclock;
414                 framedur_ns = (int64_t)crtc->hwmode.crtc_vtotal * linedur_ns;
415         } else
416                 DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
417                           crtc->base.id);
418
419         crtc->pixeldur_ns = pixeldur_ns;
420         crtc->linedur_ns  = linedur_ns;
421         crtc->framedur_ns = framedur_ns;
422
423         DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
424                   crtc->base.id, crtc->hwmode.crtc_htotal,
425                   crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay);
426         DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
427                   crtc->base.id, (int) dotclock/1000, (int) framedur_ns,
428                   (int) linedur_ns, (int) pixeldur_ns);
429 }
430
431 /**
432  * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
433  * drivers. Implements calculation of exact vblank timestamps from
434  * given drm_display_mode timings and current video scanout position
435  * of a crtc. This can be called from within get_vblank_timestamp()
436  * implementation of a kms driver to implement the actual timestamping.
437  *
438  * Should return timestamps conforming to the OML_sync_control OpenML
439  * extension specification. The timestamp corresponds to the end of
440  * the vblank interval, aka start of scanout of topmost-leftmost display
441  * pixel in the following video frame.
442  *
443  * Requires support for optional dev->driver->get_scanout_position()
444  * in kms driver, plus a bit of setup code to provide a drm_display_mode
445  * that corresponds to the true scanout timing.
446  *
447  * The current implementation only handles standard video modes. It
448  * returns as no operation if a doublescan or interlaced video mode is
449  * active. Higher level code is expected to handle this.
450  *
451  * @dev: DRM device.
452  * @crtc: Which crtc's vblank timestamp to retrieve.
453  * @max_error: Desired maximum allowable error in timestamps (nanosecs).
454  *             On return contains true maximum error of timestamp.
455  * @vblank_time: Pointer to struct timeval which should receive the timestamp.
456  * @flags: Flags to pass to driver:
457  *         0 = Default.
458  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
459  * @refcrtc: drm_crtc* of crtc which defines scanout timing.
460  *
461  * Returns negative value on error, failure or if not supported in current
462  * video mode:
463  *
464  * -EINVAL   - Invalid crtc.
465  * -EAGAIN   - Temporary unavailable, e.g., called before initial modeset.
466  * -ENOTSUPP - Function not supported in current display mode.
467  * -EIO      - Failed, e.g., due to failed scanout position query.
468  *
469  * Returns or'ed positive status flags on success:
470  *
471  * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
472  * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
473  *
474  */
475 int
476 drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
477     int *max_error, struct timeval *vblank_time, unsigned flags,
478     struct drm_crtc *refcrtc)
479 {
480         struct timeval stime, raw_time;
481         struct drm_display_mode *mode;
482         int vbl_status, vtotal, vdisplay;
483         int vpos, hpos, i;
484         int64_t framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
485         bool invbl;
486
487         if (crtc < 0 || crtc >= dev->num_crtcs) {
488                 DRM_ERROR("Invalid crtc %d\n", crtc);
489                 return -EINVAL;
490         }
491
492         /* Scanout position query not supported? Should not happen. */
493         if (!dev->driver->get_scanout_position) {
494                 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
495                 return -EIO;
496         }
497
498         mode = &refcrtc->hwmode;
499         vtotal = mode->crtc_vtotal;
500         vdisplay = mode->crtc_vdisplay;
501
502         /* Durations of frames, lines, pixels in nanoseconds. */
503         framedur_ns = refcrtc->framedur_ns;
504         linedur_ns  = refcrtc->linedur_ns;
505         pixeldur_ns = refcrtc->pixeldur_ns;
506
507         /* If mode timing undefined, just return as no-op:
508          * Happens during initial modesetting of a crtc.
509          */
510         if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) {
511                 DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
512                 return -EAGAIN;
513         }
514
515         /* Get current scanout position with system timestamp.
516          * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
517          * if single query takes longer than max_error nanoseconds.
518          *
519          * This guarantees a tight bound on maximum error if
520          * code gets preempted or delayed for some reason.
521          */
522         for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
523                 /* Disable preemption to make it very likely to
524                  * succeed in the first iteration.
525                  */
526                 crit_enter();
527
528                 /* Get system timestamp before query. */
529                 getmicrouptime(&stime);
530
531                 /* Get vertical and horizontal scanout pos. vpos, hpos. */
532                 vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos);
533
534                 /* Get system timestamp after query. */
535                 getmicrouptime(&raw_time);
536
537                 crit_exit();
538
539                 /* Return as no-op if scanout query unsupported or failed. */
540                 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
541                         DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
542                                   crtc, vbl_status);
543                         return -EIO;
544                 }
545
546                 duration_ns = timeval_to_ns(&raw_time) - timeval_to_ns(&stime);
547
548                 /* Accept result with <  max_error nsecs timing uncertainty. */
549                 if (duration_ns <= (int64_t) *max_error)
550                         break;
551         }
552
553         /* Noisy system timing? */
554         if (i == DRM_TIMESTAMP_MAXRETRIES) {
555                 DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
556                           crtc, (int) duration_ns/1000, *max_error/1000, i);
557         }
558
559         /* Return upper bound of timestamp precision error. */
560         *max_error = (int) duration_ns;
561
562         /* Check if in vblank area:
563          * vpos is >=0 in video scanout area, but negative
564          * within vblank area, counting down the number of lines until
565          * start of scanout.
566          */
567         invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
568
569         /* Convert scanout position into elapsed time at raw_time query
570          * since start of scanout at first display scanline. delta_ns
571          * can be negative if start of scanout hasn't happened yet.
572          */
573         delta_ns = (int64_t)vpos * linedur_ns + (int64_t)hpos * pixeldur_ns;
574
575         /* Is vpos outside nominal vblank area, but less than
576          * 1/100 of a frame height away from start of vblank?
577          * If so, assume this isn't a massively delayed vblank
578          * interrupt, but a vblank interrupt that fired a few
579          * microseconds before true start of vblank. Compensate
580          * by adding a full frame duration to the final timestamp.
581          * Happens, e.g., on ATI R500, R600.
582          *
583          * We only do this if DRM_CALLED_FROM_VBLIRQ.
584          */
585         if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl &&
586             ((vdisplay - vpos) < vtotal / 100)) {
587                 delta_ns = delta_ns - framedur_ns;
588
589                 /* Signal this correction as "applied". */
590                 vbl_status |= 0x8;
591         }
592
593         /* Subtract time delta from raw timestamp to get final
594          * vblank_time timestamp for end of vblank.
595          */
596         *vblank_time = ns_to_timeval(timeval_to_ns(&raw_time) - delta_ns);
597
598         DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %jd.%jd -> %jd.%jd [e %d us, %d rep]\n",
599                   crtc, (int)vbl_status, hpos, vpos, (uintmax_t)raw_time.tv_sec,
600                   (uintmax_t)raw_time.tv_usec, (uintmax_t)vblank_time->tv_sec,
601                   (uintmax_t)vblank_time->tv_usec, (int)duration_ns/1000, i);
602
603         vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
604         if (invbl)
605                 vbl_status |= DRM_VBLANKTIME_INVBL;
606
607         return vbl_status;
608 }
609
610 static struct timeval get_drm_timestamp(void)
611 {
612         struct timeval now;
613
614         getmicrouptime(&now);
615
616         return now;
617 }
618
619 /**
620  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
621  * vblank interval.
622  *
623  * @dev: DRM device
624  * @crtc: which crtc's vblank timestamp to retrieve
625  * @tvblank: Pointer to target struct timeval which should receive the timestamp
626  * @flags: Flags to pass to driver:
627  *         0 = Default.
628  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
629  *
630  * Fetches the system timestamp corresponding to the time of the most recent
631  * vblank interval on specified crtc. May call into kms-driver to
632  * compute the timestamp with a high-precision GPU specific method.
633  *
634  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
635  * call, i.e., it isn't very precisely locked to the true vblank.
636  *
637  * Returns non-zero if timestamp is considered to be very precise.
638  */
639 u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
640                               struct timeval *tvblank, unsigned flags)
641 {
642         int ret = 0;
643
644         /* Define requested maximum error on timestamps (nanoseconds). */
645         int max_error = (int) drm_timestamp_precision * 1000;
646
647         /* Query driver if possible and precision timestamping enabled. */
648         if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
649                 ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
650                                                         tvblank, flags);
651                 if (ret > 0)
652                         return (u32) ret;
653         }
654
655         /* GPU high precision timestamp query unsupported or failed.
656          * Return gettimeofday timestamp as best estimate.
657          */
658         microtime(tvblank);
659
660         return 0;
661 }
662
663 /**
664  * drm_vblank_count - retrieve "cooked" vblank counter value
665  * @dev: DRM device
666  * @crtc: which counter to retrieve
667  *
668  * Fetches the "cooked" vblank count value that represents the number of
669  * vblank events since the system was booted, including lost events due to
670  * modesetting activity.
671  */
672 u32 drm_vblank_count(struct drm_device *dev, int crtc)
673 {
674         return atomic_read(&dev->_vblank_count[crtc]);
675 }
676
677 /**
678  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
679  * and the system timestamp corresponding to that vblank counter value.
680  *
681  * @dev: DRM device
682  * @crtc: which counter to retrieve
683  * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
684  *
685  * Fetches the "cooked" vblank count value that represents the number of
686  * vblank events since the system was booted, including lost events due to
687  * modesetting activity. Returns corresponding system timestamp of the time
688  * of the vblank interval that corresponds to the current value vblank counter
689  * value.
690  */
691 u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
692                               struct timeval *vblanktime)
693 {
694         u32 cur_vblank;
695
696         /* Read timestamp from slot of _vblank_time ringbuffer
697          * that corresponds to current vblank count. Retry if
698          * count has incremented during readout. This works like
699          * a seqlock.
700          */
701         do {
702                 cur_vblank = atomic_read(&dev->_vblank_count[crtc]);
703                 *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
704                 cpu_lfence();
705         } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc]));
706
707         return cur_vblank;
708 }
709
710 static void send_vblank_event(struct drm_device *dev,
711                 struct drm_pending_vblank_event *e,
712                 unsigned long seq, struct timeval *now)
713 {
714         KKASSERT(mutex_is_locked(&dev->event_lock));
715         e->event.sequence = seq;
716         e->event.tv_sec = now->tv_sec;
717         e->event.tv_usec = now->tv_usec;
718
719         list_add_tail(&e->base.link,
720                       &e->base.file_priv->event_list);
721         wakeup(&e->base.file_priv->event_list);
722 #if 0
723         trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
724                                          e->event.sequence);
725 #endif
726 }
727
728 /**
729  * drm_send_vblank_event - helper to send vblank event after pageflip
730  * @dev: DRM device
731  * @crtc: CRTC in question
732  * @e: the event to send
733  *
734  * Updates sequence # and timestamp on event, and sends it to userspace.
735  * Caller must hold event lock.
736  */
737 void drm_send_vblank_event(struct drm_device *dev, int crtc,
738                 struct drm_pending_vblank_event *e)
739 {
740         struct timeval now;
741         unsigned int seq;
742         if (crtc >= 0) {
743                 seq = drm_vblank_count_and_time(dev, crtc, &now);
744         } else {
745                 seq = 0;
746
747                 now = get_drm_timestamp();
748         }
749         e->pipe = crtc;
750         send_vblank_event(dev, e, seq, &now);
751 }
752 EXPORT_SYMBOL(drm_send_vblank_event);
753
754 /**
755  * drm_update_vblank_count - update the master vblank counter
756  * @dev: DRM device
757  * @crtc: counter to update
758  *
759  * Call back into the driver to update the appropriate vblank counter
760  * (specified by @crtc).  Deal with wraparound, if it occurred, and
761  * update the last read value so we can deal with wraparound on the next
762  * call if necessary.
763  *
764  * Only necessary when going from off->on, to account for frames we
765  * didn't get an interrupt for.
766  *
767  * Note: caller must hold dev->vbl_lock since this reads & writes
768  * device vblank fields.
769  */
770 static void drm_update_vblank_count(struct drm_device *dev, int crtc)
771 {
772         u32 cur_vblank, diff, tslot, rc;
773         struct timeval t_vblank;
774
775         /*
776          * Interrupts were disabled prior to this call, so deal with counter
777          * wrap if needed.
778          * NOTE!  It's possible we lost a full dev->max_vblank_count events
779          * here if the register is small or we had vblank interrupts off for
780          * a long time.
781          *
782          * We repeat the hardware vblank counter & timestamp query until
783          * we get consistent results. This to prevent races between gpu
784          * updating its hardware counter while we are retrieving the
785          * corresponding vblank timestamp.
786          */
787         do {
788                 cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
789                 rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
790         } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
791
792         /* Deal with counter wrap */
793         diff = cur_vblank - dev->last_vblank[crtc];
794         if (cur_vblank < dev->last_vblank[crtc]) {
795                 diff += dev->max_vblank_count;
796
797                 DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
798                           crtc, dev->last_vblank[crtc], cur_vblank, diff);
799         }
800
801         DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
802                   crtc, diff);
803
804         /* Reinitialize corresponding vblank timestamp if high-precision query
805          * available. Skip this step if query unsupported or failed. Will
806          * reinitialize delayed at next vblank interrupt in that case.
807          */
808         if (rc) {
809                 tslot = atomic_read(&dev->_vblank_count[crtc]) + diff;
810                 vblanktimestamp(dev, crtc, tslot) = t_vblank;
811         }
812
813         atomic_add(diff, &dev->_vblank_count[crtc]);
814 }
815
816 /**
817  * drm_vblank_get - get a reference count on vblank events
818  * @dev: DRM device
819  * @crtc: which CRTC to own
820  *
821  * Acquire a reference count on vblank events to avoid having them disabled
822  * while in use.
823  *
824  * RETURNS
825  * Zero on success, nonzero on failure.
826  */
827 int drm_vblank_get(struct drm_device *dev, int crtc)
828 {
829         int ret = 0;
830
831         lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
832         /* Going from 0->1 means we have to enable interrupts again */
833         if (atomic_add_return(1, &dev->vblank_refcount[crtc]) == 1) {
834                 lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
835                 if (!dev->vblank_enabled[crtc]) {
836                         /* Enable vblank irqs under vblank_time_lock protection.
837                          * All vblank count & timestamp updates are held off
838                          * until we are done reinitializing master counter and
839                          * timestamps. Filtercode in drm_handle_vblank() will
840                          * prevent double-accounting of same vblank interval.
841                          */
842                         ret = -dev->driver->enable_vblank(dev, crtc);
843                         DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
844                                   crtc, ret);
845                         if (ret)
846                                 atomic_dec(&dev->vblank_refcount[crtc]);
847                         else {
848                                 dev->vblank_enabled[crtc] = 1;
849                                 drm_update_vblank_count(dev, crtc);
850                         }
851                 }
852                 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
853         } else {
854                 if (!dev->vblank_enabled[crtc]) {
855                         atomic_dec(&dev->vblank_refcount[crtc]);
856                         ret = EINVAL;
857                 }
858         }
859         lockmgr(&dev->vbl_lock, LK_RELEASE);
860
861         return ret;
862 }
863
864 /**
865  * drm_vblank_put - give up ownership of vblank events
866  * @dev: DRM device
867  * @crtc: which counter to give up
868  *
869  * Release ownership of a given vblank counter, turning off interrupts
870  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
871  */
872 void drm_vblank_put(struct drm_device *dev, int crtc)
873 {
874         BUG_ON(atomic_read(&dev->vblank_refcount[crtc]) == 0);
875
876         /* Last user schedules interrupt disable */
877         if (atomic_dec_and_test(&dev->vblank_refcount[crtc]) &&
878             (drm_vblank_offdelay > 0))
879                 mod_timer(&dev->vblank_disable_timer,
880                           jiffies + ((drm_vblank_offdelay * DRM_HZ)/1000));
881 }
882 EXPORT_SYMBOL(drm_vblank_put);
883
884 void drm_vblank_off(struct drm_device *dev, int crtc)
885 {
886         struct drm_pending_vblank_event *e, *t;
887         struct timeval now;
888         unsigned int seq;
889
890         lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
891         vblank_disable_and_save(dev, crtc);
892         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
893         wakeup(&dev->_vblank_count[crtc]);
894
895         /* Send any queued vblank events, lest the natives grow disquiet */
896         seq = drm_vblank_count_and_time(dev, crtc, &now);
897         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
898                 if (e->pipe != crtc)
899                         continue;
900                 DRM_DEBUG("Sending premature vblank event on disable: \
901                           wanted %d, current %d\n",
902                           e->event.sequence, seq);
903                 list_del(&e->base.link);
904                 drm_vblank_put(dev, e->pipe);
905                 send_vblank_event(dev, e, seq, &now);
906         }
907
908         lockmgr(&dev->event_lock, LK_RELEASE);
909         lockmgr(&dev->vbl_lock, LK_RELEASE);
910 }
911
912 /**
913  * drm_vblank_pre_modeset - account for vblanks across mode sets
914  * @dev: DRM device
915  * @crtc: CRTC in question
916  * @post: post or pre mode set?
917  *
918  * Account for vblank events across mode setting events, which will likely
919  * reset the hardware frame counter.
920  */
921 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
922 {
923         /* vblank is not initialized (IRQ not installed ?) */
924         if (!dev->num_crtcs)
925                 return;
926         /*
927          * To avoid all the problems that might happen if interrupts
928          * were enabled/disabled around or between these calls, we just
929          * have the kernel take a reference on the CRTC (just once though
930          * to avoid corrupting the count if multiple, mismatch calls occur),
931          * so that interrupts remain enabled in the interim.
932          */
933         if (!dev->vblank_inmodeset[crtc]) {
934                 dev->vblank_inmodeset[crtc] = 0x1;
935                 if (drm_vblank_get(dev, crtc) == 0)
936                         dev->vblank_inmodeset[crtc] |= 0x2;
937         }
938 }
939
940 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
941 {
942
943         if (dev->vblank_inmodeset[crtc]) {
944                 lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
945                 dev->vblank_disable_allowed = 1;
946                 lockmgr(&dev->vbl_lock, LK_RELEASE);
947
948                 if (dev->vblank_inmodeset[crtc] & 0x2)
949                         drm_vblank_put(dev, crtc);
950
951                 dev->vblank_inmodeset[crtc] = 0;
952         }
953 }
954
955 /**
956  * drm_modeset_ctl - handle vblank event counter changes across mode switch
957  * @DRM_IOCTL_ARGS: standard ioctl arguments
958  *
959  * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
960  * ioctls around modesetting so that any lost vblank events are accounted for.
961  *
962  * Generally the counter will reset across mode sets.  If interrupts are
963  * enabled around this call, we don't have to do anything since the counter
964  * will have already been incremented.
965  */
966 int drm_modeset_ctl(struct drm_device *dev, void *data,
967                     struct drm_file *file_priv)
968 {
969         struct drm_modeset_ctl *modeset = data;
970         int ret = 0;
971         unsigned int crtc;
972
973         /* If drm_vblank_init() hasn't been called yet, just no-op */
974         if (!dev->num_crtcs)
975                 goto out;
976
977         crtc = modeset->crtc;
978         if (crtc >= dev->num_crtcs) {
979                 ret = -EINVAL;
980                 goto out;
981         }
982
983         switch (modeset->cmd) {
984         case _DRM_PRE_MODESET:
985                 drm_vblank_pre_modeset(dev, crtc);
986                 break;
987         case _DRM_POST_MODESET:
988                 drm_vblank_post_modeset(dev, crtc);
989                 break;
990         default:
991                 ret = -EINVAL;
992                 break;
993         }
994
995 out:
996         return ret;
997 }
998
999 static void
1000 drm_vblank_event_destroy(struct drm_pending_event *e)
1001 {
1002
1003         drm_free(e, DRM_MEM_VBLANK);
1004 }
1005
1006 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
1007                                   union drm_wait_vblank *vblwait,
1008                                   struct drm_file *file_priv)
1009 {
1010         struct drm_pending_vblank_event *e;
1011         struct timeval now;
1012         unsigned int seq;
1013         int ret;
1014
1015         e = kmalloc(sizeof *e, DRM_MEM_VBLANK, M_WAITOK | M_ZERO);
1016
1017         e->pipe = pipe;
1018         e->base.pid = curproc->p_pid;
1019         e->event.base.type = DRM_EVENT_VBLANK;
1020         e->event.base.length = sizeof e->event;
1021         e->event.user_data = vblwait->request.signal;
1022         e->base.event = &e->event.base;
1023         e->base.file_priv = file_priv;
1024         e->base.destroy = drm_vblank_event_destroy;
1025
1026         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1027
1028         if (file_priv->event_space < sizeof e->event) {
1029                 ret = EBUSY;
1030                 goto err_unlock;
1031         }
1032
1033         file_priv->event_space -= sizeof e->event;
1034         seq = drm_vblank_count_and_time(dev, pipe, &now);
1035
1036         if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1037             (seq - vblwait->request.sequence) <= (1 << 23)) {
1038                 vblwait->request.sequence = seq + 1;
1039                 vblwait->reply.sequence = vblwait->request.sequence;
1040         }
1041
1042         DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
1043                   vblwait->request.sequence, seq, pipe);
1044
1045         e->event.sequence = vblwait->request.sequence;
1046         if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1047                 drm_vblank_put(dev, pipe);
1048                 send_vblank_event(dev, e, seq, &now);
1049                 vblwait->reply.sequence = seq;
1050         } else {
1051                 /* drm_handle_vblank_events will call drm_vblank_put */
1052                 list_add_tail(&e->base.link, &dev->vblank_event_list);
1053                 vblwait->reply.sequence = vblwait->request.sequence;
1054         }
1055
1056         lockmgr(&dev->event_lock, LK_RELEASE);
1057
1058         return 0;
1059
1060 err_unlock:
1061         lockmgr(&dev->event_lock, LK_RELEASE);
1062         drm_free(e, DRM_MEM_VBLANK);
1063         drm_vblank_put(dev, pipe);
1064         return ret;
1065 }
1066
1067 /**
1068  * Wait for VBLANK.
1069  *
1070  * \param inode device inode.
1071  * \param file_priv DRM file private.
1072  * \param cmd command.
1073  * \param data user argument, pointing to a drm_wait_vblank structure.
1074  * \return zero on success or a negative number on failure.
1075  *
1076  * This function enables the vblank interrupt on the pipe requested, then
1077  * sleeps waiting for the requested sequence number to occur, and drops
1078  * the vblank interrupt refcount afterwards. (vblank irq disable follows that
1079  * after a timeout with no further vblank waits scheduled).
1080  */
1081 int drm_wait_vblank(struct drm_device *dev, void *data,
1082                     struct drm_file *file_priv)
1083 {
1084         union drm_wait_vblank *vblwait = data;
1085         int ret = 0;
1086         unsigned int flags, seq, crtc, high_crtc;
1087
1088         if (/*(!drm_dev_to_irq(dev)) || */(!dev->irq_enabled))
1089                 return (EINVAL);
1090
1091         if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1092                 return (EINVAL);
1093
1094         if (vblwait->request.type &
1095             ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1096               _DRM_VBLANK_HIGH_CRTC_MASK)) {
1097                 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1098                           vblwait->request.type,
1099                           (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1100                            _DRM_VBLANK_HIGH_CRTC_MASK));
1101                 return (EINVAL);
1102         }
1103
1104         flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1105         high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1106         if (high_crtc)
1107                 crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1108         else
1109                 crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1110         if (crtc >= dev->num_crtcs)
1111                 return (EINVAL);
1112
1113         ret = drm_vblank_get(dev, crtc);
1114         if (ret) {
1115                 DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1116                 return (ret);
1117         }
1118         seq = drm_vblank_count(dev, crtc);
1119
1120         switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1121         case _DRM_VBLANK_RELATIVE:
1122                 vblwait->request.sequence += seq;
1123                 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1124         case _DRM_VBLANK_ABSOLUTE:
1125                 break;
1126         default:
1127                 ret = (EINVAL);
1128                 goto done;
1129         }
1130
1131         if (flags & _DRM_VBLANK_EVENT) {
1132                 /* must hold on to the vblank ref until the event fires
1133                  * drm_vblank_put will be called asynchronously
1134                  */
1135                 return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
1136         }
1137
1138         if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1139             (seq - vblwait->request.sequence) <= (1<<23)) {
1140                 vblwait->request.sequence = seq + 1;
1141         }
1142
1143         dev->last_vblank_wait[crtc] = vblwait->request.sequence;
1144         lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1145         while (((drm_vblank_count(dev, crtc) - vblwait->request.sequence) >
1146             (1 << 23)) && dev->irq_enabled) {
1147                 /*
1148                  * The wakeups from the drm_irq_uninstall() and
1149                  * drm_vblank_off() may be lost there since vbl_lock
1150                  * is not held.  Then, the timeout will wake us; the 3
1151                  * seconds delay should not be a problem for
1152                  * application when crtc is disabled or irq
1153                  * uninstalled anyway.
1154                  */
1155                 ret = lksleep(&dev->_vblank_count[crtc], &dev->vblank_time_lock,
1156                     PCATCH, "drmvbl", 3 * hz);
1157                 if (ret != 0)
1158                         break;
1159         }
1160         lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1161         if (ret != EINTR) {
1162                 struct timeval now;
1163                 long reply_seq;
1164
1165                 reply_seq = drm_vblank_count_and_time(dev, crtc, &now);
1166                 vblwait->reply.sequence = reply_seq;
1167                 vblwait->reply.tval_sec = now.tv_sec;
1168                 vblwait->reply.tval_usec = now.tv_usec;
1169         }
1170
1171 done:
1172         drm_vblank_put(dev, crtc);
1173         return ret;
1174 }
1175
1176 void drm_handle_vblank_events(struct drm_device *dev, int crtc)
1177 {
1178         struct drm_pending_vblank_event *e, *t;
1179         struct timeval now;
1180         unsigned int seq;
1181
1182         seq = drm_vblank_count_and_time(dev, crtc, &now);
1183
1184         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1185
1186         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1187                 if (e->pipe != crtc)
1188                         continue;
1189                 if ((seq - e->event.sequence) > (1<<23))
1190                         continue;
1191
1192                 DRM_DEBUG("vblank event on %d, current %d\n",
1193                           e->event.sequence, seq);
1194
1195                 list_del(&e->base.link);
1196                 drm_vblank_put(dev, e->pipe);
1197                 send_vblank_event(dev, e, seq, &now);
1198         }
1199
1200         lockmgr(&dev->event_lock, LK_RELEASE);
1201 }
1202
1203 /**
1204  * drm_handle_vblank - handle a vblank event
1205  * @dev: DRM device
1206  * @crtc: where this event occurred
1207  *
1208  * Drivers should call this routine in their vblank interrupt handlers to
1209  * update the vblank counter and send any signals that may be pending.
1210  */
1211 bool drm_handle_vblank(struct drm_device *dev, int crtc)
1212 {
1213         u32 vblcount;
1214         int64_t diff_ns;
1215         struct timeval tvblank;
1216
1217         if (!dev->num_crtcs)
1218                 return false;
1219
1220         /* Need timestamp lock to prevent concurrent execution with
1221          * vblank enable/disable, as this would cause inconsistent
1222          * or corrupted timestamps and vblank counts.
1223          */
1224         lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1225
1226         /* Vblank irq handling disabled. Nothing to do. */
1227         if (!dev->vblank_enabled[crtc]) {
1228                 lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1229                 return false;
1230         }
1231
1232         /* Fetch corresponding timestamp for this vblank interval from
1233          * driver and store it in proper slot of timestamp ringbuffer.
1234          */
1235
1236         /* Get current timestamp and count. */
1237         vblcount = atomic_read(&dev->_vblank_count[crtc]);
1238         drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1239
1240         /* Compute time difference to timestamp of last vblank */
1241         diff_ns = timeval_to_ns(&tvblank) -
1242                   timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1243
1244         /* Update vblank timestamp and count if at least
1245          * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1246          * difference between last stored timestamp and current
1247          * timestamp. A smaller difference means basically
1248          * identical timestamps. Happens if this vblank has
1249          * been already processed and this is a redundant call,
1250          * e.g., due to spurious vblank interrupts. We need to
1251          * ignore those for accounting.
1252          */
1253         if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
1254                 /* Store new timestamp in ringbuffer. */
1255                 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
1256
1257                 /* Increment cooked vblank count. This also atomically commits
1258                  * the timestamp computed above.
1259                  */
1260                 atomic_inc(&dev->_vblank_count[crtc]);
1261         } else {
1262                 DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1263                           crtc, (int) diff_ns);
1264         }
1265
1266         wakeup(&dev->_vblank_count[crtc]);
1267         drm_handle_vblank_events(dev, crtc);
1268
1269         lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1270         return true;
1271 }