dma-buf.c 33 KB

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