xref: /dragonfly/sys/dev/drm/drm_irq.c (revision 66b13f02)
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 #if 0
852 	trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
853 					 e->event.sequence);
854 #endif
855 }
856 
857 /**
858  * drm_send_vblank_event - helper to send vblank event after pageflip
859  * @dev: DRM device
860  * @crtc: CRTC in question
861  * @e: the event to send
862  *
863  * Updates sequence # and timestamp on event, and sends it to userspace.
864  * Caller must hold event lock.
865  */
866 void drm_send_vblank_event(struct drm_device *dev, int crtc,
867 		struct drm_pending_vblank_event *e)
868 {
869 	struct timeval now;
870 	unsigned int seq;
871 	if (crtc >= 0) {
872 		seq = drm_vblank_count_and_time(dev, crtc, &now);
873 	} else {
874 		seq = 0;
875 
876 		now = get_drm_timestamp();
877 	}
878 	e->pipe = crtc;
879 	send_vblank_event(dev, e, seq, &now);
880 }
881 EXPORT_SYMBOL(drm_send_vblank_event);
882 
883 /**
884  * drm_vblank_enable - enable the vblank interrupt on a CRTC
885  * @dev: DRM device
886  * @crtc: CRTC in question
887  */
888 static int drm_vblank_enable(struct drm_device *dev, int crtc)
889 {
890 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
891 	int ret = 0;
892 
893 	assert_spin_locked(&dev->vbl_lock);
894 
895 	lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
896 
897 	if (!vblank->enabled) {
898 		/*
899 		 * Enable vblank irqs under vblank_time_lock protection.
900 		 * All vblank count & timestamp updates are held off
901 		 * until we are done reinitializing master counter and
902 		 * timestamps. Filtercode in drm_handle_vblank() will
903 		 * prevent double-accounting of same vblank interval.
904 		 */
905 		ret = dev->driver->enable_vblank(dev, crtc);
906 		DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n", crtc, ret);
907 		if (ret)
908 			atomic_dec(&vblank->refcount);
909 		else {
910 			vblank->enabled = true;
911 			drm_update_vblank_count(dev, crtc);
912 		}
913 	}
914 
915 	lockmgr(&dev->vblank_time_lock, LK_RELEASE);
916 
917 	return ret;
918 }
919 
920 /**
921  * drm_vblank_get - get a reference count on vblank events
922  * @dev: DRM device
923  * @crtc: which CRTC to own
924  *
925  * Acquire a reference count on vblank events to avoid having them disabled
926  * while in use.
927  *
928  * This is the legacy version of drm_crtc_vblank_get().
929  *
930  * Returns:
931  * Zero on success, nonzero on failure.
932  */
933 int drm_vblank_get(struct drm_device *dev, int crtc)
934 {
935 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
936 	int ret = 0;
937 
938 	lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
939 	/* Going from 0->1 means we have to enable interrupts again */
940 	if (atomic_add_return(1, &vblank->refcount) == 1) {
941 		ret = drm_vblank_enable(dev, crtc);
942 	} else {
943 		if (!vblank->enabled) {
944 			atomic_dec(&vblank->refcount);
945 			ret = -EINVAL;
946 		}
947 	}
948 	lockmgr(&dev->vbl_lock, LK_RELEASE);
949 
950 	return ret;
951 }
952 EXPORT_SYMBOL(drm_vblank_get);
953 
954 /**
955  * drm_crtc_vblank_get - get a reference count on vblank events
956  * @crtc: which CRTC to own
957  *
958  * Acquire a reference count on vblank events to avoid having them disabled
959  * while in use.
960  *
961  * This is the native kms version of drm_vblank_off().
962  *
963  * Returns:
964  * Zero on success, nonzero on failure.
965  */
966 int drm_crtc_vblank_get(struct drm_crtc *crtc)
967 {
968 	return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
969 }
970 EXPORT_SYMBOL(drm_crtc_vblank_get);
971 
972 /**
973  * drm_vblank_put - give up ownership of vblank events
974  * @dev: DRM device
975  * @crtc: which counter to give up
976  *
977  * Release ownership of a given vblank counter, turning off interrupts
978  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
979  *
980  * This is the legacy version of drm_crtc_vblank_put().
981  */
982 void drm_vblank_put(struct drm_device *dev, int crtc)
983 {
984 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
985 
986 	BUG_ON(atomic_read(&vblank->refcount) == 0);
987 
988 	/* Last user schedules interrupt disable */
989 	if (atomic_dec_and_test(&vblank->refcount) &&
990 	    (drm_vblank_offdelay > 0))
991 		mod_timer(&vblank->disable_timer,
992 			  jiffies + ((drm_vblank_offdelay * HZ)/1000));
993 }
994 EXPORT_SYMBOL(drm_vblank_put);
995 
996 /**
997  * drm_crtc_vblank_put - give up ownership of vblank events
998  * @crtc: which counter to give up
999  *
1000  * Release ownership of a given vblank counter, turning off interrupts
1001  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1002  *
1003  * This is the native kms version of drm_vblank_put().
1004  */
1005 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1006 {
1007 	drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1008 }
1009 EXPORT_SYMBOL(drm_crtc_vblank_put);
1010 
1011 /**
1012  * drm_vblank_off - disable vblank events on a CRTC
1013  * @dev: DRM device
1014  * @crtc: CRTC in question
1015  *
1016  * Drivers can use this function to shut down the vblank interrupt handling when
1017  * disabling a crtc. This function ensures that the latest vblank frame count is
1018  * stored so that drm_vblank_on() can restore it again.
1019  *
1020  * Drivers must use this function when the hardware vblank counter can get
1021  * reset, e.g. when suspending.
1022  *
1023  * This is the legacy version of drm_crtc_vblank_off().
1024  */
1025 void drm_vblank_off(struct drm_device *dev, int crtc)
1026 {
1027 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1028 	struct drm_pending_vblank_event *e, *t;
1029 	struct timeval now;
1030 	unsigned int seq;
1031 
1032 	lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1033 
1034 	lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
1035 	vblank_disable_and_save(dev, crtc);
1036 	wake_up(&vblank->queue);
1037 
1038 	/*
1039 	 * Prevent subsequent drm_vblank_get() from re-enabling
1040 	 * the vblank interrupt by bumping the refcount.
1041 	 */
1042 	if (!vblank->inmodeset) {
1043 		atomic_inc(&vblank->refcount);
1044 		vblank->inmodeset = 1;
1045 	}
1046 	lockmgr(&dev->vbl_lock, LK_RELEASE);
1047 
1048 	/* Send any queued vblank events, lest the natives grow disquiet */
1049 	seq = drm_vblank_count_and_time(dev, crtc, &now);
1050 
1051 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1052 		if (e->pipe != crtc)
1053 			continue;
1054 		DRM_DEBUG("Sending premature vblank event on disable: \
1055 			  wanted %d, current %d\n",
1056 			  e->event.sequence, seq);
1057 		list_del(&e->base.link);
1058 		drm_vblank_put(dev, e->pipe);
1059 		send_vblank_event(dev, e, seq, &now);
1060 	}
1061 	lockmgr(&dev->event_lock, LK_RELEASE);
1062 }
1063 EXPORT_SYMBOL(drm_vblank_off);
1064 
1065 /**
1066  * drm_crtc_vblank_off - disable vblank events on a CRTC
1067  * @crtc: CRTC in question
1068  *
1069  * Drivers can use this function to shut down the vblank interrupt handling when
1070  * disabling a crtc. This function ensures that the latest vblank frame count is
1071  * stored so that drm_vblank_on can restore it again.
1072  *
1073  * Drivers must use this function when the hardware vblank counter can get
1074  * reset, e.g. when suspending.
1075  *
1076  * This is the native kms version of drm_vblank_off().
1077  */
1078 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1079 {
1080 	drm_vblank_off(crtc->dev, drm_crtc_index(crtc));
1081 }
1082 EXPORT_SYMBOL(drm_crtc_vblank_off);
1083 
1084 /**
1085  * drm_vblank_on - enable vblank events on a CRTC
1086  * @dev: DRM device
1087  * @crtc: CRTC in question
1088  *
1089  * This functions restores the vblank interrupt state captured with
1090  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1091  * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1092  * in driver load code to reflect the current hardware state of the crtc.
1093  *
1094  * This is the legacy version of drm_crtc_vblank_on().
1095  */
1096 void drm_vblank_on(struct drm_device *dev, int crtc)
1097 {
1098 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1099 
1100 	lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
1101 	/* Drop our private "prevent drm_vblank_get" refcount */
1102 	if (vblank->inmodeset) {
1103 		atomic_dec(&vblank->refcount);
1104 		vblank->inmodeset = 0;
1105 	}
1106 
1107 	/*
1108 	 * sample the current counter to avoid random jumps
1109 	 * when drm_vblank_enable() applies the diff
1110 	 *
1111 	 * -1 to make sure user will never see the same
1112 	 * vblank counter value before and after a modeset
1113 	 */
1114 	vblank->last =
1115 		(dev->driver->get_vblank_counter(dev, crtc) - 1) &
1116 		dev->max_vblank_count;
1117 
1118 	/* re-enable interrupts if there's are users left */
1119 	if (atomic_read(&vblank->refcount) != 0)
1120 		WARN_ON(drm_vblank_enable(dev, crtc));
1121 	lockmgr(&dev->vbl_lock, LK_RELEASE);
1122 }
1123 EXPORT_SYMBOL(drm_vblank_on);
1124 
1125 /**
1126  * drm_crtc_vblank_on - enable vblank events on a CRTC
1127  * @crtc: CRTC in question
1128  *
1129  * This functions restores the vblank interrupt state captured with
1130  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1131  * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1132  * in driver load code to reflect the current hardware state of the crtc.
1133  *
1134  * This is the native kms version of drm_vblank_on().
1135  */
1136 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1137 {
1138 	drm_vblank_on(crtc->dev, drm_crtc_index(crtc));
1139 }
1140 EXPORT_SYMBOL(drm_crtc_vblank_on);
1141 
1142 /**
1143  * drm_vblank_pre_modeset - account for vblanks across mode sets
1144  * @dev: DRM device
1145  * @crtc: CRTC in question
1146  *
1147  * Account for vblank events across mode setting events, which will likely
1148  * reset the hardware frame counter.
1149  *
1150  * This is done by grabbing a temporary vblank reference to ensure that the
1151  * vblank interrupt keeps running across the modeset sequence. With this the
1152  * software-side vblank frame counting will ensure that there are no jumps or
1153  * discontinuities.
1154  *
1155  * Unfortunately this approach is racy and also doesn't work when the vblank
1156  * interrupt stops running, e.g. across system suspend resume. It is therefore
1157  * highly recommended that drivers use the newer drm_vblank_off() and
1158  * drm_vblank_on() instead. drm_vblank_pre_modeset() only works correctly when
1159  * using "cooked" software vblank frame counters and not relying on any hardware
1160  * counters.
1161  *
1162  * Drivers must call drm_vblank_post_modeset() when re-enabling the same crtc
1163  * again.
1164  */
1165 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
1166 {
1167 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1168 
1169 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
1170 	if (!dev->num_crtcs)
1171 		return;
1172 	/*
1173 	 * To avoid all the problems that might happen if interrupts
1174 	 * were enabled/disabled around or between these calls, we just
1175 	 * have the kernel take a reference on the CRTC (just once though
1176 	 * to avoid corrupting the count if multiple, mismatch calls occur),
1177 	 * so that interrupts remain enabled in the interim.
1178 	 */
1179 	if (!vblank->inmodeset) {
1180 		vblank->inmodeset = 0x1;
1181 		if (drm_vblank_get(dev, crtc) == 0)
1182 			vblank->inmodeset |= 0x2;
1183 	}
1184 }
1185 EXPORT_SYMBOL(drm_vblank_pre_modeset);
1186 
1187 /**
1188  * drm_vblank_post_modeset - undo drm_vblank_pre_modeset changes
1189  * @dev: DRM device
1190  * @crtc: CRTC in question
1191  *
1192  * This function again drops the temporary vblank reference acquired in
1193  * drm_vblank_pre_modeset.
1194  */
1195 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
1196 {
1197 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1198 
1199 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
1200 	if (!dev->num_crtcs)
1201 		return;
1202 
1203 	if (vblank->inmodeset) {
1204 		lockmgr(&dev->vbl_lock, LK_EXCLUSIVE);
1205 		dev->vblank_disable_allowed = true;
1206 		lockmgr(&dev->vbl_lock, LK_RELEASE);
1207 
1208 		if (vblank->inmodeset & 0x2)
1209 			drm_vblank_put(dev, crtc);
1210 
1211 		vblank->inmodeset = 0;
1212 	}
1213 }
1214 EXPORT_SYMBOL(drm_vblank_post_modeset);
1215 
1216 /*
1217  * drm_modeset_ctl - handle vblank event counter changes across mode switch
1218  * @DRM_IOCTL_ARGS: standard ioctl arguments
1219  *
1220  * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
1221  * ioctls around modesetting so that any lost vblank events are accounted for.
1222  *
1223  * Generally the counter will reset across mode sets.  If interrupts are
1224  * enabled around this call, we don't have to do anything since the counter
1225  * will have already been incremented.
1226  */
1227 int drm_modeset_ctl(struct drm_device *dev, void *data,
1228 		    struct drm_file *file_priv)
1229 {
1230 	struct drm_modeset_ctl *modeset = data;
1231 	unsigned int crtc;
1232 
1233 	/* If drm_vblank_init() hasn't been called yet, just no-op */
1234 	if (!dev->num_crtcs)
1235 		return 0;
1236 
1237 	/* KMS drivers handle this internally */
1238 	if (drm_core_check_feature(dev, DRIVER_MODESET))
1239 		return 0;
1240 
1241 	crtc = modeset->crtc;
1242 	if (crtc >= dev->num_crtcs)
1243 		return -EINVAL;
1244 
1245 	switch (modeset->cmd) {
1246 	case _DRM_PRE_MODESET:
1247 		drm_vblank_pre_modeset(dev, crtc);
1248 		break;
1249 	case _DRM_POST_MODESET:
1250 		drm_vblank_post_modeset(dev, crtc);
1251 		break;
1252 	default:
1253 		return -EINVAL;
1254 	}
1255 
1256 	return 0;
1257 }
1258 
1259 /* DragonFly-specific */
1260 static void
1261 drm_vblank_event_destroy(struct drm_pending_event *e)
1262 {
1263 	kfree(e);
1264 }
1265 
1266 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
1267 				  union drm_wait_vblank *vblwait,
1268 				  struct drm_file *file_priv)
1269 {
1270 	struct drm_pending_vblank_event *e;
1271 	struct timeval now;
1272 	unsigned int seq;
1273 	int ret;
1274 
1275 	e = kzalloc(sizeof *e, GFP_KERNEL);
1276 	if (e == NULL) {
1277 		ret = -ENOMEM;
1278 		goto err_put;
1279 	}
1280 
1281 	e->pipe = pipe;
1282 	e->base.pid = curproc->p_pid;
1283 	e->event.base.type = DRM_EVENT_VBLANK;
1284 	e->event.base.length = sizeof e->event;
1285 	e->event.user_data = vblwait->request.signal;
1286 	e->base.event = &e->event.base;
1287 	e->base.file_priv = file_priv;
1288 	e->base.destroy = drm_vblank_event_destroy;
1289 
1290 	lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1291 
1292 	if (file_priv->event_space < sizeof e->event) {
1293 		ret = -EBUSY;
1294 		goto err_unlock;
1295 	}
1296 
1297 	file_priv->event_space -= sizeof e->event;
1298 	seq = drm_vblank_count_and_time(dev, pipe, &now);
1299 
1300 	if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1301 	    (seq - vblwait->request.sequence) <= (1 << 23)) {
1302 		vblwait->request.sequence = seq + 1;
1303 		vblwait->reply.sequence = vblwait->request.sequence;
1304 	}
1305 
1306 	DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
1307 		  vblwait->request.sequence, seq, pipe);
1308 
1309 #if 0
1310 	trace_drm_vblank_event_queued(current->pid, pipe,
1311 				      vblwait->request.sequence);
1312 #endif
1313 
1314 	e->event.sequence = vblwait->request.sequence;
1315 	if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1316 		drm_vblank_put(dev, pipe);
1317 		send_vblank_event(dev, e, seq, &now);
1318 		vblwait->reply.sequence = seq;
1319 	} else {
1320 		/* drm_handle_vblank_events will call drm_vblank_put */
1321 		list_add_tail(&e->base.link, &dev->vblank_event_list);
1322 		vblwait->reply.sequence = vblwait->request.sequence;
1323 	}
1324 
1325 	lockmgr(&dev->event_lock, LK_RELEASE);
1326 
1327 	return 0;
1328 
1329 err_unlock:
1330 	lockmgr(&dev->event_lock, LK_RELEASE);
1331 	kfree(e);
1332 err_put:
1333 	drm_vblank_put(dev, pipe);
1334 	return ret;
1335 }
1336 
1337 /*
1338  * Wait for VBLANK.
1339  *
1340  * \param inode device inode.
1341  * \param file_priv DRM file private.
1342  * \param cmd command.
1343  * \param data user argument, pointing to a drm_wait_vblank structure.
1344  * \return zero on success or a negative number on failure.
1345  *
1346  * This function enables the vblank interrupt on the pipe requested, then
1347  * sleeps waiting for the requested sequence number to occur, and drops
1348  * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
1349  * after a timeout with no further vblank waits scheduled).
1350  */
1351 int drm_wait_vblank(struct drm_device *dev, void *data,
1352 		    struct drm_file *file_priv)
1353 {
1354 	struct drm_vblank_crtc *vblank;
1355 	union drm_wait_vblank *vblwait = data;
1356 	int ret;
1357 	unsigned int flags, seq, crtc, high_crtc;
1358 
1359 	if (!dev->irq_enabled)
1360 		return -EINVAL;
1361 
1362 	if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1363 		return -EINVAL;
1364 
1365 	if (vblwait->request.type &
1366 	    ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1367 	      _DRM_VBLANK_HIGH_CRTC_MASK)) {
1368 		DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1369 			  vblwait->request.type,
1370 			  (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1371 			   _DRM_VBLANK_HIGH_CRTC_MASK));
1372 		return -EINVAL;
1373 	}
1374 
1375 	flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1376 	high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1377 	if (high_crtc)
1378 		crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1379 	else
1380 		crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1381 	if (crtc >= dev->num_crtcs)
1382 		return -EINVAL;
1383 
1384 	vblank = &dev->vblank[crtc];
1385 
1386 	ret = drm_vblank_get(dev, crtc);
1387 	if (ret) {
1388 		DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1389 		return ret;
1390 	}
1391 	seq = drm_vblank_count(dev, crtc);
1392 
1393 	switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1394 	case _DRM_VBLANK_RELATIVE:
1395 		vblwait->request.sequence += seq;
1396 		vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1397 	case _DRM_VBLANK_ABSOLUTE:
1398 		break;
1399 	default:
1400 		ret = -EINVAL;
1401 		goto done;
1402 	}
1403 
1404 	if (flags & _DRM_VBLANK_EVENT) {
1405 		/* must hold on to the vblank ref until the event fires
1406 		 * drm_vblank_put will be called asynchronously
1407 		 */
1408 		return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
1409 	}
1410 
1411 	if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1412 	    (seq - vblwait->request.sequence) <= (1<<23)) {
1413 		vblwait->request.sequence = seq + 1;
1414 	}
1415 
1416 	DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
1417 		  vblwait->request.sequence, crtc);
1418 	vblank->last_wait = vblwait->request.sequence;
1419 	DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1420 		    (((drm_vblank_count(dev, crtc) -
1421 		       vblwait->request.sequence) <= (1 << 23)) ||
1422 		     !vblank->enabled ||
1423 		     !dev->irq_enabled));
1424 
1425 	if (ret != -EINTR) {
1426 		struct timeval now;
1427 
1428 		vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
1429 		vblwait->reply.tval_sec = now.tv_sec;
1430 		vblwait->reply.tval_usec = now.tv_usec;
1431 
1432 		DRM_DEBUG("returning %d to client\n",
1433 			  vblwait->reply.sequence);
1434 	} else {
1435 		DRM_DEBUG("vblank wait interrupted by signal\n");
1436 	}
1437 
1438 done:
1439 	drm_vblank_put(dev, crtc);
1440 	return ret;
1441 }
1442 
1443 static void drm_handle_vblank_events(struct drm_device *dev, int crtc)
1444 {
1445 	struct drm_pending_vblank_event *e, *t;
1446 	struct timeval now;
1447 	unsigned int seq;
1448 
1449 
1450 	seq = drm_vblank_count_and_time(dev, crtc, &now);
1451 
1452 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1453 		if (e->pipe != crtc)
1454 			continue;
1455 		if ((seq - e->event.sequence) > (1<<23))
1456 			continue;
1457 
1458 		DRM_DEBUG("vblank event on %d, current %d\n",
1459 			  e->event.sequence, seq);
1460 
1461 		list_del(&e->base.link);
1462 		drm_vblank_put(dev, e->pipe);
1463 		send_vblank_event(dev, e, seq, &now);
1464 	}
1465 
1466 #if 0
1467 	trace_drm_vblank_event(crtc, seq);
1468 #endif
1469 }
1470 
1471 /**
1472  * drm_handle_vblank - handle a vblank event
1473  * @dev: DRM device
1474  * @crtc: where this event occurred
1475  *
1476  * Drivers should call this routine in their vblank interrupt handlers to
1477  * update the vblank counter and send any signals that may be pending.
1478  */
1479 bool drm_handle_vblank(struct drm_device *dev, int crtc)
1480 {
1481 	struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1482 	u32 vblcount;
1483 	s64 diff_ns;
1484 	struct timeval tvblank;
1485 
1486 	if (!dev->num_crtcs)
1487 		return false;
1488 
1489 	lockmgr(&dev->event_lock, LK_EXCLUSIVE);
1490 
1491 	/* Need timestamp lock to prevent concurrent execution with
1492 	 * vblank enable/disable, as this would cause inconsistent
1493 	 * or corrupted timestamps and vblank counts.
1494 	 */
1495 	lockmgr(&dev->vblank_time_lock, LK_EXCLUSIVE);
1496 
1497 	/* Vblank irq handling disabled. Nothing to do. */
1498 	if (!vblank->enabled) {
1499 		lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1500 		lockmgr(&dev->event_lock, LK_RELEASE);
1501 		return false;
1502 	}
1503 
1504 	/* Fetch corresponding timestamp for this vblank interval from
1505 	 * driver and store it in proper slot of timestamp ringbuffer.
1506 	 */
1507 
1508 	/* Get current timestamp and count. */
1509 	vblcount = atomic_read(&vblank->count);
1510 	drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1511 
1512 	/* Compute time difference to timestamp of last vblank */
1513 	diff_ns = timeval_to_ns(&tvblank) -
1514 		  timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1515 
1516 	/* Update vblank timestamp and count if at least
1517 	 * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1518 	 * difference between last stored timestamp and current
1519 	 * timestamp. A smaller difference means basically
1520 	 * identical timestamps. Happens if this vblank has
1521 	 * been already processed and this is a redundant call,
1522 	 * e.g., due to spurious vblank interrupts. We need to
1523 	 * ignore those for accounting.
1524 	 */
1525 	if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
1526 		/* Store new timestamp in ringbuffer. */
1527 		vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
1528 
1529 		/* Increment cooked vblank count. This also atomically commits
1530 		 * the timestamp computed above.
1531 		 */
1532 		smp_mb__before_atomic();
1533 		atomic_inc(&vblank->count);
1534 		smp_mb__after_atomic();
1535 	} else {
1536 		DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1537 			  crtc, (int) diff_ns);
1538 	}
1539 
1540 	lockmgr(&dev->vblank_time_lock, LK_RELEASE);
1541 
1542 	wake_up(&vblank->queue);
1543 	drm_handle_vblank_events(dev, crtc);
1544 
1545 	lockmgr(&dev->event_lock, LK_RELEASE);
1546 
1547 	return true;
1548 }
1549 EXPORT_SYMBOL(drm_handle_vblank);
1550