Merge branch 'topic-0620/samsung-pm-3.4' into chromeos-exynos-3.4
[cascardo/linux.git] / drivers / media / video / videobuf2-core.c
1 /*
2  * videobuf2-core.c - V4L2 driver helper 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  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation.
12  */
13
14 #include <linux/err.h>
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/mm.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/sched.h>
21
22 #include <media/videobuf2-core.h>
23
24 static int debug;
25 module_param(debug, int, 0644);
26
27 #define dprintk(level, fmt, arg...)                                     \
28         do {                                                            \
29                 if (debug >= level)                                     \
30                         printk(KERN_DEBUG "vb2: " fmt, ## arg);         \
31         } while (0)
32
33 #define call_memop(q, op, args...)                                      \
34         (((q)->mem_ops->op) ?                                           \
35                 ((q)->mem_ops->op(args)) : 0)
36
37 #define call_qop(q, op, args...)                                        \
38         (((q)->ops->op) ? ((q)->ops->op(args)) : 0)
39
40 #define V4L2_BUFFER_STATE_FLAGS (V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
41                                  V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
42                                  V4L2_BUF_FLAG_PREPARED)
43
44 /**
45  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
46  */
47 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
48 {
49         struct vb2_queue *q = vb->vb2_queue;
50         void *mem_priv;
51         int plane;
52
53         /* Allocate memory for all planes in this buffer */
54         for (plane = 0; plane < vb->num_planes; ++plane) {
55                 mem_priv = call_memop(q, alloc, q->alloc_ctx[plane],
56                                       q->plane_sizes[plane]);
57                 if (IS_ERR_OR_NULL(mem_priv))
58                         goto free;
59
60                 /* Associate allocator private data with this plane */
61                 vb->planes[plane].mem_priv = mem_priv;
62                 vb->v4l2_planes[plane].length = q->plane_sizes[plane];
63         }
64
65         return 0;
66 free:
67         /* Free already allocated memory if one of the allocations failed */
68         for (; plane > 0; --plane) {
69                 call_memop(q, put, vb->planes[plane - 1].mem_priv);
70                 vb->planes[plane - 1].mem_priv = NULL;
71         }
72
73         return -ENOMEM;
74 }
75
76 /**
77  * __vb2_buf_mem_free() - free memory of the given buffer
78  */
79 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
80 {
81         struct vb2_queue *q = vb->vb2_queue;
82         unsigned int plane;
83
84         for (plane = 0; plane < vb->num_planes; ++plane) {
85                 call_memop(q, put, vb->planes[plane].mem_priv);
86                 vb->planes[plane].mem_priv = NULL;
87                 dprintk(3, "Freed plane %d of buffer %d\n", plane,
88                         vb->v4l2_buf.index);
89         }
90 }
91
92 /**
93  * __vb2_buf_userptr_put() - release userspace memory associated with
94  * a USERPTR buffer
95  */
96 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
97 {
98         struct vb2_queue *q = vb->vb2_queue;
99         unsigned int plane;
100
101         for (plane = 0; plane < vb->num_planes; ++plane) {
102                 if (vb->planes[plane].mem_priv)
103                         call_memop(q, 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_queue *q, struct vb2_plane *p)
113 {
114         if (!p->mem_priv)
115                 return;
116
117         if (p->dbuf_mapped)
118                 call_memop(q, unmap_dmabuf, p->mem_priv);
119
120         call_memop(q, detach_dmabuf, p->mem_priv);
121         dma_buf_put(p->dbuf);
122         memset(p, 0, sizeof *p);
123 }
124
125 /**
126  * __vb2_buf_dmabuf_put() - release memory associated with
127  * a DMABUF shared buffer
128  */
129 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
130 {
131         struct vb2_queue *q = vb->vb2_queue;
132         unsigned int plane;
133
134         for (plane = 0; plane < vb->num_planes; ++plane)
135                 __vb2_plane_dmabuf_put(q, &vb->planes[plane]);
136 }
137
138 /**
139  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
140  * every buffer on the queue
141  */
142 static void __setup_offsets(struct vb2_queue *q, unsigned int n)
143 {
144         unsigned int buffer, plane;
145         struct vb2_buffer *vb;
146         unsigned long off;
147
148         if (q->num_buffers) {
149                 struct v4l2_plane *p;
150                 vb = q->bufs[q->num_buffers - 1];
151                 p = &vb->v4l2_planes[vb->num_planes - 1];
152                 off = PAGE_ALIGN(p->m.mem_offset + p->length);
153         } else {
154                 off = 0;
155         }
156
157         for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
158                 vb = q->bufs[buffer];
159                 if (!vb)
160                         continue;
161
162                 for (plane = 0; plane < vb->num_planes; ++plane) {
163                         vb->v4l2_planes[plane].length = q->plane_sizes[plane];
164                         vb->v4l2_planes[plane].m.mem_offset = off;
165
166                         dprintk(3, "Buffer %d, plane %d offset 0x%08lx\n",
167                                         buffer, plane, off);
168
169                         off += vb->v4l2_planes[plane].length;
170                         off = PAGE_ALIGN(off);
171                 }
172         }
173 }
174
175 /**
176  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
177  * video buffer memory for all buffers/planes on the queue and initializes the
178  * queue
179  *
180  * Returns the number of buffers successfully allocated.
181  */
182 static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
183                              unsigned int num_buffers, unsigned int num_planes)
184 {
185         unsigned int buffer;
186         struct vb2_buffer *vb;
187         int ret;
188
189         for (buffer = 0; buffer < num_buffers; ++buffer) {
190                 /* Allocate videobuf buffer structures */
191                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
192                 if (!vb) {
193                         dprintk(1, "Memory alloc for buffer struct failed\n");
194                         break;
195                 }
196
197                 /* Length stores number of planes for multiplanar buffers */
198                 if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
199                         vb->v4l2_buf.length = num_planes;
200
201                 vb->state = VB2_BUF_STATE_DEQUEUED;
202                 vb->vb2_queue = q;
203                 vb->num_planes = num_planes;
204                 vb->v4l2_buf.index = q->num_buffers + buffer;
205                 vb->v4l2_buf.type = q->type;
206                 vb->v4l2_buf.memory = memory;
207
208                 /* Allocate video buffer memory for the MMAP type */
209                 if (memory == V4L2_MEMORY_MMAP) {
210                         ret = __vb2_buf_mem_alloc(vb);
211                         if (ret) {
212                                 dprintk(1, "Failed allocating memory for "
213                                                 "buffer %d\n", buffer);
214                                 kfree(vb);
215                                 break;
216                         }
217                         /*
218                          * Call the driver-provided buffer initialization
219                          * callback, if given. An error in initialization
220                          * results in queue setup failure.
221                          */
222                         ret = call_qop(q, buf_init, vb);
223                         if (ret) {
224                                 dprintk(1, "Buffer %d %p initialization"
225                                         " failed\n", buffer, vb);
226                                 __vb2_buf_mem_free(vb);
227                                 kfree(vb);
228                                 break;
229                         }
230                 }
231
232                 q->bufs[q->num_buffers + buffer] = vb;
233         }
234
235         __setup_offsets(q, buffer);
236
237         dprintk(1, "Allocated %d buffers, %d plane(s) each\n",
238                         buffer, num_planes);
239
240         return buffer;
241 }
242
243 /**
244  * __vb2_free_mem() - release all video buffer memory for a given queue
245  */
246 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
247 {
248         unsigned int buffer;
249         struct vb2_buffer *vb;
250
251         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
252              ++buffer) {
253                 vb = q->bufs[buffer];
254                 if (!vb)
255                         continue;
256
257                 /* Free MMAP buffers or release USERPTR buffers */
258                 if (q->memory == V4L2_MEMORY_MMAP)
259                         __vb2_buf_mem_free(vb);
260                 else if (q->memory == V4L2_MEMORY_DMABUF)
261                         __vb2_buf_dmabuf_put(vb);
262                 else
263                         __vb2_buf_userptr_put(vb);
264         }
265 }
266
267 /**
268  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
269  * related information, if no buffers are left return the queue to an
270  * uninitialized state. Might be called even if the queue has already been freed.
271  */
272 static void __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
273 {
274         unsigned int buffer;
275
276         /* Call driver-provided cleanup function for each buffer, if provided */
277         if (q->ops->buf_cleanup) {
278                 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
279                      ++buffer) {
280                         if (NULL == q->bufs[buffer])
281                                 continue;
282                         q->ops->buf_cleanup(q->bufs[buffer]);
283                 }
284         }
285
286         /* Release video buffer memory */
287         __vb2_free_mem(q, buffers);
288
289         /* Free videobuf buffers */
290         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
291              ++buffer) {
292                 kfree(q->bufs[buffer]);
293                 q->bufs[buffer] = NULL;
294         }
295
296         q->num_buffers -= buffers;
297         if (!q->num_buffers)
298                 q->memory = 0;
299         INIT_LIST_HEAD(&q->queued_list);
300 }
301
302 /**
303  * __verify_planes_array() - verify that the planes array passed in struct
304  * v4l2_buffer from userspace can be safely used
305  */
306 static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
307 {
308         /* Is memory for copying plane information present? */
309         if (NULL == b->m.planes) {
310                 dprintk(1, "Multi-planar buffer passed but "
311                            "planes array not provided\n");
312                 return -EINVAL;
313         }
314
315         if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
316                 dprintk(1, "Incorrect planes array length, "
317                            "expected %d, got %d\n", vb->num_planes, b->length);
318                 return -EINVAL;
319         }
320
321         return 0;
322 }
323
324 /**
325  * __buffer_in_use() - return true if the buffer is in use and
326  * the queue cannot be freed (by the means of REQBUFS(0)) call
327  */
328 static bool __buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
329 {
330         unsigned int plane;
331         for (plane = 0; plane < vb->num_planes; ++plane) {
332                 void *mem_priv = vb->planes[plane].mem_priv;
333                 /*
334                  * If num_users() has not been provided, call_memop
335                  * will return 0, apparently nobody cares about this
336                  * case anyway. If num_users() returns more than 1,
337                  * we are not the only user of the plane's memory.
338                  */
339                 if (mem_priv && call_memop(q, num_users, mem_priv) > 1)
340                         return true;
341         }
342         return false;
343 }
344
345 /**
346  * __buffers_in_use() - return true if any buffers on the queue are in use and
347  * the queue cannot be freed (by the means of REQBUFS(0)) call
348  */
349 static bool __buffers_in_use(struct vb2_queue *q)
350 {
351         unsigned int buffer;
352         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
353                 if (__buffer_in_use(q, q->bufs[buffer]))
354                         return true;
355         }
356         return false;
357 }
358
359 /**
360  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
361  * returned to userspace
362  */
363 static int __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
364 {
365         struct vb2_queue *q = vb->vb2_queue;
366         int ret;
367
368         /* Copy back data such as timestamp, flags, input, etc. */
369         memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
370         b->input = vb->v4l2_buf.input;
371         b->reserved = vb->v4l2_buf.reserved;
372
373         if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
374                 ret = __verify_planes_array(vb, b);
375                 if (ret)
376                         return ret;
377
378                 /*
379                  * Fill in plane-related data if userspace provided an array
380                  * for it. The memory and size is verified above.
381                  */
382                 memcpy(b->m.planes, vb->v4l2_planes,
383                         b->length * sizeof(struct v4l2_plane));
384
385                 if (q->memory == V4L2_MEMORY_DMABUF) {
386                         unsigned int plane;
387                         for (plane = 0; plane < vb->num_planes; ++plane)
388                                 b->m.planes[plane].m.fd = 0;
389                 }
390         } else {
391                 /*
392                  * We use length and offset in v4l2_planes array even for
393                  * single-planar buffers, but userspace does not.
394                  */
395                 b->length = vb->v4l2_planes[0].length;
396                 b->bytesused = vb->v4l2_planes[0].bytesused;
397                 if (q->memory == V4L2_MEMORY_MMAP)
398                         b->m.offset = vb->v4l2_planes[0].m.mem_offset;
399                 else if (q->memory == V4L2_MEMORY_USERPTR)
400                         b->m.userptr = vb->v4l2_planes[0].m.userptr;
401                 else if (q->memory == V4L2_MEMORY_DMABUF)
402                         b->m.fd = 0;
403         }
404
405         /*
406          * Clear any buffer state related flags.
407          */
408         b->flags &= ~V4L2_BUFFER_STATE_FLAGS;
409
410         switch (vb->state) {
411         case VB2_BUF_STATE_QUEUED:
412         case VB2_BUF_STATE_ACTIVE:
413                 b->flags |= V4L2_BUF_FLAG_QUEUED;
414                 break;
415         case VB2_BUF_STATE_ERROR:
416                 b->flags |= V4L2_BUF_FLAG_ERROR;
417                 /* fall through */
418         case VB2_BUF_STATE_DONE:
419                 b->flags |= V4L2_BUF_FLAG_DONE;
420                 break;
421         case VB2_BUF_STATE_PREPARED:
422                 b->flags |= V4L2_BUF_FLAG_PREPARED;
423                 break;
424         case VB2_BUF_STATE_DEQUEUED:
425                 /* nothing */
426                 break;
427         }
428
429         if (__buffer_in_use(q, vb))
430                 b->flags |= V4L2_BUF_FLAG_MAPPED;
431
432         return 0;
433 }
434
435 /**
436  * vb2_querybuf() - query video buffer information
437  * @q:          videobuf queue
438  * @b:          buffer struct passed from userspace to vidioc_querybuf handler
439  *              in driver
440  *
441  * Should be called from vidioc_querybuf ioctl handler in driver.
442  * This function will verify the passed v4l2_buffer structure and fill the
443  * relevant information for the userspace.
444  *
445  * The return values from this function are intended to be directly returned
446  * from vidioc_querybuf handler in driver.
447  */
448 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
449 {
450         struct vb2_buffer *vb;
451
452         if (b->type != q->type) {
453                 dprintk(1, "querybuf: wrong buffer type\n");
454                 return -EINVAL;
455         }
456
457         if (b->index >= q->num_buffers) {
458                 dprintk(1, "querybuf: buffer index out of range\n");
459                 return -EINVAL;
460         }
461         vb = q->bufs[b->index];
462
463         return __fill_v4l2_buffer(vb, b);
464 }
465 EXPORT_SYMBOL(vb2_querybuf);
466
467 /**
468  * __verify_userptr_ops() - verify that all memory operations required for
469  * USERPTR queue type have been provided
470  */
471 static int __verify_userptr_ops(struct vb2_queue *q)
472 {
473         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
474             !q->mem_ops->put_userptr)
475                 return -EINVAL;
476
477         return 0;
478 }
479
480 /**
481  * __verify_mmap_ops() - verify that all memory operations required for
482  * MMAP queue type have been provided
483  */
484 static int __verify_mmap_ops(struct vb2_queue *q)
485 {
486         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
487             !q->mem_ops->put || !q->mem_ops->mmap)
488                 return -EINVAL;
489
490         return 0;
491 }
492
493 /**
494  * __verify_dmabuf_ops() - verify that all memory operations required for
495  * DMABUF queue type have been provided
496  */
497 static int __verify_dmabuf_ops(struct vb2_queue *q)
498 {
499         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
500             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
501             !q->mem_ops->unmap_dmabuf)
502                 return -EINVAL;
503
504         return 0;
505 }
506
507 /**
508  * vb2_reqbufs() - Initiate streaming
509  * @q:          videobuf2 queue
510  * @req:        struct passed from userspace to vidioc_reqbufs handler in driver
511  *
512  * Should be called from vidioc_reqbufs ioctl handler of a driver.
513  * This function:
514  * 1) verifies streaming parameters passed from the userspace,
515  * 2) sets up the queue,
516  * 3) negotiates number of buffers and planes per buffer with the driver
517  *    to be used during streaming,
518  * 4) allocates internal buffer structures (struct vb2_buffer), according to
519  *    the agreed parameters,
520  * 5) for MMAP memory type, allocates actual video memory, using the
521  *    memory handling/allocation routines provided during queue initialization
522  *
523  * If req->count is 0, all the memory will be freed instead.
524  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
525  * and the queue is not busy, memory will be reallocated.
526  *
527  * The return values from this function are intended to be directly returned
528  * from vidioc_reqbufs handler in driver.
529  */
530 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
531 {
532         unsigned int num_buffers, allocated_buffers, num_planes = 0;
533         int ret = 0;
534
535         if (q->fileio) {
536                 dprintk(1, "reqbufs: file io in progress\n");
537                 return -EBUSY;
538         }
539
540         if (req->memory != V4L2_MEMORY_MMAP &&
541             req->memory != V4L2_MEMORY_DMABUF &&
542             req->memory != V4L2_MEMORY_USERPTR) {
543                 dprintk(1, "reqbufs: unsupported memory type\n");
544                 return -EINVAL;
545         }
546
547         if (req->type != q->type) {
548                 dprintk(1, "reqbufs: requested type is incorrect\n");
549                 return -EINVAL;
550         }
551
552         if (q->streaming) {
553                 dprintk(1, "reqbufs: streaming active\n");
554                 return -EBUSY;
555         }
556
557         /*
558          * Make sure all the required memory ops for given memory type
559          * are available.
560          */
561         if (req->memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
562                 dprintk(1, "reqbufs: MMAP for current setup unsupported\n");
563                 return -EINVAL;
564         }
565
566         if (req->memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
567                 dprintk(1, "reqbufs: USERPTR for current setup unsupported\n");
568                 return -EINVAL;
569         }
570
571         if (req->memory == V4L2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
572                 dprintk(1, "reqbufs: DMABUF for current setup unsupported\n");
573                 return -EINVAL;
574         }
575
576         if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
577                 /*
578                  * We already have buffers allocated, so first check if they
579                  * are not in use and can be freed.
580                  */
581                 if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
582                         dprintk(1, "reqbufs: memory in use, cannot free\n");
583                         return -EBUSY;
584                 }
585
586                 __vb2_queue_free(q, q->num_buffers);
587
588                 /*
589                  * In case of REQBUFS(0) return immediately without calling
590                  * driver's queue_setup() callback and allocating resources.
591                  */
592                 if (req->count == 0)
593                         return 0;
594         }
595
596         /*
597          * Make sure the requested values and current defaults are sane.
598          */
599         num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
600         memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
601         memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
602         q->memory = req->memory;
603
604         /*
605          * Ask the driver how many buffers and planes per buffer it requires.
606          * Driver also sets the size and allocator context for each plane.
607          */
608         ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
609                        q->plane_sizes, q->alloc_ctx);
610         if (ret)
611                 return ret;
612
613         /* Finally, allocate buffers and video memory */
614         ret = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes);
615         if (ret == 0) {
616                 dprintk(1, "Memory allocation failed\n");
617                 return -ENOMEM;
618         }
619
620         allocated_buffers = ret;
621
622         /*
623          * Check if driver can handle the allocated number of buffers.
624          */
625         if (allocated_buffers < num_buffers) {
626                 num_buffers = allocated_buffers;
627
628                 ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
629                                &num_planes, q->plane_sizes, q->alloc_ctx);
630
631                 if (!ret && allocated_buffers < num_buffers)
632                         ret = -ENOMEM;
633
634                 /*
635                  * Either the driver has accepted a smaller number of buffers,
636                  * or .queue_setup() returned an error
637                  */
638         }
639
640         q->num_buffers = allocated_buffers;
641
642         if (ret < 0) {
643                 __vb2_queue_free(q, allocated_buffers);
644                 return ret;
645         }
646
647         /*
648          * Return the number of successfully allocated buffers
649          * to the userspace.
650          */
651         req->count = allocated_buffers;
652
653         return 0;
654 }
655 EXPORT_SYMBOL_GPL(vb2_reqbufs);
656
657 /**
658  * vb2_create_bufs() - Allocate buffers and any required auxiliary structs
659  * @q:          videobuf2 queue
660  * @create:     creation parameters, passed from userspace to vidioc_create_bufs
661  *              handler in driver
662  *
663  * Should be called from vidioc_create_bufs ioctl handler of a driver.
664  * This function:
665  * 1) verifies parameter sanity
666  * 2) calls the .queue_setup() queue operation
667  * 3) performs any necessary memory allocations
668  *
669  * The return values from this function are intended to be directly returned
670  * from vidioc_create_bufs handler in driver.
671  */
672 int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
673 {
674         unsigned int num_planes = 0, num_buffers, allocated_buffers;
675         int ret = 0;
676
677         if (q->fileio) {
678                 dprintk(1, "%s(): file io in progress\n", __func__);
679                 return -EBUSY;
680         }
681
682         if (create->memory != V4L2_MEMORY_MMAP &&
683             create->memory != V4L2_MEMORY_USERPTR &&
684             create->memory != V4L2_MEMORY_DMABUF) {
685                 dprintk(1, "%s(): unsupported memory type\n", __func__);
686                 return -EINVAL;
687         }
688
689         if (create->format.type != q->type) {
690                 dprintk(1, "%s(): requested type is incorrect\n", __func__);
691                 return -EINVAL;
692         }
693
694         /*
695          * Make sure all the required memory ops for given memory type
696          * are available.
697          */
698         if (create->memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
699                 dprintk(1, "%s(): MMAP for current setup unsupported\n", __func__);
700                 return -EINVAL;
701         }
702
703         if (create->memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
704                 dprintk(1, "%s(): USERPTR for current setup unsupported\n", __func__);
705                 return -EINVAL;
706         }
707
708         if (create->memory == V4L2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
709                 dprintk(1, "%s(): DMABUF for current setup unsupported\n", __func__);
710                 return -EINVAL;
711         }
712
713         if (q->num_buffers == VIDEO_MAX_FRAME) {
714                 dprintk(1, "%s(): maximum number of buffers already allocated\n",
715                         __func__);
716                 return -ENOBUFS;
717         }
718
719         create->index = q->num_buffers;
720
721         if (!q->num_buffers) {
722                 memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
723                 memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
724                 q->memory = create->memory;
725         }
726
727         num_buffers = min(create->count, VIDEO_MAX_FRAME - q->num_buffers);
728
729         /*
730          * Ask the driver, whether the requested number of buffers, planes per
731          * buffer and their sizes are acceptable
732          */
733         ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
734                        &num_planes, q->plane_sizes, q->alloc_ctx);
735         if (ret)
736                 return ret;
737
738         /* Finally, allocate buffers and video memory */
739         ret = __vb2_queue_alloc(q, create->memory, num_buffers,
740                                 num_planes);
741         if (ret < 0) {
742                 dprintk(1, "Memory allocation failed with error: %d\n", ret);
743                 return ret;
744         }
745
746         allocated_buffers = ret;
747
748         /*
749          * Check if driver can handle the so far allocated number of buffers.
750          */
751         if (ret < num_buffers) {
752                 num_buffers = ret;
753
754                 /*
755                  * q->num_buffers contains the total number of buffers, that the
756                  * queue driver has set up
757                  */
758                 ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
759                                &num_planes, q->plane_sizes, q->alloc_ctx);
760
761                 if (!ret && allocated_buffers < num_buffers)
762                         ret = -ENOMEM;
763
764                 /*
765                  * Either the driver has accepted a smaller number of buffers,
766                  * or .queue_setup() returned an error
767                  */
768         }
769
770         q->num_buffers += allocated_buffers;
771
772         if (ret < 0) {
773                 __vb2_queue_free(q, allocated_buffers);
774                 return ret;
775         }
776
777         /*
778          * Return the number of successfully allocated buffers
779          * to the userspace.
780          */
781         create->count = allocated_buffers;
782
783         return 0;
784 }
785 EXPORT_SYMBOL_GPL(vb2_create_bufs);
786
787 /**
788  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
789  * @vb:         vb2_buffer to which the plane in question belongs to
790  * @plane_no:   plane number for which the address is to be returned
791  *
792  * This function returns a kernel virtual address of a given plane if
793  * such a mapping exist, NULL otherwise.
794  */
795 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
796 {
797         struct vb2_queue *q = vb->vb2_queue;
798
799         if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
800                 return NULL;
801
802         return call_memop(q, vaddr, vb->planes[plane_no].mem_priv);
803
804 }
805 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
806
807 /**
808  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
809  * @vb:         vb2_buffer to which the plane in question belongs to
810  * @plane_no:   plane number for which the cookie is to be returned
811  *
812  * This function returns an allocator specific cookie for a given plane if
813  * available, NULL otherwise. The allocator should provide some simple static
814  * inline function, which would convert this cookie to the allocator specific
815  * type that can be used directly by the driver to access the buffer. This can
816  * be for example physical address, pointer to scatter list or IOMMU mapping.
817  */
818 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
819 {
820         struct vb2_queue *q = vb->vb2_queue;
821
822         if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
823                 return NULL;
824
825         return call_memop(q, cookie, vb->planes[plane_no].mem_priv);
826 }
827 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
828
829 /**
830  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
831  * @vb:         vb2_buffer returned from the driver
832  * @state:      either VB2_BUF_STATE_DONE if the operation finished successfully
833  *              or VB2_BUF_STATE_ERROR if the operation finished with an error
834  *
835  * This function should be called by the driver after a hardware operation on
836  * a buffer is finished and the buffer may be returned to userspace. The driver
837  * cannot use this buffer anymore until it is queued back to it by videobuf
838  * by the means of buf_queue callback. Only buffers previously queued to the
839  * driver by buf_queue can be passed to this function.
840  */
841 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
842 {
843         struct vb2_queue *q = vb->vb2_queue;
844         unsigned long flags;
845         unsigned int plane;
846
847         if (vb->state != VB2_BUF_STATE_ACTIVE)
848                 return;
849
850         if (state != VB2_BUF_STATE_DONE && state != VB2_BUF_STATE_ERROR)
851                 return;
852
853         dprintk(4, "Done processing on buffer %d, state: %d\n",
854                         vb->v4l2_buf.index, vb->state);
855
856         /* sync buffers */
857         for (plane = 0; plane < vb->num_planes; ++plane)
858                 call_memop(q, finish, vb->planes[plane].mem_priv);
859
860         /* Add the buffer to the done buffers list */
861         spin_lock_irqsave(&q->done_lock, flags);
862         vb->state = state;
863         list_add_tail(&vb->done_entry, &q->done_list);
864         atomic_dec(&q->queued_count);
865         spin_unlock_irqrestore(&q->done_lock, flags);
866
867         /* Inform any processes that may be waiting for buffers */
868         wake_up(&q->done_wq);
869 }
870 EXPORT_SYMBOL_GPL(vb2_buffer_done);
871
872 /**
873  * __fill_vb2_buffer() - fill a vb2_buffer with information provided in
874  * a v4l2_buffer by the userspace
875  */
876 static int __fill_vb2_buffer(struct vb2_buffer *vb, const struct v4l2_buffer *b,
877                                 struct v4l2_plane *v4l2_planes)
878 {
879         unsigned int plane;
880         int ret;
881
882         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
883                 /*
884                  * Verify that the userspace gave us a valid array for
885                  * plane information.
886                  */
887                 ret = __verify_planes_array(vb, b);
888                 if (ret)
889                         return ret;
890
891                 /* Fill in driver-provided information for OUTPUT types */
892                 if (V4L2_TYPE_IS_OUTPUT(b->type)) {
893                         /*
894                          * Will have to go up to b->length when API starts
895                          * accepting variable number of planes.
896                          */
897                         for (plane = 0; plane < vb->num_planes; ++plane) {
898                                 v4l2_planes[plane].bytesused =
899                                         b->m.planes[plane].bytesused;
900                                 v4l2_planes[plane].data_offset =
901                                         b->m.planes[plane].data_offset;
902                         }
903                 }
904
905                 if (b->memory == V4L2_MEMORY_USERPTR) {
906                         for (plane = 0; plane < vb->num_planes; ++plane) {
907                                 v4l2_planes[plane].m.userptr =
908                                         b->m.planes[plane].m.userptr;
909                                 v4l2_planes[plane].length =
910                                         b->m.planes[plane].length;
911                         }
912                 }
913                 if (b->memory == V4L2_MEMORY_DMABUF) {
914                         for (plane = 0; plane < vb->num_planes; ++plane) {
915                                 v4l2_planes[plane].bytesused =
916                                         b->m.planes[plane].bytesused;
917                                 v4l2_planes[plane].m.fd =
918                                         b->m.planes[plane].m.fd;
919                         }
920                 }
921         } else {
922                 /*
923                  * Single-planar buffers do not use planes array,
924                  * so fill in relevant v4l2_buffer struct fields instead.
925                  * In videobuf we use our internal V4l2_planes struct for
926                  * single-planar buffers as well, for simplicity.
927                  */
928                 if (V4L2_TYPE_IS_OUTPUT(b->type))
929                         v4l2_planes[0].bytesused = b->bytesused;
930
931                 if (b->memory == V4L2_MEMORY_USERPTR) {
932                         v4l2_planes[0].m.userptr = b->m.userptr;
933                         v4l2_planes[0].length = b->length;
934                 }
935
936                 if (b->memory == V4L2_MEMORY_DMABUF)
937                         v4l2_planes[0].m.fd = b->m.fd;
938
939         }
940
941         vb->v4l2_buf.field = b->field;
942         vb->v4l2_buf.timestamp = b->timestamp;
943         vb->v4l2_buf.input = b->input;
944         vb->v4l2_buf.flags = b->flags & ~V4L2_BUFFER_STATE_FLAGS;
945
946         return 0;
947 }
948
949 /**
950  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
951  */
952 static int __qbuf_userptr(struct vb2_buffer *vb, const struct v4l2_buffer *b)
953 {
954         struct v4l2_plane planes[VIDEO_MAX_PLANES];
955         struct vb2_queue *q = vb->vb2_queue;
956         void *mem_priv;
957         unsigned int plane;
958         int ret;
959         int write = !V4L2_TYPE_IS_OUTPUT(q->type);
960
961         /* Verify and copy relevant information provided by the userspace */
962         ret = __fill_vb2_buffer(vb, b, planes);
963         if (ret)
964                 return ret;
965
966         for (plane = 0; plane < vb->num_planes; ++plane) {
967                 /* Skip the plane if already verified */
968                 if (vb->v4l2_planes[plane].m.userptr &&
969                     vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
970                     && vb->v4l2_planes[plane].length == planes[plane].length)
971                         continue;
972
973                 dprintk(3, "qbuf: userspace address for plane %d changed, "
974                                 "reacquiring memory\n", plane);
975
976                 /* Check if the provided plane buffer is large enough */
977                 if (planes[plane].length < q->plane_sizes[plane]) {
978                         ret = -EINVAL;
979                         goto err;
980                 }
981
982                 /* Release previously acquired memory if present */
983                 if (vb->planes[plane].mem_priv)
984                         call_memop(q, put_userptr, vb->planes[plane].mem_priv);
985
986                 vb->planes[plane].mem_priv = NULL;
987                 vb->v4l2_planes[plane].m.userptr = 0;
988                 vb->v4l2_planes[plane].length = 0;
989
990                 /* Acquire each plane's memory */
991                 mem_priv = call_memop(q, get_userptr, q->alloc_ctx[plane],
992                                       planes[plane].m.userptr,
993                                       planes[plane].length, write);
994                 if (IS_ERR_OR_NULL(mem_priv)) {
995                         dprintk(1, "qbuf: failed acquiring userspace "
996                                                 "memory for plane %d\n", plane);
997                         ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
998                         goto err;
999                 }
1000                 vb->planes[plane].mem_priv = mem_priv;
1001         }
1002
1003         /*
1004          * Call driver-specific initialization on the newly acquired buffer,
1005          * if provided.
1006          */
1007         ret = call_qop(q, buf_init, vb);
1008         if (ret) {
1009                 dprintk(1, "qbuf: buffer initialization failed\n");
1010                 goto err;
1011         }
1012
1013         /*
1014          * Now that everything is in order, copy relevant information
1015          * provided by userspace.
1016          */
1017         for (plane = 0; plane < vb->num_planes; ++plane)
1018                 vb->v4l2_planes[plane] = planes[plane];
1019
1020         return 0;
1021 err:
1022         /* In case of errors, release planes that were already acquired */
1023         for (plane = 0; plane < vb->num_planes; ++plane) {
1024                 if (vb->planes[plane].mem_priv)
1025                         call_memop(q, put_userptr, vb->planes[plane].mem_priv);
1026                 vb->planes[plane].mem_priv = NULL;
1027                 vb->v4l2_planes[plane].m.userptr = 0;
1028                 vb->v4l2_planes[plane].length = 0;
1029         }
1030
1031         return ret;
1032 }
1033
1034 /**
1035  * __qbuf_mmap() - handle qbuf of an MMAP buffer
1036  */
1037 static int __qbuf_mmap(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1038 {
1039         return __fill_vb2_buffer(vb, b, vb->v4l2_planes);
1040 }
1041
1042 /**
1043  * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1044  */
1045 static int __qbuf_dmabuf(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1046 {
1047         struct v4l2_plane planes[VIDEO_MAX_PLANES];
1048         struct vb2_queue *q = vb->vb2_queue;
1049         void *mem_priv;
1050         unsigned int plane;
1051         int ret;
1052         int write = !V4L2_TYPE_IS_OUTPUT(q->type);
1053
1054         /* Verify and copy relevant information provided by the userspace */
1055         ret = __fill_vb2_buffer(vb, b, planes);
1056         if (ret)
1057                 return ret;
1058
1059         for (plane = 0; plane < vb->num_planes; ++plane) {
1060                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1061
1062                 if (IS_ERR_OR_NULL(dbuf)) {
1063                         dprintk(1, "qbuf: invalid dmabuf fd for "
1064                                 "plane %d\n", plane);
1065                         ret = -EINVAL;
1066                         goto err;
1067                 }
1068
1069                 /* Skip the plane if already verified */
1070                 if (dbuf == vb->planes[plane].dbuf) {
1071                         planes[plane].length = dbuf->size;
1072                         dma_buf_put(dbuf);
1073                         continue;
1074                 }
1075
1076                 dprintk(3, "qbuf: buffer description for plane %d changed, "
1077                         "reattaching dma buf\n", plane);
1078
1079                 /* Release previously acquired memory if present */
1080                 __vb2_plane_dmabuf_put(q, &vb->planes[plane]);
1081
1082                 /* Acquire each plane's memory */
1083                 mem_priv = call_memop(q, attach_dmabuf, q->alloc_ctx[plane],
1084                         dbuf, q->plane_sizes[plane], write);
1085                 if (IS_ERR(mem_priv)) {
1086                         dprintk(1, "qbuf: failed acquiring dmabuf "
1087                                 "memory for plane %d\n", plane);
1088                         ret = PTR_ERR(mem_priv);
1089                         goto err;
1090                 }
1091
1092                 planes[plane].length = dbuf->size;
1093                 vb->planes[plane].dbuf = dbuf;
1094                 vb->planes[plane].mem_priv = mem_priv;
1095         }
1096
1097         /* TODO: This pins the buffer(s) with  dma_buf_map_attachment()).. but
1098          * really we want to do this just before the DMA, not while queueing
1099          * the buffer(s)..
1100          */
1101         for (plane = 0; plane < vb->num_planes; ++plane) {
1102                 ret = call_memop(q, map_dmabuf, vb->planes[plane].mem_priv);
1103                 if (ret) {
1104                         dprintk(1, "qbuf: failed mapping dmabuf "
1105                                 "memory for plane %d\n", plane);
1106                         goto err;
1107                 }
1108                 vb->planes[plane].dbuf_mapped = 1;
1109         }
1110
1111         /*
1112          * Call driver-specific initialization on the newly acquired buffer,
1113          * if provided.
1114          */
1115         ret = call_qop(q, buf_init, vb);
1116         if (ret) {
1117                 dprintk(1, "qbuf: buffer initialization failed\n");
1118                 goto err;
1119         }
1120
1121         /*
1122          * Now that everything is in order, copy relevant information
1123          * provided by userspace.
1124          */
1125         for (plane = 0; plane < vb->num_planes; ++plane)
1126                 vb->v4l2_planes[plane] = planes[plane];
1127
1128         return 0;
1129 err:
1130         /* In case of errors, release planes that were already acquired */
1131         __vb2_buf_dmabuf_put(vb);
1132
1133         return ret;
1134 }
1135
1136 /**
1137  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1138  */
1139 static void __enqueue_in_driver(struct vb2_buffer *vb)
1140 {
1141         struct vb2_queue *q = vb->vb2_queue;
1142         unsigned int plane;
1143
1144         vb->state = VB2_BUF_STATE_ACTIVE;
1145         atomic_inc(&q->queued_count);
1146
1147         /* sync buffers */
1148         for (plane = 0; plane < vb->num_planes; ++plane)
1149                 call_memop(q, prepare, vb->planes[plane].mem_priv);
1150
1151         q->ops->buf_queue(vb);
1152 }
1153
1154 static int __buf_prepare(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1155 {
1156         struct vb2_queue *q = vb->vb2_queue;
1157         int ret;
1158
1159         switch (q->memory) {
1160         case V4L2_MEMORY_MMAP:
1161                 ret = __qbuf_mmap(vb, b);
1162                 break;
1163         case V4L2_MEMORY_USERPTR:
1164                 ret = __qbuf_userptr(vb, b);
1165                 break;
1166         case V4L2_MEMORY_DMABUF:
1167                 ret = __qbuf_dmabuf(vb, b);
1168                 break;
1169         default:
1170                 WARN(1, "Invalid queue type\n");
1171                 ret = -EINVAL;
1172         }
1173
1174         if (!ret)
1175                 ret = call_qop(q, buf_prepare, vb);
1176         if (ret)
1177                 dprintk(1, "qbuf: buffer preparation failed: %d\n", ret);
1178         else
1179                 vb->state = VB2_BUF_STATE_PREPARED;
1180
1181         return ret;
1182 }
1183
1184 /**
1185  * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
1186  * @q:          videobuf2 queue
1187  * @b:          buffer structure passed from userspace to vidioc_prepare_buf
1188  *              handler in driver
1189  *
1190  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1191  * This function:
1192  * 1) verifies the passed buffer,
1193  * 2) calls buf_prepare callback in the driver (if provided), in which
1194  *    driver-specific buffer initialization can be performed,
1195  *
1196  * The return values from this function are intended to be directly returned
1197  * from vidioc_prepare_buf handler in driver.
1198  */
1199 int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
1200 {
1201         struct vb2_buffer *vb;
1202         int ret;
1203
1204         if (q->fileio) {
1205                 dprintk(1, "%s(): file io in progress\n", __func__);
1206                 return -EBUSY;
1207         }
1208
1209         if (b->type != q->type) {
1210                 dprintk(1, "%s(): invalid buffer type\n", __func__);
1211                 return -EINVAL;
1212         }
1213
1214         if (b->index >= q->num_buffers) {
1215                 dprintk(1, "%s(): buffer index out of range\n", __func__);
1216                 return -EINVAL;
1217         }
1218
1219         vb = q->bufs[b->index];
1220         if (NULL == vb) {
1221                 /* Should never happen */
1222                 dprintk(1, "%s(): buffer is NULL\n", __func__);
1223                 return -EINVAL;
1224         }
1225
1226         if (b->memory != q->memory) {
1227                 dprintk(1, "%s(): invalid memory type\n", __func__);
1228                 return -EINVAL;
1229         }
1230
1231         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1232                 dprintk(1, "%s(): invalid buffer state %d\n", __func__, vb->state);
1233                 return -EINVAL;
1234         }
1235
1236         ret = __buf_prepare(vb, b);
1237         if (ret < 0)
1238                 return ret;
1239
1240         __fill_v4l2_buffer(vb, b);
1241
1242         return 0;
1243 }
1244 EXPORT_SYMBOL_GPL(vb2_prepare_buf);
1245
1246 /**
1247  * vb2_qbuf() - Queue a buffer from userspace
1248  * @q:          videobuf2 queue
1249  * @b:          buffer structure passed from userspace to vidioc_qbuf handler
1250  *              in driver
1251  *
1252  * Should be called from vidioc_qbuf ioctl handler of a driver.
1253  * This function:
1254  * 1) verifies the passed buffer,
1255  * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
1256  *    which driver-specific buffer initialization can be performed,
1257  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
1258  *    callback for processing.
1259  *
1260  * The return values from this function are intended to be directly returned
1261  * from vidioc_qbuf handler in driver.
1262  */
1263 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
1264 {
1265         struct rw_semaphore *mmap_sem = NULL;
1266         struct vb2_buffer *vb;
1267         int ret = 0;
1268
1269         /*
1270          * In case of user pointer buffers vb2 allocator needs to get direct
1271          * access to userspace pages. This requires getting read access on
1272          * mmap semaphore in the current process structure. The same
1273          * semaphore is taken before calling mmap operation, while both mmap
1274          * and qbuf are called by the driver or v4l2 core with driver's lock
1275          * held. To avoid a AB-BA deadlock (mmap_sem then driver's lock in
1276          * mmap and driver's lock then mmap_sem in qbuf) the videobuf2 core
1277          * release driver's lock, takes mmap_sem and then takes again driver's
1278          * lock.
1279          *
1280          * To avoid race with other vb2 calls, which might be called after
1281          * releasing driver's lock, this operation is performed at the
1282          * beggining of qbuf processing. This way the queue status is
1283          * consistent after getting driver's lock back.
1284          */
1285         if (q->memory == V4L2_MEMORY_USERPTR) {
1286                 mmap_sem = &current->mm->mmap_sem;
1287                 call_qop(q, wait_prepare, q);
1288                 down_read(mmap_sem);
1289                 call_qop(q, wait_finish, q);
1290         }
1291
1292         if (q->fileio) {
1293                 dprintk(1, "qbuf: file io in progress\n");
1294                 ret = -EBUSY;
1295                 goto unlock;
1296         }
1297
1298         if (b->type != q->type) {
1299                 dprintk(1, "qbuf: invalid buffer type\n");
1300                 ret = -EINVAL;
1301                 goto unlock;
1302         }
1303
1304         if (b->index >= q->num_buffers) {
1305                 dprintk(1, "qbuf: buffer index out of range\n");
1306                 ret = -EINVAL;
1307                 goto unlock;
1308         }
1309
1310         vb = q->bufs[b->index];
1311         if (NULL == vb) {
1312                 /* Should never happen */
1313                 dprintk(1, "qbuf: buffer is NULL\n");
1314                 ret = -EINVAL;
1315                 goto unlock;
1316         }
1317
1318         if (b->memory != q->memory) {
1319                 dprintk(1, "qbuf: invalid memory type\n");
1320                 ret = -EINVAL;
1321                 goto unlock;
1322         }
1323
1324         switch (vb->state) {
1325         case VB2_BUF_STATE_DEQUEUED:
1326                 ret = __buf_prepare(vb, b);
1327                 if (ret)
1328                         goto unlock;
1329         case VB2_BUF_STATE_PREPARED:
1330                 break;
1331         default:
1332                 dprintk(1, "qbuf: buffer already in use\n");
1333                 ret = -EINVAL;
1334                 goto unlock;
1335         }
1336
1337         /*
1338          * Add to the queued buffers list, a buffer will stay on it until
1339          * dequeued in dqbuf.
1340          */
1341         list_add_tail(&vb->queued_entry, &q->queued_list);
1342         vb->state = VB2_BUF_STATE_QUEUED;
1343
1344         /*
1345          * If already streaming, give the buffer to driver for processing.
1346          * If not, the buffer will be given to driver on next streamon.
1347          */
1348         if (q->streaming)
1349                 __enqueue_in_driver(vb);
1350
1351         /* Fill buffer information for the userspace */
1352         __fill_v4l2_buffer(vb, b);
1353
1354         dprintk(1, "qbuf of buffer %d succeeded\n", vb->v4l2_buf.index);
1355 unlock:
1356         if (mmap_sem)
1357                 up_read(mmap_sem);
1358         return ret;
1359 }
1360 EXPORT_SYMBOL_GPL(vb2_qbuf);
1361
1362 /**
1363  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1364  * for dequeuing
1365  *
1366  * Will sleep if required for nonblocking == false.
1367  */
1368 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1369 {
1370         /*
1371          * All operations on vb_done_list are performed under done_lock
1372          * spinlock protection. However, buffers may be removed from
1373          * it and returned to userspace only while holding both driver's
1374          * lock and the done_lock spinlock. Thus we can be sure that as
1375          * long as we hold the driver's lock, the list will remain not
1376          * empty if list_empty() check succeeds.
1377          */
1378
1379         for (;;) {
1380                 int ret;
1381
1382                 if (!q->streaming) {
1383                         dprintk(1, "Streaming off, will not wait for buffers\n");
1384                         return -EINVAL;
1385                 }
1386
1387                 if (!list_empty(&q->done_list)) {
1388                         /*
1389                          * Found a buffer that we were waiting for.
1390                          */
1391                         break;
1392                 }
1393
1394                 if (nonblocking) {
1395                         dprintk(1, "Nonblocking and no buffers to dequeue, "
1396                                                                 "will not wait\n");
1397                         return -EAGAIN;
1398                 }
1399
1400                 /*
1401                  * We are streaming and blocking, wait for another buffer to
1402                  * become ready or for streamoff. Driver's lock is released to
1403                  * allow streamoff or qbuf to be called while waiting.
1404                  */
1405                 call_qop(q, wait_prepare, q);
1406
1407                 /*
1408                  * All locks have been released, it is safe to sleep now.
1409                  */
1410                 dprintk(3, "Will sleep waiting for buffers\n");
1411                 ret = wait_event_interruptible(q->done_wq,
1412                                 !list_empty(&q->done_list) || !q->streaming);
1413
1414                 /*
1415                  * We need to reevaluate both conditions again after reacquiring
1416                  * the locks or return an error if one occurred.
1417                  */
1418                 call_qop(q, wait_finish, q);
1419                 if (ret)
1420                         return ret;
1421         }
1422         return 0;
1423 }
1424
1425 /**
1426  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1427  *
1428  * Will sleep if required for nonblocking == false.
1429  */
1430 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1431                                 int nonblocking)
1432 {
1433         unsigned long flags;
1434         int ret;
1435
1436         /*
1437          * Wait for at least one buffer to become available on the done_list.
1438          */
1439         ret = __vb2_wait_for_done_vb(q, nonblocking);
1440         if (ret)
1441                 return ret;
1442
1443         /*
1444          * Driver's lock has been held since we last verified that done_list
1445          * is not empty, so no need for another list_empty(done_list) check.
1446          */
1447         spin_lock_irqsave(&q->done_lock, flags);
1448         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1449         list_del(&(*vb)->done_entry);
1450         spin_unlock_irqrestore(&q->done_lock, flags);
1451
1452         return 0;
1453 }
1454
1455 /**
1456  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
1457  * @q:          videobuf2 queue
1458  *
1459  * This function will wait until all buffers that have been given to the driver
1460  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
1461  * wait_prepare, wait_finish pair. It is intended to be called with all locks
1462  * taken, for example from stop_streaming() callback.
1463  */
1464 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1465 {
1466         if (!q->streaming) {
1467                 dprintk(1, "Streaming off, will not wait for buffers\n");
1468                 return -EINVAL;
1469         }
1470
1471         wait_event(q->done_wq, !atomic_read(&q->queued_count));
1472         return 0;
1473 }
1474 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1475
1476 /**
1477  * vb2_dqbuf() - Dequeue a buffer to the userspace
1478  * @q:          videobuf2 queue
1479  * @b:          buffer structure passed from userspace to vidioc_dqbuf handler
1480  *              in driver
1481  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
1482  *               buffers ready for dequeuing are present. Normally the driver
1483  *               would be passing (file->f_flags & O_NONBLOCK) here
1484  *
1485  * Should be called from vidioc_dqbuf ioctl handler of a driver.
1486  * This function:
1487  * 1) verifies the passed buffer,
1488  * 2) calls buf_finish callback in the driver (if provided), in which
1489  *    driver can perform any additional operations that may be required before
1490  *    returning the buffer to userspace, such as cache sync,
1491  * 3) the buffer struct members are filled with relevant information for
1492  *    the userspace.
1493  *
1494  * The return values from this function are intended to be directly returned
1495  * from vidioc_dqbuf handler in driver.
1496  */
1497 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
1498 {
1499         struct vb2_buffer *vb = NULL;
1500         int ret;
1501
1502         if (q->fileio) {
1503                 dprintk(1, "dqbuf: file io in progress\n");
1504                 return -EBUSY;
1505         }
1506
1507         if (b->type != q->type) {
1508                 dprintk(1, "dqbuf: invalid buffer type\n");
1509                 return -EINVAL;
1510         }
1511
1512         ret = __vb2_get_done_vb(q, &vb, nonblocking);
1513         if (ret < 0) {
1514                 dprintk(1, "dqbuf: error getting next done buffer\n");
1515                 return ret;
1516         }
1517
1518         ret = call_qop(q, buf_finish, vb);
1519         if (ret) {
1520                 dprintk(1, "dqbuf: buffer finish failed\n");
1521                 return ret;
1522         }
1523
1524         /* TODO: this unpins the buffer(dma_buf_unmap_attachment()).. but
1525          * really we want to do this just after DMA, not when the
1526          * buffer is dequeued..
1527          */
1528         if (q->memory == V4L2_MEMORY_DMABUF) {
1529                 unsigned int i;
1530
1531                 for (i = 0; i < vb->num_planes; ++i) {
1532                         call_memop(q, unmap_dmabuf, vb->planes[i].mem_priv);
1533                         vb->planes[i].dbuf_mapped = 0;
1534                 }
1535         }
1536
1537         switch (vb->state) {
1538         case VB2_BUF_STATE_DONE:
1539                 dprintk(3, "dqbuf: Returning done buffer\n");
1540                 break;
1541         case VB2_BUF_STATE_ERROR:
1542                 dprintk(3, "dqbuf: Returning done buffer with errors\n");
1543                 break;
1544         default:
1545                 dprintk(1, "dqbuf: Invalid buffer state\n");
1546                 return -EINVAL;
1547         }
1548
1549         /* Fill buffer information for the userspace */
1550         __fill_v4l2_buffer(vb, b);
1551         /* Remove from videobuf queue */
1552         list_del(&vb->queued_entry);
1553
1554         dprintk(1, "dqbuf of buffer %d, with state %d\n",
1555                         vb->v4l2_buf.index, vb->state);
1556
1557         vb->state = VB2_BUF_STATE_DEQUEUED;
1558         return 0;
1559 }
1560 EXPORT_SYMBOL_GPL(vb2_dqbuf);
1561
1562 /**
1563  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1564  *
1565  * Removes all queued buffers from driver's queue and all buffers queued by
1566  * userspace from videobuf's queue. Returns to state after reqbufs.
1567  */
1568 static void __vb2_queue_cancel(struct vb2_queue *q)
1569 {
1570         unsigned int i;
1571
1572         /*
1573          * Tell driver to stop all transactions and release all queued
1574          * buffers.
1575          */
1576         if (q->streaming)
1577                 call_qop(q, stop_streaming, q);
1578         q->streaming = 0;
1579
1580         /*
1581          * Remove all buffers from videobuf's list...
1582          */
1583         INIT_LIST_HEAD(&q->queued_list);
1584         /*
1585          * ...and done list; userspace will not receive any buffers it
1586          * has not already dequeued before initiating cancel.
1587          */
1588         INIT_LIST_HEAD(&q->done_list);
1589         atomic_set(&q->queued_count, 0);
1590         wake_up_all(&q->done_wq);
1591
1592         /*
1593          * Reinitialize all buffers for next use.
1594          */
1595         for (i = 0; i < q->num_buffers; ++i)
1596                 q->bufs[i]->state = VB2_BUF_STATE_DEQUEUED;
1597 }
1598
1599 /**
1600  * vb2_streamon - start streaming
1601  * @q:          videobuf2 queue
1602  * @type:       type argument passed from userspace to vidioc_streamon handler
1603  *
1604  * Should be called from vidioc_streamon handler of a driver.
1605  * This function:
1606  * 1) verifies current state
1607  * 2) passes any previously queued buffers to the driver and starts streaming
1608  *
1609  * The return values from this function are intended to be directly returned
1610  * from vidioc_streamon handler in the driver.
1611  */
1612 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
1613 {
1614         struct vb2_buffer *vb;
1615         int ret;
1616
1617         if (q->fileio) {
1618                 dprintk(1, "streamon: file io in progress\n");
1619                 return -EBUSY;
1620         }
1621
1622         if (type != q->type) {
1623                 dprintk(1, "streamon: invalid stream type\n");
1624                 return -EINVAL;
1625         }
1626
1627         if (q->streaming) {
1628                 dprintk(1, "streamon: already streaming\n");
1629                 return -EBUSY;
1630         }
1631
1632         /*
1633          * If any buffers were queued before streamon,
1634          * we can now pass them to driver for processing.
1635          */
1636         list_for_each_entry(vb, &q->queued_list, queued_entry)
1637                 __enqueue_in_driver(vb);
1638
1639         /*
1640          * Let driver notice that streaming state has been enabled.
1641          */
1642         ret = call_qop(q, start_streaming, q, atomic_read(&q->queued_count));
1643         if (ret) {
1644                 dprintk(1, "streamon: driver refused to start streaming\n");
1645                 __vb2_queue_cancel(q);
1646                 return ret;
1647         }
1648
1649         q->streaming = 1;
1650
1651         dprintk(3, "Streamon successful\n");
1652         return 0;
1653 }
1654 EXPORT_SYMBOL_GPL(vb2_streamon);
1655
1656
1657 /**
1658  * vb2_streamoff - stop streaming
1659  * @q:          videobuf2 queue
1660  * @type:       type argument passed from userspace to vidioc_streamoff handler
1661  *
1662  * Should be called from vidioc_streamoff handler of a driver.
1663  * This function:
1664  * 1) verifies current state,
1665  * 2) stop streaming and dequeues any queued buffers, including those previously
1666  *    passed to the driver (after waiting for the driver to finish).
1667  *
1668  * This call can be used for pausing playback.
1669  * The return values from this function are intended to be directly returned
1670  * from vidioc_streamoff handler in the driver
1671  */
1672 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
1673 {
1674         if (q->fileio) {
1675                 dprintk(1, "streamoff: file io in progress\n");
1676                 return -EBUSY;
1677         }
1678
1679         if (type != q->type) {
1680                 dprintk(1, "streamoff: invalid stream type\n");
1681                 return -EINVAL;
1682         }
1683
1684         if (!q->streaming) {
1685                 dprintk(1, "streamoff: not streaming\n");
1686                 return -EINVAL;
1687         }
1688
1689         /*
1690          * Cancel will pause streaming and remove all buffers from the driver
1691          * and videobuf, effectively returning control over them to userspace.
1692          */
1693         __vb2_queue_cancel(q);
1694
1695         dprintk(3, "Streamoff successful\n");
1696         return 0;
1697 }
1698 EXPORT_SYMBOL_GPL(vb2_streamoff);
1699
1700 /**
1701  * __find_plane_by_offset() - find plane associated with the given offset off
1702  */
1703 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1704                         unsigned int *_buffer, unsigned int *_plane)
1705 {
1706         struct vb2_buffer *vb;
1707         unsigned int buffer, plane;
1708
1709         /*
1710          * Go over all buffers and their planes, comparing the given offset
1711          * with an offset assigned to each plane. If a match is found,
1712          * return its buffer and plane numbers.
1713          */
1714         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1715                 vb = q->bufs[buffer];
1716
1717                 for (plane = 0; plane < vb->num_planes; ++plane) {
1718                         if (vb->v4l2_planes[plane].m.mem_offset == off) {
1719                                 *_buffer = buffer;
1720                                 *_plane = plane;
1721                                 return 0;
1722                         }
1723                 }
1724         }
1725
1726         return -EINVAL;
1727 }
1728
1729 /**
1730  * vb2_expbuf() - Export a buffer as a file descriptor
1731  * @q:          videobuf2 queue
1732  * @eb:         export buffer structure passed from userspace to vidioc_expbuf
1733  *              handler in driver
1734  *
1735  * The return values from this function are intended to be directly returned
1736  * from vidioc_expbuf handler in driver.
1737  */
1738 int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
1739 {
1740         struct vb2_buffer *vb = NULL;
1741         struct vb2_plane *vb_plane;
1742         unsigned int buffer, plane;
1743         int ret;
1744         struct dma_buf *dbuf;
1745
1746         if (q->memory != V4L2_MEMORY_MMAP) {
1747                 dprintk(1, "Queue is not currently set up for mmap\n");
1748                 return -EINVAL;
1749         }
1750
1751         if (!q->mem_ops->get_dmabuf) {
1752                 dprintk(1, "Queue does not support DMA buffer exporting\n");
1753                 return -EINVAL;
1754         }
1755
1756         if (eb->flags & ~O_CLOEXEC) {
1757                 dprintk(1, "Queue does support only O_CLOEXEC flag\n");
1758                 return -EINVAL;
1759         }
1760
1761         /*
1762          * Find the plane corresponding to the offset passed by userspace.
1763          */
1764         ret = __find_plane_by_offset(q, eb->mem_offset, &buffer, &plane);
1765         if (ret) {
1766                 dprintk(1, "invalid offset %u\n", eb->mem_offset);
1767                 return ret;
1768         }
1769
1770         vb = q->bufs[buffer];
1771         vb_plane = &vb->planes[plane];
1772
1773         dbuf = call_memop(q, get_dmabuf, vb_plane->mem_priv);
1774         if (IS_ERR_OR_NULL(dbuf)) {
1775                 dprintk(1, "Failed to export buffer %d, plane %d\n",
1776                         buffer, plane);
1777                 return -EINVAL;
1778         }
1779
1780         ret = dma_buf_fd(dbuf, eb->flags);
1781         if (ret < 0) {
1782                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1783                         buffer, plane, ret);
1784                 dma_buf_put(dbuf);
1785                 return ret;
1786         }
1787
1788         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1789                 buffer, plane, ret);
1790         eb->fd = ret;
1791
1792         return 0;
1793 }
1794 EXPORT_SYMBOL_GPL(vb2_expbuf);
1795
1796 /**
1797  * vb2_mmap() - map video buffers into application address space
1798  * @q:          videobuf2 queue
1799  * @vma:        vma passed to the mmap file operation handler in the driver
1800  *
1801  * Should be called from mmap file operation handler of a driver.
1802  * This function maps one plane of one of the available video buffers to
1803  * userspace. To map whole video memory allocated on reqbufs, this function
1804  * has to be called once per each plane per each buffer previously allocated.
1805  *
1806  * When the userspace application calls mmap, it passes to it an offset returned
1807  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
1808  * a "cookie", which is then used to identify the plane to be mapped.
1809  * This function finds a plane with a matching offset and a mapping is performed
1810  * by the means of a provided memory operation.
1811  *
1812  * The return values from this function are intended to be directly returned
1813  * from the mmap handler in driver.
1814  */
1815 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1816 {
1817         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1818         struct vb2_buffer *vb;
1819         unsigned int buffer, plane;
1820         int ret;
1821
1822         if (q->memory != V4L2_MEMORY_MMAP) {
1823                 dprintk(1, "Queue is not currently set up for mmap\n");
1824                 return -EINVAL;
1825         }
1826
1827         /*
1828          * Check memory area access mode.
1829          */
1830         if (!(vma->vm_flags & VM_SHARED)) {
1831                 dprintk(1, "Invalid vma flags, VM_SHARED needed\n");
1832                 return -EINVAL;
1833         }
1834         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1835                 if (!(vma->vm_flags & VM_WRITE)) {
1836                         dprintk(1, "Invalid vma flags, VM_WRITE needed\n");
1837                         return -EINVAL;
1838                 }
1839         } else {
1840                 if (!(vma->vm_flags & VM_READ)) {
1841                         dprintk(1, "Invalid vma flags, VM_READ needed\n");
1842                         return -EINVAL;
1843                 }
1844         }
1845
1846         /*
1847          * Find the plane corresponding to the offset passed by userspace.
1848          */
1849         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1850         if (ret)
1851                 return ret;
1852
1853         vb = q->bufs[buffer];
1854
1855         ret = call_memop(q, mmap, vb->planes[plane].mem_priv, vma);
1856         if (ret)
1857                 return ret;
1858
1859         dprintk(3, "Buffer %d, plane %d successfully mapped\n", buffer, plane);
1860         return 0;
1861 }
1862 EXPORT_SYMBOL_GPL(vb2_mmap);
1863
1864 #ifndef CONFIG_MMU
1865 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
1866                                     unsigned long addr,
1867                                     unsigned long len,
1868                                     unsigned long pgoff,
1869                                     unsigned long flags)
1870 {
1871         unsigned long off = pgoff << PAGE_SHIFT;
1872         struct vb2_buffer *vb;
1873         unsigned int buffer, plane;
1874         int ret;
1875
1876         if (q->memory != V4L2_MEMORY_MMAP) {
1877                 dprintk(1, "Queue is not currently set up for mmap\n");
1878                 return -EINVAL;
1879         }
1880
1881         /*
1882          * Find the plane corresponding to the offset passed by userspace.
1883          */
1884         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1885         if (ret)
1886                 return ret;
1887
1888         vb = q->bufs[buffer];
1889
1890         return (unsigned long)vb2_plane_vaddr(vb, plane);
1891 }
1892 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
1893 #endif
1894
1895 static int __vb2_init_fileio(struct vb2_queue *q, int read);
1896 static int __vb2_cleanup_fileio(struct vb2_queue *q);
1897
1898 /**
1899  * vb2_poll() - implements poll userspace operation
1900  * @q:          videobuf2 queue
1901  * @file:       file argument passed to the poll file operation handler
1902  * @wait:       wait argument passed to the poll file operation handler
1903  *
1904  * This function implements poll file operation handler for a driver.
1905  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
1906  * be informed that the file descriptor of a video device is available for
1907  * reading.
1908  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
1909  * will be reported as available for writing.
1910  *
1911  * The return values from this function are intended to be directly returned
1912  * from poll handler in driver.
1913  */
1914 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
1915 {
1916         unsigned long flags;
1917         unsigned int ret;
1918         struct vb2_buffer *vb = NULL;
1919
1920         /*
1921          * Start file I/O emulator only if streaming API has not been used yet.
1922          */
1923         if (q->num_buffers == 0 && q->fileio == NULL) {
1924                 if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ)) {
1925                         ret = __vb2_init_fileio(q, 1);
1926                         if (ret)
1927                                 return POLLERR;
1928                 }
1929                 if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE)) {
1930                         ret = __vb2_init_fileio(q, 0);
1931                         if (ret)
1932                                 return POLLERR;
1933                         /*
1934                          * Write to OUTPUT queue can be done immediately.
1935                          */
1936                         return POLLOUT | POLLWRNORM;
1937                 }
1938         }
1939
1940         /*
1941          * There is nothing to wait for if no buffers have already been queued.
1942          */
1943         if (list_empty(&q->queued_list))
1944                 return POLLERR;
1945
1946         poll_wait(file, &q->done_wq, wait);
1947
1948         /*
1949          * Take first buffer available for dequeuing.
1950          */
1951         spin_lock_irqsave(&q->done_lock, flags);
1952         if (!list_empty(&q->done_list))
1953                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
1954                                         done_entry);
1955         spin_unlock_irqrestore(&q->done_lock, flags);
1956
1957         if (vb && (vb->state == VB2_BUF_STATE_DONE
1958                         || vb->state == VB2_BUF_STATE_ERROR)) {
1959                 return (V4L2_TYPE_IS_OUTPUT(q->type)) ? POLLOUT | POLLWRNORM :
1960                         POLLIN | POLLRDNORM;
1961         }
1962         return 0;
1963 }
1964 EXPORT_SYMBOL_GPL(vb2_poll);
1965
1966 /**
1967  * vb2_queue_init() - initialize a videobuf2 queue
1968  * @q:          videobuf2 queue; this structure should be allocated in driver
1969  *
1970  * The vb2_queue structure should be allocated by the driver. The driver is
1971  * responsible of clearing it's content and setting initial values for some
1972  * required entries before calling this function.
1973  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
1974  * to the struct vb2_queue description in include/media/videobuf2-core.h
1975  * for more information.
1976  */
1977 int vb2_queue_init(struct vb2_queue *q)
1978 {
1979         BUG_ON(!q);
1980         BUG_ON(!q->ops);
1981         BUG_ON(!q->mem_ops);
1982         BUG_ON(!q->type);
1983         BUG_ON(!q->io_modes);
1984
1985         BUG_ON(!q->ops->queue_setup);
1986         BUG_ON(!q->ops->buf_queue);
1987
1988         INIT_LIST_HEAD(&q->queued_list);
1989         INIT_LIST_HEAD(&q->done_list);
1990         spin_lock_init(&q->done_lock);
1991         init_waitqueue_head(&q->done_wq);
1992
1993         if (q->buf_struct_size == 0)
1994                 q->buf_struct_size = sizeof(struct vb2_buffer);
1995
1996         return 0;
1997 }
1998 EXPORT_SYMBOL_GPL(vb2_queue_init);
1999
2000 /**
2001  * vb2_queue_release() - stop streaming, release the queue and free memory
2002  * @q:          videobuf2 queue
2003  *
2004  * This function stops streaming and performs necessary clean ups, including
2005  * freeing video buffer memory. The driver is responsible for freeing
2006  * the vb2_queue structure itself.
2007  */
2008 void vb2_queue_release(struct vb2_queue *q)
2009 {
2010         __vb2_cleanup_fileio(q);
2011         __vb2_queue_cancel(q);
2012         __vb2_queue_free(q, q->num_buffers);
2013 }
2014 EXPORT_SYMBOL_GPL(vb2_queue_release);
2015
2016 /**
2017  * struct vb2_fileio_buf - buffer context used by file io emulator
2018  *
2019  * vb2 provides a compatibility layer and emulator of file io (read and
2020  * write) calls on top of streaming API. This structure is used for
2021  * tracking context related to the buffers.
2022  */
2023 struct vb2_fileio_buf {
2024         void *vaddr;
2025         unsigned int size;
2026         unsigned int pos;
2027         unsigned int queued:1;
2028 };
2029
2030 /**
2031  * struct vb2_fileio_data - queue context used by file io emulator
2032  *
2033  * vb2 provides a compatibility layer and emulator of file io (read and
2034  * write) calls on top of streaming API. For proper operation it required
2035  * this structure to save the driver state between each call of the read
2036  * or write function.
2037  */
2038 struct vb2_fileio_data {
2039         struct v4l2_requestbuffers req;
2040         struct v4l2_buffer b;
2041         struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
2042         unsigned int index;
2043         unsigned int q_count;
2044         unsigned int dq_count;
2045         unsigned int flags;
2046 };
2047
2048 /**
2049  * __vb2_init_fileio() - initialize file io emulator
2050  * @q:          videobuf2 queue
2051  * @read:       mode selector (1 means read, 0 means write)
2052  */
2053 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2054 {
2055         struct vb2_fileio_data *fileio;
2056         int i, ret;
2057         unsigned int count = 0;
2058
2059         /*
2060          * Sanity check
2061          */
2062         if ((read && !(q->io_modes & VB2_READ)) ||
2063            (!read && !(q->io_modes & VB2_WRITE)))
2064                 BUG();
2065
2066         /*
2067          * Check if device supports mapping buffers to kernel virtual space.
2068          */
2069         if (!q->mem_ops->vaddr)
2070                 return -EBUSY;
2071
2072         /*
2073          * Check if streaming api has not been already activated.
2074          */
2075         if (q->streaming || q->num_buffers > 0)
2076                 return -EBUSY;
2077
2078         /*
2079          * Start with count 1, driver can increase it in queue_setup()
2080          */
2081         count = 1;
2082
2083         dprintk(3, "setting up file io: mode %s, count %d, flags %08x\n",
2084                 (read) ? "read" : "write", count, q->io_flags);
2085
2086         fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
2087         if (fileio == NULL)
2088                 return -ENOMEM;
2089
2090         fileio->flags = q->io_flags;
2091
2092         /*
2093          * Request buffers and use MMAP type to force driver
2094          * to allocate buffers by itself.
2095          */
2096         fileio->req.count = count;
2097         fileio->req.memory = V4L2_MEMORY_MMAP;
2098         fileio->req.type = q->type;
2099         ret = vb2_reqbufs(q, &fileio->req);
2100         if (ret)
2101                 goto err_kfree;
2102
2103         /*
2104          * Check if plane_count is correct
2105          * (multiplane buffers are not supported).
2106          */
2107         if (q->bufs[0]->num_planes != 1) {
2108                 fileio->req.count = 0;
2109                 ret = -EBUSY;
2110                 goto err_reqbufs;
2111         }
2112
2113         /*
2114          * Get kernel address of each buffer.
2115          */
2116         for (i = 0; i < q->num_buffers; i++) {
2117                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2118                 if (fileio->bufs[i].vaddr == NULL)
2119                         goto err_reqbufs;
2120                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2121         }
2122
2123         /*
2124          * Read mode requires pre queuing of all buffers.
2125          */
2126         if (read) {
2127                 /*
2128                  * Queue all buffers.
2129                  */
2130                 for (i = 0; i < q->num_buffers; i++) {
2131                         struct v4l2_buffer *b = &fileio->b;
2132                         memset(b, 0, sizeof(*b));
2133                         b->type = q->type;
2134                         b->memory = q->memory;
2135                         b->index = i;
2136                         ret = vb2_qbuf(q, b);
2137                         if (ret)
2138                                 goto err_reqbufs;
2139                         fileio->bufs[i].queued = 1;
2140                 }
2141
2142                 /*
2143                  * Start streaming.
2144                  */
2145                 ret = vb2_streamon(q, q->type);
2146                 if (ret)
2147                         goto err_reqbufs;
2148         }
2149
2150         q->fileio = fileio;
2151
2152         return ret;
2153
2154 err_reqbufs:
2155         vb2_reqbufs(q, &fileio->req);
2156
2157 err_kfree:
2158         kfree(fileio);
2159         return ret;
2160 }
2161
2162 /**
2163  * __vb2_cleanup_fileio() - free resourced used by file io emulator
2164  * @q:          videobuf2 queue
2165  */
2166 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2167 {
2168         struct vb2_fileio_data *fileio = q->fileio;
2169
2170         if (fileio) {
2171                 /*
2172                  * Hack fileio context to enable direct calls to vb2 ioctl
2173                  * interface.
2174                  */
2175                 q->fileio = NULL;
2176
2177                 vb2_streamoff(q, q->type);
2178                 fileio->req.count = 0;
2179                 vb2_reqbufs(q, &fileio->req);
2180                 kfree(fileio);
2181                 dprintk(3, "file io emulator closed\n");
2182         }
2183         return 0;
2184 }
2185
2186 /**
2187  * __vb2_perform_fileio() - perform a single file io (read or write) operation
2188  * @q:          videobuf2 queue
2189  * @data:       pointed to target userspace buffer
2190  * @count:      number of bytes to read or write
2191  * @ppos:       file handle position tracking pointer
2192  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
2193  * @read:       access mode selector (1 means read, 0 means write)
2194  */
2195 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2196                 loff_t *ppos, int nonblock, int read)
2197 {
2198         struct vb2_fileio_data *fileio;
2199         struct vb2_fileio_buf *buf;
2200         int ret, index;
2201
2202         dprintk(3, "file io: mode %s, offset %ld, count %zd, %sblocking\n",
2203                 read ? "read" : "write", (long)*ppos, count,
2204                 nonblock ? "non" : "");
2205
2206         if (!data)
2207                 return -EINVAL;
2208
2209         /*
2210          * Initialize emulator on first call.
2211          */
2212         if (!q->fileio) {
2213                 ret = __vb2_init_fileio(q, read);
2214                 dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2215                 if (ret)
2216                         return ret;
2217         }
2218         fileio = q->fileio;
2219
2220         /*
2221          * Hack fileio context to enable direct calls to vb2 ioctl interface.
2222          * The pointer will be restored before returning from this function.
2223          */
2224         q->fileio = NULL;
2225
2226         index = fileio->index;
2227         buf = &fileio->bufs[index];
2228
2229         /*
2230          * Check if we need to dequeue the buffer.
2231          */
2232         if (buf->queued) {
2233                 struct vb2_buffer *vb;
2234
2235                 /*
2236                  * Call vb2_dqbuf to get buffer back.
2237                  */
2238                 memset(&fileio->b, 0, sizeof(fileio->b));
2239                 fileio->b.type = q->type;
2240                 fileio->b.memory = q->memory;
2241                 fileio->b.index = index;
2242                 ret = vb2_dqbuf(q, &fileio->b, nonblock);
2243                 dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2244                 if (ret)
2245                         goto end;
2246                 fileio->dq_count += 1;
2247
2248                 /*
2249                  * Get number of bytes filled by the driver
2250                  */
2251                 vb = q->bufs[index];
2252                 buf->size = vb2_get_plane_payload(vb, 0);
2253                 buf->queued = 0;
2254         }
2255
2256         /*
2257          * Limit count on last few bytes of the buffer.
2258          */
2259         if (buf->pos + count > buf->size) {
2260                 count = buf->size - buf->pos;
2261                 dprintk(5, "reducing read count: %zd\n", count);
2262         }
2263
2264         /*
2265          * Transfer data to userspace.
2266          */
2267         dprintk(3, "file io: copying %zd bytes - buffer %d, offset %u\n",
2268                 count, index, buf->pos);
2269         if (read)
2270                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2271         else
2272                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2273         if (ret) {
2274                 dprintk(3, "file io: error copying data\n");
2275                 ret = -EFAULT;
2276                 goto end;
2277         }
2278
2279         /*
2280          * Update counters.
2281          */
2282         buf->pos += count;
2283         *ppos += count;
2284
2285         /*
2286          * Queue next buffer if required.
2287          */
2288         if (buf->pos == buf->size ||
2289            (!read && (fileio->flags & VB2_FILEIO_WRITE_IMMEDIATELY))) {
2290                 /*
2291                  * Check if this is the last buffer to read.
2292                  */
2293                 if (read && (fileio->flags & VB2_FILEIO_READ_ONCE) &&
2294                     fileio->dq_count == 1) {
2295                         dprintk(3, "file io: read limit reached\n");
2296                         /*
2297                          * Restore fileio pointer and release the context.
2298                          */
2299                         q->fileio = fileio;
2300                         return __vb2_cleanup_fileio(q);
2301                 }
2302
2303                 /*
2304                  * Call vb2_qbuf and give buffer to the driver.
2305                  */
2306                 memset(&fileio->b, 0, sizeof(fileio->b));
2307                 fileio->b.type = q->type;
2308                 fileio->b.memory = q->memory;
2309                 fileio->b.index = index;
2310                 fileio->b.bytesused = buf->pos;
2311                 ret = vb2_qbuf(q, &fileio->b);
2312                 dprintk(5, "file io: vb2_dbuf result: %d\n", ret);
2313                 if (ret)
2314                         goto end;
2315
2316                 /*
2317                  * Buffer has been queued, update the status
2318                  */
2319                 buf->pos = 0;
2320                 buf->queued = 1;
2321                 buf->size = q->bufs[0]->v4l2_planes[0].length;
2322                 fileio->q_count += 1;
2323
2324                 /*
2325                  * Switch to the next buffer
2326                  */
2327                 fileio->index = (index + 1) % q->num_buffers;
2328
2329                 /*
2330                  * Start streaming if required.
2331                  */
2332                 if (!read && !q->streaming) {
2333                         ret = vb2_streamon(q, q->type);
2334                         if (ret)
2335                                 goto end;
2336                 }
2337         }
2338
2339         /*
2340          * Return proper number of bytes processed.
2341          */
2342         if (ret == 0)
2343                 ret = count;
2344 end:
2345         /*
2346          * Restore the fileio context and block vb2 ioctl interface.
2347          */
2348         q->fileio = fileio;
2349         return ret;
2350 }
2351
2352 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2353                 loff_t *ppos, int nonblocking)
2354 {
2355         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2356 }
2357 EXPORT_SYMBOL_GPL(vb2_read);
2358
2359 size_t vb2_write(struct vb2_queue *q, char __user *data, size_t count,
2360                 loff_t *ppos, int nonblocking)
2361 {
2362         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 0);
2363 }
2364 EXPORT_SYMBOL_GPL(vb2_write);
2365
2366 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
2367 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2368 MODULE_LICENSE("GPL");