dma-buf.c 33 KB

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