Linux-libre 4.15.7-gnu
[librecmc/linux-libre.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_ONCE(drm_debug & DRM_UT_VBL && !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(struct timer_list *t)
371 {
372         struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
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                 timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
440                 seqlock_init(&vblank->seqlock);
441         }
442
443         DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
444
445         /* Driver specific high-precision vblank timestamping supported? */
446         if (dev->driver->get_vblank_timestamp)
447                 DRM_INFO("Driver supports precise vblank timestamp query.\n");
448         else
449                 DRM_INFO("No driver support for vblank timestamp query.\n");
450
451         /* Must have precise timestamping for reliable vblank instant disable */
452         if (dev->vblank_disable_immediate && !dev->driver->get_vblank_timestamp) {
453                 dev->vblank_disable_immediate = false;
454                 DRM_INFO("Setting vblank_disable_immediate to false because "
455                          "get_vblank_timestamp == NULL\n");
456         }
457
458         return 0;
459
460 err:
461         dev->num_crtcs = 0;
462         return ret;
463 }
464 EXPORT_SYMBOL(drm_vblank_init);
465
466 /**
467  * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
468  * @crtc: which CRTC's vblank waitqueue to retrieve
469  *
470  * This function returns a pointer to the vblank waitqueue for the CRTC.
471  * Drivers can use this to implement vblank waits using wait_event() and related
472  * functions.
473  */
474 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
475 {
476         return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
477 }
478 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
479
480
481 /**
482  * drm_calc_timestamping_constants - calculate vblank timestamp constants
483  * @crtc: drm_crtc whose timestamp constants should be updated.
484  * @mode: display mode containing the scanout timings
485  *
486  * Calculate and store various constants which are later needed by vblank and
487  * swap-completion timestamping, e.g, by
488  * drm_calc_vbltimestamp_from_scanoutpos(). They are derived from CRTC's true
489  * scanout timing, so they take things like panel scaling or other adjustments
490  * into account.
491  */
492 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
493                                      const struct drm_display_mode *mode)
494 {
495         struct drm_device *dev = crtc->dev;
496         unsigned int pipe = drm_crtc_index(crtc);
497         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
498         int linedur_ns = 0, framedur_ns = 0;
499         int dotclock = mode->crtc_clock;
500
501         if (!dev->num_crtcs)
502                 return;
503
504         if (WARN_ON(pipe >= dev->num_crtcs))
505                 return;
506
507         /* Valid dotclock? */
508         if (dotclock > 0) {
509                 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
510
511                 /*
512                  * Convert scanline length in pixels and video
513                  * dot clock to line duration and frame duration
514                  * in nanoseconds:
515                  */
516                 linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
517                 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
518
519                 /*
520                  * Fields of interlaced scanout modes are only half a frame duration.
521                  */
522                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
523                         framedur_ns /= 2;
524         } else
525                 DRM_ERROR("crtc %u: Can't calculate constants, dotclock = 0!\n",
526                           crtc->base.id);
527
528         vblank->linedur_ns  = linedur_ns;
529         vblank->framedur_ns = framedur_ns;
530         vblank->hwmode = *mode;
531
532         DRM_DEBUG("crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
533                   crtc->base.id, mode->crtc_htotal,
534                   mode->crtc_vtotal, mode->crtc_vdisplay);
535         DRM_DEBUG("crtc %u: clock %d kHz framedur %d linedur %d\n",
536                   crtc->base.id, dotclock, framedur_ns, linedur_ns);
537 }
538 EXPORT_SYMBOL(drm_calc_timestamping_constants);
539
540 /**
541  * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
542  * @dev: DRM device
543  * @pipe: index of CRTC whose vblank timestamp to retrieve
544  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
545  *             On return contains true maximum error of timestamp
546  * @vblank_time: Pointer to time which should receive the timestamp
547  * @in_vblank_irq:
548  *     True when called from drm_crtc_handle_vblank().  Some drivers
549  *     need to apply some workarounds for gpu-specific vblank irq quirks
550  *     if flag is set.
551  *
552  * Implements calculation of exact vblank timestamps from given drm_display_mode
553  * timings and current video scanout position of a CRTC. This can be directly
554  * used as the &drm_driver.get_vblank_timestamp implementation of a kms driver
555  * if &drm_driver.get_scanout_position is implemented.
556  *
557  * The current implementation only handles standard video modes. For double scan
558  * and interlaced modes the driver is supposed to adjust the hardware mode
559  * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
560  * match the scanout position reported.
561  *
562  * Note that atomic drivers must call drm_calc_timestamping_constants() before
563  * enabling a CRTC. The atomic helpers already take care of that in
564  * drm_atomic_helper_update_legacy_modeset_state().
565  *
566  * Returns:
567  *
568  * Returns true on success, and false on failure, i.e. when no accurate
569  * timestamp could be acquired.
570  */
571 bool drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev,
572                                            unsigned int pipe,
573                                            int *max_error,
574                                            ktime_t *vblank_time,
575                                            bool in_vblank_irq)
576 {
577         struct timespec64 ts_etime, ts_vblank_time;
578         ktime_t stime, etime;
579         bool vbl_status;
580         struct drm_crtc *crtc;
581         const struct drm_display_mode *mode;
582         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
583         int vpos, hpos, i;
584         int delta_ns, duration_ns;
585
586         if (!drm_core_check_feature(dev, DRIVER_MODESET))
587                 return false;
588
589         crtc = drm_crtc_from_index(dev, pipe);
590
591         if (pipe >= dev->num_crtcs || !crtc) {
592                 DRM_ERROR("Invalid crtc %u\n", pipe);
593                 return false;
594         }
595
596         /* Scanout position query not supported? Should not happen. */
597         if (!dev->driver->get_scanout_position) {
598                 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
599                 return false;
600         }
601
602         if (drm_drv_uses_atomic_modeset(dev))
603                 mode = &vblank->hwmode;
604         else
605                 mode = &crtc->hwmode;
606
607         /* If mode timing undefined, just return as no-op:
608          * Happens during initial modesetting of a crtc.
609          */
610         if (mode->crtc_clock == 0) {
611                 DRM_DEBUG("crtc %u: Noop due to uninitialized mode.\n", pipe);
612                 WARN_ON_ONCE(drm_drv_uses_atomic_modeset(dev));
613
614                 return false;
615         }
616
617         /* Get current scanout position with system timestamp.
618          * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
619          * if single query takes longer than max_error nanoseconds.
620          *
621          * This guarantees a tight bound on maximum error if
622          * code gets preempted or delayed for some reason.
623          */
624         for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
625                 /*
626                  * Get vertical and horizontal scanout position vpos, hpos,
627                  * and bounding timestamps stime, etime, pre/post query.
628                  */
629                 vbl_status = dev->driver->get_scanout_position(dev, pipe,
630                                                                in_vblank_irq,
631                                                                &vpos, &hpos,
632                                                                &stime, &etime,
633                                                                mode);
634
635                 /* Return as no-op if scanout query unsupported or failed. */
636                 if (!vbl_status) {
637                         DRM_DEBUG("crtc %u : scanoutpos query failed.\n",
638                                   pipe);
639                         return false;
640                 }
641
642                 /* Compute uncertainty in timestamp of scanout position query. */
643                 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
644
645                 /* Accept result with <  max_error nsecs timing uncertainty. */
646                 if (duration_ns <= *max_error)
647                         break;
648         }
649
650         /* Noisy system timing? */
651         if (i == DRM_TIMESTAMP_MAXRETRIES) {
652                 DRM_DEBUG("crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
653                           pipe, duration_ns/1000, *max_error/1000, i);
654         }
655
656         /* Return upper bound of timestamp precision error. */
657         *max_error = duration_ns;
658
659         /* Convert scanout position into elapsed time at raw_time query
660          * since start of scanout at first display scanline. delta_ns
661          * can be negative if start of scanout hasn't happened yet.
662          */
663         delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
664                            mode->crtc_clock);
665
666         /* save this only for debugging purposes */
667         ts_etime = ktime_to_timespec64(etime);
668         ts_vblank_time = ktime_to_timespec64(*vblank_time);
669         /* Subtract time delta from raw timestamp to get final
670          * vblank_time timestamp for end of vblank.
671          */
672         etime = ktime_sub_ns(etime, delta_ns);
673         *vblank_time = etime;
674
675         DRM_DEBUG_VBL("crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
676                       pipe, hpos, vpos,
677                       (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
678                       (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
679                       duration_ns / 1000, i);
680
681         return true;
682 }
683 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
684
685 /**
686  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
687  *                             vblank interval
688  * @dev: DRM device
689  * @pipe: index of CRTC whose vblank timestamp to retrieve
690  * @tvblank: Pointer to target time which should receive the timestamp
691  * @in_vblank_irq:
692  *     True when called from drm_crtc_handle_vblank().  Some drivers
693  *     need to apply some workarounds for gpu-specific vblank irq quirks
694  *     if flag is set.
695  *
696  * Fetches the system timestamp corresponding to the time of the most recent
697  * vblank interval on specified CRTC. May call into kms-driver to
698  * compute the timestamp with a high-precision GPU specific method.
699  *
700  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
701  * call, i.e., it isn't very precisely locked to the true vblank.
702  *
703  * Returns:
704  * True if timestamp is considered to be very precise, false otherwise.
705  */
706 static bool
707 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
708                           ktime_t *tvblank, bool in_vblank_irq)
709 {
710         bool ret = false;
711
712         /* Define requested maximum error on timestamps (nanoseconds). */
713         int max_error = (int) drm_timestamp_precision * 1000;
714
715         /* Query driver if possible and precision timestamping enabled. */
716         if (dev->driver->get_vblank_timestamp && (max_error > 0))
717                 ret = dev->driver->get_vblank_timestamp(dev, pipe, &max_error,
718                                                         tvblank, in_vblank_irq);
719
720         /* GPU high precision timestamp query unsupported or failed.
721          * Return current monotonic/gettimeofday timestamp as best estimate.
722          */
723         if (!ret)
724                 *tvblank = ktime_get();
725
726         return ret;
727 }
728
729 /**
730  * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
731  * @crtc: which counter to retrieve
732  *
733  * Fetches the "cooked" vblank count value that represents the number of
734  * vblank events since the system was booted, including lost events due to
735  * modesetting activity. Note that this timer isn't correct against a racing
736  * vblank interrupt (since it only reports the software vblank counter), see
737  * drm_crtc_accurate_vblank_count() for such use-cases.
738  *
739  * Returns:
740  * The software vblank counter.
741  */
742 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
743 {
744         return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
745 }
746 EXPORT_SYMBOL(drm_crtc_vblank_count);
747
748 /**
749  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
750  *     system timestamp corresponding to that vblank counter value.
751  * @dev: DRM device
752  * @pipe: index of CRTC whose counter to retrieve
753  * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
754  *
755  * Fetches the "cooked" vblank count value that represents the number of
756  * vblank events since the system was booted, including lost events due to
757  * modesetting activity. Returns corresponding system timestamp of the time
758  * of the vblank interval that corresponds to the current vblank counter value.
759  *
760  * This is the legacy version of drm_crtc_vblank_count_and_time().
761  */
762 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
763                                      ktime_t *vblanktime)
764 {
765         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
766         u64 vblank_count;
767         unsigned int seq;
768
769         if (WARN_ON(pipe >= dev->num_crtcs)) {
770                 *vblanktime = 0;
771                 return 0;
772         }
773
774         do {
775                 seq = read_seqbegin(&vblank->seqlock);
776                 vblank_count = vblank->count;
777                 *vblanktime = vblank->time;
778         } while (read_seqretry(&vblank->seqlock, seq));
779
780         return vblank_count;
781 }
782
783 /**
784  * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
785  *     and the system timestamp corresponding to that vblank counter value
786  * @crtc: which counter to retrieve
787  * @vblanktime: Pointer to time to receive the vblank timestamp.
788  *
789  * Fetches the "cooked" vblank count value that represents the number of
790  * vblank events since the system was booted, including lost events due to
791  * modesetting activity. Returns corresponding system timestamp of the time
792  * of the vblank interval that corresponds to the current vblank counter value.
793  */
794 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
795                                    ktime_t *vblanktime)
796 {
797         return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
798                                          vblanktime);
799 }
800 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
801
802 static void send_vblank_event(struct drm_device *dev,
803                 struct drm_pending_vblank_event *e,
804                 u64 seq, ktime_t now)
805 {
806         struct timespec64 tv;
807
808         switch (e->event.base.type) {
809         case DRM_EVENT_VBLANK:
810         case DRM_EVENT_FLIP_COMPLETE:
811                 tv = ktime_to_timespec64(now);
812                 e->event.vbl.sequence = seq;
813                 /*
814                  * e->event is a user space structure, with hardcoded unsigned
815                  * 32-bit seconds/microseconds. This is safe as we always use
816                  * monotonic timestamps since linux-4.15
817                  */
818                 e->event.vbl.tv_sec = tv.tv_sec;
819                 e->event.vbl.tv_usec = tv.tv_nsec / 1000;
820                 break;
821         case DRM_EVENT_CRTC_SEQUENCE:
822                 if (seq)
823                         e->event.seq.sequence = seq;
824                 e->event.seq.time_ns = ktime_to_ns(now);
825                 break;
826         }
827         trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
828         drm_send_event_locked(dev, &e->base);
829 }
830
831 /**
832  * drm_crtc_arm_vblank_event - arm vblank event after pageflip
833  * @crtc: the source CRTC of the vblank event
834  * @e: the event to send
835  *
836  * A lot of drivers need to generate vblank events for the very next vblank
837  * interrupt. For example when the page flip interrupt happens when the page
838  * flip gets armed, but not when it actually executes within the next vblank
839  * period. This helper function implements exactly the required vblank arming
840  * behaviour.
841  *
842  * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
843  * atomic commit must ensure that the next vblank happens at exactly the same
844  * time as the atomic commit is committed to the hardware. This function itself
845  * does **not** protect against the next vblank interrupt racing with either this
846  * function call or the atomic commit operation. A possible sequence could be:
847  *
848  * 1. Driver commits new hardware state into vblank-synchronized registers.
849  * 2. A vblank happens, committing the hardware state. Also the corresponding
850  *    vblank interrupt is fired off and fully processed by the interrupt
851  *    handler.
852  * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
853  * 4. The event is only send out for the next vblank, which is wrong.
854  *
855  * An equivalent race can happen when the driver calls
856  * drm_crtc_arm_vblank_event() before writing out the new hardware state.
857  *
858  * The only way to make this work safely is to prevent the vblank from firing
859  * (and the hardware from committing anything else) until the entire atomic
860  * commit sequence has run to completion. If the hardware does not have such a
861  * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
862  * Instead drivers need to manually send out the event from their interrupt
863  * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
864  * possible race with the hardware committing the atomic update.
865  *
866  * Caller must hold a vblank reference for the event @e, which will be dropped
867  * when the next vblank arrives.
868  */
869 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
870                                struct drm_pending_vblank_event *e)
871 {
872         struct drm_device *dev = crtc->dev;
873         unsigned int pipe = drm_crtc_index(crtc);
874
875         assert_spin_locked(&dev->event_lock);
876
877         e->pipe = pipe;
878         e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
879         list_add_tail(&e->base.link, &dev->vblank_event_list);
880 }
881 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
882
883 /**
884  * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
885  * @crtc: the source CRTC of the vblank event
886  * @e: the event to send
887  *
888  * Updates sequence # and timestamp on event for the most recently processed
889  * vblank, and sends it to userspace.  Caller must hold event lock.
890  *
891  * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
892  * situation, especially to send out events for atomic commit operations.
893  */
894 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
895                                 struct drm_pending_vblank_event *e)
896 {
897         struct drm_device *dev = crtc->dev;
898         u64 seq;
899         unsigned int pipe = drm_crtc_index(crtc);
900         ktime_t now;
901
902         if (dev->num_crtcs > 0) {
903                 seq = drm_vblank_count_and_time(dev, pipe, &now);
904         } else {
905                 seq = 0;
906
907                 now = ktime_get();
908         }
909         e->pipe = pipe;
910         send_vblank_event(dev, e, seq, now);
911 }
912 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
913
914 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
915 {
916         if (drm_core_check_feature(dev, DRIVER_MODESET)) {
917                 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
918
919                 if (crtc->funcs->enable_vblank)
920                         return crtc->funcs->enable_vblank(crtc);
921         }
922
923         return dev->driver->enable_vblank(dev, pipe);
924 }
925
926 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
927 {
928         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
929         int ret = 0;
930
931         assert_spin_locked(&dev->vbl_lock);
932
933         spin_lock(&dev->vblank_time_lock);
934
935         if (!vblank->enabled) {
936                 /*
937                  * Enable vblank irqs under vblank_time_lock protection.
938                  * All vblank count & timestamp updates are held off
939                  * until we are done reinitializing master counter and
940                  * timestamps. Filtercode in drm_handle_vblank() will
941                  * prevent double-accounting of same vblank interval.
942                  */
943                 ret = __enable_vblank(dev, pipe);
944                 DRM_DEBUG("enabling vblank on crtc %u, ret: %d\n", pipe, ret);
945                 if (ret) {
946                         atomic_dec(&vblank->refcount);
947                 } else {
948                         drm_update_vblank_count(dev, pipe, 0);
949                         /* drm_update_vblank_count() includes a wmb so we just
950                          * need to ensure that the compiler emits the write
951                          * to mark the vblank as enabled after the call
952                          * to drm_update_vblank_count().
953                          */
954                         WRITE_ONCE(vblank->enabled, true);
955                 }
956         }
957
958         spin_unlock(&dev->vblank_time_lock);
959
960         return ret;
961 }
962
963 static int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
964 {
965         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
966         unsigned long irqflags;
967         int ret = 0;
968
969         if (!dev->num_crtcs)
970                 return -EINVAL;
971
972         if (WARN_ON(pipe >= dev->num_crtcs))
973                 return -EINVAL;
974
975         spin_lock_irqsave(&dev->vbl_lock, irqflags);
976         /* Going from 0->1 means we have to enable interrupts again */
977         if (atomic_add_return(1, &vblank->refcount) == 1) {
978                 ret = drm_vblank_enable(dev, pipe);
979         } else {
980                 if (!vblank->enabled) {
981                         atomic_dec(&vblank->refcount);
982                         ret = -EINVAL;
983                 }
984         }
985         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
986
987         return ret;
988 }
989
990 /**
991  * drm_crtc_vblank_get - get a reference count on vblank events
992  * @crtc: which CRTC to own
993  *
994  * Acquire a reference count on vblank events to avoid having them disabled
995  * while in use.
996  *
997  * Returns:
998  * Zero on success or a negative error code on failure.
999  */
1000 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1001 {
1002         return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1003 }
1004 EXPORT_SYMBOL(drm_crtc_vblank_get);
1005
1006 static void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1007 {
1008         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1009
1010         if (WARN_ON(pipe >= dev->num_crtcs))
1011                 return;
1012
1013         if (WARN_ON(atomic_read(&vblank->refcount) == 0))
1014                 return;
1015
1016         /* Last user schedules interrupt disable */
1017         if (atomic_dec_and_test(&vblank->refcount)) {
1018                 if (drm_vblank_offdelay == 0)
1019                         return;
1020                 else if (drm_vblank_offdelay < 0)
1021                         vblank_disable_fn(&vblank->disable_timer);
1022                 else if (!dev->vblank_disable_immediate)
1023                         mod_timer(&vblank->disable_timer,
1024                                   jiffies + ((drm_vblank_offdelay * HZ)/1000));
1025         }
1026 }
1027
1028 /**
1029  * drm_crtc_vblank_put - give up ownership of vblank events
1030  * @crtc: which counter to give up
1031  *
1032  * Release ownership of a given vblank counter, turning off interrupts
1033  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1034  */
1035 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1036 {
1037         drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1038 }
1039 EXPORT_SYMBOL(drm_crtc_vblank_put);
1040
1041 /**
1042  * drm_wait_one_vblank - wait for one vblank
1043  * @dev: DRM device
1044  * @pipe: CRTC index
1045  *
1046  * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1047  * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1048  * due to lack of driver support or because the crtc is off.
1049  *
1050  * This is the legacy version of drm_crtc_wait_one_vblank().
1051  */
1052 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1053 {
1054         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1055         int ret;
1056         u32 last;
1057
1058         if (WARN_ON(pipe >= dev->num_crtcs))
1059                 return;
1060
1061         ret = drm_vblank_get(dev, pipe);
1062         if (WARN(ret, "vblank not available on crtc %i, ret=%i\n", pipe, ret))
1063                 return;
1064
1065         last = drm_vblank_count(dev, pipe);
1066
1067         ret = wait_event_timeout(vblank->queue,
1068                                  last != drm_vblank_count(dev, pipe),
1069                                  msecs_to_jiffies(100));
1070
1071         WARN(ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1072
1073         drm_vblank_put(dev, pipe);
1074 }
1075 EXPORT_SYMBOL(drm_wait_one_vblank);
1076
1077 /**
1078  * drm_crtc_wait_one_vblank - wait for one vblank
1079  * @crtc: DRM crtc
1080  *
1081  * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1082  * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1083  * due to lack of driver support or because the crtc is off.
1084  */
1085 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1086 {
1087         drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1088 }
1089 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1090
1091 /**
1092  * drm_crtc_vblank_off - disable vblank events on a CRTC
1093  * @crtc: CRTC in question
1094  *
1095  * Drivers can use this function to shut down the vblank interrupt handling when
1096  * disabling a crtc. This function ensures that the latest vblank frame count is
1097  * stored so that drm_vblank_on can restore it again.
1098  *
1099  * Drivers must use this function when the hardware vblank counter can get
1100  * reset, e.g. when suspending or disabling the @crtc in general.
1101  */
1102 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1103 {
1104         struct drm_device *dev = crtc->dev;
1105         unsigned int pipe = drm_crtc_index(crtc);
1106         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1107         struct drm_pending_vblank_event *e, *t;
1108
1109         ktime_t now;
1110         unsigned long irqflags;
1111         u64 seq;
1112
1113         if (WARN_ON(pipe >= dev->num_crtcs))
1114                 return;
1115
1116         spin_lock_irqsave(&dev->event_lock, irqflags);
1117
1118         spin_lock(&dev->vbl_lock);
1119         DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1120                       pipe, vblank->enabled, vblank->inmodeset);
1121
1122         /* Avoid redundant vblank disables without previous
1123          * drm_crtc_vblank_on(). */
1124         if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1125                 drm_vblank_disable_and_save(dev, pipe);
1126
1127         wake_up(&vblank->queue);
1128
1129         /*
1130          * Prevent subsequent drm_vblank_get() from re-enabling
1131          * the vblank interrupt by bumping the refcount.
1132          */
1133         if (!vblank->inmodeset) {
1134                 atomic_inc(&vblank->refcount);
1135                 vblank->inmodeset = 1;
1136         }
1137         spin_unlock(&dev->vbl_lock);
1138
1139         /* Send any queued vblank events, lest the natives grow disquiet */
1140         seq = drm_vblank_count_and_time(dev, pipe, &now);
1141
1142         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1143                 if (e->pipe != pipe)
1144                         continue;
1145                 DRM_DEBUG("Sending premature vblank event on disable: "
1146                           "wanted %llu, current %llu\n",
1147                           e->sequence, seq);
1148                 list_del(&e->base.link);
1149                 drm_vblank_put(dev, pipe);
1150                 send_vblank_event(dev, e, seq, now);
1151         }
1152         spin_unlock_irqrestore(&dev->event_lock, irqflags);
1153
1154         /* Will be reset by the modeset helpers when re-enabling the crtc by
1155          * calling drm_calc_timestamping_constants(). */
1156         vblank->hwmode.crtc_clock = 0;
1157 }
1158 EXPORT_SYMBOL(drm_crtc_vblank_off);
1159
1160 /**
1161  * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1162  * @crtc: CRTC in question
1163  *
1164  * Drivers can use this function to reset the vblank state to off at load time.
1165  * Drivers should use this together with the drm_crtc_vblank_off() and
1166  * drm_crtc_vblank_on() functions. The difference compared to
1167  * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1168  * and hence doesn't need to call any driver hooks.
1169  *
1170  * This is useful for recovering driver state e.g. on driver load, or on resume.
1171  */
1172 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1173 {
1174         struct drm_device *dev = crtc->dev;
1175         unsigned long irqflags;
1176         unsigned int pipe = drm_crtc_index(crtc);
1177         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1178
1179         spin_lock_irqsave(&dev->vbl_lock, irqflags);
1180         /*
1181          * Prevent subsequent drm_vblank_get() from enabling the vblank
1182          * interrupt by bumping the refcount.
1183          */
1184         if (!vblank->inmodeset) {
1185                 atomic_inc(&vblank->refcount);
1186                 vblank->inmodeset = 1;
1187         }
1188         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1189
1190         WARN_ON(!list_empty(&dev->vblank_event_list));
1191 }
1192 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1193
1194 /**
1195  * drm_crtc_vblank_on - enable vblank events on a CRTC
1196  * @crtc: CRTC in question
1197  *
1198  * This functions restores the vblank interrupt state captured with
1199  * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1200  * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1201  * unbalanced and so can also be unconditionally called in driver load code to
1202  * reflect the current hardware state of the crtc.
1203  */
1204 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1205 {
1206         struct drm_device *dev = crtc->dev;
1207         unsigned int pipe = drm_crtc_index(crtc);
1208         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1209         unsigned long irqflags;
1210
1211         if (WARN_ON(pipe >= dev->num_crtcs))
1212                 return;
1213
1214         spin_lock_irqsave(&dev->vbl_lock, irqflags);
1215         DRM_DEBUG_VBL("crtc %d, vblank enabled %d, inmodeset %d\n",
1216                       pipe, vblank->enabled, vblank->inmodeset);
1217
1218         /* Drop our private "prevent drm_vblank_get" refcount */
1219         if (vblank->inmodeset) {
1220                 atomic_dec(&vblank->refcount);
1221                 vblank->inmodeset = 0;
1222         }
1223
1224         drm_reset_vblank_timestamp(dev, pipe);
1225
1226         /*
1227          * re-enable interrupts if there are users left, or the
1228          * user wishes vblank interrupts to be enabled all the time.
1229          */
1230         if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1231                 WARN_ON(drm_vblank_enable(dev, pipe));
1232         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1233 }
1234 EXPORT_SYMBOL(drm_crtc_vblank_on);
1235
1236 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1237                                           unsigned int pipe)
1238 {
1239         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1240
1241         /* vblank is not initialized (IRQ not installed ?), or has been freed */
1242         if (!dev->num_crtcs)
1243                 return;
1244
1245         if (WARN_ON(pipe >= dev->num_crtcs))
1246                 return;
1247
1248         /*
1249          * To avoid all the problems that might happen if interrupts
1250          * were enabled/disabled around or between these calls, we just
1251          * have the kernel take a reference on the CRTC (just once though
1252          * to avoid corrupting the count if multiple, mismatch calls occur),
1253          * so that interrupts remain enabled in the interim.
1254          */
1255         if (!vblank->inmodeset) {
1256                 vblank->inmodeset = 0x1;
1257                 if (drm_vblank_get(dev, pipe) == 0)
1258                         vblank->inmodeset |= 0x2;
1259         }
1260 }
1261
1262 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1263                                            unsigned int pipe)
1264 {
1265         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1266         unsigned long irqflags;
1267
1268         /* vblank is not initialized (IRQ not installed ?), or has been freed */
1269         if (!dev->num_crtcs)
1270                 return;
1271
1272         if (WARN_ON(pipe >= dev->num_crtcs))
1273                 return;
1274
1275         if (vblank->inmodeset) {
1276                 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1277                 drm_reset_vblank_timestamp(dev, pipe);
1278                 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1279
1280                 if (vblank->inmodeset & 0x2)
1281                         drm_vblank_put(dev, pipe);
1282
1283                 vblank->inmodeset = 0;
1284         }
1285 }
1286
1287 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1288                                  struct drm_file *file_priv)
1289 {
1290         struct drm_modeset_ctl *modeset = data;
1291         unsigned int pipe;
1292
1293         /* If drm_vblank_init() hasn't been called yet, just no-op */
1294         if (!dev->num_crtcs)
1295                 return 0;
1296
1297         /* KMS drivers handle this internally */
1298         if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1299                 return 0;
1300
1301         pipe = modeset->crtc;
1302         if (pipe >= dev->num_crtcs)
1303                 return -EINVAL;
1304
1305         switch (modeset->cmd) {
1306         case _DRM_PRE_MODESET:
1307                 drm_legacy_vblank_pre_modeset(dev, pipe);
1308                 break;
1309         case _DRM_POST_MODESET:
1310                 drm_legacy_vblank_post_modeset(dev, pipe);
1311                 break;
1312         default:
1313                 return -EINVAL;
1314         }
1315
1316         return 0;
1317 }
1318
1319 static inline bool vblank_passed(u64 seq, u64 ref)
1320 {
1321         return (seq - ref) <= (1 << 23);
1322 }
1323
1324 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1325                                   u64 req_seq,
1326                                   union drm_wait_vblank *vblwait,
1327                                   struct drm_file *file_priv)
1328 {
1329         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1330         struct drm_pending_vblank_event *e;
1331         ktime_t now;
1332         unsigned long flags;
1333         u64 seq;
1334         int ret;
1335
1336         e = kzalloc(sizeof(*e), GFP_KERNEL);
1337         if (e == NULL) {
1338                 ret = -ENOMEM;
1339                 goto err_put;
1340         }
1341
1342         e->pipe = pipe;
1343         e->event.base.type = DRM_EVENT_VBLANK;
1344         e->event.base.length = sizeof(e->event.vbl);
1345         e->event.vbl.user_data = vblwait->request.signal;
1346         e->event.vbl.crtc_id = 0;
1347         if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1348                 struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1349                 if (crtc)
1350                         e->event.vbl.crtc_id = crtc->base.id;
1351         }
1352
1353         spin_lock_irqsave(&dev->event_lock, flags);
1354
1355         /*
1356          * drm_crtc_vblank_off() might have been called after we called
1357          * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1358          * vblank disable, so no need for further locking.  The reference from
1359          * drm_vblank_get() protects against vblank disable from another source.
1360          */
1361         if (!READ_ONCE(vblank->enabled)) {
1362                 ret = -EINVAL;
1363                 goto err_unlock;
1364         }
1365
1366         ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1367                                             &e->event.base);
1368
1369         if (ret)
1370                 goto err_unlock;
1371
1372         seq = drm_vblank_count_and_time(dev, pipe, &now);
1373
1374         DRM_DEBUG("event on vblank count %llu, current %llu, crtc %u\n",
1375                   req_seq, seq, pipe);
1376
1377         trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1378
1379         e->sequence = req_seq;
1380         if (vblank_passed(seq, req_seq)) {
1381                 drm_vblank_put(dev, pipe);
1382                 send_vblank_event(dev, e, seq, now);
1383                 vblwait->reply.sequence = seq;
1384         } else {
1385                 /* drm_handle_vblank_events will call drm_vblank_put */
1386                 list_add_tail(&e->base.link, &dev->vblank_event_list);
1387                 vblwait->reply.sequence = req_seq;
1388         }
1389
1390         spin_unlock_irqrestore(&dev->event_lock, flags);
1391
1392         return 0;
1393
1394 err_unlock:
1395         spin_unlock_irqrestore(&dev->event_lock, flags);
1396         kfree(e);
1397 err_put:
1398         drm_vblank_put(dev, pipe);
1399         return ret;
1400 }
1401
1402 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1403 {
1404         if (vblwait->request.sequence)
1405                 return false;
1406
1407         return _DRM_VBLANK_RELATIVE ==
1408                 (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1409                                           _DRM_VBLANK_EVENT |
1410                                           _DRM_VBLANK_NEXTONMISS));
1411 }
1412
1413 /*
1414  * Widen a 32-bit param to 64-bits.
1415  *
1416  * \param narrow 32-bit value (missing upper 32 bits)
1417  * \param near 64-bit value that should be 'close' to near
1418  *
1419  * This function returns a 64-bit value using the lower 32-bits from
1420  * 'narrow' and constructing the upper 32-bits so that the result is
1421  * as close as possible to 'near'.
1422  */
1423
1424 static u64 widen_32_to_64(u32 narrow, u64 near)
1425 {
1426         return near + (s32) (narrow - near);
1427 }
1428
1429 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1430                                   struct drm_wait_vblank_reply *reply)
1431 {
1432         ktime_t now;
1433         struct timespec64 ts;
1434
1435         /*
1436          * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1437          * to store the seconds. This is safe as we always use monotonic
1438          * timestamps since linux-4.15.
1439          */
1440         reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1441         ts = ktime_to_timespec64(now);
1442         reply->tval_sec = (u32)ts.tv_sec;
1443         reply->tval_usec = ts.tv_nsec / 1000;
1444 }
1445
1446 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1447                           struct drm_file *file_priv)
1448 {
1449         struct drm_crtc *crtc;
1450         struct drm_vblank_crtc *vblank;
1451         union drm_wait_vblank *vblwait = data;
1452         int ret;
1453         u64 req_seq, seq;
1454         unsigned int pipe_index;
1455         unsigned int flags, pipe, high_pipe;
1456
1457         if (!dev->irq_enabled)
1458                 return -EINVAL;
1459
1460         if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1461                 return -EINVAL;
1462
1463         if (vblwait->request.type &
1464             ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1465               _DRM_VBLANK_HIGH_CRTC_MASK)) {
1466                 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1467                           vblwait->request.type,
1468                           (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1469                            _DRM_VBLANK_HIGH_CRTC_MASK));
1470                 return -EINVAL;
1471         }
1472
1473         flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1474         high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1475         if (high_pipe)
1476                 pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1477         else
1478                 pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1479
1480         /* Convert lease-relative crtc index into global crtc index */
1481         if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1482                 pipe = 0;
1483                 drm_for_each_crtc(crtc, dev) {
1484                         if (drm_lease_held(file_priv, crtc->base.id)) {
1485                                 if (pipe_index == 0)
1486                                         break;
1487                                 pipe_index--;
1488                         }
1489                         pipe++;
1490                 }
1491         } else {
1492                 pipe = pipe_index;
1493         }
1494
1495         if (pipe >= dev->num_crtcs)
1496                 return -EINVAL;
1497
1498         vblank = &dev->vblank[pipe];
1499
1500         /* If the counter is currently enabled and accurate, short-circuit
1501          * queries to return the cached timestamp of the last vblank.
1502          */
1503         if (dev->vblank_disable_immediate &&
1504             drm_wait_vblank_is_query(vblwait) &&
1505             READ_ONCE(vblank->enabled)) {
1506                 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1507                 return 0;
1508         }
1509
1510         ret = drm_vblank_get(dev, pipe);
1511         if (ret) {
1512                 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1513                 return ret;
1514         }
1515         seq = drm_vblank_count(dev, pipe);
1516
1517         switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1518         case _DRM_VBLANK_RELATIVE:
1519                 req_seq = seq + vblwait->request.sequence;
1520                 vblwait->request.sequence = req_seq;
1521                 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1522                 break;
1523         case _DRM_VBLANK_ABSOLUTE:
1524                 req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1525                 break;
1526         default:
1527                 ret = -EINVAL;
1528                 goto done;
1529         }
1530
1531         if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1532             vblank_passed(seq, req_seq)) {
1533                 req_seq = seq + 1;
1534                 vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1535                 vblwait->request.sequence = req_seq;
1536         }
1537
1538         if (flags & _DRM_VBLANK_EVENT) {
1539                 /* must hold on to the vblank ref until the event fires
1540                  * drm_vblank_put will be called asynchronously
1541                  */
1542                 return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1543         }
1544
1545         if (req_seq != seq) {
1546                 DRM_DEBUG("waiting on vblank count %llu, crtc %u\n",
1547                           req_seq, pipe);
1548                 DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1549                             vblank_passed(drm_vblank_count(dev, pipe),
1550                                           req_seq) ||
1551                             !READ_ONCE(vblank->enabled));
1552         }
1553
1554         if (ret != -EINTR) {
1555                 drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1556
1557                 DRM_DEBUG("crtc %d returning %u to client\n",
1558                           pipe, vblwait->reply.sequence);
1559         } else {
1560                 DRM_DEBUG("crtc %d vblank wait interrupted by signal\n", pipe);
1561         }
1562
1563 done:
1564         drm_vblank_put(dev, pipe);
1565         return ret;
1566 }
1567
1568 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1569 {
1570         struct drm_pending_vblank_event *e, *t;
1571         ktime_t now;
1572         u64 seq;
1573
1574         assert_spin_locked(&dev->event_lock);
1575
1576         seq = drm_vblank_count_and_time(dev, pipe, &now);
1577
1578         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1579                 if (e->pipe != pipe)
1580                         continue;
1581                 if (!vblank_passed(seq, e->sequence))
1582                         continue;
1583
1584                 DRM_DEBUG("vblank event on %llu, current %llu\n",
1585                           e->sequence, seq);
1586
1587                 list_del(&e->base.link);
1588                 drm_vblank_put(dev, pipe);
1589                 send_vblank_event(dev, e, seq, now);
1590         }
1591
1592         trace_drm_vblank_event(pipe, seq);
1593 }
1594
1595 /**
1596  * drm_handle_vblank - handle a vblank event
1597  * @dev: DRM device
1598  * @pipe: index of CRTC where this event occurred
1599  *
1600  * Drivers should call this routine in their vblank interrupt handlers to
1601  * update the vblank counter and send any signals that may be pending.
1602  *
1603  * This is the legacy version of drm_crtc_handle_vblank().
1604  */
1605 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1606 {
1607         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1608         unsigned long irqflags;
1609         bool disable_irq;
1610
1611         if (WARN_ON_ONCE(!dev->num_crtcs))
1612                 return false;
1613
1614         if (WARN_ON(pipe >= dev->num_crtcs))
1615                 return false;
1616
1617         spin_lock_irqsave(&dev->event_lock, irqflags);
1618
1619         /* Need timestamp lock to prevent concurrent execution with
1620          * vblank enable/disable, as this would cause inconsistent
1621          * or corrupted timestamps and vblank counts.
1622          */
1623         spin_lock(&dev->vblank_time_lock);
1624
1625         /* Vblank irq handling disabled. Nothing to do. */
1626         if (!vblank->enabled) {
1627                 spin_unlock(&dev->vblank_time_lock);
1628                 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1629                 return false;
1630         }
1631
1632         drm_update_vblank_count(dev, pipe, true);
1633
1634         spin_unlock(&dev->vblank_time_lock);
1635
1636         wake_up(&vblank->queue);
1637
1638         /* With instant-off, we defer disabling the interrupt until after
1639          * we finish processing the following vblank after all events have
1640          * been signaled. The disable has to be last (after
1641          * drm_handle_vblank_events) so that the timestamp is always accurate.
1642          */
1643         disable_irq = (dev->vblank_disable_immediate &&
1644                        drm_vblank_offdelay > 0 &&
1645                        !atomic_read(&vblank->refcount));
1646
1647         drm_handle_vblank_events(dev, pipe);
1648
1649         spin_unlock_irqrestore(&dev->event_lock, irqflags);
1650
1651         if (disable_irq)
1652                 vblank_disable_fn(&vblank->disable_timer);
1653
1654         return true;
1655 }
1656 EXPORT_SYMBOL(drm_handle_vblank);
1657
1658 /**
1659  * drm_crtc_handle_vblank - handle a vblank event
1660  * @crtc: where this event occurred
1661  *
1662  * Drivers should call this routine in their vblank interrupt handlers to
1663  * update the vblank counter and send any signals that may be pending.
1664  *
1665  * This is the native KMS version of drm_handle_vblank().
1666  *
1667  * Returns:
1668  * True if the event was successfully handled, false on failure.
1669  */
1670 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
1671 {
1672         return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
1673 }
1674 EXPORT_SYMBOL(drm_crtc_handle_vblank);
1675
1676 /*
1677  * Get crtc VBLANK count.
1678  *
1679  * \param dev DRM device
1680  * \param data user arguement, pointing to a drm_crtc_get_sequence structure.
1681  * \param file_priv drm file private for the user's open file descriptor
1682  */
1683
1684 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
1685                                 struct drm_file *file_priv)
1686 {
1687         struct drm_crtc *crtc;
1688         struct drm_vblank_crtc *vblank;
1689         int pipe;
1690         struct drm_crtc_get_sequence *get_seq = data;
1691         ktime_t now;
1692         bool vblank_enabled;
1693         int ret;
1694
1695         if (!drm_core_check_feature(dev, DRIVER_MODESET))
1696                 return -EINVAL;
1697
1698         if (!dev->irq_enabled)
1699                 return -EINVAL;
1700
1701         crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
1702         if (!crtc)
1703                 return -ENOENT;
1704
1705         pipe = drm_crtc_index(crtc);
1706
1707         vblank = &dev->vblank[pipe];
1708         vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
1709
1710         if (!vblank_enabled) {
1711                 ret = drm_crtc_vblank_get(crtc);
1712                 if (ret) {
1713                         DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1714                         return ret;
1715                 }
1716         }
1717         drm_modeset_lock(&crtc->mutex, NULL);
1718         if (crtc->state)
1719                 get_seq->active = crtc->state->enable;
1720         else
1721                 get_seq->active = crtc->enabled;
1722         drm_modeset_unlock(&crtc->mutex);
1723         get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1724         get_seq->sequence_ns = ktime_to_ns(now);
1725         if (!vblank_enabled)
1726                 drm_crtc_vblank_put(crtc);
1727         return 0;
1728 }
1729
1730 /*
1731  * Queue a event for VBLANK sequence
1732  *
1733  * \param dev DRM device
1734  * \param data user arguement, pointing to a drm_crtc_queue_sequence structure.
1735  * \param file_priv drm file private for the user's open file descriptor
1736  */
1737
1738 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
1739                                   struct drm_file *file_priv)
1740 {
1741         struct drm_crtc *crtc;
1742         struct drm_vblank_crtc *vblank;
1743         int pipe;
1744         struct drm_crtc_queue_sequence *queue_seq = data;
1745         ktime_t now;
1746         struct drm_pending_vblank_event *e;
1747         u32 flags;
1748         u64 seq;
1749         u64 req_seq;
1750         int ret;
1751         unsigned long spin_flags;
1752
1753         if (!drm_core_check_feature(dev, DRIVER_MODESET))
1754                 return -EINVAL;
1755
1756         if (!dev->irq_enabled)
1757                 return -EINVAL;
1758
1759         crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
1760         if (!crtc)
1761                 return -ENOENT;
1762
1763         flags = queue_seq->flags;
1764         /* Check valid flag bits */
1765         if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
1766                       DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
1767                 return -EINVAL;
1768
1769         pipe = drm_crtc_index(crtc);
1770
1771         vblank = &dev->vblank[pipe];
1772
1773         e = kzalloc(sizeof(*e), GFP_KERNEL);
1774         if (e == NULL)
1775                 return -ENOMEM;
1776
1777         ret = drm_crtc_vblank_get(crtc);
1778         if (ret) {
1779                 DRM_DEBUG("crtc %d failed to acquire vblank counter, %d\n", pipe, ret);
1780                 goto err_free;
1781         }
1782
1783         seq = drm_vblank_count_and_time(dev, pipe, &now);
1784         req_seq = queue_seq->sequence;
1785
1786         if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
1787                 req_seq += seq;
1788
1789         if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && vblank_passed(seq, req_seq))
1790                 req_seq = seq + 1;
1791
1792         e->pipe = pipe;
1793         e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
1794         e->event.base.length = sizeof(e->event.seq);
1795         e->event.seq.user_data = queue_seq->user_data;
1796
1797         spin_lock_irqsave(&dev->event_lock, spin_flags);
1798
1799         /*
1800          * drm_crtc_vblank_off() might have been called after we called
1801          * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1802          * vblank disable, so no need for further locking.  The reference from
1803          * drm_crtc_vblank_get() protects against vblank disable from another source.
1804          */
1805         if (!READ_ONCE(vblank->enabled)) {
1806                 ret = -EINVAL;
1807                 goto err_unlock;
1808         }
1809
1810         ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1811                                             &e->event.base);
1812
1813         if (ret)
1814                 goto err_unlock;
1815
1816         e->sequence = req_seq;
1817
1818         if (vblank_passed(seq, req_seq)) {
1819                 drm_crtc_vblank_put(crtc);
1820                 send_vblank_event(dev, e, seq, now);
1821                 queue_seq->sequence = seq;
1822         } else {
1823                 /* drm_handle_vblank_events will call drm_vblank_put */
1824                 list_add_tail(&e->base.link, &dev->vblank_event_list);
1825                 queue_seq->sequence = req_seq;
1826         }
1827
1828         spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1829         return 0;
1830
1831 err_unlock:
1832         spin_unlock_irqrestore(&dev->event_lock, spin_flags);
1833         drm_crtc_vblank_put(crtc);
1834 err_free:
1835         kfree(e);
1836         return ret;
1837 }