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