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