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