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