drm_irq.c 40 KB

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