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