Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * drm_irq.c IRQ and vblank support
0003  *
0004  * \author Rickard E. (Rik) Faith <faith@valinux.com>
0005  * \author Gareth Hughes <gareth@valinux.com>
0006  *
0007  * Permission is hereby granted, free of charge, to any person obtaining a
0008  * copy of this software and associated documentation files (the "Software"),
0009  * to deal in the Software without restriction, including without limitation
0010  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
0011  * and/or sell copies of the Software, and to permit persons to whom the
0012  * Software is furnished to do so, subject to the following conditions:
0013  *
0014  * The above copyright notice and this permission notice (including the next
0015  * paragraph) shall be included in all copies or substantial portions of the
0016  * Software.
0017  *
0018  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0019  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0020  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
0021  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
0022  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
0023  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
0024  * OTHER DEALINGS IN THE SOFTWARE.
0025  */
0026 
0027 #include <linux/export.h>
0028 #include <linux/kthread.h>
0029 #include <linux/moduleparam.h>
0030 
0031 #include <drm/drm_crtc.h>
0032 #include <drm/drm_drv.h>
0033 #include <drm/drm_framebuffer.h>
0034 #include <drm/drm_managed.h>
0035 #include <drm/drm_modeset_helper_vtables.h>
0036 #include <drm/drm_print.h>
0037 #include <drm/drm_vblank.h>
0038 
0039 #include "drm_internal.h"
0040 #include "drm_trace.h"
0041 
0042 /**
0043  * DOC: vblank handling
0044  *
0045  * From the computer's perspective, every time the monitor displays
0046  * a new frame the scanout engine has "scanned out" the display image
0047  * from top to bottom, one row of pixels at a time. The current row
0048  * of pixels is referred to as the current scanline.
0049  *
0050  * In addition to the display's visible area, there's usually a couple of
0051  * extra scanlines which aren't actually displayed on the screen.
0052  * These extra scanlines don't contain image data and are occasionally used
0053  * for features like audio and infoframes. The region made up of these
0054  * scanlines is referred to as the vertical blanking region, or vblank for
0055  * short.
0056  *
0057  * For historical reference, the vertical blanking period was designed to
0058  * give the electron gun (on CRTs) enough time to move back to the top of
0059  * the screen to start scanning out the next frame. Similar for horizontal
0060  * blanking periods. They were designed to give the electron gun enough
0061  * time to move back to the other side of the screen to start scanning the
0062  * next scanline.
0063  *
0064  * ::
0065  *
0066  *
0067  *    physical →   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
0068  *    top of      |                                        |
0069  *    display     |                                        |
0070  *                |               New frame                |
0071  *                |                                        |
0072  *                |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓|
0073  *                |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| ← Scanline,
0074  *                |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓|   updates the
0075  *                |                                        |   frame as it
0076  *                |                                        |   travels down
0077  *                |                                        |   ("scan out")
0078  *                |               Old frame                |
0079  *                |                                        |
0080  *                |                                        |
0081  *                |                                        |
0082  *                |                                        |   physical
0083  *                |                                        |   bottom of
0084  *    vertical    |⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽| ← display
0085  *    blanking    ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
0086  *    region   →  ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
0087  *                ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
0088  *    start of →   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
0089  *    new frame
0090  *
0091  * "Physical top of display" is the reference point for the high-precision/
0092  * corrected timestamp.
0093  *
0094  * On a lot of display hardware, programming needs to take effect during the
0095  * vertical blanking period so that settings like gamma, the image buffer
0096  * buffer to be scanned out, etc. can safely be changed without showing
0097  * any visual artifacts on the screen. In some unforgiving hardware, some of
0098  * this programming has to both start and end in the same vblank. To help
0099  * with the timing of the hardware programming, an interrupt is usually
0100  * available to notify the driver when it can start the updating of registers.
0101  * The interrupt is in this context named the vblank interrupt.
0102  *
0103  * The vblank interrupt may be fired at different points depending on the
0104  * hardware. Some hardware implementations will fire the interrupt when the
0105  * new frame start, other implementations will fire the interrupt at different
0106  * points in time.
0107  *
0108  * Vertical blanking plays a major role in graphics rendering. To achieve
0109  * tear-free display, users must synchronize page flips and/or rendering to
0110  * vertical blanking. The DRM API offers ioctls to perform page flips
0111  * synchronized to vertical blanking and wait for vertical blanking.
0112  *
0113  * The DRM core handles most of the vertical blanking management logic, which
0114  * involves filtering out spurious interrupts, keeping race-free blanking
0115  * counters, coping with counter wrap-around and resets and keeping use counts.
0116  * It relies on the driver to generate vertical blanking interrupts and
0117  * optionally provide a hardware vertical blanking counter.
0118  *
0119  * Drivers must initialize the vertical blanking handling core with a call to
0120  * drm_vblank_init(). Minimally, a driver needs to implement
0121  * &drm_crtc_funcs.enable_vblank and &drm_crtc_funcs.disable_vblank plus call
0122  * drm_crtc_handle_vblank() in its vblank interrupt handler for working vblank
0123  * support.
0124  *
0125  * Vertical blanking interrupts can be enabled by the DRM core or by drivers
0126  * themselves (for instance to handle page flipping operations).  The DRM core
0127  * maintains a vertical blanking use count to ensure that the interrupts are not
0128  * disabled while a user still needs them. To increment the use count, drivers
0129  * call drm_crtc_vblank_get() and release the vblank reference again with
0130  * drm_crtc_vblank_put(). In between these two calls vblank interrupts are
0131  * guaranteed to be enabled.
0132  *
0133  * On many hardware disabling the vblank interrupt cannot be done in a race-free
0134  * manner, see &drm_driver.vblank_disable_immediate and
0135  * &drm_driver.max_vblank_count. In that case the vblank core only disables the
0136  * vblanks after a timer has expired, which can be configured through the
0137  * ``vblankoffdelay`` module parameter.
0138  *
0139  * Drivers for hardware without support for vertical-blanking interrupts
0140  * must not call drm_vblank_init(). For such drivers, atomic helpers will
0141  * automatically generate fake vblank events as part of the display update.
0142  * This functionality also can be controlled by the driver by enabling and
0143  * disabling struct drm_crtc_state.no_vblank.
0144  */
0145 
0146 /* Retry timestamp calculation up to 3 times to satisfy
0147  * drm_timestamp_precision before giving up.
0148  */
0149 #define DRM_TIMESTAMP_MAXRETRIES 3
0150 
0151 /* Threshold in nanoseconds for detection of redundant
0152  * vblank irq in drm_handle_vblank(). 1 msec should be ok.
0153  */
0154 #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
0155 
0156 static bool
0157 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
0158               ktime_t *tvblank, bool in_vblank_irq);
0159 
0160 static unsigned int drm_timestamp_precision = 20;  /* Default to 20 usecs. */
0161 
0162 static int drm_vblank_offdelay = 5000;    /* Default to 5000 msecs. */
0163 
0164 module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
0165 module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
0166 MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
0167 MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
0168 
0169 static void store_vblank(struct drm_device *dev, unsigned int pipe,
0170              u32 vblank_count_inc,
0171              ktime_t t_vblank, u32 last)
0172 {
0173     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0174 
0175     assert_spin_locked(&dev->vblank_time_lock);
0176 
0177     vblank->last = last;
0178 
0179     write_seqlock(&vblank->seqlock);
0180     vblank->time = t_vblank;
0181     atomic64_add(vblank_count_inc, &vblank->count);
0182     write_sequnlock(&vblank->seqlock);
0183 }
0184 
0185 static u32 drm_max_vblank_count(struct drm_device *dev, unsigned int pipe)
0186 {
0187     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0188 
0189     return vblank->max_vblank_count ?: dev->max_vblank_count;
0190 }
0191 
0192 /*
0193  * "No hw counter" fallback implementation of .get_vblank_counter() hook,
0194  * if there is no usable hardware frame counter available.
0195  */
0196 static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
0197 {
0198     drm_WARN_ON_ONCE(dev, drm_max_vblank_count(dev, pipe) != 0);
0199     return 0;
0200 }
0201 
0202 static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
0203 {
0204     if (drm_core_check_feature(dev, DRIVER_MODESET)) {
0205         struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
0206 
0207         if (drm_WARN_ON(dev, !crtc))
0208             return 0;
0209 
0210         if (crtc->funcs->get_vblank_counter)
0211             return crtc->funcs->get_vblank_counter(crtc);
0212     }
0213 #ifdef CONFIG_DRM_LEGACY
0214     else if (dev->driver->get_vblank_counter) {
0215         return dev->driver->get_vblank_counter(dev, pipe);
0216     }
0217 #endif
0218 
0219     return drm_vblank_no_hw_counter(dev, pipe);
0220 }
0221 
0222 /*
0223  * Reset the stored timestamp for the current vblank count to correspond
0224  * to the last vblank occurred.
0225  *
0226  * Only to be called from drm_crtc_vblank_on().
0227  *
0228  * Note: caller must hold &drm_device.vbl_lock since this reads & writes
0229  * device vblank fields.
0230  */
0231 static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
0232 {
0233     u32 cur_vblank;
0234     bool rc;
0235     ktime_t t_vblank;
0236     int count = DRM_TIMESTAMP_MAXRETRIES;
0237 
0238     spin_lock(&dev->vblank_time_lock);
0239 
0240     /*
0241      * sample the current counter to avoid random jumps
0242      * when drm_vblank_enable() applies the diff
0243      */
0244     do {
0245         cur_vblank = __get_vblank_counter(dev, pipe);
0246         rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
0247     } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
0248 
0249     /*
0250      * Only reinitialize corresponding vblank timestamp if high-precision query
0251      * available and didn't fail. Otherwise reinitialize delayed at next vblank
0252      * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
0253      */
0254     if (!rc)
0255         t_vblank = 0;
0256 
0257     /*
0258      * +1 to make sure user will never see the same
0259      * vblank counter value before and after a modeset
0260      */
0261     store_vblank(dev, pipe, 1, t_vblank, cur_vblank);
0262 
0263     spin_unlock(&dev->vblank_time_lock);
0264 }
0265 
0266 /*
0267  * Call back into the driver to update the appropriate vblank counter
0268  * (specified by @pipe).  Deal with wraparound, if it occurred, and
0269  * update the last read value so we can deal with wraparound on the next
0270  * call if necessary.
0271  *
0272  * Only necessary when going from off->on, to account for frames we
0273  * didn't get an interrupt for.
0274  *
0275  * Note: caller must hold &drm_device.vbl_lock since this reads & writes
0276  * device vblank fields.
0277  */
0278 static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
0279                     bool in_vblank_irq)
0280 {
0281     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0282     u32 cur_vblank, diff;
0283     bool rc;
0284     ktime_t t_vblank;
0285     int count = DRM_TIMESTAMP_MAXRETRIES;
0286     int framedur_ns = vblank->framedur_ns;
0287     u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
0288 
0289     /*
0290      * Interrupts were disabled prior to this call, so deal with counter
0291      * wrap if needed.
0292      * NOTE!  It's possible we lost a full dev->max_vblank_count + 1 events
0293      * here if the register is small or we had vblank interrupts off for
0294      * a long time.
0295      *
0296      * We repeat the hardware vblank counter & timestamp query until
0297      * we get consistent results. This to prevent races between gpu
0298      * updating its hardware counter while we are retrieving the
0299      * corresponding vblank timestamp.
0300      */
0301     do {
0302         cur_vblank = __get_vblank_counter(dev, pipe);
0303         rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, in_vblank_irq);
0304     } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
0305 
0306     if (max_vblank_count) {
0307         /* trust the hw counter when it's around */
0308         diff = (cur_vblank - vblank->last) & max_vblank_count;
0309     } else if (rc && framedur_ns) {
0310         u64 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
0311 
0312         /*
0313          * Figure out how many vblanks we've missed based
0314          * on the difference in the timestamps and the
0315          * frame/field duration.
0316          */
0317 
0318         drm_dbg_vbl(dev, "crtc %u: Calculating number of vblanks."
0319                 " diff_ns = %lld, framedur_ns = %d)\n",
0320                 pipe, (long long)diff_ns, framedur_ns);
0321 
0322         diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
0323 
0324         if (diff == 0 && in_vblank_irq)
0325             drm_dbg_vbl(dev, "crtc %u: Redundant vblirq ignored\n",
0326                     pipe);
0327     } else {
0328         /* some kind of default for drivers w/o accurate vbl timestamping */
0329         diff = in_vblank_irq ? 1 : 0;
0330     }
0331 
0332     /*
0333      * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
0334      * interval? If so then vblank irqs keep running and it will likely
0335      * happen that the hardware vblank counter is not trustworthy as it
0336      * might reset at some point in that interval and vblank timestamps
0337      * are not trustworthy either in that interval. Iow. this can result
0338      * in a bogus diff >> 1 which must be avoided as it would cause
0339      * random large forward jumps of the software vblank counter.
0340      */
0341     if (diff > 1 && (vblank->inmodeset & 0x2)) {
0342         drm_dbg_vbl(dev,
0343                 "clamping vblank bump to 1 on crtc %u: diffr=%u"
0344                 " due to pre-modeset.\n", pipe, diff);
0345         diff = 1;
0346     }
0347 
0348     drm_dbg_vbl(dev, "updating vblank count on crtc %u:"
0349             " current=%llu, diff=%u, hw=%u hw_last=%u\n",
0350             pipe, (unsigned long long)atomic64_read(&vblank->count),
0351             diff, cur_vblank, vblank->last);
0352 
0353     if (diff == 0) {
0354         drm_WARN_ON_ONCE(dev, cur_vblank != vblank->last);
0355         return;
0356     }
0357 
0358     /*
0359      * Only reinitialize corresponding vblank timestamp if high-precision query
0360      * available and didn't fail, or we were called from the vblank interrupt.
0361      * Otherwise reinitialize delayed at next vblank interrupt and assign 0
0362      * for now, to mark the vblanktimestamp as invalid.
0363      */
0364     if (!rc && !in_vblank_irq)
0365         t_vblank = 0;
0366 
0367     store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
0368 }
0369 
0370 u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
0371 {
0372     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0373     u64 count;
0374 
0375     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
0376         return 0;
0377 
0378     count = atomic64_read(&vblank->count);
0379 
0380     /*
0381      * This read barrier corresponds to the implicit write barrier of the
0382      * write seqlock in store_vblank(). Note that this is the only place
0383      * where we need an explicit barrier, since all other access goes
0384      * through drm_vblank_count_and_time(), which already has the required
0385      * read barrier curtesy of the read seqlock.
0386      */
0387     smp_rmb();
0388 
0389     return count;
0390 }
0391 
0392 /**
0393  * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
0394  * @crtc: which counter to retrieve
0395  *
0396  * This function is similar to drm_crtc_vblank_count() but this function
0397  * interpolates to handle a race with vblank interrupts using the high precision
0398  * timestamping support.
0399  *
0400  * This is mostly useful for hardware that can obtain the scanout position, but
0401  * doesn't have a hardware frame counter.
0402  */
0403 u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
0404 {
0405     struct drm_device *dev = crtc->dev;
0406     unsigned int pipe = drm_crtc_index(crtc);
0407     u64 vblank;
0408     unsigned long flags;
0409 
0410     drm_WARN_ONCE(dev, drm_debug_enabled(DRM_UT_VBL) &&
0411               !crtc->funcs->get_vblank_timestamp,
0412               "This function requires support for accurate vblank timestamps.");
0413 
0414     spin_lock_irqsave(&dev->vblank_time_lock, flags);
0415 
0416     drm_update_vblank_count(dev, pipe, false);
0417     vblank = drm_vblank_count(dev, pipe);
0418 
0419     spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
0420 
0421     return vblank;
0422 }
0423 EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
0424 
0425 static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
0426 {
0427     if (drm_core_check_feature(dev, DRIVER_MODESET)) {
0428         struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
0429 
0430         if (drm_WARN_ON(dev, !crtc))
0431             return;
0432 
0433         if (crtc->funcs->disable_vblank)
0434             crtc->funcs->disable_vblank(crtc);
0435     }
0436 #ifdef CONFIG_DRM_LEGACY
0437     else {
0438         dev->driver->disable_vblank(dev, pipe);
0439     }
0440 #endif
0441 }
0442 
0443 /*
0444  * Disable vblank irq's on crtc, make sure that last vblank count
0445  * of hardware and corresponding consistent software vblank counter
0446  * are preserved, even if there are any spurious vblank irq's after
0447  * disable.
0448  */
0449 void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
0450 {
0451     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0452     unsigned long irqflags;
0453 
0454     assert_spin_locked(&dev->vbl_lock);
0455 
0456     /* Prevent vblank irq processing while disabling vblank irqs,
0457      * so no updates of timestamps or count can happen after we've
0458      * disabled. Needed to prevent races in case of delayed irq's.
0459      */
0460     spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
0461 
0462     /*
0463      * Update vblank count and disable vblank interrupts only if the
0464      * interrupts were enabled. This avoids calling the ->disable_vblank()
0465      * operation in atomic context with the hardware potentially runtime
0466      * suspended.
0467      */
0468     if (!vblank->enabled)
0469         goto out;
0470 
0471     /*
0472      * Update the count and timestamp to maintain the
0473      * appearance that the counter has been ticking all along until
0474      * this time. This makes the count account for the entire time
0475      * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
0476      */
0477     drm_update_vblank_count(dev, pipe, false);
0478     __disable_vblank(dev, pipe);
0479     vblank->enabled = false;
0480 
0481 out:
0482     spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
0483 }
0484 
0485 static void vblank_disable_fn(struct timer_list *t)
0486 {
0487     struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
0488     struct drm_device *dev = vblank->dev;
0489     unsigned int pipe = vblank->pipe;
0490     unsigned long irqflags;
0491 
0492     spin_lock_irqsave(&dev->vbl_lock, irqflags);
0493     if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
0494         drm_dbg_core(dev, "disabling vblank on crtc %u\n", pipe);
0495         drm_vblank_disable_and_save(dev, pipe);
0496     }
0497     spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
0498 }
0499 
0500 static void drm_vblank_init_release(struct drm_device *dev, void *ptr)
0501 {
0502     struct drm_vblank_crtc *vblank = ptr;
0503 
0504     drm_WARN_ON(dev, READ_ONCE(vblank->enabled) &&
0505             drm_core_check_feature(dev, DRIVER_MODESET));
0506 
0507     drm_vblank_destroy_worker(vblank);
0508     del_timer_sync(&vblank->disable_timer);
0509 }
0510 
0511 /**
0512  * drm_vblank_init - initialize vblank support
0513  * @dev: DRM device
0514  * @num_crtcs: number of CRTCs supported by @dev
0515  *
0516  * This function initializes vblank support for @num_crtcs display pipelines.
0517  * Cleanup is handled automatically through a cleanup function added with
0518  * drmm_add_action_or_reset().
0519  *
0520  * Returns:
0521  * Zero on success or a negative error code on failure.
0522  */
0523 int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
0524 {
0525     int ret;
0526     unsigned int i;
0527 
0528     spin_lock_init(&dev->vbl_lock);
0529     spin_lock_init(&dev->vblank_time_lock);
0530 
0531     dev->vblank = drmm_kcalloc(dev, num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
0532     if (!dev->vblank)
0533         return -ENOMEM;
0534 
0535     dev->num_crtcs = num_crtcs;
0536 
0537     for (i = 0; i < num_crtcs; i++) {
0538         struct drm_vblank_crtc *vblank = &dev->vblank[i];
0539 
0540         vblank->dev = dev;
0541         vblank->pipe = i;
0542         init_waitqueue_head(&vblank->queue);
0543         timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
0544         seqlock_init(&vblank->seqlock);
0545 
0546         ret = drmm_add_action_or_reset(dev, drm_vblank_init_release,
0547                            vblank);
0548         if (ret)
0549             return ret;
0550 
0551         ret = drm_vblank_worker_init(vblank);
0552         if (ret)
0553             return ret;
0554     }
0555 
0556     return 0;
0557 }
0558 EXPORT_SYMBOL(drm_vblank_init);
0559 
0560 /**
0561  * drm_dev_has_vblank - test if vblanking has been initialized for
0562  *                      a device
0563  * @dev: the device
0564  *
0565  * Drivers may call this function to test if vblank support is
0566  * initialized for a device. For most hardware this means that vblanking
0567  * can also be enabled.
0568  *
0569  * Atomic helpers use this function to initialize
0570  * &drm_crtc_state.no_vblank. See also drm_atomic_helper_check_modeset().
0571  *
0572  * Returns:
0573  * True if vblanking has been initialized for the given device, false
0574  * otherwise.
0575  */
0576 bool drm_dev_has_vblank(const struct drm_device *dev)
0577 {
0578     return dev->num_crtcs != 0;
0579 }
0580 EXPORT_SYMBOL(drm_dev_has_vblank);
0581 
0582 /**
0583  * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
0584  * @crtc: which CRTC's vblank waitqueue to retrieve
0585  *
0586  * This function returns a pointer to the vblank waitqueue for the CRTC.
0587  * Drivers can use this to implement vblank waits using wait_event() and related
0588  * functions.
0589  */
0590 wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
0591 {
0592     return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
0593 }
0594 EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
0595 
0596 
0597 /**
0598  * drm_calc_timestamping_constants - calculate vblank timestamp constants
0599  * @crtc: drm_crtc whose timestamp constants should be updated.
0600  * @mode: display mode containing the scanout timings
0601  *
0602  * Calculate and store various constants which are later needed by vblank and
0603  * swap-completion timestamping, e.g, by
0604  * drm_crtc_vblank_helper_get_vblank_timestamp(). They are derived from
0605  * CRTC's true scanout timing, so they take things like panel scaling or
0606  * other adjustments into account.
0607  */
0608 void drm_calc_timestamping_constants(struct drm_crtc *crtc,
0609                      const struct drm_display_mode *mode)
0610 {
0611     struct drm_device *dev = crtc->dev;
0612     unsigned int pipe = drm_crtc_index(crtc);
0613     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0614     int linedur_ns = 0, framedur_ns = 0;
0615     int dotclock = mode->crtc_clock;
0616 
0617     if (!drm_dev_has_vblank(dev))
0618         return;
0619 
0620     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
0621         return;
0622 
0623     /* Valid dotclock? */
0624     if (dotclock > 0) {
0625         int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
0626 
0627         /*
0628          * Convert scanline length in pixels and video
0629          * dot clock to line duration and frame duration
0630          * in nanoseconds:
0631          */
0632         linedur_ns  = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
0633         framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
0634 
0635         /*
0636          * Fields of interlaced scanout modes are only half a frame duration.
0637          */
0638         if (mode->flags & DRM_MODE_FLAG_INTERLACE)
0639             framedur_ns /= 2;
0640     } else {
0641         drm_err(dev, "crtc %u: Can't calculate constants, dotclock = 0!\n",
0642             crtc->base.id);
0643     }
0644 
0645     vblank->linedur_ns  = linedur_ns;
0646     vblank->framedur_ns = framedur_ns;
0647     drm_mode_copy(&vblank->hwmode, mode);
0648 
0649     drm_dbg_core(dev,
0650              "crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
0651              crtc->base.id, mode->crtc_htotal,
0652              mode->crtc_vtotal, mode->crtc_vdisplay);
0653     drm_dbg_core(dev, "crtc %u: clock %d kHz framedur %d linedur %d\n",
0654              crtc->base.id, dotclock, framedur_ns, linedur_ns);
0655 }
0656 EXPORT_SYMBOL(drm_calc_timestamping_constants);
0657 
0658 /**
0659  * drm_crtc_vblank_helper_get_vblank_timestamp_internal - precise vblank
0660  *                                                        timestamp helper
0661  * @crtc: CRTC whose vblank timestamp to retrieve
0662  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
0663  *             On return contains true maximum error of timestamp
0664  * @vblank_time: Pointer to time which should receive the timestamp
0665  * @in_vblank_irq:
0666  *     True when called from drm_crtc_handle_vblank().  Some drivers
0667  *     need to apply some workarounds for gpu-specific vblank irq quirks
0668  *     if flag is set.
0669  * @get_scanout_position:
0670  *     Callback function to retrieve the scanout position. See
0671  *     @struct drm_crtc_helper_funcs.get_scanout_position.
0672  *
0673  * Implements calculation of exact vblank timestamps from given drm_display_mode
0674  * timings and current video scanout position of a CRTC.
0675  *
0676  * The current implementation only handles standard video modes. For double scan
0677  * and interlaced modes the driver is supposed to adjust the hardware mode
0678  * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
0679  * match the scanout position reported.
0680  *
0681  * Note that atomic drivers must call drm_calc_timestamping_constants() before
0682  * enabling a CRTC. The atomic helpers already take care of that in
0683  * drm_atomic_helper_calc_timestamping_constants().
0684  *
0685  * Returns:
0686  *
0687  * Returns true on success, and false on failure, i.e. when no accurate
0688  * timestamp could be acquired.
0689  */
0690 bool
0691 drm_crtc_vblank_helper_get_vblank_timestamp_internal(
0692     struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time,
0693     bool in_vblank_irq,
0694     drm_vblank_get_scanout_position_func get_scanout_position)
0695 {
0696     struct drm_device *dev = crtc->dev;
0697     unsigned int pipe = crtc->index;
0698     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0699     struct timespec64 ts_etime, ts_vblank_time;
0700     ktime_t stime, etime;
0701     bool vbl_status;
0702     const struct drm_display_mode *mode;
0703     int vpos, hpos, i;
0704     int delta_ns, duration_ns;
0705 
0706     if (pipe >= dev->num_crtcs) {
0707         drm_err(dev, "Invalid crtc %u\n", pipe);
0708         return false;
0709     }
0710 
0711     /* Scanout position query not supported? Should not happen. */
0712     if (!get_scanout_position) {
0713         drm_err(dev, "Called from CRTC w/o get_scanout_position()!?\n");
0714         return false;
0715     }
0716 
0717     if (drm_drv_uses_atomic_modeset(dev))
0718         mode = &vblank->hwmode;
0719     else
0720         mode = &crtc->hwmode;
0721 
0722     /* If mode timing undefined, just return as no-op:
0723      * Happens during initial modesetting of a crtc.
0724      */
0725     if (mode->crtc_clock == 0) {
0726         drm_dbg_core(dev, "crtc %u: Noop due to uninitialized mode.\n",
0727                  pipe);
0728         drm_WARN_ON_ONCE(dev, drm_drv_uses_atomic_modeset(dev));
0729         return false;
0730     }
0731 
0732     /* Get current scanout position with system timestamp.
0733      * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
0734      * if single query takes longer than max_error nanoseconds.
0735      *
0736      * This guarantees a tight bound on maximum error if
0737      * code gets preempted or delayed for some reason.
0738      */
0739     for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
0740         /*
0741          * Get vertical and horizontal scanout position vpos, hpos,
0742          * and bounding timestamps stime, etime, pre/post query.
0743          */
0744         vbl_status = get_scanout_position(crtc, in_vblank_irq,
0745                           &vpos, &hpos,
0746                           &stime, &etime,
0747                           mode);
0748 
0749         /* Return as no-op if scanout query unsupported or failed. */
0750         if (!vbl_status) {
0751             drm_dbg_core(dev,
0752                      "crtc %u : scanoutpos query failed.\n",
0753                      pipe);
0754             return false;
0755         }
0756 
0757         /* Compute uncertainty in timestamp of scanout position query. */
0758         duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
0759 
0760         /* Accept result with <  max_error nsecs timing uncertainty. */
0761         if (duration_ns <= *max_error)
0762             break;
0763     }
0764 
0765     /* Noisy system timing? */
0766     if (i == DRM_TIMESTAMP_MAXRETRIES) {
0767         drm_dbg_core(dev,
0768                  "crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
0769                  pipe, duration_ns / 1000, *max_error / 1000, i);
0770     }
0771 
0772     /* Return upper bound of timestamp precision error. */
0773     *max_error = duration_ns;
0774 
0775     /* Convert scanout position into elapsed time at raw_time query
0776      * since start of scanout at first display scanline. delta_ns
0777      * can be negative if start of scanout hasn't happened yet.
0778      */
0779     delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
0780                mode->crtc_clock);
0781 
0782     /* Subtract time delta from raw timestamp to get final
0783      * vblank_time timestamp for end of vblank.
0784      */
0785     *vblank_time = ktime_sub_ns(etime, delta_ns);
0786 
0787     if (!drm_debug_enabled(DRM_UT_VBL))
0788         return true;
0789 
0790     ts_etime = ktime_to_timespec64(etime);
0791     ts_vblank_time = ktime_to_timespec64(*vblank_time);
0792 
0793     drm_dbg_vbl(dev,
0794             "crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
0795             pipe, hpos, vpos,
0796             (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
0797             (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
0798             duration_ns / 1000, i);
0799 
0800     return true;
0801 }
0802 EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp_internal);
0803 
0804 /**
0805  * drm_crtc_vblank_helper_get_vblank_timestamp - precise vblank timestamp
0806  *                                               helper
0807  * @crtc: CRTC whose vblank timestamp to retrieve
0808  * @max_error: Desired maximum allowable error in timestamps (nanosecs)
0809  *             On return contains true maximum error of timestamp
0810  * @vblank_time: Pointer to time which should receive the timestamp
0811  * @in_vblank_irq:
0812  *     True when called from drm_crtc_handle_vblank().  Some drivers
0813  *     need to apply some workarounds for gpu-specific vblank irq quirks
0814  *     if flag is set.
0815  *
0816  * Implements calculation of exact vblank timestamps from given drm_display_mode
0817  * timings and current video scanout position of a CRTC. This can be directly
0818  * used as the &drm_crtc_funcs.get_vblank_timestamp implementation of a kms
0819  * driver if &drm_crtc_helper_funcs.get_scanout_position is implemented.
0820  *
0821  * The current implementation only handles standard video modes. For double scan
0822  * and interlaced modes the driver is supposed to adjust the hardware mode
0823  * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
0824  * match the scanout position reported.
0825  *
0826  * Note that atomic drivers must call drm_calc_timestamping_constants() before
0827  * enabling a CRTC. The atomic helpers already take care of that in
0828  * drm_atomic_helper_calc_timestamping_constants().
0829  *
0830  * Returns:
0831  *
0832  * Returns true on success, and false on failure, i.e. when no accurate
0833  * timestamp could be acquired.
0834  */
0835 bool drm_crtc_vblank_helper_get_vblank_timestamp(struct drm_crtc *crtc,
0836                          int *max_error,
0837                          ktime_t *vblank_time,
0838                          bool in_vblank_irq)
0839 {
0840     return drm_crtc_vblank_helper_get_vblank_timestamp_internal(
0841         crtc, max_error, vblank_time, in_vblank_irq,
0842         crtc->helper_private->get_scanout_position);
0843 }
0844 EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp);
0845 
0846 /**
0847  * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
0848  *                             vblank interval
0849  * @dev: DRM device
0850  * @pipe: index of CRTC whose vblank timestamp to retrieve
0851  * @tvblank: Pointer to target time which should receive the timestamp
0852  * @in_vblank_irq:
0853  *     True when called from drm_crtc_handle_vblank().  Some drivers
0854  *     need to apply some workarounds for gpu-specific vblank irq quirks
0855  *     if flag is set.
0856  *
0857  * Fetches the system timestamp corresponding to the time of the most recent
0858  * vblank interval on specified CRTC. May call into kms-driver to
0859  * compute the timestamp with a high-precision GPU specific method.
0860  *
0861  * Returns zero if timestamp originates from uncorrected do_gettimeofday()
0862  * call, i.e., it isn't very precisely locked to the true vblank.
0863  *
0864  * Returns:
0865  * True if timestamp is considered to be very precise, false otherwise.
0866  */
0867 static bool
0868 drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
0869               ktime_t *tvblank, bool in_vblank_irq)
0870 {
0871     struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
0872     bool ret = false;
0873 
0874     /* Define requested maximum error on timestamps (nanoseconds). */
0875     int max_error = (int) drm_timestamp_precision * 1000;
0876 
0877     /* Query driver if possible and precision timestamping enabled. */
0878     if (crtc && crtc->funcs->get_vblank_timestamp && max_error > 0) {
0879         struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
0880 
0881         ret = crtc->funcs->get_vblank_timestamp(crtc, &max_error,
0882                             tvblank, in_vblank_irq);
0883     }
0884 
0885     /* GPU high precision timestamp query unsupported or failed.
0886      * Return current monotonic/gettimeofday timestamp as best estimate.
0887      */
0888     if (!ret)
0889         *tvblank = ktime_get();
0890 
0891     return ret;
0892 }
0893 
0894 /**
0895  * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
0896  * @crtc: which counter to retrieve
0897  *
0898  * Fetches the "cooked" vblank count value that represents the number of
0899  * vblank events since the system was booted, including lost events due to
0900  * modesetting activity. Note that this timer isn't correct against a racing
0901  * vblank interrupt (since it only reports the software vblank counter), see
0902  * drm_crtc_accurate_vblank_count() for such use-cases.
0903  *
0904  * Note that for a given vblank counter value drm_crtc_handle_vblank()
0905  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
0906  * provide a barrier: Any writes done before calling
0907  * drm_crtc_handle_vblank() will be visible to callers of the later
0908  * functions, if the vblank count is the same or a later one.
0909  *
0910  * See also &drm_vblank_crtc.count.
0911  *
0912  * Returns:
0913  * The software vblank counter.
0914  */
0915 u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
0916 {
0917     return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
0918 }
0919 EXPORT_SYMBOL(drm_crtc_vblank_count);
0920 
0921 /**
0922  * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
0923  *     system timestamp corresponding to that vblank counter value.
0924  * @dev: DRM device
0925  * @pipe: index of CRTC whose counter to retrieve
0926  * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
0927  *
0928  * Fetches the "cooked" vblank count value that represents the number of
0929  * vblank events since the system was booted, including lost events due to
0930  * modesetting activity. Returns corresponding system timestamp of the time
0931  * of the vblank interval that corresponds to the current vblank counter value.
0932  *
0933  * This is the legacy version of drm_crtc_vblank_count_and_time().
0934  */
0935 static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
0936                      ktime_t *vblanktime)
0937 {
0938     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
0939     u64 vblank_count;
0940     unsigned int seq;
0941 
0942     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs)) {
0943         *vblanktime = 0;
0944         return 0;
0945     }
0946 
0947     do {
0948         seq = read_seqbegin(&vblank->seqlock);
0949         vblank_count = atomic64_read(&vblank->count);
0950         *vblanktime = vblank->time;
0951     } while (read_seqretry(&vblank->seqlock, seq));
0952 
0953     return vblank_count;
0954 }
0955 
0956 /**
0957  * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
0958  *     and the system timestamp corresponding to that vblank counter value
0959  * @crtc: which counter to retrieve
0960  * @vblanktime: Pointer to time to receive the vblank timestamp.
0961  *
0962  * Fetches the "cooked" vblank count value that represents the number of
0963  * vblank events since the system was booted, including lost events due to
0964  * modesetting activity. Returns corresponding system timestamp of the time
0965  * of the vblank interval that corresponds to the current vblank counter value.
0966  *
0967  * Note that for a given vblank counter value drm_crtc_handle_vblank()
0968  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
0969  * provide a barrier: Any writes done before calling
0970  * drm_crtc_handle_vblank() will be visible to callers of the later
0971  * functions, if the vblank count is the same or a later one.
0972  *
0973  * See also &drm_vblank_crtc.count.
0974  */
0975 u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
0976                    ktime_t *vblanktime)
0977 {
0978     return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
0979                      vblanktime);
0980 }
0981 EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
0982 
0983 static void send_vblank_event(struct drm_device *dev,
0984         struct drm_pending_vblank_event *e,
0985         u64 seq, ktime_t now)
0986 {
0987     struct timespec64 tv;
0988 
0989     switch (e->event.base.type) {
0990     case DRM_EVENT_VBLANK:
0991     case DRM_EVENT_FLIP_COMPLETE:
0992         tv = ktime_to_timespec64(now);
0993         e->event.vbl.sequence = seq;
0994         /*
0995          * e->event is a user space structure, with hardcoded unsigned
0996          * 32-bit seconds/microseconds. This is safe as we always use
0997          * monotonic timestamps since linux-4.15
0998          */
0999         e->event.vbl.tv_sec = tv.tv_sec;
1000         e->event.vbl.tv_usec = tv.tv_nsec / 1000;
1001         break;
1002     case DRM_EVENT_CRTC_SEQUENCE:
1003         if (seq)
1004             e->event.seq.sequence = seq;
1005         e->event.seq.time_ns = ktime_to_ns(now);
1006         break;
1007     }
1008     trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
1009     /*
1010      * Use the same timestamp for any associated fence signal to avoid
1011      * mismatch in timestamps for vsync & fence events triggered by the
1012      * same HW event. Frameworks like SurfaceFlinger in Android expects the
1013      * retire-fence timestamp to match exactly with HW vsync as it uses it
1014      * for its software vsync modeling.
1015      */
1016     drm_send_event_timestamp_locked(dev, &e->base, now);
1017 }
1018 
1019 /**
1020  * drm_crtc_arm_vblank_event - arm vblank event after pageflip
1021  * @crtc: the source CRTC of the vblank event
1022  * @e: the event to send
1023  *
1024  * A lot of drivers need to generate vblank events for the very next vblank
1025  * interrupt. For example when the page flip interrupt happens when the page
1026  * flip gets armed, but not when it actually executes within the next vblank
1027  * period. This helper function implements exactly the required vblank arming
1028  * behaviour.
1029  *
1030  * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
1031  * atomic commit must ensure that the next vblank happens at exactly the same
1032  * time as the atomic commit is committed to the hardware. This function itself
1033  * does **not** protect against the next vblank interrupt racing with either this
1034  * function call or the atomic commit operation. A possible sequence could be:
1035  *
1036  * 1. Driver commits new hardware state into vblank-synchronized registers.
1037  * 2. A vblank happens, committing the hardware state. Also the corresponding
1038  *    vblank interrupt is fired off and fully processed by the interrupt
1039  *    handler.
1040  * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
1041  * 4. The event is only send out for the next vblank, which is wrong.
1042  *
1043  * An equivalent race can happen when the driver calls
1044  * drm_crtc_arm_vblank_event() before writing out the new hardware state.
1045  *
1046  * The only way to make this work safely is to prevent the vblank from firing
1047  * (and the hardware from committing anything else) until the entire atomic
1048  * commit sequence has run to completion. If the hardware does not have such a
1049  * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
1050  * Instead drivers need to manually send out the event from their interrupt
1051  * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
1052  * possible race with the hardware committing the atomic update.
1053  *
1054  * Caller must hold a vblank reference for the event @e acquired by a
1055  * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
1056  */
1057 void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
1058                    struct drm_pending_vblank_event *e)
1059 {
1060     struct drm_device *dev = crtc->dev;
1061     unsigned int pipe = drm_crtc_index(crtc);
1062 
1063     assert_spin_locked(&dev->event_lock);
1064 
1065     e->pipe = pipe;
1066     e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
1067     list_add_tail(&e->base.link, &dev->vblank_event_list);
1068 }
1069 EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
1070 
1071 /**
1072  * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
1073  * @crtc: the source CRTC of the vblank event
1074  * @e: the event to send
1075  *
1076  * Updates sequence # and timestamp on event for the most recently processed
1077  * vblank, and sends it to userspace.  Caller must hold event lock.
1078  *
1079  * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
1080  * situation, especially to send out events for atomic commit operations.
1081  */
1082 void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
1083                 struct drm_pending_vblank_event *e)
1084 {
1085     struct drm_device *dev = crtc->dev;
1086     u64 seq;
1087     unsigned int pipe = drm_crtc_index(crtc);
1088     ktime_t now;
1089 
1090     if (drm_dev_has_vblank(dev)) {
1091         seq = drm_vblank_count_and_time(dev, pipe, &now);
1092     } else {
1093         seq = 0;
1094 
1095         now = ktime_get();
1096     }
1097     e->pipe = pipe;
1098     send_vblank_event(dev, e, seq, now);
1099 }
1100 EXPORT_SYMBOL(drm_crtc_send_vblank_event);
1101 
1102 static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
1103 {
1104     if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1105         struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1106 
1107         if (drm_WARN_ON(dev, !crtc))
1108             return 0;
1109 
1110         if (crtc->funcs->enable_vblank)
1111             return crtc->funcs->enable_vblank(crtc);
1112     }
1113 #ifdef CONFIG_DRM_LEGACY
1114     else if (dev->driver->enable_vblank) {
1115         return dev->driver->enable_vblank(dev, pipe);
1116     }
1117 #endif
1118 
1119     return -EINVAL;
1120 }
1121 
1122 static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
1123 {
1124     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1125     int ret = 0;
1126 
1127     assert_spin_locked(&dev->vbl_lock);
1128 
1129     spin_lock(&dev->vblank_time_lock);
1130 
1131     if (!vblank->enabled) {
1132         /*
1133          * Enable vblank irqs under vblank_time_lock protection.
1134          * All vblank count & timestamp updates are held off
1135          * until we are done reinitializing master counter and
1136          * timestamps. Filtercode in drm_handle_vblank() will
1137          * prevent double-accounting of same vblank interval.
1138          */
1139         ret = __enable_vblank(dev, pipe);
1140         drm_dbg_core(dev, "enabling vblank on crtc %u, ret: %d\n",
1141                  pipe, ret);
1142         if (ret) {
1143             atomic_dec(&vblank->refcount);
1144         } else {
1145             drm_update_vblank_count(dev, pipe, 0);
1146             /* drm_update_vblank_count() includes a wmb so we just
1147              * need to ensure that the compiler emits the write
1148              * to mark the vblank as enabled after the call
1149              * to drm_update_vblank_count().
1150              */
1151             WRITE_ONCE(vblank->enabled, true);
1152         }
1153     }
1154 
1155     spin_unlock(&dev->vblank_time_lock);
1156 
1157     return ret;
1158 }
1159 
1160 int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
1161 {
1162     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1163     unsigned long irqflags;
1164     int ret = 0;
1165 
1166     if (!drm_dev_has_vblank(dev))
1167         return -EINVAL;
1168 
1169     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1170         return -EINVAL;
1171 
1172     spin_lock_irqsave(&dev->vbl_lock, irqflags);
1173     /* Going from 0->1 means we have to enable interrupts again */
1174     if (atomic_add_return(1, &vblank->refcount) == 1) {
1175         ret = drm_vblank_enable(dev, pipe);
1176     } else {
1177         if (!vblank->enabled) {
1178             atomic_dec(&vblank->refcount);
1179             ret = -EINVAL;
1180         }
1181     }
1182     spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
1183 
1184     return ret;
1185 }
1186 
1187 /**
1188  * drm_crtc_vblank_get - get a reference count on vblank events
1189  * @crtc: which CRTC to own
1190  *
1191  * Acquire a reference count on vblank events to avoid having them disabled
1192  * while in use.
1193  *
1194  * Returns:
1195  * Zero on success or a negative error code on failure.
1196  */
1197 int drm_crtc_vblank_get(struct drm_crtc *crtc)
1198 {
1199     return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
1200 }
1201 EXPORT_SYMBOL(drm_crtc_vblank_get);
1202 
1203 void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
1204 {
1205     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1206 
1207     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1208         return;
1209 
1210     if (drm_WARN_ON(dev, atomic_read(&vblank->refcount) == 0))
1211         return;
1212 
1213     /* Last user schedules interrupt disable */
1214     if (atomic_dec_and_test(&vblank->refcount)) {
1215         if (drm_vblank_offdelay == 0)
1216             return;
1217         else if (drm_vblank_offdelay < 0)
1218             vblank_disable_fn(&vblank->disable_timer);
1219         else if (!dev->vblank_disable_immediate)
1220             mod_timer(&vblank->disable_timer,
1221                   jiffies + ((drm_vblank_offdelay * HZ)/1000));
1222     }
1223 }
1224 
1225 /**
1226  * drm_crtc_vblank_put - give up ownership of vblank events
1227  * @crtc: which counter to give up
1228  *
1229  * Release ownership of a given vblank counter, turning off interrupts
1230  * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
1231  */
1232 void drm_crtc_vblank_put(struct drm_crtc *crtc)
1233 {
1234     drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
1235 }
1236 EXPORT_SYMBOL(drm_crtc_vblank_put);
1237 
1238 /**
1239  * drm_wait_one_vblank - wait for one vblank
1240  * @dev: DRM device
1241  * @pipe: CRTC index
1242  *
1243  * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
1244  * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
1245  * due to lack of driver support or because the crtc is off.
1246  *
1247  * This is the legacy version of drm_crtc_wait_one_vblank().
1248  */
1249 void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
1250 {
1251     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1252     int ret;
1253     u64 last;
1254 
1255     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1256         return;
1257 
1258     ret = drm_vblank_get(dev, pipe);
1259     if (drm_WARN(dev, ret, "vblank not available on crtc %i, ret=%i\n",
1260              pipe, ret))
1261         return;
1262 
1263     last = drm_vblank_count(dev, pipe);
1264 
1265     ret = wait_event_timeout(vblank->queue,
1266                  last != drm_vblank_count(dev, pipe),
1267                  msecs_to_jiffies(100));
1268 
1269     drm_WARN(dev, ret == 0, "vblank wait timed out on crtc %i\n", pipe);
1270 
1271     drm_vblank_put(dev, pipe);
1272 }
1273 EXPORT_SYMBOL(drm_wait_one_vblank);
1274 
1275 /**
1276  * drm_crtc_wait_one_vblank - wait for one vblank
1277  * @crtc: DRM crtc
1278  *
1279  * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
1280  * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
1281  * due to lack of driver support or because the crtc is off.
1282  */
1283 void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
1284 {
1285     drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
1286 }
1287 EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
1288 
1289 /**
1290  * drm_crtc_vblank_off - disable vblank events on a CRTC
1291  * @crtc: CRTC in question
1292  *
1293  * Drivers can use this function to shut down the vblank interrupt handling when
1294  * disabling a crtc. This function ensures that the latest vblank frame count is
1295  * stored so that drm_vblank_on can restore it again.
1296  *
1297  * Drivers must use this function when the hardware vblank counter can get
1298  * reset, e.g. when suspending or disabling the @crtc in general.
1299  */
1300 void drm_crtc_vblank_off(struct drm_crtc *crtc)
1301 {
1302     struct drm_device *dev = crtc->dev;
1303     unsigned int pipe = drm_crtc_index(crtc);
1304     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1305     struct drm_pending_vblank_event *e, *t;
1306     ktime_t now;
1307     u64 seq;
1308 
1309     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1310         return;
1311 
1312     /*
1313      * Grab event_lock early to prevent vblank work from being scheduled
1314      * while we're in the middle of shutting down vblank interrupts
1315      */
1316     spin_lock_irq(&dev->event_lock);
1317 
1318     spin_lock(&dev->vbl_lock);
1319     drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
1320             pipe, vblank->enabled, vblank->inmodeset);
1321 
1322     /* Avoid redundant vblank disables without previous
1323      * drm_crtc_vblank_on(). */
1324     if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
1325         drm_vblank_disable_and_save(dev, pipe);
1326 
1327     wake_up(&vblank->queue);
1328 
1329     /*
1330      * Prevent subsequent drm_vblank_get() from re-enabling
1331      * the vblank interrupt by bumping the refcount.
1332      */
1333     if (!vblank->inmodeset) {
1334         atomic_inc(&vblank->refcount);
1335         vblank->inmodeset = 1;
1336     }
1337     spin_unlock(&dev->vbl_lock);
1338 
1339     /* Send any queued vblank events, lest the natives grow disquiet */
1340     seq = drm_vblank_count_and_time(dev, pipe, &now);
1341 
1342     list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1343         if (e->pipe != pipe)
1344             continue;
1345         drm_dbg_core(dev, "Sending premature vblank event on disable: "
1346                  "wanted %llu, current %llu\n",
1347                  e->sequence, seq);
1348         list_del(&e->base.link);
1349         drm_vblank_put(dev, pipe);
1350         send_vblank_event(dev, e, seq, now);
1351     }
1352 
1353     /* Cancel any leftover pending vblank work */
1354     drm_vblank_cancel_pending_works(vblank);
1355 
1356     spin_unlock_irq(&dev->event_lock);
1357 
1358     /* Will be reset by the modeset helpers when re-enabling the crtc by
1359      * calling drm_calc_timestamping_constants(). */
1360     vblank->hwmode.crtc_clock = 0;
1361 
1362     /* Wait for any vblank work that's still executing to finish */
1363     drm_vblank_flush_worker(vblank);
1364 }
1365 EXPORT_SYMBOL(drm_crtc_vblank_off);
1366 
1367 /**
1368  * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
1369  * @crtc: CRTC in question
1370  *
1371  * Drivers can use this function to reset the vblank state to off at load time.
1372  * Drivers should use this together with the drm_crtc_vblank_off() and
1373  * drm_crtc_vblank_on() functions. The difference compared to
1374  * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
1375  * and hence doesn't need to call any driver hooks.
1376  *
1377  * This is useful for recovering driver state e.g. on driver load, or on resume.
1378  */
1379 void drm_crtc_vblank_reset(struct drm_crtc *crtc)
1380 {
1381     struct drm_device *dev = crtc->dev;
1382     unsigned int pipe = drm_crtc_index(crtc);
1383     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1384 
1385     spin_lock_irq(&dev->vbl_lock);
1386     /*
1387      * Prevent subsequent drm_vblank_get() from enabling the vblank
1388      * interrupt by bumping the refcount.
1389      */
1390     if (!vblank->inmodeset) {
1391         atomic_inc(&vblank->refcount);
1392         vblank->inmodeset = 1;
1393     }
1394     spin_unlock_irq(&dev->vbl_lock);
1395 
1396     drm_WARN_ON(dev, !list_empty(&dev->vblank_event_list));
1397     drm_WARN_ON(dev, !list_empty(&vblank->pending_work));
1398 }
1399 EXPORT_SYMBOL(drm_crtc_vblank_reset);
1400 
1401 /**
1402  * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
1403  * @crtc: CRTC in question
1404  * @max_vblank_count: max hardware vblank counter value
1405  *
1406  * Update the maximum hardware vblank counter value for @crtc
1407  * at runtime. Useful for hardware where the operation of the
1408  * hardware vblank counter depends on the currently active
1409  * display configuration.
1410  *
1411  * For example, if the hardware vblank counter does not work
1412  * when a specific connector is active the maximum can be set
1413  * to zero. And when that specific connector isn't active the
1414  * maximum can again be set to the appropriate non-zero value.
1415  *
1416  * If used, must be called before drm_vblank_on().
1417  */
1418 void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
1419                    u32 max_vblank_count)
1420 {
1421     struct drm_device *dev = crtc->dev;
1422     unsigned int pipe = drm_crtc_index(crtc);
1423     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1424 
1425     drm_WARN_ON(dev, dev->max_vblank_count);
1426     drm_WARN_ON(dev, !READ_ONCE(vblank->inmodeset));
1427 
1428     vblank->max_vblank_count = max_vblank_count;
1429 }
1430 EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
1431 
1432 /**
1433  * drm_crtc_vblank_on - enable vblank events on a CRTC
1434  * @crtc: CRTC in question
1435  *
1436  * This functions restores the vblank interrupt state captured with
1437  * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
1438  * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
1439  * unbalanced and so can also be unconditionally called in driver load code to
1440  * reflect the current hardware state of the crtc.
1441  */
1442 void drm_crtc_vblank_on(struct drm_crtc *crtc)
1443 {
1444     struct drm_device *dev = crtc->dev;
1445     unsigned int pipe = drm_crtc_index(crtc);
1446     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1447 
1448     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1449         return;
1450 
1451     spin_lock_irq(&dev->vbl_lock);
1452     drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
1453             pipe, vblank->enabled, vblank->inmodeset);
1454 
1455     /* Drop our private "prevent drm_vblank_get" refcount */
1456     if (vblank->inmodeset) {
1457         atomic_dec(&vblank->refcount);
1458         vblank->inmodeset = 0;
1459     }
1460 
1461     drm_reset_vblank_timestamp(dev, pipe);
1462 
1463     /*
1464      * re-enable interrupts if there are users left, or the
1465      * user wishes vblank interrupts to be enabled all the time.
1466      */
1467     if (atomic_read(&vblank->refcount) != 0 || drm_vblank_offdelay == 0)
1468         drm_WARN_ON(dev, drm_vblank_enable(dev, pipe));
1469     spin_unlock_irq(&dev->vbl_lock);
1470 }
1471 EXPORT_SYMBOL(drm_crtc_vblank_on);
1472 
1473 static void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
1474 {
1475     ktime_t t_vblank;
1476     struct drm_vblank_crtc *vblank;
1477     int framedur_ns;
1478     u64 diff_ns;
1479     u32 cur_vblank, diff = 1;
1480     int count = DRM_TIMESTAMP_MAXRETRIES;
1481     u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
1482 
1483     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1484         return;
1485 
1486     assert_spin_locked(&dev->vbl_lock);
1487     assert_spin_locked(&dev->vblank_time_lock);
1488 
1489     vblank = &dev->vblank[pipe];
1490     drm_WARN_ONCE(dev,
1491               drm_debug_enabled(DRM_UT_VBL) && !vblank->framedur_ns,
1492               "Cannot compute missed vblanks without frame duration\n");
1493     framedur_ns = vblank->framedur_ns;
1494 
1495     do {
1496         cur_vblank = __get_vblank_counter(dev, pipe);
1497         drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
1498     } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
1499 
1500     diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
1501     if (framedur_ns)
1502         diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
1503 
1504 
1505     drm_dbg_vbl(dev,
1506             "missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
1507             diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
1508     vblank->last = (cur_vblank - diff) & max_vblank_count;
1509 }
1510 
1511 /**
1512  * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
1513  * @crtc: CRTC in question
1514  *
1515  * Power manamement features can cause frame counter resets between vblank
1516  * disable and enable. Drivers can use this function in their
1517  * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
1518  * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
1519  * vblank counter.
1520  *
1521  * Note that drivers must have race-free high-precision timestamping support,
1522  * i.e.  &drm_crtc_funcs.get_vblank_timestamp must be hooked up and
1523  * &drm_driver.vblank_disable_immediate must be set to indicate the
1524  * time-stamping functions are race-free against vblank hardware counter
1525  * increments.
1526  */
1527 void drm_crtc_vblank_restore(struct drm_crtc *crtc)
1528 {
1529     WARN_ON_ONCE(!crtc->funcs->get_vblank_timestamp);
1530     WARN_ON_ONCE(!crtc->dev->vblank_disable_immediate);
1531 
1532     drm_vblank_restore(crtc->dev, drm_crtc_index(crtc));
1533 }
1534 EXPORT_SYMBOL(drm_crtc_vblank_restore);
1535 
1536 static void drm_legacy_vblank_pre_modeset(struct drm_device *dev,
1537                       unsigned int pipe)
1538 {
1539     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1540 
1541     /* vblank is not initialized (IRQ not installed ?), or has been freed */
1542     if (!drm_dev_has_vblank(dev))
1543         return;
1544 
1545     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1546         return;
1547 
1548     /*
1549      * To avoid all the problems that might happen if interrupts
1550      * were enabled/disabled around or between these calls, we just
1551      * have the kernel take a reference on the CRTC (just once though
1552      * to avoid corrupting the count if multiple, mismatch calls occur),
1553      * so that interrupts remain enabled in the interim.
1554      */
1555     if (!vblank->inmodeset) {
1556         vblank->inmodeset = 0x1;
1557         if (drm_vblank_get(dev, pipe) == 0)
1558             vblank->inmodeset |= 0x2;
1559     }
1560 }
1561 
1562 static void drm_legacy_vblank_post_modeset(struct drm_device *dev,
1563                        unsigned int pipe)
1564 {
1565     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1566 
1567     /* vblank is not initialized (IRQ not installed ?), or has been freed */
1568     if (!drm_dev_has_vblank(dev))
1569         return;
1570 
1571     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1572         return;
1573 
1574     if (vblank->inmodeset) {
1575         spin_lock_irq(&dev->vbl_lock);
1576         drm_reset_vblank_timestamp(dev, pipe);
1577         spin_unlock_irq(&dev->vbl_lock);
1578 
1579         if (vblank->inmodeset & 0x2)
1580             drm_vblank_put(dev, pipe);
1581 
1582         vblank->inmodeset = 0;
1583     }
1584 }
1585 
1586 int drm_legacy_modeset_ctl_ioctl(struct drm_device *dev, void *data,
1587                  struct drm_file *file_priv)
1588 {
1589     struct drm_modeset_ctl *modeset = data;
1590     unsigned int pipe;
1591 
1592     /* If drm_vblank_init() hasn't been called yet, just no-op */
1593     if (!drm_dev_has_vblank(dev))
1594         return 0;
1595 
1596     /* KMS drivers handle this internally */
1597     if (!drm_core_check_feature(dev, DRIVER_LEGACY))
1598         return 0;
1599 
1600     pipe = modeset->crtc;
1601     if (pipe >= dev->num_crtcs)
1602         return -EINVAL;
1603 
1604     switch (modeset->cmd) {
1605     case _DRM_PRE_MODESET:
1606         drm_legacy_vblank_pre_modeset(dev, pipe);
1607         break;
1608     case _DRM_POST_MODESET:
1609         drm_legacy_vblank_post_modeset(dev, pipe);
1610         break;
1611     default:
1612         return -EINVAL;
1613     }
1614 
1615     return 0;
1616 }
1617 
1618 static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
1619                   u64 req_seq,
1620                   union drm_wait_vblank *vblwait,
1621                   struct drm_file *file_priv)
1622 {
1623     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1624     struct drm_pending_vblank_event *e;
1625     ktime_t now;
1626     u64 seq;
1627     int ret;
1628 
1629     e = kzalloc(sizeof(*e), GFP_KERNEL);
1630     if (e == NULL) {
1631         ret = -ENOMEM;
1632         goto err_put;
1633     }
1634 
1635     e->pipe = pipe;
1636     e->event.base.type = DRM_EVENT_VBLANK;
1637     e->event.base.length = sizeof(e->event.vbl);
1638     e->event.vbl.user_data = vblwait->request.signal;
1639     e->event.vbl.crtc_id = 0;
1640     if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1641         struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1642 
1643         if (crtc)
1644             e->event.vbl.crtc_id = crtc->base.id;
1645     }
1646 
1647     spin_lock_irq(&dev->event_lock);
1648 
1649     /*
1650      * drm_crtc_vblank_off() might have been called after we called
1651      * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
1652      * vblank disable, so no need for further locking.  The reference from
1653      * drm_vblank_get() protects against vblank disable from another source.
1654      */
1655     if (!READ_ONCE(vblank->enabled)) {
1656         ret = -EINVAL;
1657         goto err_unlock;
1658     }
1659 
1660     ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
1661                         &e->event.base);
1662 
1663     if (ret)
1664         goto err_unlock;
1665 
1666     seq = drm_vblank_count_and_time(dev, pipe, &now);
1667 
1668     drm_dbg_core(dev, "event on vblank count %llu, current %llu, crtc %u\n",
1669              req_seq, seq, pipe);
1670 
1671     trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
1672 
1673     e->sequence = req_seq;
1674     if (drm_vblank_passed(seq, req_seq)) {
1675         drm_vblank_put(dev, pipe);
1676         send_vblank_event(dev, e, seq, now);
1677         vblwait->reply.sequence = seq;
1678     } else {
1679         /* drm_handle_vblank_events will call drm_vblank_put */
1680         list_add_tail(&e->base.link, &dev->vblank_event_list);
1681         vblwait->reply.sequence = req_seq;
1682     }
1683 
1684     spin_unlock_irq(&dev->event_lock);
1685 
1686     return 0;
1687 
1688 err_unlock:
1689     spin_unlock_irq(&dev->event_lock);
1690     kfree(e);
1691 err_put:
1692     drm_vblank_put(dev, pipe);
1693     return ret;
1694 }
1695 
1696 static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
1697 {
1698     if (vblwait->request.sequence)
1699         return false;
1700 
1701     return _DRM_VBLANK_RELATIVE ==
1702         (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
1703                       _DRM_VBLANK_EVENT |
1704                       _DRM_VBLANK_NEXTONMISS));
1705 }
1706 
1707 /*
1708  * Widen a 32-bit param to 64-bits.
1709  *
1710  * \param narrow 32-bit value (missing upper 32 bits)
1711  * \param near 64-bit value that should be 'close' to near
1712  *
1713  * This function returns a 64-bit value using the lower 32-bits from
1714  * 'narrow' and constructing the upper 32-bits so that the result is
1715  * as close as possible to 'near'.
1716  */
1717 
1718 static u64 widen_32_to_64(u32 narrow, u64 near)
1719 {
1720     return near + (s32) (narrow - near);
1721 }
1722 
1723 static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
1724                   struct drm_wait_vblank_reply *reply)
1725 {
1726     ktime_t now;
1727     struct timespec64 ts;
1728 
1729     /*
1730      * drm_wait_vblank_reply is a UAPI structure that uses 'long'
1731      * to store the seconds. This is safe as we always use monotonic
1732      * timestamps since linux-4.15.
1733      */
1734     reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
1735     ts = ktime_to_timespec64(now);
1736     reply->tval_sec = (u32)ts.tv_sec;
1737     reply->tval_usec = ts.tv_nsec / 1000;
1738 }
1739 
1740 static bool drm_wait_vblank_supported(struct drm_device *dev)
1741 {
1742 #if IS_ENABLED(CONFIG_DRM_LEGACY)
1743     if (unlikely(drm_core_check_feature(dev, DRIVER_LEGACY)))
1744         return dev->irq_enabled;
1745 #endif
1746     return drm_dev_has_vblank(dev);
1747 }
1748 
1749 int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
1750               struct drm_file *file_priv)
1751 {
1752     struct drm_crtc *crtc;
1753     struct drm_vblank_crtc *vblank;
1754     union drm_wait_vblank *vblwait = data;
1755     int ret;
1756     u64 req_seq, seq;
1757     unsigned int pipe_index;
1758     unsigned int flags, pipe, high_pipe;
1759 
1760     if (!drm_wait_vblank_supported(dev))
1761         return -EOPNOTSUPP;
1762 
1763     if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
1764         return -EINVAL;
1765 
1766     if (vblwait->request.type &
1767         ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1768           _DRM_VBLANK_HIGH_CRTC_MASK)) {
1769         drm_dbg_core(dev,
1770                  "Unsupported type value 0x%x, supported mask 0x%x\n",
1771                  vblwait->request.type,
1772                  (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
1773                   _DRM_VBLANK_HIGH_CRTC_MASK));
1774         return -EINVAL;
1775     }
1776 
1777     flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
1778     high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
1779     if (high_pipe)
1780         pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
1781     else
1782         pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
1783 
1784     /* Convert lease-relative crtc index into global crtc index */
1785     if (drm_core_check_feature(dev, DRIVER_MODESET)) {
1786         pipe = 0;
1787         drm_for_each_crtc(crtc, dev) {
1788             if (drm_lease_held(file_priv, crtc->base.id)) {
1789                 if (pipe_index == 0)
1790                     break;
1791                 pipe_index--;
1792             }
1793             pipe++;
1794         }
1795     } else {
1796         pipe = pipe_index;
1797     }
1798 
1799     if (pipe >= dev->num_crtcs)
1800         return -EINVAL;
1801 
1802     vblank = &dev->vblank[pipe];
1803 
1804     /* If the counter is currently enabled and accurate, short-circuit
1805      * queries to return the cached timestamp of the last vblank.
1806      */
1807     if (dev->vblank_disable_immediate &&
1808         drm_wait_vblank_is_query(vblwait) &&
1809         READ_ONCE(vblank->enabled)) {
1810         drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1811         return 0;
1812     }
1813 
1814     ret = drm_vblank_get(dev, pipe);
1815     if (ret) {
1816         drm_dbg_core(dev,
1817                  "crtc %d failed to acquire vblank counter, %d\n",
1818                  pipe, ret);
1819         return ret;
1820     }
1821     seq = drm_vblank_count(dev, pipe);
1822 
1823     switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
1824     case _DRM_VBLANK_RELATIVE:
1825         req_seq = seq + vblwait->request.sequence;
1826         vblwait->request.sequence = req_seq;
1827         vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
1828         break;
1829     case _DRM_VBLANK_ABSOLUTE:
1830         req_seq = widen_32_to_64(vblwait->request.sequence, seq);
1831         break;
1832     default:
1833         ret = -EINVAL;
1834         goto done;
1835     }
1836 
1837     if ((flags & _DRM_VBLANK_NEXTONMISS) &&
1838         drm_vblank_passed(seq, req_seq)) {
1839         req_seq = seq + 1;
1840         vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
1841         vblwait->request.sequence = req_seq;
1842     }
1843 
1844     if (flags & _DRM_VBLANK_EVENT) {
1845         /* must hold on to the vblank ref until the event fires
1846          * drm_vblank_put will be called asynchronously
1847          */
1848         return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
1849     }
1850 
1851     if (req_seq != seq) {
1852         int wait;
1853 
1854         drm_dbg_core(dev, "waiting on vblank count %llu, crtc %u\n",
1855                  req_seq, pipe);
1856         wait = wait_event_interruptible_timeout(vblank->queue,
1857             drm_vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
1858                       !READ_ONCE(vblank->enabled),
1859             msecs_to_jiffies(3000));
1860 
1861         switch (wait) {
1862         case 0:
1863             /* timeout */
1864             ret = -EBUSY;
1865             break;
1866         case -ERESTARTSYS:
1867             /* interrupted by signal */
1868             ret = -EINTR;
1869             break;
1870         default:
1871             ret = 0;
1872             break;
1873         }
1874     }
1875 
1876     if (ret != -EINTR) {
1877         drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
1878 
1879         drm_dbg_core(dev, "crtc %d returning %u to client\n",
1880                  pipe, vblwait->reply.sequence);
1881     } else {
1882         drm_dbg_core(dev, "crtc %d vblank wait interrupted by signal\n",
1883                  pipe);
1884     }
1885 
1886 done:
1887     drm_vblank_put(dev, pipe);
1888     return ret;
1889 }
1890 
1891 static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
1892 {
1893     struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
1894     bool high_prec = false;
1895     struct drm_pending_vblank_event *e, *t;
1896     ktime_t now;
1897     u64 seq;
1898 
1899     assert_spin_locked(&dev->event_lock);
1900 
1901     seq = drm_vblank_count_and_time(dev, pipe, &now);
1902 
1903     list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
1904         if (e->pipe != pipe)
1905             continue;
1906         if (!drm_vblank_passed(seq, e->sequence))
1907             continue;
1908 
1909         drm_dbg_core(dev, "vblank event on %llu, current %llu\n",
1910                  e->sequence, seq);
1911 
1912         list_del(&e->base.link);
1913         drm_vblank_put(dev, pipe);
1914         send_vblank_event(dev, e, seq, now);
1915     }
1916 
1917     if (crtc && crtc->funcs->get_vblank_timestamp)
1918         high_prec = true;
1919 
1920     trace_drm_vblank_event(pipe, seq, now, high_prec);
1921 }
1922 
1923 /**
1924  * drm_handle_vblank - handle a vblank event
1925  * @dev: DRM device
1926  * @pipe: index of CRTC where this event occurred
1927  *
1928  * Drivers should call this routine in their vblank interrupt handlers to
1929  * update the vblank counter and send any signals that may be pending.
1930  *
1931  * This is the legacy version of drm_crtc_handle_vblank().
1932  */
1933 bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
1934 {
1935     struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
1936     unsigned long irqflags;
1937     bool disable_irq;
1938 
1939     if (drm_WARN_ON_ONCE(dev, !drm_dev_has_vblank(dev)))
1940         return false;
1941 
1942     if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
1943         return false;
1944 
1945     spin_lock_irqsave(&dev->event_lock, irqflags);
1946 
1947     /* Need timestamp lock to prevent concurrent execution with
1948      * vblank enable/disable, as this would cause inconsistent
1949      * or corrupted timestamps and vblank counts.
1950      */
1951     spin_lock(&dev->vblank_time_lock);
1952 
1953     /* Vblank irq handling disabled. Nothing to do. */
1954     if (!vblank->enabled) {
1955         spin_unlock(&dev->vblank_time_lock);
1956         spin_unlock_irqrestore(&dev->event_lock, irqflags);
1957         return false;
1958     }
1959 
1960     drm_update_vblank_count(dev, pipe, true);
1961 
1962     spin_unlock(&dev->vblank_time_lock);
1963 
1964     wake_up(&vblank->queue);
1965 
1966     /* With instant-off, we defer disabling the interrupt until after
1967      * we finish processing the following vblank after all events have
1968      * been signaled. The disable has to be last (after
1969      * drm_handle_vblank_events) so that the timestamp is always accurate.
1970      */
1971     disable_irq = (dev->vblank_disable_immediate &&
1972                drm_vblank_offdelay > 0 &&
1973                !atomic_read(&vblank->refcount));
1974 
1975     drm_handle_vblank_events(dev, pipe);
1976     drm_handle_vblank_works(vblank);
1977 
1978     spin_unlock_irqrestore(&dev->event_lock, irqflags);
1979 
1980     if (disable_irq)
1981         vblank_disable_fn(&vblank->disable_timer);
1982 
1983     return true;
1984 }
1985 EXPORT_SYMBOL(drm_handle_vblank);
1986 
1987 /**
1988  * drm_crtc_handle_vblank - handle a vblank event
1989  * @crtc: where this event occurred
1990  *
1991  * Drivers should call this routine in their vblank interrupt handlers to
1992  * update the vblank counter and send any signals that may be pending.
1993  *
1994  * This is the native KMS version of drm_handle_vblank().
1995  *
1996  * Note that for a given vblank counter value drm_crtc_handle_vblank()
1997  * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
1998  * provide a barrier: Any writes done before calling
1999  * drm_crtc_handle_vblank() will be visible to callers of the later
2000  * functions, if the vblank count is the same or a later one.
2001  *
2002  * See also &drm_vblank_crtc.count.
2003  *
2004  * Returns:
2005  * True if the event was successfully handled, false on failure.
2006  */
2007 bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
2008 {
2009     return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
2010 }
2011 EXPORT_SYMBOL(drm_crtc_handle_vblank);
2012 
2013 /*
2014  * Get crtc VBLANK count.
2015  *
2016  * \param dev DRM device
2017  * \param data user argument, pointing to a drm_crtc_get_sequence structure.
2018  * \param file_priv drm file private for the user's open file descriptor
2019  */
2020 
2021 int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
2022                 struct drm_file *file_priv)
2023 {
2024     struct drm_crtc *crtc;
2025     struct drm_vblank_crtc *vblank;
2026     int pipe;
2027     struct drm_crtc_get_sequence *get_seq = data;
2028     ktime_t now;
2029     bool vblank_enabled;
2030     int ret;
2031 
2032     if (!drm_core_check_feature(dev, DRIVER_MODESET))
2033         return -EOPNOTSUPP;
2034 
2035     if (!drm_dev_has_vblank(dev))
2036         return -EOPNOTSUPP;
2037 
2038     crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
2039     if (!crtc)
2040         return -ENOENT;
2041 
2042     pipe = drm_crtc_index(crtc);
2043 
2044     vblank = &dev->vblank[pipe];
2045     vblank_enabled = dev->vblank_disable_immediate && READ_ONCE(vblank->enabled);
2046 
2047     if (!vblank_enabled) {
2048         ret = drm_crtc_vblank_get(crtc);
2049         if (ret) {
2050             drm_dbg_core(dev,
2051                      "crtc %d failed to acquire vblank counter, %d\n",
2052                      pipe, ret);
2053             return ret;
2054         }
2055     }
2056     drm_modeset_lock(&crtc->mutex, NULL);
2057     if (crtc->state)
2058         get_seq->active = crtc->state->enable;
2059     else
2060         get_seq->active = crtc->enabled;
2061     drm_modeset_unlock(&crtc->mutex);
2062     get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
2063     get_seq->sequence_ns = ktime_to_ns(now);
2064     if (!vblank_enabled)
2065         drm_crtc_vblank_put(crtc);
2066     return 0;
2067 }
2068 
2069 /*
2070  * Queue a event for VBLANK sequence
2071  *
2072  * \param dev DRM device
2073  * \param data user argument, pointing to a drm_crtc_queue_sequence structure.
2074  * \param file_priv drm file private for the user's open file descriptor
2075  */
2076 
2077 int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
2078                   struct drm_file *file_priv)
2079 {
2080     struct drm_crtc *crtc;
2081     struct drm_vblank_crtc *vblank;
2082     int pipe;
2083     struct drm_crtc_queue_sequence *queue_seq = data;
2084     ktime_t now;
2085     struct drm_pending_vblank_event *e;
2086     u32 flags;
2087     u64 seq;
2088     u64 req_seq;
2089     int ret;
2090 
2091     if (!drm_core_check_feature(dev, DRIVER_MODESET))
2092         return -EOPNOTSUPP;
2093 
2094     if (!drm_dev_has_vblank(dev))
2095         return -EOPNOTSUPP;
2096 
2097     crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
2098     if (!crtc)
2099         return -ENOENT;
2100 
2101     flags = queue_seq->flags;
2102     /* Check valid flag bits */
2103     if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
2104               DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
2105         return -EINVAL;
2106 
2107     pipe = drm_crtc_index(crtc);
2108 
2109     vblank = &dev->vblank[pipe];
2110 
2111     e = kzalloc(sizeof(*e), GFP_KERNEL);
2112     if (e == NULL)
2113         return -ENOMEM;
2114 
2115     ret = drm_crtc_vblank_get(crtc);
2116     if (ret) {
2117         drm_dbg_core(dev,
2118                  "crtc %d failed to acquire vblank counter, %d\n",
2119                  pipe, ret);
2120         goto err_free;
2121     }
2122 
2123     seq = drm_vblank_count_and_time(dev, pipe, &now);
2124     req_seq = queue_seq->sequence;
2125 
2126     if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
2127         req_seq += seq;
2128 
2129     if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && drm_vblank_passed(seq, req_seq))
2130         req_seq = seq + 1;
2131 
2132     e->pipe = pipe;
2133     e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
2134     e->event.base.length = sizeof(e->event.seq);
2135     e->event.seq.user_data = queue_seq->user_data;
2136 
2137     spin_lock_irq(&dev->event_lock);
2138 
2139     /*
2140      * drm_crtc_vblank_off() might have been called after we called
2141      * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
2142      * vblank disable, so no need for further locking.  The reference from
2143      * drm_crtc_vblank_get() protects against vblank disable from another source.
2144      */
2145     if (!READ_ONCE(vblank->enabled)) {
2146         ret = -EINVAL;
2147         goto err_unlock;
2148     }
2149 
2150     ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
2151                         &e->event.base);
2152 
2153     if (ret)
2154         goto err_unlock;
2155 
2156     e->sequence = req_seq;
2157 
2158     if (drm_vblank_passed(seq, req_seq)) {
2159         drm_crtc_vblank_put(crtc);
2160         send_vblank_event(dev, e, seq, now);
2161         queue_seq->sequence = seq;
2162     } else {
2163         /* drm_handle_vblank_events will call drm_vblank_put */
2164         list_add_tail(&e->base.link, &dev->vblank_event_list);
2165         queue_seq->sequence = req_seq;
2166     }
2167 
2168     spin_unlock_irq(&dev->event_lock);
2169     return 0;
2170 
2171 err_unlock:
2172     spin_unlock_irq(&dev->event_lock);
2173     drm_crtc_vblank_put(crtc);
2174 err_free:
2175     kfree(e);
2176     return ret;
2177 }
2178