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