Home | History | Annotate | Line # | Download | only in drm
drm_vblank.c revision 1.12
      1 /*	$NetBSD: drm_vblank.c,v 1.12 2021/12/19 12:05:08 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.12 2021/12/19 12:05:08 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 
    485 /**
    486  * drm_vblank_init - initialize vblank support
    487  * @dev: DRM device
    488  * @num_crtcs: number of CRTCs supported by @dev
    489  *
    490  * This function initializes vblank support for @num_crtcs display pipelines.
    491  * Cleanup is handled by the DRM core, or through calling drm_dev_fini() for
    492  * drivers with a &drm_driver.release callback.
    493  *
    494  * Returns:
    495  * Zero on success or a negative error code on failure.
    496  */
    497 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
    498 {
    499 	int ret = -ENOMEM;
    500 	unsigned int i;
    501 
    502 	spin_lock_init(&dev->vblank_time_lock);
    503 
    504 	dev->num_crtcs = num_crtcs;
    505 
    506 	dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
    507 	if (!dev->vblank)
    508 		goto err;
    509 
    510 	for (i = 0; i < num_crtcs; i++) {
    511 		struct drm_vblank_crtc *vblank = &dev->vblank[i];
    512 
    513 		vblank->dev = dev;
    514 		vblank->pipe = i;
    515 		DRM_INIT_WAITQUEUE(&vblank->queue, "drmvblnq");
    516 		timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
    517 		seqlock_init(&vblank->seqlock);
    518 	}
    519 
    520 	DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
    521 
    522 	/* Driver specific high-precision vblank timestamping supported? */
    523 	if (dev->driver->get_vblank_timestamp)
    524 		DRM_INFO("Driver supports precise vblank timestamp query.\n");
    525 	else
    526 		DRM_INFO("No driver support for vblank timestamp query.\n");
    527 
    528 	/* Must have precise timestamping for reliable vblank instant disable */
    529 	if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
    530 		dev->vblank_disable_immediate = false;
    531 		DRM_INFO("Setting vblank_disable_immediate to false because "
    532 			 "get_vblank_timestamp == NULL\n");
    533 	}
    534 
    535 	return 0;
    536 
    537 err:
    538 	dev->num_crtcs = 0;
    539 	return ret;
    540 }
    541 EXPORT_SYMBOL(drm_vblank_init);
    542 
    543 /**
    544  * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
    545  * @crtc: which CRTC's vblank waitqueue to retrieve
    546  *
    547  * This function returns a pointer to the vblank waitqueue for the CRTC.
    548  * Drivers can use this to implement vblank waits using wait_event() and related
    549  * functions.
    550  */
    551 drm_waitqueue_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
    552 {
    553 	return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
    554 }
    555 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
    556 
    557 
    558 /**
    559  * drm_calc_timestamping_constants - calculate vblank timestamp constants
    560  * @crtc: drm_crtc whose timestamp constants should be updated.
    561  * @mode: display mode containing the scanout timings
    562  *
    563  * Calculate and store various constants which are later needed by vblank and
    564  * swap-completion timestamping, e.g, by
    565  * drm_calc_vbltimestamp_from_scanoutpos(). They are derived from CRTC's true
    566  * scanout timing, so they take things like panel scaling or other adjustments
    567  * into account.
    568  */
    569 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
    570 				     const struct drm_display_mode *mode)
    571 {
    572 	struct drm_device *dev = crtc->dev;
    573 	unsigned int pipe = drm_crtc_index(crtc);
    574 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
    575 	int linedur_ns = 0, framedur_ns = 0;
    576 	int dotclock = mode->crtc_clock;
    577 
    578 	if (!dev->num_crtcs)
    579 		return;
    580 
    581 	if (WARN_ON(pipe >= dev->num_crtcs))
    582 		return;
    583 
    584 	/* Valid dotclock? */
    585 	if (dotclock > 0) {
    586 		int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
    587 
    588 		/*
    589 		 * Convert scanline length in pixels and video
    590 		 * dot clock to line duration and frame duration
    591 		 * in nanoseconds:
    592 		 */
    593 		linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
    594 		framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
    595 
    596 		/*
    597 		 * Fields of interlaced scanout modes are only half a frame duration.
    598 		 */
    599 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
    600 			framedur_ns /= 2;
    601 	} else
    602 		DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
    603 			  crtc->base.id);
    604 
    605 	vblank->linedur_ns  = linedur_ns;
    606 	vblank->framedur_ns = framedur_ns;
    607 	vblank->hwmode = *mode;
    608 
    609 	DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
    610 		  crtc->base.id, mode->crtc_htotal,
    611 		  mode->crtc_vtotal, mode->crtc_vdisplay);
    612 	DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
    613 		  crtc->base.id, dotclock, framedur_ns, linedur_ns);
    614 }
    615 EXPORT_SYMBOL(drm_calc_timestamping_constants);
    616 
    617 /**
    618  * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
    619  * @dev: DRM device
    620  * @pipe: index of CRTC whose vblank timestamp to retrieve
    621  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
    622  *             On return contains true maximum error of timestamp
    623  * @vblank_time: Pointer to time which should receive the timestamp
    624  * @in_vblank_irq:
    625  *     True when called from drm_crtc_handle_vblank().  Some drivers
    626  *     need to apply some workarounds for gpu-specific vblank irq quirks
    627  *     if flag is set.
    628  *
    629  * Implements calculation of exact vblank timestamps from given drm_display_mode
    630  * timings and current video scanout position of a CRTC. This can be directly
    631  * used as the &drm_driver.get_vblank_timestamp implementation of a kms driver
    632  * if &drm_driver.get_scanout_position is implemented.
    633  *
    634  * The current implementation only handles standard video modes. For double scan
    635  * and interlaced modes the driver is supposed to adjust the hardware mode
    636  * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
    637  * match the scanout position reported.
    638  *
    639  * Note that atomic drivers must call drm_calc_timestamping_constants() before
    640  * enabling a CRTC. The atomic helpers already take care of that in
    641  * drm_atomic_helper_update_legacy_modeset_state().
    642  *
    643  * Returns:
    644  *
    645  * Returns true on success, and false on failure, i.e. when no accurate
    646  * timestamp could be acquired.
    647  */
    648 bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
    649 					   unsigned int pipe,
    650 					   int *max_error,
    651 					   ktime_t *vblank_time,
    652 					   bool in_vblank_irq)
    653 {
    654 	struct timespec64 ts_etime, ts_vblank_time;
    655 	ktime_t stime, etime;
    656 	bool vbl_status;
    657 	struct drm_crtc *crtc;
    658 	const struct drm_display_mode *mode;
    659 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
    660 	int vpos, hpos, i;
    661 	int delta_ns, duration_ns;
    662 
    663 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
    664 		return false;
    665 
    666 	crtc = drm_crtc_from_index(dev, pipe);
    667 
    668 	if (pipe >= dev->num_crtcs || !crtc) {
    669 		DRM_ERROR("Invalid crtc %u\n", pipe);
    670 		return false;
    671 	}
    672 
    673 	/* Scanout position query not supported? Should not happen. */
    674 	if (!dev->driver->get_scanout_position) {
    675 		DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
    676 		return false;
    677 	}
    678 
    679 	if (drm_drv_uses_atomic_modeset(dev))
    680 		mode = &vblank->hwmode;
    681 	else
    682 		mode = &crtc->hwmode;
    683 
    684 	/* If mode timing undefined, just return as no-op:
    685 	 * Happens during initial modesetting of a crtc.
    686 	 */
    687 	if (mode->crtc_clock == 0) {
    688 		DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
    689 		WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
    690 
    691 		return false;
    692 	}
    693 
    694 	/* Get current scanout position with system timestamp.
    695 	 * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
    696 	 * if single query takes longer than max_error nanoseconds.
    697 	 *
    698 	 * This guarantees a tight bound on maximum error if
    699 	 * code gets preempted or delayed for some reason.
    700 	 */
    701 	for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
    702 		/*
    703 		 * Get vertical and horizontal scanout position vpos, hpos,
    704 		 * and bounding timestamps stime, etime, pre/post query.
    705 		 */
    706 		vbl_status = dev->driver->get_scanout_position(dev, pipe,
    707 							       in_vblank_irq,
    708 							       &vpos, &hpos,
    709 							       &stime, &etime,
    710 							       mode);
    711 
    712 		/* Return as no-op if scanout query unsupported or failed. */
    713 		if (!vbl_status) {
    714 			DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
    715 				  pipe);
    716 			return false;
    717 		}
    718 
    719 		/* Compute uncertainty in timestamp of scanout position query. */
    720 		duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
    721 
    722 		/* Accept result with <  max_error nsecs timing uncertainty. */
    723 		if (duration_ns <= *max_error)
    724 			break;
    725 	}
    726 
    727 	/* Noisy system timing? */
    728 	if (i == DRM_TIMESTAMP_MAXRETRIES) {
    729 		DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
    730 			  pipe, duration_ns/1000, *max_error/1000, i);
    731 	}
    732 
    733 	/* Return upper bound of timestamp precision error. */
    734 	*max_error = duration_ns;
    735 
    736 	/* Convert scanout position into elapsed time at raw_time query
    737 	 * since start of scanout at first display scanline. delta_ns
    738 	 * can be negative if start of scanout hasn't happened yet.
    739 	 */
    740 	delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
    741 			   mode->crtc_clock);
    742 
    743 	/* Subtract time delta from raw timestamp to get final
    744 	 * vblank_time timestamp for end of vblank.
    745 	 */
    746 	*vblank_time = ktime_sub_ns(etime, delta_ns);
    747 
    748 	if (!drm_debug_enabled(DRM_UT_VBL))
    749 		return true;
    750 
    751 	ts_etime = ktime_to_timespec64(etime);
    752 	ts_vblank_time = ktime_to_timespec64(*vblank_time);
    753 
    754 	DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %"PRId64".%06ld -> %"PRId64".%06ld [e %d us, %d rep]\n",
    755 		      pipe, hpos, vpos,
    756 		      (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
    757 		      (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
    758 		      duration_ns / 1000, i);
    759 
    760 	return true;
    761 }
    762 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
    763 
    764 /**
    765  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
    766  *                             vblank interval
    767  * @dev: DRM device
    768  * @pipe: index of CRTC whose vblank timestamp to retrieve
    769  * @tvblank: Pointer to target time which should receive the timestamp
    770  * @in_vblank_irq:
    771  *     True when called from drm_crtc_handle_vblank().  Some drivers
    772  *     need to apply some workarounds for gpu-specific vblank irq quirks
    773  *     if flag is set.
    774  *
    775  * Fetches the system timestamp corresponding to the time of the most recent
    776  * vblank interval on specified CRTC. May call into kms-driver to
    777  * compute the timestamp with a high-precision GPU specific method.
    778  *
    779  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
    780  * call, i.e., it isn't very precisely locked to the true vblank.
    781  *
    782  * Returns:
    783  * True if timestamp is considered to be very precise, false otherwise.
    784  */
    785 static bool
    786 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
    787 			  ktime_t *tvblank, bool in_vblank_irq)
    788 {
    789 	bool ret = false;
    790 
    791 	/* Define requested maximum error on timestamps (nanoseconds). */
    792 	int max_error = (int) drm_timestamp_precision * 1000;
    793 
    794 	/* Query driver if possible and precision timestamping enabled. */
    795 	if (dev->driver->get_vblank_timestamp && (max_error > 0))
    796 		ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
    797 							tvblank, in_vblank_irq);
    798 
    799 	/* GPU high precision timestamp query unsupported or failed.
    800 	 * Return current monotonic/gettimeofday timestamp as best estimate.
    801 	 */
    802 	if (!ret)
    803 		*tvblank = ktime_get();
    804 
    805 	return ret;
    806 }
    807 
    808 /**
    809  * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
    810  * @crtc: which counter to retrieve
    811  *
    812  * Fetches the "cooked" vblank count value that represents the number of
    813  * vblank events since the system was booted, including lost events due to
    814  * modesetting activity. Note that this timer isn't correct against a racing
    815  * vblank interrupt (since it only reports the software vblank counter), see
    816  * drm_crtc_accurate_vblank_count() for such use-cases.
    817  *
    818  * Note that for a given vblank counter value drm_crtc_handle_vblank()
    819  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
    820  * provide a barrier: Any writes done before calling
    821  * drm_crtc_handle_vblank() will be visible to callers of the later
    822  * functions, iff the vblank count is the same or a later one.
    823  *
    824  * See also &drm_vblank_crtc.count.
    825  *
    826  * Returns:
    827  * The software vblank counter.
    828  */
    829 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
    830 {
    831 	return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
    832 }
    833 EXPORT_SYMBOL(drm_crtc_vblank_count);
    834 
    835 /**
    836  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
    837  *     system timestamp corresponding to that vblank counter value.
    838  * @dev: DRM device
    839  * @pipe: index of CRTC whose counter to retrieve
    840  * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
    841  *
    842  * Fetches the "cooked" vblank count value that represents the number of
    843  * vblank events since the system was booted, including lost events due to
    844  * modesetting activity. Returns corresponding system timestamp of the time
    845  * of the vblank interval that corresponds to the current vblank counter value.
    846  *
    847  * This is the legacy version of drm_crtc_vblank_count_and_time().
    848  */
    849 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
    850 				     ktime_t *vblanktime)
    851 {
    852 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
    853 	u64 vblank_count;
    854 	unsigned int seq;
    855 
    856 	if (WARN_ON(pipe >= dev->num_crtcs)) {
    857 		*vblanktime = 0;
    858 		return 0;
    859 	}
    860 
    861 	do {
    862 		seq = read_seqbegin(&vblank->seqlock);
    863 		vblank_count = atomic64_read(&vblank->count);
    864 		*vblanktime = vblank->time;
    865 	} while (read_seqretry(&vblank->seqlock, seq));
    866 
    867 	return vblank_count;
    868 }
    869 
    870 /**
    871  * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
    872  *     and the system timestamp corresponding to that vblank counter value
    873  * @crtc: which counter to retrieve
    874  * @vblanktime: Pointer to time to receive the vblank timestamp.
    875  *
    876  * Fetches the "cooked" vblank count value that represents the number of
    877  * vblank events since the system was booted, including lost events due to
    878  * modesetting activity. Returns corresponding system timestamp of the time
    879  * of the vblank interval that corresponds to the current vblank counter value.
    880  *
    881  * Note that for a given vblank counter value drm_crtc_handle_vblank()
    882  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
    883  * provide a barrier: Any writes done before calling
    884  * drm_crtc_handle_vblank() will be visible to callers of the later
    885  * functions, iff the vblank count is the same or a later one.
    886  *
    887  * See also &drm_vblank_crtc.count.
    888  */
    889 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
    890 				   ktime_t *vblanktime)
    891 {
    892 	return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
    893 					 vblanktime);
    894 }
    895 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
    896 
    897 static void send_vblank_event(struct drm_device *dev,
    898 		struct drm_pending_vblank_event *e,
    899 		u64 seq, ktime_t now)
    900 {
    901 	struct timespec64 tv;
    902 
    903 	switch (e->event.base.type) {
    904 	case DRM_EVENT_VBLANK:
    905 	case DRM_EVENT_FLIP_COMPLETE:
    906 		tv = ktime_to_timespec64(now);
    907 		e->event.vbl.sequence = seq;
    908 		/*
    909 		 * e->event is a user space structure, with hardcoded unsigned
    910 		 * 32-bit seconds/microseconds. This is safe as we always use
    911 		 * monotonic timestamps since linux-4.15
    912 		 */
    913 		e->event.vbl.tv_sec = tv.tv_sec;
    914 		e->event.vbl.tv_usec = tv.tv_nsec / 1000;
    915 		break;
    916 	case DRM_EVENT_CRTC_SEQUENCE:
    917 		if (seq)
    918 			e->event.seq.sequence = seq;
    919 		e->event.seq.time_ns = ktime_to_ns(now);
    920 		break;
    921 	}
    922 	trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
    923 	drm_send_event_locked(dev, &e->base);
    924 }
    925 
    926 /**
    927  * drm_crtc_arm_vblank_event - arm vblank event after pageflip
    928  * @crtc: the source CRTC of the vblank event
    929  * @e: the event to send
    930  *
    931  * A lot of drivers need to generate vblank events for the very next vblank
    932  * interrupt. For example when the page flip interrupt happens when the page
    933  * flip gets armed, but not when it actually executes within the next vblank
    934  * period. This helper function implements exactly the required vblank arming
    935  * behaviour.
    936  *
    937  * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
    938  * atomic commit must ensure that the next vblank happens at exactly the same
    939  * time as the atomic commit is committed to the hardware. This function itself
    940  * does **not** protect against the next vblank interrupt racing with either this
    941  * function call or the atomic commit operation. A possible sequence could be:
    942  *
    943  * 1. Driver commits new hardware state into vblank-synchronized registers.
    944  * 2. A vblank happens, committing the hardware state. Also the corresponding
    945  *    vblank interrupt is fired off and fully processed by the interrupt
    946  *    handler.
    947  * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
    948  * 4. The event is only send out for the next vblank, which is wrong.
    949  *
    950  * An equivalent race can happen when the driver calls
    951  * drm_crtc_arm_vblank_event() before writing out the new hardware state.
    952  *
    953  * The only way to make this work safely is to prevent the vblank from firing
    954  * (and the hardware from committing anything else) until the entire atomic
    955  * commit sequence has run to completion. If the hardware does not have such a
    956  * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
    957  * Instead drivers need to manually send out the event from their interrupt
    958  * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
    959  * possible race with the hardware committing the atomic update.
    960  *
    961  * Caller must hold a vblank reference for the event @e acquired by a
    962  * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
    963  */
    964 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
    965 			       struct drm_pending_vblank_event *e)
    966 {
    967 	struct drm_device *dev = crtc->dev;
    968 	unsigned int pipe = drm_crtc_index(crtc);
    969 
    970 	assert_spin_locked(&dev->event_lock);
    971 
    972 	e->pipe = pipe;
    973 	e->sequence = drm_crtc_accurate_vblank_count_locked(crtc) + 1;
    974 	list_add_tail(&e->base.link, &dev->vblank_event_list);
    975 }
    976 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
    977 
    978 /**
    979  * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
    980  * @crtc: the source CRTC of the vblank event
    981  * @e: the event to send
    982  *
    983  * Updates sequence # and timestamp on event for the most recently processed
    984  * vblank, and sends it to userspace.  Caller must hold event lock.
    985  *
    986  * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
    987  * situation, especially to send out events for atomic commit operations.
    988  */
    989 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
    990 				struct drm_pending_vblank_event *e)
    991 {
    992 	struct drm_device *dev = crtc->dev;
    993 	u64 seq;
    994 	unsigned int pipe = drm_crtc_index(crtc);
    995 	ktime_t now;
    996 
    997 	if (dev->num_crtcs > 0) {
    998 		seq = drm_vblank_count_and_time(dev, pipe, &now);
    999 	} else {
   1000 		seq = 0;
   1001 
   1002 		now = ktime_get();
   1003 	}
   1004 	e->pipe = pipe;
   1005 	send_vblank_event(dev, e, seq, now);
   1006 }
   1007 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
   1008 
   1009 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
   1010 {
   1011 	if (drm_core_check_feature(dev, DRIVER_MODESET)) {
   1012 		struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
   1013 
   1014 		if (WARN_ON(!crtc))
   1015 			return 0;
   1016 
   1017 		if (crtc->funcs->enable_vblank)
   1018 			return crtc->funcs->enable_vblank(crtc);
   1019 	}
   1020 
   1021 	return dev->driver->enable_vblank(dev, pipe);
   1022 }
   1023 
   1024 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
   1025 {
   1026 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1027 	int ret = 0;
   1028 
   1029 	assert_spin_locked(&dev->event_lock);
   1030 
   1031 	spin_lock(&dev->vblank_time_lock);
   1032 
   1033 	if (!vblank->enabled) {
   1034 		/*
   1035 		 * Enable vblank irqs under vblank_time_lock protection.
   1036 		 * All vblank count & timestamp updates are held off
   1037 		 * until we are done reinitializing master counter and
   1038 		 * timestamps. Filtercode in drm_handle_vblank() will
   1039 		 * prevent double-accounting of same vblank interval.
   1040 		 */
   1041 		ret = __enable_vblank(dev, pipe);
   1042 		DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
   1043 		if (ret) {
   1044 			atomic_dec(&vblank->refcount);
   1045 		} else {
   1046 			drm_update_vblank_count(dev, pipe, 0);
   1047 			/* drm_update_vblank_count() includes a wmb so we just
   1048 			 * need to ensure that the compiler emits the write
   1049 			 * to mark the vblank as enabled after the call
   1050 			 * to drm_update_vblank_count().
   1051 			 */
   1052 			WRITE_ONCE(vblank->enabled, true);
   1053 		}
   1054 	}
   1055 
   1056 	spin_unlock(&dev->vblank_time_lock);
   1057 
   1058 	return ret;
   1059 }
   1060 
   1061 static int drm_vblank_get_locked(struct drm_device *dev, unsigned int pipe)
   1062 {
   1063 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1064 	int ret = 0;
   1065 
   1066 	assert_spin_locked(&dev->event_lock);
   1067 
   1068 	if (!dev->num_crtcs)
   1069 		return -EINVAL;
   1070 
   1071 	if (WARN_ON(pipe >= dev->num_crtcs))
   1072 		return -EINVAL;
   1073 
   1074 	/* Going from 0->1 means we have to enable interrupts again */
   1075 	if (atomic_add_return(1, &vblank->refcount) == 1) {
   1076 		ret = drm_vblank_enable(dev, pipe);
   1077 	} else {
   1078 		if (!vblank->enabled) {
   1079 			atomic_dec(&vblank->refcount);
   1080 			ret = -EINVAL;
   1081 		}
   1082 	}
   1083 
   1084 	return ret;
   1085 }
   1086 
   1087 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
   1088 {
   1089 	int ret;
   1090 
   1091 	spin_lock(&dev->event_lock);
   1092 	ret = drm_vblank_get_locked(dev, pipe);
   1093 	spin_unlock(&dev->event_lock);
   1094 
   1095 	return ret;
   1096 }
   1097 
   1098 /**
   1099  * drm_crtc_vblank_get - get a reference count on vblank events
   1100  * @crtc: which CRTC to own
   1101  *
   1102  * Acquire a reference count on vblank events to avoid having them disabled
   1103  * while in use.
   1104  *
   1105  * Returns:
   1106  * Zero on success or a negative error code on failure.
   1107  */
   1108 int drm_crtc_vblank_get(struct drm_crtc *crtc)
   1109 {
   1110 	return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
   1111 }
   1112 EXPORT_SYMBOL(drm_crtc_vblank_get);
   1113 
   1114 int drm_crtc_vblank_get_locked(struct drm_crtc *crtc)
   1115 {
   1116 	return drm_vblank_get_locked(crtc->dev, drm_crtc_index(crtc));
   1117 }
   1118 EXPORT_SYMBOL(drm_crtc_vblank_get_locked);
   1119 
   1120 static void drm_vblank_put_locked(struct drm_device *dev, unsigned int pipe)
   1121 {
   1122 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1123 
   1124 	assert_spin_locked(&dev->event_lock);
   1125 
   1126 	if (WARN_ON(pipe >= dev->num_crtcs))
   1127 		return;
   1128 
   1129 	if (WARN_ON(atomic_read(&vblank->refcount) == 0))
   1130 		return;
   1131 
   1132 	/* Last user schedules interrupt disable */
   1133 	if (atomic_dec_and_test(&vblank->refcount)) {
   1134 		if (drm_vblank_offdelay == 0)
   1135 			return;
   1136 		else if (drm_vblank_offdelay < 0)
   1137 			vblank_disable_locked(vblank, dev, pipe);
   1138 		else if (!dev->vblank_disable_immediate)
   1139 			mod_timer(&vblank->disable_timer,
   1140 				  jiffies + ((drm_vblank_offdelay * HZ)/1000));
   1141 	}
   1142 }
   1143 
   1144 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
   1145 {
   1146 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1147 
   1148 	if (WARN_ON(pipe >= dev->num_crtcs))
   1149 		return;
   1150 
   1151 	if (WARN_ON(atomic_read(&vblank->refcount) == 0))
   1152 		return;
   1153 
   1154 	/* Last user schedules interrupt disable */
   1155 	if (atomic_dec_and_test(&vblank->refcount)) {
   1156 		if (drm_vblank_offdelay == 0)
   1157 			return;
   1158 		else if (drm_vblank_offdelay < 0)
   1159 			vblank_disable_fn(&vblank->disable_timer);
   1160 		else if (!dev->vblank_disable_immediate)
   1161 			mod_timer(&vblank->disable_timer,
   1162 				  jiffies + ((drm_vblank_offdelay * HZ)/1000));
   1163 	}
   1164 }
   1165 
   1166 /**
   1167  * drm_crtc_vblank_put - give up ownership of vblank events
   1168  * @crtc: which counter to give up
   1169  *
   1170  * Release ownership of a given vblank counter, turning off interrupts
   1171  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
   1172  */
   1173 void drm_crtc_vblank_put(struct drm_crtc *crtc)
   1174 {
   1175 	drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
   1176 }
   1177 EXPORT_SYMBOL(drm_crtc_vblank_put);
   1178 
   1179 void drm_crtc_vblank_put_locked(struct drm_crtc *crtc)
   1180 {
   1181 	drm_vblank_put_locked(crtc->dev, drm_crtc_index(crtc));
   1182 }
   1183 
   1184 /**
   1185  * drm_wait_one_vblank - wait for one vblank
   1186  * @dev: DRM device
   1187  * @pipe: CRTC index
   1188  *
   1189  * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
   1190  * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
   1191  * due to lack of driver support or because the crtc is off.
   1192  *
   1193  * This is the legacy version of drm_crtc_wait_one_vblank().
   1194  */
   1195 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
   1196 {
   1197 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1198 	int ret;
   1199 	u64 last;
   1200 
   1201 	if (WARN_ON(pipe >= dev->num_crtcs))
   1202 		return;
   1203 
   1204 	ret = drm_vblank_get(dev, pipe);
   1205 	if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
   1206 		return;
   1207 
   1208 	spin_lock(&dev->event_lock);
   1209 	last = drm_vblank_count(dev, pipe);
   1210 	DRM_SPIN_TIMED_WAIT_UNTIL(ret, &vblank->queue, &dev->event_lock,
   1211 	    msecs_to_jiffies(100),
   1212 	    last != drm_vblank_count(dev, pipe));
   1213 	spin_unlock(&dev->event_lock);
   1214 
   1215 	WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
   1216 
   1217 	drm_vblank_put(dev, pipe);
   1218 }
   1219 EXPORT_SYMBOL(drm_wait_one_vblank);
   1220 
   1221 /**
   1222  * drm_crtc_wait_one_vblank - wait for one vblank
   1223  * @crtc: DRM crtc
   1224  *
   1225  * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
   1226  * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
   1227  * due to lack of driver support or because the crtc is off.
   1228  */
   1229 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
   1230 {
   1231 	drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
   1232 }
   1233 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
   1234 
   1235 /**
   1236  * drm_crtc_vblank_off - disable vblank events on a CRTC
   1237  * @crtc: CRTC in question
   1238  *
   1239  * Drivers can use this function to shut down the vblank interrupt handling when
   1240  * disabling a crtc. This function ensures that the latest vblank frame count is
   1241  * stored so that drm_vblank_on can restore it again.
   1242  *
   1243  * Drivers must use this function when the hardware vblank counter can get
   1244  * reset, e.g. when suspending or disabling the @crtc in general.
   1245  */
   1246 void drm_crtc_vblank_off(struct drm_crtc *crtc)
   1247 {
   1248 	struct drm_device *dev = crtc->dev;
   1249 	unsigned int pipe = drm_crtc_index(crtc);
   1250 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1251 	struct drm_pending_vblank_event *e, *t;
   1252 
   1253 	ktime_t now;
   1254 	unsigned long irqflags;
   1255 	u64 seq;
   1256 
   1257 	if (WARN_ON(pipe >= dev->num_crtcs))
   1258 		return;
   1259 
   1260 	spin_lock_irqsave(&dev->event_lock, irqflags);
   1261 
   1262 	DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
   1263 		      pipe, vblank->enabled, vblank->inmodeset);
   1264 
   1265 	/* Avoid redundant vblank disables without previous
   1266 	 * drm_crtc_vblank_on(). */
   1267 	if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
   1268 		drm_vblank_disable_and_save(dev, pipe);
   1269 
   1270 	DRM_SPIN_WAKEUP_ONE(&vblank->queue, &dev->event_lock);
   1271 
   1272 	/*
   1273 	 * Prevent subsequent drm_vblank_get() from re-enabling
   1274 	 * the vblank interrupt by bumping the refcount.
   1275 	 */
   1276 	if (!vblank->inmodeset) {
   1277 		atomic_inc(&vblank->refcount);
   1278 		vblank->inmodeset = 1;
   1279 	}
   1280 
   1281 	/* Send any queued vblank events, lest the natives grow disquiet */
   1282 	seq = drm_vblank_count_and_time(dev, pipe, &now);
   1283 
   1284 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
   1285 		if (e->pipe != pipe)
   1286 			continue;
   1287 		DRM_DEBUG("Sending premature vblank event on disable: "
   1288 			  "wanted %"PRIu64", current %"PRIu64"\n",
   1289 			  e->sequence, seq);
   1290 		list_del(&e->base.link);
   1291 		drm_vblank_put(dev, pipe);
   1292 		send_vblank_event(dev, e, seq, now);
   1293 	}
   1294 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
   1295 
   1296 	/* Will be reset by the modeset helpers when re-enabling the crtc by
   1297 	 * calling drm_calc_timestamping_constants(). */
   1298 	vblank->hwmode.crtc_clock = 0;
   1299 }
   1300 EXPORT_SYMBOL(drm_crtc_vblank_off);
   1301 
   1302 /**
   1303  * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
   1304  * @crtc: CRTC in question
   1305  *
   1306  * Drivers can use this function to reset the vblank state to off at load time.
   1307  * Drivers should use this together with the drm_crtc_vblank_off() and
   1308  * drm_crtc_vblank_on() functions. The difference compared to
   1309  * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
   1310  * and hence doesn't need to call any driver hooks.
   1311  *
   1312  * This is useful for recovering driver state e.g. on driver load, or on resume.
   1313  */
   1314 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
   1315 {
   1316 	struct drm_device *dev = crtc->dev;
   1317 	unsigned long irqflags;
   1318 	unsigned int pipe = drm_crtc_index(crtc);
   1319 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1320 
   1321 	spin_lock_irqsave(&dev->event_lock, irqflags);
   1322 	/*
   1323 	 * Prevent subsequent drm_vblank_get() from enabling the vblank
   1324 	 * interrupt by bumping the refcount.
   1325 	 */
   1326 	if (!vblank->inmodeset) {
   1327 		atomic_inc(&vblank->refcount);
   1328 		vblank->inmodeset = 1;
   1329 	}
   1330 	WARN_ON(!list_empty(&dev->vblank_event_list));
   1331 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
   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->event_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->event_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->event_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->event_lock, irqflags);
   1514 		drm_reset_vblank_timestamp(dev, pipe);
   1515 		spin_unlock_irqrestore(&dev->event_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 		DRM_SPIN_TIMED_WAIT_UNTIL(wait, &vblank->queue,
   1788 		    &dev->event_lock, msecs_to_jiffies(3000),
   1789 		    (vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
   1790 			!READ_ONCE(vblank->enabled)));
   1791 
   1792 		switch (wait) {
   1793 		case 0:
   1794 			/* timeout */
   1795 			ret = -EBUSY;
   1796 			break;
   1797 		case -ERESTARTSYS:
   1798 			/* interrupted by signal */
   1799 			ret = -EINTR;
   1800 			break;
   1801 		default:
   1802 			ret = 0;
   1803 			break;
   1804 		}
   1805 	}
   1806 
   1807 	if (ret != -EINTR) {
   1808 		drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
   1809 
   1810 		DRM_DEBUG("crtc %d returning %u to client\n",
   1811 			  pipe, vblwait->reply.sequence);
   1812 	} else {
   1813 		DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
   1814 	}
   1815 
   1816 done:
   1817 	drm_vblank_put(dev, pipe);
   1818 	return ret;
   1819 }
   1820 
   1821 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
   1822 {
   1823 	struct drm_pending_vblank_event *e, *t;
   1824 	ktime_t now;
   1825 	u64 seq;
   1826 
   1827 	assert_spin_locked(&dev->event_lock);
   1828 
   1829 	seq = drm_vblank_count_and_time(dev, pipe, &now);
   1830 
   1831 	list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
   1832 		if (e->pipe != pipe)
   1833 			continue;
   1834 		if (!vblank_passed(seq, e->sequence))
   1835 			continue;
   1836 
   1837 		DRM_DEBUG("vblank event on %"PRIu64", current %"PRIu64"\n",
   1838 			  e->sequence, seq);
   1839 
   1840 		list_del(&e->base.link);
   1841 		drm_vblank_put(dev, pipe);
   1842 		send_vblank_event(dev, e, seq, now);
   1843 	}
   1844 
   1845 	trace_drm_vblank_event(pipe, seq, now,
   1846 			dev->driver->get_vblank_timestamp != NULL);
   1847 }
   1848 
   1849 /**
   1850  * drm_handle_vblank - handle a vblank event
   1851  * @dev: DRM device
   1852  * @pipe: index of CRTC where this event occurred
   1853  *
   1854  * Drivers should call this routine in their vblank interrupt handlers to
   1855  * update the vblank counter and send any signals that may be pending.
   1856  *
   1857  * This is the legacy version of drm_crtc_handle_vblank().
   1858  */
   1859 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
   1860 {
   1861 	struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
   1862 	unsigned long irqflags;
   1863 	bool disable_irq;
   1864 
   1865 	if (WARN_ON_ONCE(!dev->num_crtcs))
   1866 		return false;
   1867 
   1868 	if (WARN_ON(pipe >= dev->num_crtcs))
   1869 		return false;
   1870 
   1871 	spin_lock_irqsave(&dev->event_lock, irqflags);
   1872 
   1873 	/* Need timestamp lock to prevent concurrent execution with
   1874 	 * vblank enable/disable, as this would cause inconsistent
   1875 	 * or corrupted timestamps and vblank counts.
   1876 	 */
   1877 	spin_lock(&dev->vblank_time_lock);
   1878 
   1879 	/* Vblank irq handling disabled. Nothing to do. */
   1880 	if (!vblank->enabled) {
   1881 		spin_unlock(&dev->vblank_time_lock);
   1882 		spin_unlock_irqrestore(&dev->event_lock, irqflags);
   1883 		return false;
   1884 	}
   1885 
   1886 	drm_update_vblank_count(dev, pipe, true);
   1887 
   1888 	spin_unlock(&dev->vblank_time_lock);
   1889 
   1890 	DRM_SPIN_WAKEUP_ONE(&vblank->queue, &dev->event_lock);
   1891 
   1892 	/* With instant-off, we defer disabling the interrupt until after
   1893 	 * we finish processing the following vblank after all events have
   1894 	 * been signaled. The disable has to be last (after
   1895 	 * drm_handle_vblank_events) so that the timestamp is always accurate.
   1896 	 */
   1897 	disable_irq = (dev->vblank_disable_immediate &&
   1898 		       drm_vblank_offdelay > 0 &&
   1899 		       !atomic_read(&vblank->refcount));
   1900 
   1901 	drm_handle_vblank_events(dev, pipe);
   1902 
   1903 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
   1904 
   1905 	if (disable_irq)
   1906 		vblank_disable_fn(&vblank->disable_timer);
   1907 
   1908 	return true;
   1909 }
   1910 EXPORT_SYMBOL(drm_handle_vblank);
   1911 
   1912 /**
   1913  * drm_crtc_handle_vblank - handle a vblank event
   1914  * @crtc: where this event occurred
   1915  *
   1916  * Drivers should call this routine in their vblank interrupt handlers to
   1917  * update the vblank counter and send any signals that may be pending.
   1918  *
   1919  * This is the native KMS version of drm_handle_vblank().
   1920  *
   1921  * Note that for a given vblank counter value drm_crtc_handle_vblank()
   1922  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
   1923  * provide a barrier: Any writes done before calling
   1924  * drm_crtc_handle_vblank() will be visible to callers of the later
   1925  * functions, iff the vblank count is the same or a later one.
   1926  *
   1927  * See also &drm_vblank_crtc.count.
   1928  *
   1929  * Returns:
   1930  * True if the event was successfully handled, false on failure.
   1931  */
   1932 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
   1933 {
   1934 	return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
   1935 }
   1936 EXPORT_SYMBOL(drm_crtc_handle_vblank);
   1937 
   1938 /*
   1939  * Get crtc VBLANK count.
   1940  *
   1941  * \param dev DRM device
   1942  * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
   1943  * \param file_priv drm file private for the user's open file descriptor
   1944  */
   1945 
   1946 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
   1947 				struct drm_file *file_priv)
   1948 {
   1949 	struct drm_crtc *crtc;
   1950 	struct drm_vblank_crtc *vblank;
   1951 	int pipe;
   1952 	struct drm_crtc_get_sequence *get_seq = data;
   1953 	ktime_t now;
   1954 	bool vblank_enabled;
   1955 	int ret;
   1956 
   1957 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   1958 		return -EOPNOTSUPP;
   1959 
   1960 	if (!dev->irq_enabled)
   1961 		return -EOPNOTSUPP;
   1962 
   1963 	crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
   1964 	if (!crtc)
   1965 		return -ENOENT;
   1966 
   1967 	pipe = drm_crtc_index(crtc);
   1968 
   1969 	vblank = &dev->vblank[pipe];
   1970 	vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
   1971 
   1972 	if (!vblank_enabled) {
   1973 		ret = drm_crtc_vblank_get(crtc);
   1974 		if (ret) {
   1975 			DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
   1976 			return ret;
   1977 		}
   1978 	}
   1979 	drm_modeset_lock(&crtc->mutex, NULL);
   1980 	if (crtc->state)
   1981 		get_seq->active = crtc->state->enable;
   1982 	else
   1983 		get_seq->active = crtc->enabled;
   1984 	drm_modeset_unlock(&crtc->mutex);
   1985 	get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
   1986 	get_seq->sequence_ns = ktime_to_ns(now);
   1987 	if (!vblank_enabled)
   1988 		drm_crtc_vblank_put(crtc);
   1989 	return 0;
   1990 }
   1991 
   1992 /*
   1993  * Queue a event for VBLANK sequence
   1994  *
   1995  * \param dev DRM device
   1996  * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
   1997  * \param file_priv drm file private for the user's open file descriptor
   1998  */
   1999 
   2000 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
   2001 				  struct drm_file *file_priv)
   2002 {
   2003 	struct drm_crtc *crtc;
   2004 	struct drm_vblank_crtc *vblank;
   2005 	int pipe;
   2006 	struct drm_crtc_queue_sequence *queue_seq = data;
   2007 	ktime_t now;
   2008 	struct drm_pending_vblank_event *e;
   2009 	u32 flags;
   2010 	u64 seq;
   2011 	u64 req_seq;
   2012 	int ret;
   2013 	unsigned long spin_flags;
   2014 
   2015 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   2016 		return -EOPNOTSUPP;
   2017 
   2018 	if (!dev->irq_enabled)
   2019 		return -EOPNOTSUPP;
   2020 
   2021 	crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
   2022 	if (!crtc)
   2023 		return -ENOENT;
   2024 
   2025 	flags = queue_seq->flags;
   2026 	/* Check valid flag bits */
   2027 	if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
   2028 		      DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
   2029 		return -EINVAL;
   2030 
   2031 	pipe = drm_crtc_index(crtc);
   2032 
   2033 	vblank = &dev->vblank[pipe];
   2034 
   2035 	e = kzalloc(sizeof(*e), GFP_KERNEL);
   2036 	if (e == NULL)
   2037 		return -ENOMEM;
   2038 
   2039 	ret = drm_crtc_vblank_get(crtc);
   2040 	if (ret) {
   2041 		DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
   2042 		goto err_free;
   2043 	}
   2044 
   2045 	seq = drm_vblank_count_and_time(dev, pipe, &now);
   2046 	req_seq = queue_seq->sequence;
   2047 
   2048 	if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
   2049 		req_seq += seq;
   2050 
   2051 	if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
   2052 		req_seq = seq + 1;
   2053 
   2054 	e->pipe = pipe;
   2055 	e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
   2056 	e->event.base.length = sizeof(e->event.seq);
   2057 	e->event.seq.user_data = queue_seq->user_data;
   2058 
   2059 	spin_lock_irqsave(&dev->event_lock, spin_flags);
   2060 
   2061 	/*
   2062 	 * drm_crtc_vblank_off() might have been called after we called
   2063 	 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
   2064 	 * vblank disable, so no need for further locking.  The reference from
   2065 	 * drm_crtc_vblank_get() protects against vblank disable from another source.
   2066 	 */
   2067 	if (!READ_ONCE(vblank->enabled)) {
   2068 		ret = -EINVAL;
   2069 		goto err_unlock;
   2070 	}
   2071 
   2072 	ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
   2073 					    &e->event.base);
   2074 
   2075 	if (ret)
   2076 		goto err_unlock;
   2077 
   2078 	e->sequence = req_seq;
   2079 
   2080 	if (vblank_passed(seq, req_seq)) {
   2081 		drm_crtc_vblank_put(crtc);
   2082 		send_vblank_event(dev, e, seq, now);
   2083 		queue_seq->sequence = seq;
   2084 	} else {
   2085 		/* drm_handle_vblank_events will call drm_vblank_put */
   2086 		list_add_tail(&e->base.link, &dev->vblank_event_list);
   2087 		queue_seq->sequence = req_seq;
   2088 	}
   2089 
   2090 	spin_unlock_irqrestore(&dev->event_lock, spin_flags);
   2091 	return 0;
   2092 
   2093 err_unlock:
   2094 	spin_unlock_irqrestore(&dev->event_lock, spin_flags);
   2095 	drm_crtc_vblank_put(crtc);
   2096 err_free:
   2097 	kfree(e);
   2098 	return ret;
   2099 }
   2100