Home | History | Annotate | Line # | Download | only in drm
drm_irq.c revision 1.4
      1 /**
      2  * \file drm_irq.c
      3  * IRQ support
      4  *
      5  * \author Rickard E. (Rik) Faith <faith (at) valinux.com>
      6  * \author Gareth Hughes <gareth (at) valinux.com>
      7  */
      8 
      9 /*
     10  * Created: Fri Mar 19 14:30:16 1999 by faith (at) valinux.com
     11  *
     12  * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
     13  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
     14  * All Rights Reserved.
     15  *
     16  * Permission is hereby granted, free of charge, to any person obtaining a
     17  * copy of this software and associated documentation files (the "Software"),
     18  * to deal in the Software without restriction, including without limitation
     19  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     20  * and/or sell copies of the Software, and to permit persons to whom the
     21  * Software is furnished to do so, subject to the following conditions:
     22  *
     23  * The above copyright notice and this permission notice (including the next
     24  * paragraph) shall be included in all copies or substantial portions of the
     25  * Software.
     26  *
     27  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     28  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     29  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     30  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
     31  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
     32  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     33  * OTHER DEALINGS IN THE SOFTWARE.
     34  */
     35 
     36 #include <drm/drmP.h>
     37 #include "drm_trace.h"
     38 
     39 #include <linux/interrupt.h>	/* For task queue support */
     40 #include <linux/slab.h>
     41 
     42 #include <linux/vgaarb.h>
     43 #include <linux/export.h>
     44 
     45 #include <linux/atomic.h>
     46 #include <linux/ktime.h>
     47 #include <linux/math64.h>
     48 #include <linux/preempt.h>
     49 #include <linux/sched.h>
     50 
     51 #include <asm/bug.h>
     52 
     53 #ifdef __NetBSD__		/* XXX hurk -- selnotify &c. */
     54 #include <sys/poll.h>
     55 #include <sys/select.h>
     56 #endif
     57 
     58 /* Access macro for slots in vblank timestamp ringbuffer. */
     59 #define vblanktimestamp(dev, crtc, count) \
     60 	((dev)->vblank[crtc].time[(count) % DRM_VBLANKTIME_RBSIZE])
     61 
     62 /* Retry timestamp calculation up to 3 times to satisfy
     63  * drm_timestamp_precision before giving up.
     64  */
     65 #define DRM_TIMESTAMP_MAXRETRIES 3
     66 
     67 /* Threshold in nanoseconds for detection of redundant
     68  * vblank irq in drm_handle_vblank(). 1 msec should be ok.
     69  */
     70 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
     71 
     72 /**
     73  * Get interrupt from bus id.
     74  *
     75  * \param inode device inode.
     76  * \param file_priv DRM file private.
     77  * \param cmd command.
     78  * \param arg user argument, pointing to a drm_irq_busid structure.
     79  * \return zero on success or a negative number on failure.
     80  *
     81  * Finds the PCI device with the specified bus id and gets its IRQ number.
     82  * This IOCTL is deprecated, and will now return EINVAL for any busid not equal
     83  * to that of the device that this DRM instance attached to.
     84  */
     85 int drm_irq_by_busid(struct drm_device *dev, void *data,
     86 		     struct drm_file *file_priv)
     87 {
     88 	struct drm_irq_busid *p = data;
     89 
     90 	if (!dev->driver->bus->irq_by_busid)
     91 		return -EINVAL;
     92 
     93 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
     94 		return -EINVAL;
     95 
     96 	return dev->driver->bus->irq_by_busid(dev, p);
     97 }
     98 
     99 /*
    100  * Clear vblank timestamp buffer for a crtc.
    101  */
    102 static void clear_vblank_timestamps(struct drm_device *dev, int crtc)
    103 {
    104 	memset(dev->vblank[crtc].time, 0, sizeof(dev->vblank[crtc].time));
    105 }
    106 
    107 /*
    108  * Disable vblank irq's on crtc, make sure that last vblank count
    109  * of hardware and corresponding consistent software vblank counter
    110  * are preserved, even if there are any spurious vblank irq's after
    111  * disable.
    112  */
    113 static void vblank_disable_and_save(struct drm_device *dev, int crtc)
    114 {
    115 	unsigned long irqflags;
    116 	u32 vblcount;
    117 	s64 diff_ns;
    118 	int vblrc;
    119 	struct timeval tvblank;
    120 	int count = DRM_TIMESTAMP_MAXRETRIES;
    121 
    122 	/* Prevent vblank irq processing while disabling vblank irqs,
    123 	 * so no updates of timestamps or count can happen after we've
    124 	 * disabled. Needed to prevent races in case of delayed irq's.
    125 	 */
    126 	spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
    127 
    128 	dev->driver->disable_vblank(dev, crtc);
    129 	dev->vblank[crtc].enabled = false;
    130 
    131 	/* No further vblank irq's will be processed after
    132 	 * this point. Get current hardware vblank count and
    133 	 * vblank timestamp, repeat until they are consistent.
    134 	 *
    135 	 * FIXME: There is still a race condition here and in
    136 	 * drm_update_vblank_count() which can cause off-by-one
    137 	 * reinitialization of software vblank counter. If gpu
    138 	 * vblank counter doesn't increment exactly at the leading
    139 	 * edge of a vblank interval, then we can lose 1 count if
    140 	 * we happen to execute between start of vblank and the
    141 	 * delayed gpu counter increment.
    142 	 */
    143 	do {
    144 		dev->vblank[crtc].last = dev->driver->get_vblank_counter(dev, crtc);
    145 		vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
    146 	} while (dev->vblank[crtc].last != dev->driver->get_vblank_counter(dev, crtc) && (--count) && vblrc);
    147 
    148 	if (!count)
    149 		vblrc = 0;
    150 
    151 	/* Compute time difference to stored timestamp of last vblank
    152 	 * as updated by last invocation of drm_handle_vblank() in vblank irq.
    153 	 */
    154 	vblcount = atomic_read(&dev->vblank[crtc].count);
    155 	diff_ns = timeval_to_ns(&tvblank) -
    156 		  timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
    157 
    158 	/* If there is at least 1 msec difference between the last stored
    159 	 * timestamp and tvblank, then we are currently executing our
    160 	 * disable inside a new vblank interval, the tvblank timestamp
    161 	 * corresponds to this new vblank interval and the irq handler
    162 	 * for this vblank didn't run yet and won't run due to our disable.
    163 	 * Therefore we need to do the job of drm_handle_vblank() and
    164 	 * increment the vblank counter by one to account for this vblank.
    165 	 *
    166 	 * Skip this step if there isn't any high precision timestamp
    167 	 * available. In that case we can't account for this and just
    168 	 * hope for the best.
    169 	 */
    170 	if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
    171 		atomic_inc(&dev->vblank[crtc].count);
    172 		smp_mb__after_atomic_inc();
    173 	}
    174 
    175 	/* Invalidate all timestamps while vblank irq's are off. */
    176 	clear_vblank_timestamps(dev, crtc);
    177 
    178 	spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
    179 }
    180 
    181 static void vblank_disable_fn(unsigned long arg)
    182 {
    183 	struct drm_device *dev = (struct drm_device *)arg;
    184 	unsigned long irqflags;
    185 	int i;
    186 
    187 	if (!dev->vblank_disable_allowed)
    188 		return;
    189 
    190 	for (i = 0; i < dev->num_crtcs; i++) {
    191 		spin_lock_irqsave(&dev->vbl_lock, irqflags);
    192 		if (atomic_read(&dev->vblank[i].refcount) == 0 &&
    193 		    dev->vblank[i].enabled) {
    194 			DRM_DEBUG("disabling vblank on crtc %d\n", i);
    195 			vblank_disable_and_save(dev, i);
    196 		}
    197 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
    198 	}
    199 }
    200 
    201 void drm_vblank_cleanup(struct drm_device *dev)
    202 {
    203 	/* Bail if the driver didn't call drm_vblank_init() */
    204 	if (dev->num_crtcs == 0)
    205 		return;
    206 
    207 	del_timer_sync(&dev->vblank_disable_timer);
    208 #ifdef __NetBSD__
    209 	teardown_timer(&dev->vblank_disable_timer);
    210 #endif
    211 
    212 	vblank_disable_fn((unsigned long)dev);
    213 
    214 #ifdef __NetBSD__
    215     {
    216 	unsigned int i;
    217 	for (i = 0; i < dev->num_crtcs; i++)
    218 		DRM_DESTROY_WAITQUEUE(&dev->vblank[i].queue);
    219     }
    220 #endif
    221 
    222 	kfree(dev->vblank);
    223 
    224 	dev->num_crtcs = 0;
    225 
    226 #ifdef __NetBSD__
    227 	spin_lock_destroy(&dev->vblank_time_lock);
    228 	spin_lock_destroy(&dev->vbl_lock);
    229 #endif
    230 }
    231 EXPORT_SYMBOL(drm_vblank_cleanup);
    232 
    233 int drm_vblank_init(struct drm_device *dev, int num_crtcs)
    234 {
    235 	int i, ret = -ENOMEM;
    236 
    237 	setup_timer(&dev->vblank_disable_timer, vblank_disable_fn,
    238 		    (unsigned long)dev);
    239 	spin_lock_init(&dev->vbl_lock);
    240 	spin_lock_init(&dev->vblank_time_lock);
    241 
    242 	dev->num_crtcs = num_crtcs;
    243 
    244 	dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
    245 	if (!dev->vblank)
    246 		goto err;
    247 
    248 	for (i = 0; i < num_crtcs; i++)
    249 #ifdef __NetBSD__
    250 		DRM_INIT_WAITQUEUE(&dev->vblank[i].queue, "drmvblnq");
    251 #else
    252 		init_waitqueue_head(&dev->vblank[i].queue);
    253 #endif
    254 
    255 	DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
    256 
    257 	/* Driver specific high-precision vblank timestamping supported? */
    258 	if (dev->driver->get_vblank_timestamp)
    259 		DRM_INFO("Driver supports precise vblank timestamp query.\n");
    260 	else
    261 		DRM_INFO("No driver support for vblank timestamp query.\n");
    262 
    263 	dev->vblank_disable_allowed = false;
    264 
    265 	return 0;
    266 
    267 err:
    268 	drm_vblank_cleanup(dev);
    269 	return ret;
    270 }
    271 EXPORT_SYMBOL(drm_vblank_init);
    272 
    273 static void drm_irq_vgaarb_nokms(void *cookie, bool state)
    274 {
    275 	struct drm_device *dev = cookie;
    276 
    277 	if (dev->driver->vgaarb_irq) {
    278 		dev->driver->vgaarb_irq(dev, state);
    279 		return;
    280 	}
    281 
    282 	if (!dev->irq_enabled)
    283 		return;
    284 
    285 	if (state) {
    286 		if (dev->driver->irq_uninstall)
    287 			dev->driver->irq_uninstall(dev);
    288 	} else {
    289 		if (dev->driver->irq_preinstall)
    290 			dev->driver->irq_preinstall(dev);
    291 		if (dev->driver->irq_postinstall)
    292 			dev->driver->irq_postinstall(dev);
    293 	}
    294 }
    295 
    296 /**
    297  * Install IRQ handler.
    298  *
    299  * \param dev DRM device.
    300  *
    301  * Initializes the IRQ related data. Installs the handler, calling the driver
    302  * \c irq_preinstall() and \c irq_postinstall() functions
    303  * before and after the installation.
    304  */
    305 int drm_irq_install(struct drm_device *dev)
    306 {
    307 	int ret;
    308 	unsigned long sh_flags = 0;
    309 	const char *irqname;
    310 
    311 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
    312 		return -EINVAL;
    313 
    314 	if (drm_dev_to_irq(dev) == 0)
    315 		return -EINVAL;
    316 
    317 	mutex_lock(&dev->struct_mutex);
    318 
    319 	/* Driver must have been initialized */
    320 	if (!dev->dev_private) {
    321 		mutex_unlock(&dev->struct_mutex);
    322 		return -EINVAL;
    323 	}
    324 
    325 	if (dev->irq_enabled) {
    326 		mutex_unlock(&dev->struct_mutex);
    327 		return -EBUSY;
    328 	}
    329 	dev->irq_enabled = true;
    330 	mutex_unlock(&dev->struct_mutex);
    331 
    332 	DRM_DEBUG("irq=%d\n", drm_dev_to_irq(dev));
    333 
    334 	/* Before installing handler */
    335 	if (dev->driver->irq_preinstall)
    336 		dev->driver->irq_preinstall(dev);
    337 
    338 	/* Install handler */
    339 	if (drm_core_check_feature(dev, DRIVER_IRQ_SHARED))
    340 		sh_flags = IRQF_SHARED;
    341 
    342 	if (dev->devname)
    343 		irqname = dev->devname;
    344 	else
    345 		irqname = dev->driver->name;
    346 
    347 #ifdef __NetBSD__
    348 	ret = (*dev->driver->bus->irq_install)(dev, dev->driver->irq_handler,
    349 	    sh_flags, irqname, dev, &dev->irq_cookie);
    350 #else
    351 	ret = request_irq(drm_dev_to_irq(dev), dev->driver->irq_handler,
    352 			  sh_flags, irqname, dev);
    353 #endif
    354 
    355 	if (ret < 0) {
    356 		mutex_lock(&dev->struct_mutex);
    357 		dev->irq_enabled = false;
    358 		mutex_unlock(&dev->struct_mutex);
    359 		return ret;
    360 	}
    361 
    362 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
    363 		vga_client_register(dev->pdev, (void *)dev, drm_irq_vgaarb_nokms, NULL);
    364 
    365 	/* After installing handler */
    366 	if (dev->driver->irq_postinstall)
    367 		ret = dev->driver->irq_postinstall(dev);
    368 
    369 	if (ret < 0) {
    370 		mutex_lock(&dev->struct_mutex);
    371 		dev->irq_enabled = false;
    372 		mutex_unlock(&dev->struct_mutex);
    373 		if (!drm_core_check_feature(dev, DRIVER_MODESET))
    374 			vga_client_register(dev->pdev, NULL, NULL, NULL);
    375 #ifdef __NetBSD__
    376 		(*dev->driver->bus->irq_uninstall)(dev, dev->irq_cookie);
    377 #else
    378 		free_irq(drm_dev_to_irq(dev), dev);
    379 #endif
    380 	}
    381 
    382 	return ret;
    383 }
    384 EXPORT_SYMBOL(drm_irq_install);
    385 
    386 /**
    387  * Uninstall the IRQ handler.
    388  *
    389  * \param dev DRM device.
    390  *
    391  * Calls the driver's \c irq_uninstall() function, and stops the irq.
    392  */
    393 int drm_irq_uninstall(struct drm_device *dev)
    394 {
    395 	unsigned long irqflags;
    396 	bool irq_enabled;
    397 	int i;
    398 
    399 	if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
    400 		return -EINVAL;
    401 
    402 	mutex_lock(&dev->struct_mutex);
    403 	irq_enabled = dev->irq_enabled;
    404 	dev->irq_enabled = false;
    405 	mutex_unlock(&dev->struct_mutex);
    406 
    407 	/*
    408 	 * Wake up any waiters so they don't hang.
    409 	 */
    410 	if (dev->num_crtcs) {
    411 		spin_lock_irqsave(&dev->vbl_lock, irqflags);
    412 		for (i = 0; i < dev->num_crtcs; i++) {
    413 #ifdef __NetBSD__
    414 			DRM_SPIN_WAKEUP_ONE(&dev->vblank[i].queue,
    415 			    &dev->vbl_lock);
    416 #else
    417 			wake_up(&dev->vblank[i].queue);
    418 #endif
    419 			dev->vblank[i].enabled = false;
    420 			dev->vblank[i].last =
    421 				dev->driver->get_vblank_counter(dev, i);
    422 		}
    423 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
    424 	}
    425 
    426 	if (!irq_enabled)
    427 		return -EINVAL;
    428 
    429 	DRM_DEBUG("irq=%d\n", drm_dev_to_irq(dev));
    430 
    431 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
    432 		vga_client_register(dev->pdev, NULL, NULL, NULL);
    433 
    434 	if (dev->driver->irq_uninstall)
    435 		dev->driver->irq_uninstall(dev);
    436 
    437 #ifdef __NetBSD__
    438 	(*dev->driver->bus->irq_uninstall)(dev, dev->irq_cookie);
    439 #else
    440 	free_irq(drm_dev_to_irq(dev), dev);
    441 #endif
    442 
    443 	return 0;
    444 }
    445 EXPORT_SYMBOL(drm_irq_uninstall);
    446 
    447 /**
    448  * IRQ control ioctl.
    449  *
    450  * \param inode device inode.
    451  * \param file_priv DRM file private.
    452  * \param cmd command.
    453  * \param arg user argument, pointing to a drm_control structure.
    454  * \return zero on success or a negative number on failure.
    455  *
    456  * Calls irq_install() or irq_uninstall() according to \p arg.
    457  */
    458 int drm_control(struct drm_device *dev, void *data,
    459 		struct drm_file *file_priv)
    460 {
    461 	struct drm_control *ctl = data;
    462 
    463 	/* if we haven't irq we fallback for compatibility reasons -
    464 	 * this used to be a separate function in drm_dma.h
    465 	 */
    466 
    467 
    468 	switch (ctl->func) {
    469 	case DRM_INST_HANDLER:
    470 		if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
    471 			return 0;
    472 		if (drm_core_check_feature(dev, DRIVER_MODESET))
    473 			return 0;
    474 		if (dev->if_version < DRM_IF_VERSION(1, 2) &&
    475 		    ctl->irq != drm_dev_to_irq(dev))
    476 			return -EINVAL;
    477 		return drm_irq_install(dev);
    478 	case DRM_UNINST_HANDLER:
    479 		if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
    480 			return 0;
    481 		if (drm_core_check_feature(dev, DRIVER_MODESET))
    482 			return 0;
    483 		return drm_irq_uninstall(dev);
    484 	default:
    485 		return -EINVAL;
    486 	}
    487 }
    488 
    489 /**
    490  * drm_calc_timestamping_constants - Calculate vblank timestamp constants
    491  *
    492  * @crtc drm_crtc whose timestamp constants should be updated.
    493  * @mode display mode containing the scanout timings
    494  *
    495  * Calculate and store various constants which are later
    496  * needed by vblank and swap-completion timestamping, e.g,
    497  * by drm_calc_vbltimestamp_from_scanoutpos(). They are
    498  * derived from crtc's true scanout timing, so they take
    499  * things like panel scaling or other adjustments into account.
    500  */
    501 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
    502 				     const struct drm_display_mode *mode)
    503 {
    504 	int linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
    505 	int dotclock = mode->crtc_clock;
    506 
    507 	/* Valid dotclock? */
    508 	if (dotclock > 0) {
    509 		int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
    510 
    511 		/*
    512 		 * Convert scanline length in pixels and video
    513 		 * dot clock to line duration, frame duration
    514 		 * and pixel duration in nanoseconds:
    515 		 */
    516 		pixeldur_ns = 1000000 / dotclock;
    517 		linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
    518 		framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
    519 
    520 		/*
    521 		 * Fields of interlaced scanout modes are only half a frame duration.
    522 		 */
    523 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
    524 			framedur_ns /= 2;
    525 	} else
    526 		DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
    527 			  crtc->base.id);
    528 
    529 	crtc->pixeldur_ns = pixeldur_ns;
    530 	crtc->linedur_ns  = linedur_ns;
    531 	crtc->framedur_ns = framedur_ns;
    532 
    533 	DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
    534 		  crtc->base.id, mode->crtc_htotal,
    535 		  mode->crtc_vtotal, mode->crtc_vdisplay);
    536 	DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
    537 		  crtc->base.id, dotclock, framedur_ns,
    538 		  linedur_ns, pixeldur_ns);
    539 }
    540 EXPORT_SYMBOL(drm_calc_timestamping_constants);
    541 
    542 /**
    543  * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
    544  * drivers. Implements calculation of exact vblank timestamps from
    545  * given drm_display_mode timings and current video scanout position
    546  * of a crtc. This can be called from within get_vblank_timestamp()
    547  * implementation of a kms driver to implement the actual timestamping.
    548  *
    549  * Should return timestamps conforming to the OML_sync_control OpenML
    550  * extension specification. The timestamp corresponds to the end of
    551  * the vblank interval, aka start of scanout of topmost-leftmost display
    552  * pixel in the following video frame.
    553  *
    554  * Requires support for optional dev->driver->get_scanout_position()
    555  * in kms driver, plus a bit of setup code to provide a drm_display_mode
    556  * that corresponds to the true scanout timing.
    557  *
    558  * The current implementation only handles standard video modes. It
    559  * returns as no operation if a doublescan or interlaced video mode is
    560  * active. Higher level code is expected to handle this.
    561  *
    562  * @dev: DRM device.
    563  * @crtc: Which crtc's vblank timestamp to retrieve.
    564  * @max_error: Desired maximum allowable error in timestamps (nanosecs).
    565  *             On return contains true maximum error of timestamp.
    566  * @vblank_time: Pointer to struct timeval which should receive the timestamp.
    567  * @flags: Flags to pass to driver:
    568  *         0 = Default.
    569  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
    570  * @refcrtc: drm_crtc* of crtc which defines scanout timing.
    571  * @mode: mode which defines the scanout timings
    572  *
    573  * Returns negative value on error, failure or if not supported in current
    574  * video mode:
    575  *
    576  * -EINVAL   - Invalid crtc.
    577  * -EAGAIN   - Temporary unavailable, e.g., called before initial modeset.
    578  * -ENOTSUPP - Function not supported in current display mode.
    579  * -EIO      - Failed, e.g., due to failed scanout position query.
    580  *
    581  * Returns or'ed positive status flags on success:
    582  *
    583  * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
    584  * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
    585  *
    586  */
    587 int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
    588 					  int *max_error,
    589 					  struct timeval *vblank_time,
    590 					  unsigned flags,
    591 					  const struct drm_crtc *refcrtc,
    592 					  const struct drm_display_mode *mode)
    593 {
    594 	ktime_t stime, etime, mono_time_offset;
    595 	struct timeval tv_etime;
    596 	int vbl_status;
    597 	int vpos, hpos, i;
    598 	int framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
    599 	bool invbl;
    600 
    601 	if (crtc < 0 || crtc >= dev->num_crtcs) {
    602 		DRM_ERROR("Invalid crtc %d\n", crtc);
    603 		return -EINVAL;
    604 	}
    605 
    606 	/* Scanout position query not supported? Should not happen. */
    607 	if (!dev->driver->get_scanout_position) {
    608 		DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
    609 		return -EIO;
    610 	}
    611 
    612 	/* Durations of frames, lines, pixels in nanoseconds. */
    613 	framedur_ns = refcrtc->framedur_ns;
    614 	linedur_ns  = refcrtc->linedur_ns;
    615 	pixeldur_ns = refcrtc->pixeldur_ns;
    616 
    617 	/* If mode timing undefined, just return as no-op:
    618 	 * Happens during initial modesetting of a crtc.
    619 	 */
    620 	if (framedur_ns == 0) {
    621 		DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
    622 		return -EAGAIN;
    623 	}
    624 
    625 	/* Get current scanout position with system timestamp.
    626 	 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
    627 	 * if single query takes longer than max_error nanoseconds.
    628 	 *
    629 	 * This guarantees a tight bound on maximum error if
    630 	 * code gets preempted or delayed for some reason.
    631 	 */
    632 	for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
    633 		/*
    634 		 * Get vertical and horizontal scanout position vpos, hpos,
    635 		 * and bounding timestamps stime, etime, pre/post query.
    636 		 */
    637 		vbl_status = dev->driver->get_scanout_position(dev, crtc, flags, &vpos,
    638 							       &hpos, &stime, &etime);
    639 
    640 		/*
    641 		 * Get correction for CLOCK_MONOTONIC -> CLOCK_REALTIME if
    642 		 * CLOCK_REALTIME is requested.
    643 		 */
    644 		if (!drm_timestamp_monotonic)
    645 			mono_time_offset = ktime_get_monotonic_offset();
    646 
    647 		/* Return as no-op if scanout query unsupported or failed. */
    648 		if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
    649 			DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
    650 				  crtc, vbl_status);
    651 			return -EIO;
    652 		}
    653 
    654 		/* Compute uncertainty in timestamp of scanout position query. */
    655 		duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
    656 
    657 		/* Accept result with <  max_error nsecs timing uncertainty. */
    658 		if (duration_ns <= *max_error)
    659 			break;
    660 	}
    661 
    662 	/* Noisy system timing? */
    663 	if (i == DRM_TIMESTAMP_MAXRETRIES) {
    664 		DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
    665 			  crtc, duration_ns/1000, *max_error/1000, i);
    666 	}
    667 
    668 	/* Return upper bound of timestamp precision error. */
    669 	*max_error = duration_ns;
    670 
    671 	/* Check if in vblank area:
    672 	 * vpos is >=0 in video scanout area, but negative
    673 	 * within vblank area, counting down the number of lines until
    674 	 * start of scanout.
    675 	 */
    676 	invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
    677 
    678 	/* Convert scanout position into elapsed time at raw_time query
    679 	 * since start of scanout at first display scanline. delta_ns
    680 	 * can be negative if start of scanout hasn't happened yet.
    681 	 */
    682 	delta_ns = vpos * linedur_ns + hpos * pixeldur_ns;
    683 
    684 	if (!drm_timestamp_monotonic)
    685 		etime = ktime_sub(etime, mono_time_offset);
    686 
    687 	/* save this only for debugging purposes */
    688 	tv_etime = ktime_to_timeval(etime);
    689 	/* Subtract time delta from raw timestamp to get final
    690 	 * vblank_time timestamp for end of vblank.
    691 	 */
    692 	if (delta_ns < 0)
    693 		etime = ktime_add_ns(etime, -delta_ns);
    694 	else
    695 		etime = ktime_sub_ns(etime, delta_ns);
    696 	*vblank_time = ktime_to_timeval(etime);
    697 
    698 	DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
    699 		  crtc, (int)vbl_status, hpos, vpos,
    700 		  (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
    701 		  (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
    702 		  duration_ns/1000, i);
    703 
    704 	vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
    705 	if (invbl)
    706 		vbl_status |= DRM_VBLANKTIME_INVBL;
    707 
    708 	return vbl_status;
    709 }
    710 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
    711 
    712 static struct timeval get_drm_timestamp(void)
    713 {
    714 	ktime_t now;
    715 
    716 	now = ktime_get();
    717 	if (!drm_timestamp_monotonic)
    718 		now = ktime_sub(now, ktime_get_monotonic_offset());
    719 
    720 	return ktime_to_timeval(now);
    721 }
    722 
    723 /**
    724  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
    725  * vblank interval.
    726  *
    727  * @dev: DRM device
    728  * @crtc: which crtc's vblank timestamp to retrieve
    729  * @tvblank: Pointer to target struct timeval which should receive the timestamp
    730  * @flags: Flags to pass to driver:
    731  *         0 = Default.
    732  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
    733  *
    734  * Fetches the system timestamp corresponding to the time of the most recent
    735  * vblank interval on specified crtc. May call into kms-driver to
    736  * compute the timestamp with a high-precision GPU specific method.
    737  *
    738  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
    739  * call, i.e., it isn't very precisely locked to the true vblank.
    740  *
    741  * Returns non-zero if timestamp is considered to be very precise.
    742  */
    743 u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
    744 			      struct timeval *tvblank, unsigned flags)
    745 {
    746 	int ret;
    747 
    748 	/* Define requested maximum error on timestamps (nanoseconds). */
    749 	int max_error = (int) drm_timestamp_precision * 1000;
    750 
    751 	/* Query driver if possible and precision timestamping enabled. */
    752 	if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
    753 		ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
    754 							tvblank, flags);
    755 		if (ret > 0)
    756 			return (u32) ret;
    757 	}
    758 
    759 	/* GPU high precision timestamp query unsupported or failed.
    760 	 * Return current monotonic/gettimeofday timestamp as best estimate.
    761 	 */
    762 	*tvblank = get_drm_timestamp();
    763 
    764 	return 0;
    765 }
    766 EXPORT_SYMBOL(drm_get_last_vbltimestamp);
    767 
    768 /**
    769  * drm_vblank_count - retrieve "cooked" vblank counter value
    770  * @dev: DRM device
    771  * @crtc: which counter to retrieve
    772  *
    773  * Fetches the "cooked" vblank count value that represents the number of
    774  * vblank events since the system was booted, including lost events due to
    775  * modesetting activity.
    776  */
    777 u32 drm_vblank_count(struct drm_device *dev, int crtc)
    778 {
    779 	return atomic_read(&dev->vblank[crtc].count);
    780 }
    781 EXPORT_SYMBOL(drm_vblank_count);
    782 
    783 /**
    784  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
    785  * and the system timestamp corresponding to that vblank counter value.
    786  *
    787  * @dev: DRM device
    788  * @crtc: which counter to retrieve
    789  * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
    790  *
    791  * Fetches the "cooked" vblank count value that represents the number of
    792  * vblank events since the system was booted, including lost events due to
    793  * modesetting activity. Returns corresponding system timestamp of the time
    794  * of the vblank interval that corresponds to the current value vblank counter
    795  * value.
    796  */
    797 u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
    798 			      struct timeval *vblanktime)
    799 {
    800 	u32 cur_vblank;
    801 
    802 	/* Read timestamp from slot of _vblank_time ringbuffer
    803 	 * that corresponds to current vblank count. Retry if
    804 	 * count has incremented during readout. This works like
    805 	 * a seqlock.
    806 	 */
    807 	do {
    808 		cur_vblank = atomic_read(&dev->vblank[crtc].count);
    809 		*vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
    810 		smp_rmb();
    811 	} while (cur_vblank != atomic_read(&dev->vblank[crtc].count));
    812 
    813 	return cur_vblank;
    814 }
    815 EXPORT_SYMBOL(drm_vblank_count_and_time);
    816 
    817 static void send_vblank_event(struct drm_device *dev,
    818 		struct drm_pending_vblank_event *e,
    819 		unsigned long seq, struct timeval *now)
    820 {
    821 	WARN_ON_SMP(!spin_is_locked(&dev->event_lock));
    822 	e->event.sequence = seq;
    823 	e->event.tv_sec = now->tv_sec;
    824 	e->event.tv_usec = now->tv_usec;
    825 
    826 	list_add_tail(&e->base.link,
    827 		      &e->base.file_priv->event_list);
    828 #ifdef __NetBSD__
    829 	DRM_SPIN_WAKEUP_ONE(&e->base.file_priv->event_wait, &dev->event_lock);
    830 	selnotify(&e->base.file_priv->event_selq, (POLLIN | POLLRDNORM),
    831 	    NOTE_SUBMIT);
    832 #else
    833 	wake_up_interruptible(&e->base.file_priv->event_wait);
    834 #endif
    835 	trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
    836 					 e->event.sequence);
    837 }
    838 
    839 /**
    840  * drm_send_vblank_event - helper to send vblank event after pageflip
    841  * @dev: DRM device
    842  * @crtc: CRTC in question
    843  * @e: the event to send
    844  *
    845  * Updates sequence # and timestamp on event, and sends it to userspace.
    846  * Caller must hold event lock.
    847  */
    848 void drm_send_vblank_event(struct drm_device *dev, int crtc,
    849 		struct drm_pending_vblank_event *e)
    850 {
    851 	struct timeval now;
    852 	unsigned int seq;
    853 	if (crtc >= 0) {
    854 		seq = drm_vblank_count_and_time(dev, crtc, &now);
    855 	} else {
    856 		seq = 0;
    857 
    858 		now = get_drm_timestamp();
    859 	}
    860 	e->pipe = crtc;
    861 	send_vblank_event(dev, e, seq, &now);
    862 }
    863 EXPORT_SYMBOL(drm_send_vblank_event);
    864 
    865 /**
    866  * drm_update_vblank_count - update the master vblank counter
    867  * @dev: DRM device
    868  * @crtc: counter to update
    869  *
    870  * Call back into the driver to update the appropriate vblank counter
    871  * (specified by @crtc).  Deal with wraparound, if it occurred, and
    872  * update the last read value so we can deal with wraparound on the next
    873  * call if necessary.
    874  *
    875  * Only necessary when going from off->on, to account for frames we
    876  * didn't get an interrupt for.
    877  *
    878  * Note: caller must hold dev->vbl_lock since this reads & writes
    879  * device vblank fields.
    880  */
    881 static void drm_update_vblank_count(struct drm_device *dev, int crtc)
    882 {
    883 	u32 cur_vblank, diff, tslot, rc;
    884 	struct timeval t_vblank;
    885 
    886 	/*
    887 	 * Interrupts were disabled prior to this call, so deal with counter
    888 	 * wrap if needed.
    889 	 * NOTE!  It's possible we lost a full dev->max_vblank_count events
    890 	 * here if the register is small or we had vblank interrupts off for
    891 	 * a long time.
    892 	 *
    893 	 * We repeat the hardware vblank counter & timestamp query until
    894 	 * we get consistent results. This to prevent races between gpu
    895 	 * updating its hardware counter while we are retrieving the
    896 	 * corresponding vblank timestamp.
    897 	 */
    898 	do {
    899 		cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
    900 		rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
    901 	} while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
    902 
    903 	/* Deal with counter wrap */
    904 	diff = cur_vblank - dev->vblank[crtc].last;
    905 	if (cur_vblank < dev->vblank[crtc].last) {
    906 		diff += dev->max_vblank_count;
    907 
    908 		DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
    909 			  crtc, dev->vblank[crtc].last, cur_vblank, diff);
    910 	}
    911 
    912 	DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
    913 		  crtc, diff);
    914 
    915 	/* Reinitialize corresponding vblank timestamp if high-precision query
    916 	 * available. Skip this step if query unsupported or failed. Will
    917 	 * reinitialize delayed at next vblank interrupt in that case.
    918 	 */
    919 	if (rc) {
    920 		tslot = atomic_read(&dev->vblank[crtc].count) + diff;
    921 		vblanktimestamp(dev, crtc, tslot) = t_vblank;
    922 	}
    923 
    924 	smp_mb__before_atomic_inc();
    925 	atomic_add(diff, &dev->vblank[crtc].count);
    926 	smp_mb__after_atomic_inc();
    927 }
    928 
    929 /**
    930  * drm_vblank_get - get a reference count on vblank events
    931  * @dev: DRM device
    932  * @crtc: which CRTC to own
    933  *
    934  * Acquire a reference count on vblank events to avoid having them disabled
    935  * while in use.
    936  *
    937  * RETURNS
    938  * Zero on success, nonzero on failure.
    939  */
    940 int drm_vblank_get(struct drm_device *dev, int crtc)
    941 {
    942 	unsigned long irqflags, irqflags2;
    943 	int ret = 0;
    944 
    945 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
    946 	/* Going from 0->1 means we have to enable interrupts again */
    947 	if (atomic_add_return(1, &dev->vblank[crtc].refcount) == 1) {
    948 		spin_lock_irqsave(&dev->vblank_time_lock, irqflags2);
    949 		if (!dev->vblank[crtc].enabled) {
    950 			/* Enable vblank irqs under vblank_time_lock protection.
    951 			 * All vblank count & timestamp updates are held off
    952 			 * until we are done reinitializing master counter and
    953 			 * timestamps. Filtercode in drm_handle_vblank() will
    954 			 * prevent double-accounting of same vblank interval.
    955 			 */
    956 			ret = dev->driver->enable_vblank(dev, crtc);
    957 			DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
    958 				  crtc, ret);
    959 			if (ret)
    960 				atomic_dec(&dev->vblank[crtc].refcount);
    961 			else {
    962 				dev->vblank[crtc].enabled = true;
    963 				drm_update_vblank_count(dev, crtc);
    964 			}
    965 		}
    966 		spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags2);
    967 	} else {
    968 		if (!dev->vblank[crtc].enabled) {
    969 			atomic_dec(&dev->vblank[crtc].refcount);
    970 			ret = -EINVAL;
    971 		}
    972 	}
    973 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
    974 
    975 	return ret;
    976 }
    977 EXPORT_SYMBOL(drm_vblank_get);
    978 
    979 /**
    980  * drm_vblank_put - give up ownership of vblank events
    981  * @dev: DRM device
    982  * @crtc: which counter to give up
    983  *
    984  * Release ownership of a given vblank counter, turning off interrupts
    985  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
    986  */
    987 void drm_vblank_put(struct drm_device *dev, int crtc)
    988 {
    989 	BUG_ON(atomic_read(&dev->vblank[crtc].refcount) == 0);
    990 
    991 	/* Last user schedules interrupt disable */
    992 	if (atomic_dec_and_test(&dev->vblank[crtc].refcount) &&
    993 	    (drm_vblank_offdelay > 0))
    994 		mod_timer(&dev->vblank_disable_timer,
    995 			  jiffies + ((drm_vblank_offdelay * HZ)/1000));
    996 }
    997 EXPORT_SYMBOL(drm_vblank_put);
    998 
    999 /**
   1000  * drm_vblank_off - disable vblank events on a CRTC
   1001  * @dev: DRM device
   1002  * @crtc: CRTC in question
   1003  *
   1004  * Caller must hold event lock.
   1005  */
   1006 void drm_vblank_off(struct drm_device *dev, int crtc)
   1007 {
   1008 	struct drm_pending_vblank_event *e, *t;
   1009 	struct timeval now;
   1010 	unsigned long irqflags;
   1011 	unsigned int seq;
   1012 
   1013 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
   1014 	vblank_disable_and_save(dev, crtc);
   1015 #ifdef __NetBSD__
   1016 	DRM_SPIN_WAKEUP_ONE(&dev->vblank[crtc].queue, &dev->vbl_lock);
   1017 #else
   1018 	wake_up(&dev->vblank[crtc].queue);
   1019 #endif
   1020 
   1021 	/* Send any queued vblank events, lest the natives grow disquiet */
   1022 	seq = drm_vblank_count_and_time(dev, crtc, &now);
   1023 
   1024 	spin_lock(&dev->event_lock);
   1025 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
   1026 		if (e->pipe != crtc)
   1027 			continue;
   1028 		DRM_DEBUG("Sending premature vblank event on disable: \
   1029 			  wanted %d, current %d\n",
   1030 			  e->event.sequence, seq);
   1031 		list_del(&e->base.link);
   1032 		drm_vblank_put(dev, e->pipe);
   1033 		send_vblank_event(dev, e, seq, &now);
   1034 	}
   1035 	spin_unlock(&dev->event_lock);
   1036 
   1037 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
   1038 }
   1039 EXPORT_SYMBOL(drm_vblank_off);
   1040 
   1041 /**
   1042  * drm_vblank_pre_modeset - account for vblanks across mode sets
   1043  * @dev: DRM device
   1044  * @crtc: CRTC in question
   1045  *
   1046  * Account for vblank events across mode setting events, which will likely
   1047  * reset the hardware frame counter.
   1048  */
   1049 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
   1050 {
   1051 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
   1052 	if (!dev->num_crtcs)
   1053 		return;
   1054 	/*
   1055 	 * To avoid all the problems that might happen if interrupts
   1056 	 * were enabled/disabled around or between these calls, we just
   1057 	 * have the kernel take a reference on the CRTC (just once though
   1058 	 * to avoid corrupting the count if multiple, mismatch calls occur),
   1059 	 * so that interrupts remain enabled in the interim.
   1060 	 */
   1061 	if (!dev->vblank[crtc].inmodeset) {
   1062 		dev->vblank[crtc].inmodeset = 0x1;
   1063 		if (drm_vblank_get(dev, crtc) == 0)
   1064 			dev->vblank[crtc].inmodeset |= 0x2;
   1065 	}
   1066 }
   1067 EXPORT_SYMBOL(drm_vblank_pre_modeset);
   1068 
   1069 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
   1070 {
   1071 	unsigned long irqflags;
   1072 
   1073 	/* vblank is not initialized (IRQ not installed ?), or has been freed */
   1074 	if (!dev->num_crtcs)
   1075 		return;
   1076 
   1077 	if (dev->vblank[crtc].inmodeset) {
   1078 		spin_lock_irqsave(&dev->vbl_lock, irqflags);
   1079 		dev->vblank_disable_allowed = true;
   1080 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
   1081 
   1082 		if (dev->vblank[crtc].inmodeset & 0x2)
   1083 			drm_vblank_put(dev, crtc);
   1084 
   1085 		dev->vblank[crtc].inmodeset = 0;
   1086 	}
   1087 }
   1088 EXPORT_SYMBOL(drm_vblank_post_modeset);
   1089 
   1090 /**
   1091  * drm_modeset_ctl - handle vblank event counter changes across mode switch
   1092  * @DRM_IOCTL_ARGS: standard ioctl arguments
   1093  *
   1094  * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
   1095  * ioctls around modesetting so that any lost vblank events are accounted for.
   1096  *
   1097  * Generally the counter will reset across mode sets.  If interrupts are
   1098  * enabled around this call, we don't have to do anything since the counter
   1099  * will have already been incremented.
   1100  */
   1101 int drm_modeset_ctl(struct drm_device *dev, void *data,
   1102 		    struct drm_file *file_priv)
   1103 {
   1104 	struct drm_modeset_ctl *modeset = data;
   1105 	unsigned int crtc;
   1106 
   1107 	/* If drm_vblank_init() hasn't been called yet, just no-op */
   1108 	if (!dev->num_crtcs)
   1109 		return 0;
   1110 
   1111 	/* KMS drivers handle this internally */
   1112 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   1113 		return 0;
   1114 
   1115 	crtc = modeset->crtc;
   1116 	if (crtc >= dev->num_crtcs)
   1117 		return -EINVAL;
   1118 
   1119 	switch (modeset->cmd) {
   1120 	case _DRM_PRE_MODESET:
   1121 		drm_vblank_pre_modeset(dev, crtc);
   1122 		break;
   1123 	case _DRM_POST_MODESET:
   1124 		drm_vblank_post_modeset(dev, crtc);
   1125 		break;
   1126 	default:
   1127 		return -EINVAL;
   1128 	}
   1129 
   1130 	return 0;
   1131 }
   1132 
   1133 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
   1134 				  union drm_wait_vblank *vblwait,
   1135 				  struct drm_file *file_priv)
   1136 {
   1137 	struct drm_pending_vblank_event *e;
   1138 	struct timeval now;
   1139 	unsigned long flags;
   1140 	unsigned int seq;
   1141 	int ret;
   1142 
   1143 	e = kzalloc(sizeof *e, GFP_KERNEL);
   1144 	if (e == NULL) {
   1145 		ret = -ENOMEM;
   1146 		goto err_put;
   1147 	}
   1148 
   1149 	e->pipe = pipe;
   1150 #ifdef __NetBSD__
   1151 	e->base.pid = curproc->p_pid;
   1152 #else
   1153 	e->base.pid = current->pid;
   1154 #endif
   1155 	e->event.base.type = DRM_EVENT_VBLANK;
   1156 	e->event.base.length = sizeof e->event;
   1157 	e->event.user_data = vblwait->request.signal;
   1158 	e->base.event = &e->event.base;
   1159 	e->base.file_priv = file_priv;
   1160 	e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
   1161 
   1162 	spin_lock_irqsave(&dev->event_lock, flags);
   1163 
   1164 	if (file_priv->event_space < sizeof e->event) {
   1165 		ret = -EBUSY;
   1166 		goto err_unlock;
   1167 	}
   1168 
   1169 	file_priv->event_space -= sizeof e->event;
   1170 	seq = drm_vblank_count_and_time(dev, pipe, &now);
   1171 
   1172 	if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
   1173 	    (seq - vblwait->request.sequence) <= (1 << 23)) {
   1174 		vblwait->request.sequence = seq + 1;
   1175 		vblwait->reply.sequence = vblwait->request.sequence;
   1176 	}
   1177 
   1178 	DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
   1179 		  vblwait->request.sequence, seq, pipe);
   1180 
   1181 #ifdef __NetBSD__
   1182 	trace_drm_vblank_event_queued(curproc->p_pid, pipe,
   1183 				      vblwait->request.sequence);
   1184 #else
   1185 	trace_drm_vblank_event_queued(current->pid, pipe,
   1186 				      vblwait->request.sequence);
   1187 #endif
   1188 
   1189 	e->event.sequence = vblwait->request.sequence;
   1190 	if ((seq - vblwait->request.sequence) <= (1 << 23)) {
   1191 		drm_vblank_put(dev, pipe);
   1192 		send_vblank_event(dev, e, seq, &now);
   1193 		vblwait->reply.sequence = seq;
   1194 	} else {
   1195 		/* drm_handle_vblank_events will call drm_vblank_put */
   1196 		list_add_tail(&e->base.link, &dev->vblank_event_list);
   1197 		vblwait->reply.sequence = vblwait->request.sequence;
   1198 	}
   1199 
   1200 	spin_unlock_irqrestore(&dev->event_lock, flags);
   1201 
   1202 	return 0;
   1203 
   1204 err_unlock:
   1205 	spin_unlock_irqrestore(&dev->event_lock, flags);
   1206 	kfree(e);
   1207 err_put:
   1208 	drm_vblank_put(dev, pipe);
   1209 	return ret;
   1210 }
   1211 
   1212 /**
   1213  * Wait for VBLANK.
   1214  *
   1215  * \param inode device inode.
   1216  * \param file_priv DRM file private.
   1217  * \param cmd command.
   1218  * \param data user argument, pointing to a drm_wait_vblank structure.
   1219  * \return zero on success or a negative number on failure.
   1220  *
   1221  * This function enables the vblank interrupt on the pipe requested, then
   1222  * sleeps waiting for the requested sequence number to occur, and drops
   1223  * the vblank interrupt refcount afterwards. (vblank irq disable follows that
   1224  * after a timeout with no further vblank waits scheduled).
   1225  */
   1226 int drm_wait_vblank(struct drm_device *dev, void *data,
   1227 		    struct drm_file *file_priv)
   1228 {
   1229 	union drm_wait_vblank *vblwait = data;
   1230 	int ret;
   1231 	unsigned int flags, seq, crtc, high_crtc;
   1232 
   1233 	if (drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
   1234 		if ((!drm_dev_to_irq(dev)) || (!dev->irq_enabled))
   1235 			return -EINVAL;
   1236 
   1237 	if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
   1238 		return -EINVAL;
   1239 
   1240 	if (vblwait->request.type &
   1241 	    ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
   1242 	      _DRM_VBLANK_HIGH_CRTC_MASK)) {
   1243 		DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
   1244 			  vblwait->request.type,
   1245 			  (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
   1246 			   _DRM_VBLANK_HIGH_CRTC_MASK));
   1247 		return -EINVAL;
   1248 	}
   1249 
   1250 	flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
   1251 	high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
   1252 	if (high_crtc)
   1253 		crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
   1254 	else
   1255 		crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
   1256 	if (crtc >= dev->num_crtcs)
   1257 		return -EINVAL;
   1258 
   1259 	ret = drm_vblank_get(dev, crtc);
   1260 	if (ret) {
   1261 		DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
   1262 		return ret;
   1263 	}
   1264 	seq = drm_vblank_count(dev, crtc);
   1265 
   1266 	switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
   1267 	case _DRM_VBLANK_RELATIVE:
   1268 		vblwait->request.sequence += seq;
   1269 		vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
   1270 	case _DRM_VBLANK_ABSOLUTE:
   1271 		break;
   1272 	default:
   1273 		ret = -EINVAL;
   1274 		goto done;
   1275 	}
   1276 
   1277 	if (flags & _DRM_VBLANK_EVENT) {
   1278 		/* must hold on to the vblank ref until the event fires
   1279 		 * drm_vblank_put will be called asynchronously
   1280 		 */
   1281 		return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
   1282 	}
   1283 
   1284 	if ((flags & _DRM_VBLANK_NEXTONMISS) &&
   1285 	    (seq - vblwait->request.sequence) <= (1<<23)) {
   1286 		vblwait->request.sequence = seq + 1;
   1287 	}
   1288 
   1289 	DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
   1290 		  vblwait->request.sequence, crtc);
   1291 	dev->vblank[crtc].last_wait = vblwait->request.sequence;
   1292 #ifdef __NetBSD__
   1293     {
   1294 	unsigned long irqflags;
   1295 	spin_lock_irqsave(&dev->vbl_lock, irqflags);
   1296 	DRM_SPIN_TIMED_WAIT_UNTIL(ret, &dev->vblank[crtc].queue,
   1297 	    &dev->vbl_lock,
   1298 	    (3 * HZ),
   1299 	    (((drm_vblank_count(dev, crtc) -
   1300 		    vblwait->request.sequence) <= (1 << 23)) ||
   1301 		!dev->irq_enabled));
   1302 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
   1303 	if (0 < ret)
   1304 		/*
   1305 		 * ret is ticks remaining on success in this case, but
   1306 		 * caller just wants 0 for success.
   1307 		 */
   1308 		ret = 0;
   1309     }
   1310 #else
   1311 	DRM_WAIT_ON(ret, dev->vblank[crtc].queue, 3 * HZ,
   1312 		    (((drm_vblank_count(dev, crtc) -
   1313 		       vblwait->request.sequence) <= (1 << 23)) ||
   1314 		     !dev->irq_enabled));
   1315 #endif
   1316 
   1317 	if (ret != -EINTR) {
   1318 		struct timeval now;
   1319 
   1320 		vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
   1321 		vblwait->reply.tval_sec = now.tv_sec;
   1322 		vblwait->reply.tval_usec = now.tv_usec;
   1323 
   1324 		DRM_DEBUG("returning %d to client\n",
   1325 			  vblwait->reply.sequence);
   1326 	} else {
   1327 		DRM_DEBUG("vblank wait interrupted by signal\n");
   1328 	}
   1329 
   1330 done:
   1331 	drm_vblank_put(dev, crtc);
   1332 	return ret;
   1333 }
   1334 
   1335 static void drm_handle_vblank_events(struct drm_device *dev, int crtc)
   1336 {
   1337 	struct drm_pending_vblank_event *e, *t;
   1338 	struct timeval now;
   1339 	unsigned long flags;
   1340 	unsigned int seq;
   1341 
   1342 	seq = drm_vblank_count_and_time(dev, crtc, &now);
   1343 
   1344 	spin_lock_irqsave(&dev->event_lock, flags);
   1345 
   1346 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
   1347 		if (e->pipe != crtc)
   1348 			continue;
   1349 		if ((seq - e->event.sequence) > (1<<23))
   1350 			continue;
   1351 
   1352 		DRM_DEBUG("vblank event on %d, current %d\n",
   1353 			  e->event.sequence, seq);
   1354 
   1355 		list_del(&e->base.link);
   1356 		drm_vblank_put(dev, e->pipe);
   1357 		send_vblank_event(dev, e, seq, &now);
   1358 	}
   1359 
   1360 	spin_unlock_irqrestore(&dev->event_lock, flags);
   1361 
   1362 	trace_drm_vblank_event(crtc, seq);
   1363 }
   1364 
   1365 /**
   1366  * drm_handle_vblank - handle a vblank event
   1367  * @dev: DRM device
   1368  * @crtc: where this event occurred
   1369  *
   1370  * Drivers should call this routine in their vblank interrupt handlers to
   1371  * update the vblank counter and send any signals that may be pending.
   1372  */
   1373 bool drm_handle_vblank(struct drm_device *dev, int crtc)
   1374 {
   1375 	u32 vblcount;
   1376 	s64 diff_ns;
   1377 	struct timeval tvblank;
   1378 	unsigned long irqflags;
   1379 #ifdef __NetBSD__		/* XXX vblank locking */
   1380 	unsigned long irqflags_vbl_lock;
   1381 #endif
   1382 
   1383 	if (!dev->num_crtcs)
   1384 		return false;
   1385 
   1386 #ifdef __NetBSD__		/* XXX vblank locking */
   1387 	spin_lock_irqsave(&dev->vbl_lock, irqflags_vbl_lock);
   1388 #endif
   1389 
   1390 	/* Need timestamp lock to prevent concurrent execution with
   1391 	 * vblank enable/disable, as this would cause inconsistent
   1392 	 * or corrupted timestamps and vblank counts.
   1393 	 */
   1394 	spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
   1395 
   1396 	/* Vblank irq handling disabled. Nothing to do. */
   1397 	if (!dev->vblank[crtc].enabled) {
   1398 		spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
   1399 #ifdef __NetBSD__		/* XXX vblank locking */
   1400 		spin_unlock_irqrestore(&dev->vbl_lock, irqflags_vbl_lock);
   1401 #endif
   1402 		return false;
   1403 	}
   1404 
   1405 	/* Fetch corresponding timestamp for this vblank interval from
   1406 	 * driver and store it in proper slot of timestamp ringbuffer.
   1407 	 */
   1408 
   1409 	/* Get current timestamp and count. */
   1410 	vblcount = atomic_read(&dev->vblank[crtc].count);
   1411 	drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
   1412 
   1413 	/* Compute time difference to timestamp of last vblank */
   1414 	diff_ns = timeval_to_ns(&tvblank) -
   1415 		  timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
   1416 
   1417 	/* Update vblank timestamp and count if at least
   1418 	 * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
   1419 	 * difference between last stored timestamp and current
   1420 	 * timestamp. A smaller difference means basically
   1421 	 * identical timestamps. Happens if this vblank has
   1422 	 * been already processed and this is a redundant call,
   1423 	 * e.g., due to spurious vblank interrupts. We need to
   1424 	 * ignore those for accounting.
   1425 	 */
   1426 	if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
   1427 		/* Store new timestamp in ringbuffer. */
   1428 		vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
   1429 
   1430 		/* Increment cooked vblank count. This also atomically commits
   1431 		 * the timestamp computed above.
   1432 		 */
   1433 		smp_mb__before_atomic_inc();
   1434 		atomic_inc(&dev->vblank[crtc].count);
   1435 		smp_mb__after_atomic_inc();
   1436 	} else {
   1437 		DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
   1438 			  crtc, (int) diff_ns);
   1439 	}
   1440 
   1441 #ifdef __NetBSD__
   1442 	DRM_SPIN_WAKEUP_ONE(&dev->vblank[crtc].queue, &dev->vbl_lock);
   1443 #else
   1444 	wake_up(&dev->vblank[crtc].queue);
   1445 #endif
   1446 	drm_handle_vblank_events(dev, crtc);
   1447 
   1448 	spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
   1449 #ifdef __NetBSD__		/* XXX vblank locking */
   1450 	spin_unlock_irqrestore(&dev->vbl_lock, irqflags_vbl_lock);
   1451 #endif
   1452 	return true;
   1453 }
   1454 EXPORT_SYMBOL(drm_handle_vblank);
   1455