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