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