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