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/dma-resv.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 #include <trace/hooks/dmabuf.h>
33
34 #include "dma-buf-sysfs-stats.h"
35
36 struct dma_buf_list {
37 struct list_head head;
38 struct mutex lock;
39 };
40
41 static struct dma_buf_list db_list;
42
43 /*
44 * This function helps in traversing the db_list and calls the
45 * callback function which can extract required info out of each
46 * dmabuf.
47 */
get_each_dmabuf(int (* callback)(const struct dma_buf * dmabuf,void * private),void * private)48 int get_each_dmabuf(int (*callback)(const struct dma_buf *dmabuf,
49 void *private), void *private)
50 {
51 struct dma_buf *buf;
52 int ret = mutex_lock_interruptible(&db_list.lock);
53
54 if (ret)
55 return ret;
56
57 list_for_each_entry(buf, &db_list.head, list_node) {
58 ret = callback(buf, private);
59 if (ret)
60 break;
61 }
62 mutex_unlock(&db_list.lock);
63 return ret;
64 }
65 EXPORT_SYMBOL_NS_GPL(get_each_dmabuf, MINIDUMP);
66
dmabuffs_dname(struct dentry * dentry,char * buffer,int buflen)67 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
68 {
69 struct dma_buf *dmabuf;
70 char name[DMA_BUF_NAME_LEN];
71 size_t ret = 0;
72
73 dmabuf = dentry->d_fsdata;
74 spin_lock(&dmabuf->name_lock);
75 if (dmabuf->name)
76 ret = strlcpy(name, dmabuf->name, DMA_BUF_NAME_LEN);
77 spin_unlock(&dmabuf->name_lock);
78
79 return dynamic_dname(dentry, buffer, buflen, "/%s:%s",
80 dentry->d_name.name, ret > 0 ? name : "");
81 }
82
dma_buf_release(struct dentry * dentry)83 static void dma_buf_release(struct dentry *dentry)
84 {
85 struct dma_buf *dmabuf;
86
87 dmabuf = dentry->d_fsdata;
88 if (unlikely(!dmabuf))
89 return;
90
91 BUG_ON(dmabuf->vmapping_counter);
92
93 /*
94 * If you hit this BUG() it could mean:
95 * * There's a file reference imbalance in dma_buf_poll / dma_buf_poll_cb or somewhere else
96 * * dmabuf->cb_in/out.active are non-0 despite no pending fence callback
97 */
98 BUG_ON(dmabuf->cb_in.active || dmabuf->cb_out.active);
99
100 dma_buf_stats_teardown(dmabuf);
101 dmabuf->ops->release(dmabuf);
102
103 trace_android_vh_dma_buf_release(dmabuf);
104 if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
105 dma_resv_fini(dmabuf->resv);
106
107 WARN_ON(!list_empty(&dmabuf->attachments));
108 module_put(dmabuf->owner);
109 kfree(dmabuf->name);
110 kfree(dmabuf);
111 }
112
dma_buf_file_release(struct inode * inode,struct file * file)113 static int dma_buf_file_release(struct inode *inode, struct file *file)
114 {
115 struct dma_buf *dmabuf;
116
117 if (!is_dma_buf_file(file))
118 return -EINVAL;
119
120 dmabuf = file->private_data;
121
122 mutex_lock(&db_list.lock);
123 list_del(&dmabuf->list_node);
124 mutex_unlock(&db_list.lock);
125
126 return 0;
127 }
128
129 static const struct dentry_operations dma_buf_dentry_ops = {
130 .d_dname = dmabuffs_dname,
131 .d_release = dma_buf_release,
132 };
133
134 static struct vfsmount *dma_buf_mnt;
135
dma_buf_fs_init_context(struct fs_context * fc)136 static int dma_buf_fs_init_context(struct fs_context *fc)
137 {
138 struct pseudo_fs_context *ctx;
139
140 ctx = init_pseudo(fc, DMA_BUF_MAGIC);
141 if (!ctx)
142 return -ENOMEM;
143 ctx->dops = &dma_buf_dentry_ops;
144 return 0;
145 }
146
147 static struct file_system_type dma_buf_fs_type = {
148 .name = "dmabuf",
149 .init_fs_context = dma_buf_fs_init_context,
150 .kill_sb = kill_anon_super,
151 };
152
dma_buf_mmap_internal(struct file * file,struct vm_area_struct * vma)153 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
154 {
155 struct dma_buf *dmabuf;
156
157 if (!is_dma_buf_file(file))
158 return -EINVAL;
159
160 dmabuf = file->private_data;
161
162 /* check if buffer supports mmap */
163 if (!dmabuf->ops->mmap)
164 return -EINVAL;
165
166 /* check for overflowing the buffer's size */
167 if (vma->vm_pgoff + vma_pages(vma) >
168 dmabuf->size >> PAGE_SHIFT)
169 return -EINVAL;
170
171 return dmabuf->ops->mmap(dmabuf, vma);
172 }
173
dma_buf_llseek(struct file * file,loff_t offset,int whence)174 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
175 {
176 struct dma_buf *dmabuf;
177 loff_t base;
178
179 if (!is_dma_buf_file(file))
180 return -EBADF;
181
182 dmabuf = file->private_data;
183
184 /* only support discovering the end of the buffer,
185 but also allow SEEK_SET to maintain the idiomatic
186 SEEK_END(0), SEEK_CUR(0) pattern */
187 if (whence == SEEK_END)
188 base = dmabuf->size;
189 else if (whence == SEEK_SET)
190 base = 0;
191 else
192 return -EINVAL;
193
194 if (offset != 0)
195 return -EINVAL;
196
197 return base + offset;
198 }
199
200 /**
201 * DOC: implicit fence polling
202 *
203 * To support cross-device and cross-driver synchronization of buffer access
204 * implicit fences (represented internally in the kernel with &struct dma_fence)
205 * can be attached to a &dma_buf. The glue for that and a few related things are
206 * provided in the &dma_resv structure.
207 *
208 * Userspace can query the state of these implicitly tracked fences using poll()
209 * and related system calls:
210 *
211 * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
212 * most recent write or exclusive fence.
213 *
214 * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
215 * all attached fences, shared and exclusive ones.
216 *
217 * Note that this only signals the completion of the respective fences, i.e. the
218 * DMA transfers are complete. Cache flushing and any other necessary
219 * preparations before CPU access can begin still need to happen.
220 */
221
dma_buf_poll_cb(struct dma_fence * fence,struct dma_fence_cb * cb)222 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
223 {
224 struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
225 struct dma_buf *dmabuf = container_of(dcb->poll, struct dma_buf, poll);
226 unsigned long flags;
227
228 spin_lock_irqsave(&dcb->poll->lock, flags);
229 wake_up_locked_poll(dcb->poll, dcb->active);
230 dcb->active = 0;
231 spin_unlock_irqrestore(&dcb->poll->lock, flags);
232 dma_fence_put(fence);
233 /* Paired with get_file in dma_buf_poll */
234 fput(dmabuf->file);
235 }
236
dma_buf_poll_shared(struct dma_resv * resv,struct dma_buf_poll_cb_t * dcb)237 static bool dma_buf_poll_shared(struct dma_resv *resv,
238 struct dma_buf_poll_cb_t *dcb)
239 {
240 struct dma_resv_list *fobj = dma_resv_shared_list(resv);
241 struct dma_fence *fence;
242 int i, r;
243
244 if (!fobj)
245 return false;
246
247 for (i = 0; i < fobj->shared_count; ++i) {
248 fence = rcu_dereference_protected(fobj->shared[i],
249 dma_resv_held(resv));
250 dma_fence_get(fence);
251 r = dma_fence_add_callback(fence, &dcb->cb, dma_buf_poll_cb);
252 if (!r)
253 return true;
254 dma_fence_put(fence);
255 }
256
257 return false;
258 }
259
dma_buf_poll_excl(struct dma_resv * resv,struct dma_buf_poll_cb_t * dcb)260 static bool dma_buf_poll_excl(struct dma_resv *resv,
261 struct dma_buf_poll_cb_t *dcb)
262 {
263 struct dma_fence *fence = dma_resv_excl_fence(resv);
264 int r;
265
266 if (!fence)
267 return false;
268
269 dma_fence_get(fence);
270 r = dma_fence_add_callback(fence, &dcb->cb, dma_buf_poll_cb);
271 if (!r)
272 return true;
273 dma_fence_put(fence);
274
275 return false;
276 }
277
dma_buf_poll(struct file * file,poll_table * poll)278 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
279 {
280 struct dma_buf *dmabuf;
281 struct dma_resv *resv;
282 __poll_t events;
283
284 dmabuf = file->private_data;
285 if (!dmabuf || !dmabuf->resv)
286 return EPOLLERR;
287
288 resv = dmabuf->resv;
289
290 poll_wait(file, &dmabuf->poll, poll);
291
292 events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
293 if (!events)
294 return 0;
295
296 dma_resv_lock(resv, NULL);
297
298 if (events & EPOLLOUT) {
299 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_out;
300
301 /* Check that callback isn't busy */
302 spin_lock_irq(&dmabuf->poll.lock);
303 if (dcb->active)
304 events &= ~EPOLLOUT;
305 else
306 dcb->active = EPOLLOUT;
307 spin_unlock_irq(&dmabuf->poll.lock);
308
309 if (events & EPOLLOUT) {
310 /* Paired with fput in dma_buf_poll_cb */
311 get_file(dmabuf->file);
312
313 if (!dma_buf_poll_shared(resv, dcb) &&
314 !dma_buf_poll_excl(resv, dcb))
315
316 /* No callback queued, wake up any other waiters */
317 dma_buf_poll_cb(NULL, &dcb->cb);
318 else
319 events &= ~EPOLLOUT;
320 }
321 }
322
323 if (events & EPOLLIN) {
324 struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_in;
325
326 /* Check that callback isn't busy */
327 spin_lock_irq(&dmabuf->poll.lock);
328 if (dcb->active)
329 events &= ~EPOLLIN;
330 else
331 dcb->active = EPOLLIN;
332 spin_unlock_irq(&dmabuf->poll.lock);
333
334 if (events & EPOLLIN) {
335 /* Paired with fput in dma_buf_poll_cb */
336 get_file(dmabuf->file);
337
338 if (!dma_buf_poll_excl(resv, dcb))
339 /* No callback queued, wake up any other waiters */
340 dma_buf_poll_cb(NULL, &dcb->cb);
341 else
342 events &= ~EPOLLIN;
343 }
344 }
345
346 dma_resv_unlock(resv);
347 return events;
348 }
349
_dma_buf_set_name(struct dma_buf * dmabuf,const char * name)350 static long _dma_buf_set_name(struct dma_buf *dmabuf, const char *name)
351 {
352 spin_lock(&dmabuf->name_lock);
353 kfree(dmabuf->name);
354 dmabuf->name = name;
355 spin_unlock(&dmabuf->name_lock);
356
357 return 0;
358 }
359
360 /**
361 * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
362 * It could support changing the name of the dma-buf if the same piece of
363 * memory is used for multiple purpose between different devices.
364 *
365 * @dmabuf: [in] dmabuf buffer that will be renamed.
366 * @buf: [in] A piece of userspace memory that contains the name of
367 * the dma-buf.
368 *
369 * Returns 0 on success. If the dma-buf buffer is already attached to
370 * devices, return -EBUSY.
371 *
372 */
dma_buf_set_name(struct dma_buf * dmabuf,const char * name)373 long dma_buf_set_name(struct dma_buf *dmabuf, const char *name)
374 {
375 long ret = 0;
376 char *buf = kstrndup(name, DMA_BUF_NAME_LEN, GFP_KERNEL);
377
378 if (!buf)
379 return -ENOMEM;
380
381 ret = _dma_buf_set_name(dmabuf, buf);
382 if (ret)
383 kfree(buf);
384
385 return ret;
386 }
387 EXPORT_SYMBOL_GPL(dma_buf_set_name);
388
dma_buf_set_name_user(struct dma_buf * dmabuf,const char __user * buf)389 static long dma_buf_set_name_user(struct dma_buf *dmabuf, const char __user *buf)
390 {
391 char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
392 long ret = 0;
393
394 if (IS_ERR(name))
395 return PTR_ERR(name);
396
397 ret = _dma_buf_set_name(dmabuf, name);
398 if (ret)
399 kfree(name);
400
401 return ret;
402 }
403
dma_buf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)404 static long dma_buf_ioctl(struct file *file,
405 unsigned int cmd, unsigned long arg)
406 {
407 struct dma_buf *dmabuf;
408 struct dma_buf_sync sync;
409 enum dma_data_direction direction;
410 int ret;
411
412 dmabuf = file->private_data;
413
414 switch (cmd) {
415 case DMA_BUF_IOCTL_SYNC:
416 if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
417 return -EFAULT;
418
419 if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
420 return -EINVAL;
421
422 switch (sync.flags & DMA_BUF_SYNC_RW) {
423 case DMA_BUF_SYNC_READ:
424 direction = DMA_FROM_DEVICE;
425 break;
426 case DMA_BUF_SYNC_WRITE:
427 direction = DMA_TO_DEVICE;
428 break;
429 case DMA_BUF_SYNC_RW:
430 direction = DMA_BIDIRECTIONAL;
431 break;
432 default:
433 return -EINVAL;
434 }
435
436 if (sync.flags & DMA_BUF_SYNC_END)
437 ret = dma_buf_end_cpu_access(dmabuf, direction);
438 else
439 ret = dma_buf_begin_cpu_access(dmabuf, direction);
440
441 return ret;
442
443 case DMA_BUF_SET_NAME_A:
444 case DMA_BUF_SET_NAME_B:
445 return dma_buf_set_name_user(dmabuf, (const char __user *)arg);
446
447 default:
448 return -ENOTTY;
449 }
450 }
451
dma_buf_show_fdinfo(struct seq_file * m,struct file * file)452 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
453 {
454 struct dma_buf *dmabuf = file->private_data;
455
456 seq_printf(m, "size:\t%zu\n", dmabuf->size);
457 /* Don't count the temporary reference taken inside procfs seq_show */
458 seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
459 seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
460 spin_lock(&dmabuf->name_lock);
461 if (dmabuf->name)
462 seq_printf(m, "name:\t%s\n", dmabuf->name);
463 spin_unlock(&dmabuf->name_lock);
464 }
465
466 static const struct file_operations dma_buf_fops = {
467 .release = dma_buf_file_release,
468 .mmap = dma_buf_mmap_internal,
469 .llseek = dma_buf_llseek,
470 .poll = dma_buf_poll,
471 .unlocked_ioctl = dma_buf_ioctl,
472 .compat_ioctl = compat_ptr_ioctl,
473 .show_fdinfo = dma_buf_show_fdinfo,
474 };
475
476 /*
477 * is_dma_buf_file - Check if struct file* is associated with dma_buf
478 */
is_dma_buf_file(struct file * file)479 int is_dma_buf_file(struct file *file)
480 {
481 return file->f_op == &dma_buf_fops;
482 }
483 EXPORT_SYMBOL_NS_GPL(is_dma_buf_file, MINIDUMP);
484
dma_buf_getfile(struct dma_buf * dmabuf,int flags)485 static struct file *dma_buf_getfile(struct dma_buf *dmabuf, int flags)
486 {
487 static atomic64_t dmabuf_inode = ATOMIC64_INIT(0);
488 struct file *file;
489 struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
490
491 if (IS_ERR(inode))
492 return ERR_CAST(inode);
493
494 inode->i_size = dmabuf->size;
495 inode_set_bytes(inode, dmabuf->size);
496
497 /*
498 * The ->i_ino acquired from get_next_ino() is not unique thus
499 * not suitable for using it as dentry name by dmabuf stats.
500 * Override ->i_ino with the unique and dmabuffs specific
501 * value.
502 */
503 inode->i_ino = atomic64_add_return(1, &dmabuf_inode);
504 file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
505 flags, &dma_buf_fops);
506 if (IS_ERR(file))
507 goto err_alloc_file;
508 file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
509 file->private_data = dmabuf;
510 file->f_path.dentry->d_fsdata = dmabuf;
511
512 return file;
513
514 err_alloc_file:
515 iput(inode);
516 return file;
517 }
518
519 /**
520 * DOC: dma buf device access
521 *
522 * For device DMA access to a shared DMA buffer the usual sequence of operations
523 * is fairly simple:
524 *
525 * 1. The exporter defines his exporter instance using
526 * DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
527 * buffer object into a &dma_buf. It then exports that &dma_buf to userspace
528 * as a file descriptor by calling dma_buf_fd().
529 *
530 * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
531 * to share with: First the filedescriptor is converted to a &dma_buf using
532 * dma_buf_get(). Then the buffer is attached to the device using
533 * dma_buf_attach().
534 *
535 * Up to this stage the exporter is still free to migrate or reallocate the
536 * backing storage.
537 *
538 * 3. Once the buffer is attached to all devices userspace can initiate DMA
539 * access to the shared buffer. In the kernel this is done by calling
540 * dma_buf_map_attachment() and dma_buf_unmap_attachment().
541 *
542 * 4. Once a driver is done with a shared buffer it needs to call
543 * dma_buf_detach() (after cleaning up any mappings) and then release the
544 * reference acquired with dma_buf_get() by calling dma_buf_put().
545 *
546 * For the detailed semantics exporters are expected to implement see
547 * &dma_buf_ops.
548 */
549
550 /**
551 * dma_buf_export - Creates a new dma_buf, and associates an anon file
552 * with this buffer, so it can be exported.
553 * Also connect the allocator specific data and ops to the buffer.
554 * Additionally, provide a name string for exporter; useful in debugging.
555 *
556 * @exp_info: [in] holds all the export related information provided
557 * by the exporter. see &struct dma_buf_export_info
558 * for further details.
559 *
560 * Returns, on success, a newly created struct dma_buf object, which wraps the
561 * supplied private data and operations for struct dma_buf_ops. On either
562 * missing ops, or error in allocating struct dma_buf, will return negative
563 * error.
564 *
565 * For most cases the easiest way to create @exp_info is through the
566 * %DEFINE_DMA_BUF_EXPORT_INFO macro.
567 */
dma_buf_export(const struct dma_buf_export_info * exp_info)568 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
569 {
570 struct dma_buf *dmabuf;
571 struct dma_resv *resv = exp_info->resv;
572 struct file *file;
573 size_t alloc_size = sizeof(struct dma_buf);
574 int ret;
575
576 if (!exp_info->resv)
577 alloc_size += sizeof(struct dma_resv);
578 else
579 /* prevent &dma_buf[1] == dma_buf->resv */
580 alloc_size += 1;
581
582 if (WARN_ON(!exp_info->priv
583 || !exp_info->ops
584 || !exp_info->ops->map_dma_buf
585 || !exp_info->ops->unmap_dma_buf
586 || !exp_info->ops->release)) {
587 return ERR_PTR(-EINVAL);
588 }
589
590 if (WARN_ON(exp_info->ops->cache_sgt_mapping &&
591 (exp_info->ops->pin || exp_info->ops->unpin)))
592 return ERR_PTR(-EINVAL);
593
594 if (WARN_ON(!exp_info->ops->pin != !exp_info->ops->unpin))
595 return ERR_PTR(-EINVAL);
596
597 if (!try_module_get(exp_info->owner))
598 return ERR_PTR(-ENOENT);
599
600 dmabuf = kzalloc(alloc_size, GFP_KERNEL);
601 if (!dmabuf) {
602 ret = -ENOMEM;
603 goto err_module;
604 }
605
606 dmabuf->priv = exp_info->priv;
607 dmabuf->ops = exp_info->ops;
608 dmabuf->size = exp_info->size;
609 dmabuf->exp_name = exp_info->exp_name;
610 dmabuf->owner = exp_info->owner;
611 spin_lock_init(&dmabuf->name_lock);
612 init_waitqueue_head(&dmabuf->poll);
613 dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
614 dmabuf->cb_in.active = dmabuf->cb_out.active = 0;
615
616 if (!resv) {
617 resv = (struct dma_resv *)&dmabuf[1];
618 dma_resv_init(resv);
619 }
620 dmabuf->resv = resv;
621
622 file = dma_buf_getfile(dmabuf, exp_info->flags);
623 if (IS_ERR(file)) {
624 ret = PTR_ERR(file);
625 goto err_dmabuf;
626 }
627
628 file->f_mode |= FMODE_LSEEK;
629 dmabuf->file = file;
630
631 mutex_init(&dmabuf->lock);
632 INIT_LIST_HEAD(&dmabuf->attachments);
633
634 mutex_lock(&db_list.lock);
635 list_add(&dmabuf->list_node, &db_list.head);
636 mutex_unlock(&db_list.lock);
637
638 ret = dma_buf_stats_setup(dmabuf);
639 if (ret)
640 goto err_sysfs;
641
642 return dmabuf;
643
644 err_sysfs:
645 /*
646 * Set file->f_path.dentry->d_fsdata to NULL so that when
647 * dma_buf_release() gets invoked by dentry_ops, it exits
648 * early before calling the release() dma_buf op.
649 */
650 file->f_path.dentry->d_fsdata = NULL;
651 fput(file);
652 err_dmabuf:
653 kfree(dmabuf);
654 err_module:
655 module_put(exp_info->owner);
656 return ERR_PTR(ret);
657 }
658 EXPORT_SYMBOL_GPL(dma_buf_export);
659
660 /**
661 * dma_buf_fd - returns a file descriptor for the given struct dma_buf
662 * @dmabuf: [in] pointer to dma_buf for which fd is required.
663 * @flags: [in] flags to give to fd
664 *
665 * On success, returns an associated 'fd'. Else, returns error.
666 */
dma_buf_fd(struct dma_buf * dmabuf,int flags)667 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
668 {
669 int fd;
670
671 if (!dmabuf || !dmabuf->file)
672 return -EINVAL;
673
674 fd = get_unused_fd_flags(flags);
675 if (fd < 0)
676 return fd;
677
678 fd_install(fd, dmabuf->file);
679
680 return fd;
681 }
682 EXPORT_SYMBOL_GPL(dma_buf_fd);
683
684 /**
685 * dma_buf_get - returns the struct dma_buf related to an fd
686 * @fd: [in] fd associated with the struct dma_buf to be returned
687 *
688 * On success, returns the struct dma_buf associated with an fd; uses
689 * file's refcounting done by fget to increase refcount. returns ERR_PTR
690 * otherwise.
691 */
dma_buf_get(int fd)692 struct dma_buf *dma_buf_get(int fd)
693 {
694 struct file *file;
695
696 file = fget(fd);
697
698 if (!file)
699 return ERR_PTR(-EBADF);
700
701 if (!is_dma_buf_file(file)) {
702 fput(file);
703 return ERR_PTR(-EINVAL);
704 }
705
706 return file->private_data;
707 }
708 EXPORT_SYMBOL_GPL(dma_buf_get);
709
710 /**
711 * dma_buf_put - decreases refcount of the buffer
712 * @dmabuf: [in] buffer to reduce refcount of
713 *
714 * Uses file's refcounting done implicitly by fput().
715 *
716 * If, as a result of this call, the refcount becomes 0, the 'release' file
717 * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
718 * in turn, and frees the memory allocated for dmabuf when exported.
719 */
dma_buf_put(struct dma_buf * dmabuf)720 void dma_buf_put(struct dma_buf *dmabuf)
721 {
722 if (WARN_ON(!dmabuf || !dmabuf->file))
723 return;
724
725 fput(dmabuf->file);
726 }
727 EXPORT_SYMBOL_GPL(dma_buf_put);
728
mangle_sg_table(struct sg_table * sg_table)729 static void mangle_sg_table(struct sg_table *sg_table)
730 {
731 #ifdef CONFIG_DMABUF_DEBUG
732 int i;
733 struct scatterlist *sg;
734
735 /* To catch abuse of the underlying struct page by importers mix
736 * up the bits, but take care to preserve the low SG_ bits to
737 * not corrupt the sgt. The mixing is undone in __unmap_dma_buf
738 * before passing the sgt back to the exporter. */
739 for_each_sgtable_sg(sg_table, sg, i)
740 sg->page_link ^= ~0xffUL;
741 #endif
742
743 }
__map_dma_buf(struct dma_buf_attachment * attach,enum dma_data_direction direction)744 static struct sg_table * __map_dma_buf(struct dma_buf_attachment *attach,
745 enum dma_data_direction direction)
746 {
747 struct sg_table *sg_table;
748
749 sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
750
751 if (!IS_ERR_OR_NULL(sg_table))
752 mangle_sg_table(sg_table);
753
754 return sg_table;
755 }
756
757 /**
758 * dma_buf_dynamic_attach - Add the device to dma_buf's attachments list
759 * @dmabuf: [in] buffer to attach device to.
760 * @dev: [in] device to be attached.
761 * @importer_ops: [in] importer operations for the attachment
762 * @importer_priv: [in] importer private pointer for the attachment
763 *
764 * Returns struct dma_buf_attachment pointer for this attachment. Attachments
765 * must be cleaned up by calling dma_buf_detach().
766 *
767 * Optionally this calls &dma_buf_ops.attach to allow device-specific attach
768 * functionality.
769 *
770 * Returns:
771 *
772 * A pointer to newly created &dma_buf_attachment on success, or a negative
773 * error code wrapped into a pointer on failure.
774 *
775 * Note that this can fail if the backing storage of @dmabuf is in a place not
776 * accessible to @dev, and cannot be moved to a more suitable place. This is
777 * indicated with the error code -EBUSY.
778 */
779 struct dma_buf_attachment *
dma_buf_dynamic_attach(struct dma_buf * dmabuf,struct device * dev,const struct dma_buf_attach_ops * importer_ops,void * importer_priv)780 dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
781 const struct dma_buf_attach_ops *importer_ops,
782 void *importer_priv)
783 {
784 struct dma_buf_attachment *attach;
785 int ret;
786
787 if (WARN_ON(!dmabuf || !dev))
788 return ERR_PTR(-EINVAL);
789
790 if (WARN_ON(importer_ops && !importer_ops->move_notify))
791 return ERR_PTR(-EINVAL);
792
793 attach = kzalloc(sizeof(*attach), GFP_KERNEL);
794 if (!attach)
795 return ERR_PTR(-ENOMEM);
796
797 attach->dev = dev;
798 attach->dmabuf = dmabuf;
799 if (importer_ops)
800 attach->peer2peer = importer_ops->allow_peer2peer;
801 attach->importer_ops = importer_ops;
802 attach->importer_priv = importer_priv;
803
804 if (dmabuf->ops->attach) {
805 ret = dmabuf->ops->attach(dmabuf, attach);
806 if (ret)
807 goto err_attach;
808 }
809 dma_resv_lock(dmabuf->resv, NULL);
810 list_add(&attach->node, &dmabuf->attachments);
811 dma_resv_unlock(dmabuf->resv);
812
813 /* When either the importer or the exporter can't handle dynamic
814 * mappings we cache the mapping here to avoid issues with the
815 * reservation object lock.
816 */
817 if (dma_buf_attachment_is_dynamic(attach) !=
818 dma_buf_is_dynamic(dmabuf)) {
819 struct sg_table *sgt;
820
821 if (dma_buf_is_dynamic(attach->dmabuf)) {
822 dma_resv_lock(attach->dmabuf->resv, NULL);
823 ret = dmabuf->ops->pin(attach);
824 if (ret)
825 goto err_unlock;
826 }
827
828 sgt = __map_dma_buf(attach, DMA_BIDIRECTIONAL);
829 if (!sgt)
830 sgt = ERR_PTR(-ENOMEM);
831 if (IS_ERR(sgt)) {
832 ret = PTR_ERR(sgt);
833 goto err_unpin;
834 }
835 if (dma_buf_is_dynamic(attach->dmabuf))
836 dma_resv_unlock(attach->dmabuf->resv);
837 attach->sgt = sgt;
838 attach->dir = DMA_BIDIRECTIONAL;
839 }
840
841 return attach;
842
843 err_attach:
844 kfree(attach);
845 return ERR_PTR(ret);
846
847 err_unpin:
848 if (dma_buf_is_dynamic(attach->dmabuf))
849 dmabuf->ops->unpin(attach);
850
851 err_unlock:
852 if (dma_buf_is_dynamic(attach->dmabuf))
853 dma_resv_unlock(attach->dmabuf->resv);
854
855 dma_buf_detach(dmabuf, attach);
856 return ERR_PTR(ret);
857 }
858 EXPORT_SYMBOL_GPL(dma_buf_dynamic_attach);
859
860 /**
861 * dma_buf_attach - Wrapper for dma_buf_dynamic_attach
862 * @dmabuf: [in] buffer to attach device to.
863 * @dev: [in] device to be attached.
864 *
865 * Wrapper to call dma_buf_dynamic_attach() for drivers which still use a static
866 * mapping.
867 */
dma_buf_attach(struct dma_buf * dmabuf,struct device * dev)868 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
869 struct device *dev)
870 {
871 return dma_buf_dynamic_attach(dmabuf, dev, NULL, NULL);
872 }
873 EXPORT_SYMBOL_GPL(dma_buf_attach);
874
__unmap_dma_buf(struct dma_buf_attachment * attach,struct sg_table * sg_table,enum dma_data_direction direction)875 static void __unmap_dma_buf(struct dma_buf_attachment *attach,
876 struct sg_table *sg_table,
877 enum dma_data_direction direction)
878 {
879 /* uses XOR, hence this unmangles */
880 mangle_sg_table(sg_table);
881
882 attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
883 }
884
885 /**
886 * dma_buf_detach - Remove the given attachment from dmabuf's attachments list
887 * @dmabuf: [in] buffer to detach from.
888 * @attach: [in] attachment to be detached; is free'd after this call.
889 *
890 * Clean up a device attachment obtained by calling dma_buf_attach().
891 *
892 * Optionally this calls &dma_buf_ops.detach for device-specific detach.
893 */
dma_buf_detach(struct dma_buf * dmabuf,struct dma_buf_attachment * attach)894 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
895 {
896 if (WARN_ON(!dmabuf || !attach))
897 return;
898
899 if (attach->sgt) {
900 if (dma_buf_is_dynamic(attach->dmabuf))
901 dma_resv_lock(attach->dmabuf->resv, NULL);
902
903 __unmap_dma_buf(attach, attach->sgt, attach->dir);
904
905 if (dma_buf_is_dynamic(attach->dmabuf)) {
906 dmabuf->ops->unpin(attach);
907 dma_resv_unlock(attach->dmabuf->resv);
908 }
909 }
910
911 dma_resv_lock(dmabuf->resv, NULL);
912 list_del(&attach->node);
913 dma_resv_unlock(dmabuf->resv);
914 if (dmabuf->ops->detach)
915 dmabuf->ops->detach(dmabuf, attach);
916
917 kfree(attach);
918 }
919 EXPORT_SYMBOL_GPL(dma_buf_detach);
920
921 /**
922 * dma_buf_pin - Lock down the DMA-buf
923 * @attach: [in] attachment which should be pinned
924 *
925 * Only dynamic importers (who set up @attach with dma_buf_dynamic_attach()) may
926 * call this, and only for limited use cases like scanout and not for temporary
927 * pin operations. It is not permitted to allow userspace to pin arbitrary
928 * amounts of buffers through this interface.
929 *
930 * Buffers must be unpinned by calling dma_buf_unpin().
931 *
932 * Returns:
933 * 0 on success, negative error code on failure.
934 */
dma_buf_pin(struct dma_buf_attachment * attach)935 int dma_buf_pin(struct dma_buf_attachment *attach)
936 {
937 struct dma_buf *dmabuf = attach->dmabuf;
938 int ret = 0;
939
940 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
941
942 dma_resv_assert_held(dmabuf->resv);
943
944 if (dmabuf->ops->pin)
945 ret = dmabuf->ops->pin(attach);
946
947 return ret;
948 }
949 EXPORT_SYMBOL_GPL(dma_buf_pin);
950
951 /**
952 * dma_buf_unpin - Unpin a DMA-buf
953 * @attach: [in] attachment which should be unpinned
954 *
955 * This unpins a buffer pinned by dma_buf_pin() and allows the exporter to move
956 * any mapping of @attach again and inform the importer through
957 * &dma_buf_attach_ops.move_notify.
958 */
dma_buf_unpin(struct dma_buf_attachment * attach)959 void dma_buf_unpin(struct dma_buf_attachment *attach)
960 {
961 struct dma_buf *dmabuf = attach->dmabuf;
962
963 WARN_ON(!dma_buf_attachment_is_dynamic(attach));
964
965 dma_resv_assert_held(dmabuf->resv);
966
967 if (dmabuf->ops->unpin)
968 dmabuf->ops->unpin(attach);
969 }
970 EXPORT_SYMBOL_GPL(dma_buf_unpin);
971
972 /**
973 * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
974 * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
975 * dma_buf_ops.
976 * @attach: [in] attachment whose scatterlist is to be returned
977 * @direction: [in] direction of DMA transfer
978 *
979 * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
980 * on error. May return -EINTR if it is interrupted by a signal.
981 *
982 * On success, the DMA addresses and lengths in the returned scatterlist are
983 * PAGE_SIZE aligned.
984 *
985 * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
986 * the underlying backing storage is pinned for as long as a mapping exists,
987 * therefore users/importers should not hold onto a mapping for undue amounts of
988 * time.
989 *
990 * Important: Dynamic importers must wait for the exclusive fence of the struct
991 * dma_resv attached to the DMA-BUF first.
992 */
dma_buf_map_attachment(struct dma_buf_attachment * attach,enum dma_data_direction direction)993 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
994 enum dma_data_direction direction)
995 {
996 struct sg_table *sg_table;
997 int r;
998
999 might_sleep();
1000
1001 if (WARN_ON(!attach || !attach->dmabuf))
1002 return ERR_PTR(-EINVAL);
1003
1004 if (dma_buf_attachment_is_dynamic(attach))
1005 dma_resv_assert_held(attach->dmabuf->resv);
1006
1007 if (attach->sgt) {
1008 /*
1009 * Two mappings with different directions for the same
1010 * attachment are not allowed.
1011 */
1012 if (attach->dir != direction &&
1013 attach->dir != DMA_BIDIRECTIONAL)
1014 return ERR_PTR(-EBUSY);
1015
1016 return attach->sgt;
1017 }
1018
1019 if (dma_buf_is_dynamic(attach->dmabuf)) {
1020 dma_resv_assert_held(attach->dmabuf->resv);
1021 if (!IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY)) {
1022 r = attach->dmabuf->ops->pin(attach);
1023 if (r)
1024 return ERR_PTR(r);
1025 }
1026 }
1027
1028 sg_table = __map_dma_buf(attach, direction);
1029 if (!sg_table)
1030 sg_table = ERR_PTR(-ENOMEM);
1031
1032 if (IS_ERR(sg_table) && dma_buf_is_dynamic(attach->dmabuf) &&
1033 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
1034 attach->dmabuf->ops->unpin(attach);
1035
1036 if (!IS_ERR(sg_table) && attach->dmabuf->ops->cache_sgt_mapping) {
1037 attach->sgt = sg_table;
1038 attach->dir = direction;
1039 }
1040
1041 #ifdef CONFIG_DMA_API_DEBUG
1042 if (!IS_ERR(sg_table)) {
1043 struct scatterlist *sg;
1044 u64 addr;
1045 int len;
1046 int i;
1047
1048 for_each_sgtable_dma_sg(sg_table, sg, i) {
1049 addr = sg_dma_address(sg);
1050 len = sg_dma_len(sg);
1051 if (!PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len)) {
1052 pr_debug("%s: addr %llx or len %x is not page aligned!\n",
1053 __func__, addr, len);
1054 }
1055 }
1056 }
1057 #endif /* CONFIG_DMA_API_DEBUG */
1058 return sg_table;
1059 }
1060 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
1061
1062 /**
1063 * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
1064 * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
1065 * dma_buf_ops.
1066 * @attach: [in] attachment to unmap buffer from
1067 * @sg_table: [in] scatterlist info of the buffer to unmap
1068 * @direction: [in] direction of DMA transfer
1069 *
1070 * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
1071 */
dma_buf_unmap_attachment(struct dma_buf_attachment * attach,struct sg_table * sg_table,enum dma_data_direction direction)1072 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
1073 struct sg_table *sg_table,
1074 enum dma_data_direction direction)
1075 {
1076 might_sleep();
1077
1078 if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
1079 return;
1080
1081 if (dma_buf_attachment_is_dynamic(attach))
1082 dma_resv_assert_held(attach->dmabuf->resv);
1083
1084 if (attach->sgt == sg_table)
1085 return;
1086
1087 if (dma_buf_is_dynamic(attach->dmabuf))
1088 dma_resv_assert_held(attach->dmabuf->resv);
1089
1090 __unmap_dma_buf(attach, sg_table, direction);
1091
1092 if (dma_buf_is_dynamic(attach->dmabuf) &&
1093 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY))
1094 dma_buf_unpin(attach);
1095 }
1096 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
1097
1098 /**
1099 * dma_buf_move_notify - notify attachments that DMA-buf is moving
1100 *
1101 * @dmabuf: [in] buffer which is moving
1102 *
1103 * Informs all attachmenst that they need to destroy and recreated all their
1104 * mappings.
1105 */
dma_buf_move_notify(struct dma_buf * dmabuf)1106 void dma_buf_move_notify(struct dma_buf *dmabuf)
1107 {
1108 struct dma_buf_attachment *attach;
1109
1110 dma_resv_assert_held(dmabuf->resv);
1111
1112 list_for_each_entry(attach, &dmabuf->attachments, node)
1113 if (attach->importer_ops)
1114 attach->importer_ops->move_notify(attach);
1115 }
1116 EXPORT_SYMBOL_GPL(dma_buf_move_notify);
1117
1118 /**
1119 * DOC: cpu access
1120 *
1121 * There are mutliple reasons for supporting CPU access to a dma buffer object:
1122 *
1123 * - Fallback operations in the kernel, for example when a device is connected
1124 * over USB and the kernel needs to shuffle the data around first before
1125 * sending it away. Cache coherency is handled by braketing any transactions
1126 * with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
1127 * access.
1128 *
1129 * Since for most kernel internal dma-buf accesses need the entire buffer, a
1130 * vmap interface is introduced. Note that on very old 32-bit architectures
1131 * vmalloc space might be limited and result in vmap calls failing.
1132 *
1133 * Interfaces::
1134 *
1135 * void \*dma_buf_vmap(struct dma_buf \*dmabuf)
1136 * void dma_buf_vunmap(struct dma_buf \*dmabuf, void \*vaddr)
1137 *
1138 * The vmap call can fail if there is no vmap support in the exporter, or if
1139 * it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
1140 * count for all vmap access and calls down into the exporter's vmap function
1141 * only when no vmapping exists, and only unmaps it once. Protection against
1142 * concurrent vmap/vunmap calls is provided by taking the &dma_buf.lock mutex.
1143 *
1144 * - For full compatibility on the importer side with existing userspace
1145 * interfaces, which might already support mmap'ing buffers. This is needed in
1146 * many processing pipelines (e.g. feeding a software rendered image into a
1147 * hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
1148 * framework already supported this and for DMA buffer file descriptors to
1149 * replace ION buffers mmap support was needed.
1150 *
1151 * There is no special interfaces, userspace simply calls mmap on the dma-buf
1152 * fd. But like for CPU access there's a need to braket the actual access,
1153 * which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
1154 * DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
1155 * be restarted.
1156 *
1157 * Some systems might need some sort of cache coherency management e.g. when
1158 * CPU and GPU domains are being accessed through dma-buf at the same time.
1159 * To circumvent this problem there are begin/end coherency markers, that
1160 * forward directly to existing dma-buf device drivers vfunc hooks. Userspace
1161 * can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
1162 * sequence would be used like following:
1163 *
1164 * - mmap dma-buf fd
1165 * - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
1166 * to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
1167 * want (with the new data being consumed by say the GPU or the scanout
1168 * device)
1169 * - munmap once you don't need the buffer any more
1170 *
1171 * For correctness and optimal performance, it is always required to use
1172 * SYNC_START and SYNC_END before and after, respectively, when accessing the
1173 * mapped address. Userspace cannot rely on coherent access, even when there
1174 * are systems where it just works without calling these ioctls.
1175 *
1176 * - And as a CPU fallback in userspace processing pipelines.
1177 *
1178 * Similar to the motivation for kernel cpu access it is again important that
1179 * the userspace code of a given importing subsystem can use the same
1180 * interfaces with a imported dma-buf buffer object as with a native buffer
1181 * object. This is especially important for drm where the userspace part of
1182 * contemporary OpenGL, X, and other drivers is huge, and reworking them to
1183 * use a different way to mmap a buffer rather invasive.
1184 *
1185 * The assumption in the current dma-buf interfaces is that redirecting the
1186 * initial mmap is all that's needed. A survey of some of the existing
1187 * subsystems shows that no driver seems to do any nefarious thing like
1188 * syncing up with outstanding asynchronous processing on the device or
1189 * allocating special resources at fault time. So hopefully this is good
1190 * enough, since adding interfaces to intercept pagefaults and allow pte
1191 * shootdowns would increase the complexity quite a bit.
1192 *
1193 * Interface::
1194 *
1195 * int dma_buf_mmap(struct dma_buf \*, struct vm_area_struct \*,
1196 * unsigned long);
1197 *
1198 * If the importing subsystem simply provides a special-purpose mmap call to
1199 * set up a mapping in userspace, calling do_mmap with &dma_buf.file will
1200 * equally achieve that for a dma-buf object.
1201 */
1202
__dma_buf_begin_cpu_access(struct dma_buf * dmabuf,enum dma_data_direction direction)1203 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1204 enum dma_data_direction direction)
1205 {
1206 bool write = (direction == DMA_BIDIRECTIONAL ||
1207 direction == DMA_TO_DEVICE);
1208 struct dma_resv *resv = dmabuf->resv;
1209 long ret;
1210
1211 /* Wait on any implicit rendering fences */
1212 ret = dma_resv_wait_timeout(resv, write, true, MAX_SCHEDULE_TIMEOUT);
1213 if (ret < 0)
1214 return ret;
1215
1216 return 0;
1217 }
1218
1219 /**
1220 * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
1221 * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
1222 * preparations. Coherency is only guaranteed in the specified range for the
1223 * specified access direction.
1224 * @dmabuf: [in] buffer to prepare cpu access for.
1225 * @direction: [in] length of range for cpu access.
1226 *
1227 * After the cpu access is complete the caller should call
1228 * dma_buf_end_cpu_access(). Only when cpu access is braketed by both calls is
1229 * it guaranteed to be coherent with other DMA access.
1230 *
1231 * This function will also wait for any DMA transactions tracked through
1232 * implicit synchronization in &dma_buf.resv. For DMA transactions with explicit
1233 * synchronization this function will only ensure cache coherency, callers must
1234 * ensure synchronization with such DMA transactions on their own.
1235 *
1236 * Can return negative error values, returns 0 on success.
1237 */
dma_buf_begin_cpu_access(struct dma_buf * dmabuf,enum dma_data_direction direction)1238 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1239 enum dma_data_direction direction)
1240 {
1241 int ret = 0;
1242
1243 if (WARN_ON(!dmabuf))
1244 return -EINVAL;
1245
1246 might_lock(&dmabuf->resv->lock.base);
1247
1248 if (dmabuf->ops->begin_cpu_access)
1249 ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
1250
1251 /* Ensure that all fences are waited upon - but we first allow
1252 * the native handler the chance to do so more efficiently if it
1253 * chooses. A double invocation here will be reasonably cheap no-op.
1254 */
1255 if (ret == 0)
1256 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
1257
1258 return ret;
1259 }
1260 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
1261
dma_buf_begin_cpu_access_partial(struct dma_buf * dmabuf,enum dma_data_direction direction,unsigned int offset,unsigned int len)1262 int dma_buf_begin_cpu_access_partial(struct dma_buf *dmabuf,
1263 enum dma_data_direction direction,
1264 unsigned int offset, unsigned int len)
1265 {
1266 int ret = 0;
1267
1268 if (WARN_ON(!dmabuf))
1269 return -EINVAL;
1270
1271 if (dmabuf->ops->begin_cpu_access_partial)
1272 ret = dmabuf->ops->begin_cpu_access_partial(dmabuf, direction,
1273 offset, len);
1274
1275 /* Ensure that all fences are waited upon - but we first allow
1276 * the native handler the chance to do so more efficiently if it
1277 * chooses. A double invocation here will be reasonably cheap no-op.
1278 */
1279 if (ret == 0)
1280 ret = __dma_buf_begin_cpu_access(dmabuf, direction);
1281
1282 return ret;
1283 }
1284 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access_partial);
1285
1286 /**
1287 * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
1288 * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
1289 * actions. Coherency is only guaranteed in the specified range for the
1290 * specified access direction.
1291 * @dmabuf: [in] buffer to complete cpu access for.
1292 * @direction: [in] length of range for cpu access.
1293 *
1294 * This terminates CPU access started with dma_buf_begin_cpu_access().
1295 *
1296 * Can return negative error values, returns 0 on success.
1297 */
dma_buf_end_cpu_access(struct dma_buf * dmabuf,enum dma_data_direction direction)1298 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
1299 enum dma_data_direction direction)
1300 {
1301 int ret = 0;
1302
1303 WARN_ON(!dmabuf);
1304
1305 might_lock(&dmabuf->resv->lock.base);
1306
1307 if (dmabuf->ops->end_cpu_access)
1308 ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
1309
1310 return ret;
1311 }
1312 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
1313
dma_buf_end_cpu_access_partial(struct dma_buf * dmabuf,enum dma_data_direction direction,unsigned int offset,unsigned int len)1314 int dma_buf_end_cpu_access_partial(struct dma_buf *dmabuf,
1315 enum dma_data_direction direction,
1316 unsigned int offset, unsigned int len)
1317 {
1318 int ret = 0;
1319
1320 WARN_ON(!dmabuf);
1321
1322 if (dmabuf->ops->end_cpu_access_partial)
1323 ret = dmabuf->ops->end_cpu_access_partial(dmabuf, direction,
1324 offset, len);
1325
1326 return ret;
1327 }
1328 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access_partial);
1329
1330 /**
1331 * dma_buf_mmap - Setup up a userspace mmap with the given vma
1332 * @dmabuf: [in] buffer that should back the vma
1333 * @vma: [in] vma for the mmap
1334 * @pgoff: [in] offset in pages where this mmap should start within the
1335 * dma-buf buffer.
1336 *
1337 * This function adjusts the passed in vma so that it points at the file of the
1338 * dma_buf operation. It also adjusts the starting pgoff and does bounds
1339 * checking on the size of the vma. Then it calls the exporters mmap function to
1340 * set up the mapping.
1341 *
1342 * Can return negative error values, returns 0 on success.
1343 */
dma_buf_mmap(struct dma_buf * dmabuf,struct vm_area_struct * vma,unsigned long pgoff)1344 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1345 unsigned long pgoff)
1346 {
1347 if (WARN_ON(!dmabuf || !vma))
1348 return -EINVAL;
1349
1350 /* check if buffer supports mmap */
1351 if (!dmabuf->ops->mmap)
1352 return -EINVAL;
1353
1354 /* check for offset overflow */
1355 if (pgoff + vma_pages(vma) < pgoff)
1356 return -EOVERFLOW;
1357
1358 /* check for overflowing the buffer's size */
1359 if (pgoff + vma_pages(vma) >
1360 dmabuf->size >> PAGE_SHIFT)
1361 return -EINVAL;
1362
1363 /* readjust the vma */
1364 vma_set_file(vma, dmabuf->file);
1365 vma->vm_pgoff = pgoff;
1366
1367 return dmabuf->ops->mmap(dmabuf, vma);
1368 }
1369 EXPORT_SYMBOL_GPL(dma_buf_mmap);
1370
1371 /**
1372 * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1373 * address space. Same restrictions as for vmap and friends apply.
1374 * @dmabuf: [in] buffer to vmap
1375 * @map: [out] returns the vmap pointer
1376 *
1377 * This call may fail due to lack of virtual mapping address space.
1378 * These calls are optional in drivers. The intended use for them
1379 * is for mapping objects linear in kernel space for high use objects.
1380 *
1381 * To ensure coherency users must call dma_buf_begin_cpu_access() and
1382 * dma_buf_end_cpu_access() around any cpu access performed through this
1383 * mapping.
1384 *
1385 * Returns 0 on success, or a negative errno code otherwise.
1386 */
dma_buf_vmap(struct dma_buf * dmabuf,struct dma_buf_map * map)1387 int dma_buf_vmap(struct dma_buf *dmabuf, struct dma_buf_map *map)
1388 {
1389 struct dma_buf_map ptr;
1390 int ret = 0;
1391
1392 dma_buf_map_clear(map);
1393
1394 if (WARN_ON(!dmabuf))
1395 return -EINVAL;
1396
1397 if (!dmabuf->ops->vmap)
1398 return -EINVAL;
1399
1400 mutex_lock(&dmabuf->lock);
1401 if (dmabuf->vmapping_counter) {
1402 dmabuf->vmapping_counter++;
1403 BUG_ON(dma_buf_map_is_null(&dmabuf->vmap_ptr));
1404 *map = dmabuf->vmap_ptr;
1405 goto out_unlock;
1406 }
1407
1408 BUG_ON(dma_buf_map_is_set(&dmabuf->vmap_ptr));
1409
1410 ret = dmabuf->ops->vmap(dmabuf, &ptr);
1411 if (WARN_ON_ONCE(ret))
1412 goto out_unlock;
1413
1414 dmabuf->vmap_ptr = ptr;
1415 dmabuf->vmapping_counter = 1;
1416
1417 *map = dmabuf->vmap_ptr;
1418
1419 out_unlock:
1420 mutex_unlock(&dmabuf->lock);
1421 return ret;
1422 }
1423 EXPORT_SYMBOL_GPL(dma_buf_vmap);
1424
1425 /**
1426 * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1427 * @dmabuf: [in] buffer to vunmap
1428 * @map: [in] vmap pointer to vunmap
1429 */
dma_buf_vunmap(struct dma_buf * dmabuf,struct dma_buf_map * map)1430 void dma_buf_vunmap(struct dma_buf *dmabuf, struct dma_buf_map *map)
1431 {
1432 if (WARN_ON(!dmabuf))
1433 return;
1434
1435 BUG_ON(dma_buf_map_is_null(&dmabuf->vmap_ptr));
1436 BUG_ON(dmabuf->vmapping_counter == 0);
1437 BUG_ON(!dma_buf_map_is_equal(&dmabuf->vmap_ptr, map));
1438
1439 mutex_lock(&dmabuf->lock);
1440 if (--dmabuf->vmapping_counter == 0) {
1441 if (dmabuf->ops->vunmap)
1442 dmabuf->ops->vunmap(dmabuf, map);
1443 dma_buf_map_clear(&dmabuf->vmap_ptr);
1444 }
1445 mutex_unlock(&dmabuf->lock);
1446 }
1447 EXPORT_SYMBOL_GPL(dma_buf_vunmap);
1448
dma_buf_get_flags(struct dma_buf * dmabuf,unsigned long * flags)1449 int dma_buf_get_flags(struct dma_buf *dmabuf, unsigned long *flags)
1450 {
1451 int ret = 0;
1452
1453 if (WARN_ON(!dmabuf) || !flags)
1454 return -EINVAL;
1455
1456 if (dmabuf->ops->get_flags)
1457 ret = dmabuf->ops->get_flags(dmabuf, flags);
1458
1459 return ret;
1460 }
1461 EXPORT_SYMBOL_GPL(dma_buf_get_flags);
1462
1463 #ifdef CONFIG_DEBUG_FS
dma_buf_debug_show(struct seq_file * s,void * unused)1464 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1465 {
1466 struct dma_buf *buf_obj;
1467 struct dma_buf_attachment *attach_obj;
1468 struct dma_resv *robj;
1469 struct dma_resv_list *fobj;
1470 struct dma_fence *fence;
1471 int count = 0, attach_count, shared_count, i;
1472 size_t size = 0;
1473 int ret;
1474
1475 ret = mutex_lock_interruptible(&db_list.lock);
1476
1477 if (ret)
1478 return ret;
1479
1480 seq_puts(s, "\nDma-buf Objects:\n");
1481 seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\n",
1482 "size", "flags", "mode", "count", "ino");
1483
1484 list_for_each_entry(buf_obj, &db_list.head, list_node) {
1485
1486 ret = dma_resv_lock_interruptible(buf_obj->resv, NULL);
1487 if (ret)
1488 goto error_unlock;
1489
1490 spin_lock(&buf_obj->name_lock);
1491 seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1492 buf_obj->size,
1493 buf_obj->file->f_flags, buf_obj->file->f_mode,
1494 file_count(buf_obj->file),
1495 buf_obj->exp_name,
1496 file_inode(buf_obj->file)->i_ino,
1497 buf_obj->name ?: "");
1498 spin_unlock(&buf_obj->name_lock);
1499
1500 robj = buf_obj->resv;
1501 fence = dma_resv_excl_fence(robj);
1502 if (fence)
1503 seq_printf(s, "\tExclusive fence: %s %s %ssignalled\n",
1504 fence->ops->get_driver_name(fence),
1505 fence->ops->get_timeline_name(fence),
1506 dma_fence_is_signaled(fence) ? "" : "un");
1507
1508 fobj = rcu_dereference_protected(robj->fence,
1509 dma_resv_held(robj));
1510 shared_count = fobj ? fobj->shared_count : 0;
1511 for (i = 0; i < shared_count; i++) {
1512 fence = rcu_dereference_protected(fobj->shared[i],
1513 dma_resv_held(robj));
1514 seq_printf(s, "\tShared fence: %s %s %ssignalled\n",
1515 fence->ops->get_driver_name(fence),
1516 fence->ops->get_timeline_name(fence),
1517 dma_fence_is_signaled(fence) ? "" : "un");
1518 }
1519
1520 seq_puts(s, "\tAttached Devices:\n");
1521 attach_count = 0;
1522
1523 list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1524 seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1525 attach_count++;
1526 }
1527 dma_resv_unlock(buf_obj->resv);
1528
1529 seq_printf(s, "Total %d devices attached\n\n",
1530 attach_count);
1531
1532 count++;
1533 size += buf_obj->size;
1534 }
1535
1536 seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1537
1538 mutex_unlock(&db_list.lock);
1539 return 0;
1540
1541 error_unlock:
1542 mutex_unlock(&db_list.lock);
1543 return ret;
1544 }
1545
1546 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1547
1548 static struct dentry *dma_buf_debugfs_dir;
1549
dma_buf_init_debugfs(void)1550 static int dma_buf_init_debugfs(void)
1551 {
1552 struct dentry *d;
1553 int err = 0;
1554
1555 d = debugfs_create_dir("dma_buf", NULL);
1556 if (IS_ERR(d))
1557 return PTR_ERR(d);
1558
1559 dma_buf_debugfs_dir = d;
1560
1561 d = debugfs_create_file("bufinfo", S_IRUGO, dma_buf_debugfs_dir,
1562 NULL, &dma_buf_debug_fops);
1563 if (IS_ERR(d)) {
1564 pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1565 debugfs_remove_recursive(dma_buf_debugfs_dir);
1566 dma_buf_debugfs_dir = NULL;
1567 err = PTR_ERR(d);
1568 }
1569
1570 return err;
1571 }
1572
dma_buf_uninit_debugfs(void)1573 static void dma_buf_uninit_debugfs(void)
1574 {
1575 debugfs_remove_recursive(dma_buf_debugfs_dir);
1576 }
1577 #else
dma_buf_init_debugfs(void)1578 static inline int dma_buf_init_debugfs(void)
1579 {
1580 return 0;
1581 }
dma_buf_uninit_debugfs(void)1582 static inline void dma_buf_uninit_debugfs(void)
1583 {
1584 }
1585 #endif
1586
dma_buf_init(void)1587 static int __init dma_buf_init(void)
1588 {
1589 int ret;
1590
1591 ret = dma_buf_init_sysfs_statistics();
1592 if (ret)
1593 return ret;
1594
1595 dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1596 if (IS_ERR(dma_buf_mnt))
1597 return PTR_ERR(dma_buf_mnt);
1598
1599 mutex_init(&db_list.lock);
1600 INIT_LIST_HEAD(&db_list.head);
1601 dma_buf_init_debugfs();
1602 return 0;
1603 }
1604 subsys_initcall(dma_buf_init);
1605
dma_buf_deinit(void)1606 static void __exit dma_buf_deinit(void)
1607 {
1608 dma_buf_uninit_debugfs();
1609 kern_unmount(dma_buf_mnt);
1610 dma_buf_uninit_sysfs_statistics();
1611 }
1612 __exitcall(dma_buf_deinit);
1613