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