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