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