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