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