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