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