drm_irq.c 39 KB

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