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