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