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