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