Merge branch 'linux-linaro-lsk-v4.4-android' of git://git.linaro.org/kernel/linux...
[firefly-linux-kernel-4.4.55.git] / drivers / media / v4l2-core / videobuf2-core.c
1 /*
2  * videobuf2-core.c - video buffer 2 core framework
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  *
6  * Author: Pawel Osciak <pawel@osciak.com>
7  *         Marek Szyprowski <m.szyprowski@samsung.com>
8  *
9  * The vb2_thread implementation was based on code from videobuf-dvb.c:
10  *      (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation.
15  */
16
17 #include <linux/err.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/mm.h>
21 #include <linux/poll.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
26
27 #include <media/videobuf2-core.h>
28
29 #include <trace/events/vb2.h>
30
31 #include "videobuf2-internal.h"
32
33 int vb2_debug;
34 EXPORT_SYMBOL_GPL(vb2_debug);
35 module_param_named(debug, vb2_debug, int, 0644);
36
37 static void __vb2_queue_cancel(struct vb2_queue *q);
38 static void __enqueue_in_driver(struct vb2_buffer *vb);
39
40 /**
41  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
42  */
43 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
44 {
45         struct vb2_queue *q = vb->vb2_queue;
46         void *mem_priv;
47         int plane;
48
49         /*
50          * Allocate memory for all planes in this buffer
51          * NOTE: mmapped areas should be page aligned
52          */
53         for (plane = 0; plane < vb->num_planes; ++plane) {
54                 unsigned long size = PAGE_ALIGN(q->plane_sizes[plane]);
55
56                 mem_priv = call_ptr_memop(vb, alloc, q->alloc_ctx[plane],
57                                       size, q->dma_dir, q->gfp_flags);
58                 if (IS_ERR_OR_NULL(mem_priv))
59                         goto free;
60
61                 /* Associate allocator private data with this plane */
62                 vb->planes[plane].mem_priv = mem_priv;
63                 vb->planes[plane].length = q->plane_sizes[plane];
64         }
65
66         return 0;
67 free:
68         /* Free already allocated memory if one of the allocations failed */
69         for (; plane > 0; --plane) {
70                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
71                 vb->planes[plane - 1].mem_priv = NULL;
72         }
73
74         return -ENOMEM;
75 }
76
77 /**
78  * __vb2_buf_mem_free() - free memory of the given buffer
79  */
80 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
81 {
82         unsigned int plane;
83
84         for (plane = 0; plane < vb->num_planes; ++plane) {
85                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
86                 vb->planes[plane].mem_priv = NULL;
87                 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
88         }
89 }
90
91 /**
92  * __vb2_buf_userptr_put() - release userspace memory associated with
93  * a USERPTR buffer
94  */
95 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
96 {
97         unsigned int plane;
98
99         for (plane = 0; plane < vb->num_planes; ++plane) {
100                 if (vb->planes[plane].mem_priv)
101                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
102                 vb->planes[plane].mem_priv = NULL;
103         }
104 }
105
106 /**
107  * __vb2_plane_dmabuf_put() - release memory associated with
108  * a DMABUF shared plane
109  */
110 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
111 {
112         if (!p->mem_priv)
113                 return;
114
115         if (p->dbuf_mapped)
116                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
117
118         call_void_memop(vb, detach_dmabuf, p->mem_priv);
119         dma_buf_put(p->dbuf);
120         p->mem_priv = NULL;
121         p->dbuf = NULL;
122         p->dbuf_mapped = 0;
123 }
124
125 /**
126  * __vb2_buf_dmabuf_put() - release memory associated with
127  * a DMABUF shared buffer
128  */
129 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
130 {
131         unsigned int plane;
132
133         for (plane = 0; plane < vb->num_planes; ++plane)
134                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
135 }
136
137 /**
138  * __setup_lengths() - setup initial lengths for every plane in
139  * every buffer on the queue
140  */
141 static void __setup_lengths(struct vb2_queue *q, unsigned int n)
142 {
143         unsigned int buffer, plane;
144         struct vb2_buffer *vb;
145
146         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
147                 vb = q->bufs[buffer];
148                 if (!vb)
149                         continue;
150
151                 for (plane = 0; plane < vb->num_planes; ++plane)
152                         vb->planes[plane].length = q->plane_sizes[plane];
153         }
154 }
155
156 /**
157  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
158  * every buffer on the queue
159  */
160 static void __setup_offsets(struct vb2_queue *q, unsigned int n)
161 {
162         unsigned int buffer, plane;
163         struct vb2_buffer *vb;
164         unsigned long off;
165
166         if (q->num_buffers) {
167                 struct vb2_plane *p;
168                 vb = q->bufs[q->num_buffers - 1];
169                 p = &vb->planes[vb->num_planes - 1];
170                 off = PAGE_ALIGN(p->m.offset + p->length);
171         } else {
172                 off = 0;
173         }
174
175         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
176                 vb = q->bufs[buffer];
177                 if (!vb)
178                         continue;
179
180                 for (plane = 0; plane < vb->num_planes; ++plane) {
181                         vb->planes[plane].m.offset = off;
182
183                         dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
184                                         buffer, plane, off);
185
186                         off += vb->planes[plane].length;
187                         off = PAGE_ALIGN(off);
188                 }
189         }
190 }
191
192 /**
193  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
194  * video buffer memory for all buffers/planes on the queue and initializes the
195  * queue
196  *
197  * Returns the number of buffers successfully allocated.
198  */
199 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
200                              unsigned int num_buffers, unsigned int num_planes)
201 {
202         unsigned int buffer;
203         struct vb2_buffer *vb;
204         int ret;
205
206         for (buffer = 0; buffer < num_buffers; ++buffer) {
207                 /* Allocate videobuf buffer structures */
208                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
209                 if (!vb) {
210                         dprintk(1, "memory alloc for buffer struct failed\n");
211                         break;
212                 }
213
214                 vb->state = VB2_BUF_STATE_DEQUEUED;
215                 vb->vb2_queue = q;
216                 vb->num_planes = num_planes;
217                 vb->index = q->num_buffers + buffer;
218                 vb->type = q->type;
219                 vb->memory = memory;
220
221                 /* Allocate video buffer memory for the MMAP type */
222                 if (memory == VB2_MEMORY_MMAP) {
223                         ret = __vb2_buf_mem_alloc(vb);
224                         if (ret) {
225                                 dprintk(1, "failed allocating memory for "
226                                                 "buffer %d\n", buffer);
227                                 kfree(vb);
228                                 break;
229                         }
230                         /*
231                          * Call the driver-provided buffer initialization
232                          * callback, if given. An error in initialization
233                          * results in queue setup failure.
234                          */
235                         ret = call_vb_qop(vb, buf_init, vb);
236                         if (ret) {
237                                 dprintk(1, "buffer %d %p initialization"
238                                         " failed\n", buffer, vb);
239                                 __vb2_buf_mem_free(vb);
240                                 kfree(vb);
241                                 break;
242                         }
243                 }
244
245                 q->bufs[q->num_buffers + buffer] = vb;
246         }
247
248         __setup_lengths(q, buffer);
249         if (memory == VB2_MEMORY_MMAP)
250                 __setup_offsets(q, buffer);
251
252         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
253                         buffer, num_planes);
254
255         return buffer;
256 }
257
258 /**
259  * __vb2_free_mem() - release all video buffer memory for a given queue
260  */
261 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
262 {
263         unsigned int buffer;
264         struct vb2_buffer *vb;
265
266         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
267              ++buffer) {
268                 vb = q->bufs[buffer];
269                 if (!vb)
270                         continue;
271
272                 /* Free MMAP buffers or release USERPTR buffers */
273                 if (q->memory == VB2_MEMORY_MMAP)
274                         __vb2_buf_mem_free(vb);
275                 else if (q->memory == VB2_MEMORY_DMABUF)
276                         __vb2_buf_dmabuf_put(vb);
277                 else
278                         __vb2_buf_userptr_put(vb);
279         }
280 }
281
282 /**
283  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
284  * related information, if no buffers are left return the queue to an
285  * uninitialized state. Might be called even if the queue has already been freed.
286  */
287 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
288 {
289         unsigned int buffer;
290
291         /*
292          * Sanity check: when preparing a buffer the queue lock is released for
293          * a short while (see __buf_prepare for the details), which would allow
294          * a race with a reqbufs which can call this function. Removing the
295          * buffers from underneath __buf_prepare is obviously a bad idea, so we
296          * check if any of the buffers is in the state PREPARING, and if so we
297          * just return -EAGAIN.
298          */
299         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
300              ++buffer) {
301                 if (q->bufs[buffer] == NULL)
302                         continue;
303                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
304                         dprintk(1, "preparing buffers, cannot free\n");
305                         return -EAGAIN;
306                 }
307         }
308
309         /* Call driver-provided cleanup function for each buffer, if provided */
310         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
311              ++buffer) {
312                 struct vb2_buffer *vb = q->bufs[buffer];
313
314                 if (vb && vb->planes[0].mem_priv)
315                         call_void_vb_qop(vb, buf_cleanup, vb);
316         }
317
318         /* Release video buffer memory */
319         __vb2_free_mem(q, buffers);
320
321 #ifdef CONFIG_VIDEO_ADV_DEBUG
322         /*
323          * Check that all the calls were balances during the life-time of this
324          * queue. If not (or if the debug level is 1 or up), then dump the
325          * counters to the kernel log.
326          */
327         if (q->num_buffers) {
328                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
329                                   q->cnt_wait_prepare != q->cnt_wait_finish;
330
331                 if (unbalanced || vb2_debug) {
332                         pr_info("vb2: counters for queue %p:%s\n", q,
333                                 unbalanced ? " UNBALANCED!" : "");
334                         pr_info("vb2:     setup: %u start_streaming: %u stop_streaming: %u\n",
335                                 q->cnt_queue_setup, q->cnt_start_streaming,
336                                 q->cnt_stop_streaming);
337                         pr_info("vb2:     wait_prepare: %u wait_finish: %u\n",
338                                 q->cnt_wait_prepare, q->cnt_wait_finish);
339                 }
340                 q->cnt_queue_setup = 0;
341                 q->cnt_wait_prepare = 0;
342                 q->cnt_wait_finish = 0;
343                 q->cnt_start_streaming = 0;
344                 q->cnt_stop_streaming = 0;
345         }
346         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
347                 struct vb2_buffer *vb = q->bufs[buffer];
348                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
349                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
350                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
351                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
352                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
353                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
354                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
355                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
356
357                 if (unbalanced || vb2_debug) {
358                         pr_info("vb2:   counters for queue %p, buffer %d:%s\n",
359                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
360                         pr_info("vb2:     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
361                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
362                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
363                         pr_info("vb2:     buf_queue: %u buf_done: %u\n",
364                                 vb->cnt_buf_queue, vb->cnt_buf_done);
365                         pr_info("vb2:     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
366                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
367                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
368                                 vb->cnt_mem_mmap);
369                         pr_info("vb2:     get_userptr: %u put_userptr: %u\n",
370                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
371                         pr_info("vb2:     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
372                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
373                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
374                         pr_info("vb2:     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
375                                 vb->cnt_mem_get_dmabuf,
376                                 vb->cnt_mem_num_users,
377                                 vb->cnt_mem_vaddr,
378                                 vb->cnt_mem_cookie);
379                 }
380         }
381 #endif
382
383         /* Free videobuf buffers */
384         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
385              ++buffer) {
386                 kfree(q->bufs[buffer]);
387                 q->bufs[buffer] = NULL;
388         }
389
390         q->num_buffers -= buffers;
391         if (!q->num_buffers) {
392                 q->memory = 0;
393                 INIT_LIST_HEAD(&q->queued_list);
394         }
395         return 0;
396 }
397
398 /**
399  * vb2_buffer_in_use() - return true if the buffer is in use and
400  * the queue cannot be freed (by the means of REQBUFS(0)) call
401  */
402 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
403 {
404         unsigned int plane;
405         for (plane = 0; plane < vb->num_planes; ++plane) {
406                 void *mem_priv = vb->planes[plane].mem_priv;
407                 /*
408                  * If num_users() has not been provided, call_memop
409                  * will return 0, apparently nobody cares about this
410                  * case anyway. If num_users() returns more than 1,
411                  * we are not the only user of the plane's memory.
412                  */
413                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
414                         return true;
415         }
416         return false;
417 }
418 EXPORT_SYMBOL(vb2_buffer_in_use);
419
420 /**
421  * __buffers_in_use() - return true if any buffers on the queue are in use and
422  * the queue cannot be freed (by the means of REQBUFS(0)) call
423  */
424 static bool __buffers_in_use(struct vb2_queue *q)
425 {
426         unsigned int buffer;
427         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
428                 if (vb2_buffer_in_use(q, q->bufs[buffer]))
429                         return true;
430         }
431         return false;
432 }
433
434 /**
435  * vb2_core_querybuf() - query video buffer information
436  * @q:          videobuf queue
437  * @index:      id number of the buffer
438  * @pb:         buffer struct passed from userspace
439  *
440  * Should be called from vidioc_querybuf ioctl handler in driver.
441  * The passed buffer should have been verified.
442  * This function fills the relevant information for the userspace.
443  *
444  * The return values from this function are intended to be directly returned
445  * from vidioc_querybuf handler in driver.
446  */
447 int vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
448 {
449         return call_bufop(q, fill_user_buffer, q->bufs[index], pb);
450 }
451 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
452
453 /**
454  * __verify_userptr_ops() - verify that all memory operations required for
455  * USERPTR queue type have been provided
456  */
457 static int __verify_userptr_ops(struct vb2_queue *q)
458 {
459         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
460             !q->mem_ops->put_userptr)
461                 return -EINVAL;
462
463         return 0;
464 }
465
466 /**
467  * __verify_mmap_ops() - verify that all memory operations required for
468  * MMAP queue type have been provided
469  */
470 static int __verify_mmap_ops(struct vb2_queue *q)
471 {
472         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
473             !q->mem_ops->put || !q->mem_ops->mmap)
474                 return -EINVAL;
475
476         return 0;
477 }
478
479 /**
480  * __verify_dmabuf_ops() - verify that all memory operations required for
481  * DMABUF queue type have been provided
482  */
483 static int __verify_dmabuf_ops(struct vb2_queue *q)
484 {
485         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
486             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
487             !q->mem_ops->unmap_dmabuf)
488                 return -EINVAL;
489
490         return 0;
491 }
492
493 /**
494  * vb2_verify_memory_type() - Check whether the memory type and buffer type
495  * passed to a buffer operation are compatible with the queue.
496  */
497 int vb2_verify_memory_type(struct vb2_queue *q,
498                 enum vb2_memory memory, unsigned int type)
499 {
500         if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
501             memory != VB2_MEMORY_DMABUF) {
502                 dprintk(1, "unsupported memory type\n");
503                 return -EINVAL;
504         }
505
506         if (type != q->type) {
507                 dprintk(1, "requested type is incorrect\n");
508                 return -EINVAL;
509         }
510
511         /*
512          * Make sure all the required memory ops for given memory type
513          * are available.
514          */
515         if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
516                 dprintk(1, "MMAP for current setup unsupported\n");
517                 return -EINVAL;
518         }
519
520         if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
521                 dprintk(1, "USERPTR for current setup unsupported\n");
522                 return -EINVAL;
523         }
524
525         if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
526                 dprintk(1, "DMABUF for current setup unsupported\n");
527                 return -EINVAL;
528         }
529
530         /*
531          * Place the busy tests at the end: -EBUSY can be ignored when
532          * create_bufs is called with count == 0, but count == 0 should still
533          * do the memory and type validation.
534          */
535         if (vb2_fileio_is_active(q)) {
536                 dprintk(1, "file io in progress\n");
537                 return -EBUSY;
538         }
539         return 0;
540 }
541 EXPORT_SYMBOL(vb2_verify_memory_type);
542
543 /**
544  * vb2_core_reqbufs() - Initiate streaming
545  * @q:          videobuf2 queue
546  * @memory: memory type
547  * @count: requested buffer count
548  *
549  * Should be called from vidioc_reqbufs ioctl handler of a driver.
550  * This function:
551  * 1) verifies streaming parameters passed from the userspace,
552  * 2) sets up the queue,
553  * 3) negotiates number of buffers and planes per buffer with the driver
554  *    to be used during streaming,
555  * 4) allocates internal buffer structures (struct vb2_buffer), according to
556  *    the agreed parameters,
557  * 5) for MMAP memory type, allocates actual video memory, using the
558  *    memory handling/allocation routines provided during queue initialization
559  *
560  * If req->count is 0, all the memory will be freed instead.
561  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
562  * and the queue is not busy, memory will be reallocated.
563  *
564  * The return values from this function are intended to be directly returned
565  * from vidioc_reqbufs handler in driver.
566  */
567 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
568                 unsigned int *count)
569 {
570         unsigned int num_buffers, allocated_buffers, num_planes = 0;
571         int ret;
572
573         if (q->streaming) {
574                 dprintk(1, "streaming active\n");
575                 return -EBUSY;
576         }
577
578         if (*count == 0 || q->num_buffers != 0 || q->memory != memory) {
579                 /*
580                  * We already have buffers allocated, so first check if they
581                  * are not in use and can be freed.
582                  */
583                 mutex_lock(&q->mmap_lock);
584                 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
585                         mutex_unlock(&q->mmap_lock);
586                         dprintk(1, "memory in use, cannot free\n");
587                         return -EBUSY;
588                 }
589
590                 /*
591                  * Call queue_cancel to clean up any buffers in the PREPARED or
592                  * QUEUED state which is possible if buffers were prepared or
593                  * queued without ever calling STREAMON.
594                  */
595                 __vb2_queue_cancel(q);
596                 ret = __vb2_queue_free(q, q->num_buffers);
597                 mutex_unlock(&q->mmap_lock);
598                 if (ret)
599                         return ret;
600
601                 /*
602                  * In case of REQBUFS(0) return immediately without calling
603                  * driver's queue_setup() callback and allocating resources.
604                  */
605                 if (*count == 0)
606                         return 0;
607         }
608
609         /*
610          * Make sure the requested values and current defaults are sane.
611          */
612         num_buffers = min_t(unsigned int, *count, VB2_MAX_FRAME);
613         num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
614         memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
615         memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
616         q->memory = memory;
617
618         /*
619          * Ask the driver how many buffers and planes per buffer it requires.
620          * Driver also sets the size and allocator context for each plane.
621          */
622         ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
623                        q->plane_sizes, q->alloc_ctx);
624         if (ret)
625                 return ret;
626
627         /* Finally, allocate buffers and video memory */
628         allocated_buffers =
629                 __vb2_queue_alloc(q, memory, num_buffers, num_planes);
630         if (allocated_buffers == 0) {
631                 dprintk(1, "memory allocation failed\n");
632                 return -ENOMEM;
633         }
634
635         /*
636          * There is no point in continuing if we can't allocate the minimum
637          * number of buffers needed by this vb2_queue.
638          */
639         if (allocated_buffers < q->min_buffers_needed)
640                 ret = -ENOMEM;
641
642         /*
643          * Check if driver can handle the allocated number of buffers.
644          */
645         if (!ret && allocated_buffers < num_buffers) {
646                 num_buffers = allocated_buffers;
647
648                 ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
649                                &num_planes, q->plane_sizes, q->alloc_ctx);
650
651                 if (!ret && allocated_buffers < num_buffers)
652                         ret = -ENOMEM;
653
654                 /*
655                  * Either the driver has accepted a smaller number of buffers,
656                  * or .queue_setup() returned an error
657                  */
658         }
659
660         mutex_lock(&q->mmap_lock);
661         q->num_buffers = allocated_buffers;
662
663         if (ret < 0) {
664                 /*
665                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
666                  * from q->num_buffers.
667                  */
668                 __vb2_queue_free(q, allocated_buffers);
669                 mutex_unlock(&q->mmap_lock);
670                 return ret;
671         }
672         mutex_unlock(&q->mmap_lock);
673
674         /*
675          * Return the number of successfully allocated buffers
676          * to the userspace.
677          */
678         *count = allocated_buffers;
679         q->waiting_for_buffers = !q->is_output;
680
681         return 0;
682 }
683 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
684
685 /**
686  * vb2_core_create_bufs() - Allocate buffers and any required auxiliary structs
687  * @q:          videobuf2 queue
688  * @memory: memory type
689  * @count: requested buffer count
690  * @parg: parameter passed to device driver
691  *
692  * Should be called from vidioc_create_bufs ioctl handler of a driver.
693  * This function:
694  * 1) verifies parameter sanity
695  * 2) calls the .queue_setup() queue operation
696  * 3) performs any necessary memory allocations
697  *
698  * The return values from this function are intended to be directly returned
699  * from vidioc_create_bufs handler in driver.
700  */
701 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
702                 unsigned int *count, const void *parg)
703 {
704         unsigned int num_planes = 0, num_buffers, allocated_buffers;
705         int ret;
706
707         if (q->num_buffers == VB2_MAX_FRAME) {
708                 dprintk(1, "maximum number of buffers already allocated\n");
709                 return -ENOBUFS;
710         }
711
712         if (!q->num_buffers) {
713                 memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
714                 memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
715                 q->memory = memory;
716                 q->waiting_for_buffers = !q->is_output;
717         }
718
719         num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
720
721         /*
722          * Ask the driver, whether the requested number of buffers, planes per
723          * buffer and their sizes are acceptable
724          */
725         ret = call_qop(q, queue_setup, q, parg, &num_buffers,
726                        &num_planes, q->plane_sizes, q->alloc_ctx);
727         if (ret)
728                 return ret;
729
730         /* Finally, allocate buffers and video memory */
731         allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
732                                 num_planes);
733         if (allocated_buffers == 0) {
734                 dprintk(1, "memory allocation failed\n");
735                 return -ENOMEM;
736         }
737
738         /*
739          * Check if driver can handle the so far allocated number of buffers.
740          */
741         if (allocated_buffers < num_buffers) {
742                 num_buffers = allocated_buffers;
743
744                 /*
745                  * q->num_buffers contains the total number of buffers, that the
746                  * queue driver has set up
747                  */
748                 ret = call_qop(q, queue_setup, q, parg, &num_buffers,
749                                &num_planes, q->plane_sizes, q->alloc_ctx);
750
751                 if (!ret && allocated_buffers < num_buffers)
752                         ret = -ENOMEM;
753
754                 /*
755                  * Either the driver has accepted a smaller number of buffers,
756                  * or .queue_setup() returned an error
757                  */
758         }
759
760         mutex_lock(&q->mmap_lock);
761         q->num_buffers += allocated_buffers;
762
763         if (ret < 0) {
764                 /*
765                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
766                  * from q->num_buffers.
767                  */
768                 __vb2_queue_free(q, allocated_buffers);
769                 mutex_unlock(&q->mmap_lock);
770                 return -ENOMEM;
771         }
772         mutex_unlock(&q->mmap_lock);
773
774         /*
775          * Return the number of successfully allocated buffers
776          * to the userspace.
777          */
778         *count = allocated_buffers;
779
780         return 0;
781 }
782 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
783
784 /**
785  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
786  * @vb:         vb2_buffer to which the plane in question belongs to
787  * @plane_no:   plane number for which the address is to be returned
788  *
789  * This function returns a kernel virtual address of a given plane if
790  * such a mapping exist, NULL otherwise.
791  */
792 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
793 {
794         if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
795                 return NULL;
796
797         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
798
799 }
800 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
801
802 /**
803  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
804  * @vb:         vb2_buffer to which the plane in question belongs to
805  * @plane_no:   plane number for which the cookie is to be returned
806  *
807  * This function returns an allocator specific cookie for a given plane if
808  * available, NULL otherwise. The allocator should provide some simple static
809  * inline function, which would convert this cookie to the allocator specific
810  * type that can be used directly by the driver to access the buffer. This can
811  * be for example physical address, pointer to scatter list or IOMMU mapping.
812  */
813 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
814 {
815         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
816                 return NULL;
817
818         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
819 }
820 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
821
822 /**
823  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
824  * @vb:         vb2_buffer returned from the driver
825  * @state:      either VB2_BUF_STATE_DONE if the operation finished successfully,
826  *              VB2_BUF_STATE_ERROR if the operation finished with an error or
827  *              VB2_BUF_STATE_QUEUED if the driver wants to requeue buffers.
828  *              If start_streaming fails then it should return buffers with state
829  *              VB2_BUF_STATE_QUEUED to put them back into the queue.
830  *
831  * This function should be called by the driver after a hardware operation on
832  * a buffer is finished and the buffer may be returned to userspace. The driver
833  * cannot use this buffer anymore until it is queued back to it by videobuf
834  * by the means of buf_queue callback. Only buffers previously queued to the
835  * driver by buf_queue can be passed to this function.
836  *
837  * While streaming a buffer can only be returned in state DONE or ERROR.
838  * The start_streaming op can also return them in case the DMA engine cannot
839  * be started for some reason. In that case the buffers should be returned with
840  * state QUEUED.
841  */
842 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
843 {
844         struct vb2_queue *q = vb->vb2_queue;
845         unsigned long flags;
846         unsigned int plane;
847
848         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
849                 return;
850
851         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
852                     state != VB2_BUF_STATE_ERROR &&
853                     state != VB2_BUF_STATE_QUEUED &&
854                     state != VB2_BUF_STATE_REQUEUEING))
855                 state = VB2_BUF_STATE_ERROR;
856
857 #ifdef CONFIG_VIDEO_ADV_DEBUG
858         /*
859          * Although this is not a callback, it still does have to balance
860          * with the buf_queue op. So update this counter manually.
861          */
862         vb->cnt_buf_done++;
863 #endif
864         dprintk(4, "done processing on buffer %d, state: %d\n",
865                         vb->index, state);
866
867         /* sync buffers */
868         for (plane = 0; plane < vb->num_planes; ++plane)
869                 call_void_memop(vb, finish, vb->planes[plane].mem_priv);
870
871         spin_lock_irqsave(&q->done_lock, flags);
872         if (state == VB2_BUF_STATE_QUEUED ||
873             state == VB2_BUF_STATE_REQUEUEING) {
874                 vb->state = VB2_BUF_STATE_QUEUED;
875         } else {
876                 /* Add the buffer to the done buffers list */
877                 list_add_tail(&vb->done_entry, &q->done_list);
878                 vb->state = state;
879         }
880         atomic_dec(&q->owned_by_drv_count);
881         spin_unlock_irqrestore(&q->done_lock, flags);
882
883         trace_vb2_buf_done(q, vb);
884
885         switch (state) {
886         case VB2_BUF_STATE_QUEUED:
887                 return;
888         case VB2_BUF_STATE_REQUEUEING:
889                 if (q->start_streaming_called)
890                         __enqueue_in_driver(vb);
891                 return;
892         default:
893                 /* Inform any processes that may be waiting for buffers */
894                 wake_up(&q->done_wq);
895                 break;
896         }
897 }
898 EXPORT_SYMBOL_GPL(vb2_buffer_done);
899
900 /**
901  * vb2_discard_done() - discard all buffers marked as DONE
902  * @q:          videobuf2 queue
903  *
904  * This function is intended to be used with suspend/resume operations. It
905  * discards all 'done' buffers as they would be too old to be requested after
906  * resume.
907  *
908  * Drivers must stop the hardware and synchronize with interrupt handlers and/or
909  * delayed works before calling this function to make sure no buffer will be
910  * touched by the driver and/or hardware.
911  */
912 void vb2_discard_done(struct vb2_queue *q)
913 {
914         struct vb2_buffer *vb;
915         unsigned long flags;
916
917         spin_lock_irqsave(&q->done_lock, flags);
918         list_for_each_entry(vb, &q->done_list, done_entry)
919                 vb->state = VB2_BUF_STATE_ERROR;
920         spin_unlock_irqrestore(&q->done_lock, flags);
921 }
922 EXPORT_SYMBOL_GPL(vb2_discard_done);
923
924 /**
925  * __qbuf_mmap() - handle qbuf of an MMAP buffer
926  */
927 static int __qbuf_mmap(struct vb2_buffer *vb, const void *pb)
928 {
929         int ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
930                         vb, pb, vb->planes);
931         return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
932 }
933
934 /**
935  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
936  */
937 static int __qbuf_userptr(struct vb2_buffer *vb, const void *pb)
938 {
939         struct vb2_plane planes[VB2_MAX_PLANES];
940         struct vb2_queue *q = vb->vb2_queue;
941         void *mem_priv;
942         unsigned int plane;
943         int ret;
944         bool reacquired = vb->planes[0].mem_priv == NULL;
945
946         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
947         /* Copy relevant information provided by the userspace */
948         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer, vb, pb, planes);
949         if (ret)
950                 return ret;
951
952         for (plane = 0; plane < vb->num_planes; ++plane) {
953                 /* Skip the plane if already verified */
954                 if (vb->planes[plane].m.userptr &&
955                         vb->planes[plane].m.userptr == planes[plane].m.userptr
956                         && vb->planes[plane].length == planes[plane].length)
957                         continue;
958
959                 dprintk(3, "userspace address for plane %d changed, "
960                                 "reacquiring memory\n", plane);
961
962                 /* Check if the provided plane buffer is large enough */
963                 if (planes[plane].length < q->plane_sizes[plane]) {
964                         dprintk(1, "provided buffer size %u is less than "
965                                                 "setup size %u for plane %d\n",
966                                                 planes[plane].length,
967                                                 q->plane_sizes[plane], plane);
968                         ret = -EINVAL;
969                         goto err;
970                 }
971
972                 /* Release previously acquired memory if present */
973                 if (vb->planes[plane].mem_priv) {
974                         if (!reacquired) {
975                                 reacquired = true;
976                                 call_void_vb_qop(vb, buf_cleanup, vb);
977                         }
978                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
979                 }
980
981                 vb->planes[plane].mem_priv = NULL;
982                 vb->planes[plane].bytesused = 0;
983                 vb->planes[plane].length = 0;
984                 vb->planes[plane].m.userptr = 0;
985                 vb->planes[plane].data_offset = 0;
986
987                 /* Acquire each plane's memory */
988                 mem_priv = call_ptr_memop(vb, get_userptr, q->alloc_ctx[plane],
989                                       planes[plane].m.userptr,
990                                       planes[plane].length, q->dma_dir);
991                 if (IS_ERR_OR_NULL(mem_priv)) {
992                         dprintk(1, "failed acquiring userspace "
993                                                 "memory for plane %d\n", plane);
994                         ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
995                         goto err;
996                 }
997                 vb->planes[plane].mem_priv = mem_priv;
998         }
999
1000         /*
1001          * Now that everything is in order, copy relevant information
1002          * provided by userspace.
1003          */
1004         for (plane = 0; plane < vb->num_planes; ++plane) {
1005                 vb->planes[plane].bytesused = planes[plane].bytesused;
1006                 vb->planes[plane].length = planes[plane].length;
1007                 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1008                 vb->planes[plane].data_offset = planes[plane].data_offset;
1009         }
1010
1011         if (reacquired) {
1012                 /*
1013                  * One or more planes changed, so we must call buf_init to do
1014                  * the driver-specific initialization on the newly acquired
1015                  * buffer, if provided.
1016                  */
1017                 ret = call_vb_qop(vb, buf_init, vb);
1018                 if (ret) {
1019                         dprintk(1, "buffer initialization failed\n");
1020                         goto err;
1021                 }
1022         }
1023
1024         ret = call_vb_qop(vb, buf_prepare, vb);
1025         if (ret) {
1026                 dprintk(1, "buffer preparation failed\n");
1027                 call_void_vb_qop(vb, buf_cleanup, vb);
1028                 goto err;
1029         }
1030
1031         return 0;
1032 err:
1033         /* In case of errors, release planes that were already acquired */
1034         for (plane = 0; plane < vb->num_planes; ++plane) {
1035                 if (vb->planes[plane].mem_priv)
1036                         call_void_memop(vb, put_userptr,
1037                                 vb->planes[plane].mem_priv);
1038                 vb->planes[plane].mem_priv = NULL;
1039                 vb->planes[plane].m.userptr = 0;
1040                 vb->planes[plane].length = 0;
1041         }
1042
1043         return ret;
1044 }
1045
1046 /**
1047  * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1048  */
1049 static int __qbuf_dmabuf(struct vb2_buffer *vb, const void *pb)
1050 {
1051         struct vb2_plane planes[VB2_MAX_PLANES];
1052         struct vb2_queue *q = vb->vb2_queue;
1053         void *mem_priv;
1054         unsigned int plane;
1055         int ret;
1056         bool reacquired = vb->planes[0].mem_priv == NULL;
1057
1058         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1059         /* Copy relevant information provided by the userspace */
1060         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer, vb, pb, planes);
1061         if (ret)
1062                 return ret;
1063
1064         for (plane = 0; plane < vb->num_planes; ++plane) {
1065                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1066
1067                 if (IS_ERR_OR_NULL(dbuf)) {
1068                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1069                                 plane);
1070                         ret = -EINVAL;
1071                         goto err;
1072                 }
1073
1074                 /* use DMABUF size if length is not provided */
1075                 if (planes[plane].length == 0)
1076                         planes[plane].length = dbuf->size;
1077
1078                 if (planes[plane].length < q->plane_sizes[plane]) {
1079                         dprintk(1, "invalid dmabuf length for plane %d\n",
1080                                 plane);
1081                         ret = -EINVAL;
1082                         goto err;
1083                 }
1084
1085                 /* Skip the plane if already verified */
1086                 if (dbuf == vb->planes[plane].dbuf &&
1087                         vb->planes[plane].length == planes[plane].length) {
1088                         dma_buf_put(dbuf);
1089                         continue;
1090                 }
1091
1092                 dprintk(1, "buffer for plane %d changed\n", plane);
1093
1094                 if (!reacquired) {
1095                         reacquired = true;
1096                         call_void_vb_qop(vb, buf_cleanup, vb);
1097                 }
1098
1099                 /* Release previously acquired memory if present */
1100                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1101                 vb->planes[plane].bytesused = 0;
1102                 vb->planes[plane].length = 0;
1103                 vb->planes[plane].m.fd = 0;
1104                 vb->planes[plane].data_offset = 0;
1105
1106                 /* Acquire each plane's memory */
1107                 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1108                         q->alloc_ctx[plane], dbuf, planes[plane].length,
1109                         q->dma_dir);
1110                 if (IS_ERR(mem_priv)) {
1111                         dprintk(1, "failed to attach dmabuf\n");
1112                         ret = PTR_ERR(mem_priv);
1113                         dma_buf_put(dbuf);
1114                         goto err;
1115                 }
1116
1117                 vb->planes[plane].dbuf = dbuf;
1118                 vb->planes[plane].mem_priv = mem_priv;
1119         }
1120
1121         /* TODO: This pins the buffer(s) with  dma_buf_map_attachment()).. but
1122          * really we want to do this just before the DMA, not while queueing
1123          * the buffer(s)..
1124          */
1125         for (plane = 0; plane < vb->num_planes; ++plane) {
1126                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1127                 if (ret) {
1128                         dprintk(1, "failed to map dmabuf for plane %d\n",
1129                                 plane);
1130                         goto err;
1131                 }
1132                 vb->planes[plane].dbuf_mapped = 1;
1133         }
1134
1135         /*
1136          * Now that everything is in order, copy relevant information
1137          * provided by userspace.
1138          */
1139         for (plane = 0; plane < vb->num_planes; ++plane) {
1140                 vb->planes[plane].bytesused = planes[plane].bytesused;
1141                 vb->planes[plane].length = planes[plane].length;
1142                 vb->planes[plane].m.fd = planes[plane].m.fd;
1143                 vb->planes[plane].data_offset = planes[plane].data_offset;
1144         }
1145
1146         if (reacquired) {
1147                 /*
1148                  * Call driver-specific initialization on the newly acquired buffer,
1149                  * if provided.
1150                  */
1151                 ret = call_vb_qop(vb, buf_init, vb);
1152                 if (ret) {
1153                         dprintk(1, "buffer initialization failed\n");
1154                         goto err;
1155                 }
1156         }
1157
1158         ret = call_vb_qop(vb, buf_prepare, vb);
1159         if (ret) {
1160                 dprintk(1, "buffer preparation failed\n");
1161                 call_void_vb_qop(vb, buf_cleanup, vb);
1162                 goto err;
1163         }
1164
1165         return 0;
1166 err:
1167         /* In case of errors, release planes that were already acquired */
1168         __vb2_buf_dmabuf_put(vb);
1169
1170         return ret;
1171 }
1172
1173 /**
1174  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1175  */
1176 static void __enqueue_in_driver(struct vb2_buffer *vb)
1177 {
1178         struct vb2_queue *q = vb->vb2_queue;
1179         unsigned int plane;
1180
1181         vb->state = VB2_BUF_STATE_ACTIVE;
1182         atomic_inc(&q->owned_by_drv_count);
1183
1184         trace_vb2_buf_queue(q, vb);
1185
1186         /* sync buffers */
1187         for (plane = 0; plane < vb->num_planes; ++plane)
1188                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1189
1190         call_void_vb_qop(vb, buf_queue, vb);
1191 }
1192
1193 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1194 {
1195         struct vb2_queue *q = vb->vb2_queue;
1196         int ret;
1197
1198         if (q->error) {
1199                 dprintk(1, "fatal error occurred on queue\n");
1200                 return -EIO;
1201         }
1202
1203         vb->state = VB2_BUF_STATE_PREPARING;
1204
1205         switch (q->memory) {
1206         case VB2_MEMORY_MMAP:
1207                 ret = __qbuf_mmap(vb, pb);
1208                 break;
1209         case VB2_MEMORY_USERPTR:
1210                 ret = __qbuf_userptr(vb, pb);
1211                 break;
1212         case VB2_MEMORY_DMABUF:
1213                 ret = __qbuf_dmabuf(vb, pb);
1214                 break;
1215         default:
1216                 WARN(1, "Invalid queue type\n");
1217                 ret = -EINVAL;
1218         }
1219
1220         if (ret)
1221                 dprintk(1, "buffer preparation failed: %d\n", ret);
1222         vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1223
1224         return ret;
1225 }
1226
1227 /**
1228  * vb2_core_prepare_buf() - Pass ownership of a buffer from userspace
1229  *                      to the kernel
1230  * @q:          videobuf2 queue
1231  * @index:      id number of the buffer
1232  * @pb:         buffer structure passed from userspace to vidioc_prepare_buf
1233  *              handler in driver
1234  *
1235  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1236  * The passed buffer should have been verified.
1237  * This function calls buf_prepare callback in the driver (if provided),
1238  * in which driver-specific buffer initialization can be performed,
1239  *
1240  * The return values from this function are intended to be directly returned
1241  * from vidioc_prepare_buf handler in driver.
1242  */
1243 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1244 {
1245         struct vb2_buffer *vb;
1246         int ret;
1247
1248         vb = q->bufs[index];
1249         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1250                 dprintk(1, "invalid buffer state %d\n",
1251                         vb->state);
1252                 return -EINVAL;
1253         }
1254
1255         ret = __buf_prepare(vb, pb);
1256         if (ret)
1257                 return ret;
1258
1259         /* Fill buffer information for the userspace */
1260         ret = call_bufop(q, fill_user_buffer, vb, pb);
1261         if (ret)
1262                 return ret;
1263
1264         dprintk(1, "prepare of buffer %d succeeded\n", vb->index);
1265
1266         return ret;
1267 }
1268 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1269
1270 /**
1271  * vb2_start_streaming() - Attempt to start streaming.
1272  * @q:          videobuf2 queue
1273  *
1274  * Attempt to start streaming. When this function is called there must be
1275  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1276  * number of buffers required for the DMA engine to function). If the
1277  * @start_streaming op fails it is supposed to return all the driver-owned
1278  * buffers back to vb2 in state QUEUED. Check if that happened and if
1279  * not warn and reclaim them forcefully.
1280  */
1281 static int vb2_start_streaming(struct vb2_queue *q)
1282 {
1283         struct vb2_buffer *vb;
1284         int ret;
1285
1286         /*
1287          * If any buffers were queued before streamon,
1288          * we can now pass them to driver for processing.
1289          */
1290         list_for_each_entry(vb, &q->queued_list, queued_entry)
1291                 __enqueue_in_driver(vb);
1292
1293         /* Tell the driver to start streaming */
1294         q->start_streaming_called = 1;
1295         ret = call_qop(q, start_streaming, q,
1296                        atomic_read(&q->owned_by_drv_count));
1297         if (!ret)
1298                 return 0;
1299
1300         q->start_streaming_called = 0;
1301
1302         dprintk(1, "driver refused to start streaming\n");
1303         /*
1304          * If you see this warning, then the driver isn't cleaning up properly
1305          * after a failed start_streaming(). See the start_streaming()
1306          * documentation in videobuf2-core.h for more information how buffers
1307          * should be returned to vb2 in start_streaming().
1308          */
1309         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1310                 unsigned i;
1311
1312                 /*
1313                  * Forcefully reclaim buffers if the driver did not
1314                  * correctly return them to vb2.
1315                  */
1316                 for (i = 0; i < q->num_buffers; ++i) {
1317                         vb = q->bufs[i];
1318                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1319                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1320                 }
1321                 /* Must be zero now */
1322                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1323         }
1324         /*
1325          * If done_list is not empty, then start_streaming() didn't call
1326          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1327          * STATE_DONE.
1328          */
1329         WARN_ON(!list_empty(&q->done_list));
1330         return ret;
1331 }
1332
1333 /**
1334  * vb2_core_qbuf() - Queue a buffer from userspace
1335  * @q:          videobuf2 queue
1336  * @index:      id number of the buffer
1337  * @pb:         buffer structure passed from userspace to vidioc_qbuf handler
1338  *              in driver
1339  *
1340  * Should be called from vidioc_qbuf ioctl handler of a driver.
1341  * The passed buffer should have been verified.
1342  * This function:
1343  * 1) if necessary, calls buf_prepare callback in the driver (if provided), in
1344  *    which driver-specific buffer initialization can be performed,
1345  * 2) if streaming is on, queues the buffer in driver by the means of buf_queue
1346  *    callback for processing.
1347  *
1348  * The return values from this function are intended to be directly returned
1349  * from vidioc_qbuf handler in driver.
1350  */
1351 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1352 {
1353         struct vb2_buffer *vb;
1354         int ret;
1355
1356         vb = q->bufs[index];
1357
1358         switch (vb->state) {
1359         case VB2_BUF_STATE_DEQUEUED:
1360                 ret = __buf_prepare(vb, pb);
1361                 if (ret)
1362                         return ret;
1363                 break;
1364         case VB2_BUF_STATE_PREPARED:
1365                 break;
1366         case VB2_BUF_STATE_PREPARING:
1367                 dprintk(1, "buffer still being prepared\n");
1368                 return -EINVAL;
1369         default:
1370                 dprintk(1, "invalid buffer state %d\n", vb->state);
1371                 return -EINVAL;
1372         }
1373
1374         /*
1375          * Add to the queued buffers list, a buffer will stay on it until
1376          * dequeued in dqbuf.
1377          */
1378         list_add_tail(&vb->queued_entry, &q->queued_list);
1379         q->queued_count++;
1380         q->waiting_for_buffers = false;
1381         vb->state = VB2_BUF_STATE_QUEUED;
1382
1383         call_bufop(q, set_timestamp, vb, pb);
1384
1385         trace_vb2_qbuf(q, vb);
1386
1387         /*
1388          * If already streaming, give the buffer to driver for processing.
1389          * If not, the buffer will be given to driver on next streamon.
1390          */
1391         if (q->start_streaming_called)
1392                 __enqueue_in_driver(vb);
1393
1394         /* Fill buffer information for the userspace */
1395         ret = call_bufop(q, fill_user_buffer, vb, pb);
1396         if (ret)
1397                 return ret;
1398
1399         /*
1400          * If streamon has been called, and we haven't yet called
1401          * start_streaming() since not enough buffers were queued, and
1402          * we now have reached the minimum number of queued buffers,
1403          * then we can finally call start_streaming().
1404          */
1405         if (q->streaming && !q->start_streaming_called &&
1406             q->queued_count >= q->min_buffers_needed) {
1407                 ret = vb2_start_streaming(q);
1408                 if (ret)
1409                         return ret;
1410         }
1411
1412         dprintk(1, "qbuf of buffer %d succeeded\n", vb->index);
1413         return 0;
1414 }
1415 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1416
1417 /**
1418  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1419  * for dequeuing
1420  *
1421  * Will sleep if required for nonblocking == false.
1422  */
1423 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1424 {
1425         /*
1426          * All operations on vb_done_list are performed under done_lock
1427          * spinlock protection. However, buffers may be removed from
1428          * it and returned to userspace only while holding both driver's
1429          * lock and the done_lock spinlock. Thus we can be sure that as
1430          * long as we hold the driver's lock, the list will remain not
1431          * empty if list_empty() check succeeds.
1432          */
1433
1434         for (;;) {
1435                 int ret;
1436
1437                 if (!q->streaming) {
1438                         dprintk(1, "streaming off, will not wait for buffers\n");
1439                         return -EINVAL;
1440                 }
1441
1442                 if (q->error) {
1443                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1444                         return -EIO;
1445                 }
1446
1447                 if (q->last_buffer_dequeued) {
1448                         dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1449                         return -EPIPE;
1450                 }
1451
1452                 if (!list_empty(&q->done_list)) {
1453                         /*
1454                          * Found a buffer that we were waiting for.
1455                          */
1456                         break;
1457                 }
1458
1459                 if (nonblocking) {
1460                         dprintk(1, "nonblocking and no buffers to dequeue, "
1461                                                                 "will not wait\n");
1462                         return -EAGAIN;
1463                 }
1464
1465                 /*
1466                  * We are streaming and blocking, wait for another buffer to
1467                  * become ready or for streamoff. Driver's lock is released to
1468                  * allow streamoff or qbuf to be called while waiting.
1469                  */
1470                 call_void_qop(q, wait_prepare, q);
1471
1472                 /*
1473                  * All locks have been released, it is safe to sleep now.
1474                  */
1475                 dprintk(3, "will sleep waiting for buffers\n");
1476                 ret = wait_event_interruptible(q->done_wq,
1477                                 !list_empty(&q->done_list) || !q->streaming ||
1478                                 q->error);
1479
1480                 /*
1481                  * We need to reevaluate both conditions again after reacquiring
1482                  * the locks or return an error if one occurred.
1483                  */
1484                 call_void_qop(q, wait_finish, q);
1485                 if (ret) {
1486                         dprintk(1, "sleep was interrupted\n");
1487                         return ret;
1488                 }
1489         }
1490         return 0;
1491 }
1492
1493 /**
1494  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1495  *
1496  * Will sleep if required for nonblocking == false.
1497  */
1498 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1499                              void *pb, int nonblocking)
1500 {
1501         unsigned long flags;
1502         int ret = 0;
1503
1504         /*
1505          * Wait for at least one buffer to become available on the done_list.
1506          */
1507         ret = __vb2_wait_for_done_vb(q, nonblocking);
1508         if (ret)
1509                 return ret;
1510
1511         /*
1512          * Driver's lock has been held since we last verified that done_list
1513          * is not empty, so no need for another list_empty(done_list) check.
1514          */
1515         spin_lock_irqsave(&q->done_lock, flags);
1516         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1517         /*
1518          * Only remove the buffer from done_list if all planes can be
1519          * handled. Some cases such as V4L2 file I/O and DVB have pb
1520          * == NULL; skip the check then as there's nothing to verify.
1521          */
1522         if (pb)
1523                 ret = call_bufop(q, verify_planes_array, *vb, pb);
1524         if (!ret)
1525                 list_del(&(*vb)->done_entry);
1526         spin_unlock_irqrestore(&q->done_lock, flags);
1527
1528         return ret;
1529 }
1530
1531 /**
1532  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
1533  * @q:          videobuf2 queue
1534  *
1535  * This function will wait until all buffers that have been given to the driver
1536  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
1537  * wait_prepare, wait_finish pair. It is intended to be called with all locks
1538  * taken, for example from stop_streaming() callback.
1539  */
1540 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1541 {
1542         if (!q->streaming) {
1543                 dprintk(1, "streaming off, will not wait for buffers\n");
1544                 return -EINVAL;
1545         }
1546
1547         if (q->start_streaming_called)
1548                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1549         return 0;
1550 }
1551 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1552
1553 /**
1554  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1555  */
1556 static void __vb2_dqbuf(struct vb2_buffer *vb)
1557 {
1558         struct vb2_queue *q = vb->vb2_queue;
1559         unsigned int i;
1560
1561         /* nothing to do if the buffer is already dequeued */
1562         if (vb->state == VB2_BUF_STATE_DEQUEUED)
1563                 return;
1564
1565         vb->state = VB2_BUF_STATE_DEQUEUED;
1566
1567         /* unmap DMABUF buffer */
1568         if (q->memory == VB2_MEMORY_DMABUF)
1569                 for (i = 0; i < vb->num_planes; ++i) {
1570                         if (!vb->planes[i].dbuf_mapped)
1571                                 continue;
1572                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1573                         vb->planes[i].dbuf_mapped = 0;
1574                 }
1575 }
1576
1577 /**
1578  * vb2_dqbuf() - Dequeue a buffer to the userspace
1579  * @q:          videobuf2 queue
1580  * @pb:         buffer structure passed from userspace to vidioc_dqbuf handler
1581  *              in driver
1582  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
1583  *               buffers ready for dequeuing are present. Normally the driver
1584  *               would be passing (file->f_flags & O_NONBLOCK) here
1585  *
1586  * Should be called from vidioc_dqbuf ioctl handler of a driver.
1587  * The passed buffer should have been verified.
1588  * This function:
1589  * 1) calls buf_finish callback in the driver (if provided), in which
1590  *    driver can perform any additional operations that may be required before
1591  *    returning the buffer to userspace, such as cache sync,
1592  * 2) the buffer struct members are filled with relevant information for
1593  *    the userspace.
1594  *
1595  * The return values from this function are intended to be directly returned
1596  * from vidioc_dqbuf handler in driver.
1597  */
1598 int vb2_core_dqbuf(struct vb2_queue *q, void *pb, bool nonblocking)
1599 {
1600         struct vb2_buffer *vb = NULL;
1601         int ret;
1602
1603         ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1604         if (ret < 0)
1605                 return ret;
1606
1607         switch (vb->state) {
1608         case VB2_BUF_STATE_DONE:
1609                 dprintk(3, "returning done buffer\n");
1610                 break;
1611         case VB2_BUF_STATE_ERROR:
1612                 dprintk(3, "returning done buffer with errors\n");
1613                 break;
1614         default:
1615                 dprintk(1, "invalid buffer state\n");
1616                 return -EINVAL;
1617         }
1618
1619         call_void_vb_qop(vb, buf_finish, vb);
1620
1621         /* Fill buffer information for the userspace */
1622         ret = call_bufop(q, fill_user_buffer, vb, pb);
1623         if (ret)
1624                 return ret;
1625
1626         /* Remove from videobuf queue */
1627         list_del(&vb->queued_entry);
1628         q->queued_count--;
1629
1630         trace_vb2_dqbuf(q, vb);
1631
1632         /* go back to dequeued state */
1633         __vb2_dqbuf(vb);
1634
1635         dprintk(1, "dqbuf of buffer %d, with state %d\n",
1636                         vb->index, vb->state);
1637
1638         return 0;
1639
1640 }
1641 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1642
1643 /**
1644  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1645  *
1646  * Removes all queued buffers from driver's queue and all buffers queued by
1647  * userspace from videobuf's queue. Returns to state after reqbufs.
1648  */
1649 static void __vb2_queue_cancel(struct vb2_queue *q)
1650 {
1651         unsigned int i;
1652
1653         /*
1654          * Tell driver to stop all transactions and release all queued
1655          * buffers.
1656          */
1657         if (q->start_streaming_called)
1658                 call_void_qop(q, stop_streaming, q);
1659
1660         /*
1661          * If you see this warning, then the driver isn't cleaning up properly
1662          * in stop_streaming(). See the stop_streaming() documentation in
1663          * videobuf2-core.h for more information how buffers should be returned
1664          * to vb2 in stop_streaming().
1665          */
1666         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1667                 for (i = 0; i < q->num_buffers; ++i)
1668                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
1669                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1670                 /* Must be zero now */
1671                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1672         }
1673
1674         q->streaming = 0;
1675         q->start_streaming_called = 0;
1676         q->queued_count = 0;
1677         q->error = 0;
1678
1679         /*
1680          * Remove all buffers from videobuf's list...
1681          */
1682         INIT_LIST_HEAD(&q->queued_list);
1683         /*
1684          * ...and done list; userspace will not receive any buffers it
1685          * has not already dequeued before initiating cancel.
1686          */
1687         INIT_LIST_HEAD(&q->done_list);
1688         atomic_set(&q->owned_by_drv_count, 0);
1689         wake_up_all(&q->done_wq);
1690
1691         /*
1692          * Reinitialize all buffers for next use.
1693          * Make sure to call buf_finish for any queued buffers. Normally
1694          * that's done in dqbuf, but that's not going to happen when we
1695          * cancel the whole queue. Note: this code belongs here, not in
1696          * __vb2_dqbuf() since in vb2_internal_dqbuf() there is a critical
1697          * call to __fill_v4l2_buffer() after buf_finish(). That order can't
1698          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1699          */
1700         for (i = 0; i < q->num_buffers; ++i) {
1701                 struct vb2_buffer *vb = q->bufs[i];
1702
1703                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1704                         vb->state = VB2_BUF_STATE_PREPARED;
1705                         call_void_vb_qop(vb, buf_finish, vb);
1706                 }
1707                 __vb2_dqbuf(vb);
1708         }
1709 }
1710
1711 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1712 {
1713         int ret;
1714
1715         if (type != q->type) {
1716                 dprintk(1, "invalid stream type\n");
1717                 return -EINVAL;
1718         }
1719
1720         if (q->streaming) {
1721                 dprintk(3, "already streaming\n");
1722                 return 0;
1723         }
1724
1725         if (!q->num_buffers) {
1726                 dprintk(1, "no buffers have been allocated\n");
1727                 return -EINVAL;
1728         }
1729
1730         if (q->num_buffers < q->min_buffers_needed) {
1731                 dprintk(1, "need at least %u allocated buffers\n",
1732                                 q->min_buffers_needed);
1733                 return -EINVAL;
1734         }
1735
1736         /*
1737          * Tell driver to start streaming provided sufficient buffers
1738          * are available.
1739          */
1740         if (q->queued_count >= q->min_buffers_needed) {
1741                 ret = vb2_start_streaming(q);
1742                 if (ret) {
1743                         __vb2_queue_cancel(q);
1744                         return ret;
1745                 }
1746         }
1747
1748         q->streaming = 1;
1749
1750         dprintk(3, "successful\n");
1751         return 0;
1752 }
1753 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1754
1755 /**
1756  * vb2_queue_error() - signal a fatal error on the queue
1757  * @q:          videobuf2 queue
1758  *
1759  * Flag that a fatal unrecoverable error has occurred and wake up all processes
1760  * waiting on the queue. Polling will now set POLLERR and queuing and dequeuing
1761  * buffers will return -EIO.
1762  *
1763  * The error flag will be cleared when cancelling the queue, either from
1764  * vb2_streamoff or vb2_queue_release. Drivers should thus not call this
1765  * function before starting the stream, otherwise the error flag will remain set
1766  * until the queue is released when closing the device node.
1767  */
1768 void vb2_queue_error(struct vb2_queue *q)
1769 {
1770         q->error = 1;
1771
1772         wake_up_all(&q->done_wq);
1773 }
1774 EXPORT_SYMBOL_GPL(vb2_queue_error);
1775
1776 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1777 {
1778         if (type != q->type) {
1779                 dprintk(1, "invalid stream type\n");
1780                 return -EINVAL;
1781         }
1782
1783         /*
1784          * Cancel will pause streaming and remove all buffers from the driver
1785          * and videobuf, effectively returning control over them to userspace.
1786          *
1787          * Note that we do this even if q->streaming == 0: if you prepare or
1788          * queue buffers, and then call streamoff without ever having called
1789          * streamon, you would still expect those buffers to be returned to
1790          * their normal dequeued state.
1791          */
1792         __vb2_queue_cancel(q);
1793         q->waiting_for_buffers = !q->is_output;
1794         q->last_buffer_dequeued = false;
1795
1796         dprintk(3, "successful\n");
1797         return 0;
1798 }
1799 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1800
1801 /**
1802  * __find_plane_by_offset() - find plane associated with the given offset off
1803  */
1804 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1805                         unsigned int *_buffer, unsigned int *_plane)
1806 {
1807         struct vb2_buffer *vb;
1808         unsigned int buffer, plane;
1809
1810         /*
1811          * Go over all buffers and their planes, comparing the given offset
1812          * with an offset assigned to each plane. If a match is found,
1813          * return its buffer and plane numbers.
1814          */
1815         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1816                 vb = q->bufs[buffer];
1817
1818                 for (plane = 0; plane < vb->num_planes; ++plane) {
1819                         if (vb->planes[plane].m.offset == off) {
1820                                 *_buffer = buffer;
1821                                 *_plane = plane;
1822                                 return 0;
1823                         }
1824                 }
1825         }
1826
1827         return -EINVAL;
1828 }
1829
1830 /**
1831  * vb2_core_expbuf() - Export a buffer as a file descriptor
1832  * @q:          videobuf2 queue
1833  * @fd:         file descriptor associated with DMABUF (set by driver) *
1834  * @type:       buffer type
1835  * @index:      id number of the buffer
1836  * @plane:      index of the plane to be exported, 0 for single plane queues
1837  * @flags:      flags for newly created file, currently only O_CLOEXEC is
1838  *              supported, refer to manual of open syscall for more details
1839  *
1840  * The return values from this function are intended to be directly returned
1841  * from vidioc_expbuf handler in driver.
1842  */
1843 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1844                 unsigned int index, unsigned int plane, unsigned int flags)
1845 {
1846         struct vb2_buffer *vb = NULL;
1847         struct vb2_plane *vb_plane;
1848         int ret;
1849         struct dma_buf *dbuf;
1850
1851         if (q->memory != VB2_MEMORY_MMAP) {
1852                 dprintk(1, "queue is not currently set up for mmap\n");
1853                 return -EINVAL;
1854         }
1855
1856         if (!q->mem_ops->get_dmabuf) {
1857                 dprintk(1, "queue does not support DMA buffer exporting\n");
1858                 return -EINVAL;
1859         }
1860
1861         if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1862                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1863                 return -EINVAL;
1864         }
1865
1866         if (type != q->type) {
1867                 dprintk(1, "invalid buffer type\n");
1868                 return -EINVAL;
1869         }
1870
1871         if (index >= q->num_buffers) {
1872                 dprintk(1, "buffer index out of range\n");
1873                 return -EINVAL;
1874         }
1875
1876         vb = q->bufs[index];
1877
1878         if (plane >= vb->num_planes) {
1879                 dprintk(1, "buffer plane out of range\n");
1880                 return -EINVAL;
1881         }
1882
1883         if (vb2_fileio_is_active(q)) {
1884                 dprintk(1, "expbuf: file io in progress\n");
1885                 return -EBUSY;
1886         }
1887
1888         vb_plane = &vb->planes[plane];
1889
1890         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1891                                 flags & O_ACCMODE);
1892         if (IS_ERR_OR_NULL(dbuf)) {
1893                 dprintk(1, "failed to export buffer %d, plane %d\n",
1894                         index, plane);
1895                 return -EINVAL;
1896         }
1897
1898         ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1899         if (ret < 0) {
1900                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1901                         index, plane, ret);
1902                 dma_buf_put(dbuf);
1903                 return ret;
1904         }
1905
1906         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1907                 index, plane, ret);
1908         *fd = ret;
1909
1910         return 0;
1911 }
1912 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1913
1914 /**
1915  * vb2_mmap() - map video buffers into application address space
1916  * @q:          videobuf2 queue
1917  * @vma:        vma passed to the mmap file operation handler in the driver
1918  *
1919  * Should be called from mmap file operation handler of a driver.
1920  * This function maps one plane of one of the available video buffers to
1921  * userspace. To map whole video memory allocated on reqbufs, this function
1922  * has to be called once per each plane per each buffer previously allocated.
1923  *
1924  * When the userspace application calls mmap, it passes to it an offset returned
1925  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
1926  * a "cookie", which is then used to identify the plane to be mapped.
1927  * This function finds a plane with a matching offset and a mapping is performed
1928  * by the means of a provided memory operation.
1929  *
1930  * The return values from this function are intended to be directly returned
1931  * from the mmap handler in driver.
1932  */
1933 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1934 {
1935         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1936         struct vb2_buffer *vb;
1937         unsigned int buffer = 0, plane = 0;
1938         int ret;
1939         unsigned long length;
1940
1941         if (q->memory != VB2_MEMORY_MMAP) {
1942                 dprintk(1, "queue is not currently set up for mmap\n");
1943                 return -EINVAL;
1944         }
1945
1946         /*
1947          * Check memory area access mode.
1948          */
1949         if (!(vma->vm_flags & VM_SHARED)) {
1950                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1951                 return -EINVAL;
1952         }
1953         if (q->is_output) {
1954                 if (!(vma->vm_flags & VM_WRITE)) {
1955                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1956                         return -EINVAL;
1957                 }
1958         } else {
1959                 if (!(vma->vm_flags & VM_READ)) {
1960                         dprintk(1, "invalid vma flags, VM_READ needed\n");
1961                         return -EINVAL;
1962                 }
1963         }
1964         if (vb2_fileio_is_active(q)) {
1965                 dprintk(1, "mmap: file io in progress\n");
1966                 return -EBUSY;
1967         }
1968
1969         /*
1970          * Find the plane corresponding to the offset passed by userspace.
1971          */
1972         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1973         if (ret)
1974                 return ret;
1975
1976         vb = q->bufs[buffer];
1977
1978         /*
1979          * MMAP requires page_aligned buffers.
1980          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1981          * so, we need to do the same here.
1982          */
1983         length = PAGE_ALIGN(vb->planes[plane].length);
1984         if (length < (vma->vm_end - vma->vm_start)) {
1985                 dprintk(1,
1986                         "MMAP invalid, as it would overflow buffer length\n");
1987                 return -EINVAL;
1988         }
1989
1990         mutex_lock(&q->mmap_lock);
1991         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1992         mutex_unlock(&q->mmap_lock);
1993         if (ret)
1994                 return ret;
1995
1996         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
1997         return 0;
1998 }
1999 EXPORT_SYMBOL_GPL(vb2_mmap);
2000
2001 #ifndef CONFIG_MMU
2002 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2003                                     unsigned long addr,
2004                                     unsigned long len,
2005                                     unsigned long pgoff,
2006                                     unsigned long flags)
2007 {
2008         unsigned long off = pgoff << PAGE_SHIFT;
2009         struct vb2_buffer *vb;
2010         unsigned int buffer, plane;
2011         void *vaddr;
2012         int ret;
2013
2014         if (q->memory != VB2_MEMORY_MMAP) {
2015                 dprintk(1, "queue is not currently set up for mmap\n");
2016                 return -EINVAL;
2017         }
2018
2019         /*
2020          * Find the plane corresponding to the offset passed by userspace.
2021          */
2022         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2023         if (ret)
2024                 return ret;
2025
2026         vb = q->bufs[buffer];
2027
2028         vaddr = vb2_plane_vaddr(vb, plane);
2029         return vaddr ? (unsigned long)vaddr : -EINVAL;
2030 }
2031 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2032 #endif
2033
2034 /**
2035  * vb2_core_queue_init() - initialize a videobuf2 queue
2036  * @q:          videobuf2 queue; this structure should be allocated in driver
2037  *
2038  * The vb2_queue structure should be allocated by the driver. The driver is
2039  * responsible of clearing it's content and setting initial values for some
2040  * required entries before calling this function.
2041  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
2042  * to the struct vb2_queue description in include/media/videobuf2-core.h
2043  * for more information.
2044  */
2045 int vb2_core_queue_init(struct vb2_queue *q)
2046 {
2047         /*
2048          * Sanity check
2049          */
2050         if (WARN_ON(!q)                   ||
2051             WARN_ON(!q->ops)              ||
2052             WARN_ON(!q->mem_ops)          ||
2053             WARN_ON(!q->type)             ||
2054             WARN_ON(!q->io_modes)         ||
2055             WARN_ON(!q->ops->queue_setup) ||
2056             WARN_ON(!q->ops->buf_queue))
2057                 return -EINVAL;
2058
2059         INIT_LIST_HEAD(&q->queued_list);
2060         INIT_LIST_HEAD(&q->done_list);
2061         spin_lock_init(&q->done_lock);
2062         mutex_init(&q->mmap_lock);
2063         init_waitqueue_head(&q->done_wq);
2064
2065         if (q->buf_struct_size == 0)
2066                 q->buf_struct_size = sizeof(struct vb2_buffer);
2067
2068         if (q->is_output)
2069                 q->dma_dir = DMA_TO_DEVICE;
2070         else
2071                 q->dma_dir = q->use_dma_bidirectional
2072                            ? DMA_BIDIRECTIONAL : DMA_FROM_DEVICE;
2073
2074         return 0;
2075 }
2076 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2077
2078 /**
2079  * vb2_core_queue_release() - stop streaming, release the queue and free memory
2080  * @q:          videobuf2 queue
2081  *
2082  * This function stops streaming and performs necessary clean ups, including
2083  * freeing video buffer memory. The driver is responsible for freeing
2084  * the vb2_queue structure itself.
2085  */
2086 void vb2_core_queue_release(struct vb2_queue *q)
2087 {
2088         __vb2_queue_cancel(q);
2089         mutex_lock(&q->mmap_lock);
2090         __vb2_queue_free(q, q->num_buffers);
2091         mutex_unlock(&q->mmap_lock);
2092 }
2093 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2094
2095 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
2096 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2097 MODULE_LICENSE("GPL");