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