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