drm_irq.c 39 KB

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