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