drm_irq.c 40 KB

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