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