drm_irq.c 40 KB

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