xref: /openbsd-src/sys/dev/pci/drm/drm_irq.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
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 <dev/pci/drm/drmP.h>
36 #include "drm_trace.h"
37 #include "drm_internal.h"
38 
39 #ifdef __linux__
40 #include <linux/interrupt.h>	/* For task queue support */
41 #include <linux/slab.h>
42 
43 #include <linux/vgaarb.h>
44 #include <linux/export.h>
45 #endif
46 
47 /* Access macro for slots in vblank timestamp ringbuffer. */
48 #define vblanktimestamp(dev, pipe, count) \
49 	((dev)->vblank[pipe].time[(count) % DRM_VBLANKTIME_RBSIZE])
50 
51 /* Retry timestamp calculation up to 3 times to satisfy
52  * drm_timestamp_precision before giving up.
53  */
54 #define DRM_TIMESTAMP_MAXRETRIES 3
55 
56 /* Threshold in nanoseconds for detection of redundant
57  * vblank irq in drm_handle_vblank(). 1 msec should be ok.
58  */
59 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
60 
61 static bool
62 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
63 			  struct timeval *tvblank, unsigned flags);
64 
65 static unsigned int drm_timestamp_precision = 20;  /* Default to 20 usecs. */
66 
67 /*
68  * Default to use monotonic timestamps for wait-for-vblank and page-flip
69  * complete events.
70  */
71 unsigned int drm_timestamp_monotonic = 1;
72 
73 static int drm_vblank_offdelay = 5000;    /* Default to 5000 msecs. */
74 
75 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
76 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
77 module_param_named(timestamp_monotonic, drm_timestamp_monotonic, int, 0600);
78 
79 static void store_vblank(struct drm_device *dev, unsigned int pipe,
80 			 u32 vblank_count_inc,
81 			 struct timeval *t_vblank, u32 last)
82 {
83 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
84 	u32 tslot;
85 
86 	assert_spin_locked(&dev->vblank_time_lock);
87 
88 	vblank->last = last;
89 
90 	/* All writers hold the spinlock, but readers are serialized by
91 	 * the latching of vblank->count below.
92 	 */
93 	tslot = vblank->count + vblank_count_inc;
94 	vblanktimestamp(dev, pipe, tslot) = *t_vblank;
95 
96 	/*
97 	 * vblank timestamp updates are protected on the write side with
98 	 * vblank_time_lock, but on the read side done locklessly using a
99 	 * sequence-lock on the vblank counter. Ensure correct ordering using
100 	 * memory barrriers. We need the barrier both before and also after the
101 	 * counter update to synchronize with the next timestamp write.
102 	 * The read-side barriers for this are in drm_vblank_count_and_time.
103 	 */
104 	smp_wmb();
105 	vblank->count += vblank_count_inc;
106 	smp_wmb();
107 }
108 
109 /**
110  * drm_reset_vblank_timestamp - reset the last timestamp to the last vblank
111  * @dev: DRM device
112  * @pipe: index of CRTC for which to reset the timestamp
113  *
114  * Reset the stored timestamp for the current vblank count to correspond
115  * to the last vblank occurred.
116  *
117  * Only to be called from drm_vblank_on().
118  *
119  * Note: caller must hold dev->vbl_lock since this reads & writes
120  * device vblank fields.
121  */
122 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
123 {
124 	u32 cur_vblank;
125 	bool rc;
126 	struct timeval t_vblank;
127 	int count = DRM_TIMESTAMP_MAXRETRIES;
128 
129 	spin_lock(&dev->vblank_time_lock);
130 
131 	/*
132 	 * sample the current counter to avoid random jumps
133 	 * when drm_vblank_enable() applies the diff
134 	 */
135 	do {
136 		cur_vblank = dev->driver->get_vblank_counter(dev, pipe);
137 		rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, 0);
138 	} while (cur_vblank != dev->driver->get_vblank_counter(dev, pipe) && --count > 0);
139 
140 	/*
141 	 * Only reinitialize corresponding vblank timestamp if high-precision query
142 	 * available and didn't fail. Otherwise reinitialize delayed at next vblank
143 	 * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
144 	 */
145 	if (!rc)
146 		t_vblank = (struct timeval) {0, 0};
147 
148 	/*
149 	 * +1 to make sure user will never see the same
150 	 * vblank counter value before and after a modeset
151 	 */
152 	store_vblank(dev, pipe, 1, &t_vblank, cur_vblank);
153 
154 	spin_unlock(&dev->vblank_time_lock);
155 }
156 
157 /**
158  * drm_update_vblank_count - update the master vblank counter
159  * @dev: DRM device
160  * @pipe: counter to update
161  *
162  * Call back into the driver to update the appropriate vblank counter
163  * (specified by @pipe).  Deal with wraparound, if it occurred, and
164  * update the last read value so we can deal with wraparound on the next
165  * call if necessary.
166  *
167  * Only necessary when going from off->on, to account for frames we
168  * didn't get an interrupt for.
169  *
170  * Note: caller must hold dev->vbl_lock since this reads & writes
171  * device vblank fields.
172  */
173 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
174 				    unsigned long flags)
175 {
176 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
177 	u32 cur_vblank, diff;
178 	bool rc;
179 	struct timeval t_vblank;
180 	int count = DRM_TIMESTAMP_MAXRETRIES;
181 	int framedur_ns = vblank->framedur_ns;
182 
183 	/*
184 	 * Interrupts were disabled prior to this call, so deal with counter
185 	 * wrap if needed.
186 	 * NOTE!  It's possible we lost a full dev->max_vblank_count + 1 events
187 	 * here if the register is small or we had vblank interrupts off for
188 	 * a long time.
189 	 *
190 	 * We repeat the hardware vblank counter & timestamp query until
191 	 * we get consistent results. This to prevent races between gpu
192 	 * updating its hardware counter while we are retrieving the
193 	 * corresponding vblank timestamp.
194 	 */
195 	do {
196 		cur_vblank = dev->driver->get_vblank_counter(dev, pipe);
197 		rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, flags);
198 	} while (cur_vblank != dev->driver->get_vblank_counter(dev, pipe) && --count > 0);
199 
200 	if (dev->max_vblank_count != 0) {
201 		/* trust the hw counter when it's around */
202 		diff = (cur_vblank - vblank->last) & dev->max_vblank_count;
203 	} else if (rc && framedur_ns) {
204 		const struct timeval *t_old;
205 		u64 diff_ns;
206 
207 		t_old = &vblanktimestamp(dev, pipe, vblank->count);
208 		diff_ns = timeval_to_ns(&t_vblank) - timeval_to_ns(t_old);
209 
210 		/*
211 		 * Figure out how many vblanks we've missed based
212 		 * on the difference in the timestamps and the
213 		 * frame/field duration.
214 		 */
215 		diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
216 
217 		if (diff == 0 && flags & DRM_CALLED_FROM_VBLIRQ)
218 			DRM_DEBUG_VBL("crtc %u: Redundant vblirq ignored."
219 				      " diff_ns = %lld, framedur_ns = %d)\n",
220 				      pipe, (long long) diff_ns, framedur_ns);
221 	} else {
222 		/* some kind of default for drivers w/o accurate vbl timestamping */
223 		diff = (flags & DRM_CALLED_FROM_VBLIRQ) != 0;
224 	}
225 
226 	/*
227 	 * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
228 	 * interval? If so then vblank irqs keep running and it will likely
229 	 * happen that the hardware vblank counter is not trustworthy as it
230 	 * might reset at some point in that interval and vblank timestamps
231 	 * are not trustworthy either in that interval. Iow. this can result
232 	 * in a bogus diff >> 1 which must be avoided as it would cause
233 	 * random large forward jumps of the software vblank counter.
234 	 */
235 	if (diff > 1 && (vblank->inmodeset & 0x2)) {
236 		DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u"
237 			      " due to pre-modeset.\n", pipe, diff);
238 		diff = 1;
239 	}
240 
241 	/*
242 	 * FIMXE: Need to replace this hack with proper seqlocks.
243 	 *
244 	 * Restrict the bump of the software vblank counter to a safe maximum
245 	 * value of +1 whenever there is the possibility that concurrent readers
246 	 * of vblank timestamps could be active at the moment, as the current
247 	 * implementation of the timestamp caching and updating is not safe
248 	 * against concurrent readers for calls to store_vblank() with a bump
249 	 * of anything but +1. A bump != 1 would very likely return corrupted
250 	 * timestamps to userspace, because the same slot in the cache could
251 	 * be concurrently written by store_vblank() and read by one of those
252 	 * readers without the read-retry logic detecting the collision.
253 	 *
254 	 * Concurrent readers can exist when we are called from the
255 	 * drm_vblank_off() or drm_vblank_on() functions and other non-vblank-
256 	 * irq callers. However, all those calls to us are happening with the
257 	 * vbl_lock locked to prevent drm_vblank_get(), so the vblank refcount
258 	 * can't increase while we are executing. Therefore a zero refcount at
259 	 * this point is safe for arbitrary counter bumps if we are called
260 	 * outside vblank irq, a non-zero count is not 100% safe. Unfortunately
261 	 * we must also accept a refcount of 1, as whenever we are called from
262 	 * drm_vblank_get() -> drm_vblank_enable() the refcount will be 1 and
263 	 * we must let that one pass through in order to not lose vblank counts
264 	 * during vblank irq off - which would completely defeat the whole
265 	 * point of this routine.
266 	 *
267 	 * Whenever we are called from vblank irq, we have to assume concurrent
268 	 * readers exist or can show up any time during our execution, even if
269 	 * the refcount is currently zero, as vblank irqs are usually only
270 	 * enabled due to the presence of readers, and because when we are called
271 	 * from vblank irq we can't hold the vbl_lock to protect us from sudden
272 	 * bumps in vblank refcount. Therefore also restrict bumps to +1 when
273 	 * called from vblank irq.
274 	 */
275 	if ((diff > 1) && (atomic_read(&vblank->refcount) > 1 ||
276 	    (flags & DRM_CALLED_FROM_VBLIRQ))) {
277 		DRM_DEBUG_VBL("clamping vblank bump to 1 on crtc %u: diffr=%u "
278 			      "refcount %u, vblirq %u\n", pipe, diff,
279 			      atomic_read(&vblank->refcount),
280 			      (flags & DRM_CALLED_FROM_VBLIRQ) != 0);
281 		diff = 1;
282 	}
283 
284 	DRM_DEBUG_VBL("updating vblank count on crtc %u:"
285 		      " current=%u, diff=%u, hw=%u hw_last=%u\n",
286 		      pipe, vblank->count, diff, cur_vblank, vblank->last);
287 
288 	if (diff == 0) {
289 		WARN_ON_ONCE(cur_vblank != vblank->last);
290 		return;
291 	}
292 
293 	/*
294 	 * Only reinitialize corresponding vblank timestamp if high-precision query
295 	 * available and didn't fail, or we were called from the vblank interrupt.
296 	 * Otherwise reinitialize delayed at next vblank interrupt and assign 0
297 	 * for now, to mark the vblanktimestamp as invalid.
298 	 */
299 	if (!rc && (flags & DRM_CALLED_FROM_VBLIRQ) == 0)
300 		t_vblank = (struct timeval) {0, 0};
301 
302 	store_vblank(dev, pipe, diff, &t_vblank, cur_vblank);
303 }
304 
305 /*
306  * Disable vblank irq's on crtc, make sure that last vblank count
307  * of hardware and corresponding consistent software vblank counter
308  * are preserved, even if there are any spurious vblank irq's after
309  * disable.
310  */
311 static void vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
312 {
313 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
314 	unsigned long irqflags;
315 
316 	/* Prevent vblank irq processing while disabling vblank irqs,
317 	 * so no updates of timestamps or count can happen after we've
318 	 * disabled. Needed to prevent races in case of delayed irq's.
319 	 */
320 	spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
321 
322 	/*
323 	 * Only disable vblank interrupts if they're enabled. This avoids
324 	 * calling the ->disable_vblank() operation in atomic context with the
325 	 * hardware potentially runtime suspended.
326 	 */
327 	if (vblank->enabled) {
328 		dev->driver->disable_vblank(dev, pipe);
329 		vblank->enabled = false;
330 	}
331 
332 	/*
333 	 * Always update the count and timestamp to maintain the
334 	 * appearance that the counter has been ticking all along until
335 	 * this time. This makes the count account for the entire time
336 	 * between drm_vblank_on() and drm_vblank_off().
337 	 */
338 	drm_update_vblank_count(dev, pipe, 0);
339 
340 	spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
341 }
342 
343 static void vblank_disable_fn(unsigned long arg)
344 {
345 	struct drm_vblank_crtc *vblank = (void *)arg;
346 	struct drm_device *dev = vblank->dev;
347 	unsigned int pipe = vblank->pipe;
348 	unsigned long irqflags;
349 
350 	if (!dev->vblank_disable_allowed)
351 		return;
352 
353 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
354 	if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
355 		DRM_DEBUG("disabling vblank on crtc %u\n", pipe);
356 		vblank_disable_and_save(dev, pipe);
357 	}
358 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
359 }
360 
361 /**
362  * drm_vblank_cleanup - cleanup vblank support
363  * @dev: DRM device
364  *
365  * This function cleans up any resources allocated in drm_vblank_init.
366  */
367 void drm_vblank_cleanup(struct drm_device *dev)
368 {
369 	unsigned int pipe;
370 
371 	/* Bail if the driver didn't call drm_vblank_init() */
372 	if (dev->num_crtcs == 0)
373 		return;
374 
375 	for (pipe = 0; pipe < dev->num_crtcs; pipe++) {
376 		struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
377 
378 		WARN_ON(vblank->enabled &&
379 			drm_core_check_feature(dev, DRIVER_MODESET));
380 
381 		del_timer_sync(&vblank->disable_timer);
382 	}
383 
384 	kfree(dev->vblank);
385 
386 	dev->num_crtcs = 0;
387 }
388 EXPORT_SYMBOL(drm_vblank_cleanup);
389 
390 /**
391  * drm_vblank_init - initialize vblank support
392  * @dev: DRM device
393  * @num_crtcs: number of CRTCs supported by @dev
394  *
395  * This function initializes vblank support for @num_crtcs display pipelines.
396  *
397  * Returns:
398  * Zero on success or a negative error code on failure.
399  */
400 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
401 {
402 	int ret = -ENOMEM;
403 	unsigned int i;
404 
405 	mtx_init(&dev->vbl_lock, IPL_TTY);
406 	mtx_init(&dev->vblank_time_lock, IPL_TTY);
407 
408 	dev->num_crtcs = num_crtcs;
409 
410 	dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
411 	if (!dev->vblank)
412 		goto err;
413 
414 	for (i = 0; i < num_crtcs; i++) {
415 		struct drm_vblank_crtc *vblank = &dev->vblank[i];
416 
417 		vblank->dev = dev;
418 		vblank->pipe = i;
419 		init_waitqueue_head(&vblank->queue);
420 		setup_timer(&vblank->disable_timer, vblank_disable_fn,
421 			    (unsigned long)vblank);
422 	}
423 
424 	DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
425 
426 	/* Driver specific high-precision vblank timestamping supported? */
427 	if (dev->driver->get_vblank_timestamp)
428 		DRM_INFO("Driver supports precise vblank timestamp query.\n");
429 	else
430 		DRM_INFO("No driver support for vblank timestamp query.\n");
431 
432 	/* Must have precise timestamping for reliable vblank instant disable */
433 	if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
434 		dev->vblank_disable_immediate = false;
435 		DRM_INFO("Setting vblank_disable_immediate to false because "
436 			 "get_vblank_timestamp == NULL\n");
437 	}
438 
439 	dev->vblank_disable_allowed = false;
440 
441 	return 0;
442 
443 err:
444 	dev->num_crtcs = 0;
445 	return ret;
446 }
447 EXPORT_SYMBOL(drm_vblank_init);
448 
449 static void drm_irq_vgaarb_nokms(void *cookie, bool state)
450 {
451 	struct drm_device *dev = cookie;
452 
453 #ifdef __linux__
454 	if (dev->driver->vgaarb_irq) {
455 		dev->driver->vgaarb_irq(dev, state);
456 		return;
457 	}
458 #endif
459 
460 	if (!dev->irq_enabled)
461 		return;
462 
463 	if (state) {
464 		if (dev->driver->irq_uninstall)
465 			dev->driver->irq_uninstall(dev);
466 	} else {
467 		if (dev->driver->irq_preinstall)
468 			dev->driver->irq_preinstall(dev);
469 		if (dev->driver->irq_postinstall)
470 			dev->driver->irq_postinstall(dev);
471 	}
472 }
473 
474 /**
475  * drm_irq_install - install IRQ handler
476  * @dev: DRM device
477  * @irq: IRQ number to install the handler for
478  *
479  * Initializes the IRQ related data. Installs the handler, calling the driver
480  * irq_preinstall() and irq_postinstall() functions before and after the
481  * installation.
482  *
483  * This is the simplified helper interface provided for drivers with no special
484  * needs. Drivers which need to install interrupt handlers for multiple
485  * interrupts must instead set drm_device->irq_enabled to signal the DRM core
486  * that vblank interrupts are available.
487  *
488  * Returns:
489  * Zero on success or a negative error code on failure.
490  */
491 int drm_irq_install(struct drm_device *dev, int irq)
492 {
493 	int ret;
494 	unsigned long sh_flags = 0;
495 
496 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
497 		return -EINVAL;
498 
499 	if (irq == 0)
500 		return -EINVAL;
501 
502 	/* Driver must have been initialized */
503 	if (!dev->dev_private)
504 		return -EINVAL;
505 
506 	if (dev->irq_enabled)
507 		return -EBUSY;
508 	dev->irq_enabled = true;
509 
510 	DRM_DEBUG("irq=%d\n", irq);
511 
512 	/* Before installing handler */
513 	if (dev->driver->irq_preinstall)
514 		dev->driver->irq_preinstall(dev);
515 
516 	/* Install handler */
517 	if (drm_core_check_feature(dev, DRIVER_IRQ_SHARED))
518 		sh_flags = IRQF_SHARED;
519 
520 	ret = request_irq(irq, dev->driver->irq_handler,
521 			  sh_flags, dev->driver->name, dev);
522 
523 	if (ret < 0) {
524 		dev->irq_enabled = false;
525 		return ret;
526 	}
527 
528 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
529 		vga_client_register(dev->pdev, (void *)dev, drm_irq_vgaarb_nokms, NULL);
530 
531 	/* After installing handler */
532 	if (dev->driver->irq_postinstall)
533 		ret = dev->driver->irq_postinstall(dev);
534 
535 	if (ret < 0) {
536 		dev->irq_enabled = false;
537 		if (!drm_core_check_feature(dev, DRIVER_MODESET))
538 			vga_client_register(dev->pdev, NULL, NULL, NULL);
539 		free_irq(irq, dev);
540 	} else {
541 		dev->irq = irq;
542 	}
543 
544 	return ret;
545 }
546 EXPORT_SYMBOL(drm_irq_install);
547 
548 /**
549  * drm_irq_uninstall - uninstall the IRQ handler
550  * @dev: DRM device
551  *
552  * Calls the driver's irq_uninstall() function and unregisters the IRQ handler.
553  * This should only be called by drivers which used drm_irq_install() to set up
554  * their interrupt handler. Other drivers must only reset
555  * drm_device->irq_enabled to false.
556  *
557  * Note that for kernel modesetting drivers it is a bug if this function fails.
558  * The sanity checks are only to catch buggy user modesetting drivers which call
559  * the same function through an ioctl.
560  *
561  * Returns:
562  * Zero on success or a negative error code on failure.
563  */
564 int drm_irq_uninstall(struct drm_device *dev)
565 {
566 	unsigned long irqflags;
567 	bool irq_enabled;
568 	int i;
569 
570 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
571 		return -EINVAL;
572 
573 	irq_enabled = dev->irq_enabled;
574 	dev->irq_enabled = false;
575 
576 	/*
577 	 * Wake up any waiters so they don't hang. This is just to paper over
578 	 * isssues for UMS drivers which aren't in full control of their
579 	 * vblank/irq handling. KMS drivers must ensure that vblanks are all
580 	 * disabled when uninstalling the irq handler.
581 	 */
582 	if (dev->num_crtcs) {
583 		spin_lock_irqsave(&dev->vbl_lock, irqflags);
584 		for (i = 0; i < dev->num_crtcs; i++) {
585 			struct drm_vblank_crtc *vblank = &dev->vblank[i];
586 
587 			if (!vblank->enabled)
588 				continue;
589 
590 			WARN_ON(drm_core_check_feature(dev, DRIVER_MODESET));
591 
592 			vblank_disable_and_save(dev, i);
593 			wake_up(&vblank->queue);
594 		}
595 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
596 	}
597 
598 	if (!irq_enabled)
599 		return -EINVAL;
600 
601 	DRM_DEBUG("irq=%d\n", dev->irq);
602 
603 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
604 		vga_client_register(dev->pdev, NULL, NULL, NULL);
605 
606 	if (dev->driver->irq_uninstall)
607 		dev->driver->irq_uninstall(dev);
608 
609 	free_irq(dev->irq, dev);
610 
611 	return 0;
612 }
613 EXPORT_SYMBOL(drm_irq_uninstall);
614 
615 /*
616  * IRQ control ioctl.
617  *
618  * \param inode device inode.
619  * \param file_priv DRM file private.
620  * \param cmd command.
621  * \param arg user argument, pointing to a drm_control structure.
622  * \return zero on success or a negative number on failure.
623  *
624  * Calls irq_install() or irq_uninstall() according to \p arg.
625  */
626 int drm_control(struct drm_device *dev, void *data,
627 		struct drm_file *file_priv)
628 {
629 	struct drm_control *ctl = data;
630 	int ret = 0, irq;
631 
632 	/* if we haven't irq we fallback for compatibility reasons -
633 	 * this used to be a separate function in drm_dma.h
634 	 */
635 
636 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
637 		return 0;
638 	if (drm_core_check_feature(dev, DRIVER_MODESET))
639 		return 0;
640 	/* UMS was only ever support on pci devices. */
641 	if (WARN_ON(!dev->pdev))
642 		return -EINVAL;
643 
644 	switch (ctl->func) {
645 	case DRM_INST_HANDLER:
646 		irq = dev->pdev->irq;
647 
648 		if (dev->if_version < DRM_IF_VERSION(1, 2) &&
649 		    ctl->irq != irq)
650 			return -EINVAL;
651 		mutex_lock(&dev->struct_mutex);
652 		ret = drm_irq_install(dev, irq);
653 		mutex_unlock(&dev->struct_mutex);
654 
655 		return ret;
656 	case DRM_UNINST_HANDLER:
657 		mutex_lock(&dev->struct_mutex);
658 		ret = drm_irq_uninstall(dev);
659 		mutex_unlock(&dev->struct_mutex);
660 
661 		return ret;
662 	default:
663 		return -EINVAL;
664 	}
665 }
666 
667 /**
668  * drm_calc_timestamping_constants - calculate vblank timestamp constants
669  * @crtc: drm_crtc whose timestamp constants should be updated.
670  * @mode: display mode containing the scanout timings
671  *
672  * Calculate and store various constants which are later
673  * needed by vblank and swap-completion timestamping, e.g,
674  * by drm_calc_vbltimestamp_from_scanoutpos(). They are
675  * derived from CRTC's true scanout timing, so they take
676  * things like panel scaling or other adjustments into account.
677  */
678 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
679 				     const struct drm_display_mode *mode)
680 {
681 	struct drm_device *dev = crtc->dev;
682 	unsigned int pipe = drm_crtc_index(crtc);
683 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
684 	int linedur_ns = 0, framedur_ns = 0;
685 	int dotclock = mode->crtc_clock;
686 
687 	if (!dev->num_crtcs)
688 		return;
689 
690 	if (WARN_ON(pipe >= dev->num_crtcs))
691 		return;
692 
693 	/* Valid dotclock? */
694 	if (dotclock > 0) {
695 		int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
696 
697 		/*
698 		 * Convert scanline length in pixels and video
699 		 * dot clock to line duration and frame duration
700 		 * in nanoseconds:
701 		 */
702 		linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
703 		framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
704 
705 		/*
706 		 * Fields of interlaced scanout modes are only half a frame duration.
707 		 */
708 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
709 			framedur_ns /= 2;
710 	} else
711 		DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
712 			  crtc->base.id);
713 
714 	vblank->linedur_ns  = linedur_ns;
715 	vblank->framedur_ns = framedur_ns;
716 
717 	DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
718 		  crtc->base.id, mode->crtc_htotal,
719 		  mode->crtc_vtotal, mode->crtc_vdisplay);
720 	DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
721 		  crtc->base.id, dotclock, framedur_ns, linedur_ns);
722 }
723 EXPORT_SYMBOL(drm_calc_timestamping_constants);
724 
725 /**
726  * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
727  * @dev: DRM device
728  * @pipe: index of CRTC whose vblank timestamp to retrieve
729  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
730  *             On return contains true maximum error of timestamp
731  * @vblank_time: Pointer to struct timeval which should receive the timestamp
732  * @flags: Flags to pass to driver:
733  *         0 = Default,
734  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
735  * @mode: mode which defines the scanout timings
736  *
737  * Implements calculation of exact vblank timestamps from given drm_display_mode
738  * timings and current video scanout position of a CRTC. This can be called from
739  * within get_vblank_timestamp() implementation of a kms driver to implement the
740  * actual timestamping.
741  *
742  * Should return timestamps conforming to the OML_sync_control OpenML
743  * extension specification. The timestamp corresponds to the end of
744  * the vblank interval, aka start of scanout of topmost-leftmost display
745  * pixel in the following video frame.
746  *
747  * Requires support for optional dev->driver->get_scanout_position()
748  * in kms driver, plus a bit of setup code to provide a drm_display_mode
749  * that corresponds to the true scanout timing.
750  *
751  * The current implementation only handles standard video modes. It
752  * returns as no operation if a doublescan or interlaced video mode is
753  * active. Higher level code is expected to handle this.
754  *
755  * Returns:
756  * Negative value on error, failure or if not supported in current
757  * video mode:
758  *
759  * -EINVAL   - Invalid CRTC.
760  * -EAGAIN   - Temporary unavailable, e.g., called before initial modeset.
761  * -ENOTSUPP - Function not supported in current display mode.
762  * -EIO      - Failed, e.g., due to failed scanout position query.
763  *
764  * Returns or'ed positive status flags on success:
765  *
766  * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
767  * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
768  *
769  */
770 int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
771 					  unsigned int pipe,
772 					  int *max_error,
773 					  struct timeval *vblank_time,
774 					  unsigned flags,
775 					  const struct drm_display_mode *mode)
776 {
777 	struct timeval tv_etime;
778 	ktime_t stime, etime;
779 	unsigned int vbl_status;
780 	int ret = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
781 	int vpos, hpos, i;
782 	int delta_ns, duration_ns;
783 
784 	if (pipe >= dev->num_crtcs) {
785 		DRM_ERROR("Invalid crtc %u\n", pipe);
786 		return -EINVAL;
787 	}
788 
789 	/* Scanout position query not supported? Should not happen. */
790 	if (!dev->driver->get_scanout_position) {
791 		DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
792 		return -EIO;
793 	}
794 
795 	/* If mode timing undefined, just return as no-op:
796 	 * Happens during initial modesetting of a crtc.
797 	 */
798 	if (mode->crtc_clock == 0) {
799 		DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
800 		return -EAGAIN;
801 	}
802 
803 	/* Get current scanout position with system timestamp.
804 	 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
805 	 * if single query takes longer than max_error nanoseconds.
806 	 *
807 	 * This guarantees a tight bound on maximum error if
808 	 * code gets preempted or delayed for some reason.
809 	 */
810 	for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
811 		/*
812 		 * Get vertical and horizontal scanout position vpos, hpos,
813 		 * and bounding timestamps stime, etime, pre/post query.
814 		 */
815 		vbl_status = dev->driver->get_scanout_position(dev, pipe, flags,
816 							       &vpos, &hpos,
817 							       &stime, &etime,
818 							       mode);
819 
820 		/* Return as no-op if scanout query unsupported or failed. */
821 		if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
822 			DRM_DEBUG("crtc %u : scanoutpos query failed [0x%x].\n",
823 				  pipe, vbl_status);
824 			return -EIO;
825 		}
826 
827 		/* Compute uncertainty in timestamp of scanout position query. */
828 		duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
829 
830 		/* Accept result with <  max_error nsecs timing uncertainty. */
831 		if (duration_ns <= *max_error)
832 			break;
833 	}
834 
835 	/* Noisy system timing? */
836 	if (i == DRM_TIMESTAMP_MAXRETRIES) {
837 		DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
838 			  pipe, duration_ns/1000, *max_error/1000, i);
839 	}
840 
841 	/* Return upper bound of timestamp precision error. */
842 	*max_error = duration_ns;
843 
844 	/* Check if in vblank area:
845 	 * vpos is >=0 in video scanout area, but negative
846 	 * within vblank area, counting down the number of lines until
847 	 * start of scanout.
848 	 */
849 	if (vbl_status & DRM_SCANOUTPOS_IN_VBLANK)
850 		ret |= DRM_VBLANKTIME_IN_VBLANK;
851 
852 	/* Convert scanout position into elapsed time at raw_time query
853 	 * since start of scanout at first display scanline. delta_ns
854 	 * can be negative if start of scanout hasn't happened yet.
855 	 */
856 	delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
857 			   mode->crtc_clock);
858 
859 	if (!drm_timestamp_monotonic)
860 		etime = ktime_mono_to_real(etime);
861 
862 	/* save this only for debugging purposes */
863 	tv_etime = ktime_to_timeval(etime);
864 	/* Subtract time delta from raw timestamp to get final
865 	 * vblank_time timestamp for end of vblank.
866 	 */
867 	if (delta_ns < 0)
868 		etime = ktime_add_ns(etime, -delta_ns);
869 	else
870 		etime = ktime_sub_ns(etime, delta_ns);
871 	*vblank_time = ktime_to_timeval(etime);
872 
873 	DRM_DEBUG_VBL("crtc %u : v 0x%x p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
874 		      pipe, vbl_status, hpos, vpos,
875 		      (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
876 		      (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
877 		      duration_ns/1000, i);
878 
879 	return ret;
880 }
881 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
882 
883 static struct timeval get_drm_timestamp(void)
884 {
885 	ktime_t now;
886 
887 	now = drm_timestamp_monotonic ? ktime_get() : ktime_get_real();
888 	return ktime_to_timeval(now);
889 }
890 
891 /**
892  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
893  *                             vblank interval
894  * @dev: DRM device
895  * @pipe: index of CRTC whose vblank timestamp to retrieve
896  * @tvblank: Pointer to target struct timeval which should receive the timestamp
897  * @flags: Flags to pass to driver:
898  *         0 = Default,
899  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
900  *
901  * Fetches the system timestamp corresponding to the time of the most recent
902  * vblank interval on specified CRTC. May call into kms-driver to
903  * compute the timestamp with a high-precision GPU specific method.
904  *
905  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
906  * call, i.e., it isn't very precisely locked to the true vblank.
907  *
908  * Returns:
909  * True if timestamp is considered to be very precise, false otherwise.
910  */
911 static bool
912 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
913 			  struct timeval *tvblank, unsigned flags)
914 {
915 	int ret;
916 
917 	/* Define requested maximum error on timestamps (nanoseconds). */
918 	int max_error = (int) drm_timestamp_precision * 1000;
919 
920 	/* Query driver if possible and precision timestamping enabled. */
921 	if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
922 		ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
923 							tvblank, flags);
924 		if (ret > 0)
925 			return true;
926 	}
927 
928 	/* GPU high precision timestamp query unsupported or failed.
929 	 * Return current monotonic/gettimeofday timestamp as best estimate.
930 	 */
931 	*tvblank = get_drm_timestamp();
932 
933 	return false;
934 }
935 
936 /**
937  * drm_vblank_count - retrieve "cooked" vblank counter value
938  * @dev: DRM device
939  * @pipe: index of CRTC for which to retrieve the counter
940  *
941  * Fetches the "cooked" vblank count value that represents the number of
942  * vblank events since the system was booted, including lost events due to
943  * modesetting activity.
944  *
945  * This is the legacy version of drm_crtc_vblank_count().
946  *
947  * Returns:
948  * The software vblank counter.
949  */
950 u32 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
951 {
952 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
953 
954 	if (WARN_ON(pipe >= dev->num_crtcs))
955 		return 0;
956 
957 	return vblank->count;
958 }
959 EXPORT_SYMBOL(drm_vblank_count);
960 
961 /**
962  * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
963  * @crtc: which counter to retrieve
964  *
965  * Fetches the "cooked" vblank count value that represents the number of
966  * vblank events since the system was booted, including lost events due to
967  * modesetting activity.
968  *
969  * This is the native KMS version of drm_vblank_count().
970  *
971  * Returns:
972  * The software vblank counter.
973  */
974 u32 drm_crtc_vblank_count(struct drm_crtc *crtc)
975 {
976 	return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
977 }
978 EXPORT_SYMBOL(drm_crtc_vblank_count);
979 
980 /**
981  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
982  *     system timestamp corresponding to that vblank counter value.
983  * @dev: DRM device
984  * @pipe: index of CRTC whose counter to retrieve
985  * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
986  *
987  * Fetches the "cooked" vblank count value that represents the number of
988  * vblank events since the system was booted, including lost events due to
989  * modesetting activity. Returns corresponding system timestamp of the time
990  * of the vblank interval that corresponds to the current vblank counter value.
991  *
992  * This is the legacy version of drm_crtc_vblank_count_and_time().
993  */
994 u32 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
995 			      struct timeval *vblanktime)
996 {
997 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
998 	int count = DRM_TIMESTAMP_MAXRETRIES;
999 	u32 cur_vblank;
1000 
1001 	if (WARN_ON(pipe >= dev->num_crtcs))
1002 		return 0;
1003 
1004 	/*
1005 	 * Vblank timestamps are read lockless. To ensure consistency the vblank
1006 	 * counter is rechecked and ordering is ensured using memory barriers.
1007 	 * This works like a seqlock. The write-side barriers are in store_vblank.
1008 	 */
1009 	do {
1010 		cur_vblank = vblank->count;
1011 		smp_rmb();
1012 		*vblanktime = vblanktimestamp(dev, pipe, cur_vblank);
1013 		smp_rmb();
1014 	} while (cur_vblank != vblank->count && --count > 0);
1015 
1016 	return cur_vblank;
1017 }
1018 EXPORT_SYMBOL(drm_vblank_count_and_time);
1019 
1020 /**
1021  * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
1022  *     and the system timestamp corresponding to that vblank counter value
1023  * @crtc: which counter to retrieve
1024  * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
1025  *
1026  * Fetches the "cooked" vblank count value that represents the number of
1027  * vblank events since the system was booted, including lost events due to
1028  * modesetting activity. Returns corresponding system timestamp of the time
1029  * of the vblank interval that corresponds to the current vblank counter value.
1030  *
1031  * This is the native KMS version of drm_vblank_count_and_time().
1032  */
1033 u32 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
1034 				   struct timeval *vblanktime)
1035 {
1036 	return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
1037 					 vblanktime);
1038 }
1039 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
1040 
1041 static void send_vblank_event(struct drm_device *dev,
1042 		struct drm_pending_vblank_event *e,
1043 		unsigned long seq, struct timeval *now)
1044 {
1045 	assert_spin_locked(&dev->event_lock);
1046 
1047 	e->event.sequence = seq;
1048 	e->event.tv_sec = now->tv_sec;
1049 	e->event.tv_usec = now->tv_usec;
1050 
1051 	list_add_tail(&e->base.link,
1052 		      &e->base.file_priv->event_list);
1053 	wake_up_interruptible(&e->base.file_priv->event_wait);
1054 #ifdef __OpenBSD__
1055 	selwakeup(&e->base.file_priv->rsel);
1056 #endif
1057 	trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
1058 					 e->event.sequence);
1059 }
1060 
1061 /**
1062  * drm_arm_vblank_event - arm vblank event after pageflip
1063  * @dev: DRM device
1064  * @pipe: CRTC index
1065  * @e: the event to prepare to send
1066  *
1067  * A lot of drivers need to generate vblank events for the very next vblank
1068  * interrupt. For example when the page flip interrupt happens when the page
1069  * flip gets armed, but not when it actually executes within the next vblank
1070  * period. This helper function implements exactly the required vblank arming
1071  * behaviour.
1072  *
1073  * Caller must hold event lock. Caller must also hold a vblank reference for
1074  * the event @e, which will be dropped when the next vblank arrives.
1075  *
1076  * This is the legacy version of drm_crtc_arm_vblank_event().
1077  */
1078 void drm_arm_vblank_event(struct drm_device *dev, unsigned int pipe,
1079 			  struct drm_pending_vblank_event *e)
1080 {
1081 	assert_spin_locked(&dev->event_lock);
1082 
1083 	e->pipe = pipe;
1084 	e->event.sequence = drm_vblank_count(dev, pipe);
1085 	list_add_tail(&e->base.link, &dev->vblank_event_list);
1086 }
1087 EXPORT_SYMBOL(drm_arm_vblank_event);
1088 
1089 /**
1090  * drm_crtc_arm_vblank_event - arm vblank event after pageflip
1091  * @crtc: the source CRTC of the vblank event
1092  * @e: the event to send
1093  *
1094  * A lot of drivers need to generate vblank events for the very next vblank
1095  * interrupt. For example when the page flip interrupt happens when the page
1096  * flip gets armed, but not when it actually executes within the next vblank
1097  * period. This helper function implements exactly the required vblank arming
1098  * behaviour.
1099  *
1100  * Caller must hold event lock. Caller must also hold a vblank reference for
1101  * the event @e, which will be dropped when the next vblank arrives.
1102  *
1103  * This is the native KMS version of drm_arm_vblank_event().
1104  */
1105 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
1106 			       struct drm_pending_vblank_event *e)
1107 {
1108 	drm_arm_vblank_event(crtc->dev, drm_crtc_index(crtc), e);
1109 }
1110 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
1111 
1112 /**
1113  * drm_send_vblank_event - helper to send vblank event after pageflip
1114  * @dev: DRM device
1115  * @pipe: CRTC index
1116  * @e: the event to send
1117  *
1118  * Updates sequence # and timestamp on event, and sends it to userspace.
1119  * Caller must hold event lock.
1120  *
1121  * This is the legacy version of drm_crtc_send_vblank_event().
1122  */
1123 void drm_send_vblank_event(struct drm_device *dev, unsigned int pipe,
1124 			   struct drm_pending_vblank_event *e)
1125 {
1126 	struct timeval now;
1127 	unsigned int seq;
1128 
1129 	if (dev->num_crtcs > 0) {
1130 		seq = drm_vblank_count_and_time(dev, pipe, &now);
1131 	} else {
1132 		seq = 0;
1133 
1134 		now = get_drm_timestamp();
1135 	}
1136 	e->pipe = pipe;
1137 	send_vblank_event(dev, e, seq, &now);
1138 }
1139 EXPORT_SYMBOL(drm_send_vblank_event);
1140 
1141 /**
1142  * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
1143  * @crtc: the source CRTC of the vblank event
1144  * @e: the event to send
1145  *
1146  * Updates sequence # and timestamp on event, and sends it to userspace.
1147  * Caller must hold event lock.
1148  *
1149  * This is the native KMS version of drm_send_vblank_event().
1150  */
1151 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
1152 				struct drm_pending_vblank_event *e)
1153 {
1154 	drm_send_vblank_event(crtc->dev, drm_crtc_index(crtc), e);
1155 }
1156 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
1157 
1158 /**
1159  * drm_vblank_enable - enable the vblank interrupt on a CRTC
1160  * @dev: DRM device
1161  * @pipe: CRTC index
1162  *
1163  * Returns:
1164  * Zero on success or a negative error code on failure.
1165  */
1166 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
1167 {
1168 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1169 	int ret = 0;
1170 
1171 	assert_spin_locked(&dev->vbl_lock);
1172 
1173 	spin_lock(&dev->vblank_time_lock);
1174 
1175 	if (!vblank->enabled) {
1176 		/*
1177 		 * Enable vblank irqs under vblank_time_lock protection.
1178 		 * All vblank count & timestamp updates are held off
1179 		 * until we are done reinitializing master counter and
1180 		 * timestamps. Filtercode in drm_handle_vblank() will
1181 		 * prevent double-accounting of same vblank interval.
1182 		 */
1183 		ret = dev->driver->enable_vblank(dev, pipe);
1184 		DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
1185 		if (ret)
1186 			atomic_dec(&vblank->refcount);
1187 		else {
1188 			vblank->enabled = true;
1189 			drm_update_vblank_count(dev, pipe, 0);
1190 		}
1191 	}
1192 
1193 	spin_unlock(&dev->vblank_time_lock);
1194 
1195 	return ret;
1196 }
1197 
1198 /**
1199  * drm_vblank_get - get a reference count on vblank events
1200  * @dev: DRM device
1201  * @pipe: index of CRTC to own
1202  *
1203  * Acquire a reference count on vblank events to avoid having them disabled
1204  * while in use.
1205  *
1206  * This is the legacy version of drm_crtc_vblank_get().
1207  *
1208  * Returns:
1209  * Zero on success or a negative error code on failure.
1210  */
1211 int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
1212 {
1213 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1214 	unsigned long irqflags;
1215 	int ret = 0;
1216 
1217 	if (!dev->num_crtcs)
1218 		return -EINVAL;
1219 
1220 	if (WARN_ON(pipe >= dev->num_crtcs))
1221 		return -EINVAL;
1222 
1223 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
1224 	/* Going from 0->1 means we have to enable interrupts again */
1225 	if (atomic_add_return(1, &vblank->refcount) == 1) {
1226 		ret = drm_vblank_enable(dev, pipe);
1227 	} else {
1228 		if (!vblank->enabled) {
1229 			atomic_dec(&vblank->refcount);
1230 			ret = -EINVAL;
1231 		}
1232 	}
1233 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1234 
1235 	return ret;
1236 }
1237 EXPORT_SYMBOL(drm_vblank_get);
1238 
1239 /**
1240  * drm_crtc_vblank_get - get a reference count on vblank events
1241  * @crtc: which CRTC to own
1242  *
1243  * Acquire a reference count on vblank events to avoid having them disabled
1244  * while in use.
1245  *
1246  * This is the native kms version of drm_vblank_get().
1247  *
1248  * Returns:
1249  * Zero on success or a negative error code on failure.
1250  */
1251 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1252 {
1253 	return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1254 }
1255 EXPORT_SYMBOL(drm_crtc_vblank_get);
1256 
1257 /**
1258  * drm_vblank_put - release ownership of vblank events
1259  * @dev: DRM device
1260  * @pipe: index of CRTC to release
1261  *
1262  * Release ownership of a given vblank counter, turning off interrupts
1263  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1264  *
1265  * This is the legacy version of drm_crtc_vblank_put().
1266  */
1267 void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1268 {
1269 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1270 
1271 	if (WARN_ON(pipe >= dev->num_crtcs))
1272 		return;
1273 
1274 	if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1275 		return;
1276 
1277 	/* Last user schedules interrupt disable */
1278 	if (atomic_dec_and_test(&vblank->refcount)) {
1279 		if (drm_vblank_offdelay == 0)
1280 			return;
1281 		else if (dev->vblank_disable_immediate || drm_vblank_offdelay < 0)
1282 			vblank_disable_fn((unsigned long)vblank);
1283 		else
1284 			mod_timer(&vblank->disable_timer,
1285 				  jiffies + ((drm_vblank_offdelay * HZ)/1000));
1286 	}
1287 }
1288 EXPORT_SYMBOL(drm_vblank_put);
1289 
1290 /**
1291  * drm_crtc_vblank_put - give up ownership of vblank events
1292  * @crtc: which counter to give up
1293  *
1294  * Release ownership of a given vblank counter, turning off interrupts
1295  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1296  *
1297  * This is the native kms version of drm_vblank_put().
1298  */
1299 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1300 {
1301 	drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1302 }
1303 EXPORT_SYMBOL(drm_crtc_vblank_put);
1304 
1305 /**
1306  * drm_wait_one_vblank - wait for one vblank
1307  * @dev: DRM device
1308  * @pipe: CRTC index
1309  *
1310  * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1311  * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1312  * due to lack of driver support or because the crtc is off.
1313  */
1314 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1315 {
1316 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1317 	int ret;
1318 	u32 last;
1319 
1320 	if (WARN_ON(pipe >= dev->num_crtcs) || cold)
1321 		return;
1322 
1323 	ret = drm_vblank_get(dev, pipe);
1324 	if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1325 		return;
1326 
1327 	last = drm_vblank_count(dev, pipe);
1328 
1329 	ret = wait_event_timeout(vblank->queue,
1330 				 last != drm_vblank_count(dev, pipe),
1331 				 msecs_to_jiffies(100));
1332 
1333 	WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1334 
1335 	drm_vblank_put(dev, pipe);
1336 }
1337 EXPORT_SYMBOL(drm_wait_one_vblank);
1338 
1339 /**
1340  * drm_crtc_wait_one_vblank - wait for one vblank
1341  * @crtc: DRM crtc
1342  *
1343  * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1344  * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1345  * due to lack of driver support or because the crtc is off.
1346  */
1347 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1348 {
1349 	drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1350 }
1351 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1352 
1353 /**
1354  * drm_vblank_off - disable vblank events on a CRTC
1355  * @dev: DRM device
1356  * @pipe: CRTC index
1357  *
1358  * Drivers can use this function to shut down the vblank interrupt handling when
1359  * disabling a crtc. This function ensures that the latest vblank frame count is
1360  * stored so that drm_vblank_on() can restore it again.
1361  *
1362  * Drivers must use this function when the hardware vblank counter can get
1363  * reset, e.g. when suspending.
1364  *
1365  * This is the legacy version of drm_crtc_vblank_off().
1366  */
1367 void drm_vblank_off(struct drm_device *dev, unsigned int pipe)
1368 {
1369 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1370 	struct drm_pending_vblank_event *e, *t;
1371 	struct timeval now;
1372 	unsigned long irqflags;
1373 	unsigned int seq;
1374 
1375 	if (WARN_ON(pipe >= dev->num_crtcs))
1376 		return;
1377 
1378 	spin_lock_irqsave(&dev->event_lock, irqflags);
1379 
1380 	spin_lock(&dev->vbl_lock);
1381 	DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1382 		      pipe, vblank->enabled, vblank->inmodeset);
1383 
1384 	/* Avoid redundant vblank disables without previous drm_vblank_on(). */
1385 	if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1386 		vblank_disable_and_save(dev, pipe);
1387 
1388 	wake_up(&vblank->queue);
1389 
1390 	/*
1391 	 * Prevent subsequent drm_vblank_get() from re-enabling
1392 	 * the vblank interrupt by bumping the refcount.
1393 	 */
1394 	if (!vblank->inmodeset) {
1395 		atomic_inc(&vblank->refcount);
1396 		vblank->inmodeset = 1;
1397 	}
1398 	spin_unlock(&dev->vbl_lock);
1399 
1400 	/* Send any queued vblank events, lest the natives grow disquiet */
1401 	seq = drm_vblank_count_and_time(dev, pipe, &now);
1402 
1403 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1404 		if (e->pipe != pipe)
1405 			continue;
1406 		DRM_DEBUG("Sending premature vblank event on disable: "
1407 			  "wanted %d, current %d\n",
1408 			  e->event.sequence, seq);
1409 		list_del(&e->base.link);
1410 		drm_vblank_put(dev, pipe);
1411 		send_vblank_event(dev, e, seq, &now);
1412 	}
1413 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
1414 }
1415 EXPORT_SYMBOL(drm_vblank_off);
1416 
1417 /**
1418  * drm_crtc_vblank_off - disable vblank events on a CRTC
1419  * @crtc: CRTC in question
1420  *
1421  * Drivers can use this function to shut down the vblank interrupt handling when
1422  * disabling a crtc. This function ensures that the latest vblank frame count is
1423  * stored so that drm_vblank_on can restore it again.
1424  *
1425  * Drivers must use this function when the hardware vblank counter can get
1426  * reset, e.g. when suspending.
1427  *
1428  * This is the native kms version of drm_vblank_off().
1429  */
1430 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1431 {
1432 	drm_vblank_off(crtc->dev, drm_crtc_index(crtc));
1433 }
1434 EXPORT_SYMBOL(drm_crtc_vblank_off);
1435 
1436 /**
1437  * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1438  * @crtc: CRTC in question
1439  *
1440  * Drivers can use this function to reset the vblank state to off at load time.
1441  * Drivers should use this together with the drm_crtc_vblank_off() and
1442  * drm_crtc_vblank_on() functions. The difference compared to
1443  * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1444  * and hence doesn't need to call any driver hooks.
1445  */
1446 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1447 {
1448 	struct drm_device *dev = crtc->dev;
1449 	unsigned long irqflags;
1450 	unsigned int pipe = drm_crtc_index(crtc);
1451 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1452 
1453 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
1454 	/*
1455 	 * Prevent subsequent drm_vblank_get() from enabling the vblank
1456 	 * interrupt by bumping the refcount.
1457 	 */
1458 	if (!vblank->inmodeset) {
1459 		atomic_inc(&vblank->refcount);
1460 		vblank->inmodeset = 1;
1461 	}
1462 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1463 
1464 	WARN_ON(!list_empty(&dev->vblank_event_list));
1465 }
1466 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1467 
1468 /**
1469  * drm_vblank_on - enable vblank events on a CRTC
1470  * @dev: DRM device
1471  * @pipe: CRTC index
1472  *
1473  * This functions restores the vblank interrupt state captured with
1474  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1475  * drm_vblank_off() can be unbalanced and so can also be unconditionally called
1476  * in driver load code to reflect the current hardware state of the crtc.
1477  *
1478  * This is the legacy version of drm_crtc_vblank_on().
1479  */
1480 void drm_vblank_on(struct drm_device *dev, unsigned int pipe)
1481 {
1482 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1483 	unsigned long irqflags;
1484 
1485 	if (WARN_ON(pipe >= dev->num_crtcs))
1486 		return;
1487 
1488 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
1489 	DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1490 		      pipe, vblank->enabled, vblank->inmodeset);
1491 
1492 	/* Drop our private "prevent drm_vblank_get" refcount */
1493 	if (vblank->inmodeset) {
1494 		atomic_dec(&vblank->refcount);
1495 		vblank->inmodeset = 0;
1496 	}
1497 
1498 	drm_reset_vblank_timestamp(dev, pipe);
1499 
1500 	/*
1501 	 * re-enable interrupts if there are users left, or the
1502 	 * user wishes vblank interrupts to be enabled all the time.
1503 	 */
1504 	if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1505 		WARN_ON(drm_vblank_enable(dev, pipe));
1506 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1507 }
1508 EXPORT_SYMBOL(drm_vblank_on);
1509 
1510 /**
1511  * drm_crtc_vblank_on - enable vblank events on a CRTC
1512  * @crtc: CRTC in question
1513  *
1514  * This functions restores the vblank interrupt state captured with
1515  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1516  * drm_vblank_off() can be unbalanced and so can also be unconditionally called
1517  * in driver load code to reflect the current hardware state of the crtc.
1518  *
1519  * This is the native kms version of drm_vblank_on().
1520  */
1521 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1522 {
1523 	drm_vblank_on(crtc->dev, drm_crtc_index(crtc));
1524 }
1525 EXPORT_SYMBOL(drm_crtc_vblank_on);
1526 
1527 /**
1528  * drm_vblank_pre_modeset - account for vblanks across mode sets
1529  * @dev: DRM device
1530  * @pipe: CRTC index
1531  *
1532  * Account for vblank events across mode setting events, which will likely
1533  * reset the hardware frame counter.
1534  *
1535  * This is done by grabbing a temporary vblank reference to ensure that the
1536  * vblank interrupt keeps running across the modeset sequence. With this the
1537  * software-side vblank frame counting will ensure that there are no jumps or
1538  * discontinuities.
1539  *
1540  * Unfortunately this approach is racy and also doesn't work when the vblank
1541  * interrupt stops running, e.g. across system suspend resume. It is therefore
1542  * highly recommended that drivers use the newer drm_vblank_off() and
1543  * drm_vblank_on() instead. drm_vblank_pre_modeset() only works correctly when
1544  * using "cooked" software vblank frame counters and not relying on any hardware
1545  * counters.
1546  *
1547  * Drivers must call drm_vblank_post_modeset() when re-enabling the same crtc
1548  * again.
1549  */
1550 void drm_vblank_pre_modeset(struct drm_device *dev, unsigned int pipe)
1551 {
1552 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1553 
1554 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
1555 	if (!dev->num_crtcs)
1556 		return;
1557 
1558 	if (WARN_ON(pipe >= dev->num_crtcs))
1559 		return;
1560 
1561 	/*
1562 	 * To avoid all the problems that might happen if interrupts
1563 	 * were enabled/disabled around or between these calls, we just
1564 	 * have the kernel take a reference on the CRTC (just once though
1565 	 * to avoid corrupting the count if multiple, mismatch calls occur),
1566 	 * so that interrupts remain enabled in the interim.
1567 	 */
1568 	if (!vblank->inmodeset) {
1569 		vblank->inmodeset = 0x1;
1570 		if (drm_vblank_get(dev, pipe) == 0)
1571 			vblank->inmodeset |= 0x2;
1572 	}
1573 }
1574 EXPORT_SYMBOL(drm_vblank_pre_modeset);
1575 
1576 /**
1577  * drm_vblank_post_modeset - undo drm_vblank_pre_modeset changes
1578  * @dev: DRM device
1579  * @pipe: CRTC index
1580  *
1581  * This function again drops the temporary vblank reference acquired in
1582  * drm_vblank_pre_modeset.
1583  */
1584 void drm_vblank_post_modeset(struct drm_device *dev, unsigned int pipe)
1585 {
1586 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1587 	unsigned long irqflags;
1588 
1589 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
1590 	if (!dev->num_crtcs)
1591 		return;
1592 
1593 	if (WARN_ON(pipe >= dev->num_crtcs))
1594 		return;
1595 
1596 	if (vblank->inmodeset) {
1597 		spin_lock_irqsave(&dev->vbl_lock, irqflags);
1598 		dev->vblank_disable_allowed = true;
1599 		drm_reset_vblank_timestamp(dev, pipe);
1600 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1601 
1602 		if (vblank->inmodeset & 0x2)
1603 			drm_vblank_put(dev, pipe);
1604 
1605 		vblank->inmodeset = 0;
1606 	}
1607 }
1608 EXPORT_SYMBOL(drm_vblank_post_modeset);
1609 
1610 /*
1611  * drm_modeset_ctl - handle vblank event counter changes across mode switch
1612  * @DRM_IOCTL_ARGS: standard ioctl arguments
1613  *
1614  * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
1615  * ioctls around modesetting so that any lost vblank events are accounted for.
1616  *
1617  * Generally the counter will reset across mode sets.  If interrupts are
1618  * enabled around this call, we don't have to do anything since the counter
1619  * will have already been incremented.
1620  */
1621 int drm_modeset_ctl(struct drm_device *dev, void *data,
1622 		    struct drm_file *file_priv)
1623 {
1624 	struct drm_modeset_ctl *modeset = data;
1625 	unsigned int pipe;
1626 
1627 	/* If drm_vblank_init() hasn't been called yet, just no-op */
1628 	if (!dev->num_crtcs)
1629 		return 0;
1630 
1631 	/* KMS drivers handle this internally */
1632 	if (drm_core_check_feature(dev, DRIVER_MODESET))
1633 		return 0;
1634 
1635 	pipe = modeset->crtc;
1636 	if (pipe >= dev->num_crtcs)
1637 		return -EINVAL;
1638 
1639 	switch (modeset->cmd) {
1640 	case _DRM_PRE_MODESET:
1641 		drm_vblank_pre_modeset(dev, pipe);
1642 		break;
1643 	case _DRM_POST_MODESET:
1644 		drm_vblank_post_modeset(dev, pipe);
1645 		break;
1646 	default:
1647 		return -EINVAL;
1648 	}
1649 
1650 	return 0;
1651 }
1652 
1653 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1654 				  union drm_wait_vblank *vblwait,
1655 				  struct drm_file *file_priv)
1656 {
1657 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1658 	struct drm_pending_vblank_event *e;
1659 	struct timeval now;
1660 	unsigned long flags;
1661 	unsigned int seq;
1662 	int ret;
1663 
1664 	e = kzalloc(sizeof(*e), GFP_KERNEL);
1665 	if (e == NULL) {
1666 		ret = -ENOMEM;
1667 		goto err_put;
1668 	}
1669 
1670 	e->pipe = pipe;
1671 #ifdef __linux__
1672 	e->base.pid = current->pid;
1673 #else
1674 	e->base.pid = curproc->p_p->ps_pid;
1675 #endif
1676 	e->event.base.type = DRM_EVENT_VBLANK;
1677 	e->event.base.length = sizeof(e->event);
1678 	e->event.user_data = vblwait->request.signal;
1679 	e->base.event = &e->event.base;
1680 	e->base.file_priv = file_priv;
1681 	e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
1682 
1683 	spin_lock_irqsave(&dev->event_lock, flags);
1684 
1685 	/*
1686 	 * drm_vblank_off() might have been called after we called
1687 	 * drm_vblank_get(). drm_vblank_off() holds event_lock
1688 	 * around the vblank disable, so no need for further locking.
1689 	 * The reference from drm_vblank_get() protects against
1690 	 * vblank disable from another source.
1691 	 */
1692 	if (!vblank->enabled) {
1693 		ret = -EINVAL;
1694 		goto err_unlock;
1695 	}
1696 
1697 	if (file_priv->event_space < sizeof(e->event)) {
1698 		ret = -EBUSY;
1699 		goto err_unlock;
1700 	}
1701 
1702 	file_priv->event_space -= sizeof(e->event);
1703 	seq = drm_vblank_count_and_time(dev, pipe, &now);
1704 
1705 	if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1706 	    (seq - vblwait->request.sequence) <= (1 << 23)) {
1707 		vblwait->request.sequence = seq + 1;
1708 		vblwait->reply.sequence = vblwait->request.sequence;
1709 	}
1710 
1711 	DRM_DEBUG("event on vblank count %d, current %d, crtc %u\n",
1712 		  vblwait->request.sequence, seq, pipe);
1713 
1714 #ifdef __linux__
1715 	trace_drm_vblank_event_queued(current->pid, pipe,
1716 				      vblwait->request.sequence);
1717 #else
1718 	trace_drm_vblank_event_queued(curproc->p_p->ps_pid, pipe,
1719 				      vblwait->request.sequence);
1720 #endif
1721 
1722 	e->event.sequence = vblwait->request.sequence;
1723 	if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1724 		drm_vblank_put(dev, pipe);
1725 		send_vblank_event(dev, e, seq, &now);
1726 		vblwait->reply.sequence = seq;
1727 	} else {
1728 		/* drm_handle_vblank_events will call drm_vblank_put */
1729 		list_add_tail(&e->base.link, &dev->vblank_event_list);
1730 		vblwait->reply.sequence = vblwait->request.sequence;
1731 	}
1732 
1733 	spin_unlock_irqrestore(&dev->event_lock, flags);
1734 
1735 	return 0;
1736 
1737 err_unlock:
1738 	spin_unlock_irqrestore(&dev->event_lock, flags);
1739 	kfree(e);
1740 err_put:
1741 	drm_vblank_put(dev, pipe);
1742 	return ret;
1743 }
1744 
1745 /*
1746  * Wait for VBLANK.
1747  *
1748  * \param inode device inode.
1749  * \param file_priv DRM file private.
1750  * \param cmd command.
1751  * \param data user argument, pointing to a drm_wait_vblank structure.
1752  * \return zero on success or a negative number on failure.
1753  *
1754  * This function enables the vblank interrupt on the pipe requested, then
1755  * sleeps waiting for the requested sequence number to occur, and drops
1756  * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
1757  * after a timeout with no further vblank waits scheduled).
1758  */
1759 int drm_wait_vblank(struct drm_device *dev, void *data,
1760 		    struct drm_file *file_priv)
1761 {
1762 	struct drm_vblank_crtc *vblank;
1763 	union drm_wait_vblank *vblwait = data;
1764 	int ret;
1765 	unsigned int flags, seq, pipe, high_pipe;
1766 
1767 	if (!dev->irq_enabled)
1768 		return -EINVAL;
1769 
1770 	if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1771 		return -EINVAL;
1772 
1773 	if (vblwait->request.type &
1774 	    ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1775 	      _DRM_VBLANK_HIGH_CRTC_MASK)) {
1776 		DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1777 			  vblwait->request.type,
1778 			  (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1779 			   _DRM_VBLANK_HIGH_CRTC_MASK));
1780 		return -EINVAL;
1781 	}
1782 
1783 	flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1784 	high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1785 	if (high_pipe)
1786 		pipe = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1787 	else
1788 		pipe = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1789 	if (pipe >= dev->num_crtcs)
1790 		return -EINVAL;
1791 
1792 	vblank = &dev->vblank[pipe];
1793 
1794 	ret = drm_vblank_get(dev, pipe);
1795 	if (ret) {
1796 		DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1797 		return ret;
1798 	}
1799 	seq = drm_vblank_count(dev, pipe);
1800 
1801 	switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1802 	case _DRM_VBLANK_RELATIVE:
1803 		vblwait->request.sequence += seq;
1804 		vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1805 	case _DRM_VBLANK_ABSOLUTE:
1806 		break;
1807 	default:
1808 		ret = -EINVAL;
1809 		goto done;
1810 	}
1811 
1812 	if (flags & _DRM_VBLANK_EVENT) {
1813 		/* must hold on to the vblank ref until the event fires
1814 		 * drm_vblank_put will be called asynchronously
1815 		 */
1816 		return drm_queue_vblank_event(dev, pipe, vblwait, file_priv);
1817 	}
1818 
1819 	if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1820 	    (seq - vblwait->request.sequence) <= (1<<23)) {
1821 		vblwait->request.sequence = seq + 1;
1822 	}
1823 
1824 	DRM_DEBUG("waiting on vblank count %d, crtc %u\n",
1825 		  vblwait->request.sequence, pipe);
1826 	vblank->last_wait = vblwait->request.sequence;
1827 	DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1828 		    (((drm_vblank_count(dev, pipe) -
1829 		       vblwait->request.sequence) <= (1 << 23)) ||
1830 		     !vblank->enabled ||
1831 		     !dev->irq_enabled));
1832 
1833 	if (ret != -EINTR) {
1834 		struct timeval now;
1835 
1836 		vblwait->reply.sequence = drm_vblank_count_and_time(dev, pipe, &now);
1837 		vblwait->reply.tval_sec = now.tv_sec;
1838 		vblwait->reply.tval_usec = now.tv_usec;
1839 
1840 		DRM_DEBUG("returning %d to client\n",
1841 			  vblwait->reply.sequence);
1842 	} else {
1843 		DRM_DEBUG("vblank wait interrupted by signal\n");
1844 	}
1845 
1846 done:
1847 	drm_vblank_put(dev, pipe);
1848 	return ret;
1849 }
1850 
1851 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1852 {
1853 	struct drm_pending_vblank_event *e, *t;
1854 	struct timeval now;
1855 	unsigned int seq;
1856 
1857 	assert_spin_locked(&dev->event_lock);
1858 
1859 	seq = drm_vblank_count_and_time(dev, pipe, &now);
1860 
1861 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1862 		if (e->pipe != pipe)
1863 			continue;
1864 		if ((seq - e->event.sequence) > (1<<23))
1865 			continue;
1866 
1867 		DRM_DEBUG("vblank event on %d, current %d\n",
1868 			  e->event.sequence, seq);
1869 
1870 		list_del(&e->base.link);
1871 		drm_vblank_put(dev, pipe);
1872 		send_vblank_event(dev, e, seq, &now);
1873 	}
1874 
1875 	trace_drm_vblank_event(pipe, seq);
1876 }
1877 
1878 /**
1879  * drm_handle_vblank - handle a vblank event
1880  * @dev: DRM device
1881  * @pipe: index of CRTC where this event occurred
1882  *
1883  * Drivers should call this routine in their vblank interrupt handlers to
1884  * update the vblank counter and send any signals that may be pending.
1885  *
1886  * This is the legacy version of drm_crtc_handle_vblank().
1887  */
1888 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1889 {
1890 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1891 	unsigned long irqflags;
1892 
1893 	if (WARN_ON_ONCE(!dev->num_crtcs))
1894 		return false;
1895 
1896 	if (WARN_ON(pipe >= dev->num_crtcs))
1897 		return false;
1898 
1899 	spin_lock_irqsave(&dev->event_lock, irqflags);
1900 
1901 	/* Need timestamp lock to prevent concurrent execution with
1902 	 * vblank enable/disable, as this would cause inconsistent
1903 	 * or corrupted timestamps and vblank counts.
1904 	 */
1905 	spin_lock(&dev->vblank_time_lock);
1906 
1907 	/* Vblank irq handling disabled. Nothing to do. */
1908 	if (!vblank->enabled) {
1909 		spin_unlock(&dev->vblank_time_lock);
1910 		spin_unlock_irqrestore(&dev->event_lock, irqflags);
1911 		return false;
1912 	}
1913 
1914 	drm_update_vblank_count(dev, pipe, DRM_CALLED_FROM_VBLIRQ);
1915 
1916 	spin_unlock(&dev->vblank_time_lock);
1917 
1918 	wake_up(&vblank->queue);
1919 	drm_handle_vblank_events(dev, pipe);
1920 
1921 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
1922 
1923 	return true;
1924 }
1925 EXPORT_SYMBOL(drm_handle_vblank);
1926 
1927 /**
1928  * drm_crtc_handle_vblank - handle a vblank event
1929  * @crtc: where this event occurred
1930  *
1931  * Drivers should call this routine in their vblank interrupt handlers to
1932  * update the vblank counter and send any signals that may be pending.
1933  *
1934  * This is the native KMS version of drm_handle_vblank().
1935  *
1936  * Returns:
1937  * True if the event was successfully handled, false on failure.
1938  */
1939 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1940 {
1941 	return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1942 }
1943 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1944 
1945 /**
1946  * drm_vblank_no_hw_counter - "No hw counter" implementation of .get_vblank_counter()
1947  * @dev: DRM device
1948  * @pipe: CRTC for which to read the counter
1949  *
1950  * Drivers can plug this into the .get_vblank_counter() function if
1951  * there is no useable hardware frame counter available.
1952  *
1953  * Returns:
1954  * 0
1955  */
1956 u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
1957 {
1958 	return 0;
1959 }
1960 EXPORT_SYMBOL(drm_vblank_no_hw_counter);
1961