dma-buf.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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 __poll_t 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. __poll_t 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. __poll_t 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. #ifdef CONFIG_COMPAT
  275. .compat_ioctl = dma_buf_ioctl,
  276. #endif
  277. };
  278. /*
  279. * is_dma_buf_file - Check if struct file* is associated with dma_buf
  280. */
  281. static inline int is_dma_buf_file(struct file *file)
  282. {
  283. return file->f_op == &dma_buf_fops;
  284. }
  285. /**
  286. * DOC: dma buf device access
  287. *
  288. * For device DMA access to a shared DMA buffer the usual sequence of operations
  289. * is fairly simple:
  290. *
  291. * 1. The exporter defines his exporter instance using
  292. * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
  293. * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
  294. * as a file descriptor by calling dma_buf_fd().
  295. *
  296. * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
  297. * to share with: First the filedescriptor is converted to a &dma_buf using
  298. * dma_buf_get(). Then the buffer is attached to the device using
  299. * dma_buf_attach().
  300. *
  301. * Up to this stage the exporter is still free to migrate or reallocate the
  302. * backing storage.
  303. *
  304. * 3. Once the buffer is attached to all devices userspace can initiate DMA
  305. * access to the shared buffer. In the kernel this is done by calling
  306. * dma_buf_map_attachment() and dma_buf_unmap_attachment().
  307. *
  308. * 4. Once a driver is done with a shared buffer it needs to call
  309. * dma_buf_detach() (after cleaning up any mappings) and then release the
  310. * reference acquired with dma_buf_get by calling dma_buf_put().
  311. *
  312. * For the detailed semantics exporters are expected to implement see
  313. * &dma_buf_ops.
  314. */
  315. /**
  316. * dma_buf_export - Creates a new dma_buf, and associates an anon file
  317. * with this buffer, so it can be exported.
  318. * Also connect the allocator specific data and ops to the buffer.
  319. * Additionally, provide a name string for exporter; useful in debugging.
  320. *
  321. * @exp_info: [in] holds all the export related information provided
  322. * by the exporter. see &struct dma_buf_export_info
  323. * for further details.
  324. *
  325. * Returns, on success, a newly created dma_buf object, which wraps the
  326. * supplied private data and operations for dma_buf_ops. On either missing
  327. * ops, or error in allocating struct dma_buf, will return negative error.
  328. *
  329. * For most cases the easiest way to create @exp_info is through the
  330. * %DEFINE_DMA_BUF_EXPORT_INFO macro.
  331. */
  332. struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
  333. {
  334. struct dma_buf *dmabuf;
  335. struct reservation_object *resv = exp_info->resv;
  336. struct file *file;
  337. size_t alloc_size = sizeof(struct dma_buf);
  338. int ret;
  339. if (!exp_info->resv)
  340. alloc_size += sizeof(struct reservation_object);
  341. else
  342. /* prevent &dma_buf[1] == dma_buf->resv */
  343. alloc_size += 1;
  344. if (WARN_ON(!exp_info->priv
  345. || !exp_info->ops
  346. || !exp_info->ops->map_dma_buf
  347. || !exp_info->ops->unmap_dma_buf
  348. || !exp_info->ops->release
  349. || !exp_info->ops->map_atomic
  350. || !exp_info->ops->map
  351. || !exp_info->ops->mmap)) {
  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, dev, 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. * There are also atomic variants of these interfaces. Like for kmap they
  590. * facilitate non-blocking fast-paths. Neither the importer nor the exporter
  591. * (in the callback) is allowed to block when using these.
  592. *
  593. * Interfaces::
  594. * void \*dma_buf_kmap_atomic(struct dma_buf \*, unsigned long);
  595. * void dma_buf_kunmap_atomic(struct dma_buf \*, unsigned long, void \*);
  596. *
  597. * For importers all the restrictions of using kmap apply, like the limited
  598. * supply of kmap_atomic slots. Hence an importer shall only hold onto at
  599. * max 2 atomic dma_buf kmaps at the same time (in any given process context).
  600. *
  601. * dma_buf kmap calls outside of the range specified in begin_cpu_access are
  602. * undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
  603. * the partial chunks at the beginning and end but may return stale or bogus
  604. * data outside of the range (in these partial chunks).
  605. *
  606. * Note that these calls need to always succeed. The exporter needs to
  607. * complete any preparations that might fail in begin_cpu_access.
  608. *
  609. * For some cases the overhead of kmap can be too high, a vmap interface
  610. * is introduced. This interface should be used very carefully, as vmalloc
  611. * space is a limited resources on many architectures.
  612. *
  613. * Interfaces::
  614. * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
  615. * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
  616. *
  617. * The vmap call can fail if there is no vmap support in the exporter, or if
  618. * it runs out of vmalloc space. Fallback to kmap should be implemented. Note
  619. * that the dma-buf layer keeps a reference count for all vmap access and
  620. * calls down into the exporter's vmap function only when no vmapping exists,
  621. * and only unmaps it once. Protection against concurrent vmap/vunmap calls is
  622. * provided by taking the dma_buf->lock mutex.
  623. *
  624. * - For full compatibility on the importer side with existing userspace
  625. * interfaces, which might already support mmap'ing buffers. This is needed in
  626. * many processing pipelines (e.g. feeding a software rendered image into a
  627. * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
  628. * framework already supported this and for DMA buffer file descriptors to
  629. * replace ION buffers mmap support was needed.
  630. *
  631. * There is no special interfaces, userspace simply calls mmap on the dma-buf
  632. * fd. But like for CPU access there's a need to braket the actual access,
  633. * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
  634. * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
  635. * be restarted.
  636. *
  637. * Some systems might need some sort of cache coherency management e.g. when
  638. * CPU and GPU domains are being accessed through dma-buf at the same time.
  639. * To circumvent this problem there are begin/end coherency markers, that
  640. * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
  641. * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
  642. * sequence would be used like following:
  643. *
  644. * - mmap dma-buf fd
  645. * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
  646. * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
  647. * want (with the new data being consumed by say the GPU or the scanout
  648. * device)
  649. * - munmap once you don't need the buffer any more
  650. *
  651. * For correctness and optimal performance, it is always required to use
  652. * SYNC_START and SYNC_END before and after, respectively, when accessing the
  653. * mapped address. Userspace cannot rely on coherent access, even when there
  654. * are systems where it just works without calling these ioctls.
  655. *
  656. * - And as a CPU fallback in userspace processing pipelines.
  657. *
  658. * Similar to the motivation for kernel cpu access it is again important that
  659. * the userspace code of a given importing subsystem can use the same
  660. * interfaces with a imported dma-buf buffer object as with a native buffer
  661. * object. This is especially important for drm where the userspace part of
  662. * contemporary OpenGL, X, and other drivers is huge, and reworking them to
  663. * use a different way to mmap a buffer rather invasive.
  664. *
  665. * The assumption in the current dma-buf interfaces is that redirecting the
  666. * initial mmap is all that's needed. A survey of some of the existing
  667. * subsystems shows that no driver seems to do any nefarious thing like
  668. * syncing up with outstanding asynchronous processing on the device or
  669. * allocating special resources at fault time. So hopefully this is good
  670. * enough, since adding interfaces to intercept pagefaults and allow pte
  671. * shootdowns would increase the complexity quite a bit.
  672. *
  673. * Interface::
  674. * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
  675. * unsigned long);
  676. *
  677. * If the importing subsystem simply provides a special-purpose mmap call to
  678. * set up a mapping in userspace, calling do_mmap with dma_buf->file will
  679. * equally achieve that for a dma-buf object.
  680. */
  681. static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  682. enum dma_data_direction direction)
  683. {
  684. bool write = (direction == DMA_BIDIRECTIONAL ||
  685. direction == DMA_TO_DEVICE);
  686. struct reservation_object *resv = dmabuf->resv;
  687. long ret;
  688. /* Wait on any implicit rendering fences */
  689. ret = reservation_object_wait_timeout_rcu(resv, write, true,
  690. MAX_SCHEDULE_TIMEOUT);
  691. if (ret < 0)
  692. return ret;
  693. return 0;
  694. }
  695. /**
  696. * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
  697. * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
  698. * preparations. Coherency is only guaranteed in the specified range for the
  699. * specified access direction.
  700. * @dmabuf: [in] buffer to prepare cpu access for.
  701. * @direction: [in] length of range for cpu access.
  702. *
  703. * After the cpu access is complete the caller should call
  704. * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
  705. * it guaranteed to be coherent with other DMA access.
  706. *
  707. * Can return negative error values, returns 0 on success.
  708. */
  709. int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  710. enum dma_data_direction direction)
  711. {
  712. int ret = 0;
  713. if (WARN_ON(!dmabuf))
  714. return -EINVAL;
  715. if (dmabuf->ops->begin_cpu_access)
  716. ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
  717. /* Ensure that all fences are waited upon - but we first allow
  718. * the native handler the chance to do so more efficiently if it
  719. * chooses. A double invocation here will be reasonably cheap no-op.
  720. */
  721. if (ret == 0)
  722. ret = __dma_buf_begin_cpu_access(dmabuf, direction);
  723. return ret;
  724. }
  725. EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
  726. /**
  727. * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
  728. * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
  729. * actions. Coherency is only guaranteed in the specified range for the
  730. * specified access direction.
  731. * @dmabuf: [in] buffer to complete cpu access for.
  732. * @direction: [in] length of range for cpu access.
  733. *
  734. * This terminates CPU access started with dma_buf_begin_cpu_access().
  735. *
  736. * Can return negative error values, returns 0 on success.
  737. */
  738. int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
  739. enum dma_data_direction direction)
  740. {
  741. int ret = 0;
  742. WARN_ON(!dmabuf);
  743. if (dmabuf->ops->end_cpu_access)
  744. ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
  745. return ret;
  746. }
  747. EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
  748. /**
  749. * dma_buf_kmap_atomic - Map a page of the buffer object into kernel address
  750. * space. The same restrictions as for kmap_atomic and friends apply.
  751. * @dmabuf: [in] buffer to map page from.
  752. * @page_num: [in] page in PAGE_SIZE units to map.
  753. *
  754. * This call must always succeed, any necessary preparations that might fail
  755. * need to be done in begin_cpu_access.
  756. */
  757. void *dma_buf_kmap_atomic(struct dma_buf *dmabuf, unsigned long page_num)
  758. {
  759. WARN_ON(!dmabuf);
  760. return dmabuf->ops->map_atomic(dmabuf, page_num);
  761. }
  762. EXPORT_SYMBOL_GPL(dma_buf_kmap_atomic);
  763. /**
  764. * dma_buf_kunmap_atomic - Unmap a page obtained by dma_buf_kmap_atomic.
  765. * @dmabuf: [in] buffer to unmap page from.
  766. * @page_num: [in] page in PAGE_SIZE units to unmap.
  767. * @vaddr: [in] kernel space pointer obtained from dma_buf_kmap_atomic.
  768. *
  769. * This call must always succeed.
  770. */
  771. void dma_buf_kunmap_atomic(struct dma_buf *dmabuf, unsigned long page_num,
  772. void *vaddr)
  773. {
  774. WARN_ON(!dmabuf);
  775. if (dmabuf->ops->unmap_atomic)
  776. dmabuf->ops->unmap_atomic(dmabuf, page_num, vaddr);
  777. }
  778. EXPORT_SYMBOL_GPL(dma_buf_kunmap_atomic);
  779. /**
  780. * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
  781. * same restrictions as for kmap and friends apply.
  782. * @dmabuf: [in] buffer to map page from.
  783. * @page_num: [in] page in PAGE_SIZE units to map.
  784. *
  785. * This call must always succeed, any necessary preparations that might fail
  786. * need to be done in begin_cpu_access.
  787. */
  788. void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
  789. {
  790. WARN_ON(!dmabuf);
  791. return dmabuf->ops->map(dmabuf, page_num);
  792. }
  793. EXPORT_SYMBOL_GPL(dma_buf_kmap);
  794. /**
  795. * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
  796. * @dmabuf: [in] buffer to unmap page from.
  797. * @page_num: [in] page in PAGE_SIZE units to unmap.
  798. * @vaddr: [in] kernel space pointer obtained from dma_buf_kmap.
  799. *
  800. * This call must always succeed.
  801. */
  802. void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
  803. void *vaddr)
  804. {
  805. WARN_ON(!dmabuf);
  806. if (dmabuf->ops->unmap)
  807. dmabuf->ops->unmap(dmabuf, page_num, vaddr);
  808. }
  809. EXPORT_SYMBOL_GPL(dma_buf_kunmap);
  810. /**
  811. * dma_buf_mmap - Setup up a userspace mmap with the given vma
  812. * @dmabuf: [in] buffer that should back the vma
  813. * @vma: [in] vma for the mmap
  814. * @pgoff: [in] offset in pages where this mmap should start within the
  815. * dma-buf buffer.
  816. *
  817. * This function adjusts the passed in vma so that it points at the file of the
  818. * dma_buf operation. It also adjusts the starting pgoff and does bounds
  819. * checking on the size of the vma. Then it calls the exporters mmap function to
  820. * set up the mapping.
  821. *
  822. * Can return negative error values, returns 0 on success.
  823. */
  824. int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
  825. unsigned long pgoff)
  826. {
  827. struct file *oldfile;
  828. int ret;
  829. if (WARN_ON(!dmabuf || !vma))
  830. return -EINVAL;
  831. /* check for offset overflow */
  832. if (pgoff + vma_pages(vma) < pgoff)
  833. return -EOVERFLOW;
  834. /* check for overflowing the buffer's size */
  835. if (pgoff + vma_pages(vma) >
  836. dmabuf->size >> PAGE_SHIFT)
  837. return -EINVAL;
  838. /* readjust the vma */
  839. get_file(dmabuf->file);
  840. oldfile = vma->vm_file;
  841. vma->vm_file = dmabuf->file;
  842. vma->vm_pgoff = pgoff;
  843. ret = dmabuf->ops->mmap(dmabuf, vma);
  844. if (ret) {
  845. /* restore old parameters on failure */
  846. vma->vm_file = oldfile;
  847. fput(dmabuf->file);
  848. } else {
  849. if (oldfile)
  850. fput(oldfile);
  851. }
  852. return ret;
  853. }
  854. EXPORT_SYMBOL_GPL(dma_buf_mmap);
  855. /**
  856. * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
  857. * address space. Same restrictions as for vmap and friends apply.
  858. * @dmabuf: [in] buffer to vmap
  859. *
  860. * This call may fail due to lack of virtual mapping address space.
  861. * These calls are optional in drivers. The intended use for them
  862. * is for mapping objects linear in kernel space for high use objects.
  863. * Please attempt to use kmap/kunmap before thinking about these interfaces.
  864. *
  865. * Returns NULL on error.
  866. */
  867. void *dma_buf_vmap(struct dma_buf *dmabuf)
  868. {
  869. void *ptr;
  870. if (WARN_ON(!dmabuf))
  871. return NULL;
  872. if (!dmabuf->ops->vmap)
  873. return NULL;
  874. mutex_lock(&dmabuf->lock);
  875. if (dmabuf->vmapping_counter) {
  876. dmabuf->vmapping_counter++;
  877. BUG_ON(!dmabuf->vmap_ptr);
  878. ptr = dmabuf->vmap_ptr;
  879. goto out_unlock;
  880. }
  881. BUG_ON(dmabuf->vmap_ptr);
  882. ptr = dmabuf->ops->vmap(dmabuf);
  883. if (WARN_ON_ONCE(IS_ERR(ptr)))
  884. ptr = NULL;
  885. if (!ptr)
  886. goto out_unlock;
  887. dmabuf->vmap_ptr = ptr;
  888. dmabuf->vmapping_counter = 1;
  889. out_unlock:
  890. mutex_unlock(&dmabuf->lock);
  891. return ptr;
  892. }
  893. EXPORT_SYMBOL_GPL(dma_buf_vmap);
  894. /**
  895. * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
  896. * @dmabuf: [in] buffer to vunmap
  897. * @vaddr: [in] vmap to vunmap
  898. */
  899. void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
  900. {
  901. if (WARN_ON(!dmabuf))
  902. return;
  903. BUG_ON(!dmabuf->vmap_ptr);
  904. BUG_ON(dmabuf->vmapping_counter == 0);
  905. BUG_ON(dmabuf->vmap_ptr != vaddr);
  906. mutex_lock(&dmabuf->lock);
  907. if (--dmabuf->vmapping_counter == 0) {
  908. if (dmabuf->ops->vunmap)
  909. dmabuf->ops->vunmap(dmabuf, vaddr);
  910. dmabuf->vmap_ptr = NULL;
  911. }
  912. mutex_unlock(&dmabuf->lock);
  913. }
  914. EXPORT_SYMBOL_GPL(dma_buf_vunmap);
  915. #ifdef CONFIG_DEBUG_FS
  916. static int dma_buf_debug_show(struct seq_file *s, void *unused)
  917. {
  918. int ret;
  919. struct dma_buf *buf_obj;
  920. struct dma_buf_attachment *attach_obj;
  921. struct reservation_object *robj;
  922. struct reservation_object_list *fobj;
  923. struct dma_fence *fence;
  924. unsigned seq;
  925. int count = 0, attach_count, shared_count, i;
  926. size_t size = 0;
  927. ret = mutex_lock_interruptible(&db_list.lock);
  928. if (ret)
  929. return ret;
  930. seq_puts(s, "\nDma-buf Objects:\n");
  931. seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\n",
  932. "size", "flags", "mode", "count");
  933. list_for_each_entry(buf_obj, &db_list.head, list_node) {
  934. ret = mutex_lock_interruptible(&buf_obj->lock);
  935. if (ret) {
  936. seq_puts(s,
  937. "\tERROR locking buffer object: skipping\n");
  938. continue;
  939. }
  940. seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\n",
  941. buf_obj->size,
  942. buf_obj->file->f_flags, buf_obj->file->f_mode,
  943. file_count(buf_obj->file),
  944. buf_obj->exp_name);
  945. robj = buf_obj->resv;
  946. while (true) {
  947. seq = read_seqcount_begin(&robj->seq);
  948. rcu_read_lock();
  949. fobj = rcu_dereference(robj->fence);
  950. shared_count = fobj ? fobj->shared_count : 0;
  951. fence = rcu_dereference(robj->fence_excl);
  952. if (!read_seqcount_retry(&robj->seq, seq))
  953. break;
  954. rcu_read_unlock();
  955. }
  956. if (fence)
  957. seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
  958. fence->ops->get_driver_name(fence),
  959. fence->ops->get_timeline_name(fence),
  960. dma_fence_is_signaled(fence) ? "" : "un");
  961. for (i = 0; i < shared_count; i++) {
  962. fence = rcu_dereference(fobj->shared[i]);
  963. if (!dma_fence_get_rcu(fence))
  964. continue;
  965. seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
  966. fence->ops->get_driver_name(fence),
  967. fence->ops->get_timeline_name(fence),
  968. dma_fence_is_signaled(fence) ? "" : "un");
  969. }
  970. rcu_read_unlock();
  971. seq_puts(s, "\tAttached Devices:\n");
  972. attach_count = 0;
  973. list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
  974. seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
  975. attach_count++;
  976. }
  977. seq_printf(s, "Total %d devices attached\n\n",
  978. attach_count);
  979. count++;
  980. size += buf_obj->size;
  981. mutex_unlock(&buf_obj->lock);
  982. }
  983. seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
  984. mutex_unlock(&db_list.lock);
  985. return 0;
  986. }
  987. static int dma_buf_debug_open(struct inode *inode, struct file *file)
  988. {
  989. return single_open(file, dma_buf_debug_show, NULL);
  990. }
  991. static const struct file_operations dma_buf_debug_fops = {
  992. .open = dma_buf_debug_open,
  993. .read = seq_read,
  994. .llseek = seq_lseek,
  995. .release = single_release,
  996. };
  997. static struct dentry *dma_buf_debugfs_dir;
  998. static int dma_buf_init_debugfs(void)
  999. {
  1000. struct dentry *d;
  1001. int err = 0;
  1002. d = debugfs_create_dir("dma_buf", NULL);
  1003. if (IS_ERR(d))
  1004. return PTR_ERR(d);
  1005. dma_buf_debugfs_dir = d;
  1006. d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
  1007. NULL, &dma_buf_debug_fops);
  1008. if (IS_ERR(d)) {
  1009. pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
  1010. debugfs_remove_recursive(dma_buf_debugfs_dir);
  1011. dma_buf_debugfs_dir = NULL;
  1012. err = PTR_ERR(d);
  1013. }
  1014. return err;
  1015. }
  1016. static void dma_buf_uninit_debugfs(void)
  1017. {
  1018. debugfs_remove_recursive(dma_buf_debugfs_dir);
  1019. }
  1020. #else
  1021. static inline int dma_buf_init_debugfs(void)
  1022. {
  1023. return 0;
  1024. }
  1025. static inline void dma_buf_uninit_debugfs(void)
  1026. {
  1027. }
  1028. #endif
  1029. static int __init dma_buf_init(void)
  1030. {
  1031. mutex_init(&db_list.lock);
  1032. INIT_LIST_HEAD(&db_list.head);
  1033. dma_buf_init_debugfs();
  1034. return 0;
  1035. }
  1036. subsys_initcall(dma_buf_init);
  1037. static void __exit dma_buf_deinit(void)
  1038. {
  1039. dma_buf_uninit_debugfs();
  1040. }
  1041. __exitcall(dma_buf_deinit);