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