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