1 // SPDX-License-Identifier: GPL-2.0-only
3 * Framework for buffer objects that can be shared across devices/subsystems.
5 * Copyright(C) 2011 Linaro Limited. All rights reserved.
6 * Author: Sumit Semwal <sumit.semwal@ti.com>
8 * Many thanks to linaro-mm-sig list, and specially
9 * Arnd Bergmann <arnd@arndb.de>, Rob Clark <rob@ti.com> and
10 * Daniel Vetter <daniel@ffwll.ch> for their support in creation and
11 * refining of this idea.
15 #include <linux/slab.h>
16 #include <linux/dma-buf.h>
17 #include <linux/dma-fence.h>
18 #include <linux/anon_inodes.h>
19 #include <linux/export.h>
20 #include <linux/debugfs.h>
21 #include <linux/module.h>
22 #include <linux/seq_file.h>
23 #include <linux/poll.h>
24 #include <linux/dma-resv.h>
26 #include <linux/mount.h>
27 #include <linux/pseudo_fs.h>
29 #include <uapi/linux/dma-buf.h>
30 #include <uapi/linux/magic.h>
32 #include "dma-buf-sysfs-stats.h"
34 static inline int is_dma_buf_file(struct file *);
37 struct list_head head;
41 static struct dma_buf_list db_list;
43 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
45 struct dma_buf *dmabuf;
46 char name[DMA_BUF_NAME_LEN];
49 dmabuf = dentry->d_fsdata;
50 spin_lock(&dmabuf->name_lock);
52 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
53 spin_unlock(&dmabuf->name_lock);
55 return dynamic_dname(dentry, buffer, buflen, "/%s:%s",
56 dentry->d_name.name, ret > 0 ? name : "");
59 static void dma_buf_release(struct dentry *dentry)
61 struct dma_buf *dmabuf;
63 dmabuf = dentry->d_fsdata;
64 if (unlikely(!dmabuf))
67 BUG_ON(dmabuf->vmapping_counter);
70 * Any fences that a dma-buf poll can wait on should be signaled
71 * before releasing dma-buf. This is the responsibility of each
72 * driver that uses the reservation objects.
74 * If you hit this BUG() it means someone dropped their ref to the
75 * dma-buf while still having pending operation to the buffer.
77 BUG_ON(dmabuf->cb_shared.active || dmabuf->cb_excl.active);
79 dmabuf->ops->release(dmabuf);
81 if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
82 dma_resv_fini(dmabuf->resv);
84 dma_buf_stats_teardown(dmabuf);
85 module_put(dmabuf->owner);
90 static int dma_buf_file_release(struct inode *inode, struct file *file)
92 struct dma_buf *dmabuf;
94 if (!is_dma_buf_file(file))
97 dmabuf = file->private_data;
99 mutex_lock(&db_list.lock);
100 list_del(&dmabuf->list_node);
101 mutex_unlock(&db_list.lock);
106 static const struct dentry_operations dma_buf_dentry_ops = {
107 .d_dname = dmabuffs_dname,
108 .d_release = dma_buf_release,
111 static struct vfsmount *dma_buf_mnt;
113 static int dma_buf_fs_init_context(struct fs_context *fc)
115 struct pseudo_fs_context *ctx;
117 ctx = init_pseudo(fc, DMA_BUF_MAGIC);
120 ctx->dops = &dma_buf_dentry_ops;
124 static struct file_system_type dma_buf_fs_type = {
126 .init_fs_context = dma_buf_fs_init_context,
127 .kill_sb = kill_anon_super,
130 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
132 struct dma_buf *dmabuf;
134 if (!is_dma_buf_file(file))
137 dmabuf = file->private_data;
139 /* check if buffer supports mmap */
140 if (!dmabuf->ops->mmap)
143 /* check for overflowing the buffer's size */
144 if (vma->vm_pgoff + vma_pages(vma) >
145 dmabuf->size >> PAGE_SHIFT)
148 return dmabuf->ops->mmap(dmabuf, vma);
151 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
153 struct dma_buf *dmabuf;
156 if (!is_dma_buf_file(file))
159 dmabuf = file->private_data;
161 /* only support discovering the end of the buffer,
162 but also allow SEEK_SET to maintain the idiomatic
163 SEEK_END(0), SEEK_CUR(0) pattern */
164 if (whence == SEEK_END)
166 else if (whence == SEEK_SET)
174 return base + offset;
178 * DOC: implicit fence polling
180 * To support cross-device and cross-driver synchronization of buffer access
181 * implicit fences (represented internally in the kernel with &struct dma_fence)
182 * can be attached to a &dma_buf. The glue for that and a few related things are
183 * provided in the &dma_resv structure.
185 * Userspace can query the state of these implicitly tracked fences using poll()
186 * and related system calls:
188 * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
189 * most recent write or exclusive fence.
191 * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
192 * all attached fences, shared and exclusive ones.
194 * Note that this only signals the completion of the respective fences, i.e. the
195 * DMA transfers are complete. Cache flushing and any other necessary
196 * preparations before CPU access can begin still need to happen.
199 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
201 struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
204 spin_lock_irqsave(&dcb->poll->lock, flags);
205 wake_up_locked_poll(dcb->poll, dcb->active);
207 spin_unlock_irqrestore(&dcb->poll->lock, flags);
210 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
212 struct dma_buf *dmabuf;
213 struct dma_resv *resv;
214 struct dma_resv_list *fobj;
215 struct dma_fence *fence_excl;
217 unsigned shared_count, seq;
219 dmabuf = file->private_data;
220 if (!dmabuf || !dmabuf->resv)
225 poll_wait(file, &dmabuf->poll, poll);
227 events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
232 seq = read_seqcount_begin(&resv->seq);
235 fobj = rcu_dereference(resv->fence);
237 shared_count = fobj->shared_count;
240 fence_excl = dma_resv_excl_fence(resv);
241 if (read_seqcount_retry(&resv->seq, seq)) {
246 if (fence_excl && (!(events & EPOLLOUT) || shared_count == 0)) {
247 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_excl;
248 __poll_t pevents = EPOLLIN;
250 if (shared_count == 0)
253 spin_lock_irq(&dmabuf->poll.lock);
255 dcb->active |= pevents;
258 dcb->active = pevents;
259 spin_unlock_irq(&dmabuf->poll.lock);
261 if (events & pevents) {
262 if (!dma_fence_get_rcu(fence_excl)) {
263 /* force a recheck */
265 dma_buf_poll_cb(NULL, &dcb->cb);
266 } else if (!dma_fence_add_callback(fence_excl, &dcb->cb,
269 dma_fence_put(fence_excl);
272 * No callback queued, wake up any additional
275 dma_fence_put(fence_excl);
276 dma_buf_poll_cb(NULL, &dcb->cb);
281 if ((events & EPOLLOUT) && shared_count > 0) {
282 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_shared;
285 /* Only queue a new callback if no event has fired yet */
286 spin_lock_irq(&dmabuf->poll.lock);
290 dcb->active = EPOLLOUT;
291 spin_unlock_irq(&dmabuf->poll.lock);
293 if (!(events & EPOLLOUT))
296 for (i = 0; i < shared_count; ++i) {
297 struct dma_fence *fence = rcu_dereference(fobj->shared[i]);
299 if (!dma_fence_get_rcu(fence)) {
301 * fence refcount dropped to zero, this means
302 * that fobj has been freed
304 * call dma_buf_poll_cb and force a recheck!
307 dma_buf_poll_cb(NULL, &dcb->cb);
310 if (!dma_fence_add_callback(fence, &dcb->cb,
312 dma_fence_put(fence);
316 dma_fence_put(fence);
319 /* No callback queued, wake up any additional waiters. */
320 if (i == shared_count)
321 dma_buf_poll_cb(NULL, &dcb->cb);
330 * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
331 * The name of the dma-buf buffer can only be set when the dma-buf is not
332 * attached to any devices. It could theoritically support changing the
333 * name of the dma-buf if the same piece of memory is used for multiple
334 * purpose between different devices.
336 * @dmabuf: [in] dmabuf buffer that will be renamed.
337 * @buf: [in] A piece of userspace memory that contains the name of
340 * Returns 0 on success. If the dma-buf buffer is already attached to
341 * devices, return -EBUSY.
344 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
346 char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
350 return PTR_ERR(name);
352 dma_resv_lock(dmabuf->resv, NULL);
353 if (!list_empty(&dmabuf->attachments)) {
358 spin_lock(&dmabuf->name_lock);
361 spin_unlock(&dmabuf->name_lock);
364 dma_resv_unlock(dmabuf->resv);
368 static long dma_buf_ioctl(struct file *file,
369 unsigned int cmd, unsigned long arg)
371 struct dma_buf *dmabuf;
372 struct dma_buf_sync sync;
373 enum dma_data_direction direction;
376 dmabuf = file->private_data;
379 case DMA_BUF_IOCTL_SYNC:
380 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
383 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
386 switch (sync.flags & DMA_BUF_SYNC_RW) {
387 case DMA_BUF_SYNC_READ:
388 direction = DMA_FROM_DEVICE;
390 case DMA_BUF_SYNC_WRITE:
391 direction = DMA_TO_DEVICE;
393 case DMA_BUF_SYNC_RW:
394 direction = DMA_BIDIRECTIONAL;
400 if (sync.flags & DMA_BUF_SYNC_END)
401 ret = dma_buf_end_cpu_access(dmabuf, direction);
403 ret = dma_buf_begin_cpu_access(dmabuf, direction);
407 case DMA_BUF_SET_NAME_A:
408 case DMA_BUF_SET_NAME_B:
409 return dma_buf_set_name(dmabuf, (const char __user *)arg);
416 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
418 struct dma_buf *dmabuf = file->private_data;
420 seq_printf(m, "size:\t%zu\n", dmabuf->size);
421 /* Don't count the temporary reference taken inside procfs seq_show */
422 seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
423 seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
424 spin_lock(&dmabuf->name_lock);
426 seq_printf(m, "name:\t%s\n", dmabuf->name);
427 spin_unlock(&dmabuf->name_lock);
430 static const struct file_operations dma_buf_fops = {
431 .release = dma_buf_file_release,
432 .mmap = dma_buf_mmap_internal,
433 .llseek = dma_buf_llseek,
434 .poll = dma_buf_poll,
435 .unlocked_ioctl = dma_buf_ioctl,
436 .compat_ioctl = compat_ptr_ioctl,
437 .show_fdinfo = dma_buf_show_fdinfo,
441 * is_dma_buf_file - Check if struct file* is associated with dma_buf
443 static inline int is_dma_buf_file(struct file *file)
445 return file->f_op == &dma_buf_fops;
448 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
451 struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
454 return ERR_CAST(inode);
456 inode->i_size = dmabuf->size;
457 inode_set_bytes(inode, dmabuf->size);
459 file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
460 flags, &dma_buf_fops);
463 file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
464 file->private_data = dmabuf;
465 file->f_path.dentry->d_fsdata = dmabuf;
475 * DOC: dma buf device access
477 * For device DMA access to a shared DMA buffer the usual sequence of operations
480 * 1. The exporter defines his exporter instance using
481 * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
482 * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
483 * as a file descriptor by calling dma_buf_fd().
485 * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
486 * to share with: First the filedescriptor is converted to a &dma_buf using
487 * dma_buf_get(). Then the buffer is attached to the device using
490 * Up to this stage the exporter is still free to migrate or reallocate the
493 * 3. Once the buffer is attached to all devices userspace can initiate DMA
494 * access to the shared buffer. In the kernel this is done by calling
495 * dma_buf_map_attachment() and dma_buf_unmap_attachment().
497 * 4. Once a driver is done with a shared buffer it needs to call
498 * dma_buf_detach() (after cleaning up any mappings) and then release the
499 * reference acquired with dma_buf_get() by calling dma_buf_put().
501 * For the detailed semantics exporters are expected to implement see
506 * dma_buf_export - Creates a new dma_buf, and associates an anon file
507 * with this buffer, so it can be exported.
508 * Also connect the allocator specific data and ops to the buffer.
509 * Additionally, provide a name string for exporter; useful in debugging.
511 * @exp_info: [in] holds all the export related information provided
512 * by the exporter. see &struct dma_buf_export_info
513 * for further details.
515 * Returns, on success, a newly created struct dma_buf object, which wraps the
516 * supplied private data and operations for struct dma_buf_ops. On either
517 * missing ops, or error in allocating struct dma_buf, will return negative
520 * For most cases the easiest way to create @exp_info is through the
521 * %DEFINE_DMA_BUF_EXPORT_INFO macro.
523 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
525 struct dma_buf *dmabuf;
526 struct dma_resv *resv = exp_info->resv;
528 size_t alloc_size = sizeof(struct dma_buf);
532 alloc_size += sizeof(struct dma_resv);
534 /* prevent &dma_buf[1] == dma_buf->resv */
537 if (WARN_ON(!exp_info->priv
539 || !exp_info->ops->map_dma_buf
540 || !exp_info->ops->unmap_dma_buf
541 || !exp_info->ops->release)) {
542 return ERR_PTR(-EINVAL);
545 if (WARN_ON(exp_info->ops->cache_sgt_mapping &&
546 (exp_info->ops->pin || exp_info->ops->unpin)))
547 return ERR_PTR(-EINVAL);
549 if (WARN_ON(!exp_info->ops->pin != !exp_info->ops->unpin))
550 return ERR_PTR(-EINVAL);
552 if (!try_module_get(exp_info->owner))
553 return ERR_PTR(-ENOENT);
555 dmabuf = kzalloc(alloc_size, GFP_KERNEL);
561 dmabuf->priv = exp_info->priv;
562 dmabuf->ops = exp_info->ops;
563 dmabuf->size = exp_info->size;
564 dmabuf->exp_name = exp_info->exp_name;
565 dmabuf->owner = exp_info->owner;
566 spin_lock_init(&dmabuf->name_lock);
567 init_waitqueue_head(&dmabuf->poll);
568 dmabuf->cb_excl.poll = dmabuf->cb_shared.poll = &dmabuf->poll;
569 dmabuf->cb_excl.active = dmabuf->cb_shared.active = 0;
572 resv = (struct dma_resv *)&dmabuf[1];
577 file = dma_buf_getfile(dmabuf, exp_info->flags);
583 file->f_mode |= FMODE_LSEEK;
586 ret = dma_buf_stats_setup(dmabuf);
590 mutex_init(&dmabuf->lock);
591 INIT_LIST_HEAD(&dmabuf->attachments);
593 mutex_lock(&db_list.lock);
594 list_add(&dmabuf->list_node, &db_list.head);
595 mutex_unlock(&db_list.lock);
601 * Set file->f_path.dentry->d_fsdata to NULL so that when
602 * dma_buf_release() gets invoked by dentry_ops, it exits
603 * early before calling the release() dma_buf op.
605 file->f_path.dentry->d_fsdata = NULL;
610 module_put(exp_info->owner);
613 EXPORT_SYMBOL_GPL(dma_buf_export);
616 * dma_buf_fd - returns a file descriptor for the given struct dma_buf
617 * @dmabuf: [in] pointer to dma_buf for which fd is required.
618 * @flags: [in] flags to give to fd
620 * On success, returns an associated 'fd'. Else, returns error.
622 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
626 if (!dmabuf || !dmabuf->file)
629 fd = get_unused_fd_flags(flags);
633 fd_install(fd, dmabuf->file);
637 EXPORT_SYMBOL_GPL(dma_buf_fd);
640 * dma_buf_get - returns the struct dma_buf related to an fd
641 * @fd: [in] fd associated with the struct dma_buf to be returned
643 * On success, returns the struct dma_buf associated with an fd; uses
644 * file's refcounting done by fget to increase refcount. returns ERR_PTR
647 struct dma_buf *dma_buf_get(int fd)
654 return ERR_PTR(-EBADF);
656 if (!is_dma_buf_file(file)) {
658 return ERR_PTR(-EINVAL);
661 return file->private_data;
663 EXPORT_SYMBOL_GPL(dma_buf_get);
666 * dma_buf_put - decreases refcount of the buffer
667 * @dmabuf: [in] buffer to reduce refcount of
669 * Uses file's refcounting done implicitly by fput().
671 * If, as a result of this call, the refcount becomes 0, the 'release' file
672 * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
673 * in turn, and frees the memory allocated for dmabuf when exported.
675 void dma_buf_put(struct dma_buf *dmabuf)
677 if (WARN_ON(!dmabuf || !dmabuf->file))
682 EXPORT_SYMBOL_GPL(dma_buf_put);
684 static void mangle_sg_table(struct sg_table *sg_table)
686 #ifdef CONFIG_DMABUF_DEBUG
688 struct scatterlist *sg;
690 /* To catch abuse of the underlying struct page by importers mix
691 * up the bits, but take care to preserve the low SG_ bits to
692 * not corrupt the sgt. The mixing is undone in __unmap_dma_buf
693 * before passing the sgt back to the exporter. */
694 for_each_sgtable_sg(sg_table, sg, i)
695 sg->page_link ^= ~0xffUL;
699 static struct sg_table * __map_dma_buf(struct dma_buf_attachment *attach,
700 enum dma_data_direction direction)
702 struct sg_table *sg_table;
704 sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
706 if (!IS_ERR_OR_NULL(sg_table))
707 mangle_sg_table(sg_table);
713 * dma_buf_dynamic_attach - Add the device to dma_buf's attachments list
714 * @dmabuf: [in] buffer to attach device to.
715 * @dev: [in] device to be attached.
716 * @importer_ops: [in] importer operations for the attachment
717 * @importer_priv: [in] importer private pointer for the attachment
719 * Returns struct dma_buf_attachment pointer for this attachment. Attachments
720 * must be cleaned up by calling dma_buf_detach().
722 * Optionally this calls &dma_buf_ops.attach to allow device-specific attach
727 * A pointer to newly created &dma_buf_attachment on success, or a negative
728 * error code wrapped into a pointer on failure.
730 * Note that this can fail if the backing storage of @dmabuf is in a place not
731 * accessible to @dev, and cannot be moved to a more suitable place. This is
732 * indicated with the error code -EBUSY.
734 struct dma_buf_attachment *
735 dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
736 const struct dma_buf_attach_ops *importer_ops,
739 struct dma_buf_attachment *attach;
741 unsigned int attach_uid;
743 if (WARN_ON(!dmabuf || !dev))
744 return ERR_PTR(-EINVAL);
746 if (WARN_ON(importer_ops && !importer_ops->move_notify))
747 return ERR_PTR(-EINVAL);
749 attach = kzalloc(sizeof(*attach), GFP_KERNEL);
751 return ERR_PTR(-ENOMEM);
754 attach->dmabuf = dmabuf;
756 attach->peer2peer = importer_ops->allow_peer2peer;
757 attach->importer_ops = importer_ops;
758 attach->importer_priv = importer_priv;
760 if (dmabuf->ops->attach) {
761 ret = dmabuf->ops->attach(dmabuf, attach);
765 dma_resv_lock(dmabuf->resv, NULL);
766 list_add(&attach->node, &dmabuf->attachments);
767 attach_uid = dma_buf_update_attach_uid(dmabuf);
768 dma_resv_unlock(dmabuf->resv);
770 ret = dma_buf_attach_stats_setup(attach, attach_uid);
774 /* When either the importer or the exporter can't handle dynamic
775 * mappings we cache the mapping here to avoid issues with the
776 * reservation object lock.
778 if (dma_buf_attachment_is_dynamic(attach) !=
779 dma_buf_is_dynamic(dmabuf)) {
780 struct sg_table *sgt;
782 if (dma_buf_is_dynamic(attach->dmabuf)) {
783 dma_resv_lock(attach->dmabuf->resv, NULL);
784 ret = dmabuf->ops->pin(attach);
789 sgt = __map_dma_buf(attach, DMA_BIDIRECTIONAL);
791 sgt = ERR_PTR(-ENOMEM);
796 if (dma_buf_is_dynamic(attach->dmabuf))
797 dma_resv_unlock(attach->dmabuf->resv);
799 attach->dir = DMA_BIDIRECTIONAL;
800 dma_buf_update_attachment_map_count(attach, 1 /* delta */);
810 if (dma_buf_is_dynamic(attach->dmabuf))
811 dmabuf->ops->unpin(attach);
814 if (dma_buf_is_dynamic(attach->dmabuf))
815 dma_resv_unlock(attach->dmabuf->resv);
818 dma_buf_detach(dmabuf, attach);
821 EXPORT_SYMBOL_GPL(dma_buf_dynamic_attach);
824 * dma_buf_attach - Wrapper for dma_buf_dynamic_attach
825 * @dmabuf: [in] buffer to attach device to.
826 * @dev: [in] device to be attached.
828 * Wrapper to call dma_buf_dynamic_attach() for drivers which still use a static
831 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
834 return dma_buf_dynamic_attach(dmabuf, dev, NULL, NULL);
836 EXPORT_SYMBOL_GPL(dma_buf_attach);
838 static void __unmap_dma_buf(struct dma_buf_attachment *attach,
839 struct sg_table *sg_table,
840 enum dma_data_direction direction)
842 /* uses XOR, hence this unmangles */
843 mangle_sg_table(sg_table);
845 attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
849 * dma_buf_detach - Remove the given attachment from dmabuf's attachments list
850 * @dmabuf: [in] buffer to detach from.
851 * @attach: [in] attachment to be detached; is free'd after this call.
853 * Clean up a device attachment obtained by calling dma_buf_attach().
855 * Optionally this calls &dma_buf_ops.detach for device-specific detach.
857 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
859 if (WARN_ON(!dmabuf || !attach))
863 if (dma_buf_is_dynamic(attach->dmabuf))
864 dma_resv_lock(attach->dmabuf->resv, NULL);
866 __unmap_dma_buf(attach, attach->sgt, attach->dir);
867 dma_buf_update_attachment_map_count(attach, -1 /* delta */);
869 if (dma_buf_is_dynamic(attach->dmabuf)) {
870 dmabuf->ops->unpin(attach);
871 dma_resv_unlock(attach->dmabuf->resv);
875 dma_resv_lock(dmabuf->resv, NULL);
876 list_del(&attach->node);
877 dma_resv_unlock(dmabuf->resv);
878 if (dmabuf->ops->detach)
879 dmabuf->ops->detach(dmabuf, attach);
881 dma_buf_attach_stats_teardown(attach);
884 EXPORT_SYMBOL_GPL(dma_buf_detach);
887 * dma_buf_pin - Lock down the DMA-buf
888 * @attach: [in] attachment which should be pinned
890 * Only dynamic importers (who set up @attach with dma_buf_dynamic_attach()) may
891 * call this, and only for limited use cases like scanout and not for temporary
892 * pin operations. It is not permitted to allow userspace to pin arbitrary
893 * amounts of buffers through this interface.
895 * Buffers must be unpinned by calling dma_buf_unpin().
898 * 0 on success, negative error code on failure.
900 int dma_buf_pin(struct dma_buf_attachment *attach)
902 struct dma_buf *dmabuf = attach->dmabuf;
905 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
907 dma_resv_assert_held(dmabuf->resv);
909 if (dmabuf->ops->pin)
910 ret = dmabuf->ops->pin(attach);
914 EXPORT_SYMBOL_GPL(dma_buf_pin);
917 * dma_buf_unpin - Unpin a DMA-buf
918 * @attach: [in] attachment which should be unpinned
920 * This unpins a buffer pinned by dma_buf_pin() and allows the exporter to move
921 * any mapping of @attach again and inform the importer through
922 * &dma_buf_attach_ops.move_notify.
924 void dma_buf_unpin(struct dma_buf_attachment *attach)
926 struct dma_buf *dmabuf = attach->dmabuf;
928 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
930 dma_resv_assert_held(dmabuf->resv);
932 if (dmabuf->ops->unpin)
933 dmabuf->ops->unpin(attach);
935 EXPORT_SYMBOL_GPL(dma_buf_unpin);
938 * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
939 * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
941 * @attach: [in] attachment whose scatterlist is to be returned
942 * @direction: [in] direction of DMA transfer
944 * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
945 * on error. May return -EINTR if it is interrupted by a signal.
947 * On success, the DMA addresses and lengths in the returned scatterlist are
950 * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
951 * the underlying backing storage is pinned for as long as a mapping exists,
952 * therefore users/importers should not hold onto a mapping for undue amounts of
955 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
956 enum dma_data_direction direction)
958 struct sg_table *sg_table;
963 if (WARN_ON(!attach || !attach->dmabuf))
964 return ERR_PTR(-EINVAL);
966 if (dma_buf_attachment_is_dynamic(attach))
967 dma_resv_assert_held(attach->dmabuf->resv);
971 * Two mappings with different directions for the same
972 * attachment are not allowed.
974 if (attach->dir != direction &&
975 attach->dir != DMA_BIDIRECTIONAL)
976 return ERR_PTR(-EBUSY);
981 if (dma_buf_is_dynamic(attach->dmabuf)) {
982 dma_resv_assert_held(attach->dmabuf->resv);
983 if (!IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY)) {
984 r = attach->dmabuf->ops->pin(attach);
990 sg_table = __map_dma_buf(attach, direction);
992 sg_table = ERR_PTR(-ENOMEM);
994 if (IS_ERR(sg_table) && dma_buf_is_dynamic(attach->dmabuf) &&
995 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
996 attach->dmabuf->ops->unpin(attach);
998 if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
999 attach->sgt = sg_table;
1000 attach->dir = direction;
1003 #ifdef CONFIG_DMA_API_DEBUG
1004 if (!IS_ERR(sg_table)) {
1005 struct scatterlist *sg;
1010 for_each_sgtable_dma_sg(sg_table, sg, i) {
1011 addr = sg_dma_address(sg);
1012 len = sg_dma_len(sg);
1013 if (!PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len)) {
1014 pr_debug("%s: addr %llx or len %x is not page aligned!\n",
1015 __func__, addr, len);
1019 #endif /* CONFIG_DMA_API_DEBUG */
1021 if (!IS_ERR(sg_table))
1022 dma_buf_update_attachment_map_count(attach, 1 /* delta */);
1026 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
1029 * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
1030 * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
1032 * @attach: [in] attachment to unmap buffer from
1033 * @sg_table: [in] scatterlist info of the buffer to unmap
1034 * @direction: [in] direction of DMA transfer
1036 * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
1038 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
1039 struct sg_table *sg_table,
1040 enum dma_data_direction direction)
1044 if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
1047 if (dma_buf_attachment_is_dynamic(attach))
1048 dma_resv_assert_held(attach->dmabuf->resv);
1050 if (attach->sgt == sg_table)
1053 if (dma_buf_is_dynamic(attach->dmabuf))
1054 dma_resv_assert_held(attach->dmabuf->resv);
1056 __unmap_dma_buf(attach, sg_table, direction);
1058 if (dma_buf_is_dynamic(attach->dmabuf) &&
1059 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
1060 dma_buf_unpin(attach);
1062 dma_buf_update_attachment_map_count(attach, -1 /* delta */);
1064 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
1067 * dma_buf_move_notify - notify attachments that DMA-buf is moving
1069 * @dmabuf: [in] buffer which is moving
1071 * Informs all attachmenst that they need to destroy and recreated all their
1074 void dma_buf_move_notify(struct dma_buf *dmabuf)
1076 struct dma_buf_attachment *attach;
1078 dma_resv_assert_held(dmabuf->resv);
1080 list_for_each_entry(attach, &dmabuf->attachments, node)
1081 if (attach->importer_ops)
1082 attach->importer_ops->move_notify(attach);
1084 EXPORT_SYMBOL_GPL(dma_buf_move_notify);
1089 * There are mutliple reasons for supporting CPU access to a dma buffer object:
1091 * - Fallback operations in the kernel, for example when a device is connected
1092 * over USB and the kernel needs to shuffle the data around first before
1093 * sending it away. Cache coherency is handled by braketing any transactions
1094 * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
1097 * Since for most kernel internal dma-buf accesses need the entire buffer, a
1098 * vmap interface is introduced. Note that on very old 32-bit architectures
1099 * vmalloc space might be limited and result in vmap calls failing.
1103 * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
1104 * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
1106 * The vmap call can fail if there is no vmap support in the exporter, or if
1107 * it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
1108 * count for all vmap access and calls down into the exporter's vmap function
1109 * only when no vmapping exists, and only unmaps it once. Protection against
1110 * concurrent vmap/vunmap calls is provided by taking the &dma_buf.lock mutex.
1112 * - For full compatibility on the importer side with existing userspace
1113 * interfaces, which might already support mmap'ing buffers. This is needed in
1114 * many processing pipelines (e.g. feeding a software rendered image into a
1115 * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
1116 * framework already supported this and for DMA buffer file descriptors to
1117 * replace ION buffers mmap support was needed.
1119 * There is no special interfaces, userspace simply calls mmap on the dma-buf
1120 * fd. But like for CPU access there's a need to braket the actual access,
1121 * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
1122 * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
1125 * Some systems might need some sort of cache coherency management e.g. when
1126 * CPU and GPU domains are being accessed through dma-buf at the same time.
1127 * To circumvent this problem there are begin/end coherency markers, that
1128 * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
1129 * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
1130 * sequence would be used like following:
1133 * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
1134 * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
1135 * want (with the new data being consumed by say the GPU or the scanout
1137 * - munmap once you don't need the buffer any more
1139 * For correctness and optimal performance, it is always required to use
1140 * SYNC_START and SYNC_END before and after, respectively, when accessing the
1141 * mapped address. Userspace cannot rely on coherent access, even when there
1142 * are systems where it just works without calling these ioctls.
1144 * - And as a CPU fallback in userspace processing pipelines.
1146 * Similar to the motivation for kernel cpu access it is again important that
1147 * the userspace code of a given importing subsystem can use the same
1148 * interfaces with a imported dma-buf buffer object as with a native buffer
1149 * object. This is especially important for drm where the userspace part of
1150 * contemporary OpenGL, X, and other drivers is huge, and reworking them to
1151 * use a different way to mmap a buffer rather invasive.
1153 * The assumption in the current dma-buf interfaces is that redirecting the
1154 * initial mmap is all that's needed. A survey of some of the existing
1155 * subsystems shows that no driver seems to do any nefarious thing like
1156 * syncing up with outstanding asynchronous processing on the device or
1157 * allocating special resources at fault time. So hopefully this is good
1158 * enough, since adding interfaces to intercept pagefaults and allow pte
1159 * shootdowns would increase the complexity quite a bit.
1163 * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
1166 * If the importing subsystem simply provides a special-purpose mmap call to
1167 * set up a mapping in userspace, calling do_mmap with &dma_buf.file will
1168 * equally achieve that for a dma-buf object.
1171 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1172 enum dma_data_direction direction)
1174 bool write = (direction == DMA_BIDIRECTIONAL ||
1175 direction == DMA_TO_DEVICE);
1176 struct dma_resv *resv = dmabuf->resv;
1179 /* Wait on any implicit rendering fences */
1180 ret = dma_resv_wait_timeout(resv, write, true, MAX_SCHEDULE_TIMEOUT);
1188 * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
1189 * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
1190 * preparations. Coherency is only guaranteed in the specified range for the
1191 * specified access direction.
1192 * @dmabuf: [in] buffer to prepare cpu access for.
1193 * @direction: [in] length of range for cpu access.
1195 * After the cpu access is complete the caller should call
1196 * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
1197 * it guaranteed to be coherent with other DMA access.
1199 * This function will also wait for any DMA transactions tracked through
1200 * implicit synchronization in &dma_buf.resv. For DMA transactions with explicit
1201 * synchronization this function will only ensure cache coherency, callers must
1202 * ensure synchronization with such DMA transactions on their own.
1204 * Can return negative error values, returns 0 on success.
1206 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1207 enum dma_data_direction direction)
1211 if (WARN_ON(!dmabuf))
1214 might_lock(&dmabuf->resv->lock.base);
1216 if (dmabuf->ops->begin_cpu_access)
1217 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
1219 /* Ensure that all fences are waited upon - but we first allow
1220 * the native handler the chance to do so more efficiently if it
1221 * chooses. A double invocation here will be reasonably cheap no-op.
1224 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
1228 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
1231 * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
1232 * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
1233 * actions. Coherency is only guaranteed in the specified range for the
1234 * specified access direction.
1235 * @dmabuf: [in] buffer to complete cpu access for.
1236 * @direction: [in] length of range for cpu access.
1238 * This terminates CPU access started with dma_buf_begin_cpu_access().
1240 * Can return negative error values, returns 0 on success.
1242 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
1243 enum dma_data_direction direction)
1249 might_lock(&dmabuf->resv->lock.base);
1251 if (dmabuf->ops->end_cpu_access)
1252 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
1256 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
1260 * dma_buf_mmap - Setup up a userspace mmap with the given vma
1261 * @dmabuf: [in] buffer that should back the vma
1262 * @vma: [in] vma for the mmap
1263 * @pgoff: [in] offset in pages where this mmap should start within the
1266 * This function adjusts the passed in vma so that it points at the file of the
1267 * dma_buf operation. It also adjusts the starting pgoff and does bounds
1268 * checking on the size of the vma. Then it calls the exporters mmap function to
1269 * set up the mapping.
1271 * Can return negative error values, returns 0 on success.
1273 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1274 unsigned long pgoff)
1276 if (WARN_ON(!dmabuf || !vma))
1279 /* check if buffer supports mmap */
1280 if (!dmabuf->ops->mmap)
1283 /* check for offset overflow */
1284 if (pgoff + vma_pages(vma) < pgoff)
1287 /* check for overflowing the buffer's size */
1288 if (pgoff + vma_pages(vma) >
1289 dmabuf->size >> PAGE_SHIFT)
1292 /* readjust the vma */
1293 vma_set_file(vma, dmabuf->file);
1294 vma->vm_pgoff = pgoff;
1296 return dmabuf->ops->mmap(dmabuf, vma);
1298 EXPORT_SYMBOL_GPL(dma_buf_mmap);
1301 * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1302 * address space. Same restrictions as for vmap and friends apply.
1303 * @dmabuf: [in] buffer to vmap
1304 * @map: [out] returns the vmap pointer
1306 * This call may fail due to lack of virtual mapping address space.
1307 * These calls are optional in drivers. The intended use for them
1308 * is for mapping objects linear in kernel space for high use objects.
1310 * To ensure coherency users must call dma_buf_begin_cpu_access() and
1311 * dma_buf_end_cpu_access() around any cpu access performed through this
1314 * Returns 0 on success, or a negative errno code otherwise.
1316 int dma_buf_vmap(struct dma_buf *dmabuf, struct dma_buf_map *map)
1318 struct dma_buf_map ptr;
1321 dma_buf_map_clear(map);
1323 if (WARN_ON(!dmabuf))
1326 if (!dmabuf->ops->vmap)
1329 mutex_lock(&dmabuf->lock);
1330 if (dmabuf->vmapping_counter) {
1331 dmabuf->vmapping_counter++;
1332 BUG_ON(dma_buf_map_is_null(&dmabuf->vmap_ptr));
1333 *map = dmabuf->vmap_ptr;
1337 BUG_ON(dma_buf_map_is_set(&dmabuf->vmap_ptr));
1339 ret = dmabuf->ops->vmap(dmabuf, &ptr);
1340 if (WARN_ON_ONCE(ret))
1343 dmabuf->vmap_ptr = ptr;
1344 dmabuf->vmapping_counter = 1;
1346 *map = dmabuf->vmap_ptr;
1349 mutex_unlock(&dmabuf->lock);
1352 EXPORT_SYMBOL_GPL(dma_buf_vmap);
1355 * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1356 * @dmabuf: [in] buffer to vunmap
1357 * @map: [in] vmap pointer to vunmap
1359 void dma_buf_vunmap(struct dma_buf *dmabuf, struct dma_buf_map *map)
1361 if (WARN_ON(!dmabuf))
1364 BUG_ON(dma_buf_map_is_null(&dmabuf->vmap_ptr));
1365 BUG_ON(dmabuf->vmapping_counter == 0);
1366 BUG_ON(!dma_buf_map_is_equal(&dmabuf->vmap_ptr, map));
1368 mutex_lock(&dmabuf->lock);
1369 if (--dmabuf->vmapping_counter == 0) {
1370 if (dmabuf->ops->vunmap)
1371 dmabuf->ops->vunmap(dmabuf, map);
1372 dma_buf_map_clear(&dmabuf->vmap_ptr);
1374 mutex_unlock(&dmabuf->lock);
1376 EXPORT_SYMBOL_GPL(dma_buf_vunmap);
1378 #ifdef CONFIG_DEBUG_FS
1379 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1381 struct dma_buf *buf_obj;
1382 struct dma_buf_attachment *attach_obj;
1383 struct dma_resv *robj;
1384 struct dma_resv_list *fobj;
1385 struct dma_fence *fence;
1386 int count = 0, attach_count, shared_count, i;
1390 ret = mutex_lock_interruptible(&db_list.lock);
1395 seq_puts(s, "\nDma-buf Objects:\n");
1396 seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\n",
1397 "size", "flags", "mode", "count", "ino");
1399 list_for_each_entry(buf_obj, &db_list.head, list_node) {
1401 ret = dma_resv_lock_interruptible(buf_obj->resv, NULL);
1405 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1407 buf_obj->file->f_flags, buf_obj->file->f_mode,
1408 file_count(buf_obj->file),
1410 file_inode(buf_obj->file)->i_ino,
1411 buf_obj->name ?: "");
1413 robj = buf_obj->resv;
1414 fence = dma_resv_excl_fence(robj);
1416 seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
1417 fence->ops->get_driver_name(fence),
1418 fence->ops->get_timeline_name(fence),
1419 dma_fence_is_signaled(fence) ? "" : "un");
1421 fobj = rcu_dereference_protected(robj->fence,
1422 dma_resv_held(robj));
1423 shared_count = fobj ? fobj->shared_count : 0;
1424 for (i = 0; i < shared_count; i++) {
1425 fence = rcu_dereference_protected(fobj->shared[i],
1426 dma_resv_held(robj));
1427 seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
1428 fence->ops->get_driver_name(fence),
1429 fence->ops->get_timeline_name(fence),
1430 dma_fence_is_signaled(fence) ? "" : "un");
1433 seq_puts(s, "\tAttached Devices:\n");
1436 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1437 seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1440 dma_resv_unlock(buf_obj->resv);
1442 seq_printf(s, "Total %d devices attached\n\n",
1446 size += buf_obj->size;
1449 seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1451 mutex_unlock(&db_list.lock);
1455 mutex_unlock(&db_list.lock);
1459 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1461 static struct dentry *dma_buf_debugfs_dir;
1463 static int dma_buf_init_debugfs(void)
1468 d = debugfs_create_dir("dma_buf", NULL);
1472 dma_buf_debugfs_dir = d;
1474 d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1475 NULL, &dma_buf_debug_fops);
1477 pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1478 debugfs_remove_recursive(dma_buf_debugfs_dir);
1479 dma_buf_debugfs_dir = NULL;
1486 static void dma_buf_uninit_debugfs(void)
1488 debugfs_remove_recursive(dma_buf_debugfs_dir);
1491 static inline int dma_buf_init_debugfs(void)
1495 static inline void dma_buf_uninit_debugfs(void)
1500 static int __init dma_buf_init(void)
1504 ret = dma_buf_init_sysfs_statistics();
1508 dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1509 if (IS_ERR(dma_buf_mnt))
1510 return PTR_ERR(dma_buf_mnt);
1512 mutex_init(&db_list.lock);
1513 INIT_LIST_HEAD(&db_list.head);
1514 dma_buf_init_debugfs();
1517 subsys_initcall(dma_buf_init);
1519 static void __exit dma_buf_deinit(void)
1521 dma_buf_uninit_debugfs();
1522 kern_unmount(dma_buf_mnt);
1523 dma_buf_uninit_sysfs_statistics();
1525 __exitcall(dma_buf_deinit);