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