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