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