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