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