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