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