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/reservation.h>
26 #include <linux/mount.h>
28 #include <uapi/linux/dma-buf.h>
29 #include <uapi/linux/magic.h>
31 static inline int is_dma_buf_file(struct file *);
34 struct list_head head;
38 static struct dma_buf_list db_list;
40 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
42 struct dma_buf *dmabuf;
43 char name[DMA_BUF_NAME_LEN];
46 dmabuf = dentry->d_fsdata;
47 mutex_lock(&dmabuf->lock);
49 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
50 mutex_unlock(&dmabuf->lock);
52 return dynamic_dname(dentry, buffer, buflen, "/%s:%s",
53 dentry->d_name.name, ret > 0 ? name : "");
56 static const struct dentry_operations dma_buf_dentry_ops = {
57 .d_dname = dmabuffs_dname,
60 static struct vfsmount *dma_buf_mnt;
62 static struct dentry *dma_buf_fs_mount(struct file_system_type *fs_type,
63 int flags, const char *name, void *data)
65 return mount_pseudo(fs_type, "dmabuf:", NULL, &dma_buf_dentry_ops,
69 static struct file_system_type dma_buf_fs_type = {
71 .mount = dma_buf_fs_mount,
72 .kill_sb = kill_anon_super,
75 static int dma_buf_release(struct inode *inode, struct file *file)
77 struct dma_buf *dmabuf;
79 if (!is_dma_buf_file(file))
82 dmabuf = file->private_data;
84 BUG_ON(dmabuf->vmapping_counter);
87 * Any fences that a dma-buf poll can wait on should be signaled
88 * before releasing dma-buf. This is the responsibility of each
89 * driver that uses the reservation objects.
91 * If you hit this BUG() it means someone dropped their ref to the
92 * dma-buf while still having pending operation to the buffer.
94 BUG_ON(dmabuf->cb_shared.active || dmabuf->cb_excl.active);
96 dmabuf->ops->release(dmabuf);
98 mutex_lock(&db_list.lock);
99 list_del(&dmabuf->list_node);
100 mutex_unlock(&db_list.lock);
102 if (dmabuf->resv == (struct reservation_object *)&dmabuf[1])
103 reservation_object_fini(dmabuf->resv);
105 module_put(dmabuf->owner);
110 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
112 struct dma_buf *dmabuf;
114 if (!is_dma_buf_file(file))
117 dmabuf = file->private_data;
119 /* check if buffer supports mmap */
120 if (!dmabuf->ops->mmap)
123 /* check for overflowing the buffer's size */
124 if (vma->vm_pgoff + vma_pages(vma) >
125 dmabuf->size >> PAGE_SHIFT)
128 return dmabuf->ops->mmap(dmabuf, vma);
131 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
133 struct dma_buf *dmabuf;
136 if (!is_dma_buf_file(file))
139 dmabuf = file->private_data;
141 /* only support discovering the end of the buffer,
142 but also allow SEEK_SET to maintain the idiomatic
143 SEEK_END(0), SEEK_CUR(0) pattern */
144 if (whence == SEEK_END)
146 else if (whence == SEEK_SET)
154 return base + offset;
160 * To support cross-device and cross-driver synchronization of buffer access
161 * implicit fences (represented internally in the kernel with &struct fence) can
162 * be attached to a &dma_buf. The glue for that and a few related things are
163 * provided in the &reservation_object structure.
165 * Userspace can query the state of these implicitly tracked fences using poll()
166 * and related system calls:
168 * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
169 * most recent write or exclusive fence.
171 * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
172 * all attached fences, shared and exclusive ones.
174 * Note that this only signals the completion of the respective fences, i.e. the
175 * DMA transfers are complete. Cache flushing and any other necessary
176 * preparations before CPU access can begin still need to happen.
179 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
181 struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
184 spin_lock_irqsave(&dcb->poll->lock, flags);
185 wake_up_locked_poll(dcb->poll, dcb->active);
187 spin_unlock_irqrestore(&dcb->poll->lock, flags);
190 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
192 struct dma_buf *dmabuf;
193 struct reservation_object *resv;
194 struct reservation_object_list *fobj;
195 struct dma_fence *fence_excl;
197 unsigned shared_count, seq;
199 dmabuf = file->private_data;
200 if (!dmabuf || !dmabuf->resv)
205 poll_wait(file, &dmabuf->poll, poll);
207 events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
212 seq = read_seqcount_begin(&resv->seq);
215 fobj = rcu_dereference(resv->fence);
217 shared_count = fobj->shared_count;
220 fence_excl = rcu_dereference(resv->fence_excl);
221 if (read_seqcount_retry(&resv->seq, seq)) {
226 if (fence_excl && (!(events & EPOLLOUT) || shared_count == 0)) {
227 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_excl;
228 __poll_t pevents = EPOLLIN;
230 if (shared_count == 0)
233 spin_lock_irq(&dmabuf->poll.lock);
235 dcb->active |= pevents;
238 dcb->active = pevents;
239 spin_unlock_irq(&dmabuf->poll.lock);
241 if (events & pevents) {
242 if (!dma_fence_get_rcu(fence_excl)) {
243 /* force a recheck */
245 dma_buf_poll_cb(NULL, &dcb->cb);
246 } else if (!dma_fence_add_callback(fence_excl, &dcb->cb,
249 dma_fence_put(fence_excl);
252 * No callback queued, wake up any additional
255 dma_fence_put(fence_excl);
256 dma_buf_poll_cb(NULL, &dcb->cb);
261 if ((events & EPOLLOUT) && shared_count > 0) {
262 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_shared;
265 /* Only queue a new callback if no event has fired yet */
266 spin_lock_irq(&dmabuf->poll.lock);
270 dcb->active = EPOLLOUT;
271 spin_unlock_irq(&dmabuf->poll.lock);
273 if (!(events & EPOLLOUT))
276 for (i = 0; i < shared_count; ++i) {
277 struct dma_fence *fence = rcu_dereference(fobj->shared[i]);
279 if (!dma_fence_get_rcu(fence)) {
281 * fence refcount dropped to zero, this means
282 * that fobj has been freed
284 * call dma_buf_poll_cb and force a recheck!
287 dma_buf_poll_cb(NULL, &dcb->cb);
290 if (!dma_fence_add_callback(fence, &dcb->cb,
292 dma_fence_put(fence);
296 dma_fence_put(fence);
299 /* No callback queued, wake up any additional waiters. */
300 if (i == shared_count)
301 dma_buf_poll_cb(NULL, &dcb->cb);
310 * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
311 * The name of the dma-buf buffer can only be set when the dma-buf is not
312 * attached to any devices. It could theoritically support changing the
313 * name of the dma-buf if the same piece of memory is used for multiple
314 * purpose between different devices.
316 * @dmabuf [in] dmabuf buffer that will be renamed.
317 * @buf: [in] A piece of userspace memory that contains the name of
320 * Returns 0 on success. If the dma-buf buffer is already attached to
321 * devices, return -EBUSY.
324 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
326 char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
330 return PTR_ERR(name);
332 mutex_lock(&dmabuf->lock);
333 if (!list_empty(&dmabuf->attachments)) {
342 mutex_unlock(&dmabuf->lock);
346 static long dma_buf_ioctl(struct file *file,
347 unsigned int cmd, unsigned long arg)
349 struct dma_buf *dmabuf;
350 struct dma_buf_sync sync;
351 enum dma_data_direction direction;
354 dmabuf = file->private_data;
357 case DMA_BUF_IOCTL_SYNC:
358 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
361 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
364 switch (sync.flags & DMA_BUF_SYNC_RW) {
365 case DMA_BUF_SYNC_READ:
366 direction = DMA_FROM_DEVICE;
368 case DMA_BUF_SYNC_WRITE:
369 direction = DMA_TO_DEVICE;
371 case DMA_BUF_SYNC_RW:
372 direction = DMA_BIDIRECTIONAL;
378 if (sync.flags & DMA_BUF_SYNC_END)
379 ret = dma_buf_end_cpu_access(dmabuf, direction);
381 ret = dma_buf_begin_cpu_access(dmabuf, direction);
385 case DMA_BUF_SET_NAME:
386 return dma_buf_set_name(dmabuf, (const char __user *)arg);
393 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
395 struct dma_buf *dmabuf = file->private_data;
397 seq_printf(m, "size:\t%zu\n", dmabuf->size);
398 /* Don't count the temporary reference taken inside procfs seq_show */
399 seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
400 seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
401 mutex_lock(&dmabuf->lock);
403 seq_printf(m, "name:\t%s\n", dmabuf->name);
404 mutex_unlock(&dmabuf->lock);
407 static const struct file_operations dma_buf_fops = {
408 .release = dma_buf_release,
409 .mmap = dma_buf_mmap_internal,
410 .llseek = dma_buf_llseek,
411 .poll = dma_buf_poll,
412 .unlocked_ioctl = dma_buf_ioctl,
414 .compat_ioctl = dma_buf_ioctl,
416 .show_fdinfo = dma_buf_show_fdinfo,
420 * is_dma_buf_file - Check if struct file* is associated with dma_buf
422 static inline int is_dma_buf_file(struct file *file)
424 return file->f_op == &dma_buf_fops;
427 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
430 struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
433 return ERR_CAST(inode);
435 inode->i_size = dmabuf->size;
436 inode_set_bytes(inode, dmabuf->size);
438 file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
439 flags, &dma_buf_fops);
442 file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
443 file->private_data = dmabuf;
444 file->f_path.dentry->d_fsdata = dmabuf;
454 * DOC: dma buf device access
456 * For device DMA access to a shared DMA buffer the usual sequence of operations
459 * 1. The exporter defines his exporter instance using
460 * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
461 * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
462 * as a file descriptor by calling dma_buf_fd().
464 * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
465 * to share with: First the filedescriptor is converted to a &dma_buf using
466 * dma_buf_get(). Then the buffer is attached to the device using
469 * Up to this stage the exporter is still free to migrate or reallocate the
472 * 3. Once the buffer is attached to all devices userspace can initiate DMA
473 * access to the shared buffer. In the kernel this is done by calling
474 * dma_buf_map_attachment() and dma_buf_unmap_attachment().
476 * 4. Once a driver is done with a shared buffer it needs to call
477 * dma_buf_detach() (after cleaning up any mappings) and then release the
478 * reference acquired with dma_buf_get by calling dma_buf_put().
480 * For the detailed semantics exporters are expected to implement see
485 * dma_buf_export - Creates a new dma_buf, and associates an anon file
486 * with this buffer, so it can be exported.
487 * Also connect the allocator specific data and ops to the buffer.
488 * Additionally, provide a name string for exporter; useful in debugging.
490 * @exp_info: [in] holds all the export related information provided
491 * by the exporter. see &struct dma_buf_export_info
492 * for further details.
494 * Returns, on success, a newly created dma_buf object, which wraps the
495 * supplied private data and operations for dma_buf_ops. On either missing
496 * ops, or error in allocating struct dma_buf, will return negative error.
498 * For most cases the easiest way to create @exp_info is through the
499 * %DEFINE_DMA_BUF_EXPORT_INFO macro.
501 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
503 struct dma_buf *dmabuf;
504 struct reservation_object *resv = exp_info->resv;
506 size_t alloc_size = sizeof(struct dma_buf);
510 alloc_size += sizeof(struct reservation_object);
512 /* prevent &dma_buf[1] == dma_buf->resv */
515 if (WARN_ON(!exp_info->priv
517 || !exp_info->ops->map_dma_buf
518 || !exp_info->ops->unmap_dma_buf
519 || !exp_info->ops->release)) {
520 return ERR_PTR(-EINVAL);
523 if (!try_module_get(exp_info->owner))
524 return ERR_PTR(-ENOENT);
526 dmabuf = kzalloc(alloc_size, GFP_KERNEL);
532 dmabuf->priv = exp_info->priv;
533 dmabuf->ops = exp_info->ops;
534 dmabuf->size = exp_info->size;
535 dmabuf->exp_name = exp_info->exp_name;
536 dmabuf->owner = exp_info->owner;
537 init_waitqueue_head(&dmabuf->poll);
538 dmabuf->cb_excl.poll = dmabuf->cb_shared.poll = &dmabuf->poll;
539 dmabuf->cb_excl.active = dmabuf->cb_shared.active = 0;
542 resv = (struct reservation_object *)&dmabuf[1];
543 reservation_object_init(resv);
547 file = dma_buf_getfile(dmabuf, exp_info->flags);
553 file->f_mode |= FMODE_LSEEK;
556 mutex_init(&dmabuf->lock);
557 INIT_LIST_HEAD(&dmabuf->attachments);
559 mutex_lock(&db_list.lock);
560 list_add(&dmabuf->list_node, &db_list.head);
561 mutex_unlock(&db_list.lock);
568 module_put(exp_info->owner);
571 EXPORT_SYMBOL_GPL(dma_buf_export);
574 * dma_buf_fd - returns a file descriptor for the given dma_buf
575 * @dmabuf: [in] pointer to dma_buf for which fd is required.
576 * @flags: [in] flags to give to fd
578 * On success, returns an associated 'fd'. Else, returns error.
580 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
584 if (!dmabuf || !dmabuf->file)
587 fd = get_unused_fd_flags(flags);
591 fd_install(fd, dmabuf->file);
595 EXPORT_SYMBOL_GPL(dma_buf_fd);
598 * dma_buf_get - returns the dma_buf structure related to an fd
599 * @fd: [in] fd associated with the dma_buf to be returned
601 * On success, returns the dma_buf structure associated with an fd; uses
602 * file's refcounting done by fget to increase refcount. returns ERR_PTR
605 struct dma_buf *dma_buf_get(int fd)
612 return ERR_PTR(-EBADF);
614 if (!is_dma_buf_file(file)) {
616 return ERR_PTR(-EINVAL);
619 return file->private_data;
621 EXPORT_SYMBOL_GPL(dma_buf_get);
624 * dma_buf_put - decreases refcount of the buffer
625 * @dmabuf: [in] buffer to reduce refcount of
627 * Uses file's refcounting done implicitly by fput().
629 * If, as a result of this call, the refcount becomes 0, the 'release' file
630 * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
631 * in turn, and frees the memory allocated for dmabuf when exported.
633 void dma_buf_put(struct dma_buf *dmabuf)
635 if (WARN_ON(!dmabuf || !dmabuf->file))
640 EXPORT_SYMBOL_GPL(dma_buf_put);
643 * dma_buf_attach - Add the device to dma_buf's attachments list; optionally,
644 * calls attach() of dma_buf_ops to allow device-specific attach functionality
645 * @dmabuf: [in] buffer to attach device to.
646 * @dev: [in] device to be attached.
648 * Returns struct dma_buf_attachment pointer for this attachment. Attachments
649 * must be cleaned up by calling dma_buf_detach().
653 * A pointer to newly created &dma_buf_attachment on success, or a negative
654 * error code wrapped into a pointer on failure.
656 * Note that this can fail if the backing storage of @dmabuf is in a place not
657 * accessible to @dev, and cannot be moved to a more suitable place. This is
658 * indicated with the error code -EBUSY.
660 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
663 struct dma_buf_attachment *attach;
666 if (WARN_ON(!dmabuf || !dev))
667 return ERR_PTR(-EINVAL);
669 attach = kzalloc(sizeof(*attach), GFP_KERNEL);
671 return ERR_PTR(-ENOMEM);
674 attach->dmabuf = dmabuf;
676 mutex_lock(&dmabuf->lock);
678 if (dmabuf->ops->attach) {
679 ret = dmabuf->ops->attach(dmabuf, attach);
683 list_add(&attach->node, &dmabuf->attachments);
685 mutex_unlock(&dmabuf->lock);
691 mutex_unlock(&dmabuf->lock);
694 EXPORT_SYMBOL_GPL(dma_buf_attach);
697 * dma_buf_detach - Remove the given attachment from dmabuf's attachments list;
698 * optionally calls detach() of dma_buf_ops for device-specific detach
699 * @dmabuf: [in] buffer to detach from.
700 * @attach: [in] attachment to be detached; is free'd after this call.
702 * Clean up a device attachment obtained by calling dma_buf_attach().
704 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
706 if (WARN_ON(!dmabuf || !attach))
710 dmabuf->ops->unmap_dma_buf(attach, attach->sgt, attach->dir);
712 mutex_lock(&dmabuf->lock);
713 list_del(&attach->node);
714 if (dmabuf->ops->detach)
715 dmabuf->ops->detach(dmabuf, attach);
717 mutex_unlock(&dmabuf->lock);
720 EXPORT_SYMBOL_GPL(dma_buf_detach);
723 * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
724 * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
726 * @attach: [in] attachment whose scatterlist is to be returned
727 * @direction: [in] direction of DMA transfer
729 * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
730 * on error. May return -EINTR if it is interrupted by a signal.
732 * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
733 * the underlying backing storage is pinned for as long as a mapping exists,
734 * therefore users/importers should not hold onto a mapping for undue amounts of
737 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
738 enum dma_data_direction direction)
740 struct sg_table *sg_table;
744 if (WARN_ON(!attach || !attach->dmabuf))
745 return ERR_PTR(-EINVAL);
749 * Two mappings with different directions for the same
750 * attachment are not allowed.
752 if (attach->dir != direction &&
753 attach->dir != DMA_BIDIRECTIONAL)
754 return ERR_PTR(-EBUSY);
759 sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
761 sg_table = ERR_PTR(-ENOMEM);
763 if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
764 attach->sgt = sg_table;
765 attach->dir = direction;
770 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
773 * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
774 * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
776 * @attach: [in] attachment to unmap buffer from
777 * @sg_table: [in] scatterlist info of the buffer to unmap
778 * @direction: [in] direction of DMA transfer
780 * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
782 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
783 struct sg_table *sg_table,
784 enum dma_data_direction direction)
788 if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
791 if (attach->sgt == sg_table)
794 attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
796 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
801 * There are mutliple reasons for supporting CPU access to a dma buffer object:
803 * - Fallback operations in the kernel, for example when a device is connected
804 * over USB and the kernel needs to shuffle the data around first before
805 * sending it away. Cache coherency is handled by braketing any transactions
806 * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
809 * To support dma_buf objects residing in highmem cpu access is page-based
810 * using an api similar to kmap. Accessing a dma_buf is done in aligned chunks
811 * of PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which
812 * returns a pointer in kernel virtual address space. Afterwards the chunk
813 * needs to be unmapped again. There is no limit on how often a given chunk
814 * can be mapped and unmapped, i.e. the importer does not need to call
815 * begin_cpu_access again before mapping the same chunk again.
818 * void \*dma_buf_kmap(struct dma_buf \*, unsigned long);
819 * void dma_buf_kunmap(struct dma_buf \*, unsigned long, void \*);
821 * Implementing the functions is optional for exporters and for importers all
822 * the restrictions of using kmap apply.
824 * dma_buf kmap calls outside of the range specified in begin_cpu_access are
825 * undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
826 * the partial chunks at the beginning and end but may return stale or bogus
827 * data outside of the range (in these partial chunks).
829 * For some cases the overhead of kmap can be too high, a vmap interface
830 * is introduced. This interface should be used very carefully, as vmalloc
831 * space is a limited resources on many architectures.
834 * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
835 * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
837 * The vmap call can fail if there is no vmap support in the exporter, or if
838 * it runs out of vmalloc space. Fallback to kmap should be implemented. Note
839 * that the dma-buf layer keeps a reference count for all vmap access and
840 * calls down into the exporter's vmap function only when no vmapping exists,
841 * and only unmaps it once. Protection against concurrent vmap/vunmap calls is
842 * provided by taking the dma_buf->lock mutex.
844 * - For full compatibility on the importer side with existing userspace
845 * interfaces, which might already support mmap'ing buffers. This is needed in
846 * many processing pipelines (e.g. feeding a software rendered image into a
847 * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
848 * framework already supported this and for DMA buffer file descriptors to
849 * replace ION buffers mmap support was needed.
851 * There is no special interfaces, userspace simply calls mmap on the dma-buf
852 * fd. But like for CPU access there's a need to braket the actual access,
853 * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
854 * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
857 * Some systems might need some sort of cache coherency management e.g. when
858 * CPU and GPU domains are being accessed through dma-buf at the same time.
859 * To circumvent this problem there are begin/end coherency markers, that
860 * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
861 * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
862 * sequence would be used like following:
865 * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
866 * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
867 * want (with the new data being consumed by say the GPU or the scanout
869 * - munmap once you don't need the buffer any more
871 * For correctness and optimal performance, it is always required to use
872 * SYNC_START and SYNC_END before and after, respectively, when accessing the
873 * mapped address. Userspace cannot rely on coherent access, even when there
874 * are systems where it just works without calling these ioctls.
876 * - And as a CPU fallback in userspace processing pipelines.
878 * Similar to the motivation for kernel cpu access it is again important that
879 * the userspace code of a given importing subsystem can use the same
880 * interfaces with a imported dma-buf buffer object as with a native buffer
881 * object. This is especially important for drm where the userspace part of
882 * contemporary OpenGL, X, and other drivers is huge, and reworking them to
883 * use a different way to mmap a buffer rather invasive.
885 * The assumption in the current dma-buf interfaces is that redirecting the
886 * initial mmap is all that's needed. A survey of some of the existing
887 * subsystems shows that no driver seems to do any nefarious thing like
888 * syncing up with outstanding asynchronous processing on the device or
889 * allocating special resources at fault time. So hopefully this is good
890 * enough, since adding interfaces to intercept pagefaults and allow pte
891 * shootdowns would increase the complexity quite a bit.
894 * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
897 * If the importing subsystem simply provides a special-purpose mmap call to
898 * set up a mapping in userspace, calling do_mmap with dma_buf->file will
899 * equally achieve that for a dma-buf object.
902 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
903 enum dma_data_direction direction)
905 bool write = (direction == DMA_BIDIRECTIONAL ||
906 direction == DMA_TO_DEVICE);
907 struct reservation_object *resv = dmabuf->resv;
910 /* Wait on any implicit rendering fences */
911 ret = reservation_object_wait_timeout_rcu(resv, write, true,
912 MAX_SCHEDULE_TIMEOUT);
920 * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
921 * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
922 * preparations. Coherency is only guaranteed in the specified range for the
923 * specified access direction.
924 * @dmabuf: [in] buffer to prepare cpu access for.
925 * @direction: [in] length of range for cpu access.
927 * After the cpu access is complete the caller should call
928 * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
929 * it guaranteed to be coherent with other DMA access.
931 * Can return negative error values, returns 0 on success.
933 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
934 enum dma_data_direction direction)
938 if (WARN_ON(!dmabuf))
941 if (dmabuf->ops->begin_cpu_access)
942 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
944 /* Ensure that all fences are waited upon - but we first allow
945 * the native handler the chance to do so more efficiently if it
946 * chooses. A double invocation here will be reasonably cheap no-op.
949 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
953 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
956 * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
957 * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
958 * actions. Coherency is only guaranteed in the specified range for the
959 * specified access direction.
960 * @dmabuf: [in] buffer to complete cpu access for.
961 * @direction: [in] length of range for cpu access.
963 * This terminates CPU access started with dma_buf_begin_cpu_access().
965 * Can return negative error values, returns 0 on success.
967 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
968 enum dma_data_direction direction)
974 if (dmabuf->ops->end_cpu_access)
975 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
979 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
982 * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
983 * same restrictions as for kmap and friends apply.
984 * @dmabuf: [in] buffer to map page from.
985 * @page_num: [in] page in PAGE_SIZE units to map.
987 * This call must always succeed, any necessary preparations that might fail
988 * need to be done in begin_cpu_access.
990 void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
994 if (!dmabuf->ops->map)
996 return dmabuf->ops->map(dmabuf, page_num);
998 EXPORT_SYMBOL_GPL(dma_buf_kmap);
1001 * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
1002 * @dmabuf: [in] buffer to unmap page from.
1003 * @page_num: [in] page in PAGE_SIZE units to unmap.
1004 * @vaddr: [in] kernel space pointer obtained from dma_buf_kmap.
1006 * This call must always succeed.
1008 void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
1013 if (dmabuf->ops->unmap)
1014 dmabuf->ops->unmap(dmabuf, page_num, vaddr);
1016 EXPORT_SYMBOL_GPL(dma_buf_kunmap);
1020 * dma_buf_mmap - Setup up a userspace mmap with the given vma
1021 * @dmabuf: [in] buffer that should back the vma
1022 * @vma: [in] vma for the mmap
1023 * @pgoff: [in] offset in pages where this mmap should start within the
1026 * This function adjusts the passed in vma so that it points at the file of the
1027 * dma_buf operation. It also adjusts the starting pgoff and does bounds
1028 * checking on the size of the vma. Then it calls the exporters mmap function to
1029 * set up the mapping.
1031 * Can return negative error values, returns 0 on success.
1033 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1034 unsigned long pgoff)
1036 struct file *oldfile;
1039 if (WARN_ON(!dmabuf || !vma))
1042 /* check if buffer supports mmap */
1043 if (!dmabuf->ops->mmap)
1046 /* check for offset overflow */
1047 if (pgoff + vma_pages(vma) < pgoff)
1050 /* check for overflowing the buffer's size */
1051 if (pgoff + vma_pages(vma) >
1052 dmabuf->size >> PAGE_SHIFT)
1055 /* readjust the vma */
1056 get_file(dmabuf->file);
1057 oldfile = vma->vm_file;
1058 vma->vm_file = dmabuf->file;
1059 vma->vm_pgoff = pgoff;
1061 ret = dmabuf->ops->mmap(dmabuf, vma);
1063 /* restore old parameters on failure */
1064 vma->vm_file = oldfile;
1073 EXPORT_SYMBOL_GPL(dma_buf_mmap);
1076 * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1077 * address space. Same restrictions as for vmap and friends apply.
1078 * @dmabuf: [in] buffer to vmap
1080 * This call may fail due to lack of virtual mapping address space.
1081 * These calls are optional in drivers. The intended use for them
1082 * is for mapping objects linear in kernel space for high use objects.
1083 * Please attempt to use kmap/kunmap before thinking about these interfaces.
1085 * Returns NULL on error.
1087 void *dma_buf_vmap(struct dma_buf *dmabuf)
1091 if (WARN_ON(!dmabuf))
1094 if (!dmabuf->ops->vmap)
1097 mutex_lock(&dmabuf->lock);
1098 if (dmabuf->vmapping_counter) {
1099 dmabuf->vmapping_counter++;
1100 BUG_ON(!dmabuf->vmap_ptr);
1101 ptr = dmabuf->vmap_ptr;
1105 BUG_ON(dmabuf->vmap_ptr);
1107 ptr = dmabuf->ops->vmap(dmabuf);
1108 if (WARN_ON_ONCE(IS_ERR(ptr)))
1113 dmabuf->vmap_ptr = ptr;
1114 dmabuf->vmapping_counter = 1;
1117 mutex_unlock(&dmabuf->lock);
1120 EXPORT_SYMBOL_GPL(dma_buf_vmap);
1123 * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1124 * @dmabuf: [in] buffer to vunmap
1125 * @vaddr: [in] vmap to vunmap
1127 void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
1129 if (WARN_ON(!dmabuf))
1132 BUG_ON(!dmabuf->vmap_ptr);
1133 BUG_ON(dmabuf->vmapping_counter == 0);
1134 BUG_ON(dmabuf->vmap_ptr != vaddr);
1136 mutex_lock(&dmabuf->lock);
1137 if (--dmabuf->vmapping_counter == 0) {
1138 if (dmabuf->ops->vunmap)
1139 dmabuf->ops->vunmap(dmabuf, vaddr);
1140 dmabuf->vmap_ptr = NULL;
1142 mutex_unlock(&dmabuf->lock);
1144 EXPORT_SYMBOL_GPL(dma_buf_vunmap);
1146 #ifdef CONFIG_DEBUG_FS
1147 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1150 struct dma_buf *buf_obj;
1151 struct dma_buf_attachment *attach_obj;
1152 struct reservation_object *robj;
1153 struct reservation_object_list *fobj;
1154 struct dma_fence *fence;
1156 int count = 0, attach_count, shared_count, i;
1159 ret = mutex_lock_interruptible(&db_list.lock);
1164 seq_puts(s, "\nDma-buf Objects:\n");
1165 seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\n",
1166 "size", "flags", "mode", "count", "ino");
1168 list_for_each_entry(buf_obj, &db_list.head, list_node) {
1169 ret = mutex_lock_interruptible(&buf_obj->lock);
1173 "\tERROR locking buffer object: skipping\n");
1177 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1179 buf_obj->file->f_flags, buf_obj->file->f_mode,
1180 file_count(buf_obj->file),
1182 file_inode(buf_obj->file)->i_ino,
1183 buf_obj->name ?: "");
1185 robj = buf_obj->resv;
1187 seq = read_seqcount_begin(&robj->seq);
1189 fobj = rcu_dereference(robj->fence);
1190 shared_count = fobj ? fobj->shared_count : 0;
1191 fence = rcu_dereference(robj->fence_excl);
1192 if (!read_seqcount_retry(&robj->seq, seq))
1198 seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
1199 fence->ops->get_driver_name(fence),
1200 fence->ops->get_timeline_name(fence),
1201 dma_fence_is_signaled(fence) ? "" : "un");
1202 for (i = 0; i < shared_count; i++) {
1203 fence = rcu_dereference(fobj->shared[i]);
1204 if (!dma_fence_get_rcu(fence))
1206 seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
1207 fence->ops->get_driver_name(fence),
1208 fence->ops->get_timeline_name(fence),
1209 dma_fence_is_signaled(fence) ? "" : "un");
1210 dma_fence_put(fence);
1214 seq_puts(s, "\tAttached Devices:\n");
1217 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1218 seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1222 seq_printf(s, "Total %d devices attached\n\n",
1226 size += buf_obj->size;
1227 mutex_unlock(&buf_obj->lock);
1230 seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1232 mutex_unlock(&db_list.lock);
1236 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1238 static struct dentry *dma_buf_debugfs_dir;
1240 static int dma_buf_init_debugfs(void)
1245 d = debugfs_create_dir("dma_buf", NULL);
1249 dma_buf_debugfs_dir = d;
1251 d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1252 NULL, &dma_buf_debug_fops);
1254 pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1255 debugfs_remove_recursive(dma_buf_debugfs_dir);
1256 dma_buf_debugfs_dir = NULL;
1263 static void dma_buf_uninit_debugfs(void)
1265 debugfs_remove_recursive(dma_buf_debugfs_dir);
1268 static inline int dma_buf_init_debugfs(void)
1272 static inline void dma_buf_uninit_debugfs(void)
1277 static int __init dma_buf_init(void)
1279 dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1280 if (IS_ERR(dma_buf_mnt))
1281 return PTR_ERR(dma_buf_mnt);
1283 mutex_init(&db_list.lock);
1284 INIT_LIST_HEAD(&db_list.head);
1285 dma_buf_init_debugfs();
1288 subsys_initcall(dma_buf_init);
1290 static void __exit dma_buf_deinit(void)
1292 dma_buf_uninit_debugfs();
1293 kern_unmount(dma_buf_mnt);
1295 __exitcall(dma_buf_deinit);