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