These changes are the raw update to linux-4.4.6-rt14. Kernel sources
[kvmfornfv.git] / kernel / 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
29 #include <trace/events/vb2.h>
30
31 #include "videobuf2-internal.h"
32
33 int vb2_debug;
34 EXPORT_SYMBOL_GPL(vb2_debug);
35 module_param_named(debug, vb2_debug, int, 0644);
36
37 static void __vb2_queue_cancel(struct vb2_queue *q);
38 static void __enqueue_in_driver(struct vb2_buffer *vb);
39
40 /**
41  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
42  */
43 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
44 {
45         struct vb2_queue *q = vb->vb2_queue;
46         enum dma_data_direction dma_dir =
47                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
48         void *mem_priv;
49         int plane;
50
51         /*
52          * Allocate memory for all planes in this buffer
53          * NOTE: mmapped areas should be page aligned
54          */
55         for (plane = 0; plane < vb->num_planes; ++plane) {
56                 unsigned long size = PAGE_ALIGN(q->plane_sizes[plane]);
57
58                 mem_priv = call_ptr_memop(vb, alloc, q->alloc_ctx[plane],
59                                       size, dma_dir, q->gfp_flags);
60                 if (IS_ERR_OR_NULL(mem_priv))
61                         goto free;
62
63                 /* Associate allocator private data with this plane */
64                 vb->planes[plane].mem_priv = mem_priv;
65                 vb->planes[plane].length = q->plane_sizes[plane];
66         }
67
68         return 0;
69 free:
70         /* Free already allocated memory if one of the allocations failed */
71         for (; plane > 0; --plane) {
72                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
73                 vb->planes[plane - 1].mem_priv = NULL;
74         }
75
76         return -ENOMEM;
77 }
78
79 /**
80  * __vb2_buf_mem_free() - free memory of the given buffer
81  */
82 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
83 {
84         unsigned int plane;
85
86         for (plane = 0; plane < vb->num_planes; ++plane) {
87                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
88                 vb->planes[plane].mem_priv = NULL;
89                 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
90         }
91 }
92
93 /**
94  * __vb2_buf_userptr_put() - release userspace memory associated with
95  * a USERPTR buffer
96  */
97 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
98 {
99         unsigned int plane;
100
101         for (plane = 0; plane < vb->num_planes; ++plane) {
102                 if (vb->planes[plane].mem_priv)
103                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
104                 vb->planes[plane].mem_priv = NULL;
105         }
106 }
107
108 /**
109  * __vb2_plane_dmabuf_put() - release memory associated with
110  * a DMABUF shared plane
111  */
112 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
113 {
114         if (!p->mem_priv)
115                 return;
116
117         if (p->dbuf_mapped)
118                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
119
120         call_void_memop(vb, detach_dmabuf, p->mem_priv);
121         dma_buf_put(p->dbuf);
122         p->mem_priv = NULL;
123         p->dbuf = NULL;
124         p->dbuf_mapped = 0;
125 }
126
127 /**
128  * __vb2_buf_dmabuf_put() - release memory associated with
129  * a DMABUF shared buffer
130  */
131 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
132 {
133         unsigned int plane;
134
135         for (plane = 0; plane < vb->num_planes; ++plane)
136                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
137 }
138
139 /**
140  * __setup_lengths() - setup initial lengths for every plane in
141  * every buffer on the queue
142  */
143 static void __setup_lengths(struct vb2_queue *q, unsigned int n)
144 {
145         unsigned int buffer, plane;
146         struct vb2_buffer *vb;
147
148         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
149                 vb = q->bufs[buffer];
150                 if (!vb)
151                         continue;
152
153                 for (plane = 0; plane < vb->num_planes; ++plane)
154                         vb->planes[plane].length = q->plane_sizes[plane];
155         }
156 }
157
158 /**
159  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
160  * every buffer on the queue
161  */
162 static void __setup_offsets(struct vb2_queue *q, unsigned int n)
163 {
164         unsigned int buffer, plane;
165         struct vb2_buffer *vb;
166         unsigned long off;
167
168         if (q->num_buffers) {
169                 struct vb2_plane *p;
170                 vb = q->bufs[q->num_buffers - 1];
171                 p = &vb->planes[vb->num_planes - 1];
172                 off = PAGE_ALIGN(p->m.offset + p->length);
173         } else {
174                 off = 0;
175         }
176
177         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
178                 vb = q->bufs[buffer];
179                 if (!vb)
180                         continue;
181
182                 for (plane = 0; plane < vb->num_planes; ++plane) {
183                         vb->planes[plane].m.offset = off;
184
185                         dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
186                                         buffer, plane, off);
187
188                         off += vb->planes[plane].length;
189                         off = PAGE_ALIGN(off);
190                 }
191         }
192 }
193
194 /**
195  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
196  * video buffer memory for all buffers/planes on the queue and initializes the
197  * queue
198  *
199  * Returns the number of buffers successfully allocated.
200  */
201 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
202                              unsigned int num_buffers, unsigned int num_planes)
203 {
204         unsigned int buffer;
205         struct vb2_buffer *vb;
206         int ret;
207
208         for (buffer = 0; buffer < num_buffers; ++buffer) {
209                 /* Allocate videobuf buffer structures */
210                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
211                 if (!vb) {
212                         dprintk(1, "memory alloc for buffer struct failed\n");
213                         break;
214                 }
215
216                 vb->state = VB2_BUF_STATE_DEQUEUED;
217                 vb->vb2_queue = q;
218                 vb->num_planes = num_planes;
219                 vb->index = q->num_buffers + buffer;
220                 vb->type = q->type;
221                 vb->memory = memory;
222
223                 /* Allocate video buffer memory for the MMAP type */
224                 if (memory == VB2_MEMORY_MMAP) {
225                         ret = __vb2_buf_mem_alloc(vb);
226                         if (ret) {
227                                 dprintk(1, "failed allocating memory for "
228                                                 "buffer %d\n", buffer);
229                                 kfree(vb);
230                                 break;
231                         }
232                         /*
233                          * Call the driver-provided buffer initialization
234                          * callback, if given. An error in initialization
235                          * results in queue setup failure.
236                          */
237                         ret = call_vb_qop(vb, buf_init, vb);
238                         if (ret) {
239                                 dprintk(1, "buffer %d %p initialization"
240                                         " failed\n", buffer, vb);
241                                 __vb2_buf_mem_free(vb);
242                                 kfree(vb);
243                                 break;
244                         }
245                 }
246
247                 q->bufs[q->num_buffers + buffer] = vb;
248         }
249
250         __setup_lengths(q, buffer);
251         if (memory == VB2_MEMORY_MMAP)
252                 __setup_offsets(q, buffer);
253
254         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
255                         buffer, num_planes);
256
257         return buffer;
258 }
259
260 /**
261  * __vb2_free_mem() - release all video buffer memory for a given queue
262  */
263 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
264 {
265         unsigned int buffer;
266         struct vb2_buffer *vb;
267
268         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
269              ++buffer) {
270                 vb = q->bufs[buffer];
271                 if (!vb)
272                         continue;
273
274                 /* Free MMAP buffers or release USERPTR buffers */
275                 if (q->memory == VB2_MEMORY_MMAP)
276                         __vb2_buf_mem_free(vb);
277                 else if (q->memory == VB2_MEMORY_DMABUF)
278                         __vb2_buf_dmabuf_put(vb);
279                 else
280                         __vb2_buf_userptr_put(vb);
281         }
282 }
283
284 /**
285  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
286  * related information, if no buffers are left return the queue to an
287  * uninitialized state. Might be called even if the queue has already been freed.
288  */
289 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
290 {
291         unsigned int buffer;
292
293         /*
294          * Sanity check: when preparing a buffer the queue lock is released for
295          * a short while (see __buf_prepare for the details), which would allow
296          * a race with a reqbufs which can call this function. Removing the
297          * buffers from underneath __buf_prepare is obviously a bad idea, so we
298          * check if any of the buffers is in the state PREPARING, and if so we
299          * just return -EAGAIN.
300          */
301         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
302              ++buffer) {
303                 if (q->bufs[buffer] == NULL)
304                         continue;
305                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
306                         dprintk(1, "preparing buffers, cannot free\n");
307                         return -EAGAIN;
308                 }
309         }
310
311         /* Call driver-provided cleanup function for each buffer, if provided */
312         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
313              ++buffer) {
314                 struct vb2_buffer *vb = q->bufs[buffer];
315
316                 if (vb && vb->planes[0].mem_priv)
317                         call_void_vb_qop(vb, buf_cleanup, vb);
318         }
319
320         /* Release video buffer memory */
321         __vb2_free_mem(q, buffers);
322
323 #ifdef CONFIG_VIDEO_ADV_DEBUG
324         /*
325          * Check that all the calls were balances during the life-time of this
326          * queue. If not (or if the debug level is 1 or up), then dump the
327          * counters to the kernel log.
328          */
329         if (q->num_buffers) {
330                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
331                                   q->cnt_wait_prepare != q->cnt_wait_finish;
332
333                 if (unbalanced || vb2_debug) {
334                         pr_info("vb2: counters for queue %p:%s\n", q,
335                                 unbalanced ? " UNBALANCED!" : "");
336                         pr_info("vb2:     setup: %u start_streaming: %u stop_streaming: %u\n",
337                                 q->cnt_queue_setup, q->cnt_start_streaming,
338                                 q->cnt_stop_streaming);
339                         pr_info("vb2:     wait_prepare: %u wait_finish: %u\n",
340                                 q->cnt_wait_prepare, q->cnt_wait_finish);
341                 }
342                 q->cnt_queue_setup = 0;
343                 q->cnt_wait_prepare = 0;
344                 q->cnt_wait_finish = 0;
345                 q->cnt_start_streaming = 0;
346                 q->cnt_stop_streaming = 0;
347         }
348         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
349                 struct vb2_buffer *vb = q->bufs[buffer];
350                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
351                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
352                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
353                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
354                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
355                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
356                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
357                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
358
359                 if (unbalanced || vb2_debug) {
360                         pr_info("vb2:   counters for queue %p, buffer %d:%s\n",
361                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
362                         pr_info("vb2:     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
363                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
364                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
365                         pr_info("vb2:     buf_queue: %u buf_done: %u\n",
366                                 vb->cnt_buf_queue, vb->cnt_buf_done);
367                         pr_info("vb2:     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
368                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
369                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
370                                 vb->cnt_mem_mmap);
371                         pr_info("vb2:     get_userptr: %u put_userptr: %u\n",
372                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
373                         pr_info("vb2:     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
374                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
375                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
376                         pr_info("vb2:     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
377                                 vb->cnt_mem_get_dmabuf,
378                                 vb->cnt_mem_num_users,
379                                 vb->cnt_mem_vaddr,
380                                 vb->cnt_mem_cookie);
381                 }
382         }
383 #endif
384
385         /* Free videobuf buffers */
386         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
387              ++buffer) {
388                 kfree(q->bufs[buffer]);
389                 q->bufs[buffer] = NULL;
390         }
391
392         q->num_buffers -= buffers;
393         if (!q->num_buffers) {
394                 q->memory = 0;
395                 INIT_LIST_HEAD(&q->queued_list);
396         }
397         return 0;
398 }
399
400 /**
401  * vb2_buffer_in_use() - return true if the buffer is in use and
402  * the queue cannot be freed (by the means of REQBUFS(0)) call
403  */
404 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
405 {
406         unsigned int plane;
407         for (plane = 0; plane < vb->num_planes; ++plane) {
408                 void *mem_priv = vb->planes[plane].mem_priv;
409                 /*
410                  * If num_users() has not been provided, call_memop
411                  * will return 0, apparently nobody cares about this
412                  * case anyway. If num_users() returns more than 1,
413                  * we are not the only user of the plane's memory.
414                  */
415                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
416                         return true;
417         }
418         return false;
419 }
420 EXPORT_SYMBOL(vb2_buffer_in_use);
421
422 /**
423  * __buffers_in_use() - return true if any buffers on the queue are in use and
424  * the queue cannot be freed (by the means of REQBUFS(0)) call
425  */
426 static bool __buffers_in_use(struct vb2_queue *q)
427 {
428         unsigned int buffer;
429         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
430                 if (vb2_buffer_in_use(q, q->bufs[buffer]))
431                         return true;
432         }
433         return false;
434 }
435
436 /**
437  * vb2_core_querybuf() - query video buffer information
438  * @q:          videobuf queue
439  * @index:      id number of the buffer
440  * @pb:         buffer struct passed from userspace
441  *
442  * Should be called from vidioc_querybuf ioctl handler in driver.
443  * The passed buffer should have been verified.
444  * This function fills the relevant information for the userspace.
445  *
446  * The return values from this function are intended to be directly returned
447  * from vidioc_querybuf handler in driver.
448  */
449 int vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
450 {
451         return call_bufop(q, fill_user_buffer, q->bufs[index], pb);
452 }
453 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
454
455 /**
456  * __verify_userptr_ops() - verify that all memory operations required for
457  * USERPTR queue type have been provided
458  */
459 static int __verify_userptr_ops(struct vb2_queue *q)
460 {
461         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
462             !q->mem_ops->put_userptr)
463                 return -EINVAL;
464
465         return 0;
466 }
467
468 /**
469  * __verify_mmap_ops() - verify that all memory operations required for
470  * MMAP queue type have been provided
471  */
472 static int __verify_mmap_ops(struct vb2_queue *q)
473 {
474         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
475             !q->mem_ops->put || !q->mem_ops->mmap)
476                 return -EINVAL;
477
478         return 0;
479 }
480
481 /**
482  * __verify_dmabuf_ops() - verify that all memory operations required for
483  * DMABUF queue type have been provided
484  */
485 static int __verify_dmabuf_ops(struct vb2_queue *q)
486 {
487         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
488             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
489             !q->mem_ops->unmap_dmabuf)
490                 return -EINVAL;
491
492         return 0;
493 }
494
495 /**
496  * vb2_verify_memory_type() - Check whether the memory type and buffer type
497  * passed to a buffer operation are compatible with the queue.
498  */
499 int vb2_verify_memory_type(struct vb2_queue *q,
500                 enum vb2_memory memory, unsigned int type)
501 {
502         if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
503             memory != VB2_MEMORY_DMABUF) {
504                 dprintk(1, "unsupported memory type\n");
505                 return -EINVAL;
506         }
507
508         if (type != q->type) {
509                 dprintk(1, "requested type is incorrect\n");
510                 return -EINVAL;
511         }
512
513         /*
514          * Make sure all the required memory ops for given memory type
515          * are available.
516          */
517         if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
518                 dprintk(1, "MMAP for current setup unsupported\n");
519                 return -EINVAL;
520         }
521
522         if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
523                 dprintk(1, "USERPTR for current setup unsupported\n");
524                 return -EINVAL;
525         }
526
527         if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
528                 dprintk(1, "DMABUF for current setup unsupported\n");
529                 return -EINVAL;
530         }
531
532         /*
533          * Place the busy tests at the end: -EBUSY can be ignored when
534          * create_bufs is called with count == 0, but count == 0 should still
535          * do the memory and type validation.
536          */
537         if (vb2_fileio_is_active(q)) {
538                 dprintk(1, "file io in progress\n");
539                 return -EBUSY;
540         }
541         return 0;
542 }
543 EXPORT_SYMBOL(vb2_verify_memory_type);
544
545 /**
546  * vb2_core_reqbufs() - Initiate streaming
547  * @q:          videobuf2 queue
548  * @memory: memory type
549  * @count: requested buffer count
550  *
551  * Should be called from vidioc_reqbufs ioctl handler of a driver.
552  * This function:
553  * 1) verifies streaming parameters passed from the userspace,
554  * 2) sets up the queue,
555  * 3) negotiates number of buffers and planes per buffer with the driver
556  *    to be used during streaming,
557  * 4) allocates internal buffer structures (struct vb2_buffer), according to
558  *    the agreed parameters,
559  * 5) for MMAP memory type, allocates actual video memory, using the
560  *    memory handling/allocation routines provided during queue initialization
561  *
562  * If req->count is 0, all the memory will be freed instead.
563  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
564  * and the queue is not busy, memory will be reallocated.
565  *
566  * The return values from this function are intended to be directly returned
567  * from vidioc_reqbufs handler in driver.
568  */
569 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
570                 unsigned int *count)
571 {
572         unsigned int num_buffers, allocated_buffers, num_planes = 0;
573         int ret;
574
575         if (q->streaming) {
576                 dprintk(1, "streaming active\n");
577                 return -EBUSY;
578         }
579
580         if (*count == 0 || q->num_buffers != 0 || q->memory != memory) {
581                 /*
582                  * We already have buffers allocated, so first check if they
583                  * are not in use and can be freed.
584                  */
585                 mutex_lock(&q->mmap_lock);
586                 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
587                         mutex_unlock(&q->mmap_lock);
588                         dprintk(1, "memory in use, cannot free\n");
589                         return -EBUSY;
590                 }
591
592                 /*
593                  * Call queue_cancel to clean up any buffers in the PREPARED or
594                  * QUEUED state which is possible if buffers were prepared or
595                  * queued without ever calling STREAMON.
596                  */
597                 __vb2_queue_cancel(q);
598                 ret = __vb2_queue_free(q, q->num_buffers);
599                 mutex_unlock(&q->mmap_lock);
600                 if (ret)
601                         return ret;
602
603                 /*
604                  * In case of REQBUFS(0) return immediately without calling
605                  * driver's queue_setup() callback and allocating resources.
606                  */
607                 if (*count == 0)
608                         return 0;
609         }
610
611         /*
612          * Make sure the requested values and current defaults are sane.
613          */
614         num_buffers = min_t(unsigned int, *count, VB2_MAX_FRAME);
615         num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
616         memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
617         memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
618         q->memory = memory;
619
620         /*
621          * Ask the driver how many buffers and planes per buffer it requires.
622          * Driver also sets the size and allocator context for each plane.
623          */
624         ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
625                        q->plane_sizes, q->alloc_ctx);
626         if (ret)
627                 return ret;
628
629         /* Finally, allocate buffers and video memory */
630         allocated_buffers =
631                 __vb2_queue_alloc(q, memory, num_buffers, num_planes);
632         if (allocated_buffers == 0) {
633                 dprintk(1, "memory allocation failed\n");
634                 return -ENOMEM;
635         }
636
637         /*
638          * There is no point in continuing if we can't allocate the minimum
639          * number of buffers needed by this vb2_queue.
640          */
641         if (allocated_buffers < q->min_buffers_needed)
642                 ret = -ENOMEM;
643
644         /*
645          * Check if driver can handle the allocated number of buffers.
646          */
647         if (!ret && allocated_buffers < num_buffers) {
648                 num_buffers = allocated_buffers;
649
650                 ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
651                                &num_planes, q->plane_sizes, q->alloc_ctx);
652
653                 if (!ret && allocated_buffers < num_buffers)
654                         ret = -ENOMEM;
655
656                 /*
657                  * Either the driver has accepted a smaller number of buffers,
658                  * or .queue_setup() returned an error
659                  */
660         }
661
662         mutex_lock(&q->mmap_lock);
663         q->num_buffers = allocated_buffers;
664
665         if (ret < 0) {
666                 /*
667                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
668                  * from q->num_buffers.
669                  */
670                 __vb2_queue_free(q, allocated_buffers);
671                 mutex_unlock(&q->mmap_lock);
672                 return ret;
673         }
674         mutex_unlock(&q->mmap_lock);
675
676         /*
677          * Return the number of successfully allocated buffers
678          * to the userspace.
679          */
680         *count = allocated_buffers;
681         q->waiting_for_buffers = !q->is_output;
682
683         return 0;
684 }
685 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
686
687 /**
688  * vb2_core_create_bufs() - Allocate buffers and any required auxiliary structs
689  * @q:          videobuf2 queue
690  * @memory: memory type
691  * @count: requested buffer count
692  * @parg: parameter passed to device driver
693  *
694  * Should be called from vidioc_create_bufs ioctl handler of a driver.
695  * This function:
696  * 1) verifies parameter sanity
697  * 2) calls the .queue_setup() queue operation
698  * 3) performs any necessary memory allocations
699  *
700  * The return values from this function are intended to be directly returned
701  * from vidioc_create_bufs handler in driver.
702  */
703 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
704                 unsigned int *count, const void *parg)
705 {
706         unsigned int num_planes = 0, num_buffers, allocated_buffers;
707         int ret;
708
709         if (q->num_buffers == VB2_MAX_FRAME) {
710                 dprintk(1, "maximum number of buffers already allocated\n");
711                 return -ENOBUFS;
712         }
713
714         if (!q->num_buffers) {
715                 memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
716                 memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
717                 q->memory = memory;
718                 q->waiting_for_buffers = !q->is_output;
719         }
720
721         num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
722
723         /*
724          * Ask the driver, whether the requested number of buffers, planes per
725          * buffer and their sizes are acceptable
726          */
727         ret = call_qop(q, queue_setup, q, parg, &num_buffers,
728                        &num_planes, q->plane_sizes, q->alloc_ctx);
729         if (ret)
730                 return ret;
731
732         /* Finally, allocate buffers and video memory */
733         allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
734                                 num_planes);
735         if (allocated_buffers == 0) {
736                 dprintk(1, "memory allocation failed\n");
737                 return -ENOMEM;
738         }
739
740         /*
741          * Check if driver can handle the so far allocated number of buffers.
742          */
743         if (allocated_buffers < num_buffers) {
744                 num_buffers = allocated_buffers;
745
746                 /*
747                  * q->num_buffers contains the total number of buffers, that the
748                  * queue driver has set up
749                  */
750                 ret = call_qop(q, queue_setup, q, parg, &num_buffers,
751                                &num_planes, q->plane_sizes, q->alloc_ctx);
752
753                 if (!ret && allocated_buffers < num_buffers)
754                         ret = -ENOMEM;
755
756                 /*
757                  * Either the driver has accepted a smaller number of buffers,
758                  * or .queue_setup() returned an error
759                  */
760         }
761
762         mutex_lock(&q->mmap_lock);
763         q->num_buffers += allocated_buffers;
764
765         if (ret < 0) {
766                 /*
767                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
768                  * from q->num_buffers.
769                  */
770                 __vb2_queue_free(q, allocated_buffers);
771                 mutex_unlock(&q->mmap_lock);
772                 return -ENOMEM;
773         }
774         mutex_unlock(&q->mmap_lock);
775
776         /*
777          * Return the number of successfully allocated buffers
778          * to the userspace.
779          */
780         *count = allocated_buffers;
781
782         return 0;
783 }
784 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
785
786 /**
787  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
788  * @vb:         vb2_buffer to which the plane in question belongs to
789  * @plane_no:   plane number for which the address is to be returned
790  *
791  * This function returns a kernel virtual address of a given plane if
792  * such a mapping exist, NULL otherwise.
793  */
794 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
795 {
796         if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
797                 return NULL;
798
799         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
800
801 }
802 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
803
804 /**
805  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
806  * @vb:         vb2_buffer to which the plane in question belongs to
807  * @plane_no:   plane number for which the cookie is to be returned
808  *
809  * This function returns an allocator specific cookie for a given plane if
810  * available, NULL otherwise. The allocator should provide some simple static
811  * inline function, which would convert this cookie to the allocator specific
812  * type that can be used directly by the driver to access the buffer. This can
813  * be for example physical address, pointer to scatter list or IOMMU mapping.
814  */
815 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
816 {
817         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
818                 return NULL;
819
820         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
821 }
822 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
823
824 /**
825  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
826  * @vb:         vb2_buffer returned from the driver
827  * @state:      either VB2_BUF_STATE_DONE if the operation finished successfully,
828  *              VB2_BUF_STATE_ERROR if the operation finished with an error or
829  *              VB2_BUF_STATE_QUEUED if the driver wants to requeue buffers.
830  *              If start_streaming fails then it should return buffers with state
831  *              VB2_BUF_STATE_QUEUED to put them back into the queue.
832  *
833  * This function should be called by the driver after a hardware operation on
834  * a buffer is finished and the buffer may be returned to userspace. The driver
835  * cannot use this buffer anymore until it is queued back to it by videobuf
836  * by the means of buf_queue callback. Only buffers previously queued to the
837  * driver by buf_queue can be passed to this function.
838  *
839  * While streaming a buffer can only be returned in state DONE or ERROR.
840  * The start_streaming op can also return them in case the DMA engine cannot
841  * be started for some reason. In that case the buffers should be returned with
842  * state QUEUED.
843  */
844 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
845 {
846         struct vb2_queue *q = vb->vb2_queue;
847         unsigned long flags;
848         unsigned int plane;
849
850         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
851                 return;
852
853         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
854                     state != VB2_BUF_STATE_ERROR &&
855                     state != VB2_BUF_STATE_QUEUED &&
856                     state != VB2_BUF_STATE_REQUEUEING))
857                 state = VB2_BUF_STATE_ERROR;
858
859 #ifdef CONFIG_VIDEO_ADV_DEBUG
860         /*
861          * Although this is not a callback, it still does have to balance
862          * with the buf_queue op. So update this counter manually.
863          */
864         vb->cnt_buf_done++;
865 #endif
866         dprintk(4, "done processing on buffer %d, state: %d\n",
867                         vb->index, state);
868
869         /* sync buffers */
870         for (plane = 0; plane < vb->num_planes; ++plane)
871                 call_void_memop(vb, finish, vb->planes[plane].mem_priv);
872
873         spin_lock_irqsave(&q->done_lock, flags);
874         if (state == VB2_BUF_STATE_QUEUED ||
875             state == VB2_BUF_STATE_REQUEUEING) {
876                 vb->state = VB2_BUF_STATE_QUEUED;
877         } else {
878                 /* Add the buffer to the done buffers list */
879                 list_add_tail(&vb->done_entry, &q->done_list);
880                 vb->state = state;
881         }
882         atomic_dec(&q->owned_by_drv_count);
883         spin_unlock_irqrestore(&q->done_lock, flags);
884
885         trace_vb2_buf_done(q, vb);
886
887         switch (state) {
888         case VB2_BUF_STATE_QUEUED:
889                 return;
890         case VB2_BUF_STATE_REQUEUEING:
891                 if (q->start_streaming_called)
892                         __enqueue_in_driver(vb);
893                 return;
894         default:
895                 /* Inform any processes that may be waiting for buffers */
896                 wake_up(&q->done_wq);
897                 break;
898         }
899 }
900 EXPORT_SYMBOL_GPL(vb2_buffer_done);
901
902 /**
903  * vb2_discard_done() - discard all buffers marked as DONE
904  * @q:          videobuf2 queue
905  *
906  * This function is intended to be used with suspend/resume operations. It
907  * discards all 'done' buffers as they would be too old to be requested after
908  * resume.
909  *
910  * Drivers must stop the hardware and synchronize with interrupt handlers and/or
911  * delayed works before calling this function to make sure no buffer will be
912  * touched by the driver and/or hardware.
913  */
914 void vb2_discard_done(struct vb2_queue *q)
915 {
916         struct vb2_buffer *vb;
917         unsigned long flags;
918
919         spin_lock_irqsave(&q->done_lock, flags);
920         list_for_each_entry(vb, &q->done_list, done_entry)
921                 vb->state = VB2_BUF_STATE_ERROR;
922         spin_unlock_irqrestore(&q->done_lock, flags);
923 }
924 EXPORT_SYMBOL_GPL(vb2_discard_done);
925
926 /**
927  * __qbuf_mmap() - handle qbuf of an MMAP buffer
928  */
929 static int __qbuf_mmap(struct vb2_buffer *vb, const void *pb)
930 {
931         int ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
932                         vb, pb, vb->planes);
933         return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
934 }
935
936 /**
937  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
938  */
939 static int __qbuf_userptr(struct vb2_buffer *vb, const void *pb)
940 {
941         struct vb2_plane planes[VB2_MAX_PLANES];
942         struct vb2_queue *q = vb->vb2_queue;
943         void *mem_priv;
944         unsigned int plane;
945         int ret;
946         enum dma_data_direction dma_dir =
947                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
948         bool reacquired = vb->planes[0].mem_priv == NULL;
949
950         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
951         /* Copy relevant information provided by the userspace */
952         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer, vb, pb, planes);
953         if (ret)
954                 return ret;
955
956         for (plane = 0; plane < vb->num_planes; ++plane) {
957                 /* Skip the plane if already verified */
958                 if (vb->planes[plane].m.userptr &&
959                         vb->planes[plane].m.userptr == planes[plane].m.userptr
960                         && vb->planes[plane].length == planes[plane].length)
961                         continue;
962
963                 dprintk(3, "userspace address for plane %d changed, "
964                                 "reacquiring memory\n", plane);
965
966                 /* Check if the provided plane buffer is large enough */
967                 if (planes[plane].length < q->plane_sizes[plane]) {
968                         dprintk(1, "provided buffer size %u is less than "
969                                                 "setup size %u for plane %d\n",
970                                                 planes[plane].length,
971                                                 q->plane_sizes[plane], plane);
972                         ret = -EINVAL;
973                         goto err;
974                 }
975
976                 /* Release previously acquired memory if present */
977                 if (vb->planes[plane].mem_priv) {
978                         if (!reacquired) {
979                                 reacquired = true;
980                                 call_void_vb_qop(vb, buf_cleanup, vb);
981                         }
982                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
983                 }
984
985                 vb->planes[plane].mem_priv = NULL;
986                 vb->planes[plane].bytesused = 0;
987                 vb->planes[plane].length = 0;
988                 vb->planes[plane].m.userptr = 0;
989                 vb->planes[plane].data_offset = 0;
990
991                 /* Acquire each plane's memory */
992                 mem_priv = call_ptr_memop(vb, get_userptr, q->alloc_ctx[plane],
993                                       planes[plane].m.userptr,
994                                       planes[plane].length, dma_dir);
995                 if (IS_ERR_OR_NULL(mem_priv)) {
996                         dprintk(1, "failed acquiring userspace "
997                                                 "memory for plane %d\n", plane);
998                         ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
999                         goto err;
1000                 }
1001                 vb->planes[plane].mem_priv = mem_priv;
1002         }
1003
1004         /*
1005          * Now that everything is in order, copy relevant information
1006          * provided by userspace.
1007          */
1008         for (plane = 0; plane < vb->num_planes; ++plane) {
1009                 vb->planes[plane].bytesused = planes[plane].bytesused;
1010                 vb->planes[plane].length = planes[plane].length;
1011                 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1012                 vb->planes[plane].data_offset = planes[plane].data_offset;
1013         }
1014
1015         if (reacquired) {
1016                 /*
1017                  * One or more planes changed, so we must call buf_init to do
1018                  * the driver-specific initialization on the newly acquired
1019                  * buffer, if provided.
1020                  */
1021                 ret = call_vb_qop(vb, buf_init, vb);
1022                 if (ret) {
1023                         dprintk(1, "buffer initialization failed\n");
1024                         goto err;
1025                 }
1026         }
1027
1028         ret = call_vb_qop(vb, buf_prepare, vb);
1029         if (ret) {
1030                 dprintk(1, "buffer preparation failed\n");
1031                 call_void_vb_qop(vb, buf_cleanup, vb);
1032                 goto err;
1033         }
1034
1035         return 0;
1036 err:
1037         /* In case of errors, release planes that were already acquired */
1038         for (plane = 0; plane < vb->num_planes; ++plane) {
1039                 if (vb->planes[plane].mem_priv)
1040                         call_void_memop(vb, put_userptr,
1041                                 vb->planes[plane].mem_priv);
1042                 vb->planes[plane].mem_priv = NULL;
1043                 vb->planes[plane].m.userptr = 0;
1044                 vb->planes[plane].length = 0;
1045         }
1046
1047         return ret;
1048 }
1049
1050 /**
1051  * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1052  */
1053 static int __qbuf_dmabuf(struct vb2_buffer *vb, const void *pb)
1054 {
1055         struct vb2_plane planes[VB2_MAX_PLANES];
1056         struct vb2_queue *q = vb->vb2_queue;
1057         void *mem_priv;
1058         unsigned int plane;
1059         int ret;
1060         enum dma_data_direction dma_dir =
1061                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1062         bool reacquired = vb->planes[0].mem_priv == NULL;
1063
1064         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1065         /* Copy relevant information provided by the userspace */
1066         ret = call_bufop(vb->vb2_queue, fill_vb2_buffer, vb, pb, planes);
1067         if (ret)
1068                 return ret;
1069
1070         for (plane = 0; plane < vb->num_planes; ++plane) {
1071                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1072
1073                 if (IS_ERR_OR_NULL(dbuf)) {
1074                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1075                                 plane);
1076                         ret = -EINVAL;
1077                         goto err;
1078                 }
1079
1080                 /* use DMABUF size if length is not provided */
1081                 if (planes[plane].length == 0)
1082                         planes[plane].length = dbuf->size;
1083
1084                 if (planes[plane].length < q->plane_sizes[plane]) {
1085                         dprintk(1, "invalid dmabuf length for plane %d\n",
1086                                 plane);
1087                         ret = -EINVAL;
1088                         goto err;
1089                 }
1090
1091                 /* Skip the plane if already verified */
1092                 if (dbuf == vb->planes[plane].dbuf &&
1093                         vb->planes[plane].length == planes[plane].length) {
1094                         dma_buf_put(dbuf);
1095                         continue;
1096                 }
1097
1098                 dprintk(1, "buffer for plane %d changed\n", plane);
1099
1100                 if (!reacquired) {
1101                         reacquired = true;
1102                         call_void_vb_qop(vb, buf_cleanup, vb);
1103                 }
1104
1105                 /* Release previously acquired memory if present */
1106                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1107                 vb->planes[plane].bytesused = 0;
1108                 vb->planes[plane].length = 0;
1109                 vb->planes[plane].m.fd = 0;
1110                 vb->planes[plane].data_offset = 0;
1111
1112                 /* Acquire each plane's memory */
1113                 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1114                         q->alloc_ctx[plane], dbuf, planes[plane].length,
1115                         dma_dir);
1116                 if (IS_ERR(mem_priv)) {
1117                         dprintk(1, "failed to attach dmabuf\n");
1118                         ret = PTR_ERR(mem_priv);
1119                         dma_buf_put(dbuf);
1120                         goto err;
1121                 }
1122
1123                 vb->planes[plane].dbuf = dbuf;
1124                 vb->planes[plane].mem_priv = mem_priv;
1125         }
1126
1127         /* TODO: This pins the buffer(s) with  dma_buf_map_attachment()).. but
1128          * really we want to do this just before the DMA, not while queueing
1129          * the buffer(s)..
1130          */
1131         for (plane = 0; plane < vb->num_planes; ++plane) {
1132                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1133                 if (ret) {
1134                         dprintk(1, "failed to map dmabuf for plane %d\n",
1135                                 plane);
1136                         goto err;
1137                 }
1138                 vb->planes[plane].dbuf_mapped = 1;
1139         }
1140
1141         /*
1142          * Now that everything is in order, copy relevant information
1143          * provided by userspace.
1144          */
1145         for (plane = 0; plane < vb->num_planes; ++plane) {
1146                 vb->planes[plane].bytesused = planes[plane].bytesused;
1147                 vb->planes[plane].length = planes[plane].length;
1148                 vb->planes[plane].m.fd = planes[plane].m.fd;
1149                 vb->planes[plane].data_offset = planes[plane].data_offset;
1150         }
1151
1152         if (reacquired) {
1153                 /*
1154                  * Call driver-specific initialization on the newly acquired buffer,
1155                  * if provided.
1156                  */
1157                 ret = call_vb_qop(vb, buf_init, vb);
1158                 if (ret) {
1159                         dprintk(1, "buffer initialization failed\n");
1160                         goto err;
1161                 }
1162         }
1163
1164         ret = call_vb_qop(vb, buf_prepare, vb);
1165         if (ret) {
1166                 dprintk(1, "buffer preparation failed\n");
1167                 call_void_vb_qop(vb, buf_cleanup, vb);
1168                 goto err;
1169         }
1170
1171         return 0;
1172 err:
1173         /* In case of errors, release planes that were already acquired */
1174         __vb2_buf_dmabuf_put(vb);
1175
1176         return ret;
1177 }
1178
1179 /**
1180  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1181  */
1182 static void __enqueue_in_driver(struct vb2_buffer *vb)
1183 {
1184         struct vb2_queue *q = vb->vb2_queue;
1185         unsigned int plane;
1186
1187         vb->state = VB2_BUF_STATE_ACTIVE;
1188         atomic_inc(&q->owned_by_drv_count);
1189
1190         trace_vb2_buf_queue(q, vb);
1191
1192         /* sync buffers */
1193         for (plane = 0; plane < vb->num_planes; ++plane)
1194                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1195
1196         call_void_vb_qop(vb, buf_queue, vb);
1197 }
1198
1199 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1200 {
1201         struct vb2_queue *q = vb->vb2_queue;
1202         int ret;
1203
1204         if (q->error) {
1205                 dprintk(1, "fatal error occurred on queue\n");
1206                 return -EIO;
1207         }
1208
1209         vb->state = VB2_BUF_STATE_PREPARING;
1210
1211         switch (q->memory) {
1212         case VB2_MEMORY_MMAP:
1213                 ret = __qbuf_mmap(vb, pb);
1214                 break;
1215         case VB2_MEMORY_USERPTR:
1216                 ret = __qbuf_userptr(vb, pb);
1217                 break;
1218         case VB2_MEMORY_DMABUF:
1219                 ret = __qbuf_dmabuf(vb, pb);
1220                 break;
1221         default:
1222                 WARN(1, "Invalid queue type\n");
1223                 ret = -EINVAL;
1224         }
1225
1226         if (ret)
1227                 dprintk(1, "buffer preparation failed: %d\n", ret);
1228         vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1229
1230         return ret;
1231 }
1232
1233 /**
1234  * vb2_core_prepare_buf() - Pass ownership of a buffer from userspace
1235  *                      to the kernel
1236  * @q:          videobuf2 queue
1237  * @index:      id number of the buffer
1238  * @pb:         buffer structure passed from userspace to vidioc_prepare_buf
1239  *              handler in driver
1240  *
1241  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1242  * The passed buffer should have been verified.
1243  * This function calls buf_prepare callback in the driver (if provided),
1244  * in which driver-specific buffer initialization can be performed,
1245  *
1246  * The return values from this function are intended to be directly returned
1247  * from vidioc_prepare_buf handler in driver.
1248  */
1249 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1250 {
1251         struct vb2_buffer *vb;
1252         int ret;
1253
1254         vb = q->bufs[index];
1255         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1256                 dprintk(1, "invalid buffer state %d\n",
1257                         vb->state);
1258                 return -EINVAL;
1259         }
1260
1261         ret = __buf_prepare(vb, pb);
1262         if (ret)
1263                 return ret;
1264
1265         /* Fill buffer information for the userspace */
1266         ret = call_bufop(q, fill_user_buffer, vb, pb);
1267         if (ret)
1268                 return ret;
1269
1270         dprintk(1, "prepare of buffer %d succeeded\n", vb->index);
1271
1272         return ret;
1273 }
1274 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1275
1276 /**
1277  * vb2_start_streaming() - Attempt to start streaming.
1278  * @q:          videobuf2 queue
1279  *
1280  * Attempt to start streaming. When this function is called there must be
1281  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1282  * number of buffers required for the DMA engine to function). If the
1283  * @start_streaming op fails it is supposed to return all the driver-owned
1284  * buffers back to vb2 in state QUEUED. Check if that happened and if
1285  * not warn and reclaim them forcefully.
1286  */
1287 static int vb2_start_streaming(struct vb2_queue *q)
1288 {
1289         struct vb2_buffer *vb;
1290         int ret;
1291
1292         /*
1293          * If any buffers were queued before streamon,
1294          * we can now pass them to driver for processing.
1295          */
1296         list_for_each_entry(vb, &q->queued_list, queued_entry)
1297                 __enqueue_in_driver(vb);
1298
1299         /* Tell the driver to start streaming */
1300         q->start_streaming_called = 1;
1301         ret = call_qop(q, start_streaming, q,
1302                        atomic_read(&q->owned_by_drv_count));
1303         if (!ret)
1304                 return 0;
1305
1306         q->start_streaming_called = 0;
1307
1308         dprintk(1, "driver refused to start streaming\n");
1309         /*
1310          * If you see this warning, then the driver isn't cleaning up properly
1311          * after a failed start_streaming(). See the start_streaming()
1312          * documentation in videobuf2-core.h for more information how buffers
1313          * should be returned to vb2 in start_streaming().
1314          */
1315         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1316                 unsigned i;
1317
1318                 /*
1319                  * Forcefully reclaim buffers if the driver did not
1320                  * correctly return them to vb2.
1321                  */
1322                 for (i = 0; i < q->num_buffers; ++i) {
1323                         vb = q->bufs[i];
1324                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1325                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1326                 }
1327                 /* Must be zero now */
1328                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1329         }
1330         /*
1331          * If done_list is not empty, then start_streaming() didn't call
1332          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1333          * STATE_DONE.
1334          */
1335         WARN_ON(!list_empty(&q->done_list));
1336         return ret;
1337 }
1338
1339 /**
1340  * vb2_core_qbuf() - Queue a buffer from userspace
1341  * @q:          videobuf2 queue
1342  * @index:      id number of the buffer
1343  * @pb:         buffer structure passed from userspace to vidioc_qbuf handler
1344  *              in driver
1345  *
1346  * Should be called from vidioc_qbuf ioctl handler of a driver.
1347  * The passed buffer should have been verified.
1348  * This function:
1349  * 1) if necessary, calls buf_prepare callback in the driver (if provided), in
1350  *    which driver-specific buffer initialization can be performed,
1351  * 2) if streaming is on, queues the buffer in driver by the means of buf_queue
1352  *    callback for processing.
1353  *
1354  * The return values from this function are intended to be directly returned
1355  * from vidioc_qbuf handler in driver.
1356  */
1357 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1358 {
1359         struct vb2_buffer *vb;
1360         int ret;
1361
1362         vb = q->bufs[index];
1363
1364         switch (vb->state) {
1365         case VB2_BUF_STATE_DEQUEUED:
1366                 ret = __buf_prepare(vb, pb);
1367                 if (ret)
1368                         return ret;
1369                 break;
1370         case VB2_BUF_STATE_PREPARED:
1371                 break;
1372         case VB2_BUF_STATE_PREPARING:
1373                 dprintk(1, "buffer still being prepared\n");
1374                 return -EINVAL;
1375         default:
1376                 dprintk(1, "invalid buffer state %d\n", vb->state);
1377                 return -EINVAL;
1378         }
1379
1380         /*
1381          * Add to the queued buffers list, a buffer will stay on it until
1382          * dequeued in dqbuf.
1383          */
1384         list_add_tail(&vb->queued_entry, &q->queued_list);
1385         q->queued_count++;
1386         q->waiting_for_buffers = false;
1387         vb->state = VB2_BUF_STATE_QUEUED;
1388
1389         call_bufop(q, set_timestamp, vb, pb);
1390
1391         trace_vb2_qbuf(q, vb);
1392
1393         /*
1394          * If already streaming, give the buffer to driver for processing.
1395          * If not, the buffer will be given to driver on next streamon.
1396          */
1397         if (q->start_streaming_called)
1398                 __enqueue_in_driver(vb);
1399
1400         /* Fill buffer information for the userspace */
1401         ret = call_bufop(q, fill_user_buffer, vb, pb);
1402         if (ret)
1403                 return ret;
1404
1405         /*
1406          * If streamon has been called, and we haven't yet called
1407          * start_streaming() since not enough buffers were queued, and
1408          * we now have reached the minimum number of queued buffers,
1409          * then we can finally call start_streaming().
1410          */
1411         if (q->streaming && !q->start_streaming_called &&
1412             q->queued_count >= q->min_buffers_needed) {
1413                 ret = vb2_start_streaming(q);
1414                 if (ret)
1415                         return ret;
1416         }
1417
1418         dprintk(1, "qbuf of buffer %d succeeded\n", vb->index);
1419         return 0;
1420 }
1421 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1422
1423 /**
1424  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1425  * for dequeuing
1426  *
1427  * Will sleep if required for nonblocking == false.
1428  */
1429 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1430 {
1431         /*
1432          * All operations on vb_done_list are performed under done_lock
1433          * spinlock protection. However, buffers may be removed from
1434          * it and returned to userspace only while holding both driver's
1435          * lock and the done_lock spinlock. Thus we can be sure that as
1436          * long as we hold the driver's lock, the list will remain not
1437          * empty if list_empty() check succeeds.
1438          */
1439
1440         for (;;) {
1441                 int ret;
1442
1443                 if (!q->streaming) {
1444                         dprintk(1, "streaming off, will not wait for buffers\n");
1445                         return -EINVAL;
1446                 }
1447
1448                 if (q->error) {
1449                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1450                         return -EIO;
1451                 }
1452
1453                 if (q->last_buffer_dequeued) {
1454                         dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1455                         return -EPIPE;
1456                 }
1457
1458                 if (!list_empty(&q->done_list)) {
1459                         /*
1460                          * Found a buffer that we were waiting for.
1461                          */
1462                         break;
1463                 }
1464
1465                 if (nonblocking) {
1466                         dprintk(1, "nonblocking and no buffers to dequeue, "
1467                                                                 "will not wait\n");
1468                         return -EAGAIN;
1469                 }
1470
1471                 /*
1472                  * We are streaming and blocking, wait for another buffer to
1473                  * become ready or for streamoff. Driver's lock is released to
1474                  * allow streamoff or qbuf to be called while waiting.
1475                  */
1476                 call_void_qop(q, wait_prepare, q);
1477
1478                 /*
1479                  * All locks have been released, it is safe to sleep now.
1480                  */
1481                 dprintk(3, "will sleep waiting for buffers\n");
1482                 ret = wait_event_interruptible(q->done_wq,
1483                                 !list_empty(&q->done_list) || !q->streaming ||
1484                                 q->error);
1485
1486                 /*
1487                  * We need to reevaluate both conditions again after reacquiring
1488                  * the locks or return an error if one occurred.
1489                  */
1490                 call_void_qop(q, wait_finish, q);
1491                 if (ret) {
1492                         dprintk(1, "sleep was interrupted\n");
1493                         return ret;
1494                 }
1495         }
1496         return 0;
1497 }
1498
1499 /**
1500  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1501  *
1502  * Will sleep if required for nonblocking == false.
1503  */
1504 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1505                                 int nonblocking)
1506 {
1507         unsigned long flags;
1508         int ret;
1509
1510         /*
1511          * Wait for at least one buffer to become available on the done_list.
1512          */
1513         ret = __vb2_wait_for_done_vb(q, nonblocking);
1514         if (ret)
1515                 return ret;
1516
1517         /*
1518          * Driver's lock has been held since we last verified that done_list
1519          * is not empty, so no need for another list_empty(done_list) check.
1520          */
1521         spin_lock_irqsave(&q->done_lock, flags);
1522         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1523         /*
1524          * Only remove the buffer from done_list if v4l2_buffer can handle all
1525          * the planes.
1526          * Verifying planes is NOT necessary since it already has been checked
1527          * before the buffer is queued/prepared. So it can never fail.
1528          */
1529         list_del(&(*vb)->done_entry);
1530         spin_unlock_irqrestore(&q->done_lock, flags);
1531
1532         return ret;
1533 }
1534
1535 /**
1536  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
1537  * @q:          videobuf2 queue
1538  *
1539  * This function will wait until all buffers that have been given to the driver
1540  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
1541  * wait_prepare, wait_finish pair. It is intended to be called with all locks
1542  * taken, for example from stop_streaming() callback.
1543  */
1544 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1545 {
1546         if (!q->streaming) {
1547                 dprintk(1, "streaming off, will not wait for buffers\n");
1548                 return -EINVAL;
1549         }
1550
1551         if (q->start_streaming_called)
1552                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1553         return 0;
1554 }
1555 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1556
1557 /**
1558  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1559  */
1560 static void __vb2_dqbuf(struct vb2_buffer *vb)
1561 {
1562         struct vb2_queue *q = vb->vb2_queue;
1563         unsigned int i;
1564
1565         /* nothing to do if the buffer is already dequeued */
1566         if (vb->state == VB2_BUF_STATE_DEQUEUED)
1567                 return;
1568
1569         vb->state = VB2_BUF_STATE_DEQUEUED;
1570
1571         /* unmap DMABUF buffer */
1572         if (q->memory == VB2_MEMORY_DMABUF)
1573                 for (i = 0; i < vb->num_planes; ++i) {
1574                         if (!vb->planes[i].dbuf_mapped)
1575                                 continue;
1576                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1577                         vb->planes[i].dbuf_mapped = 0;
1578                 }
1579 }
1580
1581 /**
1582  * vb2_dqbuf() - Dequeue a buffer to the userspace
1583  * @q:          videobuf2 queue
1584  * @pb:         buffer structure passed from userspace to vidioc_dqbuf handler
1585  *              in driver
1586  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
1587  *               buffers ready for dequeuing are present. Normally the driver
1588  *               would be passing (file->f_flags & O_NONBLOCK) here
1589  *
1590  * Should be called from vidioc_dqbuf ioctl handler of a driver.
1591  * The passed buffer should have been verified.
1592  * This function:
1593  * 1) calls buf_finish callback in the driver (if provided), in which
1594  *    driver can perform any additional operations that may be required before
1595  *    returning the buffer to userspace, such as cache sync,
1596  * 2) the buffer struct members are filled with relevant information for
1597  *    the userspace.
1598  *
1599  * The return values from this function are intended to be directly returned
1600  * from vidioc_dqbuf handler in driver.
1601  */
1602 int vb2_core_dqbuf(struct vb2_queue *q, void *pb, bool nonblocking)
1603 {
1604         struct vb2_buffer *vb = NULL;
1605         int ret;
1606
1607         ret = __vb2_get_done_vb(q, &vb, nonblocking);
1608         if (ret < 0)
1609                 return ret;
1610
1611         switch (vb->state) {
1612         case VB2_BUF_STATE_DONE:
1613                 dprintk(3, "returning done buffer\n");
1614                 break;
1615         case VB2_BUF_STATE_ERROR:
1616                 dprintk(3, "returning done buffer with errors\n");
1617                 break;
1618         default:
1619                 dprintk(1, "invalid buffer state\n");
1620                 return -EINVAL;
1621         }
1622
1623         call_void_vb_qop(vb, buf_finish, vb);
1624
1625         /* Fill buffer information for the userspace */
1626         ret = call_bufop(q, fill_user_buffer, vb, pb);
1627         if (ret)
1628                 return ret;
1629
1630         /* Remove from videobuf queue */
1631         list_del(&vb->queued_entry);
1632         q->queued_count--;
1633
1634         trace_vb2_dqbuf(q, vb);
1635
1636         /* go back to dequeued state */
1637         __vb2_dqbuf(vb);
1638
1639         dprintk(1, "dqbuf of buffer %d, with state %d\n",
1640                         vb->index, vb->state);
1641
1642         return 0;
1643
1644 }
1645 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1646
1647 /**
1648  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1649  *
1650  * Removes all queued buffers from driver's queue and all buffers queued by
1651  * userspace from videobuf's queue. Returns to state after reqbufs.
1652  */
1653 static void __vb2_queue_cancel(struct vb2_queue *q)
1654 {
1655         unsigned int i;
1656
1657         /*
1658          * Tell driver to stop all transactions and release all queued
1659          * buffers.
1660          */
1661         if (q->start_streaming_called)
1662                 call_void_qop(q, stop_streaming, q);
1663
1664         /*
1665          * If you see this warning, then the driver isn't cleaning up properly
1666          * in stop_streaming(). See the stop_streaming() documentation in
1667          * videobuf2-core.h for more information how buffers should be returned
1668          * to vb2 in stop_streaming().
1669          */
1670         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1671                 for (i = 0; i < q->num_buffers; ++i)
1672                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
1673                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1674                 /* Must be zero now */
1675                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1676         }
1677
1678         q->streaming = 0;
1679         q->start_streaming_called = 0;
1680         q->queued_count = 0;
1681         q->error = 0;
1682
1683         /*
1684          * Remove all buffers from videobuf's list...
1685          */
1686         INIT_LIST_HEAD(&q->queued_list);
1687         /*
1688          * ...and done list; userspace will not receive any buffers it
1689          * has not already dequeued before initiating cancel.
1690          */
1691         INIT_LIST_HEAD(&q->done_list);
1692         atomic_set(&q->owned_by_drv_count, 0);
1693         wake_up_all(&q->done_wq);
1694
1695         /*
1696          * Reinitialize all buffers for next use.
1697          * Make sure to call buf_finish for any queued buffers. Normally
1698          * that's done in dqbuf, but that's not going to happen when we
1699          * cancel the whole queue. Note: this code belongs here, not in
1700          * __vb2_dqbuf() since in vb2_internal_dqbuf() there is a critical
1701          * call to __fill_v4l2_buffer() after buf_finish(). That order can't
1702          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1703          */
1704         for (i = 0; i < q->num_buffers; ++i) {
1705                 struct vb2_buffer *vb = q->bufs[i];
1706
1707                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1708                         vb->state = VB2_BUF_STATE_PREPARED;
1709                         call_void_vb_qop(vb, buf_finish, vb);
1710                 }
1711                 __vb2_dqbuf(vb);
1712         }
1713 }
1714
1715 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1716 {
1717         int ret;
1718
1719         if (type != q->type) {
1720                 dprintk(1, "invalid stream type\n");
1721                 return -EINVAL;
1722         }
1723
1724         if (q->streaming) {
1725                 dprintk(3, "already streaming\n");
1726                 return 0;
1727         }
1728
1729         if (!q->num_buffers) {
1730                 dprintk(1, "no buffers have been allocated\n");
1731                 return -EINVAL;
1732         }
1733
1734         if (q->num_buffers < q->min_buffers_needed) {
1735                 dprintk(1, "need at least %u allocated buffers\n",
1736                                 q->min_buffers_needed);
1737                 return -EINVAL;
1738         }
1739
1740         /*
1741          * Tell driver to start streaming provided sufficient buffers
1742          * are available.
1743          */
1744         if (q->queued_count >= q->min_buffers_needed) {
1745                 ret = vb2_start_streaming(q);
1746                 if (ret) {
1747                         __vb2_queue_cancel(q);
1748                         return ret;
1749                 }
1750         }
1751
1752         q->streaming = 1;
1753
1754         dprintk(3, "successful\n");
1755         return 0;
1756 }
1757 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1758
1759 /**
1760  * vb2_queue_error() - signal a fatal error on the queue
1761  * @q:          videobuf2 queue
1762  *
1763  * Flag that a fatal unrecoverable error has occurred and wake up all processes
1764  * waiting on the queue. Polling will now set POLLERR and queuing and dequeuing
1765  * buffers will return -EIO.
1766  *
1767  * The error flag will be cleared when cancelling the queue, either from
1768  * vb2_streamoff or vb2_queue_release. Drivers should thus not call this
1769  * function before starting the stream, otherwise the error flag will remain set
1770  * until the queue is released when closing the device node.
1771  */
1772 void vb2_queue_error(struct vb2_queue *q)
1773 {
1774         q->error = 1;
1775
1776         wake_up_all(&q->done_wq);
1777 }
1778 EXPORT_SYMBOL_GPL(vb2_queue_error);
1779
1780 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1781 {
1782         if (type != q->type) {
1783                 dprintk(1, "invalid stream type\n");
1784                 return -EINVAL;
1785         }
1786
1787         /*
1788          * Cancel will pause streaming and remove all buffers from the driver
1789          * and videobuf, effectively returning control over them to userspace.
1790          *
1791          * Note that we do this even if q->streaming == 0: if you prepare or
1792          * queue buffers, and then call streamoff without ever having called
1793          * streamon, you would still expect those buffers to be returned to
1794          * their normal dequeued state.
1795          */
1796         __vb2_queue_cancel(q);
1797         q->waiting_for_buffers = !q->is_output;
1798         q->last_buffer_dequeued = false;
1799
1800         dprintk(3, "successful\n");
1801         return 0;
1802 }
1803 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1804
1805 /**
1806  * __find_plane_by_offset() - find plane associated with the given offset off
1807  */
1808 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1809                         unsigned int *_buffer, unsigned int *_plane)
1810 {
1811         struct vb2_buffer *vb;
1812         unsigned int buffer, plane;
1813
1814         /*
1815          * Go over all buffers and their planes, comparing the given offset
1816          * with an offset assigned to each plane. If a match is found,
1817          * return its buffer and plane numbers.
1818          */
1819         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1820                 vb = q->bufs[buffer];
1821
1822                 for (plane = 0; plane < vb->num_planes; ++plane) {
1823                         if (vb->planes[plane].m.offset == off) {
1824                                 *_buffer = buffer;
1825                                 *_plane = plane;
1826                                 return 0;
1827                         }
1828                 }
1829         }
1830
1831         return -EINVAL;
1832 }
1833
1834 /**
1835  * vb2_core_expbuf() - Export a buffer as a file descriptor
1836  * @q:          videobuf2 queue
1837  * @fd:         file descriptor associated with DMABUF (set by driver) *
1838  * @type:       buffer type
1839  * @index:      id number of the buffer
1840  * @plane:      index of the plane to be exported, 0 for single plane queues
1841  * @flags:      flags for newly created file, currently only O_CLOEXEC is
1842  *              supported, refer to manual of open syscall for more details
1843  *
1844  * The return values from this function are intended to be directly returned
1845  * from vidioc_expbuf handler in driver.
1846  */
1847 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1848                 unsigned int index, unsigned int plane, unsigned int flags)
1849 {
1850         struct vb2_buffer *vb = NULL;
1851         struct vb2_plane *vb_plane;
1852         int ret;
1853         struct dma_buf *dbuf;
1854
1855         if (q->memory != VB2_MEMORY_MMAP) {
1856                 dprintk(1, "queue is not currently set up for mmap\n");
1857                 return -EINVAL;
1858         }
1859
1860         if (!q->mem_ops->get_dmabuf) {
1861                 dprintk(1, "queue does not support DMA buffer exporting\n");
1862                 return -EINVAL;
1863         }
1864
1865         if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1866                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1867                 return -EINVAL;
1868         }
1869
1870         if (type != q->type) {
1871                 dprintk(1, "invalid buffer type\n");
1872                 return -EINVAL;
1873         }
1874
1875         if (index >= q->num_buffers) {
1876                 dprintk(1, "buffer index out of range\n");
1877                 return -EINVAL;
1878         }
1879
1880         vb = q->bufs[index];
1881
1882         if (plane >= vb->num_planes) {
1883                 dprintk(1, "buffer plane out of range\n");
1884                 return -EINVAL;
1885         }
1886
1887         if (vb2_fileio_is_active(q)) {
1888                 dprintk(1, "expbuf: file io in progress\n");
1889                 return -EBUSY;
1890         }
1891
1892         vb_plane = &vb->planes[plane];
1893
1894         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1895                                 flags & O_ACCMODE);
1896         if (IS_ERR_OR_NULL(dbuf)) {
1897                 dprintk(1, "failed to export buffer %d, plane %d\n",
1898                         index, plane);
1899                 return -EINVAL;
1900         }
1901
1902         ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1903         if (ret < 0) {
1904                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1905                         index, plane, ret);
1906                 dma_buf_put(dbuf);
1907                 return ret;
1908         }
1909
1910         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1911                 index, plane, ret);
1912         *fd = ret;
1913
1914         return 0;
1915 }
1916 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1917
1918 /**
1919  * vb2_mmap() - map video buffers into application address space
1920  * @q:          videobuf2 queue
1921  * @vma:        vma passed to the mmap file operation handler in the driver
1922  *
1923  * Should be called from mmap file operation handler of a driver.
1924  * This function maps one plane of one of the available video buffers to
1925  * userspace. To map whole video memory allocated on reqbufs, this function
1926  * has to be called once per each plane per each buffer previously allocated.
1927  *
1928  * When the userspace application calls mmap, it passes to it an offset returned
1929  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
1930  * a "cookie", which is then used to identify the plane to be mapped.
1931  * This function finds a plane with a matching offset and a mapping is performed
1932  * by the means of a provided memory operation.
1933  *
1934  * The return values from this function are intended to be directly returned
1935  * from the mmap handler in driver.
1936  */
1937 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1938 {
1939         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1940         struct vb2_buffer *vb;
1941         unsigned int buffer = 0, plane = 0;
1942         int ret;
1943         unsigned long length;
1944
1945         if (q->memory != VB2_MEMORY_MMAP) {
1946                 dprintk(1, "queue is not currently set up for mmap\n");
1947                 return -EINVAL;
1948         }
1949
1950         /*
1951          * Check memory area access mode.
1952          */
1953         if (!(vma->vm_flags & VM_SHARED)) {
1954                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1955                 return -EINVAL;
1956         }
1957         if (q->is_output) {
1958                 if (!(vma->vm_flags & VM_WRITE)) {
1959                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1960                         return -EINVAL;
1961                 }
1962         } else {
1963                 if (!(vma->vm_flags & VM_READ)) {
1964                         dprintk(1, "invalid vma flags, VM_READ needed\n");
1965                         return -EINVAL;
1966                 }
1967         }
1968         if (vb2_fileio_is_active(q)) {
1969                 dprintk(1, "mmap: file io in progress\n");
1970                 return -EBUSY;
1971         }
1972
1973         /*
1974          * Find the plane corresponding to the offset passed by userspace.
1975          */
1976         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1977         if (ret)
1978                 return ret;
1979
1980         vb = q->bufs[buffer];
1981
1982         /*
1983          * MMAP requires page_aligned buffers.
1984          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1985          * so, we need to do the same here.
1986          */
1987         length = PAGE_ALIGN(vb->planes[plane].length);
1988         if (length < (vma->vm_end - vma->vm_start)) {
1989                 dprintk(1,
1990                         "MMAP invalid, as it would overflow buffer length\n");
1991                 return -EINVAL;
1992         }
1993
1994         mutex_lock(&q->mmap_lock);
1995         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1996         mutex_unlock(&q->mmap_lock);
1997         if (ret)
1998                 return ret;
1999
2000         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
2001         return 0;
2002 }
2003 EXPORT_SYMBOL_GPL(vb2_mmap);
2004
2005 #ifndef CONFIG_MMU
2006 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2007                                     unsigned long addr,
2008                                     unsigned long len,
2009                                     unsigned long pgoff,
2010                                     unsigned long flags)
2011 {
2012         unsigned long off = pgoff << PAGE_SHIFT;
2013         struct vb2_buffer *vb;
2014         unsigned int buffer, plane;
2015         void *vaddr;
2016         int ret;
2017
2018         if (q->memory != VB2_MEMORY_MMAP) {
2019                 dprintk(1, "queue is not currently set up for mmap\n");
2020                 return -EINVAL;
2021         }
2022
2023         /*
2024          * Find the plane corresponding to the offset passed by userspace.
2025          */
2026         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2027         if (ret)
2028                 return ret;
2029
2030         vb = q->bufs[buffer];
2031
2032         vaddr = vb2_plane_vaddr(vb, plane);
2033         return vaddr ? (unsigned long)vaddr : -EINVAL;
2034 }
2035 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2036 #endif
2037
2038 /**
2039  * vb2_core_queue_init() - initialize a videobuf2 queue
2040  * @q:          videobuf2 queue; this structure should be allocated in driver
2041  *
2042  * The vb2_queue structure should be allocated by the driver. The driver is
2043  * responsible of clearing it's content and setting initial values for some
2044  * required entries before calling this function.
2045  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
2046  * to the struct vb2_queue description in include/media/videobuf2-core.h
2047  * for more information.
2048  */
2049 int vb2_core_queue_init(struct vb2_queue *q)
2050 {
2051         /*
2052          * Sanity check
2053          */
2054         if (WARN_ON(!q)                   ||
2055             WARN_ON(!q->ops)              ||
2056             WARN_ON(!q->mem_ops)          ||
2057             WARN_ON(!q->type)             ||
2058             WARN_ON(!q->io_modes)         ||
2059             WARN_ON(!q->ops->queue_setup) ||
2060             WARN_ON(!q->ops->buf_queue))
2061                 return -EINVAL;
2062
2063         INIT_LIST_HEAD(&q->queued_list);
2064         INIT_LIST_HEAD(&q->done_list);
2065         spin_lock_init(&q->done_lock);
2066         mutex_init(&q->mmap_lock);
2067         init_waitqueue_head(&q->done_wq);
2068
2069         if (q->buf_struct_size == 0)
2070                 q->buf_struct_size = sizeof(struct vb2_buffer);
2071
2072         return 0;
2073 }
2074 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2075
2076 /**
2077  * vb2_core_queue_release() - stop streaming, release the queue and free memory
2078  * @q:          videobuf2 queue
2079  *
2080  * This function stops streaming and performs necessary clean ups, including
2081  * freeing video buffer memory. The driver is responsible for freeing
2082  * the vb2_queue structure itself.
2083  */
2084 void vb2_core_queue_release(struct vb2_queue *q)
2085 {
2086         __vb2_queue_cancel(q);
2087         mutex_lock(&q->mmap_lock);
2088         __vb2_queue_free(q, q->num_buffers);
2089         mutex_unlock(&q->mmap_lock);
2090 }
2091 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2092
2093 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
2094 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2095 MODULE_LICENSE("GPL");