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