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