drm_irq.c 41 KB

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