Subversion Repositories Kolibri OS

Rev

Rev 6084 | Rev 6131 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

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