drm_irq.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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 <drm/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. int count = DRM_TIMESTAMP_MAXRETRIES;
  97. /* Prevent vblank irq processing while disabling vblank irqs,
  98. * so no updates of timestamps or count can happen after we've
  99. * disabled. Needed to prevent races in case of delayed irq's.
  100. */
  101. spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
  102. dev->driver->disable_vblank(dev, crtc);
  103. dev->vblank_enabled[crtc] = 0;
  104. /* No further vblank irq's will be processed after
  105. * this point. Get current hardware vblank count and
  106. * vblank timestamp, repeat until they are consistent.
  107. *
  108. * FIXME: There is still a race condition here and in
  109. * drm_update_vblank_count() which can cause off-by-one
  110. * reinitialization of software vblank counter. If gpu
  111. * vblank counter doesn't increment exactly at the leading
  112. * edge of a vblank interval, then we can lose 1 count if
  113. * we happen to execute between start of vblank and the
  114. * delayed gpu counter increment.
  115. */
  116. do {
  117. dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc);
  118. vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0);
  119. } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc) && (--count) && vblrc);
  120. if (!count)
  121. vblrc = 0;
  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. }
  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_sync(&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 irq_preinstall() and \c irq_postinstall() functions
  263. * before and after the installation.
  264. */
  265. int drm_irq_install(struct drm_device *dev)
  266. {
  267. int ret;
  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 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. if (dev->num_crtcs) {
  342. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  343. for (i = 0; i < dev->num_crtcs; i++) {
  344. DRM_WAKEUP(&dev->vbl_queue[i]);
  345. dev->vblank_enabled[i] = 0;
  346. dev->last_vblank[i] =
  347. dev->driver->get_vblank_counter(dev, i);
  348. }
  349. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  350. }
  351. if (!irq_enabled)
  352. return -EINVAL;
  353. DRM_DEBUG("irq=%d\n", drm_dev_to_irq(dev));
  354. if (!drm_core_check_feature(dev, DRIVER_MODESET))
  355. vga_client_register(dev->pdev, NULL, NULL, NULL);
  356. if (dev->driver->irq_uninstall)
  357. dev->driver->irq_uninstall(dev);
  358. free_irq(drm_dev_to_irq(dev), dev);
  359. return 0;
  360. }
  361. EXPORT_SYMBOL(drm_irq_uninstall);
  362. /**
  363. * IRQ control ioctl.
  364. *
  365. * \param inode device inode.
  366. * \param file_priv DRM file private.
  367. * \param cmd command.
  368. * \param arg user argument, pointing to a drm_control structure.
  369. * \return zero on success or a negative number on failure.
  370. *
  371. * Calls irq_install() or irq_uninstall() according to \p arg.
  372. */
  373. int drm_control(struct drm_device *dev, void *data,
  374. struct drm_file *file_priv)
  375. {
  376. struct drm_control *ctl = data;
  377. /* if we haven't irq we fallback for compatibility reasons -
  378. * this used to be a separate function in drm_dma.h
  379. */
  380. switch (ctl->func) {
  381. case DRM_INST_HANDLER:
  382. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  383. return 0;
  384. if (drm_core_check_feature(dev, DRIVER_MODESET))
  385. return 0;
  386. if (dev->if_version < DRM_IF_VERSION(1, 2) &&
  387. ctl->irq != drm_dev_to_irq(dev))
  388. return -EINVAL;
  389. return drm_irq_install(dev);
  390. case DRM_UNINST_HANDLER:
  391. if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  392. return 0;
  393. if (drm_core_check_feature(dev, DRIVER_MODESET))
  394. return 0;
  395. return drm_irq_uninstall(dev);
  396. default:
  397. return -EINVAL;
  398. }
  399. }
  400. /**
  401. * drm_calc_timestamping_constants - Calculate and
  402. * store various constants which are later needed by
  403. * vblank and swap-completion timestamping, e.g, by
  404. * drm_calc_vbltimestamp_from_scanoutpos().
  405. * They are derived from crtc's true scanout timing,
  406. * so they take things like panel scaling or other
  407. * adjustments into account.
  408. *
  409. * @crtc drm_crtc whose timestamp constants should be updated.
  410. *
  411. */
  412. void drm_calc_timestamping_constants(struct drm_crtc *crtc)
  413. {
  414. s64 linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0;
  415. u64 dotclock;
  416. /* Dot clock in Hz: */
  417. dotclock = (u64) crtc->hwmode.clock * 1000;
  418. /* Fields of interlaced scanout modes are only halve a frame duration.
  419. * Double the dotclock to get halve the frame-/line-/pixelduration.
  420. */
  421. if (crtc->hwmode.flags & DRM_MODE_FLAG_INTERLACE)
  422. dotclock *= 2;
  423. /* Valid dotclock? */
  424. if (dotclock > 0) {
  425. int frame_size;
  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. frame_size = crtc->hwmode.crtc_htotal *
  434. crtc->hwmode.crtc_vtotal;
  435. framedur_ns = (s64) div64_u64((u64) frame_size * 1000000000,
  436. dotclock);
  437. } else
  438. DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n",
  439. crtc->base.id);
  440. crtc->pixeldur_ns = pixeldur_ns;
  441. crtc->linedur_ns = linedur_ns;
  442. crtc->framedur_ns = framedur_ns;
  443. DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
  444. crtc->base.id, crtc->hwmode.crtc_htotal,
  445. crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay);
  446. DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n",
  447. crtc->base.id, (int) dotclock/1000, (int) framedur_ns,
  448. (int) linedur_ns, (int) pixeldur_ns);
  449. }
  450. EXPORT_SYMBOL(drm_calc_timestamping_constants);
  451. /**
  452. * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms
  453. * drivers. Implements calculation of exact vblank timestamps from
  454. * given drm_display_mode timings and current video scanout position
  455. * of a crtc. This can be called from within get_vblank_timestamp()
  456. * implementation of a kms driver to implement the actual timestamping.
  457. *
  458. * Should return timestamps conforming to the OML_sync_control OpenML
  459. * extension specification. The timestamp corresponds to the end of
  460. * the vblank interval, aka start of scanout of topmost-leftmost display
  461. * pixel in the following video frame.
  462. *
  463. * Requires support for optional dev->driver->get_scanout_position()
  464. * in kms driver, plus a bit of setup code to provide a drm_display_mode
  465. * that corresponds to the true scanout timing.
  466. *
  467. * The current implementation only handles standard video modes. It
  468. * returns as no operation if a doublescan or interlaced video mode is
  469. * active. Higher level code is expected to handle this.
  470. *
  471. * @dev: DRM device.
  472. * @crtc: Which crtc's vblank timestamp to retrieve.
  473. * @max_error: Desired maximum allowable error in timestamps (nanosecs).
  474. * On return contains true maximum error of timestamp.
  475. * @vblank_time: Pointer to struct timeval which should receive the timestamp.
  476. * @flags: Flags to pass to driver:
  477. * 0 = Default.
  478. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
  479. * @refcrtc: drm_crtc* of crtc which defines scanout timing.
  480. *
  481. * Returns negative value on error, failure or if not supported in current
  482. * video mode:
  483. *
  484. * -EINVAL - Invalid crtc.
  485. * -EAGAIN - Temporary unavailable, e.g., called before initial modeset.
  486. * -ENOTSUPP - Function not supported in current display mode.
  487. * -EIO - Failed, e.g., due to failed scanout position query.
  488. *
  489. * Returns or'ed positive status flags on success:
  490. *
  491. * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping.
  492. * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval.
  493. *
  494. */
  495. int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc,
  496. int *max_error,
  497. struct timeval *vblank_time,
  498. unsigned flags,
  499. struct drm_crtc *refcrtc)
  500. {
  501. ktime_t stime, etime, mono_time_offset;
  502. struct timeval tv_etime;
  503. struct drm_display_mode *mode;
  504. int vbl_status, vtotal, vdisplay;
  505. int vpos, hpos, i;
  506. s64 framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns;
  507. bool invbl;
  508. if (crtc < 0 || crtc >= dev->num_crtcs) {
  509. DRM_ERROR("Invalid crtc %d\n", crtc);
  510. return -EINVAL;
  511. }
  512. /* Scanout position query not supported? Should not happen. */
  513. if (!dev->driver->get_scanout_position) {
  514. DRM_ERROR("Called from driver w/o get_scanout_position()!?\n");
  515. return -EIO;
  516. }
  517. mode = &refcrtc->hwmode;
  518. vtotal = mode->crtc_vtotal;
  519. vdisplay = mode->crtc_vdisplay;
  520. /* Durations of frames, lines, pixels in nanoseconds. */
  521. framedur_ns = refcrtc->framedur_ns;
  522. linedur_ns = refcrtc->linedur_ns;
  523. pixeldur_ns = refcrtc->pixeldur_ns;
  524. /* If mode timing undefined, just return as no-op:
  525. * Happens during initial modesetting of a crtc.
  526. */
  527. if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) {
  528. DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc);
  529. return -EAGAIN;
  530. }
  531. /* Get current scanout position with system timestamp.
  532. * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
  533. * if single query takes longer than max_error nanoseconds.
  534. *
  535. * This guarantees a tight bound on maximum error if
  536. * code gets preempted or delayed for some reason.
  537. */
  538. for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
  539. /* Disable preemption to make it very likely to
  540. * succeed in the first iteration even on PREEMPT_RT kernel.
  541. */
  542. preempt_disable();
  543. /* Get system timestamp before query. */
  544. stime = ktime_get();
  545. /* Get vertical and horizontal scanout pos. vpos, hpos. */
  546. vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos);
  547. /* Get system timestamp after query. */
  548. etime = ktime_get();
  549. if (!drm_timestamp_monotonic)
  550. mono_time_offset = ktime_get_monotonic_offset();
  551. preempt_enable();
  552. /* Return as no-op if scanout query unsupported or failed. */
  553. if (!(vbl_status & DRM_SCANOUTPOS_VALID)) {
  554. DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n",
  555. crtc, vbl_status);
  556. return -EIO;
  557. }
  558. duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
  559. /* Accept result with < max_error nsecs timing uncertainty. */
  560. if (duration_ns <= (s64) *max_error)
  561. break;
  562. }
  563. /* Noisy system timing? */
  564. if (i == DRM_TIMESTAMP_MAXRETRIES) {
  565. DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n",
  566. crtc, (int) duration_ns/1000, *max_error/1000, i);
  567. }
  568. /* Return upper bound of timestamp precision error. */
  569. *max_error = (int) duration_ns;
  570. /* Check if in vblank area:
  571. * vpos is >=0 in video scanout area, but negative
  572. * within vblank area, counting down the number of lines until
  573. * start of scanout.
  574. */
  575. invbl = vbl_status & DRM_SCANOUTPOS_INVBL;
  576. /* Convert scanout position into elapsed time at raw_time query
  577. * since start of scanout at first display scanline. delta_ns
  578. * can be negative if start of scanout hasn't happened yet.
  579. */
  580. delta_ns = (s64) vpos * linedur_ns + (s64) hpos * pixeldur_ns;
  581. /* Is vpos outside nominal vblank area, but less than
  582. * 1/100 of a frame height away from start of vblank?
  583. * If so, assume this isn't a massively delayed vblank
  584. * interrupt, but a vblank interrupt that fired a few
  585. * microseconds before true start of vblank. Compensate
  586. * by adding a full frame duration to the final timestamp.
  587. * Happens, e.g., on ATI R500, R600.
  588. *
  589. * We only do this if DRM_CALLED_FROM_VBLIRQ.
  590. */
  591. if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl &&
  592. ((vdisplay - vpos) < vtotal / 100)) {
  593. delta_ns = delta_ns - framedur_ns;
  594. /* Signal this correction as "applied". */
  595. vbl_status |= 0x8;
  596. }
  597. if (!drm_timestamp_monotonic)
  598. etime = ktime_sub(etime, mono_time_offset);
  599. /* save this only for debugging purposes */
  600. tv_etime = ktime_to_timeval(etime);
  601. /* Subtract time delta from raw timestamp to get final
  602. * vblank_time timestamp for end of vblank.
  603. */
  604. etime = ktime_sub_ns(etime, delta_ns);
  605. *vblank_time = ktime_to_timeval(etime);
  606. DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %ld.%ld -> %ld.%ld [e %d us, %d rep]\n",
  607. crtc, (int)vbl_status, hpos, vpos,
  608. (long)tv_etime.tv_sec, (long)tv_etime.tv_usec,
  609. (long)vblank_time->tv_sec, (long)vblank_time->tv_usec,
  610. (int)duration_ns/1000, i);
  611. vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD;
  612. if (invbl)
  613. vbl_status |= DRM_VBLANKTIME_INVBL;
  614. return vbl_status;
  615. }
  616. EXPORT_SYMBOL(drm_calc_vbltimestamp_from_scanoutpos);
  617. static struct timeval get_drm_timestamp(void)
  618. {
  619. ktime_t now;
  620. now = ktime_get();
  621. if (!drm_timestamp_monotonic)
  622. now = ktime_sub(now, ktime_get_monotonic_offset());
  623. return ktime_to_timeval(now);
  624. }
  625. /**
  626. * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent
  627. * vblank interval.
  628. *
  629. * @dev: DRM device
  630. * @crtc: which crtc's vblank timestamp to retrieve
  631. * @tvblank: Pointer to target struct timeval which should receive the timestamp
  632. * @flags: Flags to pass to driver:
  633. * 0 = Default.
  634. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler.
  635. *
  636. * Fetches the system timestamp corresponding to the time of the most recent
  637. * vblank interval on specified crtc. May call into kms-driver to
  638. * compute the timestamp with a high-precision GPU specific method.
  639. *
  640. * Returns zero if timestamp originates from uncorrected do_gettimeofday()
  641. * call, i.e., it isn't very precisely locked to the true vblank.
  642. *
  643. * Returns non-zero if timestamp is considered to be very precise.
  644. */
  645. u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc,
  646. struct timeval *tvblank, unsigned flags)
  647. {
  648. int ret;
  649. /* Define requested maximum error on timestamps (nanoseconds). */
  650. int max_error = (int) drm_timestamp_precision * 1000;
  651. /* Query driver if possible and precision timestamping enabled. */
  652. if (dev->driver->get_vblank_timestamp && (max_error > 0)) {
  653. ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error,
  654. tvblank, flags);
  655. if (ret > 0)
  656. return (u32) ret;
  657. }
  658. /* GPU high precision timestamp query unsupported or failed.
  659. * Return current monotonic/gettimeofday timestamp as best estimate.
  660. */
  661. *tvblank = get_drm_timestamp();
  662. return 0;
  663. }
  664. EXPORT_SYMBOL(drm_get_last_vbltimestamp);
  665. /**
  666. * drm_vblank_count - retrieve "cooked" vblank counter value
  667. * @dev: DRM device
  668. * @crtc: which counter to retrieve
  669. *
  670. * Fetches the "cooked" vblank count value that represents the number of
  671. * vblank events since the system was booted, including lost events due to
  672. * modesetting activity.
  673. */
  674. u32 drm_vblank_count(struct drm_device *dev, int crtc)
  675. {
  676. return atomic_read(&dev->_vblank_count[crtc]);
  677. }
  678. EXPORT_SYMBOL(drm_vblank_count);
  679. /**
  680. * drm_vblank_count_and_time - retrieve "cooked" vblank counter value
  681. * and the system timestamp corresponding to that vblank counter value.
  682. *
  683. * @dev: DRM device
  684. * @crtc: which counter to retrieve
  685. * @vblanktime: Pointer to struct timeval to receive the vblank timestamp.
  686. *
  687. * Fetches the "cooked" vblank count value that represents the number of
  688. * vblank events since the system was booted, including lost events due to
  689. * modesetting activity. Returns corresponding system timestamp of the time
  690. * of the vblank interval that corresponds to the current value vblank counter
  691. * value.
  692. */
  693. u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc,
  694. struct timeval *vblanktime)
  695. {
  696. u32 cur_vblank;
  697. /* Read timestamp from slot of _vblank_time ringbuffer
  698. * that corresponds to current vblank count. Retry if
  699. * count has incremented during readout. This works like
  700. * a seqlock.
  701. */
  702. do {
  703. cur_vblank = atomic_read(&dev->_vblank_count[crtc]);
  704. *vblanktime = vblanktimestamp(dev, crtc, cur_vblank);
  705. smp_rmb();
  706. } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc]));
  707. return cur_vblank;
  708. }
  709. EXPORT_SYMBOL(drm_vblank_count_and_time);
  710. static void send_vblank_event(struct drm_device *dev,
  711. struct drm_pending_vblank_event *e,
  712. unsigned long seq, struct timeval *now)
  713. {
  714. WARN_ON_SMP(!spin_is_locked(&dev->event_lock));
  715. e->event.sequence = seq;
  716. e->event.tv_sec = now->tv_sec;
  717. e->event.tv_usec = now->tv_usec;
  718. list_add_tail(&e->base.link,
  719. &e->base.file_priv->event_list);
  720. wake_up_interruptible(&e->base.file_priv->event_wait);
  721. trace_drm_vblank_event_delivered(e->base.pid, e->pipe,
  722. e->event.sequence);
  723. }
  724. /**
  725. * drm_send_vblank_event - helper to send vblank event after pageflip
  726. * @dev: DRM device
  727. * @crtc: CRTC in question
  728. * @e: the event to send
  729. *
  730. * Updates sequence # and timestamp on event, and sends it to userspace.
  731. * Caller must hold event lock.
  732. */
  733. void drm_send_vblank_event(struct drm_device *dev, int crtc,
  734. struct drm_pending_vblank_event *e)
  735. {
  736. struct timeval now;
  737. unsigned int seq;
  738. if (crtc >= 0) {
  739. seq = drm_vblank_count_and_time(dev, crtc, &now);
  740. } else {
  741. seq = 0;
  742. now = get_drm_timestamp();
  743. }
  744. e->pipe = crtc;
  745. send_vblank_event(dev, e, seq, &now);
  746. }
  747. EXPORT_SYMBOL(drm_send_vblank_event);
  748. /**
  749. * drm_update_vblank_count - update the master vblank counter
  750. * @dev: DRM device
  751. * @crtc: counter to update
  752. *
  753. * Call back into the driver to update the appropriate vblank counter
  754. * (specified by @crtc). Deal with wraparound, if it occurred, and
  755. * update the last read value so we can deal with wraparound on the next
  756. * call if necessary.
  757. *
  758. * Only necessary when going from off->on, to account for frames we
  759. * didn't get an interrupt for.
  760. *
  761. * Note: caller must hold dev->vbl_lock since this reads & writes
  762. * device vblank fields.
  763. */
  764. static void drm_update_vblank_count(struct drm_device *dev, int crtc)
  765. {
  766. u32 cur_vblank, diff, tslot, rc;
  767. struct timeval t_vblank;
  768. /*
  769. * Interrupts were disabled prior to this call, so deal with counter
  770. * wrap if needed.
  771. * NOTE! It's possible we lost a full dev->max_vblank_count events
  772. * here if the register is small or we had vblank interrupts off for
  773. * a long time.
  774. *
  775. * We repeat the hardware vblank counter & timestamp query until
  776. * we get consistent results. This to prevent races between gpu
  777. * updating its hardware counter while we are retrieving the
  778. * corresponding vblank timestamp.
  779. */
  780. do {
  781. cur_vblank = dev->driver->get_vblank_counter(dev, crtc);
  782. rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0);
  783. } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc));
  784. /* Deal with counter wrap */
  785. diff = cur_vblank - dev->last_vblank[crtc];
  786. if (cur_vblank < dev->last_vblank[crtc]) {
  787. diff += dev->max_vblank_count;
  788. DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n",
  789. crtc, dev->last_vblank[crtc], cur_vblank, diff);
  790. }
  791. DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n",
  792. crtc, diff);
  793. /* Reinitialize corresponding vblank timestamp if high-precision query
  794. * available. Skip this step if query unsupported or failed. Will
  795. * reinitialize delayed at next vblank interrupt in that case.
  796. */
  797. if (rc) {
  798. tslot = atomic_read(&dev->_vblank_count[crtc]) + diff;
  799. vblanktimestamp(dev, crtc, tslot) = t_vblank;
  800. }
  801. smp_mb__before_atomic_inc();
  802. atomic_add(diff, &dev->_vblank_count[crtc]);
  803. smp_mb__after_atomic_inc();
  804. }
  805. /**
  806. * drm_vblank_get - get a reference count on vblank events
  807. * @dev: DRM device
  808. * @crtc: which CRTC to own
  809. *
  810. * Acquire a reference count on vblank events to avoid having them disabled
  811. * while in use.
  812. *
  813. * RETURNS
  814. * Zero on success, nonzero on failure.
  815. */
  816. int drm_vblank_get(struct drm_device *dev, int crtc)
  817. {
  818. unsigned long irqflags, irqflags2;
  819. int ret = 0;
  820. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  821. /* Going from 0->1 means we have to enable interrupts again */
  822. if (atomic_add_return(1, &dev->vblank_refcount[crtc]) == 1) {
  823. spin_lock_irqsave(&dev->vblank_time_lock, irqflags2);
  824. if (!dev->vblank_enabled[crtc]) {
  825. /* Enable vblank irqs under vblank_time_lock protection.
  826. * All vblank count & timestamp updates are held off
  827. * until we are done reinitializing master counter and
  828. * timestamps. Filtercode in drm_handle_vblank() will
  829. * prevent double-accounting of same vblank interval.
  830. */
  831. ret = dev->driver->enable_vblank(dev, crtc);
  832. DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n",
  833. crtc, ret);
  834. if (ret)
  835. atomic_dec(&dev->vblank_refcount[crtc]);
  836. else {
  837. dev->vblank_enabled[crtc] = 1;
  838. drm_update_vblank_count(dev, crtc);
  839. }
  840. }
  841. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags2);
  842. } else {
  843. if (!dev->vblank_enabled[crtc]) {
  844. atomic_dec(&dev->vblank_refcount[crtc]);
  845. ret = -EINVAL;
  846. }
  847. }
  848. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  849. return ret;
  850. }
  851. EXPORT_SYMBOL(drm_vblank_get);
  852. /**
  853. * drm_vblank_put - give up ownership of vblank events
  854. * @dev: DRM device
  855. * @crtc: which counter to give up
  856. *
  857. * Release ownership of a given vblank counter, turning off interrupts
  858. * if possible. Disable interrupts after drm_vblank_offdelay milliseconds.
  859. */
  860. void drm_vblank_put(struct drm_device *dev, int crtc)
  861. {
  862. BUG_ON(atomic_read(&dev->vblank_refcount[crtc]) == 0);
  863. /* Last user schedules interrupt disable */
  864. if (atomic_dec_and_test(&dev->vblank_refcount[crtc]) &&
  865. (drm_vblank_offdelay > 0))
  866. mod_timer(&dev->vblank_disable_timer,
  867. jiffies + ((drm_vblank_offdelay * DRM_HZ)/1000));
  868. }
  869. EXPORT_SYMBOL(drm_vblank_put);
  870. /**
  871. * drm_vblank_off - disable vblank events on a CRTC
  872. * @dev: DRM device
  873. * @crtc: CRTC in question
  874. *
  875. * Caller must hold event lock.
  876. */
  877. void drm_vblank_off(struct drm_device *dev, int crtc)
  878. {
  879. struct drm_pending_vblank_event *e, *t;
  880. struct timeval now;
  881. unsigned long irqflags;
  882. unsigned int seq;
  883. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  884. vblank_disable_and_save(dev, crtc);
  885. DRM_WAKEUP(&dev->vbl_queue[crtc]);
  886. /* Send any queued vblank events, lest the natives grow disquiet */
  887. seq = drm_vblank_count_and_time(dev, crtc, &now);
  888. spin_lock(&dev->event_lock);
  889. list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
  890. if (e->pipe != crtc)
  891. continue;
  892. DRM_DEBUG("Sending premature vblank event on disable: \
  893. wanted %d, current %d\n",
  894. e->event.sequence, seq);
  895. list_del(&e->base.link);
  896. drm_vblank_put(dev, e->pipe);
  897. send_vblank_event(dev, e, seq, &now);
  898. }
  899. spin_unlock(&dev->event_lock);
  900. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  901. }
  902. EXPORT_SYMBOL(drm_vblank_off);
  903. /**
  904. * drm_vblank_pre_modeset - account for vblanks across mode sets
  905. * @dev: DRM device
  906. * @crtc: CRTC in question
  907. *
  908. * Account for vblank events across mode setting events, which will likely
  909. * reset the hardware frame counter.
  910. */
  911. void drm_vblank_pre_modeset(struct drm_device *dev, int crtc)
  912. {
  913. /* vblank is not initialized (IRQ not installed ?), or has been freed */
  914. if (!dev->num_crtcs)
  915. return;
  916. /*
  917. * To avoid all the problems that might happen if interrupts
  918. * were enabled/disabled around or between these calls, we just
  919. * have the kernel take a reference on the CRTC (just once though
  920. * to avoid corrupting the count if multiple, mismatch calls occur),
  921. * so that interrupts remain enabled in the interim.
  922. */
  923. if (!dev->vblank_inmodeset[crtc]) {
  924. dev->vblank_inmodeset[crtc] = 0x1;
  925. if (drm_vblank_get(dev, crtc) == 0)
  926. dev->vblank_inmodeset[crtc] |= 0x2;
  927. }
  928. }
  929. EXPORT_SYMBOL(drm_vblank_pre_modeset);
  930. void drm_vblank_post_modeset(struct drm_device *dev, int crtc)
  931. {
  932. unsigned long irqflags;
  933. /* vblank is not initialized (IRQ not installed ?), or has been freed */
  934. if (!dev->num_crtcs)
  935. return;
  936. if (dev->vblank_inmodeset[crtc]) {
  937. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  938. dev->vblank_disable_allowed = 1;
  939. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  940. if (dev->vblank_inmodeset[crtc] & 0x2)
  941. drm_vblank_put(dev, crtc);
  942. dev->vblank_inmodeset[crtc] = 0;
  943. }
  944. }
  945. EXPORT_SYMBOL(drm_vblank_post_modeset);
  946. /**
  947. * drm_modeset_ctl - handle vblank event counter changes across mode switch
  948. * @DRM_IOCTL_ARGS: standard ioctl arguments
  949. *
  950. * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET
  951. * ioctls around modesetting so that any lost vblank events are accounted for.
  952. *
  953. * Generally the counter will reset across mode sets. If interrupts are
  954. * enabled around this call, we don't have to do anything since the counter
  955. * will have already been incremented.
  956. */
  957. int drm_modeset_ctl(struct drm_device *dev, void *data,
  958. struct drm_file *file_priv)
  959. {
  960. struct drm_modeset_ctl *modeset = data;
  961. unsigned int crtc;
  962. /* If drm_vblank_init() hasn't been called yet, just no-op */
  963. if (!dev->num_crtcs)
  964. return 0;
  965. /* KMS drivers handle this internally */
  966. if (drm_core_check_feature(dev, DRIVER_MODESET))
  967. return 0;
  968. crtc = modeset->crtc;
  969. if (crtc >= dev->num_crtcs)
  970. return -EINVAL;
  971. switch (modeset->cmd) {
  972. case _DRM_PRE_MODESET:
  973. drm_vblank_pre_modeset(dev, crtc);
  974. break;
  975. case _DRM_POST_MODESET:
  976. drm_vblank_post_modeset(dev, crtc);
  977. break;
  978. default:
  979. return -EINVAL;
  980. }
  981. return 0;
  982. }
  983. static int drm_queue_vblank_event(struct drm_device *dev, int pipe,
  984. union drm_wait_vblank *vblwait,
  985. struct drm_file *file_priv)
  986. {
  987. struct drm_pending_vblank_event *e;
  988. struct timeval now;
  989. unsigned long flags;
  990. unsigned int seq;
  991. int ret;
  992. e = kzalloc(sizeof *e, GFP_KERNEL);
  993. if (e == NULL) {
  994. ret = -ENOMEM;
  995. goto err_put;
  996. }
  997. e->pipe = pipe;
  998. e->base.pid = current->pid;
  999. e->event.base.type = DRM_EVENT_VBLANK;
  1000. e->event.base.length = sizeof e->event;
  1001. e->event.user_data = vblwait->request.signal;
  1002. e->base.event = &e->event.base;
  1003. e->base.file_priv = file_priv;
  1004. e->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
  1005. spin_lock_irqsave(&dev->event_lock, flags);
  1006. if (file_priv->event_space < sizeof e->event) {
  1007. ret = -EBUSY;
  1008. goto err_unlock;
  1009. }
  1010. file_priv->event_space -= sizeof e->event;
  1011. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1012. if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) &&
  1013. (seq - vblwait->request.sequence) <= (1 << 23)) {
  1014. vblwait->request.sequence = seq + 1;
  1015. vblwait->reply.sequence = vblwait->request.sequence;
  1016. }
  1017. DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n",
  1018. vblwait->request.sequence, seq, pipe);
  1019. trace_drm_vblank_event_queued(current->pid, pipe,
  1020. vblwait->request.sequence);
  1021. e->event.sequence = vblwait->request.sequence;
  1022. if ((seq - vblwait->request.sequence) <= (1 << 23)) {
  1023. drm_vblank_put(dev, pipe);
  1024. send_vblank_event(dev, e, seq, &now);
  1025. vblwait->reply.sequence = seq;
  1026. } else {
  1027. /* drm_handle_vblank_events will call drm_vblank_put */
  1028. list_add_tail(&e->base.link, &dev->vblank_event_list);
  1029. vblwait->reply.sequence = vblwait->request.sequence;
  1030. }
  1031. spin_unlock_irqrestore(&dev->event_lock, flags);
  1032. return 0;
  1033. err_unlock:
  1034. spin_unlock_irqrestore(&dev->event_lock, flags);
  1035. kfree(e);
  1036. err_put:
  1037. drm_vblank_put(dev, pipe);
  1038. return ret;
  1039. }
  1040. /**
  1041. * Wait for VBLANK.
  1042. *
  1043. * \param inode device inode.
  1044. * \param file_priv DRM file private.
  1045. * \param cmd command.
  1046. * \param data user argument, pointing to a drm_wait_vblank structure.
  1047. * \return zero on success or a negative number on failure.
  1048. *
  1049. * This function enables the vblank interrupt on the pipe requested, then
  1050. * sleeps waiting for the requested sequence number to occur, and drops
  1051. * the vblank interrupt refcount afterwards. (vblank irq disable follows that
  1052. * after a timeout with no further vblank waits scheduled).
  1053. */
  1054. int drm_wait_vblank(struct drm_device *dev, void *data,
  1055. struct drm_file *file_priv)
  1056. {
  1057. union drm_wait_vblank *vblwait = data;
  1058. int ret;
  1059. unsigned int flags, seq, crtc, high_crtc;
  1060. if (drm_core_check_feature(dev, DRIVER_HAVE_IRQ))
  1061. if ((!drm_dev_to_irq(dev)) || (!dev->irq_enabled))
  1062. return -EINVAL;
  1063. if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
  1064. return -EINVAL;
  1065. if (vblwait->request.type &
  1066. ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
  1067. _DRM_VBLANK_HIGH_CRTC_MASK)) {
  1068. DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n",
  1069. vblwait->request.type,
  1070. (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
  1071. _DRM_VBLANK_HIGH_CRTC_MASK));
  1072. return -EINVAL;
  1073. }
  1074. flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
  1075. high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
  1076. if (high_crtc)
  1077. crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
  1078. else
  1079. crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
  1080. if (crtc >= dev->num_crtcs)
  1081. return -EINVAL;
  1082. ret = drm_vblank_get(dev, crtc);
  1083. if (ret) {
  1084. DRM_DEBUG("failed to acquire vblank counter, %d\n", ret);
  1085. return ret;
  1086. }
  1087. seq = drm_vblank_count(dev, crtc);
  1088. switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
  1089. case _DRM_VBLANK_RELATIVE:
  1090. vblwait->request.sequence += seq;
  1091. vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
  1092. case _DRM_VBLANK_ABSOLUTE:
  1093. break;
  1094. default:
  1095. ret = -EINVAL;
  1096. goto done;
  1097. }
  1098. if (flags & _DRM_VBLANK_EVENT) {
  1099. /* must hold on to the vblank ref until the event fires
  1100. * drm_vblank_put will be called asynchronously
  1101. */
  1102. return drm_queue_vblank_event(dev, crtc, vblwait, file_priv);
  1103. }
  1104. if ((flags & _DRM_VBLANK_NEXTONMISS) &&
  1105. (seq - vblwait->request.sequence) <= (1<<23)) {
  1106. vblwait->request.sequence = seq + 1;
  1107. }
  1108. DRM_DEBUG("waiting on vblank count %d, crtc %d\n",
  1109. vblwait->request.sequence, crtc);
  1110. dev->last_vblank_wait[crtc] = vblwait->request.sequence;
  1111. DRM_WAIT_ON(ret, dev->vbl_queue[crtc], 3 * DRM_HZ,
  1112. (((drm_vblank_count(dev, crtc) -
  1113. vblwait->request.sequence) <= (1 << 23)) ||
  1114. !dev->irq_enabled));
  1115. if (ret != -EINTR) {
  1116. struct timeval now;
  1117. vblwait->reply.sequence = drm_vblank_count_and_time(dev, crtc, &now);
  1118. vblwait->reply.tval_sec = now.tv_sec;
  1119. vblwait->reply.tval_usec = now.tv_usec;
  1120. DRM_DEBUG("returning %d to client\n",
  1121. vblwait->reply.sequence);
  1122. } else {
  1123. DRM_DEBUG("vblank wait interrupted by signal\n");
  1124. }
  1125. done:
  1126. drm_vblank_put(dev, crtc);
  1127. return ret;
  1128. }
  1129. static void drm_handle_vblank_events(struct drm_device *dev, int crtc)
  1130. {
  1131. struct drm_pending_vblank_event *e, *t;
  1132. struct timeval now;
  1133. unsigned long flags;
  1134. unsigned int seq;
  1135. seq = drm_vblank_count_and_time(dev, crtc, &now);
  1136. spin_lock_irqsave(&dev->event_lock, flags);
  1137. list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
  1138. if (e->pipe != crtc)
  1139. continue;
  1140. if ((seq - e->event.sequence) > (1<<23))
  1141. continue;
  1142. DRM_DEBUG("vblank event on %d, current %d\n",
  1143. e->event.sequence, seq);
  1144. list_del(&e->base.link);
  1145. drm_vblank_put(dev, e->pipe);
  1146. send_vblank_event(dev, e, seq, &now);
  1147. }
  1148. spin_unlock_irqrestore(&dev->event_lock, flags);
  1149. trace_drm_vblank_event(crtc, seq);
  1150. }
  1151. /**
  1152. * drm_handle_vblank - handle a vblank event
  1153. * @dev: DRM device
  1154. * @crtc: where this event occurred
  1155. *
  1156. * Drivers should call this routine in their vblank interrupt handlers to
  1157. * update the vblank counter and send any signals that may be pending.
  1158. */
  1159. bool drm_handle_vblank(struct drm_device *dev, int crtc)
  1160. {
  1161. u32 vblcount;
  1162. s64 diff_ns;
  1163. struct timeval tvblank;
  1164. unsigned long irqflags;
  1165. if (!dev->num_crtcs)
  1166. return false;
  1167. /* Need timestamp lock to prevent concurrent execution with
  1168. * vblank enable/disable, as this would cause inconsistent
  1169. * or corrupted timestamps and vblank counts.
  1170. */
  1171. spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
  1172. /* Vblank irq handling disabled. Nothing to do. */
  1173. if (!dev->vblank_enabled[crtc]) {
  1174. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  1175. return false;
  1176. }
  1177. /* Fetch corresponding timestamp for this vblank interval from
  1178. * driver and store it in proper slot of timestamp ringbuffer.
  1179. */
  1180. /* Get current timestamp and count. */
  1181. vblcount = atomic_read(&dev->_vblank_count[crtc]);
  1182. drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ);
  1183. /* Compute time difference to timestamp of last vblank */
  1184. diff_ns = timeval_to_ns(&tvblank) -
  1185. timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount));
  1186. /* Update vblank timestamp and count if at least
  1187. * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds
  1188. * difference between last stored timestamp and current
  1189. * timestamp. A smaller difference means basically
  1190. * identical timestamps. Happens if this vblank has
  1191. * been already processed and this is a redundant call,
  1192. * e.g., due to spurious vblank interrupts. We need to
  1193. * ignore those for accounting.
  1194. */
  1195. if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) {
  1196. /* Store new timestamp in ringbuffer. */
  1197. vblanktimestamp(dev, crtc, vblcount + 1) = tvblank;
  1198. /* Increment cooked vblank count. This also atomically commits
  1199. * the timestamp computed above.
  1200. */
  1201. smp_mb__before_atomic_inc();
  1202. atomic_inc(&dev->_vblank_count[crtc]);
  1203. smp_mb__after_atomic_inc();
  1204. } else {
  1205. DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n",
  1206. crtc, (int) diff_ns);
  1207. }
  1208. DRM_WAKEUP(&dev->vbl_queue[crtc]);
  1209. drm_handle_vblank_events(dev, crtc);
  1210. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  1211. return true;
  1212. }
  1213. EXPORT_SYMBOL(drm_handle_vblank);