drm: Really never disable vblank irqs for offdelay==0
[firefly-linux-kernel-4.4.55.git] / drivers / gpu / drm / drm_irq.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
8 /*
9  * Created: Fri Mar 19 14:30:16 1999 by faith@valinux.com
10  *
11  * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
12  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
13  * All Rights Reserved.
14  *
15  * Permission is hereby granted, free of charge, to any person obtaining a
16  * copy of this software and associated documentation files (the "Software"),
17  * to deal in the Software without restriction, including without limitation
18  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19  * and/or sell copies of the Software, and to permit persons to whom the
20  * Software is furnished to do so, subject to the following conditions:
21  *
22  * The above copyright notice and this permission notice (including the next
23  * paragraph) shall be included in all copies or substantial portions of the
24  * Software.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
29  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
30  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
31  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
32  * OTHER DEALINGS IN THE SOFTWARE.
33  */
34
35 #include <drm/drmP.h>
36 #include "drm_trace.h"
37
38 #include <linux/interrupt.h>    /* For task queue support */
39 #include <linux/slab.h>
40
41 #include <linux/vgaarb.h>
42 #include <linux/export.h>
43
44 /* Access macro for slots in vblank timestamp ringbuffer. */
45 #define vblanktimestamp(dev, crtc, count) \
46         ((dev)->vblank[crtc].time[(count) % DRM_VBLANKTIME_RBSIZE])
47
48 /* Retry timestamp calculation up to 3 times to satisfy
49  * drm_timestamp_precision before giving up.
50  */
51 #define DRM_TIMESTAMP_MAXRETRIES 3
52
53 /* Threshold in nanoseconds for detection of redundant
54  * vblank irq in drm_handle_vblank(). 1 msec should be ok.
55  */
56 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
57
58 /**
59  * drm_update_vblank_count - update the master vblank counter
60  * @dev: DRM device
61  * @crtc: counter to update
62  *
63  * Call back into the driver to update the appropriate vblank counter
64  * (specified by @crtc).  Deal with wraparound, if it occurred, and
65  * update the last read value so we can deal with wraparound on the next
66  * call if necessary.
67  *
68  * Only necessary when going from off->on, to account for frames we
69  * didn't get an interrupt for.
70  *
71  * Note: caller must hold dev->vbl_lock since this reads & writes
72  * device vblank fields.
73  */
74 static void drm_update_vblank_count(struct drm_device *dev, int crtc)
75 {
76         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
77         u32 cur_vblank, diff, tslot, rc;
78         struct timeval t_vblank;
79
80         /*
81          * Interrupts were disabled prior to this call, so deal with counter
82          * wrap if needed.
83          * NOTE!  It's possible we lost a full dev->max_vblank_count events
84          * here if the register is small or we had vblank interrupts off for
85          * a long time.
86          *
87          * We repeat the hardware vblank counter & timestamp query until
88          * we get consistent results. This to prevent races between gpu
89          * updating its hardware counter while we are retrieving the
90          * corresponding vblank timestamp.
91          */
92         do {
93                 cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
94                 rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
95         } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
96
97         /* Deal with counter wrap */
98         diff = cur_vblank - vblank->last;
99         if (cur_vblank < vblank->last) {
100                 diff += dev->max_vblank_count;
101
102                 DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
103                           crtc, vblank->last, cur_vblank, diff);
104         }
105
106         DRM_DEBUG("updating vblank count on crtc %d, missed %d\n",
107                   crtc, diff);
108
109         /* Reinitialize corresponding vblank timestamp if high-precision query
110          * available. Skip this step if query unsupported or failed. Will
111          * reinitialize delayed at next vblank interrupt in that case.
112          */
113         if (rc) {
114                 tslot = atomic_read(&vblank->count) + diff;
115                 vblanktimestamp(dev, crtc, tslot) = t_vblank;
116         }
117
118         smp_mb__before_atomic();
119         atomic_add(diff, &vblank->count);
120         smp_mb__after_atomic();
121 }
122
123 /*
124  * Disable vblank irq's on crtc, make sure that last vblank count
125  * of hardware and corresponding consistent software vblank counter
126  * are preserved, even if there are any spurious vblank irq's after
127  * disable.
128  */
129 static void vblank_disable_and_save(struct drm_device *dev, int crtc)
130 {
131         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
132         unsigned long irqflags;
133         u32 vblcount;
134         s64 diff_ns;
135         int vblrc;
136         struct timeval tvblank;
137         int count = DRM_TIMESTAMP_MAXRETRIES;
138
139         /* Prevent vblank irq processing while disabling vblank irqs,
140          * so no updates of timestamps or count can happen after we've
141          * disabled. Needed to prevent races in case of delayed irq's.
142          */
143         spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
144
145         /*
146          * If the vblank interrupt was already disbled update the count
147          * and timestamp to maintain the appearance that the counter
148          * has been ticking all along until this time. This makes the
149          * count account for the entire time between drm_vblank_on() and
150          * drm_vblank_off().
151          */
152         if (!vblank->enabled) {
153                 drm_update_vblank_count(dev, crtc);
154                 spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
155                 return;
156         }
157
158         dev->driver->disable_vblank(dev, crtc);
159         vblank->enabled = false;
160
161         /* No further vblank irq's will be processed after
162          * this point. Get current hardware vblank count and
163          * vblank timestamp, repeat until they are consistent.
164          *
165          * FIXME: There is still a race condition here and in
166          * drm_update_vblank_count() which can cause off-by-one
167          * reinitialization of software vblank counter. If gpu
168          * vblank counter doesn't increment exactly at the leading
169          * edge of a vblank interval, then we can lose 1 count if
170          * we happen to execute between start of vblank and the
171          * delayed gpu counter increment.
172          */
173         do {
174                 vblank->last = dev->driver->get_vblank_counter(dev, crtc);
175                 vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
176         } while (vblank->last != dev->driver->get_vblank_counter(dev, crtc) && (--count) && vblrc);
177
178         if (!count)
179                 vblrc = 0;
180
181         /* Compute time difference to stored timestamp of last vblank
182          * as updated by last invocation of drm_handle_vblank() in vblank irq.
183          */
184         vblcount = atomic_read(&vblank->count);
185         diff_ns = timeval_to_ns(&tvblank) -
186                   timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
187
188         /* If there is at least 1 msec difference between the last stored
189          * timestamp and tvblank, then we are currently executing our
190          * disable inside a new vblank interval, the tvblank timestamp
191          * corresponds to this new vblank interval and the irq handler
192          * for this vblank didn't run yet and won't run due to our disable.
193          * Therefore we need to do the job of drm_handle_vblank() and
194          * increment the vblank counter by one to account for this vblank.
195          *
196          * Skip this step if there isn't any high precision timestamp
197          * available. In that case we can't account for this and just
198          * hope for the best.
199          */
200         if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) {
201                 /* Store new timestamp in ringbuffer. */
202                 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
203
204                 /* Increment cooked vblank count. This also atomically commits
205                  * the timestamp computed above.
206                  */
207                 smp_mb__before_atomic();
208                 atomic_inc(&vblank->count);
209                 smp_mb__after_atomic();
210         }
211
212         spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
213 }
214
215 static void vblank_disable_fn(unsigned long arg)
216 {
217         struct drm_vblank_crtc *vblank = (void *)arg;
218         struct drm_device *dev = vblank->dev;
219         unsigned long irqflags;
220         int crtc = vblank->crtc;
221
222         if (!dev->vblank_disable_allowed)
223                 return;
224
225         spin_lock_irqsave(&dev->vbl_lock, irqflags);
226         if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
227                 DRM_DEBUG("disabling vblank on crtc %d\n", crtc);
228                 vblank_disable_and_save(dev, crtc);
229         }
230         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
231 }
232
233 /**
234  * drm_vblank_cleanup - cleanup vblank support
235  * @dev: DRM device
236  *
237  * This function cleans up any resources allocated in drm_vblank_init.
238  */
239 void drm_vblank_cleanup(struct drm_device *dev)
240 {
241         int crtc;
242         unsigned long irqflags;
243
244         /* Bail if the driver didn't call drm_vblank_init() */
245         if (dev->num_crtcs == 0)
246                 return;
247
248         for (crtc = 0; crtc < dev->num_crtcs; crtc++) {
249                 struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
250
251                 del_timer_sync(&vblank->disable_timer);
252
253                 spin_lock_irqsave(&dev->vbl_lock, irqflags);
254                 vblank_disable_and_save(dev, crtc);
255                 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
256         }
257
258         kfree(dev->vblank);
259
260         dev->num_crtcs = 0;
261 }
262 EXPORT_SYMBOL(drm_vblank_cleanup);
263
264 /**
265  * drm_vblank_init - initialize vblank support
266  * @dev: drm_device
267  * @num_crtcs: number of crtcs supported by @dev
268  *
269  * This function initializes vblank support for @num_crtcs display pipelines.
270  *
271  * Returns:
272  * Zero on success or a negative error code on failure.
273  */
274 int drm_vblank_init(struct drm_device *dev, int num_crtcs)
275 {
276         int i, ret = -ENOMEM;
277
278         spin_lock_init(&dev->vbl_lock);
279         spin_lock_init(&dev->vblank_time_lock);
280
281         dev->num_crtcs = num_crtcs;
282
283         dev->vblank = kcalloc(num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
284         if (!dev->vblank)
285                 goto err;
286
287         for (i = 0; i < num_crtcs; i++) {
288                 struct drm_vblank_crtc *vblank = &dev->vblank[i];
289
290                 vblank->dev = dev;
291                 vblank->crtc = i;
292                 init_waitqueue_head(&vblank->queue);
293                 setup_timer(&vblank->disable_timer, vblank_disable_fn,
294                             (unsigned long)vblank);
295         }
296
297         DRM_INFO("Supports vblank timestamp caching Rev 2 (21.10.2013).\n");
298
299         /* Driver specific high-precision vblank timestamping supported? */
300         if (dev->driver->get_vblank_timestamp)
301                 DRM_INFO("Driver supports precise vblank timestamp query.\n");
302         else
303                 DRM_INFO("No driver support for vblank timestamp query.\n");
304
305         dev->vblank_disable_allowed = false;
306
307         return 0;
308
309 err:
310         dev->num_crtcs = 0;
311         return ret;
312 }
313 EXPORT_SYMBOL(drm_vblank_init);
314
315 static void drm_irq_vgaarb_nokms(void *cookie, bool state)
316 {
317         struct drm_device *dev = cookie;
318
319         if (dev->driver->vgaarb_irq) {
320                 dev->driver->vgaarb_irq(dev, state);
321                 return;
322         }
323
324         if (!dev->irq_enabled)
325                 return;
326
327         if (state) {
328                 if (dev->driver->irq_uninstall)
329                         dev->driver->irq_uninstall(dev);
330         } else {
331                 if (dev->driver->irq_preinstall)
332                         dev->driver->irq_preinstall(dev);
333                 if (dev->driver->irq_postinstall)
334                         dev->driver->irq_postinstall(dev);
335         }
336 }
337
338 /**
339  * drm_irq_install - install IRQ handler
340  * @dev: DRM device
341  * @irq: IRQ number to install the handler for
342  *
343  * Initializes the IRQ related data. Installs the handler, calling the driver
344  * irq_preinstall() and irq_postinstall() functions before and after the
345  * installation.
346  *
347  * This is the simplified helper interface provided for drivers with no special
348  * needs. Drivers which need to install interrupt handlers for multiple
349  * interrupts must instead set drm_device->irq_enabled to signal the DRM core
350  * that vblank interrupts are available.
351  *
352  * Returns:
353  * Zero on success or a negative error code on failure.
354  */
355 int drm_irq_install(struct drm_device *dev, int irq)
356 {
357         int ret;
358         unsigned long sh_flags = 0;
359
360         if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
361                 return -EINVAL;
362
363         if (irq == 0)
364                 return -EINVAL;
365
366         /* Driver must have been initialized */
367         if (!dev->dev_private)
368                 return -EINVAL;
369
370         if (dev->irq_enabled)
371                 return -EBUSY;
372         dev->irq_enabled = true;
373
374         DRM_DEBUG("irq=%d\n", irq);
375
376         /* Before installing handler */
377         if (dev->driver->irq_preinstall)
378                 dev->driver->irq_preinstall(dev);
379
380         /* Install handler */
381         if (drm_core_check_feature(dev, DRIVER_IRQ_SHARED))
382                 sh_flags = IRQF_SHARED;
383
384         ret = request_irq(irq, dev->driver->irq_handler,
385                           sh_flags, dev->driver->name, dev);
386
387         if (ret < 0) {
388                 dev->irq_enabled = false;
389                 return ret;
390         }
391
392         if (!drm_core_check_feature(dev, DRIVER_MODESET))
393                 vga_client_register(dev->pdev, (void *)dev, drm_irq_vgaarb_nokms, NULL);
394
395         /* After installing handler */
396         if (dev->driver->irq_postinstall)
397                 ret = dev->driver->irq_postinstall(dev);
398
399         if (ret < 0) {
400                 dev->irq_enabled = false;
401                 if (!drm_core_check_feature(dev, DRIVER_MODESET))
402                         vga_client_register(dev->pdev, NULL, NULL, NULL);
403                 free_irq(irq, dev);
404         } else {
405                 dev->irq = irq;
406         }
407
408         return ret;
409 }
410 EXPORT_SYMBOL(drm_irq_install);
411
412 /**
413  * drm_irq_uninstall - uninstall the IRQ handler
414  * @dev: DRM device
415  *
416  * Calls the driver's irq_uninstall() function and unregisters the IRQ handler.
417  * This should only be called by drivers which used drm_irq_install() to set up
418  * their interrupt handler. Other drivers must only reset
419  * drm_device->irq_enabled to false.
420  *
421  * Note that for kernel modesetting drivers it is a bug if this function fails.
422  * The sanity checks are only to catch buggy user modesetting drivers which call
423  * the same function through an ioctl.
424  *
425  * Returns:
426  * Zero on success or a negative error code on failure.
427  */
428 int drm_irq_uninstall(struct drm_device *dev)
429 {
430         unsigned long irqflags;
431         bool irq_enabled;
432         int i;
433
434         if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
435                 return -EINVAL;
436
437         irq_enabled = dev->irq_enabled;
438         dev->irq_enabled = false;
439
440         /*
441          * Wake up any waiters so they don't hang.
442          */
443         if (dev->num_crtcs) {
444                 spin_lock_irqsave(&dev->vbl_lock, irqflags);
445                 for (i = 0; i < dev->num_crtcs; i++) {
446                         struct drm_vblank_crtc *vblank = &dev->vblank[i];
447
448                         wake_up(&vblank->queue);
449                         vblank->enabled = false;
450                         vblank->last =
451                                 dev->driver->get_vblank_counter(dev, i);
452                 }
453                 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
454         }
455
456         if (!irq_enabled)
457                 return -EINVAL;
458
459         DRM_DEBUG("irq=%d\n", dev->irq);
460
461         if (!drm_core_check_feature(dev, DRIVER_MODESET))
462                 vga_client_register(dev->pdev, NULL, NULL, NULL);
463
464         if (dev->driver->irq_uninstall)
465                 dev->driver->irq_uninstall(dev);
466
467         free_irq(dev->irq, dev);
468
469         return 0;
470 }
471 EXPORT_SYMBOL(drm_irq_uninstall);
472
473 /*
474  * IRQ control ioctl.
475  *
476  * \param inode device inode.
477  * \param file_priv DRM file private.
478  * \param cmd command.
479  * \param arg user argument, pointing to a drm_control structure.
480  * \return zero on success or a negative number on failure.
481  *
482  * Calls irq_install() or irq_uninstall() according to \p arg.
483  */
484 int drm_control(struct drm_device *dev, void *data,
485                 struct drm_file *file_priv)
486 {
487         struct drm_control *ctl = data;
488         int ret = 0, irq;
489
490         /* if we haven't irq we fallback for compatibility reasons -
491          * this used to be a separate function in drm_dma.h
492          */
493
494         if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
495                 return 0;
496         if (drm_core_check_feature(dev, DRIVER_MODESET))
497                 return 0;
498         /* UMS was only ever support on pci devices. */
499         if (WARN_ON(!dev->pdev))
500                 return -EINVAL;
501
502         switch (ctl->func) {
503         case DRM_INST_HANDLER:
504                 irq = dev->pdev->irq;
505
506                 if (dev->if_version < DRM_IF_VERSION(1, 2) &&
507                     ctl->irq != irq)
508                         return -EINVAL;
509                 mutex_lock(&dev->struct_mutex);
510                 ret = drm_irq_install(dev, irq);
511                 mutex_unlock(&dev->struct_mutex);
512
513                 return ret;
514         case DRM_UNINST_HANDLER:
515                 mutex_lock(&dev->struct_mutex);
516                 ret = drm_irq_uninstall(dev);
517                 mutex_unlock(&dev->struct_mutex);
518
519                 return ret;
520         default:
521                 return -EINVAL;
522         }
523 }
524
525 /**
526  * drm_calc_timestamping_constants - calculate vblank timestamp constants
527  * @crtc: drm_crtc whose timestamp constants should be updated.
528  * @mode: display mode containing the scanout timings
529  *
530  * Calculate and store various constants which are later
531  * needed by vblank and swap-completion timestamping, e.g,
532  * by drm_calc_vbltimestamp_from_scanoutpos(). They are
533  * derived from CRTC's true scanout timing, so they take
534  * things like panel scaling or other adjustments into account.
535  */
536 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
537                                      const struct drm_display_mode *mode)
538 {
539         int linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
540         int dotclock = mode->crtc_clock;
541
542         /* Valid dotclock? */
543         if (dotclock > 0) {
544                 int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
545
546                 /*
547                  * Convert scanline length in pixels and video
548                  * dot clock to line duration, frame duration
549                  * and pixel duration in nanoseconds:
550                  */
551                 pixeldur_ns = 1000000 / dotclock;
552                 linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
553                 framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
554
555                 /*
556                  * Fields of interlaced scanout modes are only half a frame duration.
557                  */
558                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
559                         framedur_ns /= 2;
560         } else
561                 DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
562                           crtc->base.id);
563
564         crtc->pixeldur_ns = pixeldur_ns;
565         crtc->linedur_ns  = linedur_ns;
566         crtc->framedur_ns = framedur_ns;
567
568         DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
569                   crtc->base.id, mode->crtc_htotal,
570                   mode->crtc_vtotal, mode->crtc_vdisplay);
571         DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
572                   crtc->base.id, dotclock, framedur_ns,
573                   linedur_ns, pixeldur_ns);
574 }
575 EXPORT_SYMBOL(drm_calc_timestamping_constants);
576
577 /**
578  * drm_calc_vbltimestamp_from_scanoutpos - precise vblank timestamp helper
579  * @dev: DRM device
580  * @crtc: Which CRTC's vblank timestamp to retrieve
581  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
582  *             On return contains true maximum error of timestamp
583  * @vblank_time: Pointer to struct timeval which should receive the timestamp
584  * @flags: Flags to pass to driver:
585  *         0 = Default,
586  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
587  * @refcrtc: CRTC which defines scanout timing
588  * @mode: mode which defines the scanout timings
589  *
590  * Implements calculation of exact vblank timestamps from given drm_display_mode
591  * timings and current video scanout position of a CRTC. This can be called from
592  * within get_vblank_timestamp() implementation of a kms driver to implement the
593  * actual timestamping.
594  *
595  * Should return timestamps conforming to the OML_sync_control OpenML
596  * extension specification. The timestamp corresponds to the end of
597  * the vblank interval, aka start of scanout of topmost-leftmost display
598  * pixel in the following video frame.
599  *
600  * Requires support for optional dev->driver->get_scanout_position()
601  * in kms driver, plus a bit of setup code to provide a drm_display_mode
602  * that corresponds to the true scanout timing.
603  *
604  * The current implementation only handles standard video modes. It
605  * returns as no operation if a doublescan or interlaced video mode is
606  * active. Higher level code is expected to handle this.
607  *
608  * Returns:
609  * Negative value on error, failure or if not supported in current
610  * video mode:
611  *
612  * -EINVAL   - Invalid CRTC.
613  * -EAGAIN   - Temporary unavailable, e.g., called before initial modeset.
614  * -ENOTSUPP - Function not supported in current display mode.
615  * -EIO      - Failed, e.g., due to failed scanout position query.
616  *
617  * Returns or'ed positive status flags on success:
618  *
619  * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
620  * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
621  *
622  */
623 int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
624                                           int *max_error,
625                                           struct timeval *vblank_time,
626                                           unsigned flags,
627                                           const struct drm_crtc *refcrtc,
628                                           const struct drm_display_mode *mode)
629 {
630         ktime_t stime, etime, mono_time_offset;
631         struct timeval tv_etime;
632         int vbl_status;
633         int vpos, hpos, i;
634         int framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
635         bool invbl;
636
637         if (crtc < 0 || crtc >= dev->num_crtcs) {
638                 DRM_ERROR("Invalid crtc %d\n", crtc);
639                 return -EINVAL;
640         }
641
642         /* Scanout position query not supported? Should not happen. */
643         if (!dev->driver->get_scanout_position) {
644                 DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
645                 return -EIO;
646         }
647
648         /* Durations of frames, lines, pixels in nanoseconds. */
649         framedur_ns = refcrtc->framedur_ns;
650         linedur_ns  = refcrtc->linedur_ns;
651         pixeldur_ns = refcrtc->pixeldur_ns;
652
653         /* If mode timing undefined, just return as no-op:
654          * Happens during initial modesetting of a crtc.
655          */
656         if (framedur_ns == 0) {
657                 DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
658                 return -EAGAIN;
659         }
660
661         /* Get current scanout position with system timestamp.
662          * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
663          * if single query takes longer than max_error nanoseconds.
664          *
665          * This guarantees a tight bound on maximum error if
666          * code gets preempted or delayed for some reason.
667          */
668         for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
669                 /*
670                  * Get vertical and horizontal scanout position vpos, hpos,
671                  * and bounding timestamps stime, etime, pre/post query.
672                  */
673                 vbl_status = dev->driver->get_scanout_position(dev, crtc, flags, &vpos,
674                                                                &hpos, &stime, &etime);
675
676                 /*
677                  * Get correction for CLOCK_MONOTONIC -> CLOCK_REALTIME if
678                  * CLOCK_REALTIME is requested.
679                  */
680                 if (!drm_timestamp_monotonic)
681                         mono_time_offset = ktime_get_monotonic_offset();
682
683                 /* Return as no-op if scanout query unsupported or failed. */
684                 if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
685                         DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
686                                   crtc, vbl_status);
687                         return -EIO;
688                 }
689
690                 /* Compute uncertainty in timestamp of scanout position query. */
691                 duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
692
693                 /* Accept result with <  max_error nsecs timing uncertainty. */
694                 if (duration_ns <= *max_error)
695                         break;
696         }
697
698         /* Noisy system timing? */
699         if (i == DRM_TIMESTAMP_MAXRETRIES) {
700                 DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
701                           crtc, duration_ns/1000, *max_error/1000, i);
702         }
703
704         /* Return upper bound of timestamp precision error. */
705         *max_error = duration_ns;
706
707         /* Check if in vblank area:
708          * vpos is >=0 in video scanout area, but negative
709          * within vblank area, counting down the number of lines until
710          * start of scanout.
711          */
712         invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
713
714         /* Convert scanout position into elapsed time at raw_time query
715          * since start of scanout at first display scanline. delta_ns
716          * can be negative if start of scanout hasn't happened yet.
717          */
718         delta_ns = vpos * linedur_ns + hpos * pixeldur_ns;
719
720         if (!drm_timestamp_monotonic)
721                 etime = ktime_sub(etime, mono_time_offset);
722
723         /* save this only for debugging purposes */
724         tv_etime = ktime_to_timeval(etime);
725         /* Subtract time delta from raw timestamp to get final
726          * vblank_time timestamp for end of vblank.
727          */
728         if (delta_ns < 0)
729                 etime = ktime_add_ns(etime, -delta_ns);
730         else
731                 etime = ktime_sub_ns(etime, delta_ns);
732         *vblank_time = ktime_to_timeval(etime);
733
734         DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
735                   crtc, (int)vbl_status, hpos, vpos,
736                   (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
737                   (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
738                   duration_ns/1000, i);
739
740         vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
741         if (invbl)
742                 vbl_status |= DRM_VBLANKTIME_INVBL;
743
744         return vbl_status;
745 }
746 EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
747
748 static struct timeval get_drm_timestamp(void)
749 {
750         ktime_t now;
751
752         now = ktime_get();
753         if (!drm_timestamp_monotonic)
754                 now = ktime_sub(now, ktime_get_monotonic_offset());
755
756         return ktime_to_timeval(now);
757 }
758
759 /**
760  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
761  *                             vblank interval
762  * @dev: DRM device
763  * @crtc: which CRTC's vblank timestamp to retrieve
764  * @tvblank: Pointer to target struct timeval which should receive the timestamp
765  * @flags: Flags to pass to driver:
766  *         0 = Default,
767  *         DRM_CALLED_FROM_VBLIRQ = If function is called from vbl IRQ handler
768  *
769  * Fetches the system timestamp corresponding to the time of the most recent
770  * vblank interval on specified CRTC. May call into kms-driver to
771  * compute the timestamp with a high-precision GPU specific method.
772  *
773  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
774  * call, i.e., it isn't very precisely locked to the true vblank.
775  *
776  * Returns:
777  * Non-zero if timestamp is considered to be very precise, zero otherwise.
778  */
779 u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
780                               struct timeval *tvblank, unsigned flags)
781 {
782         int ret;
783
784         /* Define requested maximum error on timestamps (nanoseconds). */
785         int max_error = (int) drm_timestamp_precision * 1000;
786
787         /* Query driver if possible and precision timestamping enabled. */
788         if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
789                 ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
790                                                         tvblank, flags);
791                 if (ret > 0)
792                         return (u32) ret;
793         }
794
795         /* GPU high precision timestamp query unsupported or failed.
796          * Return current monotonic/gettimeofday timestamp as best estimate.
797          */
798         *tvblank = get_drm_timestamp();
799
800         return 0;
801 }
802 EXPORT_SYMBOL(drm_get_last_vbltimestamp);
803
804 /**
805  * drm_vblank_count - retrieve "cooked" vblank counter value
806  * @dev: DRM device
807  * @crtc: which counter to retrieve
808  *
809  * Fetches the "cooked" vblank count value that represents the number of
810  * vblank events since the system was booted, including lost events due to
811  * modesetting activity.
812  *
813  * Returns:
814  * The software vblank counter.
815  */
816 u32 drm_vblank_count(struct drm_device *dev, int crtc)
817 {
818         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
819
820         return atomic_read(&vblank->count);
821 }
822 EXPORT_SYMBOL(drm_vblank_count);
823
824 /**
825  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
826  * and the system timestamp corresponding to that vblank counter value.
827  *
828  * @dev: DRM device
829  * @crtc: which counter to retrieve
830  * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
831  *
832  * Fetches the "cooked" vblank count value that represents the number of
833  * vblank events since the system was booted, including lost events due to
834  * modesetting activity. Returns corresponding system timestamp of the time
835  * of the vblank interval that corresponds to the current vblank counter value.
836  */
837 u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
838                               struct timeval *vblanktime)
839 {
840         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
841         u32 cur_vblank;
842
843         /* Read timestamp from slot of _vblank_time ringbuffer
844          * that corresponds to current vblank count. Retry if
845          * count has incremented during readout. This works like
846          * a seqlock.
847          */
848         do {
849                 cur_vblank = atomic_read(&vblank->count);
850                 *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
851                 smp_rmb();
852         } while (cur_vblank != atomic_read(&vblank->count));
853
854         return cur_vblank;
855 }
856 EXPORT_SYMBOL(drm_vblank_count_and_time);
857
858 static void send_vblank_event(struct drm_device *dev,
859                 struct drm_pending_vblank_event *e,
860                 unsigned long seq, struct timeval *now)
861 {
862         WARN_ON_SMP(!spin_is_locked(&dev->event_lock));
863         e->event.sequence = seq;
864         e->event.tv_sec = now->tv_sec;
865         e->event.tv_usec = now->tv_usec;
866
867         list_add_tail(&e->base.link,
868                       &e->base.file_priv->event_list);
869         wake_up_interruptible(&e->base.file_priv->event_wait);
870         trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
871                                          e->event.sequence);
872 }
873
874 /**
875  * drm_send_vblank_event - helper to send vblank event after pageflip
876  * @dev: DRM device
877  * @crtc: CRTC in question
878  * @e: the event to send
879  *
880  * Updates sequence # and timestamp on event, and sends it to userspace.
881  * Caller must hold event lock.
882  */
883 void drm_send_vblank_event(struct drm_device *dev, int crtc,
884                 struct drm_pending_vblank_event *e)
885 {
886         struct timeval now;
887         unsigned int seq;
888         if (crtc >= 0) {
889                 seq = drm_vblank_count_and_time(dev, crtc, &now);
890         } else {
891                 seq = 0;
892
893                 now = get_drm_timestamp();
894         }
895         e->pipe = crtc;
896         send_vblank_event(dev, e, seq, &now);
897 }
898 EXPORT_SYMBOL(drm_send_vblank_event);
899
900 /**
901  * drm_vblank_enable - enable the vblank interrupt on a CRTC
902  * @dev: DRM device
903  * @crtc: CRTC in question
904  */
905 static int drm_vblank_enable(struct drm_device *dev, int crtc)
906 {
907         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
908         int ret = 0;
909
910         assert_spin_locked(&dev->vbl_lock);
911
912         spin_lock(&dev->vblank_time_lock);
913
914         if (!vblank->enabled) {
915                 /*
916                  * Enable vblank irqs under vblank_time_lock protection.
917                  * All vblank count & timestamp updates are held off
918                  * until we are done reinitializing master counter and
919                  * timestamps. Filtercode in drm_handle_vblank() will
920                  * prevent double-accounting of same vblank interval.
921                  */
922                 ret = dev->driver->enable_vblank(dev, crtc);
923                 DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n", crtc, ret);
924                 if (ret)
925                         atomic_dec(&vblank->refcount);
926                 else {
927                         vblank->enabled = true;
928                         drm_update_vblank_count(dev, crtc);
929                 }
930         }
931
932         spin_unlock(&dev->vblank_time_lock);
933
934         return ret;
935 }
936
937 /**
938  * drm_vblank_get - get a reference count on vblank events
939  * @dev: DRM device
940  * @crtc: which CRTC to own
941  *
942  * Acquire a reference count on vblank events to avoid having them disabled
943  * while in use.
944  *
945  * This is the legacy version of drm_crtc_vblank_get().
946  *
947  * Returns:
948  * Zero on success, nonzero on failure.
949  */
950 int drm_vblank_get(struct drm_device *dev, int crtc)
951 {
952         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
953         unsigned long irqflags;
954         int ret = 0;
955
956         spin_lock_irqsave(&dev->vbl_lock, irqflags);
957         /* Going from 0->1 means we have to enable interrupts again */
958         if (atomic_add_return(1, &vblank->refcount) == 1) {
959                 ret = drm_vblank_enable(dev, crtc);
960         } else {
961                 if (!vblank->enabled) {
962                         atomic_dec(&vblank->refcount);
963                         ret = -EINVAL;
964                 }
965         }
966         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
967
968         return ret;
969 }
970 EXPORT_SYMBOL(drm_vblank_get);
971
972 /**
973  * drm_crtc_vblank_get - get a reference count on vblank events
974  * @crtc: which CRTC to own
975  *
976  * Acquire a reference count on vblank events to avoid having them disabled
977  * while in use.
978  *
979  * This is the native kms version of drm_vblank_off().
980  *
981  * Returns:
982  * Zero on success, nonzero on failure.
983  */
984 int drm_crtc_vblank_get(struct drm_crtc *crtc)
985 {
986         return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
987 }
988 EXPORT_SYMBOL(drm_crtc_vblank_get);
989
990 /**
991  * drm_vblank_put - give up ownership of vblank events
992  * @dev: DRM device
993  * @crtc: which counter to give up
994  *
995  * Release ownership of a given vblank counter, turning off interrupts
996  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
997  *
998  * This is the legacy version of drm_crtc_vblank_put().
999  */
1000 void drm_vblank_put(struct drm_device *dev, int crtc)
1001 {
1002         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1003
1004         BUG_ON(atomic_read(&vblank->refcount) == 0);
1005
1006         /* Last user schedules interrupt disable */
1007         if (atomic_dec_and_test(&vblank->refcount)) {
1008                 if (drm_vblank_offdelay == 0)
1009                         return;
1010                 else if (dev->vblank_disable_immediate || drm_vblank_offdelay < 0)
1011                         vblank_disable_fn((unsigned long)vblank);
1012                 else
1013                         mod_timer(&vblank->disable_timer,
1014                                   jiffies + ((drm_vblank_offdelay * HZ)/1000));
1015         }
1016 }
1017 EXPORT_SYMBOL(drm_vblank_put);
1018
1019 /**
1020  * drm_crtc_vblank_put - give up ownership of vblank events
1021  * @crtc: which counter to give up
1022  *
1023  * Release ownership of a given vblank counter, turning off interrupts
1024  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1025  *
1026  * This is the native kms version of drm_vblank_put().
1027  */
1028 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1029 {
1030         drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1031 }
1032 EXPORT_SYMBOL(drm_crtc_vblank_put);
1033
1034 /**
1035  * drm_vblank_off - disable vblank events on a CRTC
1036  * @dev: DRM device
1037  * @crtc: CRTC in question
1038  *
1039  * Drivers can use this function to shut down the vblank interrupt handling when
1040  * disabling a crtc. This function ensures that the latest vblank frame count is
1041  * stored so that drm_vblank_on() can restore it again.
1042  *
1043  * Drivers must use this function when the hardware vblank counter can get
1044  * reset, e.g. when suspending.
1045  *
1046  * This is the legacy version of drm_crtc_vblank_off().
1047  */
1048 void drm_vblank_off(struct drm_device *dev, int crtc)
1049 {
1050         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1051         struct drm_pending_vblank_event *e, *t;
1052         struct timeval now;
1053         unsigned long irqflags;
1054         unsigned int seq;
1055
1056         spin_lock_irqsave(&dev->event_lock, irqflags);
1057
1058         spin_lock(&dev->vbl_lock);
1059         vblank_disable_and_save(dev, crtc);
1060         wake_up(&vblank->queue);
1061
1062         /*
1063          * Prevent subsequent drm_vblank_get() from re-enabling
1064          * the vblank interrupt by bumping the refcount.
1065          */
1066         if (!vblank->inmodeset) {
1067                 atomic_inc(&vblank->refcount);
1068                 vblank->inmodeset = 1;
1069         }
1070         spin_unlock(&dev->vbl_lock);
1071
1072         /* Send any queued vblank events, lest the natives grow disquiet */
1073         seq = drm_vblank_count_and_time(dev, crtc, &now);
1074
1075         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1076                 if (e->pipe != crtc)
1077                         continue;
1078                 DRM_DEBUG("Sending premature vblank event on disable: \
1079                           wanted %d, current %d\n",
1080                           e->event.sequence, seq);
1081                 list_del(&e->base.link);
1082                 drm_vblank_put(dev, e->pipe);
1083                 send_vblank_event(dev, e, seq, &now);
1084         }
1085         spin_unlock_irqrestore(&dev->event_lock, irqflags);
1086 }
1087 EXPORT_SYMBOL(drm_vblank_off);
1088
1089 /**
1090  * drm_crtc_vblank_off - disable vblank events on a CRTC
1091  * @crtc: CRTC in question
1092  *
1093  * Drivers can use this function to shut down the vblank interrupt handling when
1094  * disabling a crtc. This function ensures that the latest vblank frame count is
1095  * stored so that drm_vblank_on can restore it again.
1096  *
1097  * Drivers must use this function when the hardware vblank counter can get
1098  * reset, e.g. when suspending.
1099  *
1100  * This is the native kms version of drm_vblank_off().
1101  */
1102 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1103 {
1104         drm_vblank_off(crtc->dev, drm_crtc_index(crtc));
1105 }
1106 EXPORT_SYMBOL(drm_crtc_vblank_off);
1107
1108 /**
1109  * drm_vblank_on - enable vblank events on a CRTC
1110  * @dev: DRM device
1111  * @crtc: CRTC in question
1112  *
1113  * This functions restores the vblank interrupt state captured with
1114  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1115  * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1116  * in driver load code to reflect the current hardware state of the crtc.
1117  *
1118  * This is the legacy version of drm_crtc_vblank_on().
1119  */
1120 void drm_vblank_on(struct drm_device *dev, int crtc)
1121 {
1122         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1123         unsigned long irqflags;
1124
1125         spin_lock_irqsave(&dev->vbl_lock, irqflags);
1126         /* Drop our private "prevent drm_vblank_get" refcount */
1127         if (vblank->inmodeset) {
1128                 atomic_dec(&vblank->refcount);
1129                 vblank->inmodeset = 0;
1130         }
1131
1132         /*
1133          * sample the current counter to avoid random jumps
1134          * when drm_vblank_enable() applies the diff
1135          *
1136          * -1 to make sure user will never see the same
1137          * vblank counter value before and after a modeset
1138          */
1139         vblank->last =
1140                 (dev->driver->get_vblank_counter(dev, crtc) - 1) &
1141                 dev->max_vblank_count;
1142         /*
1143          * re-enable interrupts if there are users left, or the
1144          * user wishes vblank interrupts to be enabled all the time.
1145          */
1146         if (atomic_read(&vblank->refcount) != 0 ||
1147             (!dev->vblank_disable_immediate && drm_vblank_offdelay == 0))
1148                 WARN_ON(drm_vblank_enable(dev, crtc));
1149         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1150 }
1151 EXPORT_SYMBOL(drm_vblank_on);
1152
1153 /**
1154  * drm_crtc_vblank_on - enable vblank events on a CRTC
1155  * @crtc: CRTC in question
1156  *
1157  * This functions restores the vblank interrupt state captured with
1158  * drm_vblank_off() again. Note that calls to drm_vblank_on() and
1159  * drm_vblank_off() can be unbalanced and so can also be unconditionaly called
1160  * in driver load code to reflect the current hardware state of the crtc.
1161  *
1162  * This is the native kms version of drm_vblank_on().
1163  */
1164 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1165 {
1166         drm_vblank_on(crtc->dev, drm_crtc_index(crtc));
1167 }
1168 EXPORT_SYMBOL(drm_crtc_vblank_on);
1169
1170 /**
1171  * drm_vblank_pre_modeset - account for vblanks across mode sets
1172  * @dev: DRM device
1173  * @crtc: CRTC in question
1174  *
1175  * Account for vblank events across mode setting events, which will likely
1176  * reset the hardware frame counter.
1177  *
1178  * This is done by grabbing a temporary vblank reference to ensure that the
1179  * vblank interrupt keeps running across the modeset sequence. With this the
1180  * software-side vblank frame counting will ensure that there are no jumps or
1181  * discontinuities.
1182  *
1183  * Unfortunately this approach is racy and also doesn't work when the vblank
1184  * interrupt stops running, e.g. across system suspend resume. It is therefore
1185  * highly recommended that drivers use the newer drm_vblank_off() and
1186  * drm_vblank_on() instead. drm_vblank_pre_modeset() only works correctly when
1187  * using "cooked" software vblank frame counters and not relying on any hardware
1188  * counters.
1189  *
1190  * Drivers must call drm_vblank_post_modeset() when re-enabling the same crtc
1191  * again.
1192  */
1193 void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
1194 {
1195         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1196
1197         /* vblank is not initialized (IRQ not installed ?), or has been freed */
1198         if (!dev->num_crtcs)
1199                 return;
1200         /*
1201          * To avoid all the problems that might happen if interrupts
1202          * were enabled/disabled around or between these calls, we just
1203          * have the kernel take a reference on the CRTC (just once though
1204          * to avoid corrupting the count if multiple, mismatch calls occur),
1205          * so that interrupts remain enabled in the interim.
1206          */
1207         if (!vblank->inmodeset) {
1208                 vblank->inmodeset = 0x1;
1209                 if (drm_vblank_get(dev, crtc) == 0)
1210                         vblank->inmodeset |= 0x2;
1211         }
1212 }
1213 EXPORT_SYMBOL(drm_vblank_pre_modeset);
1214
1215 /**
1216  * drm_vblank_post_modeset - undo drm_vblank_pre_modeset changes
1217  * @dev: DRM device
1218  * @crtc: CRTC in question
1219  *
1220  * This function again drops the temporary vblank reference acquired in
1221  * drm_vblank_pre_modeset.
1222  */
1223 void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
1224 {
1225         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1226         unsigned long irqflags;
1227
1228         /* vblank is not initialized (IRQ not installed ?), or has been freed */
1229         if (!dev->num_crtcs)
1230                 return;
1231
1232         if (vblank->inmodeset) {
1233                 spin_lock_irqsave(&dev->vbl_lock, irqflags);
1234                 dev->vblank_disable_allowed = true;
1235                 spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1236
1237                 if (vblank->inmodeset & 0x2)
1238                         drm_vblank_put(dev, crtc);
1239
1240                 vblank->inmodeset = 0;
1241         }
1242 }
1243 EXPORT_SYMBOL(drm_vblank_post_modeset);
1244
1245 /*
1246  * drm_modeset_ctl - handle vblank event counter changes across mode switch
1247  * @DRM_IOCTL_ARGS: standard ioctl arguments
1248  *
1249  * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
1250  * ioctls around modesetting so that any lost vblank events are accounted for.
1251  *
1252  * Generally the counter will reset across mode sets.  If interrupts are
1253  * enabled around this call, we don't have to do anything since the counter
1254  * will have already been incremented.
1255  */
1256 int drm_modeset_ctl(struct drm_device *dev, void *data,
1257                     struct drm_file *file_priv)
1258 {
1259         struct drm_modeset_ctl *modeset = data;
1260         unsigned int crtc;
1261
1262         /* If drm_vblank_init() hasn't been called yet, just no-op */
1263         if (!dev->num_crtcs)
1264                 return 0;
1265
1266         /* KMS drivers handle this internally */
1267         if (drm_core_check_feature(dev, DRIVER_MODESET))
1268                 return 0;
1269
1270         crtc = modeset->crtc;
1271         if (crtc >= dev->num_crtcs)
1272                 return -EINVAL;
1273
1274         switch (modeset->cmd) {
1275         case _DRM_PRE_MODESET:
1276                 drm_vblank_pre_modeset(dev, crtc);
1277                 break;
1278         case _DRM_POST_MODESET:
1279                 drm_vblank_post_modeset(dev, crtc);
1280                 break;
1281         default:
1282                 return -EINVAL;
1283         }
1284
1285         return 0;
1286 }
1287
1288 static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
1289                                   union drm_wait_vblank *vblwait,
1290                                   struct drm_file *file_priv)
1291 {
1292         struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1293         struct drm_pending_vblank_event *e;
1294         struct timeval now;
1295         unsigned long flags;
1296         unsigned int seq;
1297         int ret;
1298
1299         e = kzalloc(sizeof *e, GFP_KERNEL);
1300         if (e == NULL) {
1301                 ret = -ENOMEM;
1302                 goto err_put;
1303         }
1304
1305         e->pipe = pipe;
1306         e->base.pid = current->pid;
1307         e->event.base.type = DRM_EVENT_VBLANK;
1308         e->event.base.length = sizeof e->event;
1309         e->event.user_data = vblwait->request.signal;
1310         e->base.event = &e->event.base;
1311         e->base.file_priv = file_priv;
1312         e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
1313
1314         spin_lock_irqsave(&dev->event_lock, flags);
1315
1316         /*
1317          * drm_vblank_off() might have been called after we called
1318          * drm_vblank_get(). drm_vblank_off() holds event_lock
1319          * around the vblank disable, so no need for further locking.
1320          * The reference from drm_vblank_get() protects against
1321          * vblank disable from another source.
1322          */
1323         if (!vblank->enabled) {
1324                 ret = -EINVAL;
1325                 goto err_unlock;
1326         }
1327
1328         if (file_priv->event_space < sizeof e->event) {
1329                 ret = -EBUSY;
1330                 goto err_unlock;
1331         }
1332
1333         file_priv->event_space -= sizeof e->event;
1334         seq = drm_vblank_count_and_time(dev, pipe, &now);
1335
1336         if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
1337             (seq - vblwait->request.sequence) <= (1 << 23)) {
1338                 vblwait->request.sequence = seq + 1;
1339                 vblwait->reply.sequence = vblwait->request.sequence;
1340         }
1341
1342         DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
1343                   vblwait->request.sequence, seq, pipe);
1344
1345         trace_drm_vblank_event_queued(current->pid, pipe,
1346                                       vblwait->request.sequence);
1347
1348         e->event.sequence = vblwait->request.sequence;
1349         if ((seq - vblwait->request.sequence) <= (1 << 23)) {
1350                 drm_vblank_put(dev, pipe);
1351                 send_vblank_event(dev, e, seq, &now);
1352                 vblwait->reply.sequence = seq;
1353         } else {
1354                 /* drm_handle_vblank_events will call drm_vblank_put */
1355                 list_add_tail(&e->base.link, &dev->vblank_event_list);
1356                 vblwait->reply.sequence = vblwait->request.sequence;
1357         }
1358
1359         spin_unlock_irqrestore(&dev->event_lock, flags);
1360
1361         return 0;
1362
1363 err_unlock:
1364         spin_unlock_irqrestore(&dev->event_lock, flags);
1365         kfree(e);
1366 err_put:
1367         drm_vblank_put(dev, pipe);
1368         return ret;
1369 }
1370
1371 /*
1372  * Wait for VBLANK.
1373  *
1374  * \param inode device inode.
1375  * \param file_priv DRM file private.
1376  * \param cmd command.
1377  * \param data user argument, pointing to a drm_wait_vblank structure.
1378  * \return zero on success or a negative number on failure.
1379  *
1380  * This function enables the vblank interrupt on the pipe requested, then
1381  * sleeps waiting for the requested sequence number to occur, and drops
1382  * the vblank interrupt refcount afterwards. (vblank IRQ disable follows that
1383  * after a timeout with no further vblank waits scheduled).
1384  */
1385 int drm_wait_vblank(struct drm_device *dev, void *data,
1386                     struct drm_file *file_priv)
1387 {
1388         struct drm_vblank_crtc *vblank;
1389         union drm_wait_vblank *vblwait = data;
1390         int ret;
1391         unsigned int flags, seq, crtc, high_crtc;
1392
1393         if (!dev->irq_enabled)
1394                 return -EINVAL;
1395
1396         if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1397                 return -EINVAL;
1398
1399         if (vblwait->request.type &
1400             ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1401               _DRM_VBLANK_HIGH_CRTC_MASK)) {
1402                 DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
1403                           vblwait->request.type,
1404                           (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1405                            _DRM_VBLANK_HIGH_CRTC_MASK));
1406                 return -EINVAL;
1407         }
1408
1409         flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1410         high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1411         if (high_crtc)
1412                 crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1413         else
1414                 crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1415         if (crtc >= dev->num_crtcs)
1416                 return -EINVAL;
1417
1418         vblank = &dev->vblank[crtc];
1419
1420         ret = drm_vblank_get(dev, crtc);
1421         if (ret) {
1422                 DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
1423                 return ret;
1424         }
1425         seq = drm_vblank_count(dev, crtc);
1426
1427         switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1428         case _DRM_VBLANK_RELATIVE:
1429                 vblwait->request.sequence += seq;
1430                 vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1431         case _DRM_VBLANK_ABSOLUTE:
1432                 break;
1433         default:
1434                 ret = -EINVAL;
1435                 goto done;
1436         }
1437
1438         if (flags & _DRM_VBLANK_EVENT) {
1439                 /* must hold on to the vblank ref until the event fires
1440                  * drm_vblank_put will be called asynchronously
1441                  */
1442                 return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
1443         }
1444
1445         if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1446             (seq - vblwait->request.sequence) <= (1<<23)) {
1447                 vblwait->request.sequence = seq + 1;
1448         }
1449
1450         DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
1451                   vblwait->request.sequence, crtc);
1452         vblank->last_wait = vblwait->request.sequence;
1453         DRM_WAIT_ON(ret, vblank->queue, 3 * HZ,
1454                     (((drm_vblank_count(dev, crtc) -
1455                        vblwait->request.sequence) <= (1 << 23)) ||
1456                      !vblank->enabled ||
1457                      !dev->irq_enabled));
1458
1459         if (ret != -EINTR) {
1460                 struct timeval now;
1461
1462                 vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
1463                 vblwait->reply.tval_sec = now.tv_sec;
1464                 vblwait->reply.tval_usec = now.tv_usec;
1465
1466                 DRM_DEBUG("returning %d to client\n",
1467                           vblwait->reply.sequence);
1468         } else {
1469                 DRM_DEBUG("vblank wait interrupted by signal\n");
1470         }
1471
1472 done:
1473         drm_vblank_put(dev, crtc);
1474         return ret;
1475 }
1476
1477 static void drm_handle_vblank_events(struct drm_device *dev, int crtc)
1478 {
1479         struct drm_pending_vblank_event *e, *t;
1480         struct timeval now;
1481         unsigned int seq;
1482
1483         assert_spin_locked(&dev->event_lock);
1484
1485         seq = drm_vblank_count_and_time(dev, crtc, &now);
1486
1487         list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1488                 if (e->pipe != crtc)
1489                         continue;
1490                 if ((seq - e->event.sequence) > (1<<23))
1491                         continue;
1492
1493                 DRM_DEBUG("vblank event on %d, current %d\n",
1494                           e->event.sequence, seq);
1495
1496                 list_del(&e->base.link);
1497                 drm_vblank_put(dev, e->pipe);
1498                 send_vblank_event(dev, e, seq, &now);
1499         }
1500
1501         trace_drm_vblank_event(crtc, seq);
1502 }
1503
1504 /**
1505  * drm_handle_vblank - handle a vblank event
1506  * @dev: DRM device
1507  * @crtc: where this event occurred
1508  *
1509  * Drivers should call this routine in their vblank interrupt handlers to
1510  * update the vblank counter and send any signals that may be pending.
1511  */
1512 bool drm_handle_vblank(struct drm_device *dev, int crtc)
1513 {
1514         struct drm_vblank_crtc *vblank = &dev->vblank[crtc];
1515         u32 vblcount;
1516         s64 diff_ns;
1517         struct timeval tvblank;
1518         unsigned long irqflags;
1519
1520         if (!dev->num_crtcs)
1521                 return false;
1522
1523         spin_lock_irqsave(&dev->event_lock, irqflags);
1524
1525         /* Need timestamp lock to prevent concurrent execution with
1526          * vblank enable/disable, as this would cause inconsistent
1527          * or corrupted timestamps and vblank counts.
1528          */
1529         spin_lock(&dev->vblank_time_lock);
1530
1531         /* Vblank irq handling disabled. Nothing to do. */
1532         if (!vblank->enabled) {
1533                 spin_unlock(&dev->vblank_time_lock);
1534                 spin_unlock_irqrestore(&dev->event_lock, irqflags);
1535                 return false;
1536         }
1537
1538         /* Fetch corresponding timestamp for this vblank interval from
1539          * driver and store it in proper slot of timestamp ringbuffer.
1540          */
1541
1542         /* Get current timestamp and count. */
1543         vblcount = atomic_read(&vblank->count);
1544         drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
1545
1546         /* Compute time difference to timestamp of last vblank */
1547         diff_ns = timeval_to_ns(&tvblank) -
1548                   timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
1549
1550         /* Update vblank timestamp and count if at least
1551          * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
1552          * difference between last stored timestamp and current
1553          * timestamp. A smaller difference means basically
1554          * identical timestamps. Happens if this vblank has
1555          * been already processed and this is a redundant call,
1556          * e.g., due to spurious vblank interrupts. We need to
1557          * ignore those for accounting.
1558          */
1559         if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
1560                 /* Store new timestamp in ringbuffer. */
1561                 vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
1562
1563                 /* Increment cooked vblank count. This also atomically commits
1564                  * the timestamp computed above.
1565                  */
1566                 smp_mb__before_atomic();
1567                 atomic_inc(&vblank->count);
1568                 smp_mb__after_atomic();
1569         } else {
1570                 DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
1571                           crtc, (int) diff_ns);
1572         }
1573
1574         spin_unlock(&dev->vblank_time_lock);
1575
1576         wake_up(&vblank->queue);
1577         drm_handle_vblank_events(dev, crtc);
1578
1579         spin_unlock_irqrestore(&dev->event_lock, irqflags);
1580
1581         return true;
1582 }
1583 EXPORT_SYMBOL(drm_handle_vblank);