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