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/dma-fence-unwrap.h>
19 #include <linux/anon_inodes.h>
20 #include <linux/export.h>
21 #include <linux/debugfs.h>
22 #include <linux/module.h>
23 #include <linux/seq_file.h>
24 #include <linux/sync_file.h>
25 #include <linux/poll.h>
26 #include <linux/dma-resv.h>
28 #include <linux/mount.h>
29 #include <linux/pseudo_fs.h>
31 #include <uapi/linux/dma-buf.h>
32 #include <uapi/linux/magic.h>
34 #include "dma-buf-sysfs-stats.h"
36 static inline int is_dma_buf_file(struct file *);
39 struct list_head head;
43 static struct dma_buf_list db_list;
45 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
47 struct dma_buf *dmabuf;
48 char name[DMA_BUF_NAME_LEN];
51 dmabuf = dentry->d_fsdata;
52 spin_lock(&dmabuf->name_lock);
54 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
55 spin_unlock(&dmabuf->name_lock);
57 return dynamic_dname(buffer, buflen, "/%s:%s",
58 dentry->d_name.name, ret > 0 ? name : "");
61 static void dma_buf_release(struct dentry *dentry)
63 struct dma_buf *dmabuf;
65 dmabuf = dentry->d_fsdata;
66 if (unlikely(!dmabuf))
69 BUG_ON(dmabuf->vmapping_counter);
72 * If you hit this BUG() it could mean:
73 * * There's a file reference imbalance in dma_buf_poll / dma_buf_poll_cb or somewhere else
74 * * dmabuf->cb_in/out.active are non-0 despite no pending fence callback
76 BUG_ON(dmabuf->cb_in.active || dmabuf->cb_out.active);
78 dma_buf_stats_teardown(dmabuf);
79 dmabuf->ops->release(dmabuf);
81 if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
82 dma_resv_fini(dmabuf->resv);
84 WARN_ON(!list_empty(&dmabuf->attachments));
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.
198 * As an alternative to poll(), the set of fences on DMA buffer can be
199 * exported as a &sync_file using &dma_buf_sync_file_export.
202 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
204 struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
205 struct dma_buf *dmabuf = container_of(dcb->poll, struct dma_buf, poll);
208 spin_lock_irqsave(&dcb->poll->lock, flags);
209 wake_up_locked_poll(dcb->poll, dcb->active);
211 spin_unlock_irqrestore(&dcb->poll->lock, flags);
212 dma_fence_put(fence);
213 /* Paired with get_file in dma_buf_poll */
217 static bool dma_buf_poll_add_cb(struct dma_resv *resv, bool write,
218 struct dma_buf_poll_cb_t *dcb)
220 struct dma_resv_iter cursor;
221 struct dma_fence *fence;
224 dma_resv_for_each_fence(&cursor, resv, dma_resv_usage_rw(write),
226 dma_fence_get(fence);
227 r = dma_fence_add_callback(fence, &dcb->cb, dma_buf_poll_cb);
230 dma_fence_put(fence);
236 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
238 struct dma_buf *dmabuf;
239 struct dma_resv *resv;
242 dmabuf = file->private_data;
243 if (!dmabuf || !dmabuf->resv)
248 poll_wait(file, &dmabuf->poll, poll);
250 events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
254 dma_resv_lock(resv, NULL);
256 if (events & EPOLLOUT) {
257 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_out;
259 /* Check that callback isn't busy */
260 spin_lock_irq(&dmabuf->poll.lock);
264 dcb->active = EPOLLOUT;
265 spin_unlock_irq(&dmabuf->poll.lock);
267 if (events & EPOLLOUT) {
268 /* Paired with fput in dma_buf_poll_cb */
269 get_file(dmabuf->file);
271 if (!dma_buf_poll_add_cb(resv, true, dcb))
272 /* No callback queued, wake up any other waiters */
273 dma_buf_poll_cb(NULL, &dcb->cb);
279 if (events & EPOLLIN) {
280 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_in;
282 /* Check that callback isn't busy */
283 spin_lock_irq(&dmabuf->poll.lock);
287 dcb->active = EPOLLIN;
288 spin_unlock_irq(&dmabuf->poll.lock);
290 if (events & EPOLLIN) {
291 /* Paired with fput in dma_buf_poll_cb */
292 get_file(dmabuf->file);
294 if (!dma_buf_poll_add_cb(resv, false, dcb))
295 /* No callback queued, wake up any other waiters */
296 dma_buf_poll_cb(NULL, &dcb->cb);
302 dma_resv_unlock(resv);
307 * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
308 * It could support changing the name of the dma-buf if the same
309 * piece of memory is used for multiple purpose between different devices.
311 * @dmabuf: [in] dmabuf buffer that will be renamed.
312 * @buf: [in] A piece of userspace memory that contains the name of
315 * Returns 0 on success. If the dma-buf buffer is already attached to
316 * devices, return -EBUSY.
319 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
321 char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
324 return PTR_ERR(name);
326 spin_lock(&dmabuf->name_lock);
329 spin_unlock(&dmabuf->name_lock);
334 #if IS_ENABLED(CONFIG_SYNC_FILE)
335 static long dma_buf_export_sync_file(struct dma_buf *dmabuf,
336 void __user *user_data)
338 struct dma_buf_export_sync_file arg;
339 enum dma_resv_usage usage;
340 struct dma_fence *fence = NULL;
341 struct sync_file *sync_file;
344 if (copy_from_user(&arg, user_data, sizeof(arg)))
347 if (arg.flags & ~DMA_BUF_SYNC_RW)
350 if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
353 fd = get_unused_fd_flags(O_CLOEXEC);
357 usage = dma_resv_usage_rw(arg.flags & DMA_BUF_SYNC_WRITE);
358 ret = dma_resv_get_singleton(dmabuf->resv, usage, &fence);
363 fence = dma_fence_get_stub();
365 sync_file = sync_file_create(fence);
367 dma_fence_put(fence);
375 if (copy_to_user(user_data, &arg, sizeof(arg))) {
380 fd_install(fd, sync_file->file);
385 fput(sync_file->file);
391 static long dma_buf_import_sync_file(struct dma_buf *dmabuf,
392 const void __user *user_data)
394 struct dma_buf_import_sync_file arg;
395 struct dma_fence *fence, *f;
396 enum dma_resv_usage usage;
397 struct dma_fence_unwrap iter;
398 unsigned int num_fences;
401 if (copy_from_user(&arg, user_data, sizeof(arg)))
404 if (arg.flags & ~DMA_BUF_SYNC_RW)
407 if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
410 fence = sync_file_get_fence(arg.fd);
414 usage = (arg.flags & DMA_BUF_SYNC_WRITE) ? DMA_RESV_USAGE_WRITE :
418 dma_fence_unwrap_for_each(f, &iter, fence)
421 if (num_fences > 0) {
422 dma_resv_lock(dmabuf->resv, NULL);
424 ret = dma_resv_reserve_fences(dmabuf->resv, num_fences);
426 dma_fence_unwrap_for_each(f, &iter, fence)
427 dma_resv_add_fence(dmabuf->resv, f, usage);
430 dma_resv_unlock(dmabuf->resv);
433 dma_fence_put(fence);
439 static long dma_buf_ioctl(struct file *file,
440 unsigned int cmd, unsigned long arg)
442 struct dma_buf *dmabuf;
443 struct dma_buf_sync sync;
444 enum dma_data_direction direction;
447 dmabuf = file->private_data;
450 case DMA_BUF_IOCTL_SYNC:
451 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
454 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
457 switch (sync.flags & DMA_BUF_SYNC_RW) {
458 case DMA_BUF_SYNC_READ:
459 direction = DMA_FROM_DEVICE;
461 case DMA_BUF_SYNC_WRITE:
462 direction = DMA_TO_DEVICE;
464 case DMA_BUF_SYNC_RW:
465 direction = DMA_BIDIRECTIONAL;
471 if (sync.flags & DMA_BUF_SYNC_END)
472 ret = dma_buf_end_cpu_access(dmabuf, direction);
474 ret = dma_buf_begin_cpu_access(dmabuf, direction);
478 case DMA_BUF_SET_NAME_A:
479 case DMA_BUF_SET_NAME_B:
480 return dma_buf_set_name(dmabuf, (const char __user *)arg);
482 #if IS_ENABLED(CONFIG_SYNC_FILE)
483 case DMA_BUF_IOCTL_EXPORT_SYNC_FILE:
484 return dma_buf_export_sync_file(dmabuf, (void __user *)arg);
485 case DMA_BUF_IOCTL_IMPORT_SYNC_FILE:
486 return dma_buf_import_sync_file(dmabuf, (const void __user *)arg);
494 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
496 struct dma_buf *dmabuf = file->private_data;
498 seq_printf(m, "size:\t%zu\n", dmabuf->size);
499 /* Don't count the temporary reference taken inside procfs seq_show */
500 seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
501 seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
502 spin_lock(&dmabuf->name_lock);
504 seq_printf(m, "name:\t%s\n", dmabuf->name);
505 spin_unlock(&dmabuf->name_lock);
508 static const struct file_operations dma_buf_fops = {
509 .release = dma_buf_file_release,
510 .mmap = dma_buf_mmap_internal,
511 .llseek = dma_buf_llseek,
512 .poll = dma_buf_poll,
513 .unlocked_ioctl = dma_buf_ioctl,
514 .compat_ioctl = compat_ptr_ioctl,
515 .show_fdinfo = dma_buf_show_fdinfo,
519 * is_dma_buf_file - Check if struct file* is associated with dma_buf
521 static inline int is_dma_buf_file(struct file *file)
523 return file->f_op == &dma_buf_fops;
526 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
528 static atomic64_t dmabuf_inode = ATOMIC64_INIT(0);
530 struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
533 return ERR_CAST(inode);
535 inode->i_size = dmabuf->size;
536 inode_set_bytes(inode, dmabuf->size);
539 * The ->i_ino acquired from get_next_ino() is not unique thus
540 * not suitable for using it as dentry name by dmabuf stats.
541 * Override ->i_ino with the unique and dmabuffs specific
544 inode->i_ino = atomic64_add_return(1, &dmabuf_inode);
545 flags &= O_ACCMODE | O_NONBLOCK;
546 file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
547 flags, &dma_buf_fops);
550 file->private_data = dmabuf;
551 file->f_path.dentry->d_fsdata = dmabuf;
561 * DOC: dma buf device access
563 * For device DMA access to a shared DMA buffer the usual sequence of operations
566 * 1. The exporter defines his exporter instance using
567 * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
568 * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
569 * as a file descriptor by calling dma_buf_fd().
571 * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
572 * to share with: First the file descriptor is converted to a &dma_buf using
573 * dma_buf_get(). Then the buffer is attached to the device using
576 * Up to this stage the exporter is still free to migrate or reallocate the
579 * 3. Once the buffer is attached to all devices userspace can initiate DMA
580 * access to the shared buffer. In the kernel this is done by calling
581 * dma_buf_map_attachment() and dma_buf_unmap_attachment().
583 * 4. Once a driver is done with a shared buffer it needs to call
584 * dma_buf_detach() (after cleaning up any mappings) and then release the
585 * reference acquired with dma_buf_get() by calling dma_buf_put().
587 * For the detailed semantics exporters are expected to implement see
592 * dma_buf_export - Creates a new dma_buf, and associates an anon file
593 * with this buffer, so it can be exported.
594 * Also connect the allocator specific data and ops to the buffer.
595 * Additionally, provide a name string for exporter; useful in debugging.
597 * @exp_info: [in] holds all the export related information provided
598 * by the exporter. see &struct dma_buf_export_info
599 * for further details.
601 * Returns, on success, a newly created struct dma_buf object, which wraps the
602 * supplied private data and operations for struct dma_buf_ops. On either
603 * missing ops, or error in allocating struct dma_buf, will return negative
606 * For most cases the easiest way to create @exp_info is through the
607 * %DEFINE_DMA_BUF_EXPORT_INFO macro.
609 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
611 struct dma_buf *dmabuf;
612 struct dma_resv *resv = exp_info->resv;
614 size_t alloc_size = sizeof(struct dma_buf);
618 alloc_size += sizeof(struct dma_resv);
620 /* prevent &dma_buf[1] == dma_buf->resv */
623 if (WARN_ON(!exp_info->priv
625 || !exp_info->ops->map_dma_buf
626 || !exp_info->ops->unmap_dma_buf
627 || !exp_info->ops->release)) {
628 return ERR_PTR(-EINVAL);
631 if (WARN_ON(exp_info->ops->cache_sgt_mapping &&
632 (exp_info->ops->pin || exp_info->ops->unpin)))
633 return ERR_PTR(-EINVAL);
635 if (WARN_ON(!exp_info->ops->pin != !exp_info->ops->unpin))
636 return ERR_PTR(-EINVAL);
638 if (!try_module_get(exp_info->owner))
639 return ERR_PTR(-ENOENT);
641 dmabuf = kzalloc(alloc_size, GFP_KERNEL);
647 dmabuf->priv = exp_info->priv;
648 dmabuf->ops = exp_info->ops;
649 dmabuf->size = exp_info->size;
650 dmabuf->exp_name = exp_info->exp_name;
651 dmabuf->owner = exp_info->owner;
652 spin_lock_init(&dmabuf->name_lock);
653 init_waitqueue_head(&dmabuf->poll);
654 dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
655 dmabuf->cb_in.active = dmabuf->cb_out.active = 0;
658 resv = (struct dma_resv *)&dmabuf[1];
663 file = dma_buf_getfile(dmabuf, exp_info->flags);
671 mutex_init(&dmabuf->lock);
672 INIT_LIST_HEAD(&dmabuf->attachments);
674 mutex_lock(&db_list.lock);
675 list_add(&dmabuf->list_node, &db_list.head);
676 mutex_unlock(&db_list.lock);
678 ret = dma_buf_stats_setup(dmabuf);
686 * Set file->f_path.dentry->d_fsdata to NULL so that when
687 * dma_buf_release() gets invoked by dentry_ops, it exits
688 * early before calling the release() dma_buf op.
690 file->f_path.dentry->d_fsdata = NULL;
695 module_put(exp_info->owner);
698 EXPORT_SYMBOL_NS_GPL(dma_buf_export, DMA_BUF);
701 * dma_buf_fd - returns a file descriptor for the given struct dma_buf
702 * @dmabuf: [in] pointer to dma_buf for which fd is required.
703 * @flags: [in] flags to give to fd
705 * On success, returns an associated 'fd'. Else, returns error.
707 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
711 if (!dmabuf || !dmabuf->file)
714 fd = get_unused_fd_flags(flags);
718 fd_install(fd, dmabuf->file);
722 EXPORT_SYMBOL_NS_GPL(dma_buf_fd, DMA_BUF);
725 * dma_buf_get - returns the struct dma_buf related to an fd
726 * @fd: [in] fd associated with the struct dma_buf to be returned
728 * On success, returns the struct dma_buf associated with an fd; uses
729 * file's refcounting done by fget to increase refcount. returns ERR_PTR
732 struct dma_buf *dma_buf_get(int fd)
739 return ERR_PTR(-EBADF);
741 if (!is_dma_buf_file(file)) {
743 return ERR_PTR(-EINVAL);
746 return file->private_data;
748 EXPORT_SYMBOL_NS_GPL(dma_buf_get, DMA_BUF);
751 * dma_buf_put - decreases refcount of the buffer
752 * @dmabuf: [in] buffer to reduce refcount of
754 * Uses file's refcounting done implicitly by fput().
756 * If, as a result of this call, the refcount becomes 0, the 'release' file
757 * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
758 * in turn, and frees the memory allocated for dmabuf when exported.
760 void dma_buf_put(struct dma_buf *dmabuf)
762 if (WARN_ON(!dmabuf || !dmabuf->file))
767 EXPORT_SYMBOL_NS_GPL(dma_buf_put, DMA_BUF);
769 static void mangle_sg_table(struct sg_table *sg_table)
771 #ifdef CONFIG_DMABUF_DEBUG
773 struct scatterlist *sg;
775 /* To catch abuse of the underlying struct page by importers mix
776 * up the bits, but take care to preserve the low SG_ bits to
777 * not corrupt the sgt. The mixing is undone in __unmap_dma_buf
778 * before passing the sgt back to the exporter. */
779 for_each_sgtable_sg(sg_table, sg, i)
780 sg->page_link ^= ~0xffUL;
784 static struct sg_table * __map_dma_buf(struct dma_buf_attachment *attach,
785 enum dma_data_direction direction)
787 struct sg_table *sg_table;
790 sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
791 if (IS_ERR_OR_NULL(sg_table))
794 if (!dma_buf_attachment_is_dynamic(attach)) {
795 ret = dma_resv_wait_timeout(attach->dmabuf->resv,
796 DMA_RESV_USAGE_KERNEL, true,
797 MAX_SCHEDULE_TIMEOUT);
799 attach->dmabuf->ops->unmap_dma_buf(attach, sg_table,
805 mangle_sg_table(sg_table);
810 * dma_buf_dynamic_attach - Add the device to dma_buf's attachments list
811 * @dmabuf: [in] buffer to attach device to.
812 * @dev: [in] device to be attached.
813 * @importer_ops: [in] importer operations for the attachment
814 * @importer_priv: [in] importer private pointer for the attachment
816 * Returns struct dma_buf_attachment pointer for this attachment. Attachments
817 * must be cleaned up by calling dma_buf_detach().
819 * Optionally this calls &dma_buf_ops.attach to allow device-specific attach
824 * A pointer to newly created &dma_buf_attachment on success, or a negative
825 * error code wrapped into a pointer on failure.
827 * Note that this can fail if the backing storage of @dmabuf is in a place not
828 * accessible to @dev, and cannot be moved to a more suitable place. This is
829 * indicated with the error code -EBUSY.
831 struct dma_buf_attachment *
832 dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
833 const struct dma_buf_attach_ops *importer_ops,
836 struct dma_buf_attachment *attach;
839 if (WARN_ON(!dmabuf || !dev))
840 return ERR_PTR(-EINVAL);
842 if (WARN_ON(importer_ops && !importer_ops->move_notify))
843 return ERR_PTR(-EINVAL);
845 attach = kzalloc(sizeof(*attach), GFP_KERNEL);
847 return ERR_PTR(-ENOMEM);
850 attach->dmabuf = dmabuf;
852 attach->peer2peer = importer_ops->allow_peer2peer;
853 attach->importer_ops = importer_ops;
854 attach->importer_priv = importer_priv;
856 if (dmabuf->ops->attach) {
857 ret = dmabuf->ops->attach(dmabuf, attach);
861 dma_resv_lock(dmabuf->resv, NULL);
862 list_add(&attach->node, &dmabuf->attachments);
863 dma_resv_unlock(dmabuf->resv);
865 /* When either the importer or the exporter can't handle dynamic
866 * mappings we cache the mapping here to avoid issues with the
867 * reservation object lock.
869 if (dma_buf_attachment_is_dynamic(attach) !=
870 dma_buf_is_dynamic(dmabuf)) {
871 struct sg_table *sgt;
873 if (dma_buf_is_dynamic(attach->dmabuf)) {
874 dma_resv_lock(attach->dmabuf->resv, NULL);
875 ret = dmabuf->ops->pin(attach);
880 sgt = __map_dma_buf(attach, DMA_BIDIRECTIONAL);
882 sgt = ERR_PTR(-ENOMEM);
887 if (dma_buf_is_dynamic(attach->dmabuf))
888 dma_resv_unlock(attach->dmabuf->resv);
890 attach->dir = DMA_BIDIRECTIONAL;
900 if (dma_buf_is_dynamic(attach->dmabuf))
901 dmabuf->ops->unpin(attach);
904 if (dma_buf_is_dynamic(attach->dmabuf))
905 dma_resv_unlock(attach->dmabuf->resv);
907 dma_buf_detach(dmabuf, attach);
910 EXPORT_SYMBOL_NS_GPL(dma_buf_dynamic_attach, DMA_BUF);
913 * dma_buf_attach - Wrapper for dma_buf_dynamic_attach
914 * @dmabuf: [in] buffer to attach device to.
915 * @dev: [in] device to be attached.
917 * Wrapper to call dma_buf_dynamic_attach() for drivers which still use a static
920 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
923 return dma_buf_dynamic_attach(dmabuf, dev, NULL, NULL);
925 EXPORT_SYMBOL_NS_GPL(dma_buf_attach, DMA_BUF);
927 static void __unmap_dma_buf(struct dma_buf_attachment *attach,
928 struct sg_table *sg_table,
929 enum dma_data_direction direction)
931 /* uses XOR, hence this unmangles */
932 mangle_sg_table(sg_table);
934 attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
938 * dma_buf_detach - Remove the given attachment from dmabuf's attachments list
939 * @dmabuf: [in] buffer to detach from.
940 * @attach: [in] attachment to be detached; is free'd after this call.
942 * Clean up a device attachment obtained by calling dma_buf_attach().
944 * Optionally this calls &dma_buf_ops.detach for device-specific detach.
946 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
948 if (WARN_ON(!dmabuf || !attach))
952 if (dma_buf_is_dynamic(attach->dmabuf))
953 dma_resv_lock(attach->dmabuf->resv, NULL);
955 __unmap_dma_buf(attach, attach->sgt, attach->dir);
957 if (dma_buf_is_dynamic(attach->dmabuf)) {
958 dmabuf->ops->unpin(attach);
959 dma_resv_unlock(attach->dmabuf->resv);
963 dma_resv_lock(dmabuf->resv, NULL);
964 list_del(&attach->node);
965 dma_resv_unlock(dmabuf->resv);
966 if (dmabuf->ops->detach)
967 dmabuf->ops->detach(dmabuf, attach);
971 EXPORT_SYMBOL_NS_GPL(dma_buf_detach, DMA_BUF);
974 * dma_buf_pin - Lock down the DMA-buf
975 * @attach: [in] attachment which should be pinned
977 * Only dynamic importers (who set up @attach with dma_buf_dynamic_attach()) may
978 * call this, and only for limited use cases like scanout and not for temporary
979 * pin operations. It is not permitted to allow userspace to pin arbitrary
980 * amounts of buffers through this interface.
982 * Buffers must be unpinned by calling dma_buf_unpin().
985 * 0 on success, negative error code on failure.
987 int dma_buf_pin(struct dma_buf_attachment *attach)
989 struct dma_buf *dmabuf = attach->dmabuf;
992 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
994 dma_resv_assert_held(dmabuf->resv);
996 if (dmabuf->ops->pin)
997 ret = dmabuf->ops->pin(attach);
1001 EXPORT_SYMBOL_NS_GPL(dma_buf_pin, DMA_BUF);
1004 * dma_buf_unpin - Unpin a DMA-buf
1005 * @attach: [in] attachment which should be unpinned
1007 * This unpins a buffer pinned by dma_buf_pin() and allows the exporter to move
1008 * any mapping of @attach again and inform the importer through
1009 * &dma_buf_attach_ops.move_notify.
1011 void dma_buf_unpin(struct dma_buf_attachment *attach)
1013 struct dma_buf *dmabuf = attach->dmabuf;
1015 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
1017 dma_resv_assert_held(dmabuf->resv);
1019 if (dmabuf->ops->unpin)
1020 dmabuf->ops->unpin(attach);
1022 EXPORT_SYMBOL_NS_GPL(dma_buf_unpin, DMA_BUF);
1025 * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
1026 * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
1028 * @attach: [in] attachment whose scatterlist is to be returned
1029 * @direction: [in] direction of DMA transfer
1031 * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
1032 * on error. May return -EINTR if it is interrupted by a signal.
1034 * On success, the DMA addresses and lengths in the returned scatterlist are
1035 * PAGE_SIZE aligned.
1037 * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
1038 * the underlying backing storage is pinned for as long as a mapping exists,
1039 * therefore users/importers should not hold onto a mapping for undue amounts of
1042 * Important: Dynamic importers must wait for the exclusive fence of the struct
1043 * dma_resv attached to the DMA-BUF first.
1045 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
1046 enum dma_data_direction direction)
1048 struct sg_table *sg_table;
1053 if (WARN_ON(!attach || !attach->dmabuf))
1054 return ERR_PTR(-EINVAL);
1056 if (dma_buf_attachment_is_dynamic(attach))
1057 dma_resv_assert_held(attach->dmabuf->resv);
1061 * Two mappings with different directions for the same
1062 * attachment are not allowed.
1064 if (attach->dir != direction &&
1065 attach->dir != DMA_BIDIRECTIONAL)
1066 return ERR_PTR(-EBUSY);
1071 if (dma_buf_is_dynamic(attach->dmabuf)) {
1072 dma_resv_assert_held(attach->dmabuf->resv);
1073 if (!IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY)) {
1074 r = attach->dmabuf->ops->pin(attach);
1080 sg_table = __map_dma_buf(attach, direction);
1082 sg_table = ERR_PTR(-ENOMEM);
1084 if (IS_ERR(sg_table) && dma_buf_is_dynamic(attach->dmabuf) &&
1085 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
1086 attach->dmabuf->ops->unpin(attach);
1088 if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
1089 attach->sgt = sg_table;
1090 attach->dir = direction;
1093 #ifdef CONFIG_DMA_API_DEBUG
1094 if (!IS_ERR(sg_table)) {
1095 struct scatterlist *sg;
1100 for_each_sgtable_dma_sg(sg_table, sg, i) {
1101 addr = sg_dma_address(sg);
1102 len = sg_dma_len(sg);
1103 if (!PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len)) {
1104 pr_debug("%s: addr %llx or len %x is not page aligned!\n",
1105 __func__, addr, len);
1109 #endif /* CONFIG_DMA_API_DEBUG */
1112 EXPORT_SYMBOL_NS_GPL(dma_buf_map_attachment, DMA_BUF);
1115 * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
1116 * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
1118 * @attach: [in] attachment to unmap buffer from
1119 * @sg_table: [in] scatterlist info of the buffer to unmap
1120 * @direction: [in] direction of DMA transfer
1122 * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
1124 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
1125 struct sg_table *sg_table,
1126 enum dma_data_direction direction)
1130 if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
1133 if (dma_buf_attachment_is_dynamic(attach))
1134 dma_resv_assert_held(attach->dmabuf->resv);
1136 if (attach->sgt == sg_table)
1139 if (dma_buf_is_dynamic(attach->dmabuf))
1140 dma_resv_assert_held(attach->dmabuf->resv);
1142 __unmap_dma_buf(attach, sg_table, direction);
1144 if (dma_buf_is_dynamic(attach->dmabuf) &&
1145 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
1146 dma_buf_unpin(attach);
1148 EXPORT_SYMBOL_NS_GPL(dma_buf_unmap_attachment, DMA_BUF);
1151 * dma_buf_move_notify - notify attachments that DMA-buf is moving
1153 * @dmabuf: [in] buffer which is moving
1155 * Informs all attachmenst that they need to destroy and recreated all their
1158 void dma_buf_move_notify(struct dma_buf *dmabuf)
1160 struct dma_buf_attachment *attach;
1162 dma_resv_assert_held(dmabuf->resv);
1164 list_for_each_entry(attach, &dmabuf->attachments, node)
1165 if (attach->importer_ops)
1166 attach->importer_ops->move_notify(attach);
1168 EXPORT_SYMBOL_NS_GPL(dma_buf_move_notify, DMA_BUF);
1173 * There are mutliple reasons for supporting CPU access to a dma buffer object:
1175 * - Fallback operations in the kernel, for example when a device is connected
1176 * over USB and the kernel needs to shuffle the data around first before
1177 * sending it away. Cache coherency is handled by braketing any transactions
1178 * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
1181 * Since for most kernel internal dma-buf accesses need the entire buffer, a
1182 * vmap interface is introduced. Note that on very old 32-bit architectures
1183 * vmalloc space might be limited and result in vmap calls failing.
1187 * void \*dma_buf_vmap(struct dma_buf \*dmabuf, struct iosys_map \*map)
1188 * void dma_buf_vunmap(struct dma_buf \*dmabuf, struct iosys_map \*map)
1190 * The vmap call can fail if there is no vmap support in the exporter, or if
1191 * it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
1192 * count for all vmap access and calls down into the exporter's vmap function
1193 * only when no vmapping exists, and only unmaps it once. Protection against
1194 * concurrent vmap/vunmap calls is provided by taking the &dma_buf.lock mutex.
1196 * - For full compatibility on the importer side with existing userspace
1197 * interfaces, which might already support mmap'ing buffers. This is needed in
1198 * many processing pipelines (e.g. feeding a software rendered image into a
1199 * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
1200 * framework already supported this and for DMA buffer file descriptors to
1201 * replace ION buffers mmap support was needed.
1203 * There is no special interfaces, userspace simply calls mmap on the dma-buf
1204 * fd. But like for CPU access there's a need to braket the actual access,
1205 * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
1206 * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
1209 * Some systems might need some sort of cache coherency management e.g. when
1210 * CPU and GPU domains are being accessed through dma-buf at the same time.
1211 * To circumvent this problem there are begin/end coherency markers, that
1212 * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
1213 * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
1214 * sequence would be used like following:
1217 * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
1218 * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
1219 * want (with the new data being consumed by say the GPU or the scanout
1221 * - munmap once you don't need the buffer any more
1223 * For correctness and optimal performance, it is always required to use
1224 * SYNC_START and SYNC_END before and after, respectively, when accessing the
1225 * mapped address. Userspace cannot rely on coherent access, even when there
1226 * are systems where it just works without calling these ioctls.
1228 * - And as a CPU fallback in userspace processing pipelines.
1230 * Similar to the motivation for kernel cpu access it is again important that
1231 * the userspace code of a given importing subsystem can use the same
1232 * interfaces with a imported dma-buf buffer object as with a native buffer
1233 * object. This is especially important for drm where the userspace part of
1234 * contemporary OpenGL, X, and other drivers is huge, and reworking them to
1235 * use a different way to mmap a buffer rather invasive.
1237 * The assumption in the current dma-buf interfaces is that redirecting the
1238 * initial mmap is all that's needed. A survey of some of the existing
1239 * subsystems shows that no driver seems to do any nefarious thing like
1240 * syncing up with outstanding asynchronous processing on the device or
1241 * allocating special resources at fault time. So hopefully this is good
1242 * enough, since adding interfaces to intercept pagefaults and allow pte
1243 * shootdowns would increase the complexity quite a bit.
1247 * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
1250 * If the importing subsystem simply provides a special-purpose mmap call to
1251 * set up a mapping in userspace, calling do_mmap with &dma_buf.file will
1252 * equally achieve that for a dma-buf object.
1255 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1256 enum dma_data_direction direction)
1258 bool write = (direction == DMA_BIDIRECTIONAL ||
1259 direction == DMA_TO_DEVICE);
1260 struct dma_resv *resv = dmabuf->resv;
1263 /* Wait on any implicit rendering fences */
1264 ret = dma_resv_wait_timeout(resv, dma_resv_usage_rw(write),
1265 true, MAX_SCHEDULE_TIMEOUT);
1273 * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
1274 * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
1275 * preparations. Coherency is only guaranteed in the specified range for the
1276 * specified access direction.
1277 * @dmabuf: [in] buffer to prepare cpu access for.
1278 * @direction: [in] length of range for cpu access.
1280 * After the cpu access is complete the caller should call
1281 * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
1282 * it guaranteed to be coherent with other DMA access.
1284 * This function will also wait for any DMA transactions tracked through
1285 * implicit synchronization in &dma_buf.resv. For DMA transactions with explicit
1286 * synchronization this function will only ensure cache coherency, callers must
1287 * ensure synchronization with such DMA transactions on their own.
1289 * Can return negative error values, returns 0 on success.
1291 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1292 enum dma_data_direction direction)
1296 if (WARN_ON(!dmabuf))
1299 might_lock(&dmabuf->resv->lock.base);
1301 if (dmabuf->ops->begin_cpu_access)
1302 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
1304 /* Ensure that all fences are waited upon - but we first allow
1305 * the native handler the chance to do so more efficiently if it
1306 * chooses. A double invocation here will be reasonably cheap no-op.
1309 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
1313 EXPORT_SYMBOL_NS_GPL(dma_buf_begin_cpu_access, DMA_BUF);
1316 * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
1317 * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
1318 * actions. Coherency is only guaranteed in the specified range for the
1319 * specified access direction.
1320 * @dmabuf: [in] buffer to complete cpu access for.
1321 * @direction: [in] length of range for cpu access.
1323 * This terminates CPU access started with dma_buf_begin_cpu_access().
1325 * Can return negative error values, returns 0 on success.
1327 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
1328 enum dma_data_direction direction)
1334 might_lock(&dmabuf->resv->lock.base);
1336 if (dmabuf->ops->end_cpu_access)
1337 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
1341 EXPORT_SYMBOL_NS_GPL(dma_buf_end_cpu_access, DMA_BUF);
1345 * dma_buf_mmap - Setup up a userspace mmap with the given vma
1346 * @dmabuf: [in] buffer that should back the vma
1347 * @vma: [in] vma for the mmap
1348 * @pgoff: [in] offset in pages where this mmap should start within the
1351 * This function adjusts the passed in vma so that it points at the file of the
1352 * dma_buf operation. It also adjusts the starting pgoff and does bounds
1353 * checking on the size of the vma. Then it calls the exporters mmap function to
1354 * set up the mapping.
1356 * Can return negative error values, returns 0 on success.
1358 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1359 unsigned long pgoff)
1361 if (WARN_ON(!dmabuf || !vma))
1364 /* check if buffer supports mmap */
1365 if (!dmabuf->ops->mmap)
1368 /* check for offset overflow */
1369 if (pgoff + vma_pages(vma) < pgoff)
1372 /* check for overflowing the buffer's size */
1373 if (pgoff + vma_pages(vma) >
1374 dmabuf->size >> PAGE_SHIFT)
1377 /* readjust the vma */
1378 vma_set_file(vma, dmabuf->file);
1379 vma->vm_pgoff = pgoff;
1381 return dmabuf->ops->mmap(dmabuf, vma);
1383 EXPORT_SYMBOL_NS_GPL(dma_buf_mmap, DMA_BUF);
1386 * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1387 * address space. Same restrictions as for vmap and friends apply.
1388 * @dmabuf: [in] buffer to vmap
1389 * @map: [out] returns the vmap pointer
1391 * This call may fail due to lack of virtual mapping address space.
1392 * These calls are optional in drivers. The intended use for them
1393 * is for mapping objects linear in kernel space for high use objects.
1395 * To ensure coherency users must call dma_buf_begin_cpu_access() and
1396 * dma_buf_end_cpu_access() around any cpu access performed through this
1399 * Returns 0 on success, or a negative errno code otherwise.
1401 int dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
1403 struct iosys_map ptr;
1406 iosys_map_clear(map);
1408 if (WARN_ON(!dmabuf))
1411 if (!dmabuf->ops->vmap)
1414 mutex_lock(&dmabuf->lock);
1415 if (dmabuf->vmapping_counter) {
1416 dmabuf->vmapping_counter++;
1417 BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
1418 *map = dmabuf->vmap_ptr;
1422 BUG_ON(iosys_map_is_set(&dmabuf->vmap_ptr));
1424 ret = dmabuf->ops->vmap(dmabuf, &ptr);
1425 if (WARN_ON_ONCE(ret))
1428 dmabuf->vmap_ptr = ptr;
1429 dmabuf->vmapping_counter = 1;
1431 *map = dmabuf->vmap_ptr;
1434 mutex_unlock(&dmabuf->lock);
1437 EXPORT_SYMBOL_NS_GPL(dma_buf_vmap, DMA_BUF);
1440 * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1441 * @dmabuf: [in] buffer to vunmap
1442 * @map: [in] vmap pointer to vunmap
1444 void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
1446 if (WARN_ON(!dmabuf))
1449 BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
1450 BUG_ON(dmabuf->vmapping_counter == 0);
1451 BUG_ON(!iosys_map_is_equal(&dmabuf->vmap_ptr, map));
1453 mutex_lock(&dmabuf->lock);
1454 if (--dmabuf->vmapping_counter == 0) {
1455 if (dmabuf->ops->vunmap)
1456 dmabuf->ops->vunmap(dmabuf, map);
1457 iosys_map_clear(&dmabuf->vmap_ptr);
1459 mutex_unlock(&dmabuf->lock);
1461 EXPORT_SYMBOL_NS_GPL(dma_buf_vunmap, DMA_BUF);
1463 #ifdef CONFIG_DEBUG_FS
1464 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1466 struct dma_buf *buf_obj;
1467 struct dma_buf_attachment *attach_obj;
1468 int count = 0, attach_count;
1472 ret = mutex_lock_interruptible(&db_list.lock);
1477 seq_puts(s, "\nDma-buf Objects:\n");
1478 seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\tname\n",
1479 "size", "flags", "mode", "count", "ino");
1481 list_for_each_entry(buf_obj, &db_list.head, list_node) {
1483 ret = dma_resv_lock_interruptible(buf_obj->resv, NULL);
1488 spin_lock(&buf_obj->name_lock);
1489 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1491 buf_obj->file->f_flags, buf_obj->file->f_mode,
1492 file_count(buf_obj->file),
1494 file_inode(buf_obj->file)->i_ino,
1495 buf_obj->name ?: "<none>");
1496 spin_unlock(&buf_obj->name_lock);
1498 dma_resv_describe(buf_obj->resv, s);
1500 seq_puts(s, "\tAttached Devices:\n");
1503 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1504 seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1507 dma_resv_unlock(buf_obj->resv);
1509 seq_printf(s, "Total %d devices attached\n\n",
1513 size += buf_obj->size;
1516 seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1518 mutex_unlock(&db_list.lock);
1522 mutex_unlock(&db_list.lock);
1526 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1528 static struct dentry *dma_buf_debugfs_dir;
1530 static int dma_buf_init_debugfs(void)
1535 d = debugfs_create_dir("dma_buf", NULL);
1539 dma_buf_debugfs_dir = d;
1541 d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1542 NULL, &dma_buf_debug_fops);
1544 pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1545 debugfs_remove_recursive(dma_buf_debugfs_dir);
1546 dma_buf_debugfs_dir = NULL;
1553 static void dma_buf_uninit_debugfs(void)
1555 debugfs_remove_recursive(dma_buf_debugfs_dir);
1558 static inline int dma_buf_init_debugfs(void)
1562 static inline void dma_buf_uninit_debugfs(void)
1567 static int __init dma_buf_init(void)
1571 ret = dma_buf_init_sysfs_statistics();
1575 dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1576 if (IS_ERR(dma_buf_mnt))
1577 return PTR_ERR(dma_buf_mnt);
1579 mutex_init(&db_list.lock);
1580 INIT_LIST_HEAD(&db_list.head);
1581 dma_buf_init_debugfs();
1584 subsys_initcall(dma_buf_init);
1586 static void __exit dma_buf_deinit(void)
1588 dma_buf_uninit_debugfs();
1589 kern_unmount(dma_buf_mnt);
1590 dma_buf_uninit_sysfs_statistics();
1592 __exitcall(dma_buf_deinit);