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