media: vb2: check memory model for VIDIOC_CREATE_BUFS
[linux-2.6-microblaze.git] / drivers / media / common / videobuf2 / videobuf2-core.c
1 /*
2  * videobuf2-core.c - video buffer 2 core framework
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  *
6  * Author: Pawel Osciak <pawel@osciak.com>
7  *         Marek Szyprowski <m.szyprowski@samsung.com>
8  *
9  * The vb2_thread implementation was based on code from videobuf-dvb.c:
10  *      (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation.
15  */
16
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18
19 #include <linux/err.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/mm.h>
23 #include <linux/poll.h>
24 #include <linux/slab.h>
25 #include <linux/sched.h>
26 #include <linux/freezer.h>
27 #include <linux/kthread.h>
28
29 #include <media/videobuf2-core.h>
30 #include <media/v4l2-mc.h>
31
32 #include <trace/events/vb2.h>
33
34 static int debug;
35 module_param(debug, int, 0644);
36
37 #define dprintk(level, fmt, arg...)                             \
38         do {                                                    \
39                 if (debug >= level)                             \
40                         pr_info("%s: " fmt, __func__, ## arg);  \
41         } while (0)
42
43 #ifdef CONFIG_VIDEO_ADV_DEBUG
44
45 /*
46  * If advanced debugging is on, then count how often each op is called
47  * successfully, which can either be per-buffer or per-queue.
48  *
49  * This makes it easy to check that the 'init' and 'cleanup'
50  * (and variations thereof) stay balanced.
51  */
52
53 #define log_memop(vb, op)                                               \
54         dprintk(2, "call_memop(%p, %d, %s)%s\n",                        \
55                 (vb)->vb2_queue, (vb)->index, #op,                      \
56                 (vb)->vb2_queue->mem_ops->op ? "" : " (nop)")
57
58 #define call_memop(vb, op, args...)                                     \
59 ({                                                                      \
60         struct vb2_queue *_q = (vb)->vb2_queue;                         \
61         int err;                                                        \
62                                                                         \
63         log_memop(vb, op);                                              \
64         err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0;              \
65         if (!err)                                                       \
66                 (vb)->cnt_mem_ ## op++;                                 \
67         err;                                                            \
68 })
69
70 #define call_ptr_memop(vb, op, args...)                                 \
71 ({                                                                      \
72         struct vb2_queue *_q = (vb)->vb2_queue;                         \
73         void *ptr;                                                      \
74                                                                         \
75         log_memop(vb, op);                                              \
76         ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL;           \
77         if (!IS_ERR_OR_NULL(ptr))                                       \
78                 (vb)->cnt_mem_ ## op++;                                 \
79         ptr;                                                            \
80 })
81
82 #define call_void_memop(vb, op, args...)                                \
83 ({                                                                      \
84         struct vb2_queue *_q = (vb)->vb2_queue;                         \
85                                                                         \
86         log_memop(vb, op);                                              \
87         if (_q->mem_ops->op)                                            \
88                 _q->mem_ops->op(args);                                  \
89         (vb)->cnt_mem_ ## op++;                                         \
90 })
91
92 #define log_qop(q, op)                                                  \
93         dprintk(2, "call_qop(%p, %s)%s\n", q, #op,                      \
94                 (q)->ops->op ? "" : " (nop)")
95
96 #define call_qop(q, op, args...)                                        \
97 ({                                                                      \
98         int err;                                                        \
99                                                                         \
100         log_qop(q, op);                                                 \
101         err = (q)->ops->op ? (q)->ops->op(args) : 0;                    \
102         if (!err)                                                       \
103                 (q)->cnt_ ## op++;                                      \
104         err;                                                            \
105 })
106
107 #define call_void_qop(q, op, args...)                                   \
108 ({                                                                      \
109         log_qop(q, op);                                                 \
110         if ((q)->ops->op)                                               \
111                 (q)->ops->op(args);                                     \
112         (q)->cnt_ ## op++;                                              \
113 })
114
115 #define log_vb_qop(vb, op, args...)                                     \
116         dprintk(2, "call_vb_qop(%p, %d, %s)%s\n",                       \
117                 (vb)->vb2_queue, (vb)->index, #op,                      \
118                 (vb)->vb2_queue->ops->op ? "" : " (nop)")
119
120 #define call_vb_qop(vb, op, args...)                                    \
121 ({                                                                      \
122         int err;                                                        \
123                                                                         \
124         log_vb_qop(vb, op);                                             \
125         err = (vb)->vb2_queue->ops->op ?                                \
126                 (vb)->vb2_queue->ops->op(args) : 0;                     \
127         if (!err)                                                       \
128                 (vb)->cnt_ ## op++;                                     \
129         err;                                                            \
130 })
131
132 #define call_void_vb_qop(vb, op, args...)                               \
133 ({                                                                      \
134         log_vb_qop(vb, op);                                             \
135         if ((vb)->vb2_queue->ops->op)                                   \
136                 (vb)->vb2_queue->ops->op(args);                         \
137         (vb)->cnt_ ## op++;                                             \
138 })
139
140 #else
141
142 #define call_memop(vb, op, args...)                                     \
143         ((vb)->vb2_queue->mem_ops->op ?                                 \
144                 (vb)->vb2_queue->mem_ops->op(args) : 0)
145
146 #define call_ptr_memop(vb, op, args...)                                 \
147         ((vb)->vb2_queue->mem_ops->op ?                                 \
148                 (vb)->vb2_queue->mem_ops->op(args) : NULL)
149
150 #define call_void_memop(vb, op, args...)                                \
151         do {                                                            \
152                 if ((vb)->vb2_queue->mem_ops->op)                       \
153                         (vb)->vb2_queue->mem_ops->op(args);             \
154         } while (0)
155
156 #define call_qop(q, op, args...)                                        \
157         ((q)->ops->op ? (q)->ops->op(args) : 0)
158
159 #define call_void_qop(q, op, args...)                                   \
160         do {                                                            \
161                 if ((q)->ops->op)                                       \
162                         (q)->ops->op(args);                             \
163         } while (0)
164
165 #define call_vb_qop(vb, op, args...)                                    \
166         ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
167
168 #define call_void_vb_qop(vb, op, args...)                               \
169         do {                                                            \
170                 if ((vb)->vb2_queue->ops->op)                           \
171                         (vb)->vb2_queue->ops->op(args);                 \
172         } while (0)
173
174 #endif
175
176 #define call_bufop(q, op, args...)                                      \
177 ({                                                                      \
178         int ret = 0;                                                    \
179         if (q && q->buf_ops && q->buf_ops->op)                          \
180                 ret = q->buf_ops->op(args);                             \
181         ret;                                                            \
182 })
183
184 #define call_void_bufop(q, op, args...)                                 \
185 ({                                                                      \
186         if (q && q->buf_ops && q->buf_ops->op)                          \
187                 q->buf_ops->op(args);                                   \
188 })
189
190 static void __vb2_queue_cancel(struct vb2_queue *q);
191 static void __enqueue_in_driver(struct vb2_buffer *vb);
192
193 /*
194  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
195  */
196 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
197 {
198         struct vb2_queue *q = vb->vb2_queue;
199         void *mem_priv;
200         int plane;
201         int ret = -ENOMEM;
202
203         /*
204          * Allocate memory for all planes in this buffer
205          * NOTE: mmapped areas should be page aligned
206          */
207         for (plane = 0; plane < vb->num_planes; ++plane) {
208                 unsigned long size = PAGE_ALIGN(vb->planes[plane].length);
209
210                 mem_priv = call_ptr_memop(vb, alloc,
211                                 q->alloc_devs[plane] ? : q->dev,
212                                 q->dma_attrs, size, q->dma_dir, q->gfp_flags);
213                 if (IS_ERR_OR_NULL(mem_priv)) {
214                         if (mem_priv)
215                                 ret = PTR_ERR(mem_priv);
216                         goto free;
217                 }
218
219                 /* Associate allocator private data with this plane */
220                 vb->planes[plane].mem_priv = mem_priv;
221         }
222
223         return 0;
224 free:
225         /* Free already allocated memory if one of the allocations failed */
226         for (; plane > 0; --plane) {
227                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
228                 vb->planes[plane - 1].mem_priv = NULL;
229         }
230
231         return ret;
232 }
233
234 /*
235  * __vb2_buf_mem_free() - free memory of the given buffer
236  */
237 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
238 {
239         unsigned int plane;
240
241         for (plane = 0; plane < vb->num_planes; ++plane) {
242                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
243                 vb->planes[plane].mem_priv = NULL;
244                 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
245         }
246 }
247
248 /*
249  * __vb2_buf_userptr_put() - release userspace memory associated with
250  * a USERPTR buffer
251  */
252 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
253 {
254         unsigned int plane;
255
256         for (plane = 0; plane < vb->num_planes; ++plane) {
257                 if (vb->planes[plane].mem_priv)
258                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
259                 vb->planes[plane].mem_priv = NULL;
260         }
261 }
262
263 /*
264  * __vb2_plane_dmabuf_put() - release memory associated with
265  * a DMABUF shared plane
266  */
267 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
268 {
269         if (!p->mem_priv)
270                 return;
271
272         if (p->dbuf_mapped)
273                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
274
275         call_void_memop(vb, detach_dmabuf, p->mem_priv);
276         dma_buf_put(p->dbuf);
277         p->mem_priv = NULL;
278         p->dbuf = NULL;
279         p->dbuf_mapped = 0;
280 }
281
282 /*
283  * __vb2_buf_dmabuf_put() - release memory associated with
284  * a DMABUF shared buffer
285  */
286 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
287 {
288         unsigned int plane;
289
290         for (plane = 0; plane < vb->num_planes; ++plane)
291                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
292 }
293
294 /*
295  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
296  * the buffer.
297  */
298 static void __setup_offsets(struct vb2_buffer *vb)
299 {
300         struct vb2_queue *q = vb->vb2_queue;
301         unsigned int plane;
302         unsigned long off = 0;
303
304         if (vb->index) {
305                 struct vb2_buffer *prev = q->bufs[vb->index - 1];
306                 struct vb2_plane *p = &prev->planes[prev->num_planes - 1];
307
308                 off = PAGE_ALIGN(p->m.offset + p->length);
309         }
310
311         for (plane = 0; plane < vb->num_planes; ++plane) {
312                 vb->planes[plane].m.offset = off;
313
314                 dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
315                                 vb->index, plane, off);
316
317                 off += vb->planes[plane].length;
318                 off = PAGE_ALIGN(off);
319         }
320 }
321
322 /*
323  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
324  * video buffer memory for all buffers/planes on the queue and initializes the
325  * queue
326  *
327  * Returns the number of buffers successfully allocated.
328  */
329 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
330                              unsigned int num_buffers, unsigned int num_planes,
331                              const unsigned plane_sizes[VB2_MAX_PLANES])
332 {
333         unsigned int buffer, plane;
334         struct vb2_buffer *vb;
335         int ret;
336
337         /* Ensure that q->num_buffers+num_buffers is below VB2_MAX_FRAME */
338         num_buffers = min_t(unsigned int, num_buffers,
339                             VB2_MAX_FRAME - q->num_buffers);
340
341         for (buffer = 0; buffer < num_buffers; ++buffer) {
342                 /* Allocate videobuf buffer structures */
343                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
344                 if (!vb) {
345                         dprintk(1, "memory alloc for buffer struct failed\n");
346                         break;
347                 }
348
349                 vb->state = VB2_BUF_STATE_DEQUEUED;
350                 vb->vb2_queue = q;
351                 vb->num_planes = num_planes;
352                 vb->index = q->num_buffers + buffer;
353                 vb->type = q->type;
354                 vb->memory = memory;
355                 for (plane = 0; plane < num_planes; ++plane) {
356                         vb->planes[plane].length = plane_sizes[plane];
357                         vb->planes[plane].min_length = plane_sizes[plane];
358                 }
359                 call_void_bufop(q, init_buffer, vb);
360
361                 q->bufs[vb->index] = vb;
362
363                 /* Allocate video buffer memory for the MMAP type */
364                 if (memory == VB2_MEMORY_MMAP) {
365                         ret = __vb2_buf_mem_alloc(vb);
366                         if (ret) {
367                                 dprintk(1, "failed allocating memory for buffer %d\n",
368                                         buffer);
369                                 q->bufs[vb->index] = NULL;
370                                 kfree(vb);
371                                 break;
372                         }
373                         __setup_offsets(vb);
374                         /*
375                          * Call the driver-provided buffer initialization
376                          * callback, if given. An error in initialization
377                          * results in queue setup failure.
378                          */
379                         ret = call_vb_qop(vb, buf_init, vb);
380                         if (ret) {
381                                 dprintk(1, "buffer %d %p initialization failed\n",
382                                         buffer, vb);
383                                 __vb2_buf_mem_free(vb);
384                                 q->bufs[vb->index] = NULL;
385                                 kfree(vb);
386                                 break;
387                         }
388                 }
389         }
390
391         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
392                         buffer, num_planes);
393
394         return buffer;
395 }
396
397 /*
398  * __vb2_free_mem() - release all video buffer memory for a given queue
399  */
400 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
401 {
402         unsigned int buffer;
403         struct vb2_buffer *vb;
404
405         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
406              ++buffer) {
407                 vb = q->bufs[buffer];
408                 if (!vb)
409                         continue;
410
411                 /* Free MMAP buffers or release USERPTR buffers */
412                 if (q->memory == VB2_MEMORY_MMAP)
413                         __vb2_buf_mem_free(vb);
414                 else if (q->memory == VB2_MEMORY_DMABUF)
415                         __vb2_buf_dmabuf_put(vb);
416                 else
417                         __vb2_buf_userptr_put(vb);
418         }
419 }
420
421 /*
422  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
423  * related information, if no buffers are left return the queue to an
424  * uninitialized state. Might be called even if the queue has already been freed.
425  */
426 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
427 {
428         unsigned int buffer;
429
430         /*
431          * Sanity check: when preparing a buffer the queue lock is released for
432          * a short while (see __buf_prepare for the details), which would allow
433          * a race with a reqbufs which can call this function. Removing the
434          * buffers from underneath __buf_prepare is obviously a bad idea, so we
435          * check if any of the buffers is in the state PREPARING, and if so we
436          * just return -EAGAIN.
437          */
438         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
439              ++buffer) {
440                 if (q->bufs[buffer] == NULL)
441                         continue;
442                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
443                         dprintk(1, "preparing buffers, cannot free\n");
444                         return -EAGAIN;
445                 }
446         }
447
448         /* Call driver-provided cleanup function for each buffer, if provided */
449         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
450              ++buffer) {
451                 struct vb2_buffer *vb = q->bufs[buffer];
452
453                 if (vb && vb->planes[0].mem_priv)
454                         call_void_vb_qop(vb, buf_cleanup, vb);
455         }
456
457         /* Release video buffer memory */
458         __vb2_free_mem(q, buffers);
459
460 #ifdef CONFIG_VIDEO_ADV_DEBUG
461         /*
462          * Check that all the calls were balances during the life-time of this
463          * queue. If not (or if the debug level is 1 or up), then dump the
464          * counters to the kernel log.
465          */
466         if (q->num_buffers) {
467                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
468                                   q->cnt_wait_prepare != q->cnt_wait_finish;
469
470                 if (unbalanced || debug) {
471                         pr_info("counters for queue %p:%s\n", q,
472                                 unbalanced ? " UNBALANCED!" : "");
473                         pr_info("     setup: %u start_streaming: %u stop_streaming: %u\n",
474                                 q->cnt_queue_setup, q->cnt_start_streaming,
475                                 q->cnt_stop_streaming);
476                         pr_info("     wait_prepare: %u wait_finish: %u\n",
477                                 q->cnt_wait_prepare, q->cnt_wait_finish);
478                 }
479                 q->cnt_queue_setup = 0;
480                 q->cnt_wait_prepare = 0;
481                 q->cnt_wait_finish = 0;
482                 q->cnt_start_streaming = 0;
483                 q->cnt_stop_streaming = 0;
484         }
485         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
486                 struct vb2_buffer *vb = q->bufs[buffer];
487                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
488                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
489                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
490                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
491                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
492                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
493                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
494                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
495
496                 if (unbalanced || debug) {
497                         pr_info("   counters for queue %p, buffer %d:%s\n",
498                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
499                         pr_info("     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
500                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
501                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
502                         pr_info("     buf_queue: %u buf_done: %u buf_request_complete: %u\n",
503                                 vb->cnt_buf_queue, vb->cnt_buf_done,
504                                 vb->cnt_buf_request_complete);
505                         pr_info("     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
506                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
507                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
508                                 vb->cnt_mem_mmap);
509                         pr_info("     get_userptr: %u put_userptr: %u\n",
510                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
511                         pr_info("     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
512                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
513                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
514                         pr_info("     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
515                                 vb->cnt_mem_get_dmabuf,
516                                 vb->cnt_mem_num_users,
517                                 vb->cnt_mem_vaddr,
518                                 vb->cnt_mem_cookie);
519                 }
520         }
521 #endif
522
523         /* Free videobuf buffers */
524         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
525              ++buffer) {
526                 kfree(q->bufs[buffer]);
527                 q->bufs[buffer] = NULL;
528         }
529
530         q->num_buffers -= buffers;
531         if (!q->num_buffers) {
532                 q->memory = VB2_MEMORY_UNKNOWN;
533                 INIT_LIST_HEAD(&q->queued_list);
534         }
535         return 0;
536 }
537
538 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
539 {
540         unsigned int plane;
541         for (plane = 0; plane < vb->num_planes; ++plane) {
542                 void *mem_priv = vb->planes[plane].mem_priv;
543                 /*
544                  * If num_users() has not been provided, call_memop
545                  * will return 0, apparently nobody cares about this
546                  * case anyway. If num_users() returns more than 1,
547                  * we are not the only user of the plane's memory.
548                  */
549                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
550                         return true;
551         }
552         return false;
553 }
554 EXPORT_SYMBOL(vb2_buffer_in_use);
555
556 /*
557  * __buffers_in_use() - return true if any buffers on the queue are in use and
558  * the queue cannot be freed (by the means of REQBUFS(0)) call
559  */
560 static bool __buffers_in_use(struct vb2_queue *q)
561 {
562         unsigned int buffer;
563         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
564                 if (vb2_buffer_in_use(q, q->bufs[buffer]))
565                         return true;
566         }
567         return false;
568 }
569
570 void vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
571 {
572         call_void_bufop(q, fill_user_buffer, q->bufs[index], pb);
573 }
574 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
575
576 /*
577  * __verify_userptr_ops() - verify that all memory operations required for
578  * USERPTR queue type have been provided
579  */
580 static int __verify_userptr_ops(struct vb2_queue *q)
581 {
582         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
583             !q->mem_ops->put_userptr)
584                 return -EINVAL;
585
586         return 0;
587 }
588
589 /*
590  * __verify_mmap_ops() - verify that all memory operations required for
591  * MMAP queue type have been provided
592  */
593 static int __verify_mmap_ops(struct vb2_queue *q)
594 {
595         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
596             !q->mem_ops->put || !q->mem_ops->mmap)
597                 return -EINVAL;
598
599         return 0;
600 }
601
602 /*
603  * __verify_dmabuf_ops() - verify that all memory operations required for
604  * DMABUF queue type have been provided
605  */
606 static int __verify_dmabuf_ops(struct vb2_queue *q)
607 {
608         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
609             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
610             !q->mem_ops->unmap_dmabuf)
611                 return -EINVAL;
612
613         return 0;
614 }
615
616 int vb2_verify_memory_type(struct vb2_queue *q,
617                 enum vb2_memory memory, unsigned int type)
618 {
619         if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
620             memory != VB2_MEMORY_DMABUF) {
621                 dprintk(1, "unsupported memory type\n");
622                 return -EINVAL;
623         }
624
625         if (type != q->type) {
626                 dprintk(1, "requested type is incorrect\n");
627                 return -EINVAL;
628         }
629
630         /*
631          * Make sure all the required memory ops for given memory type
632          * are available.
633          */
634         if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
635                 dprintk(1, "MMAP for current setup unsupported\n");
636                 return -EINVAL;
637         }
638
639         if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
640                 dprintk(1, "USERPTR for current setup unsupported\n");
641                 return -EINVAL;
642         }
643
644         if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
645                 dprintk(1, "DMABUF for current setup unsupported\n");
646                 return -EINVAL;
647         }
648
649         /*
650          * Place the busy tests at the end: -EBUSY can be ignored when
651          * create_bufs is called with count == 0, but count == 0 should still
652          * do the memory and type validation.
653          */
654         if (vb2_fileio_is_active(q)) {
655                 dprintk(1, "file io in progress\n");
656                 return -EBUSY;
657         }
658         return 0;
659 }
660 EXPORT_SYMBOL(vb2_verify_memory_type);
661
662 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
663                 unsigned int *count)
664 {
665         unsigned int num_buffers, allocated_buffers, num_planes = 0;
666         unsigned plane_sizes[VB2_MAX_PLANES] = { };
667         unsigned int i;
668         int ret;
669
670         if (q->streaming) {
671                 dprintk(1, "streaming active\n");
672                 return -EBUSY;
673         }
674
675         if (*count == 0 || q->num_buffers != 0 ||
676             (q->memory != VB2_MEMORY_UNKNOWN && q->memory != memory)) {
677                 /*
678                  * We already have buffers allocated, so first check if they
679                  * are not in use and can be freed.
680                  */
681                 mutex_lock(&q->mmap_lock);
682                 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
683                         mutex_unlock(&q->mmap_lock);
684                         dprintk(1, "memory in use, cannot free\n");
685                         return -EBUSY;
686                 }
687
688                 /*
689                  * Call queue_cancel to clean up any buffers in the
690                  * QUEUED state which is possible if buffers were prepared or
691                  * queued without ever calling STREAMON.
692                  */
693                 __vb2_queue_cancel(q);
694                 ret = __vb2_queue_free(q, q->num_buffers);
695                 mutex_unlock(&q->mmap_lock);
696                 if (ret)
697                         return ret;
698
699                 /*
700                  * In case of REQBUFS(0) return immediately without calling
701                  * driver's queue_setup() callback and allocating resources.
702                  */
703                 if (*count == 0)
704                         return 0;
705         }
706
707         /*
708          * Make sure the requested values and current defaults are sane.
709          */
710         WARN_ON(q->min_buffers_needed > VB2_MAX_FRAME);
711         num_buffers = max_t(unsigned int, *count, q->min_buffers_needed);
712         num_buffers = min_t(unsigned int, num_buffers, VB2_MAX_FRAME);
713         memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
714         q->memory = memory;
715
716         /*
717          * Ask the driver how many buffers and planes per buffer it requires.
718          * Driver also sets the size and allocator context for each plane.
719          */
720         ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
721                        plane_sizes, q->alloc_devs);
722         if (ret)
723                 return ret;
724
725         /* Check that driver has set sane values */
726         if (WARN_ON(!num_planes))
727                 return -EINVAL;
728
729         for (i = 0; i < num_planes; i++)
730                 if (WARN_ON(!plane_sizes[i]))
731                         return -EINVAL;
732
733         /* Finally, allocate buffers and video memory */
734         allocated_buffers =
735                 __vb2_queue_alloc(q, memory, num_buffers, num_planes, plane_sizes);
736         if (allocated_buffers == 0) {
737                 dprintk(1, "memory allocation failed\n");
738                 return -ENOMEM;
739         }
740
741         /*
742          * There is no point in continuing if we can't allocate the minimum
743          * number of buffers needed by this vb2_queue.
744          */
745         if (allocated_buffers < q->min_buffers_needed)
746                 ret = -ENOMEM;
747
748         /*
749          * Check if driver can handle the allocated number of buffers.
750          */
751         if (!ret && allocated_buffers < num_buffers) {
752                 num_buffers = allocated_buffers;
753                 /*
754                  * num_planes is set by the previous queue_setup(), but since it
755                  * signals to queue_setup() whether it is called from create_bufs()
756                  * vs reqbufs() we zero it here to signal that queue_setup() is
757                  * called for the reqbufs() case.
758                  */
759                 num_planes = 0;
760
761                 ret = call_qop(q, queue_setup, q, &num_buffers,
762                                &num_planes, plane_sizes, q->alloc_devs);
763
764                 if (!ret && allocated_buffers < num_buffers)
765                         ret = -ENOMEM;
766
767                 /*
768                  * Either the driver has accepted a smaller number of buffers,
769                  * or .queue_setup() returned an error
770                  */
771         }
772
773         mutex_lock(&q->mmap_lock);
774         q->num_buffers = allocated_buffers;
775
776         if (ret < 0) {
777                 /*
778                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
779                  * from q->num_buffers.
780                  */
781                 __vb2_queue_free(q, allocated_buffers);
782                 mutex_unlock(&q->mmap_lock);
783                 return ret;
784         }
785         mutex_unlock(&q->mmap_lock);
786
787         /*
788          * Return the number of successfully allocated buffers
789          * to the userspace.
790          */
791         *count = allocated_buffers;
792         q->waiting_for_buffers = !q->is_output;
793
794         return 0;
795 }
796 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
797
798 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
799                 unsigned int *count, unsigned requested_planes,
800                 const unsigned requested_sizes[])
801 {
802         unsigned int num_planes = 0, num_buffers, allocated_buffers;
803         unsigned plane_sizes[VB2_MAX_PLANES] = { };
804         int ret;
805
806         if (q->num_buffers == VB2_MAX_FRAME) {
807                 dprintk(1, "maximum number of buffers already allocated\n");
808                 return -ENOBUFS;
809         }
810
811         if (!q->num_buffers) {
812                 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
813                 q->memory = memory;
814                 q->waiting_for_buffers = !q->is_output;
815         } else if (q->memory != memory) {
816                 dprintk(1, "memory model mismatch\n");
817                 return -EINVAL;
818         }
819
820         num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
821
822         if (requested_planes && requested_sizes) {
823                 num_planes = requested_planes;
824                 memcpy(plane_sizes, requested_sizes, sizeof(plane_sizes));
825         }
826
827         /*
828          * Ask the driver, whether the requested number of buffers, planes per
829          * buffer and their sizes are acceptable
830          */
831         ret = call_qop(q, queue_setup, q, &num_buffers,
832                        &num_planes, plane_sizes, q->alloc_devs);
833         if (ret)
834                 return ret;
835
836         /* Finally, allocate buffers and video memory */
837         allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
838                                 num_planes, plane_sizes);
839         if (allocated_buffers == 0) {
840                 dprintk(1, "memory allocation failed\n");
841                 return -ENOMEM;
842         }
843
844         /*
845          * Check if driver can handle the so far allocated number of buffers.
846          */
847         if (allocated_buffers < num_buffers) {
848                 num_buffers = allocated_buffers;
849
850                 /*
851                  * q->num_buffers contains the total number of buffers, that the
852                  * queue driver has set up
853                  */
854                 ret = call_qop(q, queue_setup, q, &num_buffers,
855                                &num_planes, plane_sizes, q->alloc_devs);
856
857                 if (!ret && allocated_buffers < num_buffers)
858                         ret = -ENOMEM;
859
860                 /*
861                  * Either the driver has accepted a smaller number of buffers,
862                  * or .queue_setup() returned an error
863                  */
864         }
865
866         mutex_lock(&q->mmap_lock);
867         q->num_buffers += allocated_buffers;
868
869         if (ret < 0) {
870                 /*
871                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
872                  * from q->num_buffers.
873                  */
874                 __vb2_queue_free(q, allocated_buffers);
875                 mutex_unlock(&q->mmap_lock);
876                 return -ENOMEM;
877         }
878         mutex_unlock(&q->mmap_lock);
879
880         /*
881          * Return the number of successfully allocated buffers
882          * to the userspace.
883          */
884         *count = allocated_buffers;
885
886         return 0;
887 }
888 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
889
890 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
891 {
892         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
893                 return NULL;
894
895         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
896
897 }
898 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
899
900 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
901 {
902         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
903                 return NULL;
904
905         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
906 }
907 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
908
909 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
910 {
911         struct vb2_queue *q = vb->vb2_queue;
912         unsigned long flags;
913         unsigned int plane;
914
915         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
916                 return;
917
918         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
919                     state != VB2_BUF_STATE_ERROR &&
920                     state != VB2_BUF_STATE_QUEUED &&
921                     state != VB2_BUF_STATE_REQUEUEING))
922                 state = VB2_BUF_STATE_ERROR;
923
924 #ifdef CONFIG_VIDEO_ADV_DEBUG
925         /*
926          * Although this is not a callback, it still does have to balance
927          * with the buf_queue op. So update this counter manually.
928          */
929         vb->cnt_buf_done++;
930 #endif
931         dprintk(4, "done processing on buffer %d, state: %d\n",
932                         vb->index, state);
933
934         if (state != VB2_BUF_STATE_QUEUED &&
935             state != VB2_BUF_STATE_REQUEUEING) {
936                 /* sync buffers */
937                 for (plane = 0; plane < vb->num_planes; ++plane)
938                         call_void_memop(vb, finish, vb->planes[plane].mem_priv);
939                 vb->synced = false;
940         }
941
942         spin_lock_irqsave(&q->done_lock, flags);
943         if (state == VB2_BUF_STATE_QUEUED ||
944             state == VB2_BUF_STATE_REQUEUEING) {
945                 vb->state = VB2_BUF_STATE_QUEUED;
946         } else {
947                 /* Add the buffer to the done buffers list */
948                 list_add_tail(&vb->done_entry, &q->done_list);
949                 vb->state = state;
950         }
951         atomic_dec(&q->owned_by_drv_count);
952
953         if (vb->req_obj.req) {
954                 /* This is not supported at the moment */
955                 WARN_ON(state == VB2_BUF_STATE_REQUEUEING);
956                 media_request_object_unbind(&vb->req_obj);
957                 media_request_object_put(&vb->req_obj);
958         }
959
960         spin_unlock_irqrestore(&q->done_lock, flags);
961
962         trace_vb2_buf_done(q, vb);
963
964         switch (state) {
965         case VB2_BUF_STATE_QUEUED:
966                 return;
967         case VB2_BUF_STATE_REQUEUEING:
968                 if (q->start_streaming_called)
969                         __enqueue_in_driver(vb);
970                 return;
971         default:
972                 /* Inform any processes that may be waiting for buffers */
973                 wake_up(&q->done_wq);
974                 break;
975         }
976 }
977 EXPORT_SYMBOL_GPL(vb2_buffer_done);
978
979 void vb2_discard_done(struct vb2_queue *q)
980 {
981         struct vb2_buffer *vb;
982         unsigned long flags;
983
984         spin_lock_irqsave(&q->done_lock, flags);
985         list_for_each_entry(vb, &q->done_list, done_entry)
986                 vb->state = VB2_BUF_STATE_ERROR;
987         spin_unlock_irqrestore(&q->done_lock, flags);
988 }
989 EXPORT_SYMBOL_GPL(vb2_discard_done);
990
991 /*
992  * __prepare_mmap() - prepare an MMAP buffer
993  */
994 static int __prepare_mmap(struct vb2_buffer *vb)
995 {
996         int ret = 0;
997
998         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
999                          vb, vb->planes);
1000         return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
1001 }
1002
1003 /*
1004  * __prepare_userptr() - prepare a USERPTR buffer
1005  */
1006 static int __prepare_userptr(struct vb2_buffer *vb)
1007 {
1008         struct vb2_plane planes[VB2_MAX_PLANES];
1009         struct vb2_queue *q = vb->vb2_queue;
1010         void *mem_priv;
1011         unsigned int plane;
1012         int ret = 0;
1013         bool reacquired = vb->planes[0].mem_priv == NULL;
1014
1015         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1016         /* Copy relevant information provided by the userspace */
1017         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1018                          vb, planes);
1019         if (ret)
1020                 return ret;
1021
1022         for (plane = 0; plane < vb->num_planes; ++plane) {
1023                 /* Skip the plane if already verified */
1024                 if (vb->planes[plane].m.userptr &&
1025                         vb->planes[plane].m.userptr == planes[plane].m.userptr
1026                         && vb->planes[plane].length == planes[plane].length)
1027                         continue;
1028
1029                 dprintk(3, "userspace address for plane %d changed, reacquiring memory\n",
1030                         plane);
1031
1032                 /* Check if the provided plane buffer is large enough */
1033                 if (planes[plane].length < vb->planes[plane].min_length) {
1034                         dprintk(1, "provided buffer size %u is less than setup size %u for plane %d\n",
1035                                                 planes[plane].length,
1036                                                 vb->planes[plane].min_length,
1037                                                 plane);
1038                         ret = -EINVAL;
1039                         goto err;
1040                 }
1041
1042                 /* Release previously acquired memory if present */
1043                 if (vb->planes[plane].mem_priv) {
1044                         if (!reacquired) {
1045                                 reacquired = true;
1046                                 call_void_vb_qop(vb, buf_cleanup, vb);
1047                         }
1048                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1049                 }
1050
1051                 vb->planes[plane].mem_priv = NULL;
1052                 vb->planes[plane].bytesused = 0;
1053                 vb->planes[plane].length = 0;
1054                 vb->planes[plane].m.userptr = 0;
1055                 vb->planes[plane].data_offset = 0;
1056
1057                 /* Acquire each plane's memory */
1058                 mem_priv = call_ptr_memop(vb, get_userptr,
1059                                 q->alloc_devs[plane] ? : q->dev,
1060                                 planes[plane].m.userptr,
1061                                 planes[plane].length, q->dma_dir);
1062                 if (IS_ERR(mem_priv)) {
1063                         dprintk(1, "failed acquiring userspace memory for plane %d\n",
1064                                 plane);
1065                         ret = PTR_ERR(mem_priv);
1066                         goto err;
1067                 }
1068                 vb->planes[plane].mem_priv = mem_priv;
1069         }
1070
1071         /*
1072          * Now that everything is in order, copy relevant information
1073          * provided by userspace.
1074          */
1075         for (plane = 0; plane < vb->num_planes; ++plane) {
1076                 vb->planes[plane].bytesused = planes[plane].bytesused;
1077                 vb->planes[plane].length = planes[plane].length;
1078                 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1079                 vb->planes[plane].data_offset = planes[plane].data_offset;
1080         }
1081
1082         if (reacquired) {
1083                 /*
1084                  * One or more planes changed, so we must call buf_init to do
1085                  * the driver-specific initialization on the newly acquired
1086                  * buffer, if provided.
1087                  */
1088                 ret = call_vb_qop(vb, buf_init, vb);
1089                 if (ret) {
1090                         dprintk(1, "buffer initialization failed\n");
1091                         goto err;
1092                 }
1093         }
1094
1095         ret = call_vb_qop(vb, buf_prepare, vb);
1096         if (ret) {
1097                 dprintk(1, "buffer preparation failed\n");
1098                 call_void_vb_qop(vb, buf_cleanup, vb);
1099                 goto err;
1100         }
1101
1102         return 0;
1103 err:
1104         /* In case of errors, release planes that were already acquired */
1105         for (plane = 0; plane < vb->num_planes; ++plane) {
1106                 if (vb->planes[plane].mem_priv)
1107                         call_void_memop(vb, put_userptr,
1108                                 vb->planes[plane].mem_priv);
1109                 vb->planes[plane].mem_priv = NULL;
1110                 vb->planes[plane].m.userptr = 0;
1111                 vb->planes[plane].length = 0;
1112         }
1113
1114         return ret;
1115 }
1116
1117 /*
1118  * __prepare_dmabuf() - prepare a DMABUF buffer
1119  */
1120 static int __prepare_dmabuf(struct vb2_buffer *vb)
1121 {
1122         struct vb2_plane planes[VB2_MAX_PLANES];
1123         struct vb2_queue *q = vb->vb2_queue;
1124         void *mem_priv;
1125         unsigned int plane;
1126         int ret = 0;
1127         bool reacquired = vb->planes[0].mem_priv == NULL;
1128
1129         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1130         /* Copy relevant information provided by the userspace */
1131         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1132                          vb, planes);
1133         if (ret)
1134                 return ret;
1135
1136         for (plane = 0; plane < vb->num_planes; ++plane) {
1137                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1138
1139                 if (IS_ERR_OR_NULL(dbuf)) {
1140                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1141                                 plane);
1142                         ret = -EINVAL;
1143                         goto err;
1144                 }
1145
1146                 /* use DMABUF size if length is not provided */
1147                 if (planes[plane].length == 0)
1148                         planes[plane].length = dbuf->size;
1149
1150                 if (planes[plane].length < vb->planes[plane].min_length) {
1151                         dprintk(1, "invalid dmabuf length %u for plane %d, minimum length %u\n",
1152                                 planes[plane].length, plane,
1153                                 vb->planes[plane].min_length);
1154                         dma_buf_put(dbuf);
1155                         ret = -EINVAL;
1156                         goto err;
1157                 }
1158
1159                 /* Skip the plane if already verified */
1160                 if (dbuf == vb->planes[plane].dbuf &&
1161                         vb->planes[plane].length == planes[plane].length) {
1162                         dma_buf_put(dbuf);
1163                         continue;
1164                 }
1165
1166                 dprintk(3, "buffer for plane %d changed\n", plane);
1167
1168                 if (!reacquired) {
1169                         reacquired = true;
1170                         call_void_vb_qop(vb, buf_cleanup, vb);
1171                 }
1172
1173                 /* Release previously acquired memory if present */
1174                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1175                 vb->planes[plane].bytesused = 0;
1176                 vb->planes[plane].length = 0;
1177                 vb->planes[plane].m.fd = 0;
1178                 vb->planes[plane].data_offset = 0;
1179
1180                 /* Acquire each plane's memory */
1181                 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1182                                 q->alloc_devs[plane] ? : q->dev,
1183                                 dbuf, planes[plane].length, q->dma_dir);
1184                 if (IS_ERR(mem_priv)) {
1185                         dprintk(1, "failed to attach dmabuf\n");
1186                         ret = PTR_ERR(mem_priv);
1187                         dma_buf_put(dbuf);
1188                         goto err;
1189                 }
1190
1191                 vb->planes[plane].dbuf = dbuf;
1192                 vb->planes[plane].mem_priv = mem_priv;
1193         }
1194
1195         /*
1196          * This pins the buffer(s) with dma_buf_map_attachment()). It's done
1197          * here instead just before the DMA, while queueing the buffer(s) so
1198          * userspace knows sooner rather than later if the dma-buf map fails.
1199          */
1200         for (plane = 0; plane < vb->num_planes; ++plane) {
1201                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1202                 if (ret) {
1203                         dprintk(1, "failed to map dmabuf for plane %d\n",
1204                                 plane);
1205                         goto err;
1206                 }
1207                 vb->planes[plane].dbuf_mapped = 1;
1208         }
1209
1210         /*
1211          * Now that everything is in order, copy relevant information
1212          * provided by userspace.
1213          */
1214         for (plane = 0; plane < vb->num_planes; ++plane) {
1215                 vb->planes[plane].bytesused = planes[plane].bytesused;
1216                 vb->planes[plane].length = planes[plane].length;
1217                 vb->planes[plane].m.fd = planes[plane].m.fd;
1218                 vb->planes[plane].data_offset = planes[plane].data_offset;
1219         }
1220
1221         if (reacquired) {
1222                 /*
1223                  * Call driver-specific initialization on the newly acquired buffer,
1224                  * if provided.
1225                  */
1226                 ret = call_vb_qop(vb, buf_init, vb);
1227                 if (ret) {
1228                         dprintk(1, "buffer initialization failed\n");
1229                         goto err;
1230                 }
1231         }
1232
1233         ret = call_vb_qop(vb, buf_prepare, vb);
1234         if (ret) {
1235                 dprintk(1, "buffer preparation failed\n");
1236                 call_void_vb_qop(vb, buf_cleanup, vb);
1237                 goto err;
1238         }
1239
1240         return 0;
1241 err:
1242         /* In case of errors, release planes that were already acquired */
1243         __vb2_buf_dmabuf_put(vb);
1244
1245         return ret;
1246 }
1247
1248 /*
1249  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1250  */
1251 static void __enqueue_in_driver(struct vb2_buffer *vb)
1252 {
1253         struct vb2_queue *q = vb->vb2_queue;
1254
1255         vb->state = VB2_BUF_STATE_ACTIVE;
1256         atomic_inc(&q->owned_by_drv_count);
1257
1258         trace_vb2_buf_queue(q, vb);
1259
1260         call_void_vb_qop(vb, buf_queue, vb);
1261 }
1262
1263 static int __buf_prepare(struct vb2_buffer *vb)
1264 {
1265         struct vb2_queue *q = vb->vb2_queue;
1266         enum vb2_buffer_state orig_state = vb->state;
1267         unsigned int plane;
1268         int ret;
1269
1270         if (q->error) {
1271                 dprintk(1, "fatal error occurred on queue\n");
1272                 return -EIO;
1273         }
1274
1275         if (vb->prepared)
1276                 return 0;
1277         WARN_ON(vb->synced);
1278
1279         vb->state = VB2_BUF_STATE_PREPARING;
1280
1281         switch (q->memory) {
1282         case VB2_MEMORY_MMAP:
1283                 ret = __prepare_mmap(vb);
1284                 break;
1285         case VB2_MEMORY_USERPTR:
1286                 ret = __prepare_userptr(vb);
1287                 break;
1288         case VB2_MEMORY_DMABUF:
1289                 ret = __prepare_dmabuf(vb);
1290                 break;
1291         default:
1292                 WARN(1, "Invalid queue type\n");
1293                 ret = -EINVAL;
1294                 break;
1295         }
1296
1297         if (ret) {
1298                 dprintk(1, "buffer preparation failed: %d\n", ret);
1299                 vb->state = orig_state;
1300                 return ret;
1301         }
1302
1303         /* sync buffers */
1304         for (plane = 0; plane < vb->num_planes; ++plane)
1305                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1306
1307         vb->synced = true;
1308         vb->prepared = true;
1309         vb->state = orig_state;
1310
1311         return 0;
1312 }
1313
1314 static int vb2_req_prepare(struct media_request_object *obj)
1315 {
1316         struct vb2_buffer *vb = container_of(obj, struct vb2_buffer, req_obj);
1317         int ret;
1318
1319         if (WARN_ON(vb->state != VB2_BUF_STATE_IN_REQUEST))
1320                 return -EINVAL;
1321
1322         mutex_lock(vb->vb2_queue->lock);
1323         ret = __buf_prepare(vb);
1324         mutex_unlock(vb->vb2_queue->lock);
1325         return ret;
1326 }
1327
1328 static void __vb2_dqbuf(struct vb2_buffer *vb);
1329
1330 static void vb2_req_unprepare(struct media_request_object *obj)
1331 {
1332         struct vb2_buffer *vb = container_of(obj, struct vb2_buffer, req_obj);
1333
1334         mutex_lock(vb->vb2_queue->lock);
1335         __vb2_dqbuf(vb);
1336         vb->state = VB2_BUF_STATE_IN_REQUEST;
1337         mutex_unlock(vb->vb2_queue->lock);
1338         WARN_ON(!vb->req_obj.req);
1339 }
1340
1341 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb,
1342                   struct media_request *req);
1343
1344 static void vb2_req_queue(struct media_request_object *obj)
1345 {
1346         struct vb2_buffer *vb = container_of(obj, struct vb2_buffer, req_obj);
1347
1348         mutex_lock(vb->vb2_queue->lock);
1349         vb2_core_qbuf(vb->vb2_queue, vb->index, NULL, NULL);
1350         mutex_unlock(vb->vb2_queue->lock);
1351 }
1352
1353 static void vb2_req_unbind(struct media_request_object *obj)
1354 {
1355         struct vb2_buffer *vb = container_of(obj, struct vb2_buffer, req_obj);
1356
1357         if (vb->state == VB2_BUF_STATE_IN_REQUEST)
1358                 call_void_bufop(vb->vb2_queue, init_buffer, vb);
1359 }
1360
1361 static void vb2_req_release(struct media_request_object *obj)
1362 {
1363         struct vb2_buffer *vb = container_of(obj, struct vb2_buffer, req_obj);
1364
1365         if (vb->state == VB2_BUF_STATE_IN_REQUEST)
1366                 vb->state = VB2_BUF_STATE_DEQUEUED;
1367 }
1368
1369 static const struct media_request_object_ops vb2_core_req_ops = {
1370         .prepare = vb2_req_prepare,
1371         .unprepare = vb2_req_unprepare,
1372         .queue = vb2_req_queue,
1373         .unbind = vb2_req_unbind,
1374         .release = vb2_req_release,
1375 };
1376
1377 bool vb2_request_object_is_buffer(struct media_request_object *obj)
1378 {
1379         return obj->ops == &vb2_core_req_ops;
1380 }
1381 EXPORT_SYMBOL_GPL(vb2_request_object_is_buffer);
1382
1383 unsigned int vb2_request_buffer_cnt(struct media_request *req)
1384 {
1385         struct media_request_object *obj;
1386         unsigned long flags;
1387         unsigned int buffer_cnt = 0;
1388
1389         spin_lock_irqsave(&req->lock, flags);
1390         list_for_each_entry(obj, &req->objects, list)
1391                 if (vb2_request_object_is_buffer(obj))
1392                         buffer_cnt++;
1393         spin_unlock_irqrestore(&req->lock, flags);
1394
1395         return buffer_cnt;
1396 }
1397 EXPORT_SYMBOL_GPL(vb2_request_buffer_cnt);
1398
1399 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1400 {
1401         struct vb2_buffer *vb;
1402         int ret;
1403
1404         vb = q->bufs[index];
1405         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1406                 dprintk(1, "invalid buffer state %d\n",
1407                         vb->state);
1408                 return -EINVAL;
1409         }
1410         if (vb->prepared) {
1411                 dprintk(1, "buffer already prepared\n");
1412                 return -EINVAL;
1413         }
1414
1415         ret = __buf_prepare(vb);
1416         if (ret)
1417                 return ret;
1418
1419         /* Fill buffer information for the userspace */
1420         call_void_bufop(q, fill_user_buffer, vb, pb);
1421
1422         dprintk(2, "prepare of buffer %d succeeded\n", vb->index);
1423
1424         return 0;
1425 }
1426 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1427
1428 /*
1429  * vb2_start_streaming() - Attempt to start streaming.
1430  * @q:          videobuf2 queue
1431  *
1432  * Attempt to start streaming. When this function is called there must be
1433  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1434  * number of buffers required for the DMA engine to function). If the
1435  * @start_streaming op fails it is supposed to return all the driver-owned
1436  * buffers back to vb2 in state QUEUED. Check if that happened and if
1437  * not warn and reclaim them forcefully.
1438  */
1439 static int vb2_start_streaming(struct vb2_queue *q)
1440 {
1441         struct vb2_buffer *vb;
1442         int ret;
1443
1444         /*
1445          * If any buffers were queued before streamon,
1446          * we can now pass them to driver for processing.
1447          */
1448         list_for_each_entry(vb, &q->queued_list, queued_entry)
1449                 __enqueue_in_driver(vb);
1450
1451         /* Tell the driver to start streaming */
1452         q->start_streaming_called = 1;
1453         ret = call_qop(q, start_streaming, q,
1454                        atomic_read(&q->owned_by_drv_count));
1455         if (!ret)
1456                 return 0;
1457
1458         q->start_streaming_called = 0;
1459
1460         dprintk(1, "driver refused to start streaming\n");
1461         /*
1462          * If you see this warning, then the driver isn't cleaning up properly
1463          * after a failed start_streaming(). See the start_streaming()
1464          * documentation in videobuf2-core.h for more information how buffers
1465          * should be returned to vb2 in start_streaming().
1466          */
1467         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1468                 unsigned i;
1469
1470                 /*
1471                  * Forcefully reclaim buffers if the driver did not
1472                  * correctly return them to vb2.
1473                  */
1474                 for (i = 0; i < q->num_buffers; ++i) {
1475                         vb = q->bufs[i];
1476                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1477                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1478                 }
1479                 /* Must be zero now */
1480                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1481         }
1482         /*
1483          * If done_list is not empty, then start_streaming() didn't call
1484          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1485          * STATE_DONE.
1486          */
1487         WARN_ON(!list_empty(&q->done_list));
1488         return ret;
1489 }
1490
1491 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb,
1492                   struct media_request *req)
1493 {
1494         struct vb2_buffer *vb;
1495         int ret;
1496
1497         if (q->error) {
1498                 dprintk(1, "fatal error occurred on queue\n");
1499                 return -EIO;
1500         }
1501
1502         vb = q->bufs[index];
1503
1504         if ((req && q->uses_qbuf) ||
1505             (!req && vb->state != VB2_BUF_STATE_IN_REQUEST &&
1506              q->uses_requests)) {
1507                 dprintk(1, "queue in wrong mode (qbuf vs requests)\n");
1508                 return -EBUSY;
1509         }
1510
1511         if (req) {
1512                 int ret;
1513
1514                 q->uses_requests = 1;
1515                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1516                         dprintk(1, "buffer %d not in dequeued state\n",
1517                                 vb->index);
1518                         return -EINVAL;
1519                 }
1520
1521                 media_request_object_init(&vb->req_obj);
1522
1523                 /* Make sure the request is in a safe state for updating. */
1524                 ret = media_request_lock_for_update(req);
1525                 if (ret)
1526                         return ret;
1527                 ret = media_request_object_bind(req, &vb2_core_req_ops,
1528                                                 q, true, &vb->req_obj);
1529                 media_request_unlock_for_update(req);
1530                 if (ret)
1531                         return ret;
1532
1533                 vb->state = VB2_BUF_STATE_IN_REQUEST;
1534                 /* Fill buffer information for the userspace */
1535                 if (pb) {
1536                         call_void_bufop(q, copy_timestamp, vb, pb);
1537                         call_void_bufop(q, fill_user_buffer, vb, pb);
1538                 }
1539
1540                 dprintk(2, "qbuf of buffer %d succeeded\n", vb->index);
1541                 return 0;
1542         }
1543
1544         if (vb->state != VB2_BUF_STATE_IN_REQUEST)
1545                 q->uses_qbuf = 1;
1546
1547         switch (vb->state) {
1548         case VB2_BUF_STATE_DEQUEUED:
1549         case VB2_BUF_STATE_IN_REQUEST:
1550                 if (!vb->prepared) {
1551                         ret = __buf_prepare(vb);
1552                         if (ret)
1553                                 return ret;
1554                 }
1555                 break;
1556         case VB2_BUF_STATE_PREPARING:
1557                 dprintk(1, "buffer still being prepared\n");
1558                 return -EINVAL;
1559         default:
1560                 dprintk(1, "invalid buffer state %d\n", vb->state);
1561                 return -EINVAL;
1562         }
1563
1564         /*
1565          * Add to the queued buffers list, a buffer will stay on it until
1566          * dequeued in dqbuf.
1567          */
1568         list_add_tail(&vb->queued_entry, &q->queued_list);
1569         q->queued_count++;
1570         q->waiting_for_buffers = false;
1571         vb->state = VB2_BUF_STATE_QUEUED;
1572
1573         if (pb)
1574                 call_void_bufop(q, copy_timestamp, vb, pb);
1575
1576         trace_vb2_qbuf(q, vb);
1577
1578         /*
1579          * If already streaming, give the buffer to driver for processing.
1580          * If not, the buffer will be given to driver on next streamon.
1581          */
1582         if (q->start_streaming_called)
1583                 __enqueue_in_driver(vb);
1584
1585         /* Fill buffer information for the userspace */
1586         if (pb)
1587                 call_void_bufop(q, fill_user_buffer, vb, pb);
1588
1589         /*
1590          * If streamon has been called, and we haven't yet called
1591          * start_streaming() since not enough buffers were queued, and
1592          * we now have reached the minimum number of queued buffers,
1593          * then we can finally call start_streaming().
1594          */
1595         if (q->streaming && !q->start_streaming_called &&
1596             q->queued_count >= q->min_buffers_needed) {
1597                 ret = vb2_start_streaming(q);
1598                 if (ret)
1599                         return ret;
1600         }
1601
1602         dprintk(2, "qbuf of buffer %d succeeded\n", vb->index);
1603         return 0;
1604 }
1605 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1606
1607 /*
1608  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1609  * for dequeuing
1610  *
1611  * Will sleep if required for nonblocking == false.
1612  */
1613 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1614 {
1615         /*
1616          * All operations on vb_done_list are performed under done_lock
1617          * spinlock protection. However, buffers may be removed from
1618          * it and returned to userspace only while holding both driver's
1619          * lock and the done_lock spinlock. Thus we can be sure that as
1620          * long as we hold the driver's lock, the list will remain not
1621          * empty if list_empty() check succeeds.
1622          */
1623
1624         for (;;) {
1625                 int ret;
1626
1627                 if (!q->streaming) {
1628                         dprintk(1, "streaming off, will not wait for buffers\n");
1629                         return -EINVAL;
1630                 }
1631
1632                 if (q->error) {
1633                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1634                         return -EIO;
1635                 }
1636
1637                 if (q->last_buffer_dequeued) {
1638                         dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1639                         return -EPIPE;
1640                 }
1641
1642                 if (!list_empty(&q->done_list)) {
1643                         /*
1644                          * Found a buffer that we were waiting for.
1645                          */
1646                         break;
1647                 }
1648
1649                 if (nonblocking) {
1650                         dprintk(3, "nonblocking and no buffers to dequeue, will not wait\n");
1651                         return -EAGAIN;
1652                 }
1653
1654                 /*
1655                  * We are streaming and blocking, wait for another buffer to
1656                  * become ready or for streamoff. Driver's lock is released to
1657                  * allow streamoff or qbuf to be called while waiting.
1658                  */
1659                 call_void_qop(q, wait_prepare, q);
1660
1661                 /*
1662                  * All locks have been released, it is safe to sleep now.
1663                  */
1664                 dprintk(3, "will sleep waiting for buffers\n");
1665                 ret = wait_event_interruptible(q->done_wq,
1666                                 !list_empty(&q->done_list) || !q->streaming ||
1667                                 q->error);
1668
1669                 /*
1670                  * We need to reevaluate both conditions again after reacquiring
1671                  * the locks or return an error if one occurred.
1672                  */
1673                 call_void_qop(q, wait_finish, q);
1674                 if (ret) {
1675                         dprintk(1, "sleep was interrupted\n");
1676                         return ret;
1677                 }
1678         }
1679         return 0;
1680 }
1681
1682 /*
1683  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1684  *
1685  * Will sleep if required for nonblocking == false.
1686  */
1687 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1688                              void *pb, int nonblocking)
1689 {
1690         unsigned long flags;
1691         int ret = 0;
1692
1693         /*
1694          * Wait for at least one buffer to become available on the done_list.
1695          */
1696         ret = __vb2_wait_for_done_vb(q, nonblocking);
1697         if (ret)
1698                 return ret;
1699
1700         /*
1701          * Driver's lock has been held since we last verified that done_list
1702          * is not empty, so no need for another list_empty(done_list) check.
1703          */
1704         spin_lock_irqsave(&q->done_lock, flags);
1705         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1706         /*
1707          * Only remove the buffer from done_list if all planes can be
1708          * handled. Some cases such as V4L2 file I/O and DVB have pb
1709          * == NULL; skip the check then as there's nothing to verify.
1710          */
1711         if (pb)
1712                 ret = call_bufop(q, verify_planes_array, *vb, pb);
1713         if (!ret)
1714                 list_del(&(*vb)->done_entry);
1715         spin_unlock_irqrestore(&q->done_lock, flags);
1716
1717         return ret;
1718 }
1719
1720 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1721 {
1722         if (!q->streaming) {
1723                 dprintk(1, "streaming off, will not wait for buffers\n");
1724                 return -EINVAL;
1725         }
1726
1727         if (q->start_streaming_called)
1728                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1729         return 0;
1730 }
1731 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1732
1733 /*
1734  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1735  */
1736 static void __vb2_dqbuf(struct vb2_buffer *vb)
1737 {
1738         struct vb2_queue *q = vb->vb2_queue;
1739         unsigned int i;
1740
1741         /* nothing to do if the buffer is already dequeued */
1742         if (vb->state == VB2_BUF_STATE_DEQUEUED)
1743                 return;
1744
1745         vb->state = VB2_BUF_STATE_DEQUEUED;
1746
1747         /* unmap DMABUF buffer */
1748         if (q->memory == VB2_MEMORY_DMABUF)
1749                 for (i = 0; i < vb->num_planes; ++i) {
1750                         if (!vb->planes[i].dbuf_mapped)
1751                                 continue;
1752                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1753                         vb->planes[i].dbuf_mapped = 0;
1754                 }
1755         if (vb->req_obj.req) {
1756                 media_request_object_unbind(&vb->req_obj);
1757                 media_request_object_put(&vb->req_obj);
1758         }
1759         call_void_bufop(q, init_buffer, vb);
1760 }
1761
1762 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1763                    bool nonblocking)
1764 {
1765         struct vb2_buffer *vb = NULL;
1766         int ret;
1767
1768         ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1769         if (ret < 0)
1770                 return ret;
1771
1772         switch (vb->state) {
1773         case VB2_BUF_STATE_DONE:
1774                 dprintk(3, "returning done buffer\n");
1775                 break;
1776         case VB2_BUF_STATE_ERROR:
1777                 dprintk(3, "returning done buffer with errors\n");
1778                 break;
1779         default:
1780                 dprintk(1, "invalid buffer state\n");
1781                 return -EINVAL;
1782         }
1783
1784         call_void_vb_qop(vb, buf_finish, vb);
1785         vb->prepared = false;
1786
1787         if (pindex)
1788                 *pindex = vb->index;
1789
1790         /* Fill buffer information for the userspace */
1791         if (pb)
1792                 call_void_bufop(q, fill_user_buffer, vb, pb);
1793
1794         /* Remove from videobuf queue */
1795         list_del(&vb->queued_entry);
1796         q->queued_count--;
1797
1798         trace_vb2_dqbuf(q, vb);
1799
1800         /* go back to dequeued state */
1801         __vb2_dqbuf(vb);
1802
1803         dprintk(2, "dqbuf of buffer %d, with state %d\n",
1804                         vb->index, vb->state);
1805
1806         return 0;
1807
1808 }
1809 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1810
1811 /*
1812  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1813  *
1814  * Removes all queued buffers from driver's queue and all buffers queued by
1815  * userspace from videobuf's queue. Returns to state after reqbufs.
1816  */
1817 static void __vb2_queue_cancel(struct vb2_queue *q)
1818 {
1819         unsigned int i;
1820
1821         /*
1822          * Tell driver to stop all transactions and release all queued
1823          * buffers.
1824          */
1825         if (q->start_streaming_called)
1826                 call_void_qop(q, stop_streaming, q);
1827
1828         /*
1829          * If you see this warning, then the driver isn't cleaning up properly
1830          * in stop_streaming(). See the stop_streaming() documentation in
1831          * videobuf2-core.h for more information how buffers should be returned
1832          * to vb2 in stop_streaming().
1833          */
1834         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1835                 for (i = 0; i < q->num_buffers; ++i)
1836                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE) {
1837                                 pr_warn("driver bug: stop_streaming operation is leaving buf %p in active state\n",
1838                                         q->bufs[i]);
1839                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1840                         }
1841                 /* Must be zero now */
1842                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1843         }
1844
1845         q->streaming = 0;
1846         q->start_streaming_called = 0;
1847         q->queued_count = 0;
1848         q->error = 0;
1849         q->uses_requests = 0;
1850         q->uses_qbuf = 0;
1851
1852         /*
1853          * Remove all buffers from videobuf's list...
1854          */
1855         INIT_LIST_HEAD(&q->queued_list);
1856         /*
1857          * ...and done list; userspace will not receive any buffers it
1858          * has not already dequeued before initiating cancel.
1859          */
1860         INIT_LIST_HEAD(&q->done_list);
1861         atomic_set(&q->owned_by_drv_count, 0);
1862         wake_up_all(&q->done_wq);
1863
1864         /*
1865          * Reinitialize all buffers for next use.
1866          * Make sure to call buf_finish for any queued buffers. Normally
1867          * that's done in dqbuf, but that's not going to happen when we
1868          * cancel the whole queue. Note: this code belongs here, not in
1869          * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1870          * call to __fill_user_buffer() after buf_finish(). That order can't
1871          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1872          */
1873         for (i = 0; i < q->num_buffers; ++i) {
1874                 struct vb2_buffer *vb = q->bufs[i];
1875                 struct media_request *req = vb->req_obj.req;
1876
1877                 /*
1878                  * If a request is associated with this buffer, then
1879                  * call buf_request_cancel() to give the driver to complete()
1880                  * related request objects. Otherwise those objects would
1881                  * never complete.
1882                  */
1883                 if (req) {
1884                         enum media_request_state state;
1885                         unsigned long flags;
1886
1887                         spin_lock_irqsave(&req->lock, flags);
1888                         state = req->state;
1889                         spin_unlock_irqrestore(&req->lock, flags);
1890
1891                         if (state == MEDIA_REQUEST_STATE_QUEUED)
1892                                 call_void_vb_qop(vb, buf_request_complete, vb);
1893                 }
1894
1895                 if (vb->synced) {
1896                         unsigned int plane;
1897
1898                         for (plane = 0; plane < vb->num_planes; ++plane)
1899                                 call_void_memop(vb, finish,
1900                                                 vb->planes[plane].mem_priv);
1901                         vb->synced = false;
1902                 }
1903
1904                 if (vb->prepared) {
1905                         call_void_vb_qop(vb, buf_finish, vb);
1906                         vb->prepared = false;
1907                 }
1908                 __vb2_dqbuf(vb);
1909         }
1910 }
1911
1912 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1913 {
1914         int ret;
1915
1916         if (type != q->type) {
1917                 dprintk(1, "invalid stream type\n");
1918                 return -EINVAL;
1919         }
1920
1921         if (q->streaming) {
1922                 dprintk(3, "already streaming\n");
1923                 return 0;
1924         }
1925
1926         if (!q->num_buffers) {
1927                 dprintk(1, "no buffers have been allocated\n");
1928                 return -EINVAL;
1929         }
1930
1931         if (q->num_buffers < q->min_buffers_needed) {
1932                 dprintk(1, "need at least %u allocated buffers\n",
1933                                 q->min_buffers_needed);
1934                 return -EINVAL;
1935         }
1936
1937         /*
1938          * Tell driver to start streaming provided sufficient buffers
1939          * are available.
1940          */
1941         if (q->queued_count >= q->min_buffers_needed) {
1942                 ret = v4l_vb2q_enable_media_source(q);
1943                 if (ret)
1944                         return ret;
1945                 ret = vb2_start_streaming(q);
1946                 if (ret) {
1947                         __vb2_queue_cancel(q);
1948                         return ret;
1949                 }
1950         }
1951
1952         q->streaming = 1;
1953
1954         dprintk(3, "successful\n");
1955         return 0;
1956 }
1957 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1958
1959 void vb2_queue_error(struct vb2_queue *q)
1960 {
1961         q->error = 1;
1962
1963         wake_up_all(&q->done_wq);
1964 }
1965 EXPORT_SYMBOL_GPL(vb2_queue_error);
1966
1967 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1968 {
1969         if (type != q->type) {
1970                 dprintk(1, "invalid stream type\n");
1971                 return -EINVAL;
1972         }
1973
1974         /*
1975          * Cancel will pause streaming and remove all buffers from the driver
1976          * and videobuf, effectively returning control over them to userspace.
1977          *
1978          * Note that we do this even if q->streaming == 0: if you prepare or
1979          * queue buffers, and then call streamoff without ever having called
1980          * streamon, you would still expect those buffers to be returned to
1981          * their normal dequeued state.
1982          */
1983         __vb2_queue_cancel(q);
1984         q->waiting_for_buffers = !q->is_output;
1985         q->last_buffer_dequeued = false;
1986
1987         dprintk(3, "successful\n");
1988         return 0;
1989 }
1990 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1991
1992 /*
1993  * __find_plane_by_offset() - find plane associated with the given offset off
1994  */
1995 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1996                         unsigned int *_buffer, unsigned int *_plane)
1997 {
1998         struct vb2_buffer *vb;
1999         unsigned int buffer, plane;
2000
2001         /*
2002          * Go over all buffers and their planes, comparing the given offset
2003          * with an offset assigned to each plane. If a match is found,
2004          * return its buffer and plane numbers.
2005          */
2006         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
2007                 vb = q->bufs[buffer];
2008
2009                 for (plane = 0; plane < vb->num_planes; ++plane) {
2010                         if (vb->planes[plane].m.offset == off) {
2011                                 *_buffer = buffer;
2012                                 *_plane = plane;
2013                                 return 0;
2014                         }
2015                 }
2016         }
2017
2018         return -EINVAL;
2019 }
2020
2021 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
2022                 unsigned int index, unsigned int plane, unsigned int flags)
2023 {
2024         struct vb2_buffer *vb = NULL;
2025         struct vb2_plane *vb_plane;
2026         int ret;
2027         struct dma_buf *dbuf;
2028
2029         if (q->memory != VB2_MEMORY_MMAP) {
2030                 dprintk(1, "queue is not currently set up for mmap\n");
2031                 return -EINVAL;
2032         }
2033
2034         if (!q->mem_ops->get_dmabuf) {
2035                 dprintk(1, "queue does not support DMA buffer exporting\n");
2036                 return -EINVAL;
2037         }
2038
2039         if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
2040                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
2041                 return -EINVAL;
2042         }
2043
2044         if (type != q->type) {
2045                 dprintk(1, "invalid buffer type\n");
2046                 return -EINVAL;
2047         }
2048
2049         if (index >= q->num_buffers) {
2050                 dprintk(1, "buffer index out of range\n");
2051                 return -EINVAL;
2052         }
2053
2054         vb = q->bufs[index];
2055
2056         if (plane >= vb->num_planes) {
2057                 dprintk(1, "buffer plane out of range\n");
2058                 return -EINVAL;
2059         }
2060
2061         if (vb2_fileio_is_active(q)) {
2062                 dprintk(1, "expbuf: file io in progress\n");
2063                 return -EBUSY;
2064         }
2065
2066         vb_plane = &vb->planes[plane];
2067
2068         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
2069                                 flags & O_ACCMODE);
2070         if (IS_ERR_OR_NULL(dbuf)) {
2071                 dprintk(1, "failed to export buffer %d, plane %d\n",
2072                         index, plane);
2073                 return -EINVAL;
2074         }
2075
2076         ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
2077         if (ret < 0) {
2078                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
2079                         index, plane, ret);
2080                 dma_buf_put(dbuf);
2081                 return ret;
2082         }
2083
2084         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
2085                 index, plane, ret);
2086         *fd = ret;
2087
2088         return 0;
2089 }
2090 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
2091
2092 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
2093 {
2094         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
2095         struct vb2_buffer *vb;
2096         unsigned int buffer = 0, plane = 0;
2097         int ret;
2098         unsigned long length;
2099
2100         if (q->memory != VB2_MEMORY_MMAP) {
2101                 dprintk(1, "queue is not currently set up for mmap\n");
2102                 return -EINVAL;
2103         }
2104
2105         /*
2106          * Check memory area access mode.
2107          */
2108         if (!(vma->vm_flags & VM_SHARED)) {
2109                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
2110                 return -EINVAL;
2111         }
2112         if (q->is_output) {
2113                 if (!(vma->vm_flags & VM_WRITE)) {
2114                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
2115                         return -EINVAL;
2116                 }
2117         } else {
2118                 if (!(vma->vm_flags & VM_READ)) {
2119                         dprintk(1, "invalid vma flags, VM_READ needed\n");
2120                         return -EINVAL;
2121                 }
2122         }
2123
2124         mutex_lock(&q->mmap_lock);
2125
2126         if (vb2_fileio_is_active(q)) {
2127                 dprintk(1, "mmap: file io in progress\n");
2128                 ret = -EBUSY;
2129                 goto unlock;
2130         }
2131
2132         /*
2133          * Find the plane corresponding to the offset passed by userspace.
2134          */
2135         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2136         if (ret)
2137                 goto unlock;
2138
2139         vb = q->bufs[buffer];
2140
2141         /*
2142          * MMAP requires page_aligned buffers.
2143          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
2144          * so, we need to do the same here.
2145          */
2146         length = PAGE_ALIGN(vb->planes[plane].length);
2147         if (length < (vma->vm_end - vma->vm_start)) {
2148                 dprintk(1,
2149                         "MMAP invalid, as it would overflow buffer length\n");
2150                 return -EINVAL;
2151         }
2152
2153         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
2154
2155 unlock:
2156         mutex_unlock(&q->mmap_lock);
2157         if (ret)
2158                 return ret;
2159
2160         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
2161         return 0;
2162 }
2163 EXPORT_SYMBOL_GPL(vb2_mmap);
2164
2165 #ifndef CONFIG_MMU
2166 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2167                                     unsigned long addr,
2168                                     unsigned long len,
2169                                     unsigned long pgoff,
2170                                     unsigned long flags)
2171 {
2172         unsigned long off = pgoff << PAGE_SHIFT;
2173         struct vb2_buffer *vb;
2174         unsigned int buffer, plane;
2175         void *vaddr;
2176         int ret;
2177
2178         if (q->memory != VB2_MEMORY_MMAP) {
2179                 dprintk(1, "queue is not currently set up for mmap\n");
2180                 return -EINVAL;
2181         }
2182
2183         /*
2184          * Find the plane corresponding to the offset passed by userspace.
2185          */
2186         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2187         if (ret)
2188                 return ret;
2189
2190         vb = q->bufs[buffer];
2191
2192         vaddr = vb2_plane_vaddr(vb, plane);
2193         return vaddr ? (unsigned long)vaddr : -EINVAL;
2194 }
2195 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2196 #endif
2197
2198 int vb2_core_queue_init(struct vb2_queue *q)
2199 {
2200         /*
2201          * Sanity check
2202          */
2203         if (WARN_ON(!q)                   ||
2204             WARN_ON(!q->ops)              ||
2205             WARN_ON(!q->mem_ops)          ||
2206             WARN_ON(!q->type)             ||
2207             WARN_ON(!q->io_modes)         ||
2208             WARN_ON(!q->ops->queue_setup) ||
2209             WARN_ON(!q->ops->buf_queue))
2210                 return -EINVAL;
2211
2212         INIT_LIST_HEAD(&q->queued_list);
2213         INIT_LIST_HEAD(&q->done_list);
2214         spin_lock_init(&q->done_lock);
2215         mutex_init(&q->mmap_lock);
2216         init_waitqueue_head(&q->done_wq);
2217
2218         q->memory = VB2_MEMORY_UNKNOWN;
2219
2220         if (q->buf_struct_size == 0)
2221                 q->buf_struct_size = sizeof(struct vb2_buffer);
2222
2223         if (q->bidirectional)
2224                 q->dma_dir = DMA_BIDIRECTIONAL;
2225         else
2226                 q->dma_dir = q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
2227
2228         return 0;
2229 }
2230 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2231
2232 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2233 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2234 void vb2_core_queue_release(struct vb2_queue *q)
2235 {
2236         __vb2_cleanup_fileio(q);
2237         __vb2_queue_cancel(q);
2238         mutex_lock(&q->mmap_lock);
2239         __vb2_queue_free(q, q->num_buffers);
2240         mutex_unlock(&q->mmap_lock);
2241 }
2242 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2243
2244 __poll_t vb2_core_poll(struct vb2_queue *q, struct file *file,
2245                 poll_table *wait)
2246 {
2247         __poll_t req_events = poll_requested_events(wait);
2248         struct vb2_buffer *vb = NULL;
2249         unsigned long flags;
2250
2251         if (!q->is_output && !(req_events & (EPOLLIN | EPOLLRDNORM)))
2252                 return 0;
2253         if (q->is_output && !(req_events & (EPOLLOUT | EPOLLWRNORM)))
2254                 return 0;
2255
2256         /*
2257          * Start file I/O emulator only if streaming API has not been used yet.
2258          */
2259         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2260                 if (!q->is_output && (q->io_modes & VB2_READ) &&
2261                                 (req_events & (EPOLLIN | EPOLLRDNORM))) {
2262                         if (__vb2_init_fileio(q, 1))
2263                                 return EPOLLERR;
2264                 }
2265                 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2266                                 (req_events & (EPOLLOUT | EPOLLWRNORM))) {
2267                         if (__vb2_init_fileio(q, 0))
2268                                 return EPOLLERR;
2269                         /*
2270                          * Write to OUTPUT queue can be done immediately.
2271                          */
2272                         return EPOLLOUT | EPOLLWRNORM;
2273                 }
2274         }
2275
2276         /*
2277          * There is nothing to wait for if the queue isn't streaming, or if the
2278          * error flag is set.
2279          */
2280         if (!vb2_is_streaming(q) || q->error)
2281                 return EPOLLERR;
2282
2283         /*
2284          * If this quirk is set and QBUF hasn't been called yet then
2285          * return EPOLLERR as well. This only affects capture queues, output
2286          * queues will always initialize waiting_for_buffers to false.
2287          * This quirk is set by V4L2 for backwards compatibility reasons.
2288          */
2289         if (q->quirk_poll_must_check_waiting_for_buffers &&
2290             q->waiting_for_buffers && (req_events & (EPOLLIN | EPOLLRDNORM)))
2291                 return EPOLLERR;
2292
2293         /*
2294          * For output streams you can call write() as long as there are fewer
2295          * buffers queued than there are buffers available.
2296          */
2297         if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2298                 return EPOLLOUT | EPOLLWRNORM;
2299
2300         if (list_empty(&q->done_list)) {
2301                 /*
2302                  * If the last buffer was dequeued from a capture queue,
2303                  * return immediately. DQBUF will return -EPIPE.
2304                  */
2305                 if (q->last_buffer_dequeued)
2306                         return EPOLLIN | EPOLLRDNORM;
2307
2308                 poll_wait(file, &q->done_wq, wait);
2309         }
2310
2311         /*
2312          * Take first buffer available for dequeuing.
2313          */
2314         spin_lock_irqsave(&q->done_lock, flags);
2315         if (!list_empty(&q->done_list))
2316                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2317                                         done_entry);
2318         spin_unlock_irqrestore(&q->done_lock, flags);
2319
2320         if (vb && (vb->state == VB2_BUF_STATE_DONE
2321                         || vb->state == VB2_BUF_STATE_ERROR)) {
2322                 return (q->is_output) ?
2323                                 EPOLLOUT | EPOLLWRNORM :
2324                                 EPOLLIN | EPOLLRDNORM;
2325         }
2326         return 0;
2327 }
2328 EXPORT_SYMBOL_GPL(vb2_core_poll);
2329
2330 /*
2331  * struct vb2_fileio_buf - buffer context used by file io emulator
2332  *
2333  * vb2 provides a compatibility layer and emulator of file io (read and
2334  * write) calls on top of streaming API. This structure is used for
2335  * tracking context related to the buffers.
2336  */
2337 struct vb2_fileio_buf {
2338         void *vaddr;
2339         unsigned int size;
2340         unsigned int pos;
2341         unsigned int queued:1;
2342 };
2343
2344 /*
2345  * struct vb2_fileio_data - queue context used by file io emulator
2346  *
2347  * @cur_index:  the index of the buffer currently being read from or
2348  *              written to. If equal to q->num_buffers then a new buffer
2349  *              must be dequeued.
2350  * @initial_index: in the read() case all buffers are queued up immediately
2351  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2352  *              buffers. However, in the write() case no buffers are initially
2353  *              queued, instead whenever a buffer is full it is queued up by
2354  *              __vb2_perform_fileio(). Only once all available buffers have
2355  *              been queued up will __vb2_perform_fileio() start to dequeue
2356  *              buffers. This means that initially __vb2_perform_fileio()
2357  *              needs to know what buffer index to use when it is queuing up
2358  *              the buffers for the first time. That initial index is stored
2359  *              in this field. Once it is equal to q->num_buffers all
2360  *              available buffers have been queued and __vb2_perform_fileio()
2361  *              should start the normal dequeue/queue cycle.
2362  *
2363  * vb2 provides a compatibility layer and emulator of file io (read and
2364  * write) calls on top of streaming API. For proper operation it required
2365  * this structure to save the driver state between each call of the read
2366  * or write function.
2367  */
2368 struct vb2_fileio_data {
2369         unsigned int count;
2370         unsigned int type;
2371         unsigned int memory;
2372         struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2373         unsigned int cur_index;
2374         unsigned int initial_index;
2375         unsigned int q_count;
2376         unsigned int dq_count;
2377         unsigned read_once:1;
2378         unsigned write_immediately:1;
2379 };
2380
2381 /*
2382  * __vb2_init_fileio() - initialize file io emulator
2383  * @q:          videobuf2 queue
2384  * @read:       mode selector (1 means read, 0 means write)
2385  */
2386 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2387 {
2388         struct vb2_fileio_data *fileio;
2389         int i, ret;
2390         unsigned int count = 0;
2391
2392         /*
2393          * Sanity check
2394          */
2395         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2396                     (!read && !(q->io_modes & VB2_WRITE))))
2397                 return -EINVAL;
2398
2399         /*
2400          * Check if device supports mapping buffers to kernel virtual space.
2401          */
2402         if (!q->mem_ops->vaddr)
2403                 return -EBUSY;
2404
2405         /*
2406          * Check if streaming api has not been already activated.
2407          */
2408         if (q->streaming || q->num_buffers > 0)
2409                 return -EBUSY;
2410
2411         /*
2412          * Start with count 1, driver can increase it in queue_setup()
2413          */
2414         count = 1;
2415
2416         dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2417                 (read) ? "read" : "write", count, q->fileio_read_once,
2418                 q->fileio_write_immediately);
2419
2420         fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2421         if (fileio == NULL)
2422                 return -ENOMEM;
2423
2424         fileio->read_once = q->fileio_read_once;
2425         fileio->write_immediately = q->fileio_write_immediately;
2426
2427         /*
2428          * Request buffers and use MMAP type to force driver
2429          * to allocate buffers by itself.
2430          */
2431         fileio->count = count;
2432         fileio->memory = VB2_MEMORY_MMAP;
2433         fileio->type = q->type;
2434         q->fileio = fileio;
2435         ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2436         if (ret)
2437                 goto err_kfree;
2438
2439         /*
2440          * Check if plane_count is correct
2441          * (multiplane buffers are not supported).
2442          */
2443         if (q->bufs[0]->num_planes != 1) {
2444                 ret = -EBUSY;
2445                 goto err_reqbufs;
2446         }
2447
2448         /*
2449          * Get kernel address of each buffer.
2450          */
2451         for (i = 0; i < q->num_buffers; i++) {
2452                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2453                 if (fileio->bufs[i].vaddr == NULL) {
2454                         ret = -EINVAL;
2455                         goto err_reqbufs;
2456                 }
2457                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2458         }
2459
2460         /*
2461          * Read mode requires pre queuing of all buffers.
2462          */
2463         if (read) {
2464                 /*
2465                  * Queue all buffers.
2466                  */
2467                 for (i = 0; i < q->num_buffers; i++) {
2468                         ret = vb2_core_qbuf(q, i, NULL, NULL);
2469                         if (ret)
2470                                 goto err_reqbufs;
2471                         fileio->bufs[i].queued = 1;
2472                 }
2473                 /*
2474                  * All buffers have been queued, so mark that by setting
2475                  * initial_index to q->num_buffers
2476                  */
2477                 fileio->initial_index = q->num_buffers;
2478                 fileio->cur_index = q->num_buffers;
2479         }
2480
2481         /*
2482          * Start streaming.
2483          */
2484         ret = vb2_core_streamon(q, q->type);
2485         if (ret)
2486                 goto err_reqbufs;
2487
2488         return ret;
2489
2490 err_reqbufs:
2491         fileio->count = 0;
2492         vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2493
2494 err_kfree:
2495         q->fileio = NULL;
2496         kfree(fileio);
2497         return ret;
2498 }
2499
2500 /*
2501  * __vb2_cleanup_fileio() - free resourced used by file io emulator
2502  * @q:          videobuf2 queue
2503  */
2504 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2505 {
2506         struct vb2_fileio_data *fileio = q->fileio;
2507
2508         if (fileio) {
2509                 vb2_core_streamoff(q, q->type);
2510                 q->fileio = NULL;
2511                 fileio->count = 0;
2512                 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2513                 kfree(fileio);
2514                 dprintk(3, "file io emulator closed\n");
2515         }
2516         return 0;
2517 }
2518
2519 /*
2520  * __vb2_perform_fileio() - perform a single file io (read or write) operation
2521  * @q:          videobuf2 queue
2522  * @data:       pointed to target userspace buffer
2523  * @count:      number of bytes to read or write
2524  * @ppos:       file handle position tracking pointer
2525  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
2526  * @read:       access mode selector (1 means read, 0 means write)
2527  */
2528 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2529                 loff_t *ppos, int nonblock, int read)
2530 {
2531         struct vb2_fileio_data *fileio;
2532         struct vb2_fileio_buf *buf;
2533         bool is_multiplanar = q->is_multiplanar;
2534         /*
2535          * When using write() to write data to an output video node the vb2 core
2536          * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2537          * else is able to provide this information with the write() operation.
2538          */
2539         bool copy_timestamp = !read && q->copy_timestamp;
2540         unsigned index;
2541         int ret;
2542
2543         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2544                 read ? "read" : "write", (long)*ppos, count,
2545                 nonblock ? "non" : "");
2546
2547         if (!data)
2548                 return -EINVAL;
2549
2550         /*
2551          * Initialize emulator on first call.
2552          */
2553         if (!vb2_fileio_is_active(q)) {
2554                 ret = __vb2_init_fileio(q, read);
2555                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2556                 if (ret)
2557                         return ret;
2558         }
2559         fileio = q->fileio;
2560
2561         /*
2562          * Check if we need to dequeue the buffer.
2563          */
2564         index = fileio->cur_index;
2565         if (index >= q->num_buffers) {
2566                 struct vb2_buffer *b;
2567
2568                 /*
2569                  * Call vb2_dqbuf to get buffer back.
2570                  */
2571                 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2572                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2573                 if (ret)
2574                         return ret;
2575                 fileio->dq_count += 1;
2576
2577                 fileio->cur_index = index;
2578                 buf = &fileio->bufs[index];
2579                 b = q->bufs[index];
2580
2581                 /*
2582                  * Get number of bytes filled by the driver
2583                  */
2584                 buf->pos = 0;
2585                 buf->queued = 0;
2586                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2587                                  : vb2_plane_size(q->bufs[index], 0);
2588                 /* Compensate for data_offset on read in the multiplanar case. */
2589                 if (is_multiplanar && read &&
2590                                 b->planes[0].data_offset < buf->size) {
2591                         buf->pos = b->planes[0].data_offset;
2592                         buf->size -= buf->pos;
2593                 }
2594         } else {
2595                 buf = &fileio->bufs[index];
2596         }
2597
2598         /*
2599          * Limit count on last few bytes of the buffer.
2600          */
2601         if (buf->pos + count > buf->size) {
2602                 count = buf->size - buf->pos;
2603                 dprintk(5, "reducing read count: %zd\n", count);
2604         }
2605
2606         /*
2607          * Transfer data to userspace.
2608          */
2609         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2610                 count, index, buf->pos);
2611         if (read)
2612                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2613         else
2614                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2615         if (ret) {
2616                 dprintk(3, "error copying data\n");
2617                 return -EFAULT;
2618         }
2619
2620         /*
2621          * Update counters.
2622          */
2623         buf->pos += count;
2624         *ppos += count;
2625
2626         /*
2627          * Queue next buffer if required.
2628          */
2629         if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2630                 struct vb2_buffer *b = q->bufs[index];
2631
2632                 /*
2633                  * Check if this is the last buffer to read.
2634                  */
2635                 if (read && fileio->read_once && fileio->dq_count == 1) {
2636                         dprintk(3, "read limit reached\n");
2637                         return __vb2_cleanup_fileio(q);
2638                 }
2639
2640                 /*
2641                  * Call vb2_qbuf and give buffer to the driver.
2642                  */
2643                 b->planes[0].bytesused = buf->pos;
2644
2645                 if (copy_timestamp)
2646                         b->timestamp = ktime_get_ns();
2647                 ret = vb2_core_qbuf(q, index, NULL, NULL);
2648                 dprintk(5, "vb2_dbuf result: %d\n", ret);
2649                 if (ret)
2650                         return ret;
2651
2652                 /*
2653                  * Buffer has been queued, update the status
2654                  */
2655                 buf->pos = 0;
2656                 buf->queued = 1;
2657                 buf->size = vb2_plane_size(q->bufs[index], 0);
2658                 fileio->q_count += 1;
2659                 /*
2660                  * If we are queuing up buffers for the first time, then
2661                  * increase initial_index by one.
2662                  */
2663                 if (fileio->initial_index < q->num_buffers)
2664                         fileio->initial_index++;
2665                 /*
2666                  * The next buffer to use is either a buffer that's going to be
2667                  * queued for the first time (initial_index < q->num_buffers)
2668                  * or it is equal to q->num_buffers, meaning that the next
2669                  * time we need to dequeue a buffer since we've now queued up
2670                  * all the 'first time' buffers.
2671                  */
2672                 fileio->cur_index = fileio->initial_index;
2673         }
2674
2675         /*
2676          * Return proper number of bytes processed.
2677          */
2678         if (ret == 0)
2679                 ret = count;
2680         return ret;
2681 }
2682
2683 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2684                 loff_t *ppos, int nonblocking)
2685 {
2686         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2687 }
2688 EXPORT_SYMBOL_GPL(vb2_read);
2689
2690 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2691                 loff_t *ppos, int nonblocking)
2692 {
2693         return __vb2_perform_fileio(q, (char __user *) data, count,
2694                                                         ppos, nonblocking, 0);
2695 }
2696 EXPORT_SYMBOL_GPL(vb2_write);
2697
2698 struct vb2_threadio_data {
2699         struct task_struct *thread;
2700         vb2_thread_fnc fnc;
2701         void *priv;
2702         bool stop;
2703 };
2704
2705 static int vb2_thread(void *data)
2706 {
2707         struct vb2_queue *q = data;
2708         struct vb2_threadio_data *threadio = q->threadio;
2709         bool copy_timestamp = false;
2710         unsigned prequeue = 0;
2711         unsigned index = 0;
2712         int ret = 0;
2713
2714         if (q->is_output) {
2715                 prequeue = q->num_buffers;
2716                 copy_timestamp = q->copy_timestamp;
2717         }
2718
2719         set_freezable();
2720
2721         for (;;) {
2722                 struct vb2_buffer *vb;
2723
2724                 /*
2725                  * Call vb2_dqbuf to get buffer back.
2726                  */
2727                 if (prequeue) {
2728                         vb = q->bufs[index++];
2729                         prequeue--;
2730                 } else {
2731                         call_void_qop(q, wait_finish, q);
2732                         if (!threadio->stop)
2733                                 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2734                         call_void_qop(q, wait_prepare, q);
2735                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2736                         if (!ret)
2737                                 vb = q->bufs[index];
2738                 }
2739                 if (ret || threadio->stop)
2740                         break;
2741                 try_to_freeze();
2742
2743                 if (vb->state != VB2_BUF_STATE_ERROR)
2744                         if (threadio->fnc(vb, threadio->priv))
2745                                 break;
2746                 call_void_qop(q, wait_finish, q);
2747                 if (copy_timestamp)
2748                         vb->timestamp = ktime_get_ns();
2749                 if (!threadio->stop)
2750                         ret = vb2_core_qbuf(q, vb->index, NULL, NULL);
2751                 call_void_qop(q, wait_prepare, q);
2752                 if (ret || threadio->stop)
2753                         break;
2754         }
2755
2756         /* Hmm, linux becomes *very* unhappy without this ... */
2757         while (!kthread_should_stop()) {
2758                 set_current_state(TASK_INTERRUPTIBLE);
2759                 schedule();
2760         }
2761         return 0;
2762 }
2763
2764 /*
2765  * This function should not be used for anything else but the videobuf2-dvb
2766  * support. If you think you have another good use-case for this, then please
2767  * contact the linux-media mailinglist first.
2768  */
2769 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2770                      const char *thread_name)
2771 {
2772         struct vb2_threadio_data *threadio;
2773         int ret = 0;
2774
2775         if (q->threadio)
2776                 return -EBUSY;
2777         if (vb2_is_busy(q))
2778                 return -EBUSY;
2779         if (WARN_ON(q->fileio))
2780                 return -EBUSY;
2781
2782         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2783         if (threadio == NULL)
2784                 return -ENOMEM;
2785         threadio->fnc = fnc;
2786         threadio->priv = priv;
2787
2788         ret = __vb2_init_fileio(q, !q->is_output);
2789         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2790         if (ret)
2791                 goto nomem;
2792         q->threadio = threadio;
2793         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2794         if (IS_ERR(threadio->thread)) {
2795                 ret = PTR_ERR(threadio->thread);
2796                 threadio->thread = NULL;
2797                 goto nothread;
2798         }
2799         return 0;
2800
2801 nothread:
2802         __vb2_cleanup_fileio(q);
2803 nomem:
2804         kfree(threadio);
2805         return ret;
2806 }
2807 EXPORT_SYMBOL_GPL(vb2_thread_start);
2808
2809 int vb2_thread_stop(struct vb2_queue *q)
2810 {
2811         struct vb2_threadio_data *threadio = q->threadio;
2812         int err;
2813
2814         if (threadio == NULL)
2815                 return 0;
2816         threadio->stop = true;
2817         /* Wake up all pending sleeps in the thread */
2818         vb2_queue_error(q);
2819         err = kthread_stop(threadio->thread);
2820         __vb2_cleanup_fileio(q);
2821         threadio->thread = NULL;
2822         kfree(threadio);
2823         q->threadio = NULL;
2824         return err;
2825 }
2826 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2827
2828 MODULE_DESCRIPTION("Media buffer core framework");
2829 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2830 MODULE_LICENSE("GPL");