Merge tag 'for-linus-20190617' of git://git.sourceforge.jp/gitroot/uclinux-h8/linux
[linux-2.6-microblaze.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
28 #include <uapi/linux/dma-buf.h>
29 #include <uapi/linux/magic.h>
30
31 static inline int is_dma_buf_file(struct file *);
32
33 struct dma_buf_list {
34         struct list_head head;
35         struct mutex lock;
36 };
37
38 static struct dma_buf_list db_list;
39
40 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
41 {
42         struct dma_buf *dmabuf;
43         char name[DMA_BUF_NAME_LEN];
44         size_t ret = 0;
45
46         dmabuf = dentry->d_fsdata;
47         mutex_lock(&dmabuf->lock);
48         if (dmabuf->name)
49                 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
50         mutex_unlock(&dmabuf->lock);
51
52         return dynamic_dname(dentry, buffer, buflen, "/%s:%s",
53                              dentry->d_name.name, ret > 0 ? name : "");
54 }
55
56 static const struct dentry_operations dma_buf_dentry_ops = {
57         .d_dname = dmabuffs_dname,
58 };
59
60 static struct vfsmount *dma_buf_mnt;
61
62 static struct dentry *dma_buf_fs_mount(struct file_system_type *fs_type,
63                 int flags, const char *name, void *data)
64 {
65         return mount_pseudo(fs_type, "dmabuf:", NULL, &dma_buf_dentry_ops,
66                         DMA_BUF_MAGIC);
67 }
68
69 static struct file_system_type dma_buf_fs_type = {
70         .name = "dmabuf",
71         .mount = dma_buf_fs_mount,
72         .kill_sb = kill_anon_super,
73 };
74
75 static int dma_buf_release(struct inode *inode, struct file *file)
76 {
77         struct dma_buf *dmabuf;
78
79         if (!is_dma_buf_file(file))
80                 return -EINVAL;
81
82         dmabuf = file->private_data;
83
84         BUG_ON(dmabuf->vmapping_counter);
85
86         /*
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.
90          *
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.
93          */
94         BUG_ON(dmabuf->cb_shared.active || dmabuf->cb_excl.active);
95
96         dmabuf->ops->release(dmabuf);
97
98         mutex_lock(&db_list.lock);
99         list_del(&dmabuf->list_node);
100         mutex_unlock(&db_list.lock);
101
102         if (dmabuf->resv == (struct reservation_object *)&dmabuf[1])
103                 reservation_object_fini(dmabuf->resv);
104
105         module_put(dmabuf->owner);
106         kfree(dmabuf);
107         return 0;
108 }
109
110 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
111 {
112         struct dma_buf *dmabuf;
113
114         if (!is_dma_buf_file(file))
115                 return -EINVAL;
116
117         dmabuf = file->private_data;
118
119         /* check if buffer supports mmap */
120         if (!dmabuf->ops->mmap)
121                 return -EINVAL;
122
123         /* check for overflowing the buffer's size */
124         if (vma->vm_pgoff + vma_pages(vma) >
125             dmabuf->size >> PAGE_SHIFT)
126                 return -EINVAL;
127
128         return dmabuf->ops->mmap(dmabuf, vma);
129 }
130
131 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
132 {
133         struct dma_buf *dmabuf;
134         loff_t base;
135
136         if (!is_dma_buf_file(file))
137                 return -EBADF;
138
139         dmabuf = file->private_data;
140
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)
145                 base = dmabuf->size;
146         else if (whence == SEEK_SET)
147                 base = 0;
148         else
149                 return -EINVAL;
150
151         if (offset != 0)
152                 return -EINVAL;
153
154         return base + offset;
155 }
156
157 /**
158  * DOC: fence polling
159  *
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.
164  *
165  * Userspace can query the state of these implicitly tracked fences using poll()
166  * and related system calls:
167  *
168  * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
169  *   most recent write or exclusive fence.
170  *
171  * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
172  *   all attached fences, shared and exclusive ones.
173  *
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.
177  */
178
179 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
180 {
181         struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
182         unsigned long flags;
183
184         spin_lock_irqsave(&dcb->poll->lock, flags);
185         wake_up_locked_poll(dcb->poll, dcb->active);
186         dcb->active = 0;
187         spin_unlock_irqrestore(&dcb->poll->lock, flags);
188 }
189
190 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
191 {
192         struct dma_buf *dmabuf;
193         struct reservation_object *resv;
194         struct reservation_object_list *fobj;
195         struct dma_fence *fence_excl;
196         __poll_t events;
197         unsigned shared_count, seq;
198
199         dmabuf = file->private_data;
200         if (!dmabuf || !dmabuf->resv)
201                 return EPOLLERR;
202
203         resv = dmabuf->resv;
204
205         poll_wait(file, &dmabuf->poll, poll);
206
207         events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
208         if (!events)
209                 return 0;
210
211 retry:
212         seq = read_seqcount_begin(&resv->seq);
213         rcu_read_lock();
214
215         fobj = rcu_dereference(resv->fence);
216         if (fobj)
217                 shared_count = fobj->shared_count;
218         else
219                 shared_count = 0;
220         fence_excl = rcu_dereference(resv->fence_excl);
221         if (read_seqcount_retry(&resv->seq, seq)) {
222                 rcu_read_unlock();
223                 goto retry;
224         }
225
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;
229
230                 if (shared_count == 0)
231                         pevents |= EPOLLOUT;
232
233                 spin_lock_irq(&dmabuf->poll.lock);
234                 if (dcb->active) {
235                         dcb->active |= pevents;
236                         events &= ~pevents;
237                 } else
238                         dcb->active = pevents;
239                 spin_unlock_irq(&dmabuf->poll.lock);
240
241                 if (events & pevents) {
242                         if (!dma_fence_get_rcu(fence_excl)) {
243                                 /* force a recheck */
244                                 events &= ~pevents;
245                                 dma_buf_poll_cb(NULL, &dcb->cb);
246                         } else if (!dma_fence_add_callback(fence_excl, &dcb->cb,
247                                                            dma_buf_poll_cb)) {
248                                 events &= ~pevents;
249                                 dma_fence_put(fence_excl);
250                         } else {
251                                 /*
252                                  * No callback queued, wake up any additional
253                                  * waiters.
254                                  */
255                                 dma_fence_put(fence_excl);
256                                 dma_buf_poll_cb(NULL, &dcb->cb);
257                         }
258                 }
259         }
260
261         if ((events & EPOLLOUT) && shared_count > 0) {
262                 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_shared;
263                 int i;
264
265                 /* Only queue a new callback if no event has fired yet */
266                 spin_lock_irq(&dmabuf->poll.lock);
267                 if (dcb->active)
268                         events &= ~EPOLLOUT;
269                 else
270                         dcb->active = EPOLLOUT;
271                 spin_unlock_irq(&dmabuf->poll.lock);
272
273                 if (!(events & EPOLLOUT))
274                         goto out;
275
276                 for (i = 0; i < shared_count; ++i) {
277                         struct dma_fence *fence = rcu_dereference(fobj->shared[i]);
278
279                         if (!dma_fence_get_rcu(fence)) {
280                                 /*
281                                  * fence refcount dropped to zero, this means
282                                  * that fobj has been freed
283                                  *
284                                  * call dma_buf_poll_cb and force a recheck!
285                                  */
286                                 events &= ~EPOLLOUT;
287                                 dma_buf_poll_cb(NULL, &dcb->cb);
288                                 break;
289                         }
290                         if (!dma_fence_add_callback(fence, &dcb->cb,
291                                                     dma_buf_poll_cb)) {
292                                 dma_fence_put(fence);
293                                 events &= ~EPOLLOUT;
294                                 break;
295                         }
296                         dma_fence_put(fence);
297                 }
298
299                 /* No callback queued, wake up any additional waiters. */
300                 if (i == shared_count)
301                         dma_buf_poll_cb(NULL, &dcb->cb);
302         }
303
304 out:
305         rcu_read_unlock();
306         return events;
307 }
308
309 /**
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.
315  *
316  * @dmabuf [in]     dmabuf buffer that will be renamed.
317  * @buf:   [in]     A piece of userspace memory that contains the name of
318  *                  the dma-buf.
319  *
320  * Returns 0 on success. If the dma-buf buffer is already attached to
321  * devices, return -EBUSY.
322  *
323  */
324 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
325 {
326         char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
327         long ret = 0;
328
329         if (IS_ERR(name))
330                 return PTR_ERR(name);
331
332         mutex_lock(&dmabuf->lock);
333         if (!list_empty(&dmabuf->attachments)) {
334                 ret = -EBUSY;
335                 kfree(name);
336                 goto out_unlock;
337         }
338         kfree(dmabuf->name);
339         dmabuf->name = name;
340
341 out_unlock:
342         mutex_unlock(&dmabuf->lock);
343         return ret;
344 }
345
346 static long dma_buf_ioctl(struct file *file,
347                           unsigned int cmd, unsigned long arg)
348 {
349         struct dma_buf *dmabuf;
350         struct dma_buf_sync sync;
351         enum dma_data_direction direction;
352         int ret;
353
354         dmabuf = file->private_data;
355
356         switch (cmd) {
357         case DMA_BUF_IOCTL_SYNC:
358                 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
359                         return -EFAULT;
360
361                 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
362                         return -EINVAL;
363
364                 switch (sync.flags & DMA_BUF_SYNC_RW) {
365                 case DMA_BUF_SYNC_READ:
366                         direction = DMA_FROM_DEVICE;
367                         break;
368                 case DMA_BUF_SYNC_WRITE:
369                         direction = DMA_TO_DEVICE;
370                         break;
371                 case DMA_BUF_SYNC_RW:
372                         direction = DMA_BIDIRECTIONAL;
373                         break;
374                 default:
375                         return -EINVAL;
376                 }
377
378                 if (sync.flags & DMA_BUF_SYNC_END)
379                         ret = dma_buf_end_cpu_access(dmabuf, direction);
380                 else
381                         ret = dma_buf_begin_cpu_access(dmabuf, direction);
382
383                 return ret;
384
385         case DMA_BUF_SET_NAME:
386                 return dma_buf_set_name(dmabuf, (const char __user *)arg);
387
388         default:
389                 return -ENOTTY;
390         }
391 }
392
393 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
394 {
395         struct dma_buf *dmabuf = file->private_data;
396
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);
402         if (dmabuf->name)
403                 seq_printf(m, "name:\t%s\n", dmabuf->name);
404         mutex_unlock(&dmabuf->lock);
405 }
406
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,
413 #ifdef CONFIG_COMPAT
414         .compat_ioctl   = dma_buf_ioctl,
415 #endif
416         .show_fdinfo    = dma_buf_show_fdinfo,
417 };
418
419 /*
420  * is_dma_buf_file - Check if struct file* is associated with dma_buf
421  */
422 static inline int is_dma_buf_file(struct file *file)
423 {
424         return file->f_op == &dma_buf_fops;
425 }
426
427 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
428 {
429         struct file *file;
430         struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
431
432         if (IS_ERR(inode))
433                 return ERR_CAST(inode);
434
435         inode->i_size = dmabuf->size;
436         inode_set_bytes(inode, dmabuf->size);
437
438         file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
439                                  flags, &dma_buf_fops);
440         if (IS_ERR(file))
441                 goto err_alloc_file;
442         file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
443         file->private_data = dmabuf;
444         file->f_path.dentry->d_fsdata = dmabuf;
445
446         return file;
447
448 err_alloc_file:
449         iput(inode);
450         return file;
451 }
452
453 /**
454  * DOC: dma buf device access
455  *
456  * For device DMA access to a shared DMA buffer the usual sequence of operations
457  * is fairly simple:
458  *
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().
463  *
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
467  *    dma_buf_attach().
468  *
469  *    Up to this stage the exporter is still free to migrate or reallocate the
470  *    backing storage.
471  *
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().
475  *
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().
479  *
480  * For the detailed semantics exporters are expected to implement see
481  * &dma_buf_ops.
482  */
483
484 /**
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.
489  *
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.
493  *
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.
497  *
498  * For most cases the easiest way to create @exp_info is through the
499  * %DEFINE_DMA_BUF_EXPORT_INFO macro.
500  */
501 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
502 {
503         struct dma_buf *dmabuf;
504         struct reservation_object *resv = exp_info->resv;
505         struct file *file;
506         size_t alloc_size = sizeof(struct dma_buf);
507         int ret;
508
509         if (!exp_info->resv)
510                 alloc_size += sizeof(struct reservation_object);
511         else
512                 /* prevent &dma_buf[1] == dma_buf->resv */
513                 alloc_size += 1;
514
515         if (WARN_ON(!exp_info->priv
516                           || !exp_info->ops
517                           || !exp_info->ops->map_dma_buf
518                           || !exp_info->ops->unmap_dma_buf
519                           || !exp_info->ops->release)) {
520                 return ERR_PTR(-EINVAL);
521         }
522
523         if (!try_module_get(exp_info->owner))
524                 return ERR_PTR(-ENOENT);
525
526         dmabuf = kzalloc(alloc_size, GFP_KERNEL);
527         if (!dmabuf) {
528                 ret = -ENOMEM;
529                 goto err_module;
530         }
531
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;
540
541         if (!resv) {
542                 resv = (struct reservation_object *)&dmabuf[1];
543                 reservation_object_init(resv);
544         }
545         dmabuf->resv = resv;
546
547         file = dma_buf_getfile(dmabuf, exp_info->flags);
548         if (IS_ERR(file)) {
549                 ret = PTR_ERR(file);
550                 goto err_dmabuf;
551         }
552
553         file->f_mode |= FMODE_LSEEK;
554         dmabuf->file = file;
555
556         mutex_init(&dmabuf->lock);
557         INIT_LIST_HEAD(&dmabuf->attachments);
558
559         mutex_lock(&db_list.lock);
560         list_add(&dmabuf->list_node, &db_list.head);
561         mutex_unlock(&db_list.lock);
562
563         return dmabuf;
564
565 err_dmabuf:
566         kfree(dmabuf);
567 err_module:
568         module_put(exp_info->owner);
569         return ERR_PTR(ret);
570 }
571 EXPORT_SYMBOL_GPL(dma_buf_export);
572
573 /**
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
577  *
578  * On success, returns an associated 'fd'. Else, returns error.
579  */
580 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
581 {
582         int fd;
583
584         if (!dmabuf || !dmabuf->file)
585                 return -EINVAL;
586
587         fd = get_unused_fd_flags(flags);
588         if (fd < 0)
589                 return fd;
590
591         fd_install(fd, dmabuf->file);
592
593         return fd;
594 }
595 EXPORT_SYMBOL_GPL(dma_buf_fd);
596
597 /**
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
600  *
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
603  * otherwise.
604  */
605 struct dma_buf *dma_buf_get(int fd)
606 {
607         struct file *file;
608
609         file = fget(fd);
610
611         if (!file)
612                 return ERR_PTR(-EBADF);
613
614         if (!is_dma_buf_file(file)) {
615                 fput(file);
616                 return ERR_PTR(-EINVAL);
617         }
618
619         return file->private_data;
620 }
621 EXPORT_SYMBOL_GPL(dma_buf_get);
622
623 /**
624  * dma_buf_put - decreases refcount of the buffer
625  * @dmabuf:     [in]    buffer to reduce refcount of
626  *
627  * Uses file's refcounting done implicitly by fput().
628  *
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.
632  */
633 void dma_buf_put(struct dma_buf *dmabuf)
634 {
635         if (WARN_ON(!dmabuf || !dmabuf->file))
636                 return;
637
638         fput(dmabuf->file);
639 }
640 EXPORT_SYMBOL_GPL(dma_buf_put);
641
642 /**
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.
647  *
648  * Returns struct dma_buf_attachment pointer for this attachment. Attachments
649  * must be cleaned up by calling dma_buf_detach().
650  *
651  * Returns:
652  *
653  * A pointer to newly created &dma_buf_attachment on success, or a negative
654  * error code wrapped into a pointer on failure.
655  *
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.
659  */
660 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
661                                           struct device *dev)
662 {
663         struct dma_buf_attachment *attach;
664         int ret;
665
666         if (WARN_ON(!dmabuf || !dev))
667                 return ERR_PTR(-EINVAL);
668
669         attach = kzalloc(sizeof(*attach), GFP_KERNEL);
670         if (!attach)
671                 return ERR_PTR(-ENOMEM);
672
673         attach->dev = dev;
674         attach->dmabuf = dmabuf;
675
676         mutex_lock(&dmabuf->lock);
677
678         if (dmabuf->ops->attach) {
679                 ret = dmabuf->ops->attach(dmabuf, attach);
680                 if (ret)
681                         goto err_attach;
682         }
683         list_add(&attach->node, &dmabuf->attachments);
684
685         mutex_unlock(&dmabuf->lock);
686
687         return attach;
688
689 err_attach:
690         kfree(attach);
691         mutex_unlock(&dmabuf->lock);
692         return ERR_PTR(ret);
693 }
694 EXPORT_SYMBOL_GPL(dma_buf_attach);
695
696 /**
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.
701  *
702  * Clean up a device attachment obtained by calling dma_buf_attach().
703  */
704 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
705 {
706         if (WARN_ON(!dmabuf || !attach))
707                 return;
708
709         if (attach->sgt)
710                 dmabuf->ops->unmap_dma_buf(attach, attach->sgt, attach->dir);
711
712         mutex_lock(&dmabuf->lock);
713         list_del(&attach->node);
714         if (dmabuf->ops->detach)
715                 dmabuf->ops->detach(dmabuf, attach);
716
717         mutex_unlock(&dmabuf->lock);
718         kfree(attach);
719 }
720 EXPORT_SYMBOL_GPL(dma_buf_detach);
721
722 /**
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
725  * dma_buf_ops.
726  * @attach:     [in]    attachment whose scatterlist is to be returned
727  * @direction:  [in]    direction of DMA transfer
728  *
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.
731  *
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
735  * time.
736  */
737 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
738                                         enum dma_data_direction direction)
739 {
740         struct sg_table *sg_table;
741
742         might_sleep();
743
744         if (WARN_ON(!attach || !attach->dmabuf))
745                 return ERR_PTR(-EINVAL);
746
747         if (attach->sgt) {
748                 /*
749                  * Two mappings with different directions for the same
750                  * attachment are not allowed.
751                  */
752                 if (attach->dir != direction &&
753                     attach->dir != DMA_BIDIRECTIONAL)
754                         return ERR_PTR(-EBUSY);
755
756                 return attach->sgt;
757         }
758
759         sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
760         if (!sg_table)
761                 sg_table = ERR_PTR(-ENOMEM);
762
763         if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
764                 attach->sgt = sg_table;
765                 attach->dir = direction;
766         }
767
768         return sg_table;
769 }
770 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
771
772 /**
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
775  * dma_buf_ops.
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
779  *
780  * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
781  */
782 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
783                                 struct sg_table *sg_table,
784                                 enum dma_data_direction direction)
785 {
786         might_sleep();
787
788         if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
789                 return;
790
791         if (attach->sgt == sg_table)
792                 return;
793
794         attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
795 }
796 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
797
798 /**
799  * DOC: cpu access
800  *
801  * There are mutliple reasons for supporting CPU access to a dma buffer object:
802  *
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()
807  *   access.
808  *
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.
816  *
817  *   Interfaces::
818  *      void \*dma_buf_kmap(struct dma_buf \*, unsigned long);
819  *      void dma_buf_kunmap(struct dma_buf \*, unsigned long, void \*);
820  *
821  *   Implementing the functions is optional for exporters and for importers all
822  *   the restrictions of using kmap apply.
823  *
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).
828  *
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.
832  *
833  *   Interfaces::
834  *      void \*dma_buf_vmap(struct dma_buf \*dmabuf)
835  *      void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
836  *
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.
843  *
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.
850  *
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
855  *   be restarted.
856  *
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:
863  *
864  *     - mmap dma-buf fd
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
868  *       device)
869  *     - munmap once you don't need the buffer any more
870  *
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.
875  *
876  * - And as a CPU fallback in userspace processing pipelines.
877  *
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.
884  *
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.
892  *
893  *   Interface::
894  *      int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
895  *                     unsigned long);
896  *
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.
900  */
901
902 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
903                                       enum dma_data_direction direction)
904 {
905         bool write = (direction == DMA_BIDIRECTIONAL ||
906                       direction == DMA_TO_DEVICE);
907         struct reservation_object *resv = dmabuf->resv;
908         long ret;
909
910         /* Wait on any implicit rendering fences */
911         ret = reservation_object_wait_timeout_rcu(resv, write, true,
912                                                   MAX_SCHEDULE_TIMEOUT);
913         if (ret < 0)
914                 return ret;
915
916         return 0;
917 }
918
919 /**
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.
926  *
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.
930  *
931  * Can return negative error values, returns 0 on success.
932  */
933 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
934                              enum dma_data_direction direction)
935 {
936         int ret = 0;
937
938         if (WARN_ON(!dmabuf))
939                 return -EINVAL;
940
941         if (dmabuf->ops->begin_cpu_access)
942                 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
943
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.
947          */
948         if (ret == 0)
949                 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
950
951         return ret;
952 }
953 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
954
955 /**
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.
962  *
963  * This terminates CPU access started with dma_buf_begin_cpu_access().
964  *
965  * Can return negative error values, returns 0 on success.
966  */
967 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
968                            enum dma_data_direction direction)
969 {
970         int ret = 0;
971
972         WARN_ON(!dmabuf);
973
974         if (dmabuf->ops->end_cpu_access)
975                 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
976
977         return ret;
978 }
979 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
980
981 /**
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.
986  *
987  * This call must always succeed, any necessary preparations that might fail
988  * need to be done in begin_cpu_access.
989  */
990 void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
991 {
992         WARN_ON(!dmabuf);
993
994         if (!dmabuf->ops->map)
995                 return NULL;
996         return dmabuf->ops->map(dmabuf, page_num);
997 }
998 EXPORT_SYMBOL_GPL(dma_buf_kmap);
999
1000 /**
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.
1005  *
1006  * This call must always succeed.
1007  */
1008 void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
1009                     void *vaddr)
1010 {
1011         WARN_ON(!dmabuf);
1012
1013         if (dmabuf->ops->unmap)
1014                 dmabuf->ops->unmap(dmabuf, page_num, vaddr);
1015 }
1016 EXPORT_SYMBOL_GPL(dma_buf_kunmap);
1017
1018
1019 /**
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
1024  *                      dma-buf buffer.
1025  *
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.
1030  *
1031  * Can return negative error values, returns 0 on success.
1032  */
1033 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1034                  unsigned long pgoff)
1035 {
1036         struct file *oldfile;
1037         int ret;
1038
1039         if (WARN_ON(!dmabuf || !vma))
1040                 return -EINVAL;
1041
1042         /* check if buffer supports mmap */
1043         if (!dmabuf->ops->mmap)
1044                 return -EINVAL;
1045
1046         /* check for offset overflow */
1047         if (pgoff + vma_pages(vma) < pgoff)
1048                 return -EOVERFLOW;
1049
1050         /* check for overflowing the buffer's size */
1051         if (pgoff + vma_pages(vma) >
1052             dmabuf->size >> PAGE_SHIFT)
1053                 return -EINVAL;
1054
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;
1060
1061         ret = dmabuf->ops->mmap(dmabuf, vma);
1062         if (ret) {
1063                 /* restore old parameters on failure */
1064                 vma->vm_file = oldfile;
1065                 fput(dmabuf->file);
1066         } else {
1067                 if (oldfile)
1068                         fput(oldfile);
1069         }
1070         return ret;
1071
1072 }
1073 EXPORT_SYMBOL_GPL(dma_buf_mmap);
1074
1075 /**
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
1079  *
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.
1084  *
1085  * Returns NULL on error.
1086  */
1087 void *dma_buf_vmap(struct dma_buf *dmabuf)
1088 {
1089         void *ptr;
1090
1091         if (WARN_ON(!dmabuf))
1092                 return NULL;
1093
1094         if (!dmabuf->ops->vmap)
1095                 return NULL;
1096
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;
1102                 goto out_unlock;
1103         }
1104
1105         BUG_ON(dmabuf->vmap_ptr);
1106
1107         ptr = dmabuf->ops->vmap(dmabuf);
1108         if (WARN_ON_ONCE(IS_ERR(ptr)))
1109                 ptr = NULL;
1110         if (!ptr)
1111                 goto out_unlock;
1112
1113         dmabuf->vmap_ptr = ptr;
1114         dmabuf->vmapping_counter = 1;
1115
1116 out_unlock:
1117         mutex_unlock(&dmabuf->lock);
1118         return ptr;
1119 }
1120 EXPORT_SYMBOL_GPL(dma_buf_vmap);
1121
1122 /**
1123  * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1124  * @dmabuf:     [in]    buffer to vunmap
1125  * @vaddr:      [in]    vmap to vunmap
1126  */
1127 void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
1128 {
1129         if (WARN_ON(!dmabuf))
1130                 return;
1131
1132         BUG_ON(!dmabuf->vmap_ptr);
1133         BUG_ON(dmabuf->vmapping_counter == 0);
1134         BUG_ON(dmabuf->vmap_ptr != vaddr);
1135
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;
1141         }
1142         mutex_unlock(&dmabuf->lock);
1143 }
1144 EXPORT_SYMBOL_GPL(dma_buf_vunmap);
1145
1146 #ifdef CONFIG_DEBUG_FS
1147 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1148 {
1149         int ret;
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;
1155         unsigned seq;
1156         int count = 0, attach_count, shared_count, i;
1157         size_t size = 0;
1158
1159         ret = mutex_lock_interruptible(&db_list.lock);
1160
1161         if (ret)
1162                 return ret;
1163
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");
1167
1168         list_for_each_entry(buf_obj, &db_list.head, list_node) {
1169                 ret = mutex_lock_interruptible(&buf_obj->lock);
1170
1171                 if (ret) {
1172                         seq_puts(s,
1173                                  "\tERROR locking buffer object: skipping\n");
1174                         continue;
1175                 }
1176
1177                 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1178                                 buf_obj->size,
1179                                 buf_obj->file->f_flags, buf_obj->file->f_mode,
1180                                 file_count(buf_obj->file),
1181                                 buf_obj->exp_name,
1182                                 file_inode(buf_obj->file)->i_ino,
1183                                 buf_obj->name ?: "");
1184
1185                 robj = buf_obj->resv;
1186                 while (true) {
1187                         seq = read_seqcount_begin(&robj->seq);
1188                         rcu_read_lock();
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))
1193                                 break;
1194                         rcu_read_unlock();
1195                 }
1196
1197                 if (fence)
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))
1205                                 continue;
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);
1211                 }
1212                 rcu_read_unlock();
1213
1214                 seq_puts(s, "\tAttached Devices:\n");
1215                 attach_count = 0;
1216
1217                 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1218                         seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1219                         attach_count++;
1220                 }
1221
1222                 seq_printf(s, "Total %d devices attached\n\n",
1223                                 attach_count);
1224
1225                 count++;
1226                 size += buf_obj->size;
1227                 mutex_unlock(&buf_obj->lock);
1228         }
1229
1230         seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1231
1232         mutex_unlock(&db_list.lock);
1233         return 0;
1234 }
1235
1236 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1237
1238 static struct dentry *dma_buf_debugfs_dir;
1239
1240 static int dma_buf_init_debugfs(void)
1241 {
1242         struct dentry *d;
1243         int err = 0;
1244
1245         d = debugfs_create_dir("dma_buf", NULL);
1246         if (IS_ERR(d))
1247                 return PTR_ERR(d);
1248
1249         dma_buf_debugfs_dir = d;
1250
1251         d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1252                                 NULL, &dma_buf_debug_fops);
1253         if (IS_ERR(d)) {
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;
1257                 err = PTR_ERR(d);
1258         }
1259
1260         return err;
1261 }
1262
1263 static void dma_buf_uninit_debugfs(void)
1264 {
1265         debugfs_remove_recursive(dma_buf_debugfs_dir);
1266 }
1267 #else
1268 static inline int dma_buf_init_debugfs(void)
1269 {
1270         return 0;
1271 }
1272 static inline void dma_buf_uninit_debugfs(void)
1273 {
1274 }
1275 #endif
1276
1277 static int __init dma_buf_init(void)
1278 {
1279         dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1280         if (IS_ERR(dma_buf_mnt))
1281                 return PTR_ERR(dma_buf_mnt);
1282
1283         mutex_init(&db_list.lock);
1284         INIT_LIST_HEAD(&db_list.head);
1285         dma_buf_init_debugfs();
1286         return 0;
1287 }
1288 subsys_initcall(dma_buf_init);
1289
1290 static void __exit dma_buf_deinit(void)
1291 {
1292         dma_buf_uninit_debugfs();
1293         kern_unmount(dma_buf_mnt);
1294 }
1295 __exitcall(dma_buf_deinit);