dma-buf.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. /*
  2. * Framework for buffer objects that can be shared across devices/subsystems.
  3. *
  4. * Copyright(C) 2011 Linaro Limited. All rights reserved.
  5. * Author: Sumit Semwal <sumit.semwal@ti.com>
  6. *
  7. * Many thanks to linaro-mm-sig list, and specially
  8. * Arnd Bergmann <arnd@arndb.de>, Rob Clark <rob@ti.com> and
  9. * Daniel Vetter <daniel@ffwll.ch> for their support in creation and
  10. * refining of this idea.
  11. *
  12. * This program is free software; you can redistribute it and/or modify it
  13. * under the terms of the GNU General Public License version 2 as published by
  14. * the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful, but WITHOUT
  17. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  18. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  19. * more details.
  20. *
  21. * You should have received a copy of the GNU General Public License along with
  22. * this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. #include <linux/fs.h>
  25. #include <linux/slab.h>
  26. #include <linux/dma-buf.h>
  27. #include <linux/dma-fence.h>
  28. #include <linux/anon_inodes.h>
  29. #include <linux/export.h>
  30. #include <linux/debugfs.h>
  31. #include <linux/module.h>
  32. #include <linux/seq_file.h>
  33. #include <linux/poll.h>
  34. #include <linux/reservation.h>
  35. #include <linux/mm.h>
  36. #include <uapi/linux/dma-buf.h>
  37. static inline int is_dma_buf_file(struct file *);
  38. struct dma_buf_list {
  39. struct list_head head;
  40. struct mutex lock;
  41. };
  42. static struct dma_buf_list db_list;
  43. static int dma_buf_release(struct inode *inode, struct file *file)
  44. {
  45. struct dma_buf *dmabuf;
  46. if (!is_dma_buf_file(file))
  47. return -EINVAL;
  48. dmabuf = file->private_data;
  49. BUG_ON(dmabuf->vmapping_counter);
  50. /*
  51. * Any fences that a dma-buf poll can wait on should be signaled
  52. * before releasing dma-buf. This is the responsibility of each
  53. * driver that uses the reservation objects.
  54. *
  55. * If you hit this BUG() it means someone dropped their ref to the
  56. * dma-buf while still having pending operation to the buffer.
  57. */
  58. BUG_ON(dmabuf->cb_shared.active || dmabuf->cb_excl.active);
  59. dmabuf->ops->release(dmabuf);
  60. mutex_lock(&db_list.lock);
  61. list_del(&dmabuf->list_node);
  62. mutex_unlock(&db_list.lock);
  63. if (dmabuf->resv == (struct reservation_object *)&dmabuf[1])
  64. reservation_object_fini(dmabuf->resv);
  65. module_put(dmabuf->owner);
  66. kfree(dmabuf);
  67. return 0;
  68. }
  69. static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
  70. {
  71. struct dma_buf *dmabuf;
  72. if (!is_dma_buf_file(file))
  73. return -EINVAL;
  74. dmabuf = file->private_data;
  75. /* check if buffer supports mmap */
  76. if (!dmabuf->ops->mmap)
  77. return -EINVAL;
  78. /* check for overflowing the buffer's size */
  79. if (vma->vm_pgoff + vma_pages(vma) >
  80. dmabuf->size >> PAGE_SHIFT)
  81. return -EINVAL;
  82. return dmabuf->ops->mmap(dmabuf, vma);
  83. }
  84. static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
  85. {
  86. struct dma_buf *dmabuf;
  87. loff_t base;
  88. if (!is_dma_buf_file(file))
  89. return -EBADF;
  90. dmabuf = file->private_data;
  91. /* only support discovering the end of the buffer,
  92. but also allow SEEK_SET to maintain the idiomatic
  93. SEEK_END(0), SEEK_CUR(0) pattern */
  94. if (whence == SEEK_END)
  95. base = dmabuf->size;
  96. else if (whence == SEEK_SET)
  97. base = 0;
  98. else
  99. return -EINVAL;
  100. if (offset != 0)
  101. return -EINVAL;
  102. return base + offset;
  103. }
  104. /**
  105. * DOC: fence polling
  106. *
  107. * To support cross-device and cross-driver synchronization of buffer access
  108. * implicit fences (represented internally in the kernel with &struct fence) can
  109. * be attached to a &dma_buf. The glue for that and a few related things are
  110. * provided in the &reservation_object structure.
  111. *
  112. * Userspace can query the state of these implicitly tracked fences using poll()
  113. * and related system calls:
  114. *
  115. * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
  116. * most recent write or exclusive fence.
  117. *
  118. * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
  119. * all attached fences, shared and exclusive ones.
  120. *
  121. * Note that this only signals the completion of the respective fences, i.e. the
  122. * DMA transfers are complete. Cache flushing and any other necessary
  123. * preparations before CPU access can begin still need to happen.
  124. */
  125. static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
  126. {
  127. struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
  128. unsigned long flags;
  129. spin_lock_irqsave(&dcb->poll->lock, flags);
  130. wake_up_locked_poll(dcb->poll, dcb->active);
  131. dcb->active = 0;
  132. spin_unlock_irqrestore(&dcb->poll->lock, flags);
  133. }
  134. static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
  135. {
  136. struct dma_buf *dmabuf;
  137. struct reservation_object *resv;
  138. struct reservation_object_list *fobj;
  139. struct dma_fence *fence_excl;
  140. __poll_t events;
  141. unsigned shared_count, seq;
  142. dmabuf = file->private_data;
  143. if (!dmabuf || !dmabuf->resv)
  144. return EPOLLERR;
  145. resv = dmabuf->resv;
  146. poll_wait(file, &dmabuf->poll, poll);
  147. events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
  148. if (!events)
  149. return 0;
  150. retry:
  151. seq = read_seqcount_begin(&resv->seq);
  152. rcu_read_lock();
  153. fobj = rcu_dereference(resv->fence);
  154. if (fobj)
  155. shared_count = fobj->shared_count;
  156. else
  157. shared_count = 0;
  158. fence_excl = rcu_dereference(resv->fence_excl);
  159. if (read_seqcount_retry(&resv->seq, seq)) {
  160. rcu_read_unlock();
  161. goto retry;
  162. }
  163. if (fence_excl && (!(events & EPOLLOUT) || shared_count == 0)) {
  164. struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_excl;
  165. __poll_t pevents = EPOLLIN;
  166. if (shared_count == 0)
  167. pevents |= EPOLLOUT;
  168. spin_lock_irq(&dmabuf->poll.lock);
  169. if (dcb->active) {
  170. dcb->active |= pevents;
  171. events &= ~pevents;
  172. } else
  173. dcb->active = pevents;
  174. spin_unlock_irq(&dmabuf->poll.lock);
  175. if (events & pevents) {
  176. if (!dma_fence_get_rcu(fence_excl)) {
  177. /* force a recheck */
  178. events &= ~pevents;
  179. dma_buf_poll_cb(NULL, &dcb->cb);
  180. } else if (!dma_fence_add_callback(fence_excl, &dcb->cb,
  181. dma_buf_poll_cb)) {
  182. events &= ~pevents;
  183. dma_fence_put(fence_excl);
  184. } else {
  185. /*
  186. * No callback queued, wake up any additional
  187. * waiters.
  188. */
  189. dma_fence_put(fence_excl);
  190. dma_buf_poll_cb(NULL, &dcb->cb);
  191. }
  192. }
  193. }
  194. if ((events & EPOLLOUT) && shared_count > 0) {
  195. struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_shared;
  196. int i;
  197. /* Only queue a new callback if no event has fired yet */
  198. spin_lock_irq(&dmabuf->poll.lock);
  199. if (dcb->active)
  200. events &= ~EPOLLOUT;
  201. else
  202. dcb->active = EPOLLOUT;
  203. spin_unlock_irq(&dmabuf->poll.lock);
  204. if (!(events & EPOLLOUT))
  205. goto out;
  206. for (i = 0; i < shared_count; ++i) {
  207. struct dma_fence *fence = rcu_dereference(fobj->shared[i]);
  208. if (!dma_fence_get_rcu(fence)) {
  209. /*
  210. * fence refcount dropped to zero, this means
  211. * that fobj has been freed
  212. *
  213. * call dma_buf_poll_cb and force a recheck!
  214. */
  215. events &= ~EPOLLOUT;
  216. dma_buf_poll_cb(NULL, &dcb->cb);
  217. break;
  218. }
  219. if (!dma_fence_add_callback(fence, &dcb->cb,
  220. dma_buf_poll_cb)) {
  221. dma_fence_put(fence);
  222. events &= ~EPOLLOUT;
  223. break;
  224. }
  225. dma_fence_put(fence);
  226. }
  227. /* No callback queued, wake up any additional waiters. */
  228. if (i == shared_count)
  229. dma_buf_poll_cb(NULL, &dcb->cb);
  230. }
  231. out:
  232. rcu_read_unlock();
  233. return events;
  234. }
  235. static long dma_buf_ioctl(struct file *file,
  236. unsigned int cmd, unsigned long arg)
  237. {
  238. struct dma_buf *dmabuf;
  239. struct dma_buf_sync sync;
  240. enum dma_data_direction direction;
  241. int ret;
  242. dmabuf = file->private_data;
  243. switch (cmd) {
  244. case DMA_BUF_IOCTL_SYNC:
  245. if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
  246. return -EFAULT;
  247. if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
  248. return -EINVAL;
  249. switch (sync.flags & DMA_BUF_SYNC_RW) {
  250. case DMA_BUF_SYNC_READ:
  251. direction = DMA_FROM_DEVICE;
  252. break;
  253. case DMA_BUF_SYNC_WRITE:
  254. direction = DMA_TO_DEVICE;
  255. break;
  256. case DMA_BUF_SYNC_RW:
  257. direction = DMA_BIDIRECTIONAL;
  258. break;
  259. default:
  260. return -EINVAL;
  261. }
  262. if (sync.flags & DMA_BUF_SYNC_END)
  263. ret = dma_buf_end_cpu_access(dmabuf, direction);
  264. else
  265. ret = dma_buf_begin_cpu_access(dmabuf, direction);
  266. return ret;
  267. default:
  268. return -ENOTTY;
  269. }
  270. }
  271. static const struct file_operations dma_buf_fops = {
  272. .release = dma_buf_release,
  273. .mmap = dma_buf_mmap_internal,
  274. .llseek = dma_buf_llseek,
  275. .poll = dma_buf_poll,
  276. .unlocked_ioctl = dma_buf_ioctl,
  277. #ifdef CONFIG_COMPAT
  278. .compat_ioctl = dma_buf_ioctl,
  279. #endif
  280. };
  281. /*
  282. * is_dma_buf_file - Check if struct file* is associated with dma_buf
  283. */
  284. static inline int is_dma_buf_file(struct file *file)
  285. {
  286. return file->f_op == &dma_buf_fops;
  287. }
  288. /**
  289. * DOC: dma buf device access
  290. *
  291. * For device DMA access to a shared DMA buffer the usual sequence of operations
  292. * is fairly simple:
  293. *
  294. * 1. The exporter defines his exporter instance using
  295. * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
  296. * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
  297. * as a file descriptor by calling dma_buf_fd().
  298. *
  299. * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
  300. * to share with: First the filedescriptor is converted to a &dma_buf using
  301. * dma_buf_get(). Then the buffer is attached to the device using
  302. * dma_buf_attach().
  303. *
  304. * Up to this stage the exporter is still free to migrate or reallocate the
  305. * backing storage.
  306. *
  307. * 3. Once the buffer is attached to all devices userspace can initiate DMA
  308. * access to the shared buffer. In the kernel this is done by calling
  309. * dma_buf_map_attachment() and dma_buf_unmap_attachment().
  310. *
  311. * 4. Once a driver is done with a shared buffer it needs to call
  312. * dma_buf_detach() (after cleaning up any mappings) and then release the
  313. * reference acquired with dma_buf_get by calling dma_buf_put().
  314. *
  315. * For the detailed semantics exporters are expected to implement see
  316. * &dma_buf_ops.
  317. */
  318. /**
  319. * dma_buf_export - Creates a new dma_buf, and associates an anon file
  320. * with this buffer, so it can be exported.
  321. * Also connect the allocator specific data and ops to the buffer.
  322. * Additionally, provide a name string for exporter; useful in debugging.
  323. *
  324. * @exp_info: [in] holds all the export related information provided
  325. * by the exporter. see &struct dma_buf_export_info
  326. * for further details.
  327. *
  328. * Returns, on success, a newly created dma_buf object, which wraps the
  329. * supplied private data and operations for dma_buf_ops. On either missing
  330. * ops, or error in allocating struct dma_buf, will return negative error.
  331. *
  332. * For most cases the easiest way to create @exp_info is through the
  333. * %DEFINE_DMA_BUF_EXPORT_INFO macro.
  334. */
  335. struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
  336. {
  337. struct dma_buf *dmabuf;
  338. struct reservation_object *resv = exp_info->resv;
  339. struct file *file;
  340. size_t alloc_size = sizeof(struct dma_buf);
  341. int ret;
  342. if (!exp_info->resv)
  343. alloc_size += sizeof(struct reservation_object);
  344. else
  345. /* prevent &dma_buf[1] == dma_buf->resv */
  346. alloc_size += 1;
  347. if (WARN_ON(!exp_info->priv
  348. || !exp_info->ops
  349. || !exp_info->ops->map_dma_buf
  350. || !exp_info->ops->unmap_dma_buf
  351. || !exp_info->ops->release)) {
  352. return ERR_PTR(-EINVAL);
  353. }
  354. if (!try_module_get(exp_info->owner))
  355. return ERR_PTR(-ENOENT);
  356. dmabuf = kzalloc(alloc_size, GFP_KERNEL);
  357. if (!dmabuf) {
  358. ret = -ENOMEM;
  359. goto err_module;
  360. }
  361. dmabuf->priv = exp_info->priv;
  362. dmabuf->ops = exp_info->ops;
  363. dmabuf->size = exp_info->size;
  364. dmabuf->exp_name = exp_info->exp_name;
  365. dmabuf->owner = exp_info->owner;
  366. init_waitqueue_head(&dmabuf->poll);
  367. dmabuf->cb_excl.poll = dmabuf->cb_shared.poll = &dmabuf->poll;
  368. dmabuf->cb_excl.active = dmabuf->cb_shared.active = 0;
  369. if (!resv) {
  370. resv = (struct reservation_object *)&dmabuf[1];
  371. reservation_object_init(resv);
  372. }
  373. dmabuf->resv = resv;
  374. file = anon_inode_getfile("dmabuf", &dma_buf_fops, dmabuf,
  375. exp_info->flags);
  376. if (IS_ERR(file)) {
  377. ret = PTR_ERR(file);
  378. goto err_dmabuf;
  379. }
  380. file->f_mode |= FMODE_LSEEK;
  381. dmabuf->file = file;
  382. mutex_init(&dmabuf->lock);
  383. INIT_LIST_HEAD(&dmabuf->attachments);
  384. mutex_lock(&db_list.lock);
  385. list_add(&dmabuf->list_node, &db_list.head);
  386. mutex_unlock(&db_list.lock);
  387. return dmabuf;
  388. err_dmabuf:
  389. kfree(dmabuf);
  390. err_module:
  391. module_put(exp_info->owner);
  392. return ERR_PTR(ret);
  393. }
  394. EXPORT_SYMBOL_GPL(dma_buf_export);
  395. /**
  396. * dma_buf_fd - returns a file descriptor for the given dma_buf
  397. * @dmabuf: [in] pointer to dma_buf for which fd is required.
  398. * @flags: [in] flags to give to fd
  399. *
  400. * On success, returns an associated 'fd'. Else, returns error.
  401. */
  402. int dma_buf_fd(struct dma_buf *dmabuf, int flags)
  403. {
  404. int fd;
  405. if (!dmabuf || !dmabuf->file)
  406. return -EINVAL;
  407. fd = get_unused_fd_flags(flags);
  408. if (fd < 0)
  409. return fd;
  410. fd_install(fd, dmabuf->file);
  411. return fd;
  412. }
  413. EXPORT_SYMBOL_GPL(dma_buf_fd);
  414. /**
  415. * dma_buf_get - returns the dma_buf structure related to an fd
  416. * @fd: [in] fd associated with the dma_buf to be returned
  417. *
  418. * On success, returns the dma_buf structure associated with an fd; uses
  419. * file's refcounting done by fget to increase refcount. returns ERR_PTR
  420. * otherwise.
  421. */
  422. struct dma_buf *dma_buf_get(int fd)
  423. {
  424. struct file *file;
  425. file = fget(fd);
  426. if (!file)
  427. return ERR_PTR(-EBADF);
  428. if (!is_dma_buf_file(file)) {
  429. fput(file);
  430. return ERR_PTR(-EINVAL);
  431. }
  432. return file->private_data;
  433. }
  434. EXPORT_SYMBOL_GPL(dma_buf_get);
  435. /**
  436. * dma_buf_put - decreases refcount of the buffer
  437. * @dmabuf: [in] buffer to reduce refcount of
  438. *
  439. * Uses file's refcounting done implicitly by fput().
  440. *
  441. * If, as a result of this call, the refcount becomes 0, the 'release' file
  442. * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
  443. * in turn, and frees the memory allocated for dmabuf when exported.
  444. */
  445. void dma_buf_put(struct dma_buf *dmabuf)
  446. {
  447. if (WARN_ON(!dmabuf || !dmabuf->file))
  448. return;
  449. fput(dmabuf->file);
  450. }
  451. EXPORT_SYMBOL_GPL(dma_buf_put);
  452. /**
  453. * dma_buf_attach - Add the device to dma_buf's attachments list; optionally,
  454. * calls attach() of dma_buf_ops to allow device-specific attach functionality
  455. * @dmabuf: [in] buffer to attach device to.
  456. * @dev: [in] device to be attached.
  457. *
  458. * Returns struct dma_buf_attachment pointer for this attachment. Attachments
  459. * must be cleaned up by calling dma_buf_detach().
  460. *
  461. * Returns:
  462. *
  463. * A pointer to newly created &dma_buf_attachment on success, or a negative
  464. * error code wrapped into a pointer on failure.
  465. *
  466. * Note that this can fail if the backing storage of @dmabuf is in a place not
  467. * accessible to @dev, and cannot be moved to a more suitable place. This is
  468. * indicated with the error code -EBUSY.
  469. */
  470. struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
  471. struct device *dev)
  472. {
  473. struct dma_buf_attachment *attach;
  474. int ret;
  475. if (WARN_ON(!dmabuf || !dev))
  476. return ERR_PTR(-EINVAL);
  477. attach = kzalloc(sizeof(*attach), GFP_KERNEL);
  478. if (!attach)
  479. return ERR_PTR(-ENOMEM);
  480. attach->dev = dev;
  481. attach->dmabuf = dmabuf;
  482. mutex_lock(&dmabuf->lock);
  483. if (dmabuf->ops->attach) {
  484. ret = dmabuf->ops->attach(dmabuf, attach);
  485. if (ret)
  486. goto err_attach;
  487. }
  488. list_add(&attach->node, &dmabuf->attachments);
  489. mutex_unlock(&dmabuf->lock);
  490. return attach;
  491. err_attach:
  492. kfree(attach);
  493. mutex_unlock(&dmabuf->lock);
  494. return ERR_PTR(ret);
  495. }
  496. EXPORT_SYMBOL_GPL(dma_buf_attach);
  497. /**
  498. * dma_buf_detach - Remove the given attachment from dmabuf's attachments list;
  499. * optionally calls detach() of dma_buf_ops for device-specific detach
  500. * @dmabuf: [in] buffer to detach from.
  501. * @attach: [in] attachment to be detached; is free'd after this call.
  502. *
  503. * Clean up a device attachment obtained by calling dma_buf_attach().
  504. */
  505. void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
  506. {
  507. if (WARN_ON(!dmabuf || !attach))
  508. return;
  509. mutex_lock(&dmabuf->lock);
  510. list_del(&attach->node);
  511. if (dmabuf->ops->detach)
  512. dmabuf->ops->detach(dmabuf, attach);
  513. mutex_unlock(&dmabuf->lock);
  514. kfree(attach);
  515. }
  516. EXPORT_SYMBOL_GPL(dma_buf_detach);
  517. /**
  518. * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
  519. * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
  520. * dma_buf_ops.
  521. * @attach: [in] attachment whose scatterlist is to be returned
  522. * @direction: [in] direction of DMA transfer
  523. *
  524. * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
  525. * on error. May return -EINTR if it is interrupted by a signal.
  526. *
  527. * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
  528. * the underlying backing storage is pinned for as long as a mapping exists,
  529. * therefore users/importers should not hold onto a mapping for undue amounts of
  530. * time.
  531. */
  532. struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
  533. enum dma_data_direction direction)
  534. {
  535. struct sg_table *sg_table;
  536. might_sleep();
  537. if (WARN_ON(!attach || !attach->dmabuf))
  538. return ERR_PTR(-EINVAL);
  539. sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
  540. if (!sg_table)
  541. sg_table = ERR_PTR(-ENOMEM);
  542. return sg_table;
  543. }
  544. EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
  545. /**
  546. * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
  547. * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
  548. * dma_buf_ops.
  549. * @attach: [in] attachment to unmap buffer from
  550. * @sg_table: [in] scatterlist info of the buffer to unmap
  551. * @direction: [in] direction of DMA transfer
  552. *
  553. * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
  554. */
  555. void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
  556. struct sg_table *sg_table,
  557. enum dma_data_direction direction)
  558. {
  559. might_sleep();
  560. if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
  561. return;
  562. attach->dmabuf->ops->unmap_dma_buf(attach, sg_table,
  563. direction);
  564. }
  565. EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
  566. /**
  567. * DOC: cpu access
  568. *
  569. * There are mutliple reasons for supporting CPU access to a dma buffer object:
  570. *
  571. * - Fallback operations in the kernel, for example when a device is connected
  572. * over USB and the kernel needs to shuffle the data around first before
  573. * sending it away. Cache coherency is handled by braketing any transactions
  574. * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
  575. * access.
  576. *
  577. * To support dma_buf objects residing in highmem cpu access is page-based
  578. * using an api similar to kmap. Accessing a dma_buf is done in aligned chunks
  579. * of PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which
  580. * returns a pointer in kernel virtual address space. Afterwards the chunk
  581. * needs to be unmapped again. There is no limit on how often a given chunk
  582. * can be mapped and unmapped, i.e. the importer does not need to call
  583. * begin_cpu_access again before mapping the same chunk again.
  584. *
  585. * Interfaces::
  586. * void \*dma_buf_kmap(struct dma_buf \*, unsigned long);
  587. * void dma_buf_kunmap(struct dma_buf \*, unsigned long, void \*);
  588. *
  589. * Implementing the functions is optional for exporters and for importers all
  590. * the restrictions of using kmap apply.
  591. *
  592. * dma_buf kmap calls outside of the range specified in begin_cpu_access are
  593. * undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
  594. * the partial chunks at the beginning and end but may return stale or bogus
  595. * data outside of the range (in these partial chunks).
  596. *
  597. * For some cases the overhead of kmap can be too high, a vmap interface
  598. * is introduced. This interface should be used very carefully, as vmalloc
  599. * space is a limited resources on many architectures.
  600. *
  601. * Interfaces::
  602. * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
  603. * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
  604. *
  605. * The vmap call can fail if there is no vmap support in the exporter, or if
  606. * it runs out of vmalloc space. Fallback to kmap should be implemented. Note
  607. * that the dma-buf layer keeps a reference count for all vmap access and
  608. * calls down into the exporter's vmap function only when no vmapping exists,
  609. * and only unmaps it once. Protection against concurrent vmap/vunmap calls is
  610. * provided by taking the dma_buf->lock mutex.
  611. *
  612. * - For full compatibility on the importer side with existing userspace
  613. * interfaces, which might already support mmap'ing buffers. This is needed in
  614. * many processing pipelines (e.g. feeding a software rendered image into a
  615. * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
  616. * framework already supported this and for DMA buffer file descriptors to
  617. * replace ION buffers mmap support was needed.
  618. *
  619. * There is no special interfaces, userspace simply calls mmap on the dma-buf
  620. * fd. But like for CPU access there's a need to braket the actual access,
  621. * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
  622. * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
  623. * be restarted.
  624. *
  625. * Some systems might need some sort of cache coherency management e.g. when
  626. * CPU and GPU domains are being accessed through dma-buf at the same time.
  627. * To circumvent this problem there are begin/end coherency markers, that
  628. * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
  629. * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
  630. * sequence would be used like following:
  631. *
  632. * - mmap dma-buf fd
  633. * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
  634. * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
  635. * want (with the new data being consumed by say the GPU or the scanout
  636. * device)
  637. * - munmap once you don't need the buffer any more
  638. *
  639. * For correctness and optimal performance, it is always required to use
  640. * SYNC_START and SYNC_END before and after, respectively, when accessing the
  641. * mapped address. Userspace cannot rely on coherent access, even when there
  642. * are systems where it just works without calling these ioctls.
  643. *
  644. * - And as a CPU fallback in userspace processing pipelines.
  645. *
  646. * Similar to the motivation for kernel cpu access it is again important that
  647. * the userspace code of a given importing subsystem can use the same
  648. * interfaces with a imported dma-buf buffer object as with a native buffer
  649. * object. This is especially important for drm where the userspace part of
  650. * contemporary OpenGL, X, and other drivers is huge, and reworking them to
  651. * use a different way to mmap a buffer rather invasive.
  652. *
  653. * The assumption in the current dma-buf interfaces is that redirecting the
  654. * initial mmap is all that's needed. A survey of some of the existing
  655. * subsystems shows that no driver seems to do any nefarious thing like
  656. * syncing up with outstanding asynchronous processing on the device or
  657. * allocating special resources at fault time. So hopefully this is good
  658. * enough, since adding interfaces to intercept pagefaults and allow pte
  659. * shootdowns would increase the complexity quite a bit.
  660. *
  661. * Interface::
  662. * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
  663. * unsigned long);
  664. *
  665. * If the importing subsystem simply provides a special-purpose mmap call to
  666. * set up a mapping in userspace, calling do_mmap with dma_buf->file will
  667. * equally achieve that for a dma-buf object.
  668. */
  669. static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  670. enum dma_data_direction direction)
  671. {
  672. bool write = (direction == DMA_BIDIRECTIONAL ||
  673. direction == DMA_TO_DEVICE);
  674. struct reservation_object *resv = dmabuf->resv;
  675. long ret;
  676. /* Wait on any implicit rendering fences */
  677. ret = reservation_object_wait_timeout_rcu(resv, write, true,
  678. MAX_SCHEDULE_TIMEOUT);
  679. if (ret < 0)
  680. return ret;
  681. return 0;
  682. }
  683. /**
  684. * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
  685. * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
  686. * preparations. Coherency is only guaranteed in the specified range for the
  687. * specified access direction.
  688. * @dmabuf: [in] buffer to prepare cpu access for.
  689. * @direction: [in] length of range for cpu access.
  690. *
  691. * After the cpu access is complete the caller should call
  692. * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
  693. * it guaranteed to be coherent with other DMA access.
  694. *
  695. * Can return negative error values, returns 0 on success.
  696. */
  697. int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  698. enum dma_data_direction direction)
  699. {
  700. int ret = 0;
  701. if (WARN_ON(!dmabuf))
  702. return -EINVAL;
  703. if (dmabuf->ops->begin_cpu_access)
  704. ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
  705. /* Ensure that all fences are waited upon - but we first allow
  706. * the native handler the chance to do so more efficiently if it
  707. * chooses. A double invocation here will be reasonably cheap no-op.
  708. */
  709. if (ret == 0)
  710. ret = __dma_buf_begin_cpu_access(dmabuf, direction);
  711. return ret;
  712. }
  713. EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
  714. /**
  715. * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
  716. * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
  717. * actions. Coherency is only guaranteed in the specified range for the
  718. * specified access direction.
  719. * @dmabuf: [in] buffer to complete cpu access for.
  720. * @direction: [in] length of range for cpu access.
  721. *
  722. * This terminates CPU access started with dma_buf_begin_cpu_access().
  723. *
  724. * Can return negative error values, returns 0 on success.
  725. */
  726. int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
  727. enum dma_data_direction direction)
  728. {
  729. int ret = 0;
  730. WARN_ON(!dmabuf);
  731. if (dmabuf->ops->end_cpu_access)
  732. ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
  733. return ret;
  734. }
  735. EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
  736. /**
  737. * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
  738. * same restrictions as for kmap and friends apply.
  739. * @dmabuf: [in] buffer to map page from.
  740. * @page_num: [in] page in PAGE_SIZE units to map.
  741. *
  742. * This call must always succeed, any necessary preparations that might fail
  743. * need to be done in begin_cpu_access.
  744. */
  745. void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
  746. {
  747. WARN_ON(!dmabuf);
  748. if (!dmabuf->ops->map)
  749. return NULL;
  750. return dmabuf->ops->map(dmabuf, page_num);
  751. }
  752. EXPORT_SYMBOL_GPL(dma_buf_kmap);
  753. /**
  754. * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
  755. * @dmabuf: [in] buffer to unmap page from.
  756. * @page_num: [in] page in PAGE_SIZE units to unmap.
  757. * @vaddr: [in] kernel space pointer obtained from dma_buf_kmap.
  758. *
  759. * This call must always succeed.
  760. */
  761. void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
  762. void *vaddr)
  763. {
  764. WARN_ON(!dmabuf);
  765. if (dmabuf->ops->unmap)
  766. dmabuf->ops->unmap(dmabuf, page_num, vaddr);
  767. }
  768. EXPORT_SYMBOL_GPL(dma_buf_kunmap);
  769. /**
  770. * dma_buf_mmap - Setup up a userspace mmap with the given vma
  771. * @dmabuf: [in] buffer that should back the vma
  772. * @vma: [in] vma for the mmap
  773. * @pgoff: [in] offset in pages where this mmap should start within the
  774. * dma-buf buffer.
  775. *
  776. * This function adjusts the passed in vma so that it points at the file of the
  777. * dma_buf operation. It also adjusts the starting pgoff and does bounds
  778. * checking on the size of the vma. Then it calls the exporters mmap function to
  779. * set up the mapping.
  780. *
  781. * Can return negative error values, returns 0 on success.
  782. */
  783. int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
  784. unsigned long pgoff)
  785. {
  786. struct file *oldfile;
  787. int ret;
  788. if (WARN_ON(!dmabuf || !vma))
  789. return -EINVAL;
  790. /* check if buffer supports mmap */
  791. if (!dmabuf->ops->mmap)
  792. return -EINVAL;
  793. /* check for offset overflow */
  794. if (pgoff + vma_pages(vma) < pgoff)
  795. return -EOVERFLOW;
  796. /* check for overflowing the buffer's size */
  797. if (pgoff + vma_pages(vma) >
  798. dmabuf->size >> PAGE_SHIFT)
  799. return -EINVAL;
  800. /* readjust the vma */
  801. get_file(dmabuf->file);
  802. oldfile = vma->vm_file;
  803. vma->vm_file = dmabuf->file;
  804. vma->vm_pgoff = pgoff;
  805. ret = dmabuf->ops->mmap(dmabuf, vma);
  806. if (ret) {
  807. /* restore old parameters on failure */
  808. vma->vm_file = oldfile;
  809. fput(dmabuf->file);
  810. } else {
  811. if (oldfile)
  812. fput(oldfile);
  813. }
  814. return ret;
  815. }
  816. EXPORT_SYMBOL_GPL(dma_buf_mmap);
  817. /**
  818. * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
  819. * address space. Same restrictions as for vmap and friends apply.
  820. * @dmabuf: [in] buffer to vmap
  821. *
  822. * This call may fail due to lack of virtual mapping address space.
  823. * These calls are optional in drivers. The intended use for them
  824. * is for mapping objects linear in kernel space for high use objects.
  825. * Please attempt to use kmap/kunmap before thinking about these interfaces.
  826. *
  827. * Returns NULL on error.
  828. */
  829. void *dma_buf_vmap(struct dma_buf *dmabuf)
  830. {
  831. void *ptr;
  832. if (WARN_ON(!dmabuf))
  833. return NULL;
  834. if (!dmabuf->ops->vmap)
  835. return NULL;
  836. mutex_lock(&dmabuf->lock);
  837. if (dmabuf->vmapping_counter) {
  838. dmabuf->vmapping_counter++;
  839. BUG_ON(!dmabuf->vmap_ptr);
  840. ptr = dmabuf->vmap_ptr;
  841. goto out_unlock;
  842. }
  843. BUG_ON(dmabuf->vmap_ptr);
  844. ptr = dmabuf->ops->vmap(dmabuf);
  845. if (WARN_ON_ONCE(IS_ERR(ptr)))
  846. ptr = NULL;
  847. if (!ptr)
  848. goto out_unlock;
  849. dmabuf->vmap_ptr = ptr;
  850. dmabuf->vmapping_counter = 1;
  851. out_unlock:
  852. mutex_unlock(&dmabuf->lock);
  853. return ptr;
  854. }
  855. EXPORT_SYMBOL_GPL(dma_buf_vmap);
  856. /**
  857. * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
  858. * @dmabuf: [in] buffer to vunmap
  859. * @vaddr: [in] vmap to vunmap
  860. */
  861. void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
  862. {
  863. if (WARN_ON(!dmabuf))
  864. return;
  865. BUG_ON(!dmabuf->vmap_ptr);
  866. BUG_ON(dmabuf->vmapping_counter == 0);
  867. BUG_ON(dmabuf->vmap_ptr != vaddr);
  868. mutex_lock(&dmabuf->lock);
  869. if (--dmabuf->vmapping_counter == 0) {
  870. if (dmabuf->ops->vunmap)
  871. dmabuf->ops->vunmap(dmabuf, vaddr);
  872. dmabuf->vmap_ptr = NULL;
  873. }
  874. mutex_unlock(&dmabuf->lock);
  875. }
  876. EXPORT_SYMBOL_GPL(dma_buf_vunmap);
  877. #ifdef CONFIG_DEBUG_FS
  878. static int dma_buf_debug_show(struct seq_file *s, void *unused)
  879. {
  880. int ret;
  881. struct dma_buf *buf_obj;
  882. struct dma_buf_attachment *attach_obj;
  883. struct reservation_object *robj;
  884. struct reservation_object_list *fobj;
  885. struct dma_fence *fence;
  886. unsigned seq;
  887. int count = 0, attach_count, shared_count, i;
  888. size_t size = 0;
  889. ret = mutex_lock_interruptible(&db_list.lock);
  890. if (ret)
  891. return ret;
  892. seq_puts(s, "\nDma-buf Objects:\n");
  893. seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\n",
  894. "size", "flags", "mode", "count");
  895. list_for_each_entry(buf_obj, &db_list.head, list_node) {
  896. ret = mutex_lock_interruptible(&buf_obj->lock);
  897. if (ret) {
  898. seq_puts(s,
  899. "\tERROR locking buffer object: skipping\n");
  900. continue;
  901. }
  902. seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\n",
  903. buf_obj->size,
  904. buf_obj->file->f_flags, buf_obj->file->f_mode,
  905. file_count(buf_obj->file),
  906. buf_obj->exp_name);
  907. robj = buf_obj->resv;
  908. while (true) {
  909. seq = read_seqcount_begin(&robj->seq);
  910. rcu_read_lock();
  911. fobj = rcu_dereference(robj->fence);
  912. shared_count = fobj ? fobj->shared_count : 0;
  913. fence = rcu_dereference(robj->fence_excl);
  914. if (!read_seqcount_retry(&robj->seq, seq))
  915. break;
  916. rcu_read_unlock();
  917. }
  918. if (fence)
  919. seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
  920. fence->ops->get_driver_name(fence),
  921. fence->ops->get_timeline_name(fence),
  922. dma_fence_is_signaled(fence) ? "" : "un");
  923. for (i = 0; i < shared_count; i++) {
  924. fence = rcu_dereference(fobj->shared[i]);
  925. if (!dma_fence_get_rcu(fence))
  926. continue;
  927. seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
  928. fence->ops->get_driver_name(fence),
  929. fence->ops->get_timeline_name(fence),
  930. dma_fence_is_signaled(fence) ? "" : "un");
  931. dma_fence_put(fence);
  932. }
  933. rcu_read_unlock();
  934. seq_puts(s, "\tAttached Devices:\n");
  935. attach_count = 0;
  936. list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
  937. seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
  938. attach_count++;
  939. }
  940. seq_printf(s, "Total %d devices attached\n\n",
  941. attach_count);
  942. count++;
  943. size += buf_obj->size;
  944. mutex_unlock(&buf_obj->lock);
  945. }
  946. seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
  947. mutex_unlock(&db_list.lock);
  948. return 0;
  949. }
  950. static int dma_buf_debug_open(struct inode *inode, struct file *file)
  951. {
  952. return single_open(file, dma_buf_debug_show, NULL);
  953. }
  954. static const struct file_operations dma_buf_debug_fops = {
  955. .open = dma_buf_debug_open,
  956. .read = seq_read,
  957. .llseek = seq_lseek,
  958. .release = single_release,
  959. };
  960. static struct dentry *dma_buf_debugfs_dir;
  961. static int dma_buf_init_debugfs(void)
  962. {
  963. struct dentry *d;
  964. int err = 0;
  965. d = debugfs_create_dir("dma_buf", NULL);
  966. if (IS_ERR(d))
  967. return PTR_ERR(d);
  968. dma_buf_debugfs_dir = d;
  969. d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
  970. NULL, &dma_buf_debug_fops);
  971. if (IS_ERR(d)) {
  972. pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
  973. debugfs_remove_recursive(dma_buf_debugfs_dir);
  974. dma_buf_debugfs_dir = NULL;
  975. err = PTR_ERR(d);
  976. }
  977. return err;
  978. }
  979. static void dma_buf_uninit_debugfs(void)
  980. {
  981. debugfs_remove_recursive(dma_buf_debugfs_dir);
  982. }
  983. #else
  984. static inline int dma_buf_init_debugfs(void)
  985. {
  986. return 0;
  987. }
  988. static inline void dma_buf_uninit_debugfs(void)
  989. {
  990. }
  991. #endif
  992. static int __init dma_buf_init(void)
  993. {
  994. mutex_init(&db_list.lock);
  995. INIT_LIST_HEAD(&db_list.head);
  996. dma_buf_init_debugfs();
  997. return 0;
  998. }
  999. subsys_initcall(dma_buf_init);
  1000. static void __exit dma_buf_deinit(void)
  1001. {
  1002. dma_buf_uninit_debugfs();
  1003. }
  1004. __exitcall(dma_buf_deinit);