drm_irq.c 41 KB

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