drm/tidss: Replace HTTP links with HTTPS ones
[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{
5a4784f4 197 drm_WARN_ON_ONCE(dev, 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
5a4784f4 206 if (drm_WARN_ON(dev, !crtc))
4ffb8dee
JM
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) {
5a4784f4 350 drm_WARN_ON_ONCE(dev, cur_vblank != vblank->last);
3ed4351a
DV
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 370
5a4784f4 371 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
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
5a4784f4
SR
406 drm_WARN_ONCE(dev, drm_debug_enabled(DRM_UT_VBL) &&
407 !crtc->funcs->get_vblank_timestamp,
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
5a4784f4 426 if (drm_WARN_ON(dev, !crtc))
4ffb8dee
JM
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
5a4784f4
SR
500 drm_WARN_ON(dev, READ_ONCE(vblank->enabled) &&
501 drm_core_check_feature(dev, DRIVER_MODESET));
3ed4351a
DV
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
5a4784f4 611 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
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);
5a4784f4 719 drm_WARN_ON_ONCE(dev, 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
5a4784f4 933 if (drm_WARN_ON(dev, 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
5a4784f4 1091 if (drm_WARN_ON(dev, !crtc))
4ffb8dee
JM
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
5a4784f4 1150 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
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
5a4784f4 1188 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1189 return;
1190
5a4784f4 1191 if (drm_WARN_ON(dev, atomic_read(&vblank->refcount) == 0))
3ed4351a
DV
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 1235
5a4784f4 1236 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1237 return;
1238
1239 ret = drm_vblank_get(dev, pipe);
5a4784f4
SR
1240 if (drm_WARN(dev, ret, "vblank not available on crtc %i, ret=%i\n",
1241 pipe, ret))
3ed4351a
DV
1242 return;
1243
1244 last = drm_vblank_count(dev, pipe);
1245
1246 ret = wait_event_timeout(vblank->queue,
1247 last != drm_vblank_count(dev, pipe),
1248 msecs_to_jiffies(100));
1249
5a4784f4 1250 drm_WARN(dev, ret == 0, "vblank wait timed out on crtc %i\n", pipe);
3ed4351a
DV
1251
1252 drm_vblank_put(dev, pipe);
1253}
1254EXPORT_SYMBOL(drm_wait_one_vblank);
1255
1256/**
1257 * drm_crtc_wait_one_vblank - wait for one vblank
1258 * @crtc: DRM crtc
1259 *
1260 * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1261 * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1262 * due to lack of driver support or because the crtc is off.
1263 */
1264void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1265{
1266 drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1267}
1268EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1269
1270/**
1271 * drm_crtc_vblank_off - disable vblank events on a CRTC
1272 * @crtc: CRTC in question
1273 *
1274 * Drivers can use this function to shut down the vblank interrupt handling when
1275 * disabling a crtc. This function ensures that the latest vblank frame count is
1276 * stored so that drm_vblank_on can restore it again.
1277 *
1278 * Drivers must use this function when the hardware vblank counter can get
57d30230 1279 * reset, e.g. when suspending or disabling the @crtc in general.
3ed4351a
DV
1280 */
1281void drm_crtc_vblank_off(struct drm_crtc *crtc)
1282{
1283 struct drm_device *dev = crtc->dev;
1284 unsigned int pipe = drm_crtc_index(crtc);
1285 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1286 struct drm_pending_vblank_event *e, *t;
67680d3c
AB
1287
1288 ktime_t now;
3ed4351a 1289 unsigned long irqflags;
570e8696 1290 u64 seq;
3ed4351a 1291
5a4784f4 1292 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1293 return;
1294
1295 spin_lock_irqsave(&dev->event_lock, irqflags);
1296
1297 spin_lock(&dev->vbl_lock);
02149a76
SR
1298 drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
1299 pipe, vblank->enabled, vblank->inmodeset);
3ed4351a
DV
1300
1301 /* Avoid redundant vblank disables without previous
1302 * drm_crtc_vblank_on(). */
1303 if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1304 drm_vblank_disable_and_save(dev, pipe);
1305
1306 wake_up(&vblank->queue);
1307
1308 /*
1309 * Prevent subsequent drm_vblank_get() from re-enabling
1310 * the vblank interrupt by bumping the refcount.
1311 */
1312 if (!vblank->inmodeset) {
1313 atomic_inc(&vblank->refcount);
1314 vblank->inmodeset = 1;
1315 }
1316 spin_unlock(&dev->vbl_lock);
1317
1318 /* Send any queued vblank events, lest the natives grow disquiet */
1319 seq = drm_vblank_count_and_time(dev, pipe, &now);
1320
1321 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1322 if (e->pipe != pipe)
1323 continue;
02149a76
SR
1324 drm_dbg_core(dev, "Sending premature vblank event on disable: "
1325 "wanted %llu, current %llu\n",
1326 e->sequence, seq);
3ed4351a
DV
1327 list_del(&e->base.link);
1328 drm_vblank_put(dev, pipe);
67680d3c 1329 send_vblank_event(dev, e, seq, now);
3ed4351a
DV
1330 }
1331 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1332
1333 /* Will be reset by the modeset helpers when re-enabling the crtc by
1334 * calling drm_calc_timestamping_constants(). */
1335 vblank->hwmode.crtc_clock = 0;
1336}
1337EXPORT_SYMBOL(drm_crtc_vblank_off);
1338
1339/**
1340 * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1341 * @crtc: CRTC in question
1342 *
1343 * Drivers can use this function to reset the vblank state to off at load time.
1344 * Drivers should use this together with the drm_crtc_vblank_off() and
1345 * drm_crtc_vblank_on() functions. The difference compared to
1346 * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1347 * and hence doesn't need to call any driver hooks.
57d30230
DV
1348 *
1349 * This is useful for recovering driver state e.g. on driver load, or on resume.
3ed4351a
DV
1350 */
1351void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1352{
1353 struct drm_device *dev = crtc->dev;
1354 unsigned long irqflags;
1355 unsigned int pipe = drm_crtc_index(crtc);
1356 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1357
1358 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1359 /*
1360 * Prevent subsequent drm_vblank_get() from enabling the vblank
1361 * interrupt by bumping the refcount.
1362 */
1363 if (!vblank->inmodeset) {
1364 atomic_inc(&vblank->refcount);
1365 vblank->inmodeset = 1;
1366 }
1367 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1368
5a4784f4 1369 drm_WARN_ON(dev, !list_empty(&dev->vblank_event_list));
3ed4351a
DV
1370}
1371EXPORT_SYMBOL(drm_crtc_vblank_reset);
1372
ed20151a
VS
1373/**
1374 * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1375 * @crtc: CRTC in question
1376 * @max_vblank_count: max hardware vblank counter value
1377 *
1378 * Update the maximum hardware vblank counter value for @crtc
1379 * at runtime. Useful for hardware where the operation of the
1380 * hardware vblank counter depends on the currently active
1381 * display configuration.
1382 *
1383 * For example, if the hardware vblank counter does not work
1384 * when a specific connector is active the maximum can be set
1385 * to zero. And when that specific connector isn't active the
1386 * maximum can again be set to the appropriate non-zero value.
1387 *
1388 * If used, must be called before drm_vblank_on().
1389 */
1390void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1391 u32 max_vblank_count)
1392{
1393 struct drm_device *dev = crtc->dev;
1394 unsigned int pipe = drm_crtc_index(crtc);
1395 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1396
5a4784f4
SR
1397 drm_WARN_ON(dev, dev->max_vblank_count);
1398 drm_WARN_ON(dev, !READ_ONCE(vblank->inmodeset));
ed20151a
VS
1399
1400 vblank->max_vblank_count = max_vblank_count;
1401}
1402EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1403
3ed4351a
DV
1404/**
1405 * drm_crtc_vblank_on - enable vblank events on a CRTC
1406 * @crtc: CRTC in question
1407 *
1408 * This functions restores the vblank interrupt state captured with
57d30230
DV
1409 * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1410 * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1411 * unbalanced and so can also be unconditionally called in driver load code to
1412 * reflect the current hardware state of the crtc.
3ed4351a
DV
1413 */
1414void drm_crtc_vblank_on(struct drm_crtc *crtc)
1415{
1416 struct drm_device *dev = crtc->dev;
1417 unsigned int pipe = drm_crtc_index(crtc);
1418 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1419 unsigned long irqflags;
1420
5a4784f4 1421 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1422 return;
1423
1424 spin_lock_irqsave(&dev->vbl_lock, irqflags);
02149a76
SR
1425 drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
1426 pipe, vblank->enabled, vblank->inmodeset);
3ed4351a
DV
1427
1428 /* Drop our private "prevent drm_vblank_get" refcount */
1429 if (vblank->inmodeset) {
1430 atomic_dec(&vblank->refcount);
1431 vblank->inmodeset = 0;
1432 }
1433
1434 drm_reset_vblank_timestamp(dev, pipe);
1435
1436 /*
1437 * re-enable interrupts if there are users left, or the
1438 * user wishes vblank interrupts to be enabled all the time.
1439 */
1440 if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
5a4784f4 1441 drm_WARN_ON(dev, drm_vblank_enable(dev, pipe));
3ed4351a
DV
1442 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1443}
1444EXPORT_SYMBOL(drm_crtc_vblank_on);
1445
d0bb96b4 1446/**
ea3f0ef3
DP
1447 * drm_vblank_restore - estimate missed vblanks and update vblank count.
1448 * @dev: DRM device
1449 * @pipe: CRTC index
d0bb96b4
DP
1450 *
1451 * Power manamement features can cause frame counter resets between vblank
ea3f0ef3
DP
1452 * disable and enable. Drivers can use this function in their
1453 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1454 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1455 * vblank counter.
d0bb96b4
DP
1456 *
1457 * This function is the legacy version of drm_crtc_vblank_restore().
1458 */
1459void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1460{
1461 ktime_t t_vblank;
1462 struct drm_vblank_crtc *vblank;
1463 int framedur_ns;
1464 u64 diff_ns;
1465 u32 cur_vblank, diff = 1;
1466 int count = DRM_TIMESTAMP_MAXRETRIES;
1467
5a4784f4 1468 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
d0bb96b4
DP
1469 return;
1470
1471 assert_spin_locked(&dev->vbl_lock);
1472 assert_spin_locked(&dev->vblank_time_lock);
1473
1474 vblank = &dev->vblank[pipe];
5a4784f4
SR
1475 drm_WARN_ONCE(dev,
1476 drm_debug_enabled(DRM_UT_VBL) && !vblank->framedur_ns,
1477 "Cannot compute missed vblanks without frame duration\n");
d0bb96b4
DP
1478 framedur_ns = vblank->framedur_ns;
1479
1480 do {
1481 cur_vblank = __get_vblank_counter(dev, pipe);
1482 drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1483 } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1484
1485 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1486 if (framedur_ns)
1487 diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1488
1489
02149a76
SR
1490 drm_dbg_vbl(dev,
1491 "missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
1492 diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
d0bb96b4
DP
1493 store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
1494}
1495EXPORT_SYMBOL(drm_vblank_restore);
1496
1497/**
ea3f0ef3
DP
1498 * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1499 * @crtc: CRTC in question
1500 *
d0bb96b4 1501 * Power manamement features can cause frame counter resets between vblank
ea3f0ef3
DP
1502 * disable and enable. Drivers can use this function in their
1503 * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1504 * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1505 * vblank counter.
d0bb96b4
DP
1506 */
1507void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1508{
1509 drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1510}
1511EXPORT_SYMBOL(drm_crtc_vblank_restore);
1512
3ed4351a
DV
1513static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1514 unsigned int pipe)
1515{
1516 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1517
1518 /* vblank is not initialized (IRQ not installed ?), or has been freed */
6015002e 1519 if (!drm_dev_has_vblank(dev))
3ed4351a
DV
1520 return;
1521
5a4784f4 1522 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1523 return;
1524
1525 /*
1526 * To avoid all the problems that might happen if interrupts
1527 * were enabled/disabled around or between these calls, we just
1528 * have the kernel take a reference on the CRTC (just once though
1529 * to avoid corrupting the count if multiple, mismatch calls occur),
1530 * so that interrupts remain enabled in the interim.
1531 */
1532 if (!vblank->inmodeset) {
1533 vblank->inmodeset = 0x1;
1534 if (drm_vblank_get(dev, pipe) == 0)
1535 vblank->inmodeset |= 0x2;
1536 }
1537}
1538
1539static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1540 unsigned int pipe)
1541{
1542 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1543 unsigned long irqflags;
1544
1545 /* vblank is not initialized (IRQ not installed ?), or has been freed */
6015002e 1546 if (!drm_dev_has_vblank(dev))
3ed4351a
DV
1547 return;
1548
5a4784f4 1549 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1550 return;
1551
1552 if (vblank->inmodeset) {
1553 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1554 drm_reset_vblank_timestamp(dev, pipe);
1555 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1556
1557 if (vblank->inmodeset & 0x2)
1558 drm_vblank_put(dev, pipe);
1559
1560 vblank->inmodeset = 0;
1561 }
1562}
1563
b6dcaaac
DV
1564int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1565 struct drm_file *file_priv)
3ed4351a
DV
1566{
1567 struct drm_modeset_ctl *modeset = data;
1568 unsigned int pipe;
1569
1570 /* If drm_vblank_init() hasn't been called yet, just no-op */
6015002e 1571 if (!drm_dev_has_vblank(dev))
3ed4351a
DV
1572 return 0;
1573
1574 /* KMS drivers handle this internally */
1575 if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1576 return 0;
1577
1578 pipe = modeset->crtc;
1579 if (pipe >= dev->num_crtcs)
1580 return -EINVAL;
1581
1582 switch (modeset->cmd) {
1583 case _DRM_PRE_MODESET:
1584 drm_legacy_vblank_pre_modeset(dev, pipe);
1585 break;
1586 case _DRM_POST_MODESET:
1587 drm_legacy_vblank_post_modeset(dev, pipe);
1588 break;
1589 default:
1590 return -EINVAL;
1591 }
1592
1593 return 0;
1594}
1595
570e8696 1596static inline bool vblank_passed(u64 seq, u64 ref)
3ed4351a
DV
1597{
1598 return (seq - ref) <= (1 << 23);
1599}
1600
1601static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
570e8696 1602 u64 req_seq,
3ed4351a
DV
1603 union drm_wait_vblank *vblwait,
1604 struct drm_file *file_priv)
1605{
1606 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1607 struct drm_pending_vblank_event *e;
67680d3c 1608 ktime_t now;
3ed4351a 1609 unsigned long flags;
570e8696 1610 u64 seq;
3ed4351a
DV
1611 int ret;
1612
1613 e = kzalloc(sizeof(*e), GFP_KERNEL);
1614 if (e == NULL) {
1615 ret = -ENOMEM;
1616 goto err_put;
1617 }
1618
1619 e->pipe = pipe;
1620 e->event.base.type = DRM_EVENT_VBLANK;
bd386e51
KP
1621 e->event.base.length = sizeof(e->event.vbl);
1622 e->event.vbl.user_data = vblwait->request.signal;
1623 e->event.vbl.crtc_id = 0;
1624 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1625 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
948de842 1626
bd386e51
KP
1627 if (crtc)
1628 e->event.vbl.crtc_id = crtc->base.id;
1629 }
3ed4351a
DV
1630
1631 spin_lock_irqsave(&dev->event_lock, flags);
1632
1633 /*
1634 * drm_crtc_vblank_off() might have been called after we called
1635 * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1636 * vblank disable, so no need for further locking. The reference from
1637 * drm_vblank_get() protects against vblank disable from another source.
1638 */
1639 if (!READ_ONCE(vblank->enabled)) {
1640 ret = -EINVAL;
1641 goto err_unlock;
1642 }
1643
1644 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1645 &e->event.base);
1646
1647 if (ret)
1648 goto err_unlock;
1649
1650 seq = drm_vblank_count_and_time(dev, pipe, &now);
1651
02149a76
SR
1652 drm_dbg_core(dev, "event on vblank count %llu, current %llu, crtc %u\n",
1653 req_seq, seq, pipe);
3ed4351a 1654
570e8696 1655 trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
3ed4351a 1656
570e8696
KP
1657 e->sequence = req_seq;
1658 if (vblank_passed(seq, req_seq)) {
3ed4351a 1659 drm_vblank_put(dev, pipe);
67680d3c 1660 send_vblank_event(dev, e, seq, now);
3ed4351a
DV
1661 vblwait->reply.sequence = seq;
1662 } else {
1663 /* drm_handle_vblank_events will call drm_vblank_put */
1664 list_add_tail(&e->base.link, &dev->vblank_event_list);
570e8696 1665 vblwait->reply.sequence = req_seq;
3ed4351a
DV
1666 }
1667
1668 spin_unlock_irqrestore(&dev->event_lock, flags);
1669
1670 return 0;
1671
1672err_unlock:
1673 spin_unlock_irqrestore(&dev->event_lock, flags);
1674 kfree(e);
1675err_put:
1676 drm_vblank_put(dev, pipe);
1677 return ret;
1678}
1679
1680static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1681{
1682 if (vblwait->request.sequence)
1683 return false;
1684
1685 return _DRM_VBLANK_RELATIVE ==
1686 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1687 _DRM_VBLANK_EVENT |
1688 _DRM_VBLANK_NEXTONMISS));
1689}
1690
570e8696
KP
1691/*
1692 * Widen a 32-bit param to 64-bits.
1693 *
1694 * \param narrow 32-bit value (missing upper 32 bits)
1695 * \param near 64-bit value that should be 'close' to near
1696 *
1697 * This function returns a 64-bit value using the lower 32-bits from
1698 * 'narrow' and constructing the upper 32-bits so that the result is
1699 * as close as possible to 'near'.
1700 */
1701
1702static u64 widen_32_to_64(u32 narrow, u64 near)
1703{
1704 return near + (s32) (narrow - near);
1705}
1706
67680d3c
AB
1707static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1708 struct drm_wait_vblank_reply *reply)
1709{
1710 ktime_t now;
1711 struct timespec64 ts;
1712
1713 /*
1714 * drm_wait_vblank_reply is a UAPI structure that uses 'long'
25e1a798
AB
1715 * to store the seconds. This is safe as we always use monotonic
1716 * timestamps since linux-4.15.
67680d3c
AB
1717 */
1718 reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1719 ts = ktime_to_timespec64(now);
1720 reply->tval_sec = (u32)ts.tv_sec;
1721 reply->tval_usec = ts.tv_nsec / 1000;
1722}
1723
b6dcaaac
DV
1724int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1725 struct drm_file *file_priv)
3ed4351a 1726{
7de440db 1727 struct drm_crtc *crtc;
3ed4351a
DV
1728 struct drm_vblank_crtc *vblank;
1729 union drm_wait_vblank *vblwait = data;
1730 int ret;
570e8696 1731 u64 req_seq, seq;
7de440db 1732 unsigned int pipe_index;
570e8696 1733 unsigned int flags, pipe, high_pipe;
3ed4351a
DV
1734
1735 if (!dev->irq_enabled)
aed6105b 1736 return -EOPNOTSUPP;
3ed4351a
DV
1737
1738 if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1739 return -EINVAL;
1740
1741 if (vblwait->request.type &
1742 ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1743 _DRM_VBLANK_HIGH_CRTC_MASK)) {
02149a76
SR
1744 drm_dbg_core(dev,
1745 "Unsupported type value 0x%x, supported mask 0x%x\n",
1746 vblwait->request.type,
1747 (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1748 _DRM_VBLANK_HIGH_CRTC_MASK));
3ed4351a
DV
1749 return -EINVAL;
1750 }
1751
1752 flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1753 high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1754 if (high_pipe)
7de440db 1755 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
3ed4351a 1756 else
7de440db
KP
1757 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1758
1759 /* Convert lease-relative crtc index into global crtc index */
1760 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1761 pipe = 0;
1762 drm_for_each_crtc(crtc, dev) {
1763 if (drm_lease_held(file_priv, crtc->base.id)) {
1764 if (pipe_index == 0)
1765 break;
1766 pipe_index--;
1767 }
1768 pipe++;
1769 }
1770 } else {
1771 pipe = pipe_index;
1772 }
1773
3ed4351a
DV
1774 if (pipe >= dev->num_crtcs)
1775 return -EINVAL;
1776
1777 vblank = &dev->vblank[pipe];
1778
1779 /* If the counter is currently enabled and accurate, short-circuit
1780 * queries to return the cached timestamp of the last vblank.
1781 */
1782 if (dev->vblank_disable_immediate &&
1783 drm_wait_vblank_is_query(vblwait) &&
1784 READ_ONCE(vblank->enabled)) {
67680d3c 1785 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
3ed4351a
DV
1786 return 0;
1787 }
1788
1789 ret = drm_vblank_get(dev, pipe);
1790 if (ret) {
02149a76
SR
1791 drm_dbg_core(dev,
1792 "crtc %d failed to acquire vblank counter, %d\n",
1793 pipe, ret);
3ed4351a
DV
1794 return ret;
1795 }
1796 seq = drm_vblank_count(dev, pipe);
1797
1798 switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1799 case _DRM_VBLANK_RELATIVE:
570e8696
KP
1800 req_seq = seq + vblwait->request.sequence;
1801 vblwait->request.sequence = req_seq;
3ed4351a 1802 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
570e8696 1803 break;
3ed4351a 1804 case _DRM_VBLANK_ABSOLUTE:
570e8696 1805 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
3ed4351a
DV
1806 break;
1807 default:
1808 ret = -EINVAL;
1809 goto done;
1810 }
1811
1812 if ((flags & _DRM_VBLANK_NEXTONMISS) &&
570e8696
KP
1813 vblank_passed(seq, req_seq)) {
1814 req_seq = seq + 1;
1815 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1816 vblwait->request.sequence = req_seq;
1817 }
3ed4351a
DV
1818
1819 if (flags & _DRM_VBLANK_EVENT) {
1820 /* must hold on to the vblank ref until the event fires
1821 * drm_vblank_put will be called asynchronously
1822 */
570e8696 1823 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
3ed4351a
DV
1824 }
1825
570e8696 1826 if (req_seq != seq) {
05103ea9
SR
1827 int wait;
1828
02149a76
SR
1829 drm_dbg_core(dev, "waiting on vblank count %llu, crtc %u\n",
1830 req_seq, pipe);
05103ea9
SR
1831 wait = wait_event_interruptible_timeout(vblank->queue,
1832 vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
1833 !READ_ONCE(vblank->enabled),
1834 msecs_to_jiffies(3000));
1835
1836 switch (wait) {
1837 case 0:
1838 /* timeout */
1839 ret = -EBUSY;
1840 break;
1841 case -ERESTARTSYS:
1842 /* interrupted by signal */
1843 ret = -EINTR;
1844 break;
1845 default:
1846 ret = 0;
1847 break;
1848 }
3ed4351a
DV
1849 }
1850
1851 if (ret != -EINTR) {
67680d3c 1852 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
3ed4351a 1853
02149a76
SR
1854 drm_dbg_core(dev, "crtc %d returning %u to client\n",
1855 pipe, vblwait->reply.sequence);
3ed4351a 1856 } else {
02149a76
SR
1857 drm_dbg_core(dev, "crtc %d vblank wait interrupted by signal\n",
1858 pipe);
3ed4351a
DV
1859 }
1860
1861done:
1862 drm_vblank_put(dev, pipe);
1863 return ret;
1864}
1865
1866static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1867{
7fe3f0d1
TZ
1868 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1869 bool high_prec = false;
3ed4351a 1870 struct drm_pending_vblank_event *e, *t;
67680d3c 1871 ktime_t now;
570e8696 1872 u64 seq;
3ed4351a
DV
1873
1874 assert_spin_locked(&dev->event_lock);
1875
1876 seq = drm_vblank_count_and_time(dev, pipe, &now);
1877
1878 list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1879 if (e->pipe != pipe)
1880 continue;
570e8696 1881 if (!vblank_passed(seq, e->sequence))
3ed4351a
DV
1882 continue;
1883
02149a76
SR
1884 drm_dbg_core(dev, "vblank event on %llu, current %llu\n",
1885 e->sequence, seq);
3ed4351a
DV
1886
1887 list_del(&e->base.link);
1888 drm_vblank_put(dev, pipe);
67680d3c 1889 send_vblank_event(dev, e, seq, now);
3ed4351a
DV
1890 }
1891
7fe3f0d1
TZ
1892 if (crtc && crtc->funcs->get_vblank_timestamp)
1893 high_prec = true;
7fe3f0d1
TZ
1894
1895 trace_drm_vblank_event(pipe, seq, now, high_prec);
3ed4351a
DV
1896}
1897
1898/**
1899 * drm_handle_vblank - handle a vblank event
1900 * @dev: DRM device
1901 * @pipe: index of CRTC where this event occurred
1902 *
1903 * Drivers should call this routine in their vblank interrupt handlers to
1904 * update the vblank counter and send any signals that may be pending.
1905 *
1906 * This is the legacy version of drm_crtc_handle_vblank().
1907 */
1908bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1909{
1910 struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1911 unsigned long irqflags;
1912 bool disable_irq;
1913
5a4784f4 1914 if (drm_WARN_ON_ONCE(dev, !drm_dev_has_vblank(dev)))
3ed4351a
DV
1915 return false;
1916
5a4784f4 1917 if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
3ed4351a
DV
1918 return false;
1919
1920 spin_lock_irqsave(&dev->event_lock, irqflags);
1921
1922 /* Need timestamp lock to prevent concurrent execution with
1923 * vblank enable/disable, as this would cause inconsistent
1924 * or corrupted timestamps and vblank counts.
1925 */
1926 spin_lock(&dev->vblank_time_lock);
1927
1928 /* Vblank irq handling disabled. Nothing to do. */
1929 if (!vblank->enabled) {
1930 spin_unlock(&dev->vblank_time_lock);
1931 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1932 return false;
1933 }
1934
1935 drm_update_vblank_count(dev, pipe, true);
1936
1937 spin_unlock(&dev->vblank_time_lock);
1938
1939 wake_up(&vblank->queue);
1940
1941 /* With instant-off, we defer disabling the interrupt until after
1942 * we finish processing the following vblank after all events have
1943 * been signaled. The disable has to be last (after
1944 * drm_handle_vblank_events) so that the timestamp is always accurate.
1945 */
1946 disable_irq = (dev->vblank_disable_immediate &&
1947 drm_vblank_offdelay > 0 &&
1948 !atomic_read(&vblank->refcount));
1949
1950 drm_handle_vblank_events(dev, pipe);
1951
1952 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1953
1954 if (disable_irq)
e99e88a9 1955 vblank_disable_fn(&vblank->disable_timer);
3ed4351a
DV
1956
1957 return true;
1958}
1959EXPORT_SYMBOL(drm_handle_vblank);
1960
1961/**
1962 * drm_crtc_handle_vblank - handle a vblank event
1963 * @crtc: where this event occurred
1964 *
1965 * Drivers should call this routine in their vblank interrupt handlers to
1966 * update the vblank counter and send any signals that may be pending.
1967 *
1968 * This is the native KMS version of drm_handle_vblank().
1969 *
bd7e3f3b
DV
1970 * Note that for a given vblank counter value drm_crtc_handle_vblank()
1971 * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
1972 * provide a barrier: Any writes done before calling
1973 * drm_crtc_handle_vblank() will be visible to callers of the later
1974 * functions, iff the vblank count is the same or a later one.
1975 *
1976 * See also &drm_vblank_crtc.count.
1977 *
3ed4351a
DV
1978 * Returns:
1979 * True if the event was successfully handled, false on failure.
1980 */
1981bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1982{
1983 return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1984}
1985EXPORT_SYMBOL(drm_crtc_handle_vblank);
3064abfa
KP
1986
1987/*
1988 * Get crtc VBLANK count.
1989 *
1990 * \param dev DRM device
1991 * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1992 * \param file_priv drm file private for the user's open file descriptor
1993 */
1994
1995int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1996 struct drm_file *file_priv)
1997{
1998 struct drm_crtc *crtc;
1999 struct drm_vblank_crtc *vblank;
2000 int pipe;
2001 struct drm_crtc_get_sequence *get_seq = data;
2002 ktime_t now;
2003 bool vblank_enabled;
2004 int ret;
2005
2006 if (!drm_core_check_feature(dev, DRIVER_MODESET))
69fdf420 2007 return -EOPNOTSUPP;
3064abfa
KP
2008
2009 if (!dev->irq_enabled)
aed6105b 2010 return -EOPNOTSUPP;
3064abfa
KP
2011
2012 crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
2013 if (!crtc)
2014 return -ENOENT;
2015
2016 pipe = drm_crtc_index(crtc);
2017
2018 vblank = &dev->vblank[pipe];
2019 vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
2020
2021 if (!vblank_enabled) {
2022 ret = drm_crtc_vblank_get(crtc);
2023 if (ret) {
02149a76
SR
2024 drm_dbg_core(dev,
2025 "crtc %d failed to acquire vblank counter, %d\n",
2026 pipe, ret);
3064abfa
KP
2027 return ret;
2028 }
2029 }
2030 drm_modeset_lock(&crtc->mutex, NULL);
2031 if (crtc->state)
2032 get_seq->active = crtc->state->enable;
2033 else
2034 get_seq->active = crtc->enabled;
2035 drm_modeset_unlock(&crtc->mutex);
2036 get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
2037 get_seq->sequence_ns = ktime_to_ns(now);
2038 if (!vblank_enabled)
2039 drm_crtc_vblank_put(crtc);
2040 return 0;
2041}
2042
2043/*
2044 * Queue a event for VBLANK sequence
2045 *
2046 * \param dev DRM device
2047 * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
2048 * \param file_priv drm file private for the user's open file descriptor
2049 */
2050
2051int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
2052 struct drm_file *file_priv)
2053{
2054 struct drm_crtc *crtc;
2055 struct drm_vblank_crtc *vblank;
2056 int pipe;
2057 struct drm_crtc_queue_sequence *queue_seq = data;
2058 ktime_t now;
2059 struct drm_pending_vblank_event *e;
2060 u32 flags;
2061 u64 seq;
2062 u64 req_seq;
2063 int ret;
2064 unsigned long spin_flags;
2065
2066 if (!drm_core_check_feature(dev, DRIVER_MODESET))
69fdf420 2067 return -EOPNOTSUPP;
3064abfa
KP
2068
2069 if (!dev->irq_enabled)
aed6105b 2070 return -EOPNOTSUPP;
3064abfa
KP
2071
2072 crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
2073 if (!crtc)
2074 return -ENOENT;
2075
2076 flags = queue_seq->flags;
2077 /* Check valid flag bits */
2078 if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
2079 DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
2080 return -EINVAL;
2081
2082 pipe = drm_crtc_index(crtc);
2083
2084 vblank = &dev->vblank[pipe];
2085
2086 e = kzalloc(sizeof(*e), GFP_KERNEL);
2087 if (e == NULL)
2088 return -ENOMEM;
2089
2090 ret = drm_crtc_vblank_get(crtc);
2091 if (ret) {
02149a76
SR
2092 drm_dbg_core(dev,
2093 "crtc %d failed to acquire vblank counter, %d\n",
2094 pipe, ret);
3064abfa
KP
2095 goto err_free;
2096 }
2097
2098 seq = drm_vblank_count_and_time(dev, pipe, &now);
2099 req_seq = queue_seq->sequence;
2100
2101 if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
2102 req_seq += seq;
2103
2104 if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
2105 req_seq = seq + 1;
2106
2107 e->pipe = pipe;
2108 e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
2109 e->event.base.length = sizeof(e->event.seq);
2110 e->event.seq.user_data = queue_seq->user_data;
2111
2112 spin_lock_irqsave(&dev->event_lock, spin_flags);
2113
2114 /*
2115 * drm_crtc_vblank_off() might have been called after we called
2116 * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
2117 * vblank disable, so no need for further locking. The reference from
2118 * drm_crtc_vblank_get() protects against vblank disable from another source.
2119 */
2120 if (!READ_ONCE(vblank->enabled)) {
2121 ret = -EINVAL;
2122 goto err_unlock;
2123 }
2124
2125 ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
2126 &e->event.base);
2127
2128 if (ret)
2129 goto err_unlock;
2130
2131 e->sequence = req_seq;
2132
2133 if (vblank_passed(seq, req_seq)) {
2134 drm_crtc_vblank_put(crtc);
2135 send_vblank_event(dev, e, seq, now);
2136 queue_seq->sequence = seq;
2137 } else {
2138 /* drm_handle_vblank_events will call drm_vblank_put */
2139 list_add_tail(&e->base.link, &dev->vblank_event_list);
2140 queue_seq->sequence = req_seq;
2141 }
2142
2143 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2144 return 0;
2145
2146err_unlock:
2147 spin_unlock_irqrestore(&dev->event_lock, spin_flags);
2148 drm_crtc_vblank_put(crtc);
2149err_free:
2150 kfree(e);
2151 return ret;
2152}