dma-buf.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 EPOLLIN, i.e. read access, can be use to query the state of the
  113. * most recent write or exclusive fence.
  114. *
  115. * - Checking for EPOLLOUT, 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 EPOLLERR;
  142. resv = dmabuf->resv;
  143. poll_wait(file, &dmabuf->poll, poll);
  144. events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
  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 & EPOLLOUT) || shared_count == 0)) {
  161. struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_excl;
  162. __poll_t pevents = EPOLLIN;
  163. if (shared_count == 0)
  164. pevents |= EPOLLOUT;
  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 & EPOLLOUT) && 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 &= ~EPOLLOUT;
  198. else
  199. dcb->active = EPOLLOUT;
  200. spin_unlock_irq(&dmabuf->poll.lock);
  201. if (!(events & EPOLLOUT))
  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 &= ~EPOLLOUT;
  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 &= ~EPOLLOUT;
  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
  350. || !exp_info->ops->mmap)) {
  351. return ERR_PTR(-EINVAL);
  352. }
  353. if (!try_module_get(exp_info->owner))
  354. return ERR_PTR(-ENOENT);
  355. dmabuf = kzalloc(alloc_size, GFP_KERNEL);
  356. if (!dmabuf) {
  357. ret = -ENOMEM;
  358. goto err_module;
  359. }
  360. dmabuf->priv = exp_info->priv;
  361. dmabuf->ops = exp_info->ops;
  362. dmabuf->size = exp_info->size;
  363. dmabuf->exp_name = exp_info->exp_name;
  364. dmabuf->owner = exp_info->owner;
  365. init_waitqueue_head(&dmabuf->poll);
  366. dmabuf->cb_excl.poll = dmabuf->cb_shared.poll = &dmabuf->poll;
  367. dmabuf->cb_excl.active = dmabuf->cb_shared.active = 0;
  368. if (!resv) {
  369. resv = (struct reservation_object *)&dmabuf[1];
  370. reservation_object_init(resv);
  371. }
  372. dmabuf->resv = resv;
  373. file = anon_inode_getfile("dmabuf", &dma_buf_fops, dmabuf,
  374. exp_info->flags);
  375. if (IS_ERR(file)) {
  376. ret = PTR_ERR(file);
  377. goto err_dmabuf;
  378. }
  379. file->f_mode |= FMODE_LSEEK;
  380. dmabuf->file = file;
  381. mutex_init(&dmabuf->lock);
  382. INIT_LIST_HEAD(&dmabuf->attachments);
  383. mutex_lock(&db_list.lock);
  384. list_add(&dmabuf->list_node, &db_list.head);
  385. mutex_unlock(&db_list.lock);
  386. return dmabuf;
  387. err_dmabuf:
  388. kfree(dmabuf);
  389. err_module:
  390. module_put(exp_info->owner);
  391. return ERR_PTR(ret);
  392. }
  393. EXPORT_SYMBOL_GPL(dma_buf_export);
  394. /**
  395. * dma_buf_fd - returns a file descriptor for the given dma_buf
  396. * @dmabuf: [in] pointer to dma_buf for which fd is required.
  397. * @flags: [in] flags to give to fd
  398. *
  399. * On success, returns an associated 'fd'. Else, returns error.
  400. */
  401. int dma_buf_fd(struct dma_buf *dmabuf, int flags)
  402. {
  403. int fd;
  404. if (!dmabuf || !dmabuf->file)
  405. return -EINVAL;
  406. fd = get_unused_fd_flags(flags);
  407. if (fd < 0)
  408. return fd;
  409. fd_install(fd, dmabuf->file);
  410. return fd;
  411. }
  412. EXPORT_SYMBOL_GPL(dma_buf_fd);
  413. /**
  414. * dma_buf_get - returns the dma_buf structure related to an fd
  415. * @fd: [in] fd associated with the dma_buf to be returned
  416. *
  417. * On success, returns the dma_buf structure associated with an fd; uses
  418. * file's refcounting done by fget to increase refcount. returns ERR_PTR
  419. * otherwise.
  420. */
  421. struct dma_buf *dma_buf_get(int fd)
  422. {
  423. struct file *file;
  424. file = fget(fd);
  425. if (!file)
  426. return ERR_PTR(-EBADF);
  427. if (!is_dma_buf_file(file)) {
  428. fput(file);
  429. return ERR_PTR(-EINVAL);
  430. }
  431. return file->private_data;
  432. }
  433. EXPORT_SYMBOL_GPL(dma_buf_get);
  434. /**
  435. * dma_buf_put - decreases refcount of the buffer
  436. * @dmabuf: [in] buffer to reduce refcount of
  437. *
  438. * Uses file's refcounting done implicitly by fput().
  439. *
  440. * If, as a result of this call, the refcount becomes 0, the 'release' file
  441. * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
  442. * in turn, and frees the memory allocated for dmabuf when exported.
  443. */
  444. void dma_buf_put(struct dma_buf *dmabuf)
  445. {
  446. if (WARN_ON(!dmabuf || !dmabuf->file))
  447. return;
  448. fput(dmabuf->file);
  449. }
  450. EXPORT_SYMBOL_GPL(dma_buf_put);
  451. /**
  452. * dma_buf_attach - Add the device to dma_buf's attachments list; optionally,
  453. * calls attach() of dma_buf_ops to allow device-specific attach functionality
  454. * @dmabuf: [in] buffer to attach device to.
  455. * @dev: [in] device to be attached.
  456. *
  457. * Returns struct dma_buf_attachment pointer for this attachment. Attachments
  458. * must be cleaned up by calling dma_buf_detach().
  459. *
  460. * Returns:
  461. *
  462. * A pointer to newly created &dma_buf_attachment on success, or a negative
  463. * error code wrapped into a pointer on failure.
  464. *
  465. * Note that this can fail if the backing storage of @dmabuf is in a place not
  466. * accessible to @dev, and cannot be moved to a more suitable place. This is
  467. * indicated with the error code -EBUSY.
  468. */
  469. struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
  470. struct device *dev)
  471. {
  472. struct dma_buf_attachment *attach;
  473. int ret;
  474. if (WARN_ON(!dmabuf || !dev))
  475. return ERR_PTR(-EINVAL);
  476. attach = kzalloc(sizeof(*attach), GFP_KERNEL);
  477. if (!attach)
  478. return ERR_PTR(-ENOMEM);
  479. attach->dev = dev;
  480. attach->dmabuf = dmabuf;
  481. mutex_lock(&dmabuf->lock);
  482. if (dmabuf->ops->attach) {
  483. ret = dmabuf->ops->attach(dmabuf, attach);
  484. if (ret)
  485. goto err_attach;
  486. }
  487. list_add(&attach->node, &dmabuf->attachments);
  488. mutex_unlock(&dmabuf->lock);
  489. return attach;
  490. err_attach:
  491. kfree(attach);
  492. mutex_unlock(&dmabuf->lock);
  493. return ERR_PTR(ret);
  494. }
  495. EXPORT_SYMBOL_GPL(dma_buf_attach);
  496. /**
  497. * dma_buf_detach - Remove the given attachment from dmabuf's attachments list;
  498. * optionally calls detach() of dma_buf_ops for device-specific detach
  499. * @dmabuf: [in] buffer to detach from.
  500. * @attach: [in] attachment to be detached; is free'd after this call.
  501. *
  502. * Clean up a device attachment obtained by calling dma_buf_attach().
  503. */
  504. void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
  505. {
  506. if (WARN_ON(!dmabuf || !attach))
  507. return;
  508. mutex_lock(&dmabuf->lock);
  509. list_del(&attach->node);
  510. if (dmabuf->ops->detach)
  511. dmabuf->ops->detach(dmabuf, attach);
  512. mutex_unlock(&dmabuf->lock);
  513. kfree(attach);
  514. }
  515. EXPORT_SYMBOL_GPL(dma_buf_detach);
  516. /**
  517. * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
  518. * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
  519. * dma_buf_ops.
  520. * @attach: [in] attachment whose scatterlist is to be returned
  521. * @direction: [in] direction of DMA transfer
  522. *
  523. * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
  524. * on error. May return -EINTR if it is interrupted by a signal.
  525. *
  526. * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
  527. * the underlying backing storage is pinned for as long as a mapping exists,
  528. * therefore users/importers should not hold onto a mapping for undue amounts of
  529. * time.
  530. */
  531. struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
  532. enum dma_data_direction direction)
  533. {
  534. struct sg_table *sg_table;
  535. might_sleep();
  536. if (WARN_ON(!attach || !attach->dmabuf))
  537. return ERR_PTR(-EINVAL);
  538. sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
  539. if (!sg_table)
  540. sg_table = ERR_PTR(-ENOMEM);
  541. return sg_table;
  542. }
  543. EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
  544. /**
  545. * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
  546. * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
  547. * dma_buf_ops.
  548. * @attach: [in] attachment to unmap buffer from
  549. * @sg_table: [in] scatterlist info of the buffer to unmap
  550. * @direction: [in] direction of DMA transfer
  551. *
  552. * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
  553. */
  554. void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
  555. struct sg_table *sg_table,
  556. enum dma_data_direction direction)
  557. {
  558. might_sleep();
  559. if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
  560. return;
  561. attach->dmabuf->ops->unmap_dma_buf(attach, sg_table,
  562. direction);
  563. }
  564. EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
  565. /**
  566. * DOC: cpu access
  567. *
  568. * There are mutliple reasons for supporting CPU access to a dma buffer object:
  569. *
  570. * - Fallback operations in the kernel, for example when a device is connected
  571. * over USB and the kernel needs to shuffle the data around first before
  572. * sending it away. Cache coherency is handled by braketing any transactions
  573. * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
  574. * access.
  575. *
  576. * To support dma_buf objects residing in highmem cpu access is page-based
  577. * using an api similar to kmap. Accessing a dma_buf is done in aligned chunks
  578. * of PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which
  579. * returns a pointer in kernel virtual address space. Afterwards the chunk
  580. * needs to be unmapped again. There is no limit on how often a given chunk
  581. * can be mapped and unmapped, i.e. the importer does not need to call
  582. * begin_cpu_access again before mapping the same chunk again.
  583. *
  584. * Interfaces::
  585. * void \*dma_buf_kmap(struct dma_buf \*, unsigned long);
  586. * void dma_buf_kunmap(struct dma_buf \*, unsigned long, void \*);
  587. *
  588. * Implementing the functions is optional for exporters and for importers all
  589. * the restrictions of using kmap apply.
  590. *
  591. * dma_buf kmap calls outside of the range specified in begin_cpu_access are
  592. * undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
  593. * the partial chunks at the beginning and end but may return stale or bogus
  594. * data outside of the range (in these partial chunks).
  595. *
  596. * For some cases the overhead of kmap can be too high, a vmap interface
  597. * is introduced. This interface should be used very carefully, as vmalloc
  598. * space is a limited resources on many architectures.
  599. *
  600. * Interfaces::
  601. * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
  602. * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
  603. *
  604. * The vmap call can fail if there is no vmap support in the exporter, or if
  605. * it runs out of vmalloc space. Fallback to kmap should be implemented. Note
  606. * that the dma-buf layer keeps a reference count for all vmap access and
  607. * calls down into the exporter's vmap function only when no vmapping exists,
  608. * and only unmaps it once. Protection against concurrent vmap/vunmap calls is
  609. * provided by taking the dma_buf->lock mutex.
  610. *
  611. * - For full compatibility on the importer side with existing userspace
  612. * interfaces, which might already support mmap'ing buffers. This is needed in
  613. * many processing pipelines (e.g. feeding a software rendered image into a
  614. * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
  615. * framework already supported this and for DMA buffer file descriptors to
  616. * replace ION buffers mmap support was needed.
  617. *
  618. * There is no special interfaces, userspace simply calls mmap on the dma-buf
  619. * fd. But like for CPU access there's a need to braket the actual access,
  620. * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
  621. * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
  622. * be restarted.
  623. *
  624. * Some systems might need some sort of cache coherency management e.g. when
  625. * CPU and GPU domains are being accessed through dma-buf at the same time.
  626. * To circumvent this problem there are begin/end coherency markers, that
  627. * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
  628. * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
  629. * sequence would be used like following:
  630. *
  631. * - mmap dma-buf fd
  632. * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
  633. * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
  634. * want (with the new data being consumed by say the GPU or the scanout
  635. * device)
  636. * - munmap once you don't need the buffer any more
  637. *
  638. * For correctness and optimal performance, it is always required to use
  639. * SYNC_START and SYNC_END before and after, respectively, when accessing the
  640. * mapped address. Userspace cannot rely on coherent access, even when there
  641. * are systems where it just works without calling these ioctls.
  642. *
  643. * - And as a CPU fallback in userspace processing pipelines.
  644. *
  645. * Similar to the motivation for kernel cpu access it is again important that
  646. * the userspace code of a given importing subsystem can use the same
  647. * interfaces with a imported dma-buf buffer object as with a native buffer
  648. * object. This is especially important for drm where the userspace part of
  649. * contemporary OpenGL, X, and other drivers is huge, and reworking them to
  650. * use a different way to mmap a buffer rather invasive.
  651. *
  652. * The assumption in the current dma-buf interfaces is that redirecting the
  653. * initial mmap is all that's needed. A survey of some of the existing
  654. * subsystems shows that no driver seems to do any nefarious thing like
  655. * syncing up with outstanding asynchronous processing on the device or
  656. * allocating special resources at fault time. So hopefully this is good
  657. * enough, since adding interfaces to intercept pagefaults and allow pte
  658. * shootdowns would increase the complexity quite a bit.
  659. *
  660. * Interface::
  661. * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
  662. * unsigned long);
  663. *
  664. * If the importing subsystem simply provides a special-purpose mmap call to
  665. * set up a mapping in userspace, calling do_mmap with dma_buf->file will
  666. * equally achieve that for a dma-buf object.
  667. */
  668. static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  669. enum dma_data_direction direction)
  670. {
  671. bool write = (direction == DMA_BIDIRECTIONAL ||
  672. direction == DMA_TO_DEVICE);
  673. struct reservation_object *resv = dmabuf->resv;
  674. long ret;
  675. /* Wait on any implicit rendering fences */
  676. ret = reservation_object_wait_timeout_rcu(resv, write, true,
  677. MAX_SCHEDULE_TIMEOUT);
  678. if (ret < 0)
  679. return ret;
  680. return 0;
  681. }
  682. /**
  683. * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
  684. * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
  685. * preparations. Coherency is only guaranteed in the specified range for the
  686. * specified access direction.
  687. * @dmabuf: [in] buffer to prepare cpu access for.
  688. * @direction: [in] length of range for cpu access.
  689. *
  690. * After the cpu access is complete the caller should call
  691. * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
  692. * it guaranteed to be coherent with other DMA access.
  693. *
  694. * Can return negative error values, returns 0 on success.
  695. */
  696. int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
  697. enum dma_data_direction direction)
  698. {
  699. int ret = 0;
  700. if (WARN_ON(!dmabuf))
  701. return -EINVAL;
  702. if (dmabuf->ops->begin_cpu_access)
  703. ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
  704. /* Ensure that all fences are waited upon - but we first allow
  705. * the native handler the chance to do so more efficiently if it
  706. * chooses. A double invocation here will be reasonably cheap no-op.
  707. */
  708. if (ret == 0)
  709. ret = __dma_buf_begin_cpu_access(dmabuf, direction);
  710. return ret;
  711. }
  712. EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
  713. /**
  714. * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
  715. * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
  716. * actions. Coherency is only guaranteed in the specified range for the
  717. * specified access direction.
  718. * @dmabuf: [in] buffer to complete cpu access for.
  719. * @direction: [in] length of range for cpu access.
  720. *
  721. * This terminates CPU access started with dma_buf_begin_cpu_access().
  722. *
  723. * Can return negative error values, returns 0 on success.
  724. */
  725. int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
  726. enum dma_data_direction direction)
  727. {
  728. int ret = 0;
  729. WARN_ON(!dmabuf);
  730. if (dmabuf->ops->end_cpu_access)
  731. ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
  732. return ret;
  733. }
  734. EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
  735. /**
  736. * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
  737. * same restrictions as for kmap and friends apply.
  738. * @dmabuf: [in] buffer to map page from.
  739. * @page_num: [in] page in PAGE_SIZE units to map.
  740. *
  741. * This call must always succeed, any necessary preparations that might fail
  742. * need to be done in begin_cpu_access.
  743. */
  744. void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
  745. {
  746. WARN_ON(!dmabuf);
  747. if (!dmabuf->ops->map)
  748. return NULL;
  749. return dmabuf->ops->map(dmabuf, page_num);
  750. }
  751. EXPORT_SYMBOL_GPL(dma_buf_kmap);
  752. /**
  753. * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
  754. * @dmabuf: [in] buffer to unmap page from.
  755. * @page_num: [in] page in PAGE_SIZE units to unmap.
  756. * @vaddr: [in] kernel space pointer obtained from dma_buf_kmap.
  757. *
  758. * This call must always succeed.
  759. */
  760. void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
  761. void *vaddr)
  762. {
  763. WARN_ON(!dmabuf);
  764. if (dmabuf->ops->unmap)
  765. dmabuf->ops->unmap(dmabuf, page_num, vaddr);
  766. }
  767. EXPORT_SYMBOL_GPL(dma_buf_kunmap);
  768. /**
  769. * dma_buf_mmap - Setup up a userspace mmap with the given vma
  770. * @dmabuf: [in] buffer that should back the vma
  771. * @vma: [in] vma for the mmap
  772. * @pgoff: [in] offset in pages where this mmap should start within the
  773. * dma-buf buffer.
  774. *
  775. * This function adjusts the passed in vma so that it points at the file of the
  776. * dma_buf operation. It also adjusts the starting pgoff and does bounds
  777. * checking on the size of the vma. Then it calls the exporters mmap function to
  778. * set up the mapping.
  779. *
  780. * Can return negative error values, returns 0 on success.
  781. */
  782. int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
  783. unsigned long pgoff)
  784. {
  785. struct file *oldfile;
  786. int ret;
  787. if (WARN_ON(!dmabuf || !vma))
  788. return -EINVAL;
  789. /* check for offset overflow */
  790. if (pgoff + vma_pages(vma) < pgoff)
  791. return -EOVERFLOW;
  792. /* check for overflowing the buffer's size */
  793. if (pgoff + vma_pages(vma) >
  794. dmabuf->size >> PAGE_SHIFT)
  795. return -EINVAL;
  796. /* readjust the vma */
  797. get_file(dmabuf->file);
  798. oldfile = vma->vm_file;
  799. vma->vm_file = dmabuf->file;
  800. vma->vm_pgoff = pgoff;
  801. ret = dmabuf->ops->mmap(dmabuf, vma);
  802. if (ret) {
  803. /* restore old parameters on failure */
  804. vma->vm_file = oldfile;
  805. fput(dmabuf->file);
  806. } else {
  807. if (oldfile)
  808. fput(oldfile);
  809. }
  810. return ret;
  811. }
  812. EXPORT_SYMBOL_GPL(dma_buf_mmap);
  813. /**
  814. * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
  815. * address space. Same restrictions as for vmap and friends apply.
  816. * @dmabuf: [in] buffer to vmap
  817. *
  818. * This call may fail due to lack of virtual mapping address space.
  819. * These calls are optional in drivers. The intended use for them
  820. * is for mapping objects linear in kernel space for high use objects.
  821. * Please attempt to use kmap/kunmap before thinking about these interfaces.
  822. *
  823. * Returns NULL on error.
  824. */
  825. void *dma_buf_vmap(struct dma_buf *dmabuf)
  826. {
  827. void *ptr;
  828. if (WARN_ON(!dmabuf))
  829. return NULL;
  830. if (!dmabuf->ops->vmap)
  831. return NULL;
  832. mutex_lock(&dmabuf->lock);
  833. if (dmabuf->vmapping_counter) {
  834. dmabuf->vmapping_counter++;
  835. BUG_ON(!dmabuf->vmap_ptr);
  836. ptr = dmabuf->vmap_ptr;
  837. goto out_unlock;
  838. }
  839. BUG_ON(dmabuf->vmap_ptr);
  840. ptr = dmabuf->ops->vmap(dmabuf);
  841. if (WARN_ON_ONCE(IS_ERR(ptr)))
  842. ptr = NULL;
  843. if (!ptr)
  844. goto out_unlock;
  845. dmabuf->vmap_ptr = ptr;
  846. dmabuf->vmapping_counter = 1;
  847. out_unlock:
  848. mutex_unlock(&dmabuf->lock);
  849. return ptr;
  850. }
  851. EXPORT_SYMBOL_GPL(dma_buf_vmap);
  852. /**
  853. * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
  854. * @dmabuf: [in] buffer to vunmap
  855. * @vaddr: [in] vmap to vunmap
  856. */
  857. void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
  858. {
  859. if (WARN_ON(!dmabuf))
  860. return;
  861. BUG_ON(!dmabuf->vmap_ptr);
  862. BUG_ON(dmabuf->vmapping_counter == 0);
  863. BUG_ON(dmabuf->vmap_ptr != vaddr);
  864. mutex_lock(&dmabuf->lock);
  865. if (--dmabuf->vmapping_counter == 0) {
  866. if (dmabuf->ops->vunmap)
  867. dmabuf->ops->vunmap(dmabuf, vaddr);
  868. dmabuf->vmap_ptr = NULL;
  869. }
  870. mutex_unlock(&dmabuf->lock);
  871. }
  872. EXPORT_SYMBOL_GPL(dma_buf_vunmap);
  873. #ifdef CONFIG_DEBUG_FS
  874. static int dma_buf_debug_show(struct seq_file *s, void *unused)
  875. {
  876. int ret;
  877. struct dma_buf *buf_obj;
  878. struct dma_buf_attachment *attach_obj;
  879. struct reservation_object *robj;
  880. struct reservation_object_list *fobj;
  881. struct dma_fence *fence;
  882. unsigned seq;
  883. int count = 0, attach_count, shared_count, i;
  884. size_t size = 0;
  885. ret = mutex_lock_interruptible(&db_list.lock);
  886. if (ret)
  887. return ret;
  888. seq_puts(s, "\nDma-buf Objects:\n");
  889. seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\n",
  890. "size", "flags", "mode", "count");
  891. list_for_each_entry(buf_obj, &db_list.head, list_node) {
  892. ret = mutex_lock_interruptible(&buf_obj->lock);
  893. if (ret) {
  894. seq_puts(s,
  895. "\tERROR locking buffer object: skipping\n");
  896. continue;
  897. }
  898. seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\n",
  899. buf_obj->size,
  900. buf_obj->file->f_flags, buf_obj->file->f_mode,
  901. file_count(buf_obj->file),
  902. buf_obj->exp_name);
  903. robj = buf_obj->resv;
  904. while (true) {
  905. seq = read_seqcount_begin(&robj->seq);
  906. rcu_read_lock();
  907. fobj = rcu_dereference(robj->fence);
  908. shared_count = fobj ? fobj->shared_count : 0;
  909. fence = rcu_dereference(robj->fence_excl);
  910. if (!read_seqcount_retry(&robj->seq, seq))
  911. break;
  912. rcu_read_unlock();
  913. }
  914. if (fence)
  915. seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
  916. fence->ops->get_driver_name(fence),
  917. fence->ops->get_timeline_name(fence),
  918. dma_fence_is_signaled(fence) ? "" : "un");
  919. for (i = 0; i < shared_count; i++) {
  920. fence = rcu_dereference(fobj->shared[i]);
  921. if (!dma_fence_get_rcu(fence))
  922. continue;
  923. seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
  924. fence->ops->get_driver_name(fence),
  925. fence->ops->get_timeline_name(fence),
  926. dma_fence_is_signaled(fence) ? "" : "un");
  927. dma_fence_put(fence);
  928. }
  929. rcu_read_unlock();
  930. seq_puts(s, "\tAttached Devices:\n");
  931. attach_count = 0;
  932. list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
  933. seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
  934. attach_count++;
  935. }
  936. seq_printf(s, "Total %d devices attached\n\n",
  937. attach_count);
  938. count++;
  939. size += buf_obj->size;
  940. mutex_unlock(&buf_obj->lock);
  941. }
  942. seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
  943. mutex_unlock(&db_list.lock);
  944. return 0;
  945. }
  946. static int dma_buf_debug_open(struct inode *inode, struct file *file)
  947. {
  948. return single_open(file, dma_buf_debug_show, NULL);
  949. }
  950. static const struct file_operations dma_buf_debug_fops = {
  951. .open = dma_buf_debug_open,
  952. .read = seq_read,
  953. .llseek = seq_lseek,
  954. .release = single_release,
  955. };
  956. static struct dentry *dma_buf_debugfs_dir;
  957. static int dma_buf_init_debugfs(void)
  958. {
  959. struct dentry *d;
  960. int err = 0;
  961. d = debugfs_create_dir("dma_buf", NULL);
  962. if (IS_ERR(d))
  963. return PTR_ERR(d);
  964. dma_buf_debugfs_dir = d;
  965. d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
  966. NULL, &dma_buf_debug_fops);
  967. if (IS_ERR(d)) {
  968. pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
  969. debugfs_remove_recursive(dma_buf_debugfs_dir);
  970. dma_buf_debugfs_dir = NULL;
  971. err = PTR_ERR(d);
  972. }
  973. return err;
  974. }
  975. static void dma_buf_uninit_debugfs(void)
  976. {
  977. debugfs_remove_recursive(dma_buf_debugfs_dir);
  978. }
  979. #else
  980. static inline int dma_buf_init_debugfs(void)
  981. {
  982. return 0;
  983. }
  984. static inline void dma_buf_uninit_debugfs(void)
  985. {
  986. }
  987. #endif
  988. static int __init dma_buf_init(void)
  989. {
  990. mutex_init(&db_list.lock);
  991. INIT_LIST_HEAD(&db_list.head);
  992. dma_buf_init_debugfs();
  993. return 0;
  994. }
  995. subsys_initcall(dma_buf_init);
  996. static void __exit dma_buf_deinit(void)
  997. {
  998. dma_buf_uninit_debugfs();
  999. }
  1000. __exitcall(dma_buf_deinit);