Merge branches 'pm-cpufreq', 'pm-cpuidle', 'pm-devfreq', 'pm-opp' and 'pm-tools'
[linux-drm-fsl-dcu.git] / drivers / media / v4l2-core / videobuf2-core.c
1 /*
2  * videobuf2-core.c - V4L2 driver helper 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/v4l2-dev.h>
28 #include <media/v4l2-fh.h>
29 #include <media/v4l2-event.h>
30 #include <media/v4l2-common.h>
31 #include <media/videobuf2-core.h>
32
33 static int debug;
34 module_param(debug, int, 0644);
35
36 #define dprintk(level, fmt, arg...)                                           \
37         do {                                                                  \
38                 if (debug >= level)                                           \
39                         pr_info("vb2: %s: " fmt, __func__, ## arg); \
40         } while (0)
41
42 #ifdef CONFIG_VIDEO_ADV_DEBUG
43
44 /*
45  * If advanced debugging is on, then count how often each op is called
46  * successfully, which can either be per-buffer or per-queue.
47  *
48  * This makes it easy to check that the 'init' and 'cleanup'
49  * (and variations thereof) stay balanced.
50  */
51
52 #define log_memop(vb, op)                                               \
53         dprintk(2, "call_memop(%p, %d, %s)%s\n",                        \
54                 (vb)->vb2_queue, (vb)->v4l2_buf.index, #op,             \
55                 (vb)->vb2_queue->mem_ops->op ? "" : " (nop)")
56
57 #define call_memop(vb, op, args...)                                     \
58 ({                                                                      \
59         struct vb2_queue *_q = (vb)->vb2_queue;                         \
60         int err;                                                        \
61                                                                         \
62         log_memop(vb, op);                                              \
63         err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0;              \
64         if (!err)                                                       \
65                 (vb)->cnt_mem_ ## op++;                                 \
66         err;                                                            \
67 })
68
69 #define call_ptr_memop(vb, op, args...)                                 \
70 ({                                                                      \
71         struct vb2_queue *_q = (vb)->vb2_queue;                         \
72         void *ptr;                                                      \
73                                                                         \
74         log_memop(vb, op);                                              \
75         ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL;           \
76         if (!IS_ERR_OR_NULL(ptr))                                       \
77                 (vb)->cnt_mem_ ## op++;                                 \
78         ptr;                                                            \
79 })
80
81 #define call_void_memop(vb, op, args...)                                \
82 ({                                                                      \
83         struct vb2_queue *_q = (vb)->vb2_queue;                         \
84                                                                         \
85         log_memop(vb, op);                                              \
86         if (_q->mem_ops->op)                                            \
87                 _q->mem_ops->op(args);                                  \
88         (vb)->cnt_mem_ ## op++;                                         \
89 })
90
91 #define log_qop(q, op)                                                  \
92         dprintk(2, "call_qop(%p, %s)%s\n", q, #op,                      \
93                 (q)->ops->op ? "" : " (nop)")
94
95 #define call_qop(q, op, args...)                                        \
96 ({                                                                      \
97         int err;                                                        \
98                                                                         \
99         log_qop(q, op);                                                 \
100         err = (q)->ops->op ? (q)->ops->op(args) : 0;                    \
101         if (!err)                                                       \
102                 (q)->cnt_ ## op++;                                      \
103         err;                                                            \
104 })
105
106 #define call_void_qop(q, op, args...)                                   \
107 ({                                                                      \
108         log_qop(q, op);                                                 \
109         if ((q)->ops->op)                                               \
110                 (q)->ops->op(args);                                     \
111         (q)->cnt_ ## op++;                                              \
112 })
113
114 #define log_vb_qop(vb, op, args...)                                     \
115         dprintk(2, "call_vb_qop(%p, %d, %s)%s\n",                       \
116                 (vb)->vb2_queue, (vb)->v4l2_buf.index, #op,             \
117                 (vb)->vb2_queue->ops->op ? "" : " (nop)")
118
119 #define call_vb_qop(vb, op, args...)                                    \
120 ({                                                                      \
121         int err;                                                        \
122                                                                         \
123         log_vb_qop(vb, op);                                             \
124         err = (vb)->vb2_queue->ops->op ?                                \
125                 (vb)->vb2_queue->ops->op(args) : 0;                     \
126         if (!err)                                                       \
127                 (vb)->cnt_ ## op++;                                     \
128         err;                                                            \
129 })
130
131 #define call_void_vb_qop(vb, op, args...)                               \
132 ({                                                                      \
133         log_vb_qop(vb, op);                                             \
134         if ((vb)->vb2_queue->ops->op)                                   \
135                 (vb)->vb2_queue->ops->op(args);                         \
136         (vb)->cnt_ ## op++;                                             \
137 })
138
139 #else
140
141 #define call_memop(vb, op, args...)                                     \
142         ((vb)->vb2_queue->mem_ops->op ?                                 \
143                 (vb)->vb2_queue->mem_ops->op(args) : 0)
144
145 #define call_ptr_memop(vb, op, args...)                                 \
146         ((vb)->vb2_queue->mem_ops->op ?                                 \
147                 (vb)->vb2_queue->mem_ops->op(args) : NULL)
148
149 #define call_void_memop(vb, op, args...)                                \
150         do {                                                            \
151                 if ((vb)->vb2_queue->mem_ops->op)                       \
152                         (vb)->vb2_queue->mem_ops->op(args);             \
153         } while (0)
154
155 #define call_qop(q, op, args...)                                        \
156         ((q)->ops->op ? (q)->ops->op(args) : 0)
157
158 #define call_void_qop(q, op, args...)                                   \
159         do {                                                            \
160                 if ((q)->ops->op)                                       \
161                         (q)->ops->op(args);                             \
162         } while (0)
163
164 #define call_vb_qop(vb, op, args...)                                    \
165         ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
166
167 #define call_void_vb_qop(vb, op, args...)                               \
168         do {                                                            \
169                 if ((vb)->vb2_queue->ops->op)                           \
170                         (vb)->vb2_queue->ops->op(args);                 \
171         } while (0)
172
173 #endif
174
175 /* Flags that are set by the vb2 core */
176 #define V4L2_BUFFER_MASK_FLAGS  (V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
177                                  V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
178                                  V4L2_BUF_FLAG_PREPARED | \
179                                  V4L2_BUF_FLAG_TIMESTAMP_MASK)
180 /* Output buffer flags that should be passed on to the driver */
181 #define V4L2_BUFFER_OUT_FLAGS   (V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | \
182                                  V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_TIMECODE)
183
184 static void __vb2_queue_cancel(struct vb2_queue *q);
185
186 /**
187  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
188  */
189 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
190 {
191         struct vb2_queue *q = vb->vb2_queue;
192         enum dma_data_direction dma_dir =
193                 V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
194         void *mem_priv;
195         int plane;
196
197         /*
198          * Allocate memory for all planes in this buffer
199          * NOTE: mmapped areas should be page aligned
200          */
201         for (plane = 0; plane < vb->num_planes; ++plane) {
202                 unsigned long size = PAGE_ALIGN(q->plane_sizes[plane]);
203
204                 mem_priv = call_ptr_memop(vb, alloc, q->alloc_ctx[plane],
205                                       size, dma_dir, q->gfp_flags);
206                 if (IS_ERR_OR_NULL(mem_priv))
207                         goto free;
208
209                 /* Associate allocator private data with this plane */
210                 vb->planes[plane].mem_priv = mem_priv;
211                 vb->v4l2_planes[plane].length = q->plane_sizes[plane];
212         }
213
214         return 0;
215 free:
216         /* Free already allocated memory if one of the allocations failed */
217         for (; plane > 0; --plane) {
218                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
219                 vb->planes[plane - 1].mem_priv = NULL;
220         }
221
222         return -ENOMEM;
223 }
224
225 /**
226  * __vb2_buf_mem_free() - free memory of the given buffer
227  */
228 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
229 {
230         unsigned int plane;
231
232         for (plane = 0; plane < vb->num_planes; ++plane) {
233                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
234                 vb->planes[plane].mem_priv = NULL;
235                 dprintk(3, "freed plane %d of buffer %d\n", plane,
236                         vb->v4l2_buf.index);
237         }
238 }
239
240 /**
241  * __vb2_buf_userptr_put() - release userspace memory associated with
242  * a USERPTR buffer
243  */
244 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
245 {
246         unsigned int plane;
247
248         for (plane = 0; plane < vb->num_planes; ++plane) {
249                 if (vb->planes[plane].mem_priv)
250                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
251                 vb->planes[plane].mem_priv = NULL;
252         }
253 }
254
255 /**
256  * __vb2_plane_dmabuf_put() - release memory associated with
257  * a DMABUF shared plane
258  */
259 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
260 {
261         if (!p->mem_priv)
262                 return;
263
264         if (p->dbuf_mapped)
265                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
266
267         call_void_memop(vb, detach_dmabuf, p->mem_priv);
268         dma_buf_put(p->dbuf);
269         memset(p, 0, sizeof(*p));
270 }
271
272 /**
273  * __vb2_buf_dmabuf_put() - release memory associated with
274  * a DMABUF shared buffer
275  */
276 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
277 {
278         unsigned int plane;
279
280         for (plane = 0; plane < vb->num_planes; ++plane)
281                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
282 }
283
284 /**
285  * __setup_lengths() - setup initial lengths for every plane in
286  * every buffer on the queue
287  */
288 static void __setup_lengths(struct vb2_queue *q, unsigned int n)
289 {
290         unsigned int buffer, plane;
291         struct vb2_buffer *vb;
292
293         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
294                 vb = q->bufs[buffer];
295                 if (!vb)
296                         continue;
297
298                 for (plane = 0; plane < vb->num_planes; ++plane)
299                         vb->v4l2_planes[plane].length = q->plane_sizes[plane];
300         }
301 }
302
303 /**
304  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
305  * every buffer on the queue
306  */
307 static void __setup_offsets(struct vb2_queue *q, unsigned int n)
308 {
309         unsigned int buffer, plane;
310         struct vb2_buffer *vb;
311         unsigned long off;
312
313         if (q->num_buffers) {
314                 struct v4l2_plane *p;
315                 vb = q->bufs[q->num_buffers - 1];
316                 p = &vb->v4l2_planes[vb->num_planes - 1];
317                 off = PAGE_ALIGN(p->m.mem_offset + p->length);
318         } else {
319                 off = 0;
320         }
321
322         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
323                 vb = q->bufs[buffer];
324                 if (!vb)
325                         continue;
326
327                 for (plane = 0; plane < vb->num_planes; ++plane) {
328                         vb->v4l2_planes[plane].m.mem_offset = off;
329
330                         dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
331                                         buffer, plane, off);
332
333                         off += vb->v4l2_planes[plane].length;
334                         off = PAGE_ALIGN(off);
335                 }
336         }
337 }
338
339 /**
340  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
341  * video buffer memory for all buffers/planes on the queue and initializes the
342  * queue
343  *
344  * Returns the number of buffers successfully allocated.
345  */
346 static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
347                              unsigned int num_buffers, unsigned int num_planes)
348 {
349         unsigned int buffer;
350         struct vb2_buffer *vb;
351         int ret;
352
353         for (buffer = 0; buffer < num_buffers; ++buffer) {
354                 /* Allocate videobuf buffer structures */
355                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
356                 if (!vb) {
357                         dprintk(1, "memory alloc for buffer struct failed\n");
358                         break;
359                 }
360
361                 /* Length stores number of planes for multiplanar buffers */
362                 if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
363                         vb->v4l2_buf.length = num_planes;
364
365                 vb->state = VB2_BUF_STATE_DEQUEUED;
366                 vb->vb2_queue = q;
367                 vb->num_planes = num_planes;
368                 vb->v4l2_buf.index = q->num_buffers + buffer;
369                 vb->v4l2_buf.type = q->type;
370                 vb->v4l2_buf.memory = memory;
371
372                 /* Allocate video buffer memory for the MMAP type */
373                 if (memory == V4L2_MEMORY_MMAP) {
374                         ret = __vb2_buf_mem_alloc(vb);
375                         if (ret) {
376                                 dprintk(1, "failed allocating memory for "
377                                                 "buffer %d\n", buffer);
378                                 kfree(vb);
379                                 break;
380                         }
381                         /*
382                          * Call the driver-provided buffer initialization
383                          * callback, if given. An error in initialization
384                          * results in queue setup failure.
385                          */
386                         ret = call_vb_qop(vb, buf_init, vb);
387                         if (ret) {
388                                 dprintk(1, "buffer %d %p initialization"
389                                         " failed\n", buffer, vb);
390                                 __vb2_buf_mem_free(vb);
391                                 kfree(vb);
392                                 break;
393                         }
394                 }
395
396                 q->bufs[q->num_buffers + buffer] = vb;
397         }
398
399         __setup_lengths(q, buffer);
400         if (memory == V4L2_MEMORY_MMAP)
401                 __setup_offsets(q, buffer);
402
403         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
404                         buffer, num_planes);
405
406         return buffer;
407 }
408
409 /**
410  * __vb2_free_mem() - release all video buffer memory for a given queue
411  */
412 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
413 {
414         unsigned int buffer;
415         struct vb2_buffer *vb;
416
417         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
418              ++buffer) {
419                 vb = q->bufs[buffer];
420                 if (!vb)
421                         continue;
422
423                 /* Free MMAP buffers or release USERPTR buffers */
424                 if (q->memory == V4L2_MEMORY_MMAP)
425                         __vb2_buf_mem_free(vb);
426                 else if (q->memory == V4L2_MEMORY_DMABUF)
427                         __vb2_buf_dmabuf_put(vb);
428                 else
429                         __vb2_buf_userptr_put(vb);
430         }
431 }
432
433 /**
434  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
435  * related information, if no buffers are left return the queue to an
436  * uninitialized state. Might be called even if the queue has already been freed.
437  */
438 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
439 {
440         unsigned int buffer;
441
442         /*
443          * Sanity check: when preparing a buffer the queue lock is released for
444          * a short while (see __buf_prepare for the details), which would allow
445          * a race with a reqbufs which can call this function. Removing the
446          * buffers from underneath __buf_prepare is obviously a bad idea, so we
447          * check if any of the buffers is in the state PREPARING, and if so we
448          * just return -EAGAIN.
449          */
450         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
451              ++buffer) {
452                 if (q->bufs[buffer] == NULL)
453                         continue;
454                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
455                         dprintk(1, "preparing buffers, cannot free\n");
456                         return -EAGAIN;
457                 }
458         }
459
460         /* Call driver-provided cleanup function for each buffer, if provided */
461         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
462              ++buffer) {
463                 struct vb2_buffer *vb = q->bufs[buffer];
464
465                 if (vb && vb->planes[0].mem_priv)
466                         call_void_vb_qop(vb, buf_cleanup, vb);
467         }
468
469         /* Release video buffer memory */
470         __vb2_free_mem(q, buffers);
471
472 #ifdef CONFIG_VIDEO_ADV_DEBUG
473         /*
474          * Check that all the calls were balances during the life-time of this
475          * queue. If not (or if the debug level is 1 or up), then dump the
476          * counters to the kernel log.
477          */
478         if (q->num_buffers) {
479                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
480                                   q->cnt_wait_prepare != q->cnt_wait_finish;
481
482                 if (unbalanced || debug) {
483                         pr_info("vb2: counters for queue %p:%s\n", q,
484                                 unbalanced ? " UNBALANCED!" : "");
485                         pr_info("vb2:     setup: %u start_streaming: %u stop_streaming: %u\n",
486                                 q->cnt_queue_setup, q->cnt_start_streaming,
487                                 q->cnt_stop_streaming);
488                         pr_info("vb2:     wait_prepare: %u wait_finish: %u\n",
489                                 q->cnt_wait_prepare, q->cnt_wait_finish);
490                 }
491                 q->cnt_queue_setup = 0;
492                 q->cnt_wait_prepare = 0;
493                 q->cnt_wait_finish = 0;
494                 q->cnt_start_streaming = 0;
495                 q->cnt_stop_streaming = 0;
496         }
497         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
498                 struct vb2_buffer *vb = q->bufs[buffer];
499                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
500                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
501                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
502                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
503                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
504                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
505                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
506                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
507
508                 if (unbalanced || debug) {
509                         pr_info("vb2:   counters for queue %p, buffer %d:%s\n",
510                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
511                         pr_info("vb2:     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
512                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
513                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
514                         pr_info("vb2:     buf_queue: %u buf_done: %u\n",
515                                 vb->cnt_buf_queue, vb->cnt_buf_done);
516                         pr_info("vb2:     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
517                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
518                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
519                                 vb->cnt_mem_mmap);
520                         pr_info("vb2:     get_userptr: %u put_userptr: %u\n",
521                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
522                         pr_info("vb2:     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
523                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
524                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
525                         pr_info("vb2:     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
526                                 vb->cnt_mem_get_dmabuf,
527                                 vb->cnt_mem_num_users,
528                                 vb->cnt_mem_vaddr,
529                                 vb->cnt_mem_cookie);
530                 }
531         }
532 #endif
533
534         /* Free videobuf buffers */
535         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
536              ++buffer) {
537                 kfree(q->bufs[buffer]);
538                 q->bufs[buffer] = NULL;
539         }
540
541         q->num_buffers -= buffers;
542         if (!q->num_buffers) {
543                 q->memory = 0;
544                 INIT_LIST_HEAD(&q->queued_list);
545         }
546         return 0;
547 }
548
549 /**
550  * __verify_planes_array() - verify that the planes array passed in struct
551  * v4l2_buffer from userspace can be safely used
552  */
553 static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
554 {
555         if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
556                 return 0;
557
558         /* Is memory for copying plane information present? */
559         if (NULL == b->m.planes) {
560                 dprintk(1, "multi-planar buffer passed but "
561                            "planes array not provided\n");
562                 return -EINVAL;
563         }
564
565         if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
566                 dprintk(1, "incorrect planes array length, "
567                            "expected %d, got %d\n", vb->num_planes, b->length);
568                 return -EINVAL;
569         }
570
571         return 0;
572 }
573
574 /**
575  * __verify_length() - Verify that the bytesused value for each plane fits in
576  * the plane length and that the data offset doesn't exceed the bytesused value.
577  */
578 static int __verify_length(struct vb2_buffer *vb, const struct v4l2_buffer *b)
579 {
580         unsigned int length;
581         unsigned int bytesused;
582         unsigned int plane;
583
584         if (!V4L2_TYPE_IS_OUTPUT(b->type))
585                 return 0;
586
587         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
588                 for (plane = 0; plane < vb->num_planes; ++plane) {
589                         length = (b->memory == V4L2_MEMORY_USERPTR ||
590                                   b->memory == V4L2_MEMORY_DMABUF)
591                                ? b->m.planes[plane].length
592                                : vb->v4l2_planes[plane].length;
593                         bytesused = b->m.planes[plane].bytesused
594                                   ? b->m.planes[plane].bytesused : length;
595
596                         if (b->m.planes[plane].bytesused > length)
597                                 return -EINVAL;
598
599                         if (b->m.planes[plane].data_offset > 0 &&
600                             b->m.planes[plane].data_offset >= bytesused)
601                                 return -EINVAL;
602                 }
603         } else {
604                 length = (b->memory == V4L2_MEMORY_USERPTR)
605                        ? b->length : vb->v4l2_planes[0].length;
606                 bytesused = b->bytesused ? b->bytesused : length;
607
608                 if (b->bytesused > length)
609                         return -EINVAL;
610         }
611
612         return 0;
613 }
614
615 /**
616  * __buffer_in_use() - return true if the buffer is in use and
617  * the queue cannot be freed (by the means of REQBUFS(0)) call
618  */
619 static bool __buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
620 {
621         unsigned int plane;
622         for (plane = 0; plane < vb->num_planes; ++plane) {
623                 void *mem_priv = vb->planes[plane].mem_priv;
624                 /*
625                  * If num_users() has not been provided, call_memop
626                  * will return 0, apparently nobody cares about this
627                  * case anyway. If num_users() returns more than 1,
628                  * we are not the only user of the plane's memory.
629                  */
630                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
631                         return true;
632         }
633         return false;
634 }
635
636 /**
637  * __buffers_in_use() - return true if any buffers on the queue are in use and
638  * the queue cannot be freed (by the means of REQBUFS(0)) call
639  */
640 static bool __buffers_in_use(struct vb2_queue *q)
641 {
642         unsigned int buffer;
643         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
644                 if (__buffer_in_use(q, q->bufs[buffer]))
645                         return true;
646         }
647         return false;
648 }
649
650 /**
651  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
652  * returned to userspace
653  */
654 static void __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
655 {
656         struct vb2_queue *q = vb->vb2_queue;
657
658         /* Copy back data such as timestamp, flags, etc. */
659         memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
660         b->reserved2 = vb->v4l2_buf.reserved2;
661         b->reserved = vb->v4l2_buf.reserved;
662
663         if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
664                 /*
665                  * Fill in plane-related data if userspace provided an array
666                  * for it. The caller has already verified memory and size.
667                  */
668                 b->length = vb->num_planes;
669                 memcpy(b->m.planes, vb->v4l2_planes,
670                         b->length * sizeof(struct v4l2_plane));
671         } else {
672                 /*
673                  * We use length and offset in v4l2_planes array even for
674                  * single-planar buffers, but userspace does not.
675                  */
676                 b->length = vb->v4l2_planes[0].length;
677                 b->bytesused = vb->v4l2_planes[0].bytesused;
678                 if (q->memory == V4L2_MEMORY_MMAP)
679                         b->m.offset = vb->v4l2_planes[0].m.mem_offset;
680                 else if (q->memory == V4L2_MEMORY_USERPTR)
681                         b->m.userptr = vb->v4l2_planes[0].m.userptr;
682                 else if (q->memory == V4L2_MEMORY_DMABUF)
683                         b->m.fd = vb->v4l2_planes[0].m.fd;
684         }
685
686         /*
687          * Clear any buffer state related flags.
688          */
689         b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
690         b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;
691         if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
692             V4L2_BUF_FLAG_TIMESTAMP_COPY) {
693                 /*
694                  * For non-COPY timestamps, drop timestamp source bits
695                  * and obtain the timestamp source from the queue.
696                  */
697                 b->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
698                 b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
699         }
700
701         switch (vb->state) {
702         case VB2_BUF_STATE_QUEUED:
703         case VB2_BUF_STATE_ACTIVE:
704                 b->flags |= V4L2_BUF_FLAG_QUEUED;
705                 break;
706         case VB2_BUF_STATE_ERROR:
707                 b->flags |= V4L2_BUF_FLAG_ERROR;
708                 /* fall through */
709         case VB2_BUF_STATE_DONE:
710                 b->flags |= V4L2_BUF_FLAG_DONE;
711                 break;
712         case VB2_BUF_STATE_PREPARED:
713                 b->flags |= V4L2_BUF_FLAG_PREPARED;
714                 break;
715         case VB2_BUF_STATE_PREPARING:
716         case VB2_BUF_STATE_DEQUEUED:
717                 /* nothing */
718                 break;
719         }
720
721         if (__buffer_in_use(q, vb))
722                 b->flags |= V4L2_BUF_FLAG_MAPPED;
723 }
724
725 /**
726  * vb2_querybuf() - query video buffer information
727  * @q:          videobuf queue
728  * @b:          buffer struct passed from userspace to vidioc_querybuf handler
729  *              in driver
730  *
731  * Should be called from vidioc_querybuf ioctl handler in driver.
732  * This function will verify the passed v4l2_buffer structure and fill the
733  * relevant information for the userspace.
734  *
735  * The return values from this function are intended to be directly returned
736  * from vidioc_querybuf handler in driver.
737  */
738 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
739 {
740         struct vb2_buffer *vb;
741         int ret;
742
743         if (b->type != q->type) {
744                 dprintk(1, "wrong buffer type\n");
745                 return -EINVAL;
746         }
747
748         if (b->index >= q->num_buffers) {
749                 dprintk(1, "buffer index out of range\n");
750                 return -EINVAL;
751         }
752         vb = q->bufs[b->index];
753         ret = __verify_planes_array(vb, b);
754         if (!ret)
755                 __fill_v4l2_buffer(vb, b);
756         return ret;
757 }
758 EXPORT_SYMBOL(vb2_querybuf);
759
760 /**
761  * __verify_userptr_ops() - verify that all memory operations required for
762  * USERPTR queue type have been provided
763  */
764 static int __verify_userptr_ops(struct vb2_queue *q)
765 {
766         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
767             !q->mem_ops->put_userptr)
768                 return -EINVAL;
769
770         return 0;
771 }
772
773 /**
774  * __verify_mmap_ops() - verify that all memory operations required for
775  * MMAP queue type have been provided
776  */
777 static int __verify_mmap_ops(struct vb2_queue *q)
778 {
779         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
780             !q->mem_ops->put || !q->mem_ops->mmap)
781                 return -EINVAL;
782
783         return 0;
784 }
785
786 /**
787  * __verify_dmabuf_ops() - verify that all memory operations required for
788  * DMABUF queue type have been provided
789  */
790 static int __verify_dmabuf_ops(struct vb2_queue *q)
791 {
792         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
793             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
794             !q->mem_ops->unmap_dmabuf)
795                 return -EINVAL;
796
797         return 0;
798 }
799
800 /**
801  * __verify_memory_type() - Check whether the memory type and buffer type
802  * passed to a buffer operation are compatible with the queue.
803  */
804 static int __verify_memory_type(struct vb2_queue *q,
805                 enum v4l2_memory memory, enum v4l2_buf_type type)
806 {
807         if (memory != V4L2_MEMORY_MMAP && memory != V4L2_MEMORY_USERPTR &&
808             memory != V4L2_MEMORY_DMABUF) {
809                 dprintk(1, "unsupported memory type\n");
810                 return -EINVAL;
811         }
812
813         if (type != q->type) {
814                 dprintk(1, "requested type is incorrect\n");
815                 return -EINVAL;
816         }
817
818         /*
819          * Make sure all the required memory ops for given memory type
820          * are available.
821          */
822         if (memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
823                 dprintk(1, "MMAP for current setup unsupported\n");
824                 return -EINVAL;
825         }
826
827         if (memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
828                 dprintk(1, "USERPTR for current setup unsupported\n");
829                 return -EINVAL;
830         }
831
832         if (memory == V4L2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
833                 dprintk(1, "DMABUF for current setup unsupported\n");
834                 return -EINVAL;
835         }
836
837         /*
838          * Place the busy tests at the end: -EBUSY can be ignored when
839          * create_bufs is called with count == 0, but count == 0 should still
840          * do the memory and type validation.
841          */
842         if (vb2_fileio_is_active(q)) {
843                 dprintk(1, "file io in progress\n");
844                 return -EBUSY;
845         }
846         return 0;
847 }
848
849 /**
850  * __reqbufs() - Initiate streaming
851  * @q:          videobuf2 queue
852  * @req:        struct passed from userspace to vidioc_reqbufs handler in driver
853  *
854  * Should be called from vidioc_reqbufs ioctl handler of a driver.
855  * This function:
856  * 1) verifies streaming parameters passed from the userspace,
857  * 2) sets up the queue,
858  * 3) negotiates number of buffers and planes per buffer with the driver
859  *    to be used during streaming,
860  * 4) allocates internal buffer structures (struct vb2_buffer), according to
861  *    the agreed parameters,
862  * 5) for MMAP memory type, allocates actual video memory, using the
863  *    memory handling/allocation routines provided during queue initialization
864  *
865  * If req->count is 0, all the memory will be freed instead.
866  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
867  * and the queue is not busy, memory will be reallocated.
868  *
869  * The return values from this function are intended to be directly returned
870  * from vidioc_reqbufs handler in driver.
871  */
872 static int __reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
873 {
874         unsigned int num_buffers, allocated_buffers, num_planes = 0;
875         int ret;
876
877         if (q->streaming) {
878                 dprintk(1, "streaming active\n");
879                 return -EBUSY;
880         }
881
882         if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
883                 /*
884                  * We already have buffers allocated, so first check if they
885                  * are not in use and can be freed.
886                  */
887                 mutex_lock(&q->mmap_lock);
888                 if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
889                         mutex_unlock(&q->mmap_lock);
890                         dprintk(1, "memory in use, cannot free\n");
891                         return -EBUSY;
892                 }
893
894                 /*
895                  * Call queue_cancel to clean up any buffers in the PREPARED or
896                  * QUEUED state which is possible if buffers were prepared or
897                  * queued without ever calling STREAMON.
898                  */
899                 __vb2_queue_cancel(q);
900                 ret = __vb2_queue_free(q, q->num_buffers);
901                 mutex_unlock(&q->mmap_lock);
902                 if (ret)
903                         return ret;
904
905                 /*
906                  * In case of REQBUFS(0) return immediately without calling
907                  * driver's queue_setup() callback and allocating resources.
908                  */
909                 if (req->count == 0)
910                         return 0;
911         }
912
913         /*
914          * Make sure the requested values and current defaults are sane.
915          */
916         num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
917         num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
918         memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
919         memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
920         q->memory = req->memory;
921
922         /*
923          * Ask the driver how many buffers and planes per buffer it requires.
924          * Driver also sets the size and allocator context for each plane.
925          */
926         ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
927                        q->plane_sizes, q->alloc_ctx);
928         if (ret)
929                 return ret;
930
931         /* Finally, allocate buffers and video memory */
932         allocated_buffers = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes);
933         if (allocated_buffers == 0) {
934                 dprintk(1, "memory allocation failed\n");
935                 return -ENOMEM;
936         }
937
938         /*
939          * There is no point in continuing if we can't allocate the minimum
940          * number of buffers needed by this vb2_queue.
941          */
942         if (allocated_buffers < q->min_buffers_needed)
943                 ret = -ENOMEM;
944
945         /*
946          * Check if driver can handle the allocated number of buffers.
947          */
948         if (!ret && allocated_buffers < num_buffers) {
949                 num_buffers = allocated_buffers;
950
951                 ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
952                                &num_planes, q->plane_sizes, q->alloc_ctx);
953
954                 if (!ret && allocated_buffers < num_buffers)
955                         ret = -ENOMEM;
956
957                 /*
958                  * Either the driver has accepted a smaller number of buffers,
959                  * or .queue_setup() returned an error
960                  */
961         }
962
963         mutex_lock(&q->mmap_lock);
964         q->num_buffers = allocated_buffers;
965
966         if (ret < 0) {
967                 /*
968                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
969                  * from q->num_buffers.
970                  */
971                 __vb2_queue_free(q, allocated_buffers);
972                 mutex_unlock(&q->mmap_lock);
973                 return ret;
974         }
975         mutex_unlock(&q->mmap_lock);
976
977         /*
978          * Return the number of successfully allocated buffers
979          * to the userspace.
980          */
981         req->count = allocated_buffers;
982         q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
983
984         return 0;
985 }
986
987 /**
988  * vb2_reqbufs() - Wrapper for __reqbufs() that also verifies the memory and
989  * type values.
990  * @q:          videobuf2 queue
991  * @req:        struct passed from userspace to vidioc_reqbufs handler in driver
992  */
993 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
994 {
995         int ret = __verify_memory_type(q, req->memory, req->type);
996
997         return ret ? ret : __reqbufs(q, req);
998 }
999 EXPORT_SYMBOL_GPL(vb2_reqbufs);
1000
1001 /**
1002  * __create_bufs() - Allocate buffers and any required auxiliary structs
1003  * @q:          videobuf2 queue
1004  * @create:     creation parameters, passed from userspace to vidioc_create_bufs
1005  *              handler in driver
1006  *
1007  * Should be called from vidioc_create_bufs ioctl handler of a driver.
1008  * This function:
1009  * 1) verifies parameter sanity
1010  * 2) calls the .queue_setup() queue operation
1011  * 3) performs any necessary memory allocations
1012  *
1013  * The return values from this function are intended to be directly returned
1014  * from vidioc_create_bufs handler in driver.
1015  */
1016 static int __create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
1017 {
1018         unsigned int num_planes = 0, num_buffers, allocated_buffers;
1019         int ret;
1020
1021         if (q->num_buffers == VIDEO_MAX_FRAME) {
1022                 dprintk(1, "maximum number of buffers already allocated\n");
1023                 return -ENOBUFS;
1024         }
1025
1026         if (!q->num_buffers) {
1027                 memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
1028                 memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
1029                 q->memory = create->memory;
1030                 q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
1031         }
1032
1033         num_buffers = min(create->count, VIDEO_MAX_FRAME - q->num_buffers);
1034
1035         /*
1036          * Ask the driver, whether the requested number of buffers, planes per
1037          * buffer and their sizes are acceptable
1038          */
1039         ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
1040                        &num_planes, q->plane_sizes, q->alloc_ctx);
1041         if (ret)
1042                 return ret;
1043
1044         /* Finally, allocate buffers and video memory */
1045         allocated_buffers = __vb2_queue_alloc(q, create->memory, num_buffers,
1046                                 num_planes);
1047         if (allocated_buffers == 0) {
1048                 dprintk(1, "memory allocation failed\n");
1049                 return -ENOMEM;
1050         }
1051
1052         /*
1053          * Check if driver can handle the so far allocated number of buffers.
1054          */
1055         if (allocated_buffers < num_buffers) {
1056                 num_buffers = allocated_buffers;
1057
1058                 /*
1059                  * q->num_buffers contains the total number of buffers, that the
1060                  * queue driver has set up
1061                  */
1062                 ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
1063                                &num_planes, q->plane_sizes, q->alloc_ctx);
1064
1065                 if (!ret && allocated_buffers < num_buffers)
1066                         ret = -ENOMEM;
1067
1068                 /*
1069                  * Either the driver has accepted a smaller number of buffers,
1070                  * or .queue_setup() returned an error
1071                  */
1072         }
1073
1074         mutex_lock(&q->mmap_lock);
1075         q->num_buffers += allocated_buffers;
1076
1077         if (ret < 0) {
1078                 /*
1079                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
1080                  * from q->num_buffers.
1081                  */
1082                 __vb2_queue_free(q, allocated_buffers);
1083                 mutex_unlock(&q->mmap_lock);
1084                 return -ENOMEM;
1085         }
1086         mutex_unlock(&q->mmap_lock);
1087
1088         /*
1089          * Return the number of successfully allocated buffers
1090          * to the userspace.
1091          */
1092         create->count = allocated_buffers;
1093
1094         return 0;
1095 }
1096
1097 /**
1098  * vb2_create_bufs() - Wrapper for __create_bufs() that also verifies the
1099  * memory and type values.
1100  * @q:          videobuf2 queue
1101  * @create:     creation parameters, passed from userspace to vidioc_create_bufs
1102  *              handler in driver
1103  */
1104 int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
1105 {
1106         int ret = __verify_memory_type(q, create->memory, create->format.type);
1107
1108         create->index = q->num_buffers;
1109         if (create->count == 0)
1110                 return ret != -EBUSY ? ret : 0;
1111         return ret ? ret : __create_bufs(q, create);
1112 }
1113 EXPORT_SYMBOL_GPL(vb2_create_bufs);
1114
1115 /**
1116  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
1117  * @vb:         vb2_buffer to which the plane in question belongs to
1118  * @plane_no:   plane number for which the address is to be returned
1119  *
1120  * This function returns a kernel virtual address of a given plane if
1121  * such a mapping exist, NULL otherwise.
1122  */
1123 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
1124 {
1125         if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
1126                 return NULL;
1127
1128         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
1129
1130 }
1131 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
1132
1133 /**
1134  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
1135  * @vb:         vb2_buffer to which the plane in question belongs to
1136  * @plane_no:   plane number for which the cookie is to be returned
1137  *
1138  * This function returns an allocator specific cookie for a given plane if
1139  * available, NULL otherwise. The allocator should provide some simple static
1140  * inline function, which would convert this cookie to the allocator specific
1141  * type that can be used directly by the driver to access the buffer. This can
1142  * be for example physical address, pointer to scatter list or IOMMU mapping.
1143  */
1144 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
1145 {
1146         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
1147                 return NULL;
1148
1149         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
1150 }
1151 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
1152
1153 /**
1154  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
1155  * @vb:         vb2_buffer returned from the driver
1156  * @state:      either VB2_BUF_STATE_DONE if the operation finished successfully
1157  *              or VB2_BUF_STATE_ERROR if the operation finished with an error.
1158  *              If start_streaming fails then it should return buffers with state
1159  *              VB2_BUF_STATE_QUEUED to put them back into the queue.
1160  *
1161  * This function should be called by the driver after a hardware operation on
1162  * a buffer is finished and the buffer may be returned to userspace. The driver
1163  * cannot use this buffer anymore until it is queued back to it by videobuf
1164  * by the means of buf_queue callback. Only buffers previously queued to the
1165  * driver by buf_queue can be passed to this function.
1166  *
1167  * While streaming a buffer can only be returned in state DONE or ERROR.
1168  * The start_streaming op can also return them in case the DMA engine cannot
1169  * be started for some reason. In that case the buffers should be returned with
1170  * state QUEUED.
1171  */
1172 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
1173 {
1174         struct vb2_queue *q = vb->vb2_queue;
1175         unsigned long flags;
1176         unsigned int plane;
1177
1178         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
1179                 return;
1180
1181         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
1182                     state != VB2_BUF_STATE_ERROR &&
1183                     state != VB2_BUF_STATE_QUEUED))
1184                 state = VB2_BUF_STATE_ERROR;
1185
1186 #ifdef CONFIG_VIDEO_ADV_DEBUG
1187         /*
1188          * Although this is not a callback, it still does have to balance
1189          * with the buf_queue op. So update this counter manually.
1190          */
1191         vb->cnt_buf_done++;
1192 #endif
1193         dprintk(4, "done processing on buffer %d, state: %d\n",
1194                         vb->v4l2_buf.index, state);
1195
1196         /* sync buffers */
1197         for (plane = 0; plane < vb->num_planes; ++plane)
1198                 call_void_memop(vb, finish, vb->planes[plane].mem_priv);
1199
1200         /* Add the buffer to the done buffers list */
1201         spin_lock_irqsave(&q->done_lock, flags);
1202         vb->state = state;
1203         if (state != VB2_BUF_STATE_QUEUED)
1204                 list_add_tail(&vb->done_entry, &q->done_list);
1205         atomic_dec(&q->owned_by_drv_count);
1206         spin_unlock_irqrestore(&q->done_lock, flags);
1207
1208         if (state == VB2_BUF_STATE_QUEUED)
1209                 return;
1210
1211         /* Inform any processes that may be waiting for buffers */
1212         wake_up(&q->done_wq);
1213 }
1214 EXPORT_SYMBOL_GPL(vb2_buffer_done);
1215
1216 /**
1217  * vb2_discard_done() - discard all buffers marked as DONE
1218  * @q:          videobuf2 queue
1219  *
1220  * This function is intended to be used with suspend/resume operations. It
1221  * discards all 'done' buffers as they would be too old to be requested after
1222  * resume.
1223  *
1224  * Drivers must stop the hardware and synchronize with interrupt handlers and/or
1225  * delayed works before calling this function to make sure no buffer will be
1226  * touched by the driver and/or hardware.
1227  */
1228 void vb2_discard_done(struct vb2_queue *q)
1229 {
1230         struct vb2_buffer *vb;
1231         unsigned long flags;
1232
1233         spin_lock_irqsave(&q->done_lock, flags);
1234         list_for_each_entry(vb, &q->done_list, done_entry)
1235                 vb->state = VB2_BUF_STATE_ERROR;
1236         spin_unlock_irqrestore(&q->done_lock, flags);
1237 }
1238 EXPORT_SYMBOL_GPL(vb2_discard_done);
1239
1240 /**
1241  * __fill_vb2_buffer() - fill a vb2_buffer with information provided in a
1242  * v4l2_buffer by the userspace. The caller has already verified that struct
1243  * v4l2_buffer has a valid number of planes.
1244  */
1245 static void __fill_vb2_buffer(struct vb2_buffer *vb, const struct v4l2_buffer *b,
1246                                 struct v4l2_plane *v4l2_planes)
1247 {
1248         unsigned int plane;
1249
1250         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
1251                 if (b->memory == V4L2_MEMORY_USERPTR) {
1252                         for (plane = 0; plane < vb->num_planes; ++plane) {
1253                                 v4l2_planes[plane].m.userptr =
1254                                         b->m.planes[plane].m.userptr;
1255                                 v4l2_planes[plane].length =
1256                                         b->m.planes[plane].length;
1257                         }
1258                 }
1259                 if (b->memory == V4L2_MEMORY_DMABUF) {
1260                         for (plane = 0; plane < vb->num_planes; ++plane) {
1261                                 v4l2_planes[plane].m.fd =
1262                                         b->m.planes[plane].m.fd;
1263                                 v4l2_planes[plane].length =
1264                                         b->m.planes[plane].length;
1265                         }
1266                 }
1267
1268                 /* Fill in driver-provided information for OUTPUT types */
1269                 if (V4L2_TYPE_IS_OUTPUT(b->type)) {
1270                         /*
1271                          * Will have to go up to b->length when API starts
1272                          * accepting variable number of planes.
1273                          *
1274                          * If bytesused == 0 for the output buffer, then fall
1275                          * back to the full buffer size. In that case
1276                          * userspace clearly never bothered to set it and
1277                          * it's a safe assumption that they really meant to
1278                          * use the full plane sizes.
1279                          */
1280                         for (plane = 0; plane < vb->num_planes; ++plane) {
1281                                 struct v4l2_plane *pdst = &v4l2_planes[plane];
1282                                 struct v4l2_plane *psrc = &b->m.planes[plane];
1283
1284                                 pdst->bytesused = psrc->bytesused ?
1285                                         psrc->bytesused : pdst->length;
1286                                 pdst->data_offset = psrc->data_offset;
1287                         }
1288                 }
1289         } else {
1290                 /*
1291                  * Single-planar buffers do not use planes array,
1292                  * so fill in relevant v4l2_buffer struct fields instead.
1293                  * In videobuf we use our internal V4l2_planes struct for
1294                  * single-planar buffers as well, for simplicity.
1295                  *
1296                  * If bytesused == 0 for the output buffer, then fall back
1297                  * to the full buffer size as that's a sensible default.
1298                  */
1299                 if (b->memory == V4L2_MEMORY_USERPTR) {
1300                         v4l2_planes[0].m.userptr = b->m.userptr;
1301                         v4l2_planes[0].length = b->length;
1302                 }
1303
1304                 if (b->memory == V4L2_MEMORY_DMABUF) {
1305                         v4l2_planes[0].m.fd = b->m.fd;
1306                         v4l2_planes[0].length = b->length;
1307                 }
1308
1309                 if (V4L2_TYPE_IS_OUTPUT(b->type))
1310                         v4l2_planes[0].bytesused = b->bytesused ?
1311                                 b->bytesused : v4l2_planes[0].length;
1312                 else
1313                         v4l2_planes[0].bytesused = 0;
1314
1315         }
1316
1317         /* Zero flags that the vb2 core handles */
1318         vb->v4l2_buf.flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
1319         if ((vb->vb2_queue->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
1320             V4L2_BUF_FLAG_TIMESTAMP_COPY || !V4L2_TYPE_IS_OUTPUT(b->type)) {
1321                 /*
1322                  * Non-COPY timestamps and non-OUTPUT queues will get
1323                  * their timestamp and timestamp source flags from the
1324                  * queue.
1325                  */
1326                 vb->v4l2_buf.flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
1327         }
1328
1329         if (V4L2_TYPE_IS_OUTPUT(b->type)) {
1330                 /*
1331                  * For output buffers mask out the timecode flag:
1332                  * this will be handled later in vb2_internal_qbuf().
1333                  * The 'field' is valid metadata for this output buffer
1334                  * and so that needs to be copied here.
1335                  */
1336                 vb->v4l2_buf.flags &= ~V4L2_BUF_FLAG_TIMECODE;
1337                 vb->v4l2_buf.field = b->field;
1338         } else {
1339                 /* Zero any output buffer flags as this is a capture buffer */
1340                 vb->v4l2_buf.flags &= ~V4L2_BUFFER_OUT_FLAGS;
1341         }
1342 }
1343
1344 /**
1345  * __qbuf_mmap() - handle qbuf of an MMAP buffer
1346  */
1347 static int __qbuf_mmap(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1348 {
1349         __fill_vb2_buffer(vb, b, vb->v4l2_planes);
1350         return call_vb_qop(vb, buf_prepare, vb);
1351 }
1352
1353 /**
1354  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
1355  */
1356 static int __qbuf_userptr(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1357 {
1358         struct v4l2_plane planes[VIDEO_MAX_PLANES];
1359         struct vb2_queue *q = vb->vb2_queue;
1360         void *mem_priv;
1361         unsigned int plane;
1362         int ret;
1363         enum dma_data_direction dma_dir =
1364                 V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1365         bool reacquired = vb->planes[0].mem_priv == NULL;
1366
1367         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1368         /* Copy relevant information provided by the userspace */
1369         __fill_vb2_buffer(vb, b, planes);
1370
1371         for (plane = 0; plane < vb->num_planes; ++plane) {
1372                 /* Skip the plane if already verified */
1373                 if (vb->v4l2_planes[plane].m.userptr &&
1374                     vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
1375                     && vb->v4l2_planes[plane].length == planes[plane].length)
1376                         continue;
1377
1378                 dprintk(3, "userspace address for plane %d changed, "
1379                                 "reacquiring memory\n", plane);
1380
1381                 /* Check if the provided plane buffer is large enough */
1382                 if (planes[plane].length < q->plane_sizes[plane]) {
1383                         dprintk(1, "provided buffer size %u is less than "
1384                                                 "setup size %u for plane %d\n",
1385                                                 planes[plane].length,
1386                                                 q->plane_sizes[plane], plane);
1387                         ret = -EINVAL;
1388                         goto err;
1389                 }
1390
1391                 /* Release previously acquired memory if present */
1392                 if (vb->planes[plane].mem_priv) {
1393                         if (!reacquired) {
1394                                 reacquired = true;
1395                                 call_void_vb_qop(vb, buf_cleanup, vb);
1396                         }
1397                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1398                 }
1399
1400                 vb->planes[plane].mem_priv = NULL;
1401                 memset(&vb->v4l2_planes[plane], 0, sizeof(struct v4l2_plane));
1402
1403                 /* Acquire each plane's memory */
1404                 mem_priv = call_ptr_memop(vb, get_userptr, q->alloc_ctx[plane],
1405                                       planes[plane].m.userptr,
1406                                       planes[plane].length, dma_dir);
1407                 if (IS_ERR_OR_NULL(mem_priv)) {
1408                         dprintk(1, "failed acquiring userspace "
1409                                                 "memory for plane %d\n", plane);
1410                         ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
1411                         goto err;
1412                 }
1413                 vb->planes[plane].mem_priv = mem_priv;
1414         }
1415
1416         /*
1417          * Now that everything is in order, copy relevant information
1418          * provided by userspace.
1419          */
1420         for (plane = 0; plane < vb->num_planes; ++plane)
1421                 vb->v4l2_planes[plane] = planes[plane];
1422
1423         if (reacquired) {
1424                 /*
1425                  * One or more planes changed, so we must call buf_init to do
1426                  * the driver-specific initialization on the newly acquired
1427                  * buffer, if provided.
1428                  */
1429                 ret = call_vb_qop(vb, buf_init, vb);
1430                 if (ret) {
1431                         dprintk(1, "buffer initialization failed\n");
1432                         goto err;
1433                 }
1434         }
1435
1436         ret = call_vb_qop(vb, buf_prepare, vb);
1437         if (ret) {
1438                 dprintk(1, "buffer preparation failed\n");
1439                 call_void_vb_qop(vb, buf_cleanup, vb);
1440                 goto err;
1441         }
1442
1443         return 0;
1444 err:
1445         /* In case of errors, release planes that were already acquired */
1446         for (plane = 0; plane < vb->num_planes; ++plane) {
1447                 if (vb->planes[plane].mem_priv)
1448                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1449                 vb->planes[plane].mem_priv = NULL;
1450                 vb->v4l2_planes[plane].m.userptr = 0;
1451                 vb->v4l2_planes[plane].length = 0;
1452         }
1453
1454         return ret;
1455 }
1456
1457 /**
1458  * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1459  */
1460 static int __qbuf_dmabuf(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1461 {
1462         struct v4l2_plane planes[VIDEO_MAX_PLANES];
1463         struct vb2_queue *q = vb->vb2_queue;
1464         void *mem_priv;
1465         unsigned int plane;
1466         int ret;
1467         enum dma_data_direction dma_dir =
1468                 V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1469         bool reacquired = vb->planes[0].mem_priv == NULL;
1470
1471         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1472         /* Copy relevant information provided by the userspace */
1473         __fill_vb2_buffer(vb, b, planes);
1474
1475         for (plane = 0; plane < vb->num_planes; ++plane) {
1476                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1477
1478                 if (IS_ERR_OR_NULL(dbuf)) {
1479                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1480                                 plane);
1481                         ret = -EINVAL;
1482                         goto err;
1483                 }
1484
1485                 /* use DMABUF size if length is not provided */
1486                 if (planes[plane].length == 0)
1487                         planes[plane].length = dbuf->size;
1488
1489                 if (planes[plane].length < q->plane_sizes[plane]) {
1490                         dprintk(1, "invalid dmabuf length for plane %d\n",
1491                                 plane);
1492                         ret = -EINVAL;
1493                         goto err;
1494                 }
1495
1496                 /* Skip the plane if already verified */
1497                 if (dbuf == vb->planes[plane].dbuf &&
1498                     vb->v4l2_planes[plane].length == planes[plane].length) {
1499                         dma_buf_put(dbuf);
1500                         continue;
1501                 }
1502
1503                 dprintk(1, "buffer for plane %d changed\n", plane);
1504
1505                 if (!reacquired) {
1506                         reacquired = true;
1507                         call_void_vb_qop(vb, buf_cleanup, vb);
1508                 }
1509
1510                 /* Release previously acquired memory if present */
1511                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1512                 memset(&vb->v4l2_planes[plane], 0, sizeof(struct v4l2_plane));
1513
1514                 /* Acquire each plane's memory */
1515                 mem_priv = call_ptr_memop(vb, attach_dmabuf, q->alloc_ctx[plane],
1516                         dbuf, planes[plane].length, dma_dir);
1517                 if (IS_ERR(mem_priv)) {
1518                         dprintk(1, "failed to attach dmabuf\n");
1519                         ret = PTR_ERR(mem_priv);
1520                         dma_buf_put(dbuf);
1521                         goto err;
1522                 }
1523
1524                 vb->planes[plane].dbuf = dbuf;
1525                 vb->planes[plane].mem_priv = mem_priv;
1526         }
1527
1528         /* TODO: This pins the buffer(s) with  dma_buf_map_attachment()).. but
1529          * really we want to do this just before the DMA, not while queueing
1530          * the buffer(s)..
1531          */
1532         for (plane = 0; plane < vb->num_planes; ++plane) {
1533                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1534                 if (ret) {
1535                         dprintk(1, "failed to map dmabuf for plane %d\n",
1536                                 plane);
1537                         goto err;
1538                 }
1539                 vb->planes[plane].dbuf_mapped = 1;
1540         }
1541
1542         /*
1543          * Now that everything is in order, copy relevant information
1544          * provided by userspace.
1545          */
1546         for (plane = 0; plane < vb->num_planes; ++plane)
1547                 vb->v4l2_planes[plane] = planes[plane];
1548
1549         if (reacquired) {
1550                 /*
1551                  * Call driver-specific initialization on the newly acquired buffer,
1552                  * if provided.
1553                  */
1554                 ret = call_vb_qop(vb, buf_init, vb);
1555                 if (ret) {
1556                         dprintk(1, "buffer initialization failed\n");
1557                         goto err;
1558                 }
1559         }
1560
1561         ret = call_vb_qop(vb, buf_prepare, vb);
1562         if (ret) {
1563                 dprintk(1, "buffer preparation failed\n");
1564                 call_void_vb_qop(vb, buf_cleanup, vb);
1565                 goto err;
1566         }
1567
1568         return 0;
1569 err:
1570         /* In case of errors, release planes that were already acquired */
1571         __vb2_buf_dmabuf_put(vb);
1572
1573         return ret;
1574 }
1575
1576 /**
1577  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1578  */
1579 static void __enqueue_in_driver(struct vb2_buffer *vb)
1580 {
1581         struct vb2_queue *q = vb->vb2_queue;
1582         unsigned int plane;
1583
1584         vb->state = VB2_BUF_STATE_ACTIVE;
1585         atomic_inc(&q->owned_by_drv_count);
1586
1587         /* sync buffers */
1588         for (plane = 0; plane < vb->num_planes; ++plane)
1589                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1590
1591         call_void_vb_qop(vb, buf_queue, vb);
1592 }
1593
1594 static int __buf_prepare(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1595 {
1596         struct vb2_queue *q = vb->vb2_queue;
1597         int ret;
1598
1599         ret = __verify_length(vb, b);
1600         if (ret < 0) {
1601                 dprintk(1, "plane parameters verification failed: %d\n", ret);
1602                 return ret;
1603         }
1604         if (b->field == V4L2_FIELD_ALTERNATE && V4L2_TYPE_IS_OUTPUT(q->type)) {
1605                 /*
1606                  * If the format's field is ALTERNATE, then the buffer's field
1607                  * should be either TOP or BOTTOM, not ALTERNATE since that
1608                  * makes no sense. The driver has to know whether the
1609                  * buffer represents a top or a bottom field in order to
1610                  * program any DMA correctly. Using ALTERNATE is wrong, since
1611                  * that just says that it is either a top or a bottom field,
1612                  * but not which of the two it is.
1613                  */
1614                 dprintk(1, "the field is incorrectly set to ALTERNATE for an output buffer\n");
1615                 return -EINVAL;
1616         }
1617
1618         if (q->error) {
1619                 dprintk(1, "fatal error occurred on queue\n");
1620                 return -EIO;
1621         }
1622
1623         vb->state = VB2_BUF_STATE_PREPARING;
1624         vb->v4l2_buf.timestamp.tv_sec = 0;
1625         vb->v4l2_buf.timestamp.tv_usec = 0;
1626         vb->v4l2_buf.sequence = 0;
1627
1628         switch (q->memory) {
1629         case V4L2_MEMORY_MMAP:
1630                 ret = __qbuf_mmap(vb, b);
1631                 break;
1632         case V4L2_MEMORY_USERPTR:
1633                 down_read(&current->mm->mmap_sem);
1634                 ret = __qbuf_userptr(vb, b);
1635                 up_read(&current->mm->mmap_sem);
1636                 break;
1637         case V4L2_MEMORY_DMABUF:
1638                 ret = __qbuf_dmabuf(vb, b);
1639                 break;
1640         default:
1641                 WARN(1, "Invalid queue type\n");
1642                 ret = -EINVAL;
1643         }
1644
1645         if (ret)
1646                 dprintk(1, "buffer preparation failed: %d\n", ret);
1647         vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1648
1649         return ret;
1650 }
1651
1652 static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
1653                                     const char *opname)
1654 {
1655         if (b->type != q->type) {
1656                 dprintk(1, "%s: invalid buffer type\n", opname);
1657                 return -EINVAL;
1658         }
1659
1660         if (b->index >= q->num_buffers) {
1661                 dprintk(1, "%s: buffer index out of range\n", opname);
1662                 return -EINVAL;
1663         }
1664
1665         if (q->bufs[b->index] == NULL) {
1666                 /* Should never happen */
1667                 dprintk(1, "%s: buffer is NULL\n", opname);
1668                 return -EINVAL;
1669         }
1670
1671         if (b->memory != q->memory) {
1672                 dprintk(1, "%s: invalid memory type\n", opname);
1673                 return -EINVAL;
1674         }
1675
1676         return __verify_planes_array(q->bufs[b->index], b);
1677 }
1678
1679 /**
1680  * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
1681  * @q:          videobuf2 queue
1682  * @b:          buffer structure passed from userspace to vidioc_prepare_buf
1683  *              handler in driver
1684  *
1685  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1686  * This function:
1687  * 1) verifies the passed buffer,
1688  * 2) calls buf_prepare callback in the driver (if provided), in which
1689  *    driver-specific buffer initialization can be performed,
1690  *
1691  * The return values from this function are intended to be directly returned
1692  * from vidioc_prepare_buf handler in driver.
1693  */
1694 int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
1695 {
1696         struct vb2_buffer *vb;
1697         int ret;
1698
1699         if (vb2_fileio_is_active(q)) {
1700                 dprintk(1, "file io in progress\n");
1701                 return -EBUSY;
1702         }
1703
1704         ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
1705         if (ret)
1706                 return ret;
1707
1708         vb = q->bufs[b->index];
1709         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1710                 dprintk(1, "invalid buffer state %d\n",
1711                         vb->state);
1712                 return -EINVAL;
1713         }
1714
1715         ret = __buf_prepare(vb, b);
1716         if (!ret) {
1717                 /* Fill buffer information for the userspace */
1718                 __fill_v4l2_buffer(vb, b);
1719
1720                 dprintk(1, "prepare of buffer %d succeeded\n", vb->v4l2_buf.index);
1721         }
1722         return ret;
1723 }
1724 EXPORT_SYMBOL_GPL(vb2_prepare_buf);
1725
1726 /**
1727  * vb2_start_streaming() - Attempt to start streaming.
1728  * @q:          videobuf2 queue
1729  *
1730  * Attempt to start streaming. When this function is called there must be
1731  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1732  * number of buffers required for the DMA engine to function). If the
1733  * @start_streaming op fails it is supposed to return all the driver-owned
1734  * buffers back to vb2 in state QUEUED. Check if that happened and if
1735  * not warn and reclaim them forcefully.
1736  */
1737 static int vb2_start_streaming(struct vb2_queue *q)
1738 {
1739         struct vb2_buffer *vb;
1740         int ret;
1741
1742         /*
1743          * If any buffers were queued before streamon,
1744          * we can now pass them to driver for processing.
1745          */
1746         list_for_each_entry(vb, &q->queued_list, queued_entry)
1747                 __enqueue_in_driver(vb);
1748
1749         /* Tell the driver to start streaming */
1750         q->start_streaming_called = 1;
1751         ret = call_qop(q, start_streaming, q,
1752                        atomic_read(&q->owned_by_drv_count));
1753         if (!ret)
1754                 return 0;
1755
1756         q->start_streaming_called = 0;
1757
1758         dprintk(1, "driver refused to start streaming\n");
1759         /*
1760          * If you see this warning, then the driver isn't cleaning up properly
1761          * after a failed start_streaming(). See the start_streaming()
1762          * documentation in videobuf2-core.h for more information how buffers
1763          * should be returned to vb2 in start_streaming().
1764          */
1765         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1766                 unsigned i;
1767
1768                 /*
1769                  * Forcefully reclaim buffers if the driver did not
1770                  * correctly return them to vb2.
1771                  */
1772                 for (i = 0; i < q->num_buffers; ++i) {
1773                         vb = q->bufs[i];
1774                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1775                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1776                 }
1777                 /* Must be zero now */
1778                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1779         }
1780         /*
1781          * If done_list is not empty, then start_streaming() didn't call
1782          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1783          * STATE_DONE.
1784          */
1785         WARN_ON(!list_empty(&q->done_list));
1786         return ret;
1787 }
1788
1789 static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
1790 {
1791         int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
1792         struct vb2_buffer *vb;
1793
1794         if (ret)
1795                 return ret;
1796
1797         vb = q->bufs[b->index];
1798
1799         switch (vb->state) {
1800         case VB2_BUF_STATE_DEQUEUED:
1801                 ret = __buf_prepare(vb, b);
1802                 if (ret)
1803                         return ret;
1804                 break;
1805         case VB2_BUF_STATE_PREPARED:
1806                 break;
1807         case VB2_BUF_STATE_PREPARING:
1808                 dprintk(1, "buffer still being prepared\n");
1809                 return -EINVAL;
1810         default:
1811                 dprintk(1, "invalid buffer state %d\n", vb->state);
1812                 return -EINVAL;
1813         }
1814
1815         /*
1816          * Add to the queued buffers list, a buffer will stay on it until
1817          * dequeued in dqbuf.
1818          */
1819         list_add_tail(&vb->queued_entry, &q->queued_list);
1820         q->queued_count++;
1821         q->waiting_for_buffers = false;
1822         vb->state = VB2_BUF_STATE_QUEUED;
1823         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1824                 /*
1825                  * For output buffers copy the timestamp if needed,
1826                  * and the timecode field and flag if needed.
1827                  */
1828                 if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
1829                     V4L2_BUF_FLAG_TIMESTAMP_COPY)
1830                         vb->v4l2_buf.timestamp = b->timestamp;
1831                 vb->v4l2_buf.flags |= b->flags & V4L2_BUF_FLAG_TIMECODE;
1832                 if (b->flags & V4L2_BUF_FLAG_TIMECODE)
1833                         vb->v4l2_buf.timecode = b->timecode;
1834         }
1835
1836         /*
1837          * If already streaming, give the buffer to driver for processing.
1838          * If not, the buffer will be given to driver on next streamon.
1839          */
1840         if (q->start_streaming_called)
1841                 __enqueue_in_driver(vb);
1842
1843         /* Fill buffer information for the userspace */
1844         __fill_v4l2_buffer(vb, b);
1845
1846         /*
1847          * If streamon has been called, and we haven't yet called
1848          * start_streaming() since not enough buffers were queued, and
1849          * we now have reached the minimum number of queued buffers,
1850          * then we can finally call start_streaming().
1851          */
1852         if (q->streaming && !q->start_streaming_called &&
1853             q->queued_count >= q->min_buffers_needed) {
1854                 ret = vb2_start_streaming(q);
1855                 if (ret)
1856                         return ret;
1857         }
1858
1859         dprintk(1, "qbuf of buffer %d succeeded\n", vb->v4l2_buf.index);
1860         return 0;
1861 }
1862
1863 /**
1864  * vb2_qbuf() - Queue a buffer from userspace
1865  * @q:          videobuf2 queue
1866  * @b:          buffer structure passed from userspace to vidioc_qbuf handler
1867  *              in driver
1868  *
1869  * Should be called from vidioc_qbuf ioctl handler of a driver.
1870  * This function:
1871  * 1) verifies the passed buffer,
1872  * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
1873  *    which driver-specific buffer initialization can be performed,
1874  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
1875  *    callback for processing.
1876  *
1877  * The return values from this function are intended to be directly returned
1878  * from vidioc_qbuf handler in driver.
1879  */
1880 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
1881 {
1882         if (vb2_fileio_is_active(q)) {
1883                 dprintk(1, "file io in progress\n");
1884                 return -EBUSY;
1885         }
1886
1887         return vb2_internal_qbuf(q, b);
1888 }
1889 EXPORT_SYMBOL_GPL(vb2_qbuf);
1890
1891 /**
1892  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1893  * for dequeuing
1894  *
1895  * Will sleep if required for nonblocking == false.
1896  */
1897 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1898 {
1899         /*
1900          * All operations on vb_done_list are performed under done_lock
1901          * spinlock protection. However, buffers may be removed from
1902          * it and returned to userspace only while holding both driver's
1903          * lock and the done_lock spinlock. Thus we can be sure that as
1904          * long as we hold the driver's lock, the list will remain not
1905          * empty if list_empty() check succeeds.
1906          */
1907
1908         for (;;) {
1909                 int ret;
1910
1911                 if (!q->streaming) {
1912                         dprintk(1, "streaming off, will not wait for buffers\n");
1913                         return -EINVAL;
1914                 }
1915
1916                 if (q->error) {
1917                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1918                         return -EIO;
1919                 }
1920
1921                 if (!list_empty(&q->done_list)) {
1922                         /*
1923                          * Found a buffer that we were waiting for.
1924                          */
1925                         break;
1926                 }
1927
1928                 if (nonblocking) {
1929                         dprintk(1, "nonblocking and no buffers to dequeue, "
1930                                                                 "will not wait\n");
1931                         return -EAGAIN;
1932                 }
1933
1934                 /*
1935                  * We are streaming and blocking, wait for another buffer to
1936                  * become ready or for streamoff. Driver's lock is released to
1937                  * allow streamoff or qbuf to be called while waiting.
1938                  */
1939                 call_void_qop(q, wait_prepare, q);
1940
1941                 /*
1942                  * All locks have been released, it is safe to sleep now.
1943                  */
1944                 dprintk(3, "will sleep waiting for buffers\n");
1945                 ret = wait_event_interruptible(q->done_wq,
1946                                 !list_empty(&q->done_list) || !q->streaming ||
1947                                 q->error);
1948
1949                 /*
1950                  * We need to reevaluate both conditions again after reacquiring
1951                  * the locks or return an error if one occurred.
1952                  */
1953                 call_void_qop(q, wait_finish, q);
1954                 if (ret) {
1955                         dprintk(1, "sleep was interrupted\n");
1956                         return ret;
1957                 }
1958         }
1959         return 0;
1960 }
1961
1962 /**
1963  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1964  *
1965  * Will sleep if required for nonblocking == false.
1966  */
1967 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1968                                 struct v4l2_buffer *b, int nonblocking)
1969 {
1970         unsigned long flags;
1971         int ret;
1972
1973         /*
1974          * Wait for at least one buffer to become available on the done_list.
1975          */
1976         ret = __vb2_wait_for_done_vb(q, nonblocking);
1977         if (ret)
1978                 return ret;
1979
1980         /*
1981          * Driver's lock has been held since we last verified that done_list
1982          * is not empty, so no need for another list_empty(done_list) check.
1983          */
1984         spin_lock_irqsave(&q->done_lock, flags);
1985         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1986         /*
1987          * Only remove the buffer from done_list if v4l2_buffer can handle all
1988          * the planes.
1989          */
1990         ret = __verify_planes_array(*vb, b);
1991         if (!ret)
1992                 list_del(&(*vb)->done_entry);
1993         spin_unlock_irqrestore(&q->done_lock, flags);
1994
1995         return ret;
1996 }
1997
1998 /**
1999  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
2000  * @q:          videobuf2 queue
2001  *
2002  * This function will wait until all buffers that have been given to the driver
2003  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
2004  * wait_prepare, wait_finish pair. It is intended to be called with all locks
2005  * taken, for example from stop_streaming() callback.
2006  */
2007 int vb2_wait_for_all_buffers(struct vb2_queue *q)
2008 {
2009         if (!q->streaming) {
2010                 dprintk(1, "streaming off, will not wait for buffers\n");
2011                 return -EINVAL;
2012         }
2013
2014         if (q->start_streaming_called)
2015                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
2016         return 0;
2017 }
2018 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
2019
2020 /**
2021  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
2022  */
2023 static void __vb2_dqbuf(struct vb2_buffer *vb)
2024 {
2025         struct vb2_queue *q = vb->vb2_queue;
2026         unsigned int i;
2027
2028         /* nothing to do if the buffer is already dequeued */
2029         if (vb->state == VB2_BUF_STATE_DEQUEUED)
2030                 return;
2031
2032         vb->state = VB2_BUF_STATE_DEQUEUED;
2033
2034         /* unmap DMABUF buffer */
2035         if (q->memory == V4L2_MEMORY_DMABUF)
2036                 for (i = 0; i < vb->num_planes; ++i) {
2037                         if (!vb->planes[i].dbuf_mapped)
2038                                 continue;
2039                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
2040                         vb->planes[i].dbuf_mapped = 0;
2041                 }
2042 }
2043
2044 static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
2045 {
2046         struct vb2_buffer *vb = NULL;
2047         int ret;
2048
2049         if (b->type != q->type) {
2050                 dprintk(1, "invalid buffer type\n");
2051                 return -EINVAL;
2052         }
2053         ret = __vb2_get_done_vb(q, &vb, b, nonblocking);
2054         if (ret < 0)
2055                 return ret;
2056
2057         switch (vb->state) {
2058         case VB2_BUF_STATE_DONE:
2059                 dprintk(3, "returning done buffer\n");
2060                 break;
2061         case VB2_BUF_STATE_ERROR:
2062                 dprintk(3, "returning done buffer with errors\n");
2063                 break;
2064         default:
2065                 dprintk(1, "invalid buffer state\n");
2066                 return -EINVAL;
2067         }
2068
2069         call_void_vb_qop(vb, buf_finish, vb);
2070
2071         /* Fill buffer information for the userspace */
2072         __fill_v4l2_buffer(vb, b);
2073         /* Remove from videobuf queue */
2074         list_del(&vb->queued_entry);
2075         q->queued_count--;
2076         /* go back to dequeued state */
2077         __vb2_dqbuf(vb);
2078
2079         dprintk(1, "dqbuf of buffer %d, with state %d\n",
2080                         vb->v4l2_buf.index, vb->state);
2081
2082         return 0;
2083 }
2084
2085 /**
2086  * vb2_dqbuf() - Dequeue a buffer to the userspace
2087  * @q:          videobuf2 queue
2088  * @b:          buffer structure passed from userspace to vidioc_dqbuf handler
2089  *              in driver
2090  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
2091  *               buffers ready for dequeuing are present. Normally the driver
2092  *               would be passing (file->f_flags & O_NONBLOCK) here
2093  *
2094  * Should be called from vidioc_dqbuf ioctl handler of a driver.
2095  * This function:
2096  * 1) verifies the passed buffer,
2097  * 2) calls buf_finish callback in the driver (if provided), in which
2098  *    driver can perform any additional operations that may be required before
2099  *    returning the buffer to userspace, such as cache sync,
2100  * 3) the buffer struct members are filled with relevant information for
2101  *    the userspace.
2102  *
2103  * The return values from this function are intended to be directly returned
2104  * from vidioc_dqbuf handler in driver.
2105  */
2106 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
2107 {
2108         if (vb2_fileio_is_active(q)) {
2109                 dprintk(1, "file io in progress\n");
2110                 return -EBUSY;
2111         }
2112         return vb2_internal_dqbuf(q, b, nonblocking);
2113 }
2114 EXPORT_SYMBOL_GPL(vb2_dqbuf);
2115
2116 /**
2117  * __vb2_queue_cancel() - cancel and stop (pause) streaming
2118  *
2119  * Removes all queued buffers from driver's queue and all buffers queued by
2120  * userspace from videobuf's queue. Returns to state after reqbufs.
2121  */
2122 static void __vb2_queue_cancel(struct vb2_queue *q)
2123 {
2124         unsigned int i;
2125
2126         /*
2127          * Tell driver to stop all transactions and release all queued
2128          * buffers.
2129          */
2130         if (q->start_streaming_called)
2131                 call_void_qop(q, stop_streaming, q);
2132
2133         /*
2134          * If you see this warning, then the driver isn't cleaning up properly
2135          * in stop_streaming(). See the stop_streaming() documentation in
2136          * videobuf2-core.h for more information how buffers should be returned
2137          * to vb2 in stop_streaming().
2138          */
2139         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
2140                 for (i = 0; i < q->num_buffers; ++i)
2141                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
2142                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
2143                 /* Must be zero now */
2144                 WARN_ON(atomic_read(&q->owned_by_drv_count));
2145         }
2146
2147         q->streaming = 0;
2148         q->start_streaming_called = 0;
2149         q->queued_count = 0;
2150         q->error = 0;
2151
2152         /*
2153          * Remove all buffers from videobuf's list...
2154          */
2155         INIT_LIST_HEAD(&q->queued_list);
2156         /*
2157          * ...and done list; userspace will not receive any buffers it
2158          * has not already dequeued before initiating cancel.
2159          */
2160         INIT_LIST_HEAD(&q->done_list);
2161         atomic_set(&q->owned_by_drv_count, 0);
2162         wake_up_all(&q->done_wq);
2163
2164         /*
2165          * Reinitialize all buffers for next use.
2166          * Make sure to call buf_finish for any queued buffers. Normally
2167          * that's done in dqbuf, but that's not going to happen when we
2168          * cancel the whole queue. Note: this code belongs here, not in
2169          * __vb2_dqbuf() since in vb2_internal_dqbuf() there is a critical
2170          * call to __fill_v4l2_buffer() after buf_finish(). That order can't
2171          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
2172          */
2173         for (i = 0; i < q->num_buffers; ++i) {
2174                 struct vb2_buffer *vb = q->bufs[i];
2175
2176                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
2177                         vb->state = VB2_BUF_STATE_PREPARED;
2178                         call_void_vb_qop(vb, buf_finish, vb);
2179                 }
2180                 __vb2_dqbuf(vb);
2181         }
2182 }
2183
2184 static int vb2_internal_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
2185 {
2186         int ret;
2187
2188         if (type != q->type) {
2189                 dprintk(1, "invalid stream type\n");
2190                 return -EINVAL;
2191         }
2192
2193         if (q->streaming) {
2194                 dprintk(3, "already streaming\n");
2195                 return 0;
2196         }
2197
2198         if (!q->num_buffers) {
2199                 dprintk(1, "no buffers have been allocated\n");
2200                 return -EINVAL;
2201         }
2202
2203         if (q->num_buffers < q->min_buffers_needed) {
2204                 dprintk(1, "need at least %u allocated buffers\n",
2205                                 q->min_buffers_needed);
2206                 return -EINVAL;
2207         }
2208
2209         /*
2210          * Tell driver to start streaming provided sufficient buffers
2211          * are available.
2212          */
2213         if (q->queued_count >= q->min_buffers_needed) {
2214                 ret = vb2_start_streaming(q);
2215                 if (ret) {
2216                         __vb2_queue_cancel(q);
2217                         return ret;
2218                 }
2219         }
2220
2221         q->streaming = 1;
2222
2223         dprintk(3, "successful\n");
2224         return 0;
2225 }
2226
2227 /**
2228  * vb2_queue_error() - signal a fatal error on the queue
2229  * @q:          videobuf2 queue
2230  *
2231  * Flag that a fatal unrecoverable error has occurred and wake up all processes
2232  * waiting on the queue. Polling will now set POLLERR and queuing and dequeuing
2233  * buffers will return -EIO.
2234  *
2235  * The error flag will be cleared when cancelling the queue, either from
2236  * vb2_streamoff or vb2_queue_release. Drivers should thus not call this
2237  * function before starting the stream, otherwise the error flag will remain set
2238  * until the queue is released when closing the device node.
2239  */
2240 void vb2_queue_error(struct vb2_queue *q)
2241 {
2242         q->error = 1;
2243
2244         wake_up_all(&q->done_wq);
2245 }
2246 EXPORT_SYMBOL_GPL(vb2_queue_error);
2247
2248 /**
2249  * vb2_streamon - start streaming
2250  * @q:          videobuf2 queue
2251  * @type:       type argument passed from userspace to vidioc_streamon handler
2252  *
2253  * Should be called from vidioc_streamon handler of a driver.
2254  * This function:
2255  * 1) verifies current state
2256  * 2) passes any previously queued buffers to the driver and starts streaming
2257  *
2258  * The return values from this function are intended to be directly returned
2259  * from vidioc_streamon handler in the driver.
2260  */
2261 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
2262 {
2263         if (vb2_fileio_is_active(q)) {
2264                 dprintk(1, "file io in progress\n");
2265                 return -EBUSY;
2266         }
2267         return vb2_internal_streamon(q, type);
2268 }
2269 EXPORT_SYMBOL_GPL(vb2_streamon);
2270
2271 static int vb2_internal_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
2272 {
2273         if (type != q->type) {
2274                 dprintk(1, "invalid stream type\n");
2275                 return -EINVAL;
2276         }
2277
2278         /*
2279          * Cancel will pause streaming and remove all buffers from the driver
2280          * and videobuf, effectively returning control over them to userspace.
2281          *
2282          * Note that we do this even if q->streaming == 0: if you prepare or
2283          * queue buffers, and then call streamoff without ever having called
2284          * streamon, you would still expect those buffers to be returned to
2285          * their normal dequeued state.
2286          */
2287         __vb2_queue_cancel(q);
2288         q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
2289
2290         dprintk(3, "successful\n");
2291         return 0;
2292 }
2293
2294 /**
2295  * vb2_streamoff - stop streaming
2296  * @q:          videobuf2 queue
2297  * @type:       type argument passed from userspace to vidioc_streamoff handler
2298  *
2299  * Should be called from vidioc_streamoff handler of a driver.
2300  * This function:
2301  * 1) verifies current state,
2302  * 2) stop streaming and dequeues any queued buffers, including those previously
2303  *    passed to the driver (after waiting for the driver to finish).
2304  *
2305  * This call can be used for pausing playback.
2306  * The return values from this function are intended to be directly returned
2307  * from vidioc_streamoff handler in the driver
2308  */
2309 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
2310 {
2311         if (vb2_fileio_is_active(q)) {
2312                 dprintk(1, "file io in progress\n");
2313                 return -EBUSY;
2314         }
2315         return vb2_internal_streamoff(q, type);
2316 }
2317 EXPORT_SYMBOL_GPL(vb2_streamoff);
2318
2319 /**
2320  * __find_plane_by_offset() - find plane associated with the given offset off
2321  */
2322 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
2323                         unsigned int *_buffer, unsigned int *_plane)
2324 {
2325         struct vb2_buffer *vb;
2326         unsigned int buffer, plane;
2327
2328         /*
2329          * Go over all buffers and their planes, comparing the given offset
2330          * with an offset assigned to each plane. If a match is found,
2331          * return its buffer and plane numbers.
2332          */
2333         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
2334                 vb = q->bufs[buffer];
2335
2336                 for (plane = 0; plane < vb->num_planes; ++plane) {
2337                         if (vb->v4l2_planes[plane].m.mem_offset == off) {
2338                                 *_buffer = buffer;
2339                                 *_plane = plane;
2340                                 return 0;
2341                         }
2342                 }
2343         }
2344
2345         return -EINVAL;
2346 }
2347
2348 /**
2349  * vb2_expbuf() - Export a buffer as a file descriptor
2350  * @q:          videobuf2 queue
2351  * @eb:         export buffer structure passed from userspace to vidioc_expbuf
2352  *              handler in driver
2353  *
2354  * The return values from this function are intended to be directly returned
2355  * from vidioc_expbuf handler in driver.
2356  */
2357 int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
2358 {
2359         struct vb2_buffer *vb = NULL;
2360         struct vb2_plane *vb_plane;
2361         int ret;
2362         struct dma_buf *dbuf;
2363
2364         if (q->memory != V4L2_MEMORY_MMAP) {
2365                 dprintk(1, "queue is not currently set up for mmap\n");
2366                 return -EINVAL;
2367         }
2368
2369         if (!q->mem_ops->get_dmabuf) {
2370                 dprintk(1, "queue does not support DMA buffer exporting\n");
2371                 return -EINVAL;
2372         }
2373
2374         if (eb->flags & ~(O_CLOEXEC | O_ACCMODE)) {
2375                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
2376                 return -EINVAL;
2377         }
2378
2379         if (eb->type != q->type) {
2380                 dprintk(1, "invalid buffer type\n");
2381                 return -EINVAL;
2382         }
2383
2384         if (eb->index >= q->num_buffers) {
2385                 dprintk(1, "buffer index out of range\n");
2386                 return -EINVAL;
2387         }
2388
2389         vb = q->bufs[eb->index];
2390
2391         if (eb->plane >= vb->num_planes) {
2392                 dprintk(1, "buffer plane out of range\n");
2393                 return -EINVAL;
2394         }
2395
2396         if (vb2_fileio_is_active(q)) {
2397                 dprintk(1, "expbuf: file io in progress\n");
2398                 return -EBUSY;
2399         }
2400
2401         vb_plane = &vb->planes[eb->plane];
2402
2403         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv, eb->flags & O_ACCMODE);
2404         if (IS_ERR_OR_NULL(dbuf)) {
2405                 dprintk(1, "failed to export buffer %d, plane %d\n",
2406                         eb->index, eb->plane);
2407                 return -EINVAL;
2408         }
2409
2410         ret = dma_buf_fd(dbuf, eb->flags & ~O_ACCMODE);
2411         if (ret < 0) {
2412                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
2413                         eb->index, eb->plane, ret);
2414                 dma_buf_put(dbuf);
2415                 return ret;
2416         }
2417
2418         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
2419                 eb->index, eb->plane, ret);
2420         eb->fd = ret;
2421
2422         return 0;
2423 }
2424 EXPORT_SYMBOL_GPL(vb2_expbuf);
2425
2426 /**
2427  * vb2_mmap() - map video buffers into application address space
2428  * @q:          videobuf2 queue
2429  * @vma:        vma passed to the mmap file operation handler in the driver
2430  *
2431  * Should be called from mmap file operation handler of a driver.
2432  * This function maps one plane of one of the available video buffers to
2433  * userspace. To map whole video memory allocated on reqbufs, this function
2434  * has to be called once per each plane per each buffer previously allocated.
2435  *
2436  * When the userspace application calls mmap, it passes to it an offset returned
2437  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
2438  * a "cookie", which is then used to identify the plane to be mapped.
2439  * This function finds a plane with a matching offset and a mapping is performed
2440  * by the means of a provided memory operation.
2441  *
2442  * The return values from this function are intended to be directly returned
2443  * from the mmap handler in driver.
2444  */
2445 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
2446 {
2447         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
2448         struct vb2_buffer *vb;
2449         unsigned int buffer = 0, plane = 0;
2450         int ret;
2451         unsigned long length;
2452
2453         if (q->memory != V4L2_MEMORY_MMAP) {
2454                 dprintk(1, "queue is not currently set up for mmap\n");
2455                 return -EINVAL;
2456         }
2457
2458         /*
2459          * Check memory area access mode.
2460          */
2461         if (!(vma->vm_flags & VM_SHARED)) {
2462                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
2463                 return -EINVAL;
2464         }
2465         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
2466                 if (!(vma->vm_flags & VM_WRITE)) {
2467                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
2468                         return -EINVAL;
2469                 }
2470         } else {
2471                 if (!(vma->vm_flags & VM_READ)) {
2472                         dprintk(1, "invalid vma flags, VM_READ needed\n");
2473                         return -EINVAL;
2474                 }
2475         }
2476         if (vb2_fileio_is_active(q)) {
2477                 dprintk(1, "mmap: file io in progress\n");
2478                 return -EBUSY;
2479         }
2480
2481         /*
2482          * Find the plane corresponding to the offset passed by userspace.
2483          */
2484         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2485         if (ret)
2486                 return ret;
2487
2488         vb = q->bufs[buffer];
2489
2490         /*
2491          * MMAP requires page_aligned buffers.
2492          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
2493          * so, we need to do the same here.
2494          */
2495         length = PAGE_ALIGN(vb->v4l2_planes[plane].length);
2496         if (length < (vma->vm_end - vma->vm_start)) {
2497                 dprintk(1,
2498                         "MMAP invalid, as it would overflow buffer length\n");
2499                 return -EINVAL;
2500         }
2501
2502         mutex_lock(&q->mmap_lock);
2503         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
2504         mutex_unlock(&q->mmap_lock);
2505         if (ret)
2506                 return ret;
2507
2508         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
2509         return 0;
2510 }
2511 EXPORT_SYMBOL_GPL(vb2_mmap);
2512
2513 #ifndef CONFIG_MMU
2514 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2515                                     unsigned long addr,
2516                                     unsigned long len,
2517                                     unsigned long pgoff,
2518                                     unsigned long flags)
2519 {
2520         unsigned long off = pgoff << PAGE_SHIFT;
2521         struct vb2_buffer *vb;
2522         unsigned int buffer, plane;
2523         void *vaddr;
2524         int ret;
2525
2526         if (q->memory != V4L2_MEMORY_MMAP) {
2527                 dprintk(1, "queue is not currently set up for mmap\n");
2528                 return -EINVAL;
2529         }
2530
2531         /*
2532          * Find the plane corresponding to the offset passed by userspace.
2533          */
2534         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2535         if (ret)
2536                 return ret;
2537
2538         vb = q->bufs[buffer];
2539
2540         vaddr = vb2_plane_vaddr(vb, plane);
2541         return vaddr ? (unsigned long)vaddr : -EINVAL;
2542 }
2543 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2544 #endif
2545
2546 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2547 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2548
2549 /**
2550  * vb2_poll() - implements poll userspace operation
2551  * @q:          videobuf2 queue
2552  * @file:       file argument passed to the poll file operation handler
2553  * @wait:       wait argument passed to the poll file operation handler
2554  *
2555  * This function implements poll file operation handler for a driver.
2556  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
2557  * be informed that the file descriptor of a video device is available for
2558  * reading.
2559  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
2560  * will be reported as available for writing.
2561  *
2562  * If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
2563  * pending events.
2564  *
2565  * The return values from this function are intended to be directly returned
2566  * from poll handler in driver.
2567  */
2568 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
2569 {
2570         struct video_device *vfd = video_devdata(file);
2571         unsigned long req_events = poll_requested_events(wait);
2572         struct vb2_buffer *vb = NULL;
2573         unsigned int res = 0;
2574         unsigned long flags;
2575
2576         if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
2577                 struct v4l2_fh *fh = file->private_data;
2578
2579                 if (v4l2_event_pending(fh))
2580                         res = POLLPRI;
2581                 else if (req_events & POLLPRI)
2582                         poll_wait(file, &fh->wait, wait);
2583         }
2584
2585         if (!V4L2_TYPE_IS_OUTPUT(q->type) && !(req_events & (POLLIN | POLLRDNORM)))
2586                 return res;
2587         if (V4L2_TYPE_IS_OUTPUT(q->type) && !(req_events & (POLLOUT | POLLWRNORM)))
2588                 return res;
2589
2590         /*
2591          * Start file I/O emulator only if streaming API has not been used yet.
2592          */
2593         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2594                 if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ) &&
2595                                 (req_events & (POLLIN | POLLRDNORM))) {
2596                         if (__vb2_init_fileio(q, 1))
2597                                 return res | POLLERR;
2598                 }
2599                 if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE) &&
2600                                 (req_events & (POLLOUT | POLLWRNORM))) {
2601                         if (__vb2_init_fileio(q, 0))
2602                                 return res | POLLERR;
2603                         /*
2604                          * Write to OUTPUT queue can be done immediately.
2605                          */
2606                         return res | POLLOUT | POLLWRNORM;
2607                 }
2608         }
2609
2610         /*
2611          * There is nothing to wait for if the queue isn't streaming, or if the
2612          * error flag is set.
2613          */
2614         if (!vb2_is_streaming(q) || q->error)
2615                 return res | POLLERR;
2616         /*
2617          * For compatibility with vb1: if QBUF hasn't been called yet, then
2618          * return POLLERR as well. This only affects capture queues, output
2619          * queues will always initialize waiting_for_buffers to false.
2620          */
2621         if (q->waiting_for_buffers)
2622                 return res | POLLERR;
2623
2624         /*
2625          * For output streams you can write as long as there are fewer buffers
2626          * queued than there are buffers available.
2627          */
2628         if (V4L2_TYPE_IS_OUTPUT(q->type) && q->queued_count < q->num_buffers)
2629                 return res | POLLOUT | POLLWRNORM;
2630
2631         if (list_empty(&q->done_list))
2632                 poll_wait(file, &q->done_wq, wait);
2633
2634         /*
2635          * Take first buffer available for dequeuing.
2636          */
2637         spin_lock_irqsave(&q->done_lock, flags);
2638         if (!list_empty(&q->done_list))
2639                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2640                                         done_entry);
2641         spin_unlock_irqrestore(&q->done_lock, flags);
2642
2643         if (vb && (vb->state == VB2_BUF_STATE_DONE
2644                         || vb->state == VB2_BUF_STATE_ERROR)) {
2645                 return (V4L2_TYPE_IS_OUTPUT(q->type)) ?
2646                                 res | POLLOUT | POLLWRNORM :
2647                                 res | POLLIN | POLLRDNORM;
2648         }
2649         return res;
2650 }
2651 EXPORT_SYMBOL_GPL(vb2_poll);
2652
2653 /**
2654  * vb2_queue_init() - initialize a videobuf2 queue
2655  * @q:          videobuf2 queue; this structure should be allocated in driver
2656  *
2657  * The vb2_queue structure should be allocated by the driver. The driver is
2658  * responsible of clearing it's content and setting initial values for some
2659  * required entries before calling this function.
2660  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
2661  * to the struct vb2_queue description in include/media/videobuf2-core.h
2662  * for more information.
2663  */
2664 int vb2_queue_init(struct vb2_queue *q)
2665 {
2666         /*
2667          * Sanity check
2668          */
2669         if (WARN_ON(!q)                   ||
2670             WARN_ON(!q->ops)              ||
2671             WARN_ON(!q->mem_ops)          ||
2672             WARN_ON(!q->type)             ||
2673             WARN_ON(!q->io_modes)         ||
2674             WARN_ON(!q->ops->queue_setup) ||
2675             WARN_ON(!q->ops->buf_queue)   ||
2676             WARN_ON(q->timestamp_flags &
2677                     ~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
2678                       V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
2679                 return -EINVAL;
2680
2681         /* Warn that the driver should choose an appropriate timestamp type */
2682         WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
2683                 V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
2684
2685         INIT_LIST_HEAD(&q->queued_list);
2686         INIT_LIST_HEAD(&q->done_list);
2687         spin_lock_init(&q->done_lock);
2688         mutex_init(&q->mmap_lock);
2689         init_waitqueue_head(&q->done_wq);
2690
2691         if (q->buf_struct_size == 0)
2692                 q->buf_struct_size = sizeof(struct vb2_buffer);
2693
2694         return 0;
2695 }
2696 EXPORT_SYMBOL_GPL(vb2_queue_init);
2697
2698 /**
2699  * vb2_queue_release() - stop streaming, release the queue and free memory
2700  * @q:          videobuf2 queue
2701  *
2702  * This function stops streaming and performs necessary clean ups, including
2703  * freeing video buffer memory. The driver is responsible for freeing
2704  * the vb2_queue structure itself.
2705  */
2706 void vb2_queue_release(struct vb2_queue *q)
2707 {
2708         __vb2_cleanup_fileio(q);
2709         __vb2_queue_cancel(q);
2710         mutex_lock(&q->mmap_lock);
2711         __vb2_queue_free(q, q->num_buffers);
2712         mutex_unlock(&q->mmap_lock);
2713 }
2714 EXPORT_SYMBOL_GPL(vb2_queue_release);
2715
2716 /**
2717  * struct vb2_fileio_buf - buffer context used by file io emulator
2718  *
2719  * vb2 provides a compatibility layer and emulator of file io (read and
2720  * write) calls on top of streaming API. This structure is used for
2721  * tracking context related to the buffers.
2722  */
2723 struct vb2_fileio_buf {
2724         void *vaddr;
2725         unsigned int size;
2726         unsigned int pos;
2727         unsigned int queued:1;
2728 };
2729
2730 /**
2731  * struct vb2_fileio_data - queue context used by file io emulator
2732  *
2733  * @cur_index:  the index of the buffer currently being read from or
2734  *              written to. If equal to q->num_buffers then a new buffer
2735  *              must be dequeued.
2736  * @initial_index: in the read() case all buffers are queued up immediately
2737  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2738  *              buffers. However, in the write() case no buffers are initially
2739  *              queued, instead whenever a buffer is full it is queued up by
2740  *              __vb2_perform_fileio(). Only once all available buffers have
2741  *              been queued up will __vb2_perform_fileio() start to dequeue
2742  *              buffers. This means that initially __vb2_perform_fileio()
2743  *              needs to know what buffer index to use when it is queuing up
2744  *              the buffers for the first time. That initial index is stored
2745  *              in this field. Once it is equal to q->num_buffers all
2746  *              available buffers have been queued and __vb2_perform_fileio()
2747  *              should start the normal dequeue/queue cycle.
2748  *
2749  * vb2 provides a compatibility layer and emulator of file io (read and
2750  * write) calls on top of streaming API. For proper operation it required
2751  * this structure to save the driver state between each call of the read
2752  * or write function.
2753  */
2754 struct vb2_fileio_data {
2755         struct v4l2_requestbuffers req;
2756         struct v4l2_plane p;
2757         struct v4l2_buffer b;
2758         struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
2759         unsigned int cur_index;
2760         unsigned int initial_index;
2761         unsigned int q_count;
2762         unsigned int dq_count;
2763         unsigned int flags;
2764 };
2765
2766 /**
2767  * __vb2_init_fileio() - initialize file io emulator
2768  * @q:          videobuf2 queue
2769  * @read:       mode selector (1 means read, 0 means write)
2770  */
2771 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2772 {
2773         struct vb2_fileio_data *fileio;
2774         int i, ret;
2775         unsigned int count = 0;
2776
2777         /*
2778          * Sanity check
2779          */
2780         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2781                     (!read && !(q->io_modes & VB2_WRITE))))
2782                 return -EINVAL;
2783
2784         /*
2785          * Check if device supports mapping buffers to kernel virtual space.
2786          */
2787         if (!q->mem_ops->vaddr)
2788                 return -EBUSY;
2789
2790         /*
2791          * Check if streaming api has not been already activated.
2792          */
2793         if (q->streaming || q->num_buffers > 0)
2794                 return -EBUSY;
2795
2796         /*
2797          * Start with count 1, driver can increase it in queue_setup()
2798          */
2799         count = 1;
2800
2801         dprintk(3, "setting up file io: mode %s, count %d, flags %08x\n",
2802                 (read) ? "read" : "write", count, q->io_flags);
2803
2804         fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
2805         if (fileio == NULL)
2806                 return -ENOMEM;
2807
2808         fileio->flags = q->io_flags;
2809
2810         /*
2811          * Request buffers and use MMAP type to force driver
2812          * to allocate buffers by itself.
2813          */
2814         fileio->req.count = count;
2815         fileio->req.memory = V4L2_MEMORY_MMAP;
2816         fileio->req.type = q->type;
2817         q->fileio = fileio;
2818         ret = __reqbufs(q, &fileio->req);
2819         if (ret)
2820                 goto err_kfree;
2821
2822         /*
2823          * Check if plane_count is correct
2824          * (multiplane buffers are not supported).
2825          */
2826         if (q->bufs[0]->num_planes != 1) {
2827                 ret = -EBUSY;
2828                 goto err_reqbufs;
2829         }
2830
2831         /*
2832          * Get kernel address of each buffer.
2833          */
2834         for (i = 0; i < q->num_buffers; i++) {
2835                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2836                 if (fileio->bufs[i].vaddr == NULL) {
2837                         ret = -EINVAL;
2838                         goto err_reqbufs;
2839                 }
2840                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2841         }
2842
2843         /*
2844          * Read mode requires pre queuing of all buffers.
2845          */
2846         if (read) {
2847                 bool is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
2848
2849                 /*
2850                  * Queue all buffers.
2851                  */
2852                 for (i = 0; i < q->num_buffers; i++) {
2853                         struct v4l2_buffer *b = &fileio->b;
2854
2855                         memset(b, 0, sizeof(*b));
2856                         b->type = q->type;
2857                         if (is_multiplanar) {
2858                                 memset(&fileio->p, 0, sizeof(fileio->p));
2859                                 b->m.planes = &fileio->p;
2860                                 b->length = 1;
2861                         }
2862                         b->memory = q->memory;
2863                         b->index = i;
2864                         ret = vb2_internal_qbuf(q, b);
2865                         if (ret)
2866                                 goto err_reqbufs;
2867                         fileio->bufs[i].queued = 1;
2868                 }
2869                 /*
2870                  * All buffers have been queued, so mark that by setting
2871                  * initial_index to q->num_buffers
2872                  */
2873                 fileio->initial_index = q->num_buffers;
2874                 fileio->cur_index = q->num_buffers;
2875         }
2876
2877         /*
2878          * Start streaming.
2879          */
2880         ret = vb2_internal_streamon(q, q->type);
2881         if (ret)
2882                 goto err_reqbufs;
2883
2884         return ret;
2885
2886 err_reqbufs:
2887         fileio->req.count = 0;
2888         __reqbufs(q, &fileio->req);
2889
2890 err_kfree:
2891         q->fileio = NULL;
2892         kfree(fileio);
2893         return ret;
2894 }
2895
2896 /**
2897  * __vb2_cleanup_fileio() - free resourced used by file io emulator
2898  * @q:          videobuf2 queue
2899  */
2900 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2901 {
2902         struct vb2_fileio_data *fileio = q->fileio;
2903
2904         if (fileio) {
2905                 vb2_internal_streamoff(q, q->type);
2906                 q->fileio = NULL;
2907                 fileio->req.count = 0;
2908                 vb2_reqbufs(q, &fileio->req);
2909                 kfree(fileio);
2910                 dprintk(3, "file io emulator closed\n");
2911         }
2912         return 0;
2913 }
2914
2915 /**
2916  * __vb2_perform_fileio() - perform a single file io (read or write) operation
2917  * @q:          videobuf2 queue
2918  * @data:       pointed to target userspace buffer
2919  * @count:      number of bytes to read or write
2920  * @ppos:       file handle position tracking pointer
2921  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
2922  * @read:       access mode selector (1 means read, 0 means write)
2923  */
2924 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2925                 loff_t *ppos, int nonblock, int read)
2926 {
2927         struct vb2_fileio_data *fileio;
2928         struct vb2_fileio_buf *buf;
2929         bool is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
2930         /*
2931          * When using write() to write data to an output video node the vb2 core
2932          * should set timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2933          * else is able to provide this information with the write() operation.
2934          */
2935         bool set_timestamp = !read &&
2936                 (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
2937                 V4L2_BUF_FLAG_TIMESTAMP_COPY;
2938         int ret, index;
2939
2940         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2941                 read ? "read" : "write", (long)*ppos, count,
2942                 nonblock ? "non" : "");
2943
2944         if (!data)
2945                 return -EINVAL;
2946
2947         /*
2948          * Initialize emulator on first call.
2949          */
2950         if (!vb2_fileio_is_active(q)) {
2951                 ret = __vb2_init_fileio(q, read);
2952                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2953                 if (ret)
2954                         return ret;
2955         }
2956         fileio = q->fileio;
2957
2958         /*
2959          * Check if we need to dequeue the buffer.
2960          */
2961         index = fileio->cur_index;
2962         if (index >= q->num_buffers) {
2963                 /*
2964                  * Call vb2_dqbuf to get buffer back.
2965                  */
2966                 memset(&fileio->b, 0, sizeof(fileio->b));
2967                 fileio->b.type = q->type;
2968                 fileio->b.memory = q->memory;
2969                 if (is_multiplanar) {
2970                         memset(&fileio->p, 0, sizeof(fileio->p));
2971                         fileio->b.m.planes = &fileio->p;
2972                         fileio->b.length = 1;
2973                 }
2974                 ret = vb2_internal_dqbuf(q, &fileio->b, nonblock);
2975                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2976                 if (ret)
2977                         return ret;
2978                 fileio->dq_count += 1;
2979
2980                 fileio->cur_index = index = fileio->b.index;
2981                 buf = &fileio->bufs[index];
2982
2983                 /*
2984                  * Get number of bytes filled by the driver
2985                  */
2986                 buf->pos = 0;
2987                 buf->queued = 0;
2988                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2989                                  : vb2_plane_size(q->bufs[index], 0);
2990                 /* Compensate for data_offset on read in the multiplanar case. */
2991                 if (is_multiplanar && read &&
2992                     fileio->b.m.planes[0].data_offset < buf->size) {
2993                         buf->pos = fileio->b.m.planes[0].data_offset;
2994                         buf->size -= buf->pos;
2995                 }
2996         } else {
2997                 buf = &fileio->bufs[index];
2998         }
2999
3000         /*
3001          * Limit count on last few bytes of the buffer.
3002          */
3003         if (buf->pos + count > buf->size) {
3004                 count = buf->size - buf->pos;
3005                 dprintk(5, "reducing read count: %zd\n", count);
3006         }
3007
3008         /*
3009          * Transfer data to userspace.
3010          */
3011         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
3012                 count, index, buf->pos);
3013         if (read)
3014                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
3015         else
3016                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
3017         if (ret) {
3018                 dprintk(3, "error copying data\n");
3019                 return -EFAULT;
3020         }
3021
3022         /*
3023          * Update counters.
3024          */
3025         buf->pos += count;
3026         *ppos += count;
3027
3028         /*
3029          * Queue next buffer if required.
3030          */
3031         if (buf->pos == buf->size ||
3032            (!read && (fileio->flags & VB2_FILEIO_WRITE_IMMEDIATELY))) {
3033                 /*
3034                  * Check if this is the last buffer to read.
3035                  */
3036                 if (read && (fileio->flags & VB2_FILEIO_READ_ONCE) &&
3037                     fileio->dq_count == 1) {
3038                         dprintk(3, "read limit reached\n");
3039                         return __vb2_cleanup_fileio(q);
3040                 }
3041
3042                 /*
3043                  * Call vb2_qbuf and give buffer to the driver.
3044                  */
3045                 memset(&fileio->b, 0, sizeof(fileio->b));
3046                 fileio->b.type = q->type;
3047                 fileio->b.memory = q->memory;
3048                 fileio->b.index = index;
3049                 fileio->b.bytesused = buf->pos;
3050                 if (is_multiplanar) {
3051                         memset(&fileio->p, 0, sizeof(fileio->p));
3052                         fileio->p.bytesused = buf->pos;
3053                         fileio->b.m.planes = &fileio->p;
3054                         fileio->b.length = 1;
3055                 }
3056                 if (set_timestamp)
3057                         v4l2_get_timestamp(&fileio->b.timestamp);
3058                 ret = vb2_internal_qbuf(q, &fileio->b);
3059                 dprintk(5, "vb2_dbuf result: %d\n", ret);
3060                 if (ret)
3061                         return ret;
3062
3063                 /*
3064                  * Buffer has been queued, update the status
3065                  */
3066                 buf->pos = 0;
3067                 buf->queued = 1;
3068                 buf->size = vb2_plane_size(q->bufs[index], 0);
3069                 fileio->q_count += 1;
3070                 /*
3071                  * If we are queuing up buffers for the first time, then
3072                  * increase initial_index by one.
3073                  */
3074                 if (fileio->initial_index < q->num_buffers)
3075                         fileio->initial_index++;
3076                 /*
3077                  * The next buffer to use is either a buffer that's going to be
3078                  * queued for the first time (initial_index < q->num_buffers)
3079                  * or it is equal to q->num_buffers, meaning that the next
3080                  * time we need to dequeue a buffer since we've now queued up
3081                  * all the 'first time' buffers.
3082                  */
3083                 fileio->cur_index = fileio->initial_index;
3084         }
3085
3086         /*
3087          * Return proper number of bytes processed.
3088          */
3089         if (ret == 0)
3090                 ret = count;
3091         return ret;
3092 }
3093
3094 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
3095                 loff_t *ppos, int nonblocking)
3096 {
3097         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
3098 }
3099 EXPORT_SYMBOL_GPL(vb2_read);
3100
3101 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
3102                 loff_t *ppos, int nonblocking)
3103 {
3104         return __vb2_perform_fileio(q, (char __user *) data, count,
3105                                                         ppos, nonblocking, 0);
3106 }
3107 EXPORT_SYMBOL_GPL(vb2_write);
3108
3109 struct vb2_threadio_data {
3110         struct task_struct *thread;
3111         vb2_thread_fnc fnc;
3112         void *priv;
3113         bool stop;
3114 };
3115
3116 static int vb2_thread(void *data)
3117 {
3118         struct vb2_queue *q = data;
3119         struct vb2_threadio_data *threadio = q->threadio;
3120         struct vb2_fileio_data *fileio = q->fileio;
3121         bool set_timestamp = false;
3122         int prequeue = 0;
3123         int index = 0;
3124         int ret = 0;
3125
3126         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
3127                 prequeue = q->num_buffers;
3128                 set_timestamp =
3129                         (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
3130                         V4L2_BUF_FLAG_TIMESTAMP_COPY;
3131         }
3132
3133         set_freezable();
3134
3135         for (;;) {
3136                 struct vb2_buffer *vb;
3137
3138                 /*
3139                  * Call vb2_dqbuf to get buffer back.
3140                  */
3141                 memset(&fileio->b, 0, sizeof(fileio->b));
3142                 fileio->b.type = q->type;
3143                 fileio->b.memory = q->memory;
3144                 if (prequeue) {
3145                         fileio->b.index = index++;
3146                         prequeue--;
3147                 } else {
3148                         call_void_qop(q, wait_finish, q);
3149                         if (!threadio->stop)
3150                                 ret = vb2_internal_dqbuf(q, &fileio->b, 0);
3151                         call_void_qop(q, wait_prepare, q);
3152                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
3153                 }
3154                 if (ret || threadio->stop)
3155                         break;
3156                 try_to_freeze();
3157
3158                 vb = q->bufs[fileio->b.index];
3159                 if (!(fileio->b.flags & V4L2_BUF_FLAG_ERROR))
3160                         if (threadio->fnc(vb, threadio->priv))
3161                                 break;
3162                 call_void_qop(q, wait_finish, q);
3163                 if (set_timestamp)
3164                         v4l2_get_timestamp(&fileio->b.timestamp);
3165                 if (!threadio->stop)
3166                         ret = vb2_internal_qbuf(q, &fileio->b);
3167                 call_void_qop(q, wait_prepare, q);
3168                 if (ret || threadio->stop)
3169                         break;
3170         }
3171
3172         /* Hmm, linux becomes *very* unhappy without this ... */
3173         while (!kthread_should_stop()) {
3174                 set_current_state(TASK_INTERRUPTIBLE);
3175                 schedule();
3176         }
3177         return 0;
3178 }
3179
3180 /*
3181  * This function should not be used for anything else but the videobuf2-dvb
3182  * support. If you think you have another good use-case for this, then please
3183  * contact the linux-media mailinglist first.
3184  */
3185 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
3186                      const char *thread_name)
3187 {
3188         struct vb2_threadio_data *threadio;
3189         int ret = 0;
3190
3191         if (q->threadio)
3192                 return -EBUSY;
3193         if (vb2_is_busy(q))
3194                 return -EBUSY;
3195         if (WARN_ON(q->fileio))
3196                 return -EBUSY;
3197
3198         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
3199         if (threadio == NULL)
3200                 return -ENOMEM;
3201         threadio->fnc = fnc;
3202         threadio->priv = priv;
3203
3204         ret = __vb2_init_fileio(q, !V4L2_TYPE_IS_OUTPUT(q->type));
3205         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
3206         if (ret)
3207                 goto nomem;
3208         q->threadio = threadio;
3209         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
3210         if (IS_ERR(threadio->thread)) {
3211                 ret = PTR_ERR(threadio->thread);
3212                 threadio->thread = NULL;
3213                 goto nothread;
3214         }
3215         return 0;
3216
3217 nothread:
3218         __vb2_cleanup_fileio(q);
3219 nomem:
3220         kfree(threadio);
3221         return ret;
3222 }
3223 EXPORT_SYMBOL_GPL(vb2_thread_start);
3224
3225 int vb2_thread_stop(struct vb2_queue *q)
3226 {
3227         struct vb2_threadio_data *threadio = q->threadio;
3228         struct vb2_fileio_data *fileio = q->fileio;
3229         int err;
3230
3231         if (threadio == NULL)
3232                 return 0;
3233         call_void_qop(q, wait_finish, q);
3234         threadio->stop = true;
3235         vb2_internal_streamoff(q, q->type);
3236         call_void_qop(q, wait_prepare, q);
3237         err = kthread_stop(threadio->thread);
3238         q->fileio = NULL;
3239         fileio->req.count = 0;
3240         vb2_reqbufs(q, &fileio->req);
3241         kfree(fileio);
3242         threadio->thread = NULL;
3243         kfree(threadio);
3244         q->fileio = NULL;
3245         q->threadio = NULL;
3246         return err;
3247 }
3248 EXPORT_SYMBOL_GPL(vb2_thread_stop);
3249
3250 /*
3251  * The following functions are not part of the vb2 core API, but are helper
3252  * functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
3253  * and struct vb2_ops.
3254  * They contain boilerplate code that most if not all drivers have to do
3255  * and so they simplify the driver code.
3256  */
3257
3258 /* The queue is busy if there is a owner and you are not that owner. */
3259 static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
3260 {
3261         return vdev->queue->owner && vdev->queue->owner != file->private_data;
3262 }
3263
3264 /* vb2 ioctl helpers */
3265
3266 int vb2_ioctl_reqbufs(struct file *file, void *priv,
3267                           struct v4l2_requestbuffers *p)
3268 {
3269         struct video_device *vdev = video_devdata(file);
3270         int res = __verify_memory_type(vdev->queue, p->memory, p->type);
3271
3272         if (res)
3273                 return res;
3274         if (vb2_queue_is_busy(vdev, file))
3275                 return -EBUSY;
3276         res = __reqbufs(vdev->queue, p);
3277         /* If count == 0, then the owner has released all buffers and he
3278            is no longer owner of the queue. Otherwise we have a new owner. */
3279         if (res == 0)
3280                 vdev->queue->owner = p->count ? file->private_data : NULL;
3281         return res;
3282 }
3283 EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);
3284
3285 int vb2_ioctl_create_bufs(struct file *file, void *priv,
3286                           struct v4l2_create_buffers *p)
3287 {
3288         struct video_device *vdev = video_devdata(file);
3289         int res = __verify_memory_type(vdev->queue, p->memory, p->format.type);
3290
3291         p->index = vdev->queue->num_buffers;
3292         /* If count == 0, then just check if memory and type are valid.
3293            Any -EBUSY result from __verify_memory_type can be mapped to 0. */
3294         if (p->count == 0)
3295                 return res != -EBUSY ? res : 0;
3296         if (res)
3297                 return res;
3298         if (vb2_queue_is_busy(vdev, file))
3299                 return -EBUSY;
3300         res = __create_bufs(vdev->queue, p);
3301         if (res == 0)
3302                 vdev->queue->owner = file->private_data;
3303         return res;
3304 }
3305 EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);
3306
3307 int vb2_ioctl_prepare_buf(struct file *file, void *priv,
3308                           struct v4l2_buffer *p)
3309 {
3310         struct video_device *vdev = video_devdata(file);
3311
3312         if (vb2_queue_is_busy(vdev, file))
3313                 return -EBUSY;
3314         return vb2_prepare_buf(vdev->queue, p);
3315 }
3316 EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);
3317
3318 int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
3319 {
3320         struct video_device *vdev = video_devdata(file);
3321
3322         /* No need to call vb2_queue_is_busy(), anyone can query buffers. */
3323         return vb2_querybuf(vdev->queue, p);
3324 }
3325 EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);
3326
3327 int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
3328 {
3329         struct video_device *vdev = video_devdata(file);
3330
3331         if (vb2_queue_is_busy(vdev, file))
3332                 return -EBUSY;
3333         return vb2_qbuf(vdev->queue, p);
3334 }
3335 EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);
3336
3337 int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
3338 {
3339         struct video_device *vdev = video_devdata(file);
3340
3341         if (vb2_queue_is_busy(vdev, file))
3342                 return -EBUSY;
3343         return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
3344 }
3345 EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);
3346
3347 int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
3348 {
3349         struct video_device *vdev = video_devdata(file);
3350
3351         if (vb2_queue_is_busy(vdev, file))
3352                 return -EBUSY;
3353         return vb2_streamon(vdev->queue, i);
3354 }
3355 EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);
3356
3357 int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
3358 {
3359         struct video_device *vdev = video_devdata(file);
3360
3361         if (vb2_queue_is_busy(vdev, file))
3362                 return -EBUSY;
3363         return vb2_streamoff(vdev->queue, i);
3364 }
3365 EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);
3366
3367 int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
3368 {
3369         struct video_device *vdev = video_devdata(file);
3370
3371         if (vb2_queue_is_busy(vdev, file))
3372                 return -EBUSY;
3373         return vb2_expbuf(vdev->queue, p);
3374 }
3375 EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);
3376
3377 /* v4l2_file_operations helpers */
3378
3379 int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
3380 {
3381         struct video_device *vdev = video_devdata(file);
3382
3383         return vb2_mmap(vdev->queue, vma);
3384 }
3385 EXPORT_SYMBOL_GPL(vb2_fop_mmap);
3386
3387 int _vb2_fop_release(struct file *file, struct mutex *lock)
3388 {
3389         struct video_device *vdev = video_devdata(file);
3390
3391         if (lock)
3392                 mutex_lock(lock);
3393         if (file->private_data == vdev->queue->owner) {
3394                 vb2_queue_release(vdev->queue);
3395                 vdev->queue->owner = NULL;
3396         }
3397         if (lock)
3398                 mutex_unlock(lock);
3399         return v4l2_fh_release(file);
3400 }
3401 EXPORT_SYMBOL_GPL(_vb2_fop_release);
3402
3403 int vb2_fop_release(struct file *file)
3404 {
3405         struct video_device *vdev = video_devdata(file);
3406         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
3407
3408         return _vb2_fop_release(file, lock);
3409 }
3410 EXPORT_SYMBOL_GPL(vb2_fop_release);
3411
3412 ssize_t vb2_fop_write(struct file *file, const char __user *buf,
3413                 size_t count, loff_t *ppos)
3414 {
3415         struct video_device *vdev = video_devdata(file);
3416         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
3417         int err = -EBUSY;
3418
3419         if (lock && mutex_lock_interruptible(lock))
3420                 return -ERESTARTSYS;
3421         if (vb2_queue_is_busy(vdev, file))
3422                 goto exit;
3423         err = vb2_write(vdev->queue, buf, count, ppos,
3424                        file->f_flags & O_NONBLOCK);
3425         if (vdev->queue->fileio)
3426                 vdev->queue->owner = file->private_data;
3427 exit:
3428         if (lock)
3429                 mutex_unlock(lock);
3430         return err;
3431 }
3432 EXPORT_SYMBOL_GPL(vb2_fop_write);
3433
3434 ssize_t vb2_fop_read(struct file *file, char __user *buf,
3435                 size_t count, loff_t *ppos)
3436 {
3437         struct video_device *vdev = video_devdata(file);
3438         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
3439         int err = -EBUSY;
3440
3441         if (lock && mutex_lock_interruptible(lock))
3442                 return -ERESTARTSYS;
3443         if (vb2_queue_is_busy(vdev, file))
3444                 goto exit;
3445         err = vb2_read(vdev->queue, buf, count, ppos,
3446                        file->f_flags & O_NONBLOCK);
3447         if (vdev->queue->fileio)
3448                 vdev->queue->owner = file->private_data;
3449 exit:
3450         if (lock)
3451                 mutex_unlock(lock);
3452         return err;
3453 }
3454 EXPORT_SYMBOL_GPL(vb2_fop_read);
3455
3456 unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
3457 {
3458         struct video_device *vdev = video_devdata(file);
3459         struct vb2_queue *q = vdev->queue;
3460         struct mutex *lock = q->lock ? q->lock : vdev->lock;
3461         unsigned res;
3462         void *fileio;
3463
3464         /*
3465          * If this helper doesn't know how to lock, then you shouldn't be using
3466          * it but you should write your own.
3467          */
3468         WARN_ON(!lock);
3469
3470         if (lock && mutex_lock_interruptible(lock))
3471                 return POLLERR;
3472
3473         fileio = q->fileio;
3474
3475         res = vb2_poll(vdev->queue, file, wait);
3476
3477         /* If fileio was started, then we have a new queue owner. */
3478         if (!fileio && q->fileio)
3479                 q->owner = file->private_data;
3480         if (lock)
3481                 mutex_unlock(lock);
3482         return res;
3483 }
3484 EXPORT_SYMBOL_GPL(vb2_fop_poll);
3485
3486 #ifndef CONFIG_MMU
3487 unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
3488                 unsigned long len, unsigned long pgoff, unsigned long flags)
3489 {
3490         struct video_device *vdev = video_devdata(file);
3491
3492         return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
3493 }
3494 EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
3495 #endif
3496
3497 /* vb2_ops helpers. Only use if vq->lock is non-NULL. */
3498
3499 void vb2_ops_wait_prepare(struct vb2_queue *vq)
3500 {
3501         mutex_unlock(vq->lock);
3502 }
3503 EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);
3504
3505 void vb2_ops_wait_finish(struct vb2_queue *vq)
3506 {
3507         mutex_lock(vq->lock);
3508 }
3509 EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);
3510
3511 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
3512 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
3513 MODULE_LICENSE("GPL");