drm_irq.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. /**
  2. * \file drm_irq.c
  3. * IRQ support
  4. *
  5. * \author Rickard E. (Rik) Faith <faith@valinux.com>
  6. * \author Gareth Hughes <gareth@valinux.com>
  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. #include "drmP.h"
  35. #include "drm_trace.h"
  36. #include <linux/interrupt.h> /* For task queue support */
  37. #include <linux/slab.h>
  38. #include <linux/vgaarb.h>
  39. /* Access macro for slots in vblank timestamp ringbuffer. */
  40. #define vblanktimestamp(dev, crtc, count) ( \
  41. (dev)->_vblank_time[(crtc) * DRM_VBLANKTIME_RBSIZE + \
  42. ((count) % DRM_VBLANKTIME_RBSIZE)])
  43. /* Retry timestamp calculation up to 3 times to satisfy
  44. * drm_timestamp_precision before giving up.
  45. */
  46. #define DRM_TIMESTAMP_MAXRETRIES 3
  47. /* Threshold in nanoseconds for detection of redundant
  48. * vblank irq in drm_handle_vblank(). 1 msec should be ok.
  49. */
  50. #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
  51. /**
  52. * Get interrupt from bus id.
  53. *
  54. * \param inode device inode.
  55. * \param file_priv DRM file private.
  56. * \param cmd command.
  57. * \param arg user argument, pointing to a drm_irq_busid structure.
  58. * \return zero on success or a negative number on failure.
  59. *
  60. * Finds the PCI device with the specified bus id and gets its IRQ number.
  61. * This IOCTL is deprecated, and will now return EINVAL for any busid not equal
  62. * to that of the device that this DRM instance attached to.
  63. */
  64. int drm_irq_by_busid(struct drm_device *dev, void *data,
  65. struct drm_file *file_priv)
  66. {
  67. struct drm_irq_busid *p = data;
  68. if (!dev->driver->bus->irq_by_busid)
  69. return -EINVAL;
  70. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  71. return -EINVAL;
  72. return dev->driver->bus->irq_by_busid(dev, p);
  73. }
  74. /*
  75. * Clear vblank timestamp buffer for a crtc.
  76. */
  77. static void clear_vblank_timestamps(struct drm_device *dev, int crtc)
  78. {
  79. memset(&dev->_vblank_time[crtc * DRM_VBLANKTIME_RBSIZE], 0,
  80. DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval));
  81. }
  82. /*
  83. * Disable vblank irq's on crtc, make sure that last vblank count
  84. * of hardware and corresponding consistent software vblank counter
  85. * are preserved, even if there are any spurious vblank irq's after
  86. * disable.
  87. */
  88. static void vblank_disable_and_save(struct drm_device *dev, int crtc)
  89. {
  90. unsigned long irqflags;
  91. u32 vblcount;
  92. s64 diff_ns;
  93. int vblrc;
  94. struct timeval tvblank;
  95. /* Prevent vblank irq processing while disabling vblank irqs,
  96. * so no updates of timestamps or count can happen after we've
  97. * disabled. Needed to prevent races in case of delayed irq's.
  98. * Disable preemption, so vblank_time_lock is held as short as
  99. * possible, even under a kernel with PREEMPT_RT patches.
  100. */
  101. preempt_disable();
  102. spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
  103. dev->driver->disable_vblank(dev, crtc);
  104. dev->vblank_enabled[crtc] = 0;
  105. /* No further vblank irq's will be processed after
  106. * this point. Get current hardware vblank count and
  107. * vblank timestamp, repeat until they are consistent.
  108. *
  109. * FIXME: There is still a race condition here and in
  110. * drm_update_vblank_count() which can cause off-by-one
  111. * reinitialization of software vblank counter. If gpu
  112. * vblank counter doesn't increment exactly at the leading
  113. * edge of a vblank interval, then we can lose 1 count if
  114. * we happen to execute between start of vblank and the
  115. * delayed gpu counter increment.
  116. */
  117. do {
  118. dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc);
  119. vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
  120. } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc));
  121. /* Compute time difference to stored timestamp of last vblank
  122. * as updated by last invocation of drm_handle_vblank() in vblank irq.
  123. */
  124. vblcount = atomic_read(&dev->_vblank_count[crtc]);
  125. diff_ns = timeval_to_ns(&tvblank) -
  126. timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
  127. /* If there is at least 1 msec difference between the last stored
  128. * timestamp and tvblank, then we are currently executing our
  129. * disable inside a new vblank interval, the tvblank timestamp
  130. * corresponds to this new vblank interval and the irq handler
  131. * for this vblank didn't run yet and won't run due to our disable.
  132. * Therefore we need to do the job of drm_handle_vblank() and
  133. * increment the vblank counter by one to account for this vblank.
  134. *
  135. * Skip this step if there isn't any high precision timestamp
  136. * available. In that case we can't account for this and just
  137. * hope for the best.
  138. */
  139. if ((vblrc > 0) && (abs(diff_ns) > 1000000))
  140. atomic_inc(&dev->_vblank_count[crtc]);
  141. /* Invalidate all timestamps while vblank irq's are off. */
  142. clear_vblank_timestamps(dev, crtc);
  143. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  144. preempt_enable();
  145. }
  146. static void vblank_disable_fn(unsigned long arg)
  147. {
  148. struct drm_device *dev = (struct drm_device *)arg;
  149. unsigned long irqflags;
  150. int i;
  151. if (!dev->vblank_disable_allowed)
  152. return;
  153. for (i = 0; i < dev->num_crtcs; i++) {
  154. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  155. if (atomic_read(&dev->vblank_refcount[i]) == 0 &&
  156. dev->vblank_enabled[i]) {
  157. DRM_DEBUG("disabling vblank on crtc %d\n", i);
  158. vblank_disable_and_save(dev, i);
  159. }
  160. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  161. }
  162. }
  163. void drm_vblank_cleanup(struct drm_device *dev)
  164. {
  165. /* Bail if the driver didn't call drm_vblank_init() */
  166. if (dev->num_crtcs == 0)
  167. return;
  168. del_timer(&dev->vblank_disable_timer);
  169. vblank_disable_fn((unsigned long)dev);
  170. kfree(dev->vbl_queue);
  171. kfree(dev->_vblank_count);
  172. kfree(dev->vblank_refcount);
  173. kfree(dev->vblank_enabled);
  174. kfree(dev->last_vblank);
  175. kfree(dev->last_vblank_wait);
  176. kfree(dev->vblank_inmodeset);
  177. kfree(dev->_vblank_time);
  178. dev->num_crtcs = 0;
  179. }
  180. EXPORT_SYMBOL(drm_vblank_cleanup);
  181. int drm_vblank_init(struct drm_device *dev, int num_crtcs)
  182. {
  183. int i, ret = -ENOMEM;
  184. setup_timer(&dev->vblank_disable_timer, vblank_disable_fn,
  185. (unsigned long)dev);
  186. spin_lock_init(&dev->vbl_lock);
  187. spin_lock_init(&dev->vblank_time_lock);
  188. dev->num_crtcs = num_crtcs;
  189. dev->vbl_queue = kmalloc(sizeof(wait_queue_head_t) * num_crtcs,
  190. GFP_KERNEL);
  191. if (!dev->vbl_queue)
  192. goto err;
  193. dev->_vblank_count = kmalloc(sizeof(atomic_t) * num_crtcs, GFP_KERNEL);
  194. if (!dev->_vblank_count)
  195. goto err;
  196. dev->vblank_refcount = kmalloc(sizeof(atomic_t) * num_crtcs,
  197. GFP_KERNEL);
  198. if (!dev->vblank_refcount)
  199. goto err;
  200. dev->vblank_enabled = kcalloc(num_crtcs, sizeof(int), GFP_KERNEL);
  201. if (!dev->vblank_enabled)
  202. goto err;
  203. dev->last_vblank = kcalloc(num_crtcs, sizeof(u32), GFP_KERNEL);
  204. if (!dev->last_vblank)
  205. goto err;
  206. dev->last_vblank_wait = kcalloc(num_crtcs, sizeof(u32), GFP_KERNEL);
  207. if (!dev->last_vblank_wait)
  208. goto err;
  209. dev->vblank_inmodeset = kcalloc(num_crtcs, sizeof(int), GFP_KERNEL);
  210. if (!dev->vblank_inmodeset)
  211. goto err;
  212. dev->_vblank_time = kcalloc(num_crtcs * DRM_VBLANKTIME_RBSIZE,
  213. sizeof(struct timeval), GFP_KERNEL);
  214. if (!dev->_vblank_time)
  215. goto err;
  216. DRM_INFO("Supports vblank timestamp caching Rev 1 (10.10.2010).\n");
  217. /* Driver specific high-precision vblank timestamping supported? */
  218. if (dev->driver->get_vblank_timestamp)
  219. DRM_INFO("Driver supports precise vblank timestamp query.\n");
  220. else
  221. DRM_INFO("No driver support for vblank timestamp query.\n");
  222. /* Zero per-crtc vblank stuff */
  223. for (i = 0; i < num_crtcs; i++) {
  224. init_waitqueue_head(&dev->vbl_queue[i]);
  225. atomic_set(&dev->_vblank_count[i], 0);
  226. atomic_set(&dev->vblank_refcount[i], 0);
  227. }
  228. dev->vblank_disable_allowed = 0;
  229. return 0;
  230. err:
  231. drm_vblank_cleanup(dev);
  232. return ret;
  233. }
  234. EXPORT_SYMBOL(drm_vblank_init);
  235. static void drm_irq_vgaarb_nokms(void *cookie, bool state)
  236. {
  237. struct drm_device *dev = cookie;
  238. if (dev->driver->vgaarb_irq) {
  239. dev->driver->vgaarb_irq(dev, state);
  240. return;
  241. }
  242. if (!dev->irq_enabled)
  243. return;
  244. if (state)
  245. dev->driver->irq_uninstall(dev);
  246. else {
  247. dev->driver->irq_preinstall(dev);
  248. dev->driver->irq_postinstall(dev);
  249. }
  250. }
  251. /**
  252. * Install IRQ handler.
  253. *
  254. * \param dev DRM device.
  255. *
  256. * Initializes the IRQ related data. Installs the handler, calling the driver
  257. * \c drm_driver_irq_preinstall() and \c drm_driver_irq_postinstall() functions
  258. * before and after the installation.
  259. */
  260. int drm_irq_install(struct drm_device *dev)
  261. {
  262. int ret = 0;
  263. unsigned long sh_flags = 0;
  264. char *irqname;
  265. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  266. return -EINVAL;
  267. if (drm_dev_to_irq(dev) == 0)
  268. return -EINVAL;
  269. mutex_lock(&dev->struct_mutex);
  270. /* Driver must have been initialized */
  271. if (!dev->dev_private) {
  272. mutex_unlock(&dev->struct_mutex);
  273. return -EINVAL;
  274. }
  275. if (dev->irq_enabled) {
  276. mutex_unlock(&dev->struct_mutex);
  277. return -EBUSY;
  278. }
  279. dev->irq_enabled = 1;
  280. mutex_unlock(&dev->struct_mutex);
  281. DRM_DEBUG("irq=%d\n", drm_dev_to_irq(dev));
  282. /* Before installing handler */
  283. dev->driver->irq_preinstall(dev);
  284. /* Install handler */
  285. if (drm_core_check_feature(dev, DRIVER_IRQ_SHARED))
  286. sh_flags = IRQF_SHARED;
  287. if (dev->devname)
  288. irqname = dev->devname;
  289. else
  290. irqname = dev->driver->name;
  291. ret = request_irq(drm_dev_to_irq(dev), dev->driver->irq_handler,
  292. sh_flags, irqname, dev);
  293. if (ret < 0) {
  294. mutex_lock(&dev->struct_mutex);
  295. dev->irq_enabled = 0;
  296. mutex_unlock(&dev->struct_mutex);
  297. return ret;
  298. }
  299. if (!drm_core_check_feature(dev, DRIVER_MODESET))
  300. vga_client_register(dev->pdev, (void *)dev, drm_irq_vgaarb_nokms, NULL);
  301. /* After installing handler */
  302. ret = dev->driver->irq_postinstall(dev);
  303. if (ret < 0) {
  304. mutex_lock(&dev->struct_mutex);
  305. dev->irq_enabled = 0;
  306. mutex_unlock(&dev->struct_mutex);
  307. }
  308. return ret;
  309. }
  310. EXPORT_SYMBOL(drm_irq_install);
  311. /**
  312. * Uninstall the IRQ handler.
  313. *
  314. * \param dev DRM device.
  315. *
  316. * Calls the driver's \c drm_driver_irq_uninstall() function, and stops the irq.
  317. */
  318. int drm_irq_uninstall(struct drm_device *dev)
  319. {
  320. unsigned long irqflags;
  321. int irq_enabled, i;
  322. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  323. return -EINVAL;
  324. mutex_lock(&dev->struct_mutex);
  325. irq_enabled = dev->irq_enabled;
  326. dev->irq_enabled = 0;
  327. mutex_unlock(&dev->struct_mutex);
  328. /*
  329. * Wake up any waiters so they don't hang.
  330. */
  331. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  332. for (i = 0; i < dev->num_crtcs; i++) {
  333. DRM_WAKEUP(&dev->vbl_queue[i]);
  334. dev->vblank_enabled[i] = 0;
  335. dev->last_vblank[i] = dev->driver->get_vblank_counter(dev, i);
  336. }
  337. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  338. if (!irq_enabled)
  339. return -EINVAL;
  340. DRM_DEBUG("irq=%d\n", drm_dev_to_irq(dev));
  341. if (!drm_core_check_feature(dev, DRIVER_MODESET))
  342. vga_client_register(dev->pdev, NULL, NULL, NULL);
  343. dev->driver->irq_uninstall(dev);
  344. free_irq(drm_dev_to_irq(dev), dev);
  345. return 0;
  346. }
  347. EXPORT_SYMBOL(drm_irq_uninstall);
  348. /**
  349. * IRQ control ioctl.
  350. *
  351. * \param inode device inode.
  352. * \param file_priv DRM file private.
  353. * \param cmd command.
  354. * \param arg user argument, pointing to a drm_control structure.
  355. * \return zero on success or a negative number on failure.
  356. *
  357. * Calls irq_install() or irq_uninstall() according to \p arg.
  358. */
  359. int drm_control(struct drm_device *dev, void *data,
  360. struct drm_file *file_priv)
  361. {
  362. struct drm_control *ctl = data;
  363. /* if we haven't irq we fallback for compatibility reasons -
  364. * this used to be a separate function in drm_dma.h
  365. */
  366. switch (ctl->func) {
  367. case DRM_INST_HANDLER:
  368. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  369. return 0;
  370. if (drm_core_check_feature(dev, DRIVER_MODESET))
  371. return 0;
  372. if (dev->if_version < DRM_IF_VERSION(1, 2) &&
  373. ctl->irq != drm_dev_to_irq(dev))
  374. return -EINVAL;
  375. return drm_irq_install(dev);
  376. case DRM_UNINST_HANDLER:
  377. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  378. return 0;
  379. if (drm_core_check_feature(dev, DRIVER_MODESET))
  380. return 0;
  381. return drm_irq_uninstall(dev);
  382. default:
  383. return -EINVAL;
  384. }
  385. }
  386. /**
  387. * drm_calc_timestamping_constants - Calculate and
  388. * store various constants which are later needed by
  389. * vblank and swap-completion timestamping, e.g, by
  390. * drm_calc_vbltimestamp_from_scanoutpos().
  391. * They are derived from crtc's true scanout timing,
  392. * so they take things like panel scaling or other
  393. * adjustments into account.
  394. *
  395. * @crtc drm_crtc whose timestamp constants should be updated.
  396. *
  397. */
  398. void drm_calc_timestamping_constants(struct drm_crtc *crtc)
  399. {
  400. s64 linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
  401. u64 dotclock;
  402. /* Dot clock in Hz: */
  403. dotclock = (u64) crtc->hwmode.clock * 1000;
  404. /* Valid dotclock? */
  405. if (dotclock > 0) {
  406. /* Convert scanline length in pixels and video dot clock to
  407. * line duration, frame duration and pixel duration in
  408. * nanoseconds:
  409. */
  410. pixeldur_ns = (s64) div64_u64(1000000000, dotclock);
  411. linedur_ns = (s64) div64_u64(((u64) crtc->hwmode.crtc_htotal *
  412. 1000000000), dotclock);
  413. framedur_ns = (s64) crtc->hwmode.crtc_vtotal * linedur_ns;
  414. } else
  415. DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
  416. crtc->base.id);
  417. crtc->pixeldur_ns = pixeldur_ns;
  418. crtc->linedur_ns = linedur_ns;
  419. crtc->framedur_ns = framedur_ns;
  420. DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
  421. crtc->base.id, crtc->hwmode.crtc_htotal,
  422. crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay);
  423. DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
  424. crtc->base.id, (int) dotclock/1000, (int) framedur_ns,
  425. (int) linedur_ns, (int) pixeldur_ns);
  426. }
  427. EXPORT_SYMBOL(drm_calc_timestamping_constants);
  428. /**
  429. * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
  430. * drivers. Implements calculation of exact vblank timestamps from
  431. * given drm_display_mode timings and current video scanout position
  432. * of a crtc. This can be called from within get_vblank_timestamp()
  433. * implementation of a kms driver to implement the actual timestamping.
  434. *
  435. * Should return timestamps conforming to the OML_sync_control OpenML
  436. * extension specification. The timestamp corresponds to the end of
  437. * the vblank interval, aka start of scanout of topmost-leftmost display
  438. * pixel in the following video frame.
  439. *
  440. * Requires support for optional dev->driver->get_scanout_position()
  441. * in kms driver, plus a bit of setup code to provide a drm_display_mode
  442. * that corresponds to the true scanout timing.
  443. *
  444. * The current implementation only handles standard video modes. It
  445. * returns as no operation if a doublescan or interlaced video mode is
  446. * active. Higher level code is expected to handle this.
  447. *
  448. * @dev: DRM device.
  449. * @crtc: Which crtc's vblank timestamp to retrieve.
  450. * @max_error: Desired maximum allowable error in timestamps (nanosecs).
  451. * On return contains true maximum error of timestamp.
  452. * @vblank_time: Pointer to struct timeval which should receive the timestamp.
  453. * @flags: Flags to pass to driver:
  454. * 0 = Default.
  455. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
  456. * @refcrtc: drm_crtc* of crtc which defines scanout timing.
  457. *
  458. * Returns negative value on error, failure or if not supported in current
  459. * video mode:
  460. *
  461. * -EINVAL - Invalid crtc.
  462. * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
  463. * -ENOTSUPP - Function not supported in current display mode.
  464. * -EIO - Failed, e.g., due to failed scanout position query.
  465. *
  466. * Returns or'ed positive status flags on success:
  467. *
  468. * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
  469. * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
  470. *
  471. */
  472. int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
  473. int *max_error,
  474. struct timeval *vblank_time,
  475. unsigned flags,
  476. struct drm_crtc *refcrtc)
  477. {
  478. struct timeval stime, raw_time;
  479. struct drm_display_mode *mode;
  480. int vbl_status, vtotal, vdisplay;
  481. int vpos, hpos, i;
  482. s64 framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
  483. bool invbl;
  484. if (crtc < 0 || crtc >= dev->num_crtcs) {
  485. DRM_ERROR("Invalid crtc %d\n", crtc);
  486. return -EINVAL;
  487. }
  488. /* Scanout position query not supported? Should not happen. */
  489. if (!dev->driver->get_scanout_position) {
  490. DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
  491. return -EIO;
  492. }
  493. mode = &refcrtc->hwmode;
  494. vtotal = mode->crtc_vtotal;
  495. vdisplay = mode->crtc_vdisplay;
  496. /* Durations of frames, lines, pixels in nanoseconds. */
  497. framedur_ns = refcrtc->framedur_ns;
  498. linedur_ns = refcrtc->linedur_ns;
  499. pixeldur_ns = refcrtc->pixeldur_ns;
  500. /* If mode timing undefined, just return as no-op:
  501. * Happens during initial modesetting of a crtc.
  502. */
  503. if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) {
  504. DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
  505. return -EAGAIN;
  506. }
  507. /* Don't know yet how to handle interlaced or
  508. * double scan modes. Just no-op for now.
  509. */
  510. if (mode->flags & (DRM_MODE_FLAG_INTERLACE | DRM_MODE_FLAG_DBLSCAN)) {
  511. DRM_DEBUG("crtc %d: Noop due to unsupported mode.\n", crtc);
  512. return -ENOTSUPP;
  513. }
  514. /* Get current scanout position with system timestamp.
  515. * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
  516. * if single query takes longer than max_error nanoseconds.
  517. *
  518. * This guarantees a tight bound on maximum error if
  519. * code gets preempted or delayed for some reason.
  520. */
  521. for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
  522. /* Disable preemption to make it very likely to
  523. * succeed in the first iteration even on PREEMPT_RT kernel.
  524. */
  525. preempt_disable();
  526. /* Get system timestamp before query. */
  527. do_gettimeofday(&stime);
  528. /* Get vertical and horizontal scanout pos. vpos, hpos. */
  529. vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos);
  530. /* Get system timestamp after query. */
  531. do_gettimeofday(&raw_time);
  532. preempt_enable();
  533. /* Return as no-op if scanout query unsupported or failed. */
  534. if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
  535. DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
  536. crtc, vbl_status);
  537. return -EIO;
  538. }
  539. duration_ns = timeval_to_ns(&raw_time) - timeval_to_ns(&stime);
  540. /* Accept result with < max_error nsecs timing uncertainty. */
  541. if (duration_ns <= (s64) *max_error)
  542. break;
  543. }
  544. /* Noisy system timing? */
  545. if (i == DRM_TIMESTAMP_MAXRETRIES) {
  546. DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
  547. crtc, (int) duration_ns/1000, *max_error/1000, i);
  548. }
  549. /* Return upper bound of timestamp precision error. */
  550. *max_error = (int) duration_ns;
  551. /* Check if in vblank area:
  552. * vpos is >=0 in video scanout area, but negative
  553. * within vblank area, counting down the number of lines until
  554. * start of scanout.
  555. */
  556. invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
  557. /* Convert scanout position into elapsed time at raw_time query
  558. * since start of scanout at first display scanline. delta_ns
  559. * can be negative if start of scanout hasn't happened yet.
  560. */
  561. delta_ns = (s64) vpos * linedur_ns + (s64) hpos * pixeldur_ns;
  562. /* Is vpos outside nominal vblank area, but less than
  563. * 1/100 of a frame height away from start of vblank?
  564. * If so, assume this isn't a massively delayed vblank
  565. * interrupt, but a vblank interrupt that fired a few
  566. * microseconds before true start of vblank. Compensate
  567. * by adding a full frame duration to the final timestamp.
  568. * Happens, e.g., on ATI R500, R600.
  569. *
  570. * We only do this if DRM_CALLED_FROM_VBLIRQ.
  571. */
  572. if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl &&
  573. ((vdisplay - vpos) < vtotal / 100)) {
  574. delta_ns = delta_ns - framedur_ns;
  575. /* Signal this correction as "applied". */
  576. vbl_status |= 0x8;
  577. }
  578. /* Subtract time delta from raw timestamp to get final
  579. * vblank_time timestamp for end of vblank.
  580. */
  581. *vblank_time = ns_to_timeval(timeval_to_ns(&raw_time) - delta_ns);
  582. DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %d.%d -> %d.%d [e %d us, %d rep]\n",
  583. crtc, (int) vbl_status, hpos, vpos, raw_time.tv_sec,
  584. raw_time.tv_usec, vblank_time->tv_sec, vblank_time->tv_usec,
  585. (int) duration_ns/1000, i);
  586. vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
  587. if (invbl)
  588. vbl_status |= DRM_VBLANKTIME_INVBL;
  589. return vbl_status;
  590. }
  591. EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
  592. /**
  593. * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
  594. * vblank interval.
  595. *
  596. * @dev: DRM device
  597. * @crtc: which crtc's vblank timestamp to retrieve
  598. * @tvblank: Pointer to target struct timeval which should receive the timestamp
  599. * @flags: Flags to pass to driver:
  600. * 0 = Default.
  601. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
  602. *
  603. * Fetches the system timestamp corresponding to the time of the most recent
  604. * vblank interval on specified crtc. May call into kms-driver to
  605. * compute the timestamp with a high-precision GPU specific method.
  606. *
  607. * Returns zero if timestamp originates from uncorrected do_gettimeofday()
  608. * call, i.e., it isn't very precisely locked to the true vblank.
  609. *
  610. * Returns non-zero if timestamp is considered to be very precise.
  611. */
  612. u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
  613. struct timeval *tvblank, unsigned flags)
  614. {
  615. int ret = 0;
  616. /* Define requested maximum error on timestamps (nanoseconds). */
  617. int max_error = (int) drm_timestamp_precision * 1000;
  618. /* Query driver if possible and precision timestamping enabled. */
  619. if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
  620. ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
  621. tvblank, flags);
  622. if (ret > 0)
  623. return (u32) ret;
  624. }
  625. /* GPU high precision timestamp query unsupported or failed.
  626. * Return gettimeofday timestamp as best estimate.
  627. */
  628. do_gettimeofday(tvblank);
  629. return 0;
  630. }
  631. EXPORT_SYMBOL(drm_get_last_vbltimestamp);
  632. /**
  633. * drm_vblank_count - retrieve "cooked" vblank counter value
  634. * @dev: DRM device
  635. * @crtc: which counter to retrieve
  636. *
  637. * Fetches the "cooked" vblank count value that represents the number of
  638. * vblank events since the system was booted, including lost events due to
  639. * modesetting activity.
  640. */
  641. u32 drm_vblank_count(struct drm_device *dev, int crtc)
  642. {
  643. return atomic_read(&dev->_vblank_count[crtc]);
  644. }
  645. EXPORT_SYMBOL(drm_vblank_count);
  646. /**
  647. * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
  648. * and the system timestamp corresponding to that vblank counter value.
  649. *
  650. * @dev: DRM device
  651. * @crtc: which counter to retrieve
  652. * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
  653. *
  654. * Fetches the "cooked" vblank count value that represents the number of
  655. * vblank events since the system was booted, including lost events due to
  656. * modesetting activity. Returns corresponding system timestamp of the time
  657. * of the vblank interval that corresponds to the current value vblank counter
  658. * value.
  659. */
  660. u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
  661. struct timeval *vblanktime)
  662. {
  663. u32 cur_vblank;
  664. /* Read timestamp from slot of _vblank_time ringbuffer
  665. * that corresponds to current vblank count. Retry if
  666. * count has incremented during readout. This works like
  667. * a seqlock.
  668. */
  669. do {
  670. cur_vblank = atomic_read(&dev->_vblank_count[crtc]);
  671. *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
  672. smp_rmb();
  673. } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc]));
  674. return cur_vblank;
  675. }
  676. EXPORT_SYMBOL(drm_vblank_count_and_time);
  677. /**
  678. * drm_update_vblank_count - update the master vblank counter
  679. * @dev: DRM device
  680. * @crtc: counter to update
  681. *
  682. * Call back into the driver to update the appropriate vblank counter
  683. * (specified by @crtc). Deal with wraparound, if it occurred, and
  684. * update the last read value so we can deal with wraparound on the next
  685. * call if necessary.
  686. *
  687. * Only necessary when going from off->on, to account for frames we
  688. * didn't get an interrupt for.
  689. *
  690. * Note: caller must hold dev->vbl_lock since this reads & writes
  691. * device vblank fields.
  692. */
  693. static void drm_update_vblank_count(struct drm_device *dev, int crtc)
  694. {
  695. u32 cur_vblank, diff, tslot, rc;
  696. struct timeval t_vblank;
  697. /*
  698. * Interrupts were disabled prior to this call, so deal with counter
  699. * wrap if needed.
  700. * NOTE! It's possible we lost a full dev->max_vblank_count events
  701. * here if the register is small or we had vblank interrupts off for
  702. * a long time.
  703. *
  704. * We repeat the hardware vblank counter & timestamp query until
  705. * we get consistent results. This to prevent races between gpu
  706. * updating its hardware counter while we are retrieving the
  707. * corresponding vblank timestamp.
  708. */
  709. do {
  710. cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
  711. rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
  712. } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
  713. /* Deal with counter wrap */
  714. diff = cur_vblank - dev->last_vblank[crtc];
  715. if (cur_vblank < dev->last_vblank[crtc]) {
  716. diff += dev->max_vblank_count;
  717. DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
  718. crtc, dev->last_vblank[crtc], cur_vblank, diff);
  719. }
  720. DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
  721. crtc, diff);
  722. /* Reinitialize corresponding vblank timestamp if high-precision query
  723. * available. Skip this step if query unsupported or failed. Will
  724. * reinitialize delayed at next vblank interrupt in that case.
  725. */
  726. if (rc) {
  727. tslot = atomic_read(&dev->_vblank_count[crtc]) + diff;
  728. vblanktimestamp(dev, crtc, tslot) = t_vblank;
  729. smp_wmb();
  730. }
  731. atomic_add(diff, &dev->_vblank_count[crtc]);
  732. }
  733. /**
  734. * drm_vblank_get - get a reference count on vblank events
  735. * @dev: DRM device
  736. * @crtc: which CRTC to own
  737. *
  738. * Acquire a reference count on vblank events to avoid having them disabled
  739. * while in use.
  740. *
  741. * RETURNS
  742. * Zero on success, nonzero on failure.
  743. */
  744. int drm_vblank_get(struct drm_device *dev, int crtc)
  745. {
  746. unsigned long irqflags, irqflags2;
  747. int ret = 0;
  748. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  749. /* Going from 0->1 means we have to enable interrupts again */
  750. if (atomic_add_return(1, &dev->vblank_refcount[crtc]) == 1) {
  751. /* Disable preemption while holding vblank_time_lock. Do
  752. * it explicitely to guard against PREEMPT_RT kernel.
  753. */
  754. preempt_disable();
  755. spin_lock_irqsave(&dev->vblank_time_lock, irqflags2);
  756. if (!dev->vblank_enabled[crtc]) {
  757. /* Enable vblank irqs under vblank_time_lock protection.
  758. * All vblank count & timestamp updates are held off
  759. * until we are done reinitializing master counter and
  760. * timestamps. Filtercode in drm_handle_vblank() will
  761. * prevent double-accounting of same vblank interval.
  762. */
  763. ret = dev->driver->enable_vblank(dev, crtc);
  764. DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
  765. crtc, ret);
  766. if (ret)
  767. atomic_dec(&dev->vblank_refcount[crtc]);
  768. else {
  769. dev->vblank_enabled[crtc] = 1;
  770. drm_update_vblank_count(dev, crtc);
  771. }
  772. }
  773. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags2);
  774. preempt_enable();
  775. } else {
  776. if (!dev->vblank_enabled[crtc]) {
  777. atomic_dec(&dev->vblank_refcount[crtc]);
  778. ret = -EINVAL;
  779. }
  780. }
  781. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  782. return ret;
  783. }
  784. EXPORT_SYMBOL(drm_vblank_get);
  785. /**
  786. * drm_vblank_put - give up ownership of vblank events
  787. * @dev: DRM device
  788. * @crtc: which counter to give up
  789. *
  790. * Release ownership of a given vblank counter, turning off interrupts
  791. * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
  792. */
  793. void drm_vblank_put(struct drm_device *dev, int crtc)
  794. {
  795. BUG_ON(atomic_read(&dev->vblank_refcount[crtc]) == 0);
  796. /* Last user schedules interrupt disable */
  797. if (atomic_dec_and_test(&dev->vblank_refcount[crtc]) &&
  798. (drm_vblank_offdelay > 0))
  799. mod_timer(&dev->vblank_disable_timer,
  800. jiffies + ((drm_vblank_offdelay * DRM_HZ)/1000));
  801. }
  802. EXPORT_SYMBOL(drm_vblank_put);
  803. void drm_vblank_off(struct drm_device *dev, int crtc)
  804. {
  805. unsigned long irqflags;
  806. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  807. vblank_disable_and_save(dev, crtc);
  808. DRM_WAKEUP(&dev->vbl_queue[crtc]);
  809. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  810. }
  811. EXPORT_SYMBOL(drm_vblank_off);
  812. /**
  813. * drm_vblank_pre_modeset - account for vblanks across mode sets
  814. * @dev: DRM device
  815. * @crtc: CRTC in question
  816. * @post: post or pre mode set?
  817. *
  818. * Account for vblank events across mode setting events, which will likely
  819. * reset the hardware frame counter.
  820. */
  821. void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
  822. {
  823. /* vblank is not initialized (IRQ not installed ?) */
  824. if (!dev->num_crtcs)
  825. return;
  826. /*
  827. * To avoid all the problems that might happen if interrupts
  828. * were enabled/disabled around or between these calls, we just
  829. * have the kernel take a reference on the CRTC (just once though
  830. * to avoid corrupting the count if multiple, mismatch calls occur),
  831. * so that interrupts remain enabled in the interim.
  832. */
  833. if (!dev->vblank_inmodeset[crtc]) {
  834. dev->vblank_inmodeset[crtc] = 0x1;
  835. if (drm_vblank_get(dev, crtc) == 0)
  836. dev->vblank_inmodeset[crtc] |= 0x2;
  837. }
  838. }
  839. EXPORT_SYMBOL(drm_vblank_pre_modeset);
  840. void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
  841. {
  842. unsigned long irqflags;
  843. if (dev->vblank_inmodeset[crtc]) {
  844. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  845. dev->vblank_disable_allowed = 1;
  846. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  847. if (dev->vblank_inmodeset[crtc] & 0x2)
  848. drm_vblank_put(dev, crtc);
  849. dev->vblank_inmodeset[crtc] = 0;
  850. }
  851. }
  852. EXPORT_SYMBOL(drm_vblank_post_modeset);
  853. /**
  854. * drm_modeset_ctl - handle vblank event counter changes across mode switch
  855. * @DRM_IOCTL_ARGS: standard ioctl arguments
  856. *
  857. * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
  858. * ioctls around modesetting so that any lost vblank events are accounted for.
  859. *
  860. * Generally the counter will reset across mode sets. If interrupts are
  861. * enabled around this call, we don't have to do anything since the counter
  862. * will have already been incremented.
  863. */
  864. int drm_modeset_ctl(struct drm_device *dev, void *data,
  865. struct drm_file *file_priv)
  866. {
  867. struct drm_modeset_ctl *modeset = data;
  868. int crtc, ret = 0;
  869. /* If drm_vblank_init() hasn't been called yet, just no-op */
  870. if (!dev->num_crtcs)
  871. goto out;
  872. crtc = modeset->crtc;
  873. if (crtc >= dev->num_crtcs) {
  874. ret = -EINVAL;
  875. goto out;
  876. }
  877. switch (modeset->cmd) {
  878. case _DRM_PRE_MODESET:
  879. drm_vblank_pre_modeset(dev, crtc);
  880. break;
  881. case _DRM_POST_MODESET:
  882. drm_vblank_post_modeset(dev, crtc);
  883. break;
  884. default:
  885. ret = -EINVAL;
  886. break;
  887. }
  888. out:
  889. return ret;
  890. }
  891. static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
  892. union drm_wait_vblank *vblwait,
  893. struct drm_file *file_priv)
  894. {
  895. struct drm_pending_vblank_event *e;
  896. struct timeval now;
  897. unsigned long flags;
  898. unsigned int seq;
  899. int ret;
  900. e = kzalloc(sizeof *e, GFP_KERNEL);
  901. if (e == NULL) {
  902. ret = -ENOMEM;
  903. goto err_put;
  904. }
  905. e->pipe = pipe;
  906. e->base.pid = current->pid;
  907. e->event.base.type = DRM_EVENT_VBLANK;
  908. e->event.base.length = sizeof e->event;
  909. e->event.user_data = vblwait->request.signal;
  910. e->base.event = &e->event.base;
  911. e->base.file_priv = file_priv;
  912. e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
  913. spin_lock_irqsave(&dev->event_lock, flags);
  914. if (file_priv->event_space < sizeof e->event) {
  915. ret = -EBUSY;
  916. goto err_unlock;
  917. }
  918. file_priv->event_space -= sizeof e->event;
  919. seq = drm_vblank_count_and_time(dev, pipe, &now);
  920. if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
  921. (seq - vblwait->request.sequence) <= (1 << 23)) {
  922. vblwait->request.sequence = seq + 1;
  923. vblwait->reply.sequence = vblwait->request.sequence;
  924. }
  925. DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
  926. vblwait->request.sequence, seq, pipe);
  927. trace_drm_vblank_event_queued(current->pid, pipe,
  928. vblwait->request.sequence);
  929. e->event.sequence = vblwait->request.sequence;
  930. if ((seq - vblwait->request.sequence) <= (1 << 23)) {
  931. e->event.sequence = seq;
  932. e->event.tv_sec = now.tv_sec;
  933. e->event.tv_usec = now.tv_usec;
  934. drm_vblank_put(dev, pipe);
  935. list_add_tail(&e->base.link, &e->base.file_priv->event_list);
  936. wake_up_interruptible(&e->base.file_priv->event_wait);
  937. vblwait->reply.sequence = seq;
  938. trace_drm_vblank_event_delivered(current->pid, pipe,
  939. vblwait->request.sequence);
  940. } else {
  941. list_add_tail(&e->base.link, &dev->vblank_event_list);
  942. vblwait->reply.sequence = vblwait->request.sequence;
  943. }
  944. spin_unlock_irqrestore(&dev->event_lock, flags);
  945. return 0;
  946. err_unlock:
  947. spin_unlock_irqrestore(&dev->event_lock, flags);
  948. kfree(e);
  949. err_put:
  950. drm_vblank_put(dev, pipe);
  951. return ret;
  952. }
  953. /**
  954. * Wait for VBLANK.
  955. *
  956. * \param inode device inode.
  957. * \param file_priv DRM file private.
  958. * \param cmd command.
  959. * \param data user argument, pointing to a drm_wait_vblank structure.
  960. * \return zero on success or a negative number on failure.
  961. *
  962. * This function enables the vblank interrupt on the pipe requested, then
  963. * sleeps waiting for the requested sequence number to occur, and drops
  964. * the vblank interrupt refcount afterwards. (vblank irq disable follows that
  965. * after a timeout with no further vblank waits scheduled).
  966. */
  967. int drm_wait_vblank(struct drm_device *dev, void *data,
  968. struct drm_file *file_priv)
  969. {
  970. union drm_wait_vblank *vblwait = data;
  971. int ret = 0;
  972. unsigned int flags, seq, crtc;
  973. if ((!drm_dev_to_irq(dev)) || (!dev->irq_enabled))
  974. return -EINVAL;
  975. if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
  976. return -EINVAL;
  977. if (vblwait->request.type &
  978. ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK)) {
  979. DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
  980. vblwait->request.type,
  981. (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK));
  982. return -EINVAL;
  983. }
  984. flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
  985. crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
  986. if (crtc >= dev->num_crtcs)
  987. return -EINVAL;
  988. ret = drm_vblank_get(dev, crtc);
  989. if (ret) {
  990. DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
  991. return ret;
  992. }
  993. seq = drm_vblank_count(dev, crtc);
  994. switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
  995. case _DRM_VBLANK_RELATIVE:
  996. vblwait->request.sequence += seq;
  997. vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
  998. case _DRM_VBLANK_ABSOLUTE:
  999. break;
  1000. default:
  1001. ret = -EINVAL;
  1002. goto done;
  1003. }
  1004. if (flags & _DRM_VBLANK_EVENT)
  1005. return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
  1006. if ((flags & _DRM_VBLANK_NEXTONMISS) &&
  1007. (seq - vblwait->request.sequence) <= (1<<23)) {
  1008. vblwait->request.sequence = seq + 1;
  1009. }
  1010. DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
  1011. vblwait->request.sequence, crtc);
  1012. dev->last_vblank_wait[crtc] = vblwait->request.sequence;
  1013. DRM_WAIT_ON(ret, dev->vbl_queue[crtc], 3 * DRM_HZ,
  1014. (((drm_vblank_count(dev, crtc) -
  1015. vblwait->request.sequence) <= (1 << 23)) ||
  1016. !dev->irq_enabled));
  1017. if (ret != -EINTR) {
  1018. struct timeval now;
  1019. vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
  1020. vblwait->reply.tval_sec = now.tv_sec;
  1021. vblwait->reply.tval_usec = now.tv_usec;
  1022. DRM_DEBUG("returning %d to client\n",
  1023. vblwait->reply.sequence);
  1024. } else {
  1025. DRM_DEBUG("vblank wait interrupted by signal\n");
  1026. }
  1027. done:
  1028. drm_vblank_put(dev, crtc);
  1029. return ret;
  1030. }
  1031. void drm_handle_vblank_events(struct drm_device *dev, int crtc)
  1032. {
  1033. struct drm_pending_vblank_event *e, *t;
  1034. struct timeval now;
  1035. unsigned long flags;
  1036. unsigned int seq;
  1037. seq = drm_vblank_count_and_time(dev, crtc, &now);
  1038. spin_lock_irqsave(&dev->event_lock, flags);
  1039. list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
  1040. if (e->pipe != crtc)
  1041. continue;
  1042. if ((seq - e->event.sequence) > (1<<23))
  1043. continue;
  1044. DRM_DEBUG("vblank event on %d, current %d\n",
  1045. e->event.sequence, seq);
  1046. e->event.sequence = seq;
  1047. e->event.tv_sec = now.tv_sec;
  1048. e->event.tv_usec = now.tv_usec;
  1049. drm_vblank_put(dev, e->pipe);
  1050. list_move_tail(&e->base.link, &e->base.file_priv->event_list);
  1051. wake_up_interruptible(&e->base.file_priv->event_wait);
  1052. trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
  1053. e->event.sequence);
  1054. }
  1055. spin_unlock_irqrestore(&dev->event_lock, flags);
  1056. trace_drm_vblank_event(crtc, seq);
  1057. }
  1058. /**
  1059. * drm_handle_vblank - handle a vblank event
  1060. * @dev: DRM device
  1061. * @crtc: where this event occurred
  1062. *
  1063. * Drivers should call this routine in their vblank interrupt handlers to
  1064. * update the vblank counter and send any signals that may be pending.
  1065. */
  1066. bool drm_handle_vblank(struct drm_device *dev, int crtc)
  1067. {
  1068. u32 vblcount;
  1069. s64 diff_ns;
  1070. struct timeval tvblank;
  1071. unsigned long irqflags;
  1072. if (!dev->num_crtcs)
  1073. return false;
  1074. /* Need timestamp lock to prevent concurrent execution with
  1075. * vblank enable/disable, as this would cause inconsistent
  1076. * or corrupted timestamps and vblank counts.
  1077. */
  1078. spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
  1079. /* Vblank irq handling disabled. Nothing to do. */
  1080. if (!dev->vblank_enabled[crtc]) {
  1081. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  1082. return false;
  1083. }
  1084. /* Fetch corresponding timestamp for this vblank interval from
  1085. * driver and store it in proper slot of timestamp ringbuffer.
  1086. */
  1087. /* Get current timestamp and count. */
  1088. vblcount = atomic_read(&dev->_vblank_count[crtc]);
  1089. drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
  1090. /* Compute time difference to timestamp of last vblank */
  1091. diff_ns = timeval_to_ns(&tvblank) -
  1092. timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
  1093. /* Update vblank timestamp and count if at least
  1094. * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
  1095. * difference between last stored timestamp and current
  1096. * timestamp. A smaller difference means basically
  1097. * identical timestamps. Happens if this vblank has
  1098. * been already processed and this is a redundant call,
  1099. * e.g., due to spurious vblank interrupts. We need to
  1100. * ignore those for accounting.
  1101. */
  1102. if (abs(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
  1103. /* Store new timestamp in ringbuffer. */
  1104. vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
  1105. smp_wmb();
  1106. /* Increment cooked vblank count. This also atomically commits
  1107. * the timestamp computed above.
  1108. */
  1109. atomic_inc(&dev->_vblank_count[crtc]);
  1110. } else {
  1111. DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
  1112. crtc, (int) diff_ns);
  1113. }
  1114. DRM_WAKEUP(&dev->vbl_queue[crtc]);
  1115. drm_handle_vblank_events(dev, crtc);
  1116. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  1117. return true;
  1118. }
  1119. EXPORT_SYMBOL(drm_handle_vblank);