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