Merge branch 'work.mount0' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs
[sfrench/cifs-2.6.git] / drivers / dma-buf / dma-buf.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Framework for buffer objects that can be shared across devices/subsystems.
4  *
5  * Copyright(C) 2011 Linaro Limited. All rights reserved.
6  * Author: Sumit Semwal <sumit.semwal@ti.com>
7  *
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.
12  */
13
14 #include <linux/fs.h>
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>
25 #include <linux/mm.h>
26 #include <linux/mount.h>
27 #include <linux/pseudo_fs.h>
28
29 #include <uapi/linux/dma-buf.h>
30 #include <uapi/linux/magic.h>
31
32 static inline int is_dma_buf_file(struct file *);
33
34 struct dma_buf_list {
35         struct list_head head;
36         struct mutex lock;
37 };
38
39 static struct dma_buf_list db_list;
40
41 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
42 {
43         struct dma_buf *dmabuf;
44         char name[DMA_BUF_NAME_LEN];
45         size_t ret = 0;
46
47         dmabuf = dentry->d_fsdata;
48         mutex_lock(&dmabuf->lock);
49         if (dmabuf->name)
50                 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
51         mutex_unlock(&dmabuf->lock);
52
53         return dynamic_dname(dentry, buffer, buflen, "/%s:%s",
54                              dentry->d_name.name, ret > 0 ? name : "");
55 }
56
57 static const struct dentry_operations dma_buf_dentry_ops = {
58         .d_dname = dmabuffs_dname,
59 };
60
61 static struct vfsmount *dma_buf_mnt;
62
63 static int dma_buf_fs_init_context(struct fs_context *fc)
64 {
65         struct pseudo_fs_context *ctx;
66
67         ctx = init_pseudo(fc, DMA_BUF_MAGIC);
68         if (!ctx)
69                 return -ENOMEM;
70         ctx->dops = &dma_buf_dentry_ops;
71         return 0;
72 }
73
74 static struct file_system_type dma_buf_fs_type = {
75         .name = "dmabuf",
76         .init_fs_context = dma_buf_fs_init_context,
77         .kill_sb = kill_anon_super,
78 };
79
80 static int dma_buf_release(struct inode *inode, struct file *file)
81 {
82         struct dma_buf *dmabuf;
83
84         if (!is_dma_buf_file(file))
85                 return -EINVAL;
86
87         dmabuf = file->private_data;
88
89         BUG_ON(dmabuf->vmapping_counter);
90
91         /*
92          * Any fences that a dma-buf poll can wait on should be signaled
93          * before releasing dma-buf. This is the responsibility of each
94          * driver that uses the reservation objects.
95          *
96          * If you hit this BUG() it means someone dropped their ref to the
97          * dma-buf while still having pending operation to the buffer.
98          */
99         BUG_ON(dmabuf->cb_shared.active || dmabuf->cb_excl.active);
100
101         dmabuf->ops->release(dmabuf);
102
103         mutex_lock(&db_list.lock);
104         list_del(&dmabuf->list_node);
105         mutex_unlock(&db_list.lock);
106
107         if (dmabuf->resv == (struct reservation_object *)&dmabuf[1])
108                 reservation_object_fini(dmabuf->resv);
109
110         module_put(dmabuf->owner);
111         kfree(dmabuf);
112         return 0;
113 }
114
115 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
116 {
117         struct dma_buf *dmabuf;
118
119         if (!is_dma_buf_file(file))
120                 return -EINVAL;
121
122         dmabuf = file->private_data;
123
124         /* check if buffer supports mmap */
125         if (!dmabuf->ops->mmap)
126                 return -EINVAL;
127
128         /* check for overflowing the buffer's size */
129         if (vma->vm_pgoff + vma_pages(vma) >
130             dmabuf->size >> PAGE_SHIFT)
131                 return -EINVAL;
132
133         return dmabuf->ops->mmap(dmabuf, vma);
134 }
135
136 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
137 {
138         struct dma_buf *dmabuf;
139         loff_t base;
140
141         if (!is_dma_buf_file(file))
142                 return -EBADF;
143
144         dmabuf = file->private_data;
145
146         /* only support discovering the end of the buffer,
147            but also allow SEEK_SET to maintain the idiomatic
148            SEEK_END(0), SEEK_CUR(0) pattern */
149         if (whence == SEEK_END)
150                 base = dmabuf->size;
151         else if (whence == SEEK_SET)
152                 base = 0;
153         else
154                 return -EINVAL;
155
156         if (offset != 0)
157                 return -EINVAL;
158
159         return base + offset;
160 }
161
162 /**
163  * DOC: fence polling
164  *
165  * To support cross-device and cross-driver synchronization of buffer access
166  * implicit fences (represented internally in the kernel with &struct fence) can
167  * be attached to a &dma_buf. The glue for that and a few related things are
168  * provided in the &reservation_object structure.
169  *
170  * Userspace can query the state of these implicitly tracked fences using poll()
171  * and related system calls:
172  *
173  * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
174  *   most recent write or exclusive fence.
175  *
176  * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
177  *   all attached fences, shared and exclusive ones.
178  *
179  * Note that this only signals the completion of the respective fences, i.e. the
180  * DMA transfers are complete. Cache flushing and any other necessary
181  * preparations before CPU access can begin still need to happen.
182  */
183
184 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
185 {
186         struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
187         unsigned long flags;
188
189         spin_lock_irqsave(&dcb->poll->lock, flags);
190         wake_up_locked_poll(dcb->poll, dcb->active);
191         dcb->active = 0;
192         spin_unlock_irqrestore(&dcb->poll->lock, flags);
193 }
194
195 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
196 {
197         struct dma_buf *dmabuf;
198         struct reservation_object *resv;
199         struct reservation_object_list *fobj;
200         struct dma_fence *fence_excl;
201         __poll_t events;
202         unsigned shared_count, seq;
203
204         dmabuf = file->private_data;
205         if (!dmabuf || !dmabuf->resv)
206                 return EPOLLERR;
207
208         resv = dmabuf->resv;
209
210         poll_wait(file, &dmabuf->poll, poll);
211
212         events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
213         if (!events)
214                 return 0;
215
216 retry:
217         seq = read_seqcount_begin(&resv->seq);
218         rcu_read_lock();
219
220         fobj = rcu_dereference(resv->fence);
221         if (fobj)
222                 shared_count = fobj->shared_count;
223         else
224                 shared_count = 0;
225         fence_excl = rcu_dereference(resv->fence_excl);
226         if (read_seqcount_retry(&resv->seq, seq)) {
227                 rcu_read_unlock();
228                 goto retry;
229         }
230
231         if (fence_excl && (!(events & EPOLLOUT) || shared_count == 0)) {
232                 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_excl;
233                 __poll_t pevents = EPOLLIN;
234
235                 if (shared_count == 0)
236                         pevents |= EPOLLOUT;
237
238                 spin_lock_irq(&dmabuf->poll.lock);
239                 if (dcb->active) {
240                         dcb->active |= pevents;
241                         events &= ~pevents;
242                 } else
243                         dcb->active = pevents;
244                 spin_unlock_irq(&dmabuf->poll.lock);
245
246                 if (events & pevents) {
247                         if (!dma_fence_get_rcu(fence_excl)) {
248                                 /* force a recheck */
249                                 events &= ~pevents;
250                                 dma_buf_poll_cb(NULL, &dcb->cb);
251                         } else if (!dma_fence_add_callback(fence_excl, &dcb->cb,
252                                                            dma_buf_poll_cb)) {
253                                 events &= ~pevents;
254                                 dma_fence_put(fence_excl);
255                         } else {
256                                 /*
257                                  * No callback queued, wake up any additional
258                                  * waiters.
259                                  */
260                                 dma_fence_put(fence_excl);
261                                 dma_buf_poll_cb(NULL, &dcb->cb);
262                         }
263                 }
264         }
265
266         if ((events & EPOLLOUT) && shared_count > 0) {
267                 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_shared;
268                 int i;
269
270                 /* Only queue a new callback if no event has fired yet */
271                 spin_lock_irq(&dmabuf->poll.lock);
272                 if (dcb->active)
273                         events &= ~EPOLLOUT;
274                 else
275                         dcb->active = EPOLLOUT;
276                 spin_unlock_irq(&dmabuf->poll.lock);
277
278                 if (!(events & EPOLLOUT))
279                         goto out;
280
281                 for (i = 0; i < shared_count; ++i) {
282                         struct dma_fence *fence = rcu_dereference(fobj->shared[i]);
283
284                         if (!dma_fence_get_rcu(fence)) {
285                                 /*
286                                  * fence refcount dropped to zero, this means
287                                  * that fobj has been freed
288                                  *
289                                  * call dma_buf_poll_cb and force a recheck!
290                                  */
291                                 events &= ~EPOLLOUT;
292                                 dma_buf_poll_cb(NULL, &dcb->cb);
293                                 break;
294                         }
295                         if (!dma_fence_add_callback(fence, &dcb->cb,
296                                                     dma_buf_poll_cb)) {
297                                 dma_fence_put(fence);
298                                 events &= ~EPOLLOUT;
299                                 break;
300                         }
301                         dma_fence_put(fence);
302                 }
303
304                 /* No callback queued, wake up any additional waiters. */
305                 if (i == shared_count)
306                         dma_buf_poll_cb(NULL, &dcb->cb);
307         }
308
309 out:
310         rcu_read_unlock();
311         return events;
312 }
313
314 /**
315  * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
316  * The name of the dma-buf buffer can only be set when the dma-buf is not
317  * attached to any devices. It could theoritically support changing the
318  * name of the dma-buf if the same piece of memory is used for multiple
319  * purpose between different devices.
320  *
321  * @dmabuf [in]     dmabuf buffer that will be renamed.
322  * @buf:   [in]     A piece of userspace memory that contains the name of
323  *                  the dma-buf.
324  *
325  * Returns 0 on success. If the dma-buf buffer is already attached to
326  * devices, return -EBUSY.
327  *
328  */
329 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
330 {
331         char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
332         long ret = 0;
333
334         if (IS_ERR(name))
335                 return PTR_ERR(name);
336
337         mutex_lock(&dmabuf->lock);
338         if (!list_empty(&dmabuf->attachments)) {
339                 ret = -EBUSY;
340                 kfree(name);
341                 goto out_unlock;
342         }
343         kfree(dmabuf->name);
344         dmabuf->name = name;
345
346 out_unlock:
347         mutex_unlock(&dmabuf->lock);
348         return ret;
349 }
350
351 static long dma_buf_ioctl(struct file *file,
352                           unsigned int cmd, unsigned long arg)
353 {
354         struct dma_buf *dmabuf;
355         struct dma_buf_sync sync;
356         enum dma_data_direction direction;
357         int ret;
358
359         dmabuf = file->private_data;
360
361         switch (cmd) {
362         case DMA_BUF_IOCTL_SYNC:
363                 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
364                         return -EFAULT;
365
366                 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
367                         return -EINVAL;
368
369                 switch (sync.flags & DMA_BUF_SYNC_RW) {
370                 case DMA_BUF_SYNC_READ:
371                         direction = DMA_FROM_DEVICE;
372                         break;
373                 case DMA_BUF_SYNC_WRITE:
374                         direction = DMA_TO_DEVICE;
375                         break;
376                 case DMA_BUF_SYNC_RW:
377                         direction = DMA_BIDIRECTIONAL;
378                         break;
379                 default:
380                         return -EINVAL;
381                 }
382
383                 if (sync.flags & DMA_BUF_SYNC_END)
384                         ret = dma_buf_end_cpu_access(dmabuf, direction);
385                 else
386                         ret = dma_buf_begin_cpu_access(dmabuf, direction);
387
388                 return ret;
389
390         case DMA_BUF_SET_NAME:
391                 return dma_buf_set_name(dmabuf, (const char __user *)arg);
392
393         default:
394                 return -ENOTTY;
395         }
396 }
397
398 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
399 {
400         struct dma_buf *dmabuf = file->private_data;
401
402         seq_printf(m, "size:\t%zu\n", dmabuf->size);
403         /* Don't count the temporary reference taken inside procfs seq_show */
404         seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
405         seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
406         mutex_lock(&dmabuf->lock);
407         if (dmabuf->name)
408                 seq_printf(m, "name:\t%s\n", dmabuf->name);
409         mutex_unlock(&dmabuf->lock);
410 }
411
412 static const struct file_operations dma_buf_fops = {
413         .release        = dma_buf_release,
414         .mmap           = dma_buf_mmap_internal,
415         .llseek         = dma_buf_llseek,
416         .poll           = dma_buf_poll,
417         .unlocked_ioctl = dma_buf_ioctl,
418 #ifdef CONFIG_COMPAT
419         .compat_ioctl   = dma_buf_ioctl,
420 #endif
421         .show_fdinfo    = dma_buf_show_fdinfo,
422 };
423
424 /*
425  * is_dma_buf_file - Check if struct file* is associated with dma_buf
426  */
427 static inline int is_dma_buf_file(struct file *file)
428 {
429         return file->f_op == &dma_buf_fops;
430 }
431
432 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
433 {
434         struct file *file;
435         struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
436
437         if (IS_ERR(inode))
438                 return ERR_CAST(inode);
439
440         inode->i_size = dmabuf->size;
441         inode_set_bytes(inode, dmabuf->size);
442
443         file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
444                                  flags, &dma_buf_fops);
445         if (IS_ERR(file))
446                 goto err_alloc_file;
447         file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
448         file->private_data = dmabuf;
449         file->f_path.dentry->d_fsdata = dmabuf;
450
451         return file;
452
453 err_alloc_file:
454         iput(inode);
455         return file;
456 }
457
458 /**
459  * DOC: dma buf device access
460  *
461  * For device DMA access to a shared DMA buffer the usual sequence of operations
462  * is fairly simple:
463  *
464  * 1. The exporter defines his exporter instance using
465  *    DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
466  *    buffer object into a &dma_buf. It then exports that &dma_buf to userspace
467  *    as a file descriptor by calling dma_buf_fd().
468  *
469  * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
470  *    to share with: First the filedescriptor is converted to a &dma_buf using
471  *    dma_buf_get(). Then the buffer is attached to the device using
472  *    dma_buf_attach().
473  *
474  *    Up to this stage the exporter is still free to migrate or reallocate the
475  *    backing storage.
476  *
477  * 3. Once the buffer is attached to all devices userspace can initiate DMA
478  *    access to the shared buffer. In the kernel this is done by calling
479  *    dma_buf_map_attachment() and dma_buf_unmap_attachment().
480  *
481  * 4. Once a driver is done with a shared buffer it needs to call
482  *    dma_buf_detach() (after cleaning up any mappings) and then release the
483  *    reference acquired with dma_buf_get by calling dma_buf_put().
484  *
485  * For the detailed semantics exporters are expected to implement see
486  * &dma_buf_ops.
487  */
488
489 /**
490  * dma_buf_export - Creates a new dma_buf, and associates an anon file
491  * with this buffer, so it can be exported.
492  * Also connect the allocator specific data and ops to the buffer.
493  * Additionally, provide a name string for exporter; useful in debugging.
494  *
495  * @exp_info:   [in]    holds all the export related information provided
496  *                      by the exporter. see &struct dma_buf_export_info
497  *                      for further details.
498  *
499  * Returns, on success, a newly created dma_buf object, which wraps the
500  * supplied private data and operations for dma_buf_ops. On either missing
501  * ops, or error in allocating struct dma_buf, will return negative error.
502  *
503  * For most cases the easiest way to create @exp_info is through the
504  * %DEFINE_DMA_BUF_EXPORT_INFO macro.
505  */
506 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
507 {
508         struct dma_buf *dmabuf;
509         struct reservation_object *resv = exp_info->resv;
510         struct file *file;
511         size_t alloc_size = sizeof(struct dma_buf);
512         int ret;
513
514         if (!exp_info->resv)
515                 alloc_size += sizeof(struct reservation_object);
516         else
517                 /* prevent &dma_buf[1] == dma_buf->resv */
518                 alloc_size += 1;
519
520         if (WARN_ON(!exp_info->priv
521                           || !exp_info->ops
522                           || !exp_info->ops->map_dma_buf
523                           || !exp_info->ops->unmap_dma_buf
524                           || !exp_info->ops->release)) {
525                 return ERR_PTR(-EINVAL);
526         }
527
528         if (!try_module_get(exp_info->owner))
529                 return ERR_PTR(-ENOENT);
530
531         dmabuf = kzalloc(alloc_size, GFP_KERNEL);
532         if (!dmabuf) {
533                 ret = -ENOMEM;
534                 goto err_module;
535         }
536
537         dmabuf->priv = exp_info->priv;
538         dmabuf->ops = exp_info->ops;
539         dmabuf->size = exp_info->size;
540         dmabuf->exp_name = exp_info->exp_name;
541         dmabuf->owner = exp_info->owner;
542         init_waitqueue_head(&dmabuf->poll);
543         dmabuf->cb_excl.poll = dmabuf->cb_shared.poll = &dmabuf->poll;
544         dmabuf->cb_excl.active = dmabuf->cb_shared.active = 0;
545
546         if (!resv) {
547                 resv = (struct reservation_object *)&dmabuf[1];
548                 reservation_object_init(resv);
549         }
550         dmabuf->resv = resv;
551
552         file = dma_buf_getfile(dmabuf, exp_info->flags);
553         if (IS_ERR(file)) {
554                 ret = PTR_ERR(file);
555                 goto err_dmabuf;
556         }
557
558         file->f_mode |= FMODE_LSEEK;
559         dmabuf->file = file;
560
561         mutex_init(&dmabuf->lock);
562         INIT_LIST_HEAD(&dmabuf->attachments);
563
564         mutex_lock(&db_list.lock);
565         list_add(&dmabuf->list_node, &db_list.head);
566         mutex_unlock(&db_list.lock);
567
568         return dmabuf;
569
570 err_dmabuf:
571         kfree(dmabuf);
572 err_module:
573         module_put(exp_info->owner);
574         return ERR_PTR(ret);
575 }
576 EXPORT_SYMBOL_GPL(dma_buf_export);
577
578 /**
579  * dma_buf_fd - returns a file descriptor for the given dma_buf
580  * @dmabuf:     [in]    pointer to dma_buf for which fd is required.
581  * @flags:      [in]    flags to give to fd
582  *
583  * On success, returns an associated 'fd'. Else, returns error.
584  */
585 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
586 {
587         int fd;
588
589         if (!dmabuf || !dmabuf->file)
590                 return -EINVAL;
591
592         fd = get_unused_fd_flags(flags);
593         if (fd < 0)
594                 return fd;
595
596         fd_install(fd, dmabuf->file);
597
598         return fd;
599 }
600 EXPORT_SYMBOL_GPL(dma_buf_fd);
601
602 /**
603  * dma_buf_get - returns the dma_buf structure related to an fd
604  * @fd: [in]    fd associated with the dma_buf to be returned
605  *
606  * On success, returns the dma_buf structure associated with an fd; uses
607  * file's refcounting done by fget to increase refcount. returns ERR_PTR
608  * otherwise.
609  */
610 struct dma_buf *dma_buf_get(int fd)
611 {
612         struct file *file;
613
614         file = fget(fd);
615
616         if (!file)
617                 return ERR_PTR(-EBADF);
618
619         if (!is_dma_buf_file(file)) {
620                 fput(file);
621                 return ERR_PTR(-EINVAL);
622         }
623
624         return file->private_data;
625 }
626 EXPORT_SYMBOL_GPL(dma_buf_get);
627
628 /**
629  * dma_buf_put - decreases refcount of the buffer
630  * @dmabuf:     [in]    buffer to reduce refcount of
631  *
632  * Uses file's refcounting done implicitly by fput().
633  *
634  * If, as a result of this call, the refcount becomes 0, the 'release' file
635  * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
636  * in turn, and frees the memory allocated for dmabuf when exported.
637  */
638 void dma_buf_put(struct dma_buf *dmabuf)
639 {
640         if (WARN_ON(!dmabuf || !dmabuf->file))
641                 return;
642
643         fput(dmabuf->file);
644 }
645 EXPORT_SYMBOL_GPL(dma_buf_put);
646
647 /**
648  * dma_buf_attach - Add the device to dma_buf's attachments list; optionally,
649  * calls attach() of dma_buf_ops to allow device-specific attach functionality
650  * @dmabuf:     [in]    buffer to attach device to.
651  * @dev:        [in]    device to be attached.
652  *
653  * Returns struct dma_buf_attachment pointer for this attachment. Attachments
654  * must be cleaned up by calling dma_buf_detach().
655  *
656  * Returns:
657  *
658  * A pointer to newly created &dma_buf_attachment on success, or a negative
659  * error code wrapped into a pointer on failure.
660  *
661  * Note that this can fail if the backing storage of @dmabuf is in a place not
662  * accessible to @dev, and cannot be moved to a more suitable place. This is
663  * indicated with the error code -EBUSY.
664  */
665 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
666                                           struct device *dev)
667 {
668         struct dma_buf_attachment *attach;
669         int ret;
670
671         if (WARN_ON(!dmabuf || !dev))
672                 return ERR_PTR(-EINVAL);
673
674         attach = kzalloc(sizeof(*attach), GFP_KERNEL);
675         if (!attach)
676                 return ERR_PTR(-ENOMEM);
677
678         attach->dev = dev;
679         attach->dmabuf = dmabuf;
680
681         mutex_lock(&dmabuf->lock);
682
683         if (dmabuf->ops->attach) {
684                 ret = dmabuf->ops->attach(dmabuf, attach);
685                 if (ret)
686                         goto err_attach;
687         }
688         list_add(&attach->node, &dmabuf->attachments);
689
690         mutex_unlock(&dmabuf->lock);
691
692         return attach;
693
694 err_attach:
695         kfree(attach);
696         mutex_unlock(&dmabuf->lock);
697         return ERR_PTR(ret);
698 }
699 EXPORT_SYMBOL_GPL(dma_buf_attach);
700
701 /**
702  * dma_buf_detach - Remove the given attachment from dmabuf's attachments list;
703  * optionally calls detach() of dma_buf_ops for device-specific detach
704  * @dmabuf:     [in]    buffer to detach from.
705  * @attach:     [in]    attachment to be detached; is free'd after this call.
706  *
707  * Clean up a device attachment obtained by calling dma_buf_attach().
708  */
709 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
710 {
711         if (WARN_ON(!dmabuf || !attach))
712                 return;
713
714         if (attach->sgt)
715                 dmabuf->ops->unmap_dma_buf(attach, attach->sgt, attach->dir);
716
717         mutex_lock(&dmabuf->lock);
718         list_del(&attach->node);
719         if (dmabuf->ops->detach)
720                 dmabuf->ops->detach(dmabuf, attach);
721
722         mutex_unlock(&dmabuf->lock);
723         kfree(attach);
724 }
725 EXPORT_SYMBOL_GPL(dma_buf_detach);
726
727 /**
728  * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
729  * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
730  * dma_buf_ops.
731  * @attach:     [in]    attachment whose scatterlist is to be returned
732  * @direction:  [in]    direction of DMA transfer
733  *
734  * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
735  * on error. May return -EINTR if it is interrupted by a signal.
736  *
737  * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
738  * the underlying backing storage is pinned for as long as a mapping exists,
739  * therefore users/importers should not hold onto a mapping for undue amounts of
740  * time.
741  */
742 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
743                                         enum dma_data_direction direction)
744 {
745         struct sg_table *sg_table;
746
747         might_sleep();
748
749         if (WARN_ON(!attach || !attach->dmabuf))
750                 return ERR_PTR(-EINVAL);
751
752         if (attach->sgt) {
753                 /*
754                  * Two mappings with different directions for the same
755                  * attachment are not allowed.
756                  */
757                 if (attach->dir != direction &&
758                     attach->dir != DMA_BIDIRECTIONAL)
759                         return ERR_PTR(-EBUSY);
760
761                 return attach->sgt;
762         }
763
764         sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
765         if (!sg_table)
766                 sg_table = ERR_PTR(-ENOMEM);
767
768         if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
769                 attach->sgt = sg_table;
770                 attach->dir = direction;
771         }
772
773         return sg_table;
774 }
775 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
776
777 /**
778  * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
779  * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
780  * dma_buf_ops.
781  * @attach:     [in]    attachment to unmap buffer from
782  * @sg_table:   [in]    scatterlist info of the buffer to unmap
783  * @direction:  [in]    direction of DMA transfer
784  *
785  * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
786  */
787 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
788                                 struct sg_table *sg_table,
789                                 enum dma_data_direction direction)
790 {
791         might_sleep();
792
793         if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
794                 return;
795
796         if (attach->sgt == sg_table)
797                 return;
798
799         attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
800 }
801 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
802
803 /**
804  * DOC: cpu access
805  *
806  * There are mutliple reasons for supporting CPU access to a dma buffer object:
807  *
808  * - Fallback operations in the kernel, for example when a device is connected
809  *   over USB and the kernel needs to shuffle the data around first before
810  *   sending it away. Cache coherency is handled by braketing any transactions
811  *   with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
812  *   access.
813  *
814  *   To support dma_buf objects residing in highmem cpu access is page-based
815  *   using an api similar to kmap. Accessing a dma_buf is done in aligned chunks
816  *   of PAGE_SIZE size. Before accessing a chunk it needs to be mapped, which
817  *   returns a pointer in kernel virtual address space. Afterwards the chunk
818  *   needs to be unmapped again. There is no limit on how often a given chunk
819  *   can be mapped and unmapped, i.e. the importer does not need to call
820  *   begin_cpu_access again before mapping the same chunk again.
821  *
822  *   Interfaces::
823  *      void \*dma_buf_kmap(struct dma_buf \*, unsigned long);
824  *      void dma_buf_kunmap(struct dma_buf \*, unsigned long, void \*);
825  *
826  *   Implementing the functions is optional for exporters and for importers all
827  *   the restrictions of using kmap apply.
828  *
829  *   dma_buf kmap calls outside of the range specified in begin_cpu_access are
830  *   undefined. If the range is not PAGE_SIZE aligned, kmap needs to succeed on
831  *   the partial chunks at the beginning and end but may return stale or bogus
832  *   data outside of the range (in these partial chunks).
833  *
834  *   For some cases the overhead of kmap can be too high, a vmap interface
835  *   is introduced. This interface should be used very carefully, as vmalloc
836  *   space is a limited resources on many architectures.
837  *
838  *   Interfaces::
839  *      void \*dma_buf_vmap(struct dma_buf \*dmabuf)
840  *      void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
841  *
842  *   The vmap call can fail if there is no vmap support in the exporter, or if
843  *   it runs out of vmalloc space. Fallback to kmap should be implemented. Note
844  *   that the dma-buf layer keeps a reference count for all vmap access and
845  *   calls down into the exporter's vmap function only when no vmapping exists,
846  *   and only unmaps it once. Protection against concurrent vmap/vunmap calls is
847  *   provided by taking the dma_buf->lock mutex.
848  *
849  * - For full compatibility on the importer side with existing userspace
850  *   interfaces, which might already support mmap'ing buffers. This is needed in
851  *   many processing pipelines (e.g. feeding a software rendered image into a
852  *   hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
853  *   framework already supported this and for DMA buffer file descriptors to
854  *   replace ION buffers mmap support was needed.
855  *
856  *   There is no special interfaces, userspace simply calls mmap on the dma-buf
857  *   fd. But like for CPU access there's a need to braket the actual access,
858  *   which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
859  *   DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
860  *   be restarted.
861  *
862  *   Some systems might need some sort of cache coherency management e.g. when
863  *   CPU and GPU domains are being accessed through dma-buf at the same time.
864  *   To circumvent this problem there are begin/end coherency markers, that
865  *   forward directly to existing dma-buf device drivers vfunc hooks. Userspace
866  *   can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
867  *   sequence would be used like following:
868  *
869  *     - mmap dma-buf fd
870  *     - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
871  *       to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
872  *       want (with the new data being consumed by say the GPU or the scanout
873  *       device)
874  *     - munmap once you don't need the buffer any more
875  *
876  *    For correctness and optimal performance, it is always required to use
877  *    SYNC_START and SYNC_END before and after, respectively, when accessing the
878  *    mapped address. Userspace cannot rely on coherent access, even when there
879  *    are systems where it just works without calling these ioctls.
880  *
881  * - And as a CPU fallback in userspace processing pipelines.
882  *
883  *   Similar to the motivation for kernel cpu access it is again important that
884  *   the userspace code of a given importing subsystem can use the same
885  *   interfaces with a imported dma-buf buffer object as with a native buffer
886  *   object. This is especially important for drm where the userspace part of
887  *   contemporary OpenGL, X, and other drivers is huge, and reworking them to
888  *   use a different way to mmap a buffer rather invasive.
889  *
890  *   The assumption in the current dma-buf interfaces is that redirecting the
891  *   initial mmap is all that's needed. A survey of some of the existing
892  *   subsystems shows that no driver seems to do any nefarious thing like
893  *   syncing up with outstanding asynchronous processing on the device or
894  *   allocating special resources at fault time. So hopefully this is good
895  *   enough, since adding interfaces to intercept pagefaults and allow pte
896  *   shootdowns would increase the complexity quite a bit.
897  *
898  *   Interface::
899  *      int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
900  *                     unsigned long);
901  *
902  *   If the importing subsystem simply provides a special-purpose mmap call to
903  *   set up a mapping in userspace, calling do_mmap with dma_buf->file will
904  *   equally achieve that for a dma-buf object.
905  */
906
907 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
908                                       enum dma_data_direction direction)
909 {
910         bool write = (direction == DMA_BIDIRECTIONAL ||
911                       direction == DMA_TO_DEVICE);
912         struct reservation_object *resv = dmabuf->resv;
913         long ret;
914
915         /* Wait on any implicit rendering fences */
916         ret = reservation_object_wait_timeout_rcu(resv, write, true,
917                                                   MAX_SCHEDULE_TIMEOUT);
918         if (ret < 0)
919                 return ret;
920
921         return 0;
922 }
923
924 /**
925  * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
926  * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
927  * preparations. Coherency is only guaranteed in the specified range for the
928  * specified access direction.
929  * @dmabuf:     [in]    buffer to prepare cpu access for.
930  * @direction:  [in]    length of range for cpu access.
931  *
932  * After the cpu access is complete the caller should call
933  * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
934  * it guaranteed to be coherent with other DMA access.
935  *
936  * Can return negative error values, returns 0 on success.
937  */
938 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
939                              enum dma_data_direction direction)
940 {
941         int ret = 0;
942
943         if (WARN_ON(!dmabuf))
944                 return -EINVAL;
945
946         if (dmabuf->ops->begin_cpu_access)
947                 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
948
949         /* Ensure that all fences are waited upon - but we first allow
950          * the native handler the chance to do so more efficiently if it
951          * chooses. A double invocation here will be reasonably cheap no-op.
952          */
953         if (ret == 0)
954                 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
955
956         return ret;
957 }
958 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
959
960 /**
961  * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
962  * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
963  * actions. Coherency is only guaranteed in the specified range for the
964  * specified access direction.
965  * @dmabuf:     [in]    buffer to complete cpu access for.
966  * @direction:  [in]    length of range for cpu access.
967  *
968  * This terminates CPU access started with dma_buf_begin_cpu_access().
969  *
970  * Can return negative error values, returns 0 on success.
971  */
972 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
973                            enum dma_data_direction direction)
974 {
975         int ret = 0;
976
977         WARN_ON(!dmabuf);
978
979         if (dmabuf->ops->end_cpu_access)
980                 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
981
982         return ret;
983 }
984 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
985
986 /**
987  * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
988  * same restrictions as for kmap and friends apply.
989  * @dmabuf:     [in]    buffer to map page from.
990  * @page_num:   [in]    page in PAGE_SIZE units to map.
991  *
992  * This call must always succeed, any necessary preparations that might fail
993  * need to be done in begin_cpu_access.
994  */
995 void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
996 {
997         WARN_ON(!dmabuf);
998
999         if (!dmabuf->ops->map)
1000                 return NULL;
1001         return dmabuf->ops->map(dmabuf, page_num);
1002 }
1003 EXPORT_SYMBOL_GPL(dma_buf_kmap);
1004
1005 /**
1006  * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
1007  * @dmabuf:     [in]    buffer to unmap page from.
1008  * @page_num:   [in]    page in PAGE_SIZE units to unmap.
1009  * @vaddr:      [in]    kernel space pointer obtained from dma_buf_kmap.
1010  *
1011  * This call must always succeed.
1012  */
1013 void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
1014                     void *vaddr)
1015 {
1016         WARN_ON(!dmabuf);
1017
1018         if (dmabuf->ops->unmap)
1019                 dmabuf->ops->unmap(dmabuf, page_num, vaddr);
1020 }
1021 EXPORT_SYMBOL_GPL(dma_buf_kunmap);
1022
1023
1024 /**
1025  * dma_buf_mmap - Setup up a userspace mmap with the given vma
1026  * @dmabuf:     [in]    buffer that should back the vma
1027  * @vma:        [in]    vma for the mmap
1028  * @pgoff:      [in]    offset in pages where this mmap should start within the
1029  *                      dma-buf buffer.
1030  *
1031  * This function adjusts the passed in vma so that it points at the file of the
1032  * dma_buf operation. It also adjusts the starting pgoff and does bounds
1033  * checking on the size of the vma. Then it calls the exporters mmap function to
1034  * set up the mapping.
1035  *
1036  * Can return negative error values, returns 0 on success.
1037  */
1038 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1039                  unsigned long pgoff)
1040 {
1041         struct file *oldfile;
1042         int ret;
1043
1044         if (WARN_ON(!dmabuf || !vma))
1045                 return -EINVAL;
1046
1047         /* check if buffer supports mmap */
1048         if (!dmabuf->ops->mmap)
1049                 return -EINVAL;
1050
1051         /* check for offset overflow */
1052         if (pgoff + vma_pages(vma) < pgoff)
1053                 return -EOVERFLOW;
1054
1055         /* check for overflowing the buffer's size */
1056         if (pgoff + vma_pages(vma) >
1057             dmabuf->size >> PAGE_SHIFT)
1058                 return -EINVAL;
1059
1060         /* readjust the vma */
1061         get_file(dmabuf->file);
1062         oldfile = vma->vm_file;
1063         vma->vm_file = dmabuf->file;
1064         vma->vm_pgoff = pgoff;
1065
1066         ret = dmabuf->ops->mmap(dmabuf, vma);
1067         if (ret) {
1068                 /* restore old parameters on failure */
1069                 vma->vm_file = oldfile;
1070                 fput(dmabuf->file);
1071         } else {
1072                 if (oldfile)
1073                         fput(oldfile);
1074         }
1075         return ret;
1076
1077 }
1078 EXPORT_SYMBOL_GPL(dma_buf_mmap);
1079
1080 /**
1081  * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1082  * address space. Same restrictions as for vmap and friends apply.
1083  * @dmabuf:     [in]    buffer to vmap
1084  *
1085  * This call may fail due to lack of virtual mapping address space.
1086  * These calls are optional in drivers. The intended use for them
1087  * is for mapping objects linear in kernel space for high use objects.
1088  * Please attempt to use kmap/kunmap before thinking about these interfaces.
1089  *
1090  * Returns NULL on error.
1091  */
1092 void *dma_buf_vmap(struct dma_buf *dmabuf)
1093 {
1094         void *ptr;
1095
1096         if (WARN_ON(!dmabuf))
1097                 return NULL;
1098
1099         if (!dmabuf->ops->vmap)
1100                 return NULL;
1101
1102         mutex_lock(&dmabuf->lock);
1103         if (dmabuf->vmapping_counter) {
1104                 dmabuf->vmapping_counter++;
1105                 BUG_ON(!dmabuf->vmap_ptr);
1106                 ptr = dmabuf->vmap_ptr;
1107                 goto out_unlock;
1108         }
1109
1110         BUG_ON(dmabuf->vmap_ptr);
1111
1112         ptr = dmabuf->ops->vmap(dmabuf);
1113         if (WARN_ON_ONCE(IS_ERR(ptr)))
1114                 ptr = NULL;
1115         if (!ptr)
1116                 goto out_unlock;
1117
1118         dmabuf->vmap_ptr = ptr;
1119         dmabuf->vmapping_counter = 1;
1120
1121 out_unlock:
1122         mutex_unlock(&dmabuf->lock);
1123         return ptr;
1124 }
1125 EXPORT_SYMBOL_GPL(dma_buf_vmap);
1126
1127 /**
1128  * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1129  * @dmabuf:     [in]    buffer to vunmap
1130  * @vaddr:      [in]    vmap to vunmap
1131  */
1132 void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
1133 {
1134         if (WARN_ON(!dmabuf))
1135                 return;
1136
1137         BUG_ON(!dmabuf->vmap_ptr);
1138         BUG_ON(dmabuf->vmapping_counter == 0);
1139         BUG_ON(dmabuf->vmap_ptr != vaddr);
1140
1141         mutex_lock(&dmabuf->lock);
1142         if (--dmabuf->vmapping_counter == 0) {
1143                 if (dmabuf->ops->vunmap)
1144                         dmabuf->ops->vunmap(dmabuf, vaddr);
1145                 dmabuf->vmap_ptr = NULL;
1146         }
1147         mutex_unlock(&dmabuf->lock);
1148 }
1149 EXPORT_SYMBOL_GPL(dma_buf_vunmap);
1150
1151 #ifdef CONFIG_DEBUG_FS
1152 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1153 {
1154         int ret;
1155         struct dma_buf *buf_obj;
1156         struct dma_buf_attachment *attach_obj;
1157         struct reservation_object *robj;
1158         struct reservation_object_list *fobj;
1159         struct dma_fence *fence;
1160         unsigned seq;
1161         int count = 0, attach_count, shared_count, i;
1162         size_t size = 0;
1163
1164         ret = mutex_lock_interruptible(&db_list.lock);
1165
1166         if (ret)
1167                 return ret;
1168
1169         seq_puts(s, "\nDma-buf Objects:\n");
1170         seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\n",
1171                    "size", "flags", "mode", "count", "ino");
1172
1173         list_for_each_entry(buf_obj, &db_list.head, list_node) {
1174                 ret = mutex_lock_interruptible(&buf_obj->lock);
1175
1176                 if (ret) {
1177                         seq_puts(s,
1178                                  "\tERROR locking buffer object: skipping\n");
1179                         continue;
1180                 }
1181
1182                 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1183                                 buf_obj->size,
1184                                 buf_obj->file->f_flags, buf_obj->file->f_mode,
1185                                 file_count(buf_obj->file),
1186                                 buf_obj->exp_name,
1187                                 file_inode(buf_obj->file)->i_ino,
1188                                 buf_obj->name ?: "");
1189
1190                 robj = buf_obj->resv;
1191                 while (true) {
1192                         seq = read_seqcount_begin(&robj->seq);
1193                         rcu_read_lock();
1194                         fobj = rcu_dereference(robj->fence);
1195                         shared_count = fobj ? fobj->shared_count : 0;
1196                         fence = rcu_dereference(robj->fence_excl);
1197                         if (!read_seqcount_retry(&robj->seq, seq))
1198                                 break;
1199                         rcu_read_unlock();
1200                 }
1201
1202                 if (fence)
1203                         seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
1204                                    fence->ops->get_driver_name(fence),
1205                                    fence->ops->get_timeline_name(fence),
1206                                    dma_fence_is_signaled(fence) ? "" : "un");
1207                 for (i = 0; i < shared_count; i++) {
1208                         fence = rcu_dereference(fobj->shared[i]);
1209                         if (!dma_fence_get_rcu(fence))
1210                                 continue;
1211                         seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
1212                                    fence->ops->get_driver_name(fence),
1213                                    fence->ops->get_timeline_name(fence),
1214                                    dma_fence_is_signaled(fence) ? "" : "un");
1215                         dma_fence_put(fence);
1216                 }
1217                 rcu_read_unlock();
1218
1219                 seq_puts(s, "\tAttached Devices:\n");
1220                 attach_count = 0;
1221
1222                 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1223                         seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1224                         attach_count++;
1225                 }
1226
1227                 seq_printf(s, "Total %d devices attached\n\n",
1228                                 attach_count);
1229
1230                 count++;
1231                 size += buf_obj->size;
1232                 mutex_unlock(&buf_obj->lock);
1233         }
1234
1235         seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1236
1237         mutex_unlock(&db_list.lock);
1238         return 0;
1239 }
1240
1241 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1242
1243 static struct dentry *dma_buf_debugfs_dir;
1244
1245 static int dma_buf_init_debugfs(void)
1246 {
1247         struct dentry *d;
1248         int err = 0;
1249
1250         d = debugfs_create_dir("dma_buf", NULL);
1251         if (IS_ERR(d))
1252                 return PTR_ERR(d);
1253
1254         dma_buf_debugfs_dir = d;
1255
1256         d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1257                                 NULL, &dma_buf_debug_fops);
1258         if (IS_ERR(d)) {
1259                 pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1260                 debugfs_remove_recursive(dma_buf_debugfs_dir);
1261                 dma_buf_debugfs_dir = NULL;
1262                 err = PTR_ERR(d);
1263         }
1264
1265         return err;
1266 }
1267
1268 static void dma_buf_uninit_debugfs(void)
1269 {
1270         debugfs_remove_recursive(dma_buf_debugfs_dir);
1271 }
1272 #else
1273 static inline int dma_buf_init_debugfs(void)
1274 {
1275         return 0;
1276 }
1277 static inline void dma_buf_uninit_debugfs(void)
1278 {
1279 }
1280 #endif
1281
1282 static int __init dma_buf_init(void)
1283 {
1284         dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1285         if (IS_ERR(dma_buf_mnt))
1286                 return PTR_ERR(dma_buf_mnt);
1287
1288         mutex_init(&db_list.lock);
1289         INIT_LIST_HEAD(&db_list.head);
1290         dma_buf_init_debugfs();
1291         return 0;
1292 }
1293 subsys_initcall(dma_buf_init);
1294
1295 static void __exit dma_buf_deinit(void)
1296 {
1297         dma_buf_uninit_debugfs();
1298         kern_unmount(dma_buf_mnt);
1299 }
1300 __exitcall(dma_buf_deinit);