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