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