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