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