06c6225e15aadbfbfad44fa0539539c7f3187936
[cascardo/linux.git] / drivers / base / dma-buf.c
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>
28 #include <linux/anon_inodes.h>
29 #include <linux/export.h>
30 #include <linux/poll.h>
31 #include <linux/sched.h>
32
33 static inline int is_dma_buf_file(struct file *);
34
35 static int dma_buf_release(struct inode *inode, struct file *file)
36 {
37         struct dma_buf *dmabuf;
38
39         if (!is_dma_buf_file(file))
40                 return -EINVAL;
41
42         dmabuf = file->private_data;
43
44         dmabuf->ops->release(dmabuf);
45         kds_callback_term(&dmabuf->kds_cb);
46         kds_resource_term(&dmabuf->kds);
47         kfree(dmabuf);
48         return 0;
49 }
50
51 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
52 {
53         struct dma_buf *dmabuf;
54
55         if (!is_dma_buf_file(file))
56                 return -EINVAL;
57
58         dmabuf = file->private_data;
59
60         /* check for overflowing the buffer's size */
61         if (vma->vm_pgoff + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) >
62             dmabuf->size >> PAGE_SHIFT)
63                 return -EINVAL;
64
65         return dmabuf->ops->mmap(dmabuf, vma);
66 }
67
68
69 static void dma_buf_kds_cb_fn(void *param1, void *param2)
70 {
71         struct kds_resource_set **rset_ptr = param1;
72         struct kds_resource_set *rset = *rset_ptr;
73         wait_queue_head_t *wait_queue = param2;
74
75         kfree(rset_ptr);
76         kds_resource_set_release(&rset);
77         wake_up(wait_queue);
78 }
79
80 static int dma_buf_kds_check(struct kds_resource *kds,
81                 unsigned long exclusive, int *poll_ret)
82 {
83         /* Synchronous wait with 0 timeout - poll availability */
84         struct kds_resource_set *rset = kds_waitall(1, &exclusive, &kds, 0);
85
86         if (IS_ERR(rset))
87                 return POLLERR;
88
89         if (rset) {
90                 kds_resource_set_release(&rset);
91                 *poll_ret = POLLIN | POLLRDNORM;
92                 if (exclusive)
93                         *poll_ret |=  POLLOUT | POLLWRNORM;
94                 return 1;
95         } else {
96                 return 0;
97         }
98 }
99
100 static unsigned int dma_buf_poll(struct file *file,
101                 struct poll_table_struct *wait)
102 {
103         struct dma_buf *dmabuf;
104         struct kds_resource *kds;
105         unsigned int ret = 0;
106
107         if (!is_dma_buf_file(file))
108                 return POLLERR;
109
110         dmabuf = file->private_data;
111         kds    = &dmabuf->kds;
112
113         if (poll_does_not_wait(wait)) {
114                 /* Check for exclusive access (superset of shared) first */
115                 if (!dma_buf_kds_check(kds, 1ul, &ret))
116                         dma_buf_kds_check(kds, 0ul, &ret);
117         } else {
118                 int events = poll_requested_events(wait);
119                 unsigned long exclusive;
120                 wait_queue_head_t *wq;
121                 struct kds_resource_set **rset_ptr =
122                                 kmalloc(sizeof(*rset_ptr), GFP_KERNEL);
123
124                 if (!rset_ptr)
125                         return POLL_ERR;
126
127                 if (events & POLLOUT) {
128                         wq = &dmabuf->wq_exclusive;
129                         exclusive = 1;
130                 } else {
131                         wq = &dmabuf->wq_shared;
132                         exclusive = 0;
133                 }
134                 poll_wait(file, wq, wait);
135                 ret = kds_async_waitall(rset_ptr, KDS_FLAG_LOCKED_WAIT,
136                                 &dmabuf->kds_cb, rset_ptr, wq, 1, &exclusive,
137                                 &kds);
138
139                 if (IS_ERR_VALUE(ret)) {
140                         ret = POLL_ERR;
141                         kfree(rset_ptr);
142                 } else {
143                         /* Can't allow access until callback */
144                         ret = 0;
145                 }
146         }
147         return ret;
148 }
149
150 static const struct file_operations dma_buf_fops = {
151         .release        = dma_buf_release,
152         .mmap           = dma_buf_mmap_internal,
153         .poll           = dma_buf_poll,
154 };
155
156 /*
157  * is_dma_buf_file - Check if struct file* is associated with dma_buf
158  */
159 static inline int is_dma_buf_file(struct file *file)
160 {
161         return file->f_op == &dma_buf_fops;
162 }
163
164 /**
165  * dma_buf_export - Creates a new dma_buf, and associates an anon file
166  * with this buffer, so it can be exported.
167  * Also connect the allocator specific data and ops to the buffer.
168  *
169  * @priv:       [in]    Attach private data of allocator to this buffer
170  * @ops:        [in]    Attach allocator-defined dma buf ops to the new buffer.
171  * @size:       [in]    Size of the buffer
172  * @flags:      [in]    mode flags for the file.
173  *
174  * Returns, on success, a newly created dma_buf object, which wraps the
175  * supplied private data and operations for dma_buf_ops. On either missing
176  * ops, or error in allocating struct dma_buf, will return negative error.
177  *
178  */
179 struct dma_buf *dma_buf_export(void *priv, const struct dma_buf_ops *ops,
180                                 size_t size, int flags)
181 {
182         struct dma_buf *dmabuf;
183         struct file *file;
184
185         if (WARN_ON(!priv || !ops
186                           || !ops->map_dma_buf
187                           || !ops->unmap_dma_buf
188                           || !ops->release
189                           || !ops->kmap_atomic
190                           || !ops->kmap
191                           || !ops->mmap)) {
192                 return ERR_PTR(-EINVAL);
193         }
194
195         dmabuf = kzalloc(sizeof(struct dma_buf), GFP_KERNEL);
196         if (dmabuf == NULL)
197                 return ERR_PTR(-ENOMEM);
198
199         dmabuf->priv = priv;
200         dmabuf->ops = ops;
201         dmabuf->size = size;
202
203         file = anon_inode_getfile("dmabuf", &dma_buf_fops, dmabuf, flags);
204
205         dmabuf->file = file;
206
207         mutex_init(&dmabuf->lock);
208         INIT_LIST_HEAD(&dmabuf->attachments);
209
210         init_waitqueue_head(&dmabuf->wq_exclusive);
211         init_waitqueue_head(&dmabuf->wq_shared);
212         kds_resource_init(&dmabuf->kds);
213         kds_callback_init(&dmabuf->kds_cb, 1, dma_buf_kds_cb_fn);
214
215         return dmabuf;
216 }
217 EXPORT_SYMBOL_GPL(dma_buf_export);
218
219
220 /**
221  * dma_buf_fd - returns a file descriptor for the given dma_buf
222  * @dmabuf:     [in]    pointer to dma_buf for which fd is required.
223  * @flags:      [in]    flags to give to fd
224  *
225  * On success, returns an associated 'fd'. Else, returns error.
226  */
227 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
228 {
229         int error, fd;
230
231         if (!dmabuf || !dmabuf->file)
232                 return -EINVAL;
233
234         error = get_unused_fd_flags(flags);
235         if (error < 0)
236                 return error;
237         fd = error;
238
239         fd_install(fd, dmabuf->file);
240
241         return fd;
242 }
243 EXPORT_SYMBOL_GPL(dma_buf_fd);
244
245 /**
246  * dma_buf_get - returns the dma_buf structure related to an fd
247  * @fd: [in]    fd associated with the dma_buf to be returned
248  *
249  * On success, returns the dma_buf structure associated with an fd; uses
250  * file's refcounting done by fget to increase refcount. returns ERR_PTR
251  * otherwise.
252  */
253 struct dma_buf *dma_buf_get(int fd)
254 {
255         struct file *file;
256
257         file = fget(fd);
258
259         if (!file)
260                 return ERR_PTR(-EBADF);
261
262         if (!is_dma_buf_file(file)) {
263                 fput(file);
264                 return ERR_PTR(-EINVAL);
265         }
266
267         return file->private_data;
268 }
269 EXPORT_SYMBOL_GPL(dma_buf_get);
270
271 /**
272  * dma_buf_put - decreases refcount of the buffer
273  * @dmabuf:     [in]    buffer to reduce refcount of
274  *
275  * Uses file's refcounting done implicitly by fput()
276  */
277 void dma_buf_put(struct dma_buf *dmabuf)
278 {
279         if (WARN_ON(!dmabuf || !dmabuf->file))
280                 return;
281
282         fput(dmabuf->file);
283 }
284 EXPORT_SYMBOL_GPL(dma_buf_put);
285
286 /**
287  * dma_buf_attach - Add the device to dma_buf's attachments list; optionally,
288  * calls attach() of dma_buf_ops to allow device-specific attach functionality
289  * @dmabuf:     [in]    buffer to attach device to.
290  * @dev:        [in]    device to be attached.
291  *
292  * Returns struct dma_buf_attachment * for this attachment; may return negative
293  * error codes.
294  *
295  */
296 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
297                                           struct device *dev)
298 {
299         struct dma_buf_attachment *attach;
300         int ret;
301
302         if (WARN_ON(!dmabuf || !dev))
303                 return ERR_PTR(-EINVAL);
304
305         attach = kzalloc(sizeof(struct dma_buf_attachment), GFP_KERNEL);
306         if (attach == NULL)
307                 return ERR_PTR(-ENOMEM);
308
309         attach->dev = dev;
310         attach->dmabuf = dmabuf;
311
312         mutex_lock(&dmabuf->lock);
313
314         if (dmabuf->ops->attach) {
315                 ret = dmabuf->ops->attach(dmabuf, dev, attach);
316                 if (ret)
317                         goto err_attach;
318         }
319         list_add(&attach->node, &dmabuf->attachments);
320
321         mutex_unlock(&dmabuf->lock);
322         return attach;
323
324 err_attach:
325         kfree(attach);
326         mutex_unlock(&dmabuf->lock);
327         return ERR_PTR(ret);
328 }
329 EXPORT_SYMBOL_GPL(dma_buf_attach);
330
331 /**
332  * dma_buf_detach - Remove the given attachment from dmabuf's attachments list;
333  * optionally calls detach() of dma_buf_ops for device-specific detach
334  * @dmabuf:     [in]    buffer to detach from.
335  * @attach:     [in]    attachment to be detached; is free'd after this call.
336  *
337  */
338 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
339 {
340         if (WARN_ON(!dmabuf || !attach))
341                 return;
342
343         mutex_lock(&dmabuf->lock);
344         list_del(&attach->node);
345         if (dmabuf->ops->detach)
346                 dmabuf->ops->detach(dmabuf, attach);
347
348         mutex_unlock(&dmabuf->lock);
349         kfree(attach);
350 }
351 EXPORT_SYMBOL_GPL(dma_buf_detach);
352
353 /**
354  * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
355  * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
356  * dma_buf_ops.
357  * @attach:     [in]    attachment whose scatterlist is to be returned
358  * @direction:  [in]    direction of DMA transfer
359  *
360  * Returns sg_table containing the scatterlist to be returned; may return NULL
361  * or ERR_PTR.
362  *
363  */
364 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
365                                         enum dma_data_direction direction)
366 {
367         struct sg_table *sg_table = ERR_PTR(-EINVAL);
368
369         might_sleep();
370
371         if (WARN_ON(!attach || !attach->dmabuf))
372                 return ERR_PTR(-EINVAL);
373
374         sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
375
376         return sg_table;
377 }
378 EXPORT_SYMBOL_GPL(dma_buf_map_attachment);
379
380 /**
381  * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
382  * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
383  * dma_buf_ops.
384  * @attach:     [in]    attachment to unmap buffer from
385  * @sg_table:   [in]    scatterlist info of the buffer to unmap
386  * @direction:  [in]    direction of DMA transfer
387  *
388  */
389 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
390                                 struct sg_table *sg_table,
391                                 enum dma_data_direction direction)
392 {
393         if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
394                 return;
395
396         attach->dmabuf->ops->unmap_dma_buf(attach, sg_table,
397                                                 direction);
398 }
399 EXPORT_SYMBOL_GPL(dma_buf_unmap_attachment);
400
401
402 /**
403  * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
404  * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
405  * preparations. Coherency is only guaranteed in the specified range for the
406  * specified access direction.
407  * @dma_buf:    [in]    buffer to prepare cpu access for.
408  * @start:      [in]    start of range for cpu access.
409  * @len:        [in]    length of range for cpu access.
410  * @direction:  [in]    length of range for cpu access.
411  *
412  * Can return negative error values, returns 0 on success.
413  */
414 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf, size_t start, size_t len,
415                              enum dma_data_direction direction)
416 {
417         int ret = 0;
418
419         if (WARN_ON(!dmabuf))
420                 return -EINVAL;
421
422         if (dmabuf->ops->begin_cpu_access)
423                 ret = dmabuf->ops->begin_cpu_access(dmabuf, start, len, direction);
424
425         return ret;
426 }
427 EXPORT_SYMBOL_GPL(dma_buf_begin_cpu_access);
428
429 /**
430  * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
431  * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
432  * actions. Coherency is only guaranteed in the specified range for the
433  * specified access direction.
434  * @dma_buf:    [in]    buffer to complete cpu access for.
435  * @start:      [in]    start of range for cpu access.
436  * @len:        [in]    length of range for cpu access.
437  * @direction:  [in]    length of range for cpu access.
438  *
439  * This call must always succeed.
440  */
441 void dma_buf_end_cpu_access(struct dma_buf *dmabuf, size_t start, size_t len,
442                             enum dma_data_direction direction)
443 {
444         WARN_ON(!dmabuf);
445
446         if (dmabuf->ops->end_cpu_access)
447                 dmabuf->ops->end_cpu_access(dmabuf, start, len, direction);
448 }
449 EXPORT_SYMBOL_GPL(dma_buf_end_cpu_access);
450
451 /**
452  * dma_buf_kmap_atomic - Map a page of the buffer object into kernel address
453  * space. The same restrictions as for kmap_atomic and friends apply.
454  * @dma_buf:    [in]    buffer to map page from.
455  * @page_num:   [in]    page in PAGE_SIZE units to map.
456  *
457  * This call must always succeed, any necessary preparations that might fail
458  * need to be done in begin_cpu_access.
459  */
460 void *dma_buf_kmap_atomic(struct dma_buf *dmabuf, unsigned long page_num)
461 {
462         WARN_ON(!dmabuf);
463
464         return dmabuf->ops->kmap_atomic(dmabuf, page_num);
465 }
466 EXPORT_SYMBOL_GPL(dma_buf_kmap_atomic);
467
468 /**
469  * dma_buf_kunmap_atomic - Unmap a page obtained by dma_buf_kmap_atomic.
470  * @dma_buf:    [in]    buffer to unmap page from.
471  * @page_num:   [in]    page in PAGE_SIZE units to unmap.
472  * @vaddr:      [in]    kernel space pointer obtained from dma_buf_kmap_atomic.
473  *
474  * This call must always succeed.
475  */
476 void dma_buf_kunmap_atomic(struct dma_buf *dmabuf, unsigned long page_num,
477                            void *vaddr)
478 {
479         WARN_ON(!dmabuf);
480
481         if (dmabuf->ops->kunmap_atomic)
482                 dmabuf->ops->kunmap_atomic(dmabuf, page_num, vaddr);
483 }
484 EXPORT_SYMBOL_GPL(dma_buf_kunmap_atomic);
485
486 /**
487  * dma_buf_kmap - Map a page of the buffer object into kernel address space. The
488  * same restrictions as for kmap and friends apply.
489  * @dma_buf:    [in]    buffer to map page from.
490  * @page_num:   [in]    page in PAGE_SIZE units to map.
491  *
492  * This call must always succeed, any necessary preparations that might fail
493  * need to be done in begin_cpu_access.
494  */
495 void *dma_buf_kmap(struct dma_buf *dmabuf, unsigned long page_num)
496 {
497         WARN_ON(!dmabuf);
498
499         return dmabuf->ops->kmap(dmabuf, page_num);
500 }
501 EXPORT_SYMBOL_GPL(dma_buf_kmap);
502
503 /**
504  * dma_buf_kunmap - Unmap a page obtained by dma_buf_kmap.
505  * @dma_buf:    [in]    buffer to unmap page from.
506  * @page_num:   [in]    page in PAGE_SIZE units to unmap.
507  * @vaddr:      [in]    kernel space pointer obtained from dma_buf_kmap.
508  *
509  * This call must always succeed.
510  */
511 void dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long page_num,
512                     void *vaddr)
513 {
514         WARN_ON(!dmabuf);
515
516         if (dmabuf->ops->kunmap)
517                 dmabuf->ops->kunmap(dmabuf, page_num, vaddr);
518 }
519 EXPORT_SYMBOL_GPL(dma_buf_kunmap);
520
521
522 /**
523  * dma_buf_mmap - Setup up a userspace mmap with the given vma
524  * @dmabuf:     [in]    buffer that should back the vma
525  * @vma:        [in]    vma for the mmap
526  * @pgoff:      [in]    offset in pages where this mmap should start within the
527  *                      dma-buf buffer.
528  *
529  * This function adjusts the passed in vma so that it points at the file of the
530  * dma_buf operation. It alsog adjusts the starting pgoff and does bounds
531  * checking on the size of the vma. Then it calls the exporters mmap function to
532  * set up the mapping.
533  *
534  * Can return negative error values, returns 0 on success.
535  */
536 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
537                  unsigned long pgoff)
538 {
539         struct file *oldfile;
540         int ret;
541
542         if (WARN_ON(!dmabuf || !vma))
543                 return -EINVAL;
544
545         /* check for offset overflow */
546         if (pgoff + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) < pgoff)
547                 return -EOVERFLOW;
548
549         /* check for overflowing the buffer's size */
550         if (pgoff + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) >
551             dmabuf->size >> PAGE_SHIFT)
552                 return -EINVAL;
553
554         /* readjust the vma */
555         get_file(dmabuf->file);
556         oldfile = vma->vm_file;
557         vma->vm_file = dmabuf->file;
558         vma->vm_pgoff = pgoff;
559
560         ret = dmabuf->ops->mmap(dmabuf, vma);
561         if (ret) {
562                 /* restore old parameters on failure */
563                 vma->vm_file = oldfile;
564                 fput(dmabuf->file);
565         } else {
566                 if (oldfile)
567                         fput(oldfile);
568         }
569         return ret;
570 }
571 EXPORT_SYMBOL_GPL(dma_buf_mmap);
572
573 /**
574  * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
575  * address space. Same restrictions as for vmap and friends apply.
576  * @dmabuf:     [in]    buffer to vmap
577  *
578  * This call may fail due to lack of virtual mapping address space.
579  * These calls are optional in drivers. The intended use for them
580  * is for mapping objects linear in kernel space for high use objects.
581  * Please attempt to use kmap/kunmap before thinking about these interfaces.
582  */
583 void *dma_buf_vmap(struct dma_buf *dmabuf)
584 {
585         if (WARN_ON(!dmabuf))
586                 return NULL;
587
588         if (dmabuf->ops->vmap)
589                 return dmabuf->ops->vmap(dmabuf);
590         return NULL;
591 }
592 EXPORT_SYMBOL_GPL(dma_buf_vmap);
593
594 /**
595  * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
596  * @dmabuf:     [in]    buffer to vunmap
597  */
598 void dma_buf_vunmap(struct dma_buf *dmabuf, void *vaddr)
599 {
600         if (WARN_ON(!dmabuf))
601                 return;
602
603         if (dmabuf->ops->vunmap)
604                 dmabuf->ops->vunmap(dmabuf, vaddr);
605 }
606 EXPORT_SYMBOL_GPL(dma_buf_vunmap);