Merge branch 'syscore' of git://git.kernel.org/pub/scm/linux/kernel/git/rafael/suspen...
[pandora-kernel.git] / drivers / media / video / 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/videobuf2-core.h>
23
24 static int debug;
25 module_param(debug, int, 0644);
26
27 #define dprintk(level, fmt, arg...)                                     \
28         do {                                                            \
29                 if (debug >= level)                                     \
30                         printk(KERN_DEBUG "vb2: " fmt, ## arg);         \
31         } while (0)
32
33 #define call_memop(q, plane, op, args...)                               \
34         (((q)->mem_ops->op) ?                                           \
35                 ((q)->mem_ops->op(args)) : 0)
36
37 #define call_qop(q, op, args...)                                        \
38         (((q)->ops->op) ? ((q)->ops->op(args)) : 0)
39
40 /**
41  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
42  */
43 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb,
44                                 unsigned long *plane_sizes)
45 {
46         struct vb2_queue *q = vb->vb2_queue;
47         void *mem_priv;
48         int plane;
49
50         /* Allocate memory for all planes in this buffer */
51         for (plane = 0; plane < vb->num_planes; ++plane) {
52                 mem_priv = call_memop(q, plane, alloc, q->alloc_ctx[plane],
53                                         plane_sizes[plane]);
54                 if (!mem_priv)
55                         goto free;
56
57                 /* Associate allocator private data with this plane */
58                 vb->planes[plane].mem_priv = mem_priv;
59                 vb->v4l2_planes[plane].length = plane_sizes[plane];
60         }
61
62         return 0;
63 free:
64         /* Free already allocated memory if one of the allocations failed */
65         for (; plane > 0; --plane)
66                 call_memop(q, plane, put, vb->planes[plane - 1].mem_priv);
67
68         return -ENOMEM;
69 }
70
71 /**
72  * __vb2_buf_mem_free() - free memory of the given buffer
73  */
74 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
75 {
76         struct vb2_queue *q = vb->vb2_queue;
77         unsigned int plane;
78
79         for (plane = 0; plane < vb->num_planes; ++plane) {
80                 call_memop(q, plane, put, vb->planes[plane].mem_priv);
81                 vb->planes[plane].mem_priv = NULL;
82                 dprintk(3, "Freed plane %d of buffer %d\n",
83                                 plane, vb->v4l2_buf.index);
84         }
85 }
86
87 /**
88  * __vb2_buf_userptr_put() - release userspace memory associated with
89  * a USERPTR buffer
90  */
91 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
92 {
93         struct vb2_queue *q = vb->vb2_queue;
94         unsigned int plane;
95
96         for (plane = 0; plane < vb->num_planes; ++plane) {
97                 void *mem_priv = vb->planes[plane].mem_priv;
98
99                 if (mem_priv) {
100                         call_memop(q, plane, put_userptr, mem_priv);
101                         vb->planes[plane].mem_priv = NULL;
102                 }
103         }
104 }
105
106 /**
107  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
108  * every buffer on the queue
109  */
110 static void __setup_offsets(struct vb2_queue *q)
111 {
112         unsigned int buffer, plane;
113         struct vb2_buffer *vb;
114         unsigned long off = 0;
115
116         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
117                 vb = q->bufs[buffer];
118                 if (!vb)
119                         continue;
120
121                 for (plane = 0; plane < vb->num_planes; ++plane) {
122                         vb->v4l2_planes[plane].m.mem_offset = off;
123
124                         dprintk(3, "Buffer %d, plane %d offset 0x%08lx\n",
125                                         buffer, plane, off);
126
127                         off += vb->v4l2_planes[plane].length;
128                         off = PAGE_ALIGN(off);
129                 }
130         }
131 }
132
133 /**
134  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
135  * video buffer memory for all buffers/planes on the queue and initializes the
136  * queue
137  *
138  * Returns the number of buffers successfully allocated.
139  */
140 static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
141                              unsigned int num_buffers, unsigned int num_planes,
142                              unsigned long plane_sizes[])
143 {
144         unsigned int buffer;
145         struct vb2_buffer *vb;
146         int ret;
147
148         for (buffer = 0; buffer < num_buffers; ++buffer) {
149                 /* Allocate videobuf buffer structures */
150                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
151                 if (!vb) {
152                         dprintk(1, "Memory alloc for buffer struct failed\n");
153                         break;
154                 }
155
156                 /* Length stores number of planes for multiplanar buffers */
157                 if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
158                         vb->v4l2_buf.length = num_planes;
159
160                 vb->state = VB2_BUF_STATE_DEQUEUED;
161                 vb->vb2_queue = q;
162                 vb->num_planes = num_planes;
163                 vb->v4l2_buf.index = buffer;
164                 vb->v4l2_buf.type = q->type;
165                 vb->v4l2_buf.memory = memory;
166
167                 /* Allocate video buffer memory for the MMAP type */
168                 if (memory == V4L2_MEMORY_MMAP) {
169                         ret = __vb2_buf_mem_alloc(vb, plane_sizes);
170                         if (ret) {
171                                 dprintk(1, "Failed allocating memory for "
172                                                 "buffer %d\n", buffer);
173                                 kfree(vb);
174                                 break;
175                         }
176                         /*
177                          * Call the driver-provided buffer initialization
178                          * callback, if given. An error in initialization
179                          * results in queue setup failure.
180                          */
181                         ret = call_qop(q, buf_init, vb);
182                         if (ret) {
183                                 dprintk(1, "Buffer %d %p initialization"
184                                         " failed\n", buffer, vb);
185                                 __vb2_buf_mem_free(vb);
186                                 kfree(vb);
187                                 break;
188                         }
189                 }
190
191                 q->bufs[buffer] = vb;
192         }
193
194         q->num_buffers = buffer;
195
196         __setup_offsets(q);
197
198         dprintk(1, "Allocated %d buffers, %d plane(s) each\n",
199                         q->num_buffers, num_planes);
200
201         return buffer;
202 }
203
204 /**
205  * __vb2_free_mem() - release all video buffer memory for a given queue
206  */
207 static void __vb2_free_mem(struct vb2_queue *q)
208 {
209         unsigned int buffer;
210         struct vb2_buffer *vb;
211
212         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
213                 vb = q->bufs[buffer];
214                 if (!vb)
215                         continue;
216
217                 /* Free MMAP buffers or release USERPTR buffers */
218                 if (q->memory == V4L2_MEMORY_MMAP)
219                         __vb2_buf_mem_free(vb);
220                 else
221                         __vb2_buf_userptr_put(vb);
222         }
223 }
224
225 /**
226  * __vb2_queue_free() - free the queue - video memory and related information
227  * and return the queue to an uninitialized state. Might be called even if the
228  * queue has already been freed.
229  */
230 static void __vb2_queue_free(struct vb2_queue *q)
231 {
232         unsigned int buffer;
233
234         /* Call driver-provided cleanup function for each buffer, if provided */
235         if (q->ops->buf_cleanup) {
236                 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
237                         if (NULL == q->bufs[buffer])
238                                 continue;
239                         q->ops->buf_cleanup(q->bufs[buffer]);
240                 }
241         }
242
243         /* Release video buffer memory */
244         __vb2_free_mem(q);
245
246         /* Free videobuf buffers */
247         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
248                 kfree(q->bufs[buffer]);
249                 q->bufs[buffer] = NULL;
250         }
251
252         q->num_buffers = 0;
253         q->memory = 0;
254 }
255
256 /**
257  * __verify_planes_array() - verify that the planes array passed in struct
258  * v4l2_buffer from userspace can be safely used
259  */
260 static int __verify_planes_array(struct vb2_buffer *vb, struct v4l2_buffer *b)
261 {
262         /* Is memory for copying plane information present? */
263         if (NULL == b->m.planes) {
264                 dprintk(1, "Multi-planar buffer passed but "
265                            "planes array not provided\n");
266                 return -EINVAL;
267         }
268
269         if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
270                 dprintk(1, "Incorrect planes array length, "
271                            "expected %d, got %d\n", vb->num_planes, b->length);
272                 return -EINVAL;
273         }
274
275         return 0;
276 }
277
278 /**
279  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
280  * returned to userspace
281  */
282 static int __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
283 {
284         struct vb2_queue *q = vb->vb2_queue;
285         int ret = 0;
286
287         /* Copy back data such as timestamp, input, etc. */
288         memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
289         b->input = vb->v4l2_buf.input;
290         b->reserved = vb->v4l2_buf.reserved;
291
292         if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
293                 ret = __verify_planes_array(vb, b);
294                 if (ret)
295                         return ret;
296
297                 /*
298                  * Fill in plane-related data if userspace provided an array
299                  * for it. The memory and size is verified above.
300                  */
301                 memcpy(b->m.planes, vb->v4l2_planes,
302                         b->length * sizeof(struct v4l2_plane));
303         } else {
304                 /*
305                  * We use length and offset in v4l2_planes array even for
306                  * single-planar buffers, but userspace does not.
307                  */
308                 b->length = vb->v4l2_planes[0].length;
309                 b->bytesused = vb->v4l2_planes[0].bytesused;
310                 if (q->memory == V4L2_MEMORY_MMAP)
311                         b->m.offset = vb->v4l2_planes[0].m.mem_offset;
312                 else if (q->memory == V4L2_MEMORY_USERPTR)
313                         b->m.userptr = vb->v4l2_planes[0].m.userptr;
314         }
315
316         b->flags = 0;
317
318         switch (vb->state) {
319         case VB2_BUF_STATE_QUEUED:
320         case VB2_BUF_STATE_ACTIVE:
321                 b->flags |= V4L2_BUF_FLAG_QUEUED;
322                 break;
323         case VB2_BUF_STATE_ERROR:
324                 b->flags |= V4L2_BUF_FLAG_ERROR;
325                 /* fall through */
326         case VB2_BUF_STATE_DONE:
327                 b->flags |= V4L2_BUF_FLAG_DONE;
328                 break;
329         case VB2_BUF_STATE_DEQUEUED:
330                 /* nothing */
331                 break;
332         }
333
334         if (vb->num_planes_mapped == vb->num_planes)
335                 b->flags |= V4L2_BUF_FLAG_MAPPED;
336
337         return ret;
338 }
339
340 /**
341  * vb2_querybuf() - query video buffer information
342  * @q:          videobuf queue
343  * @b:          buffer struct passed from userspace to vidioc_querybuf handler
344  *              in driver
345  *
346  * Should be called from vidioc_querybuf ioctl handler in driver.
347  * This function will verify the passed v4l2_buffer structure and fill the
348  * relevant information for the userspace.
349  *
350  * The return values from this function are intended to be directly returned
351  * from vidioc_querybuf handler in driver.
352  */
353 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
354 {
355         struct vb2_buffer *vb;
356
357         if (b->type != q->type) {
358                 dprintk(1, "querybuf: wrong buffer type\n");
359                 return -EINVAL;
360         }
361
362         if (b->index >= q->num_buffers) {
363                 dprintk(1, "querybuf: buffer index out of range\n");
364                 return -EINVAL;
365         }
366         vb = q->bufs[b->index];
367
368         return __fill_v4l2_buffer(vb, b);
369 }
370 EXPORT_SYMBOL(vb2_querybuf);
371
372 /**
373  * __verify_userptr_ops() - verify that all memory operations required for
374  * USERPTR queue type have been provided
375  */
376 static int __verify_userptr_ops(struct vb2_queue *q)
377 {
378         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
379             !q->mem_ops->put_userptr)
380                 return -EINVAL;
381
382         return 0;
383 }
384
385 /**
386  * __verify_mmap_ops() - verify that all memory operations required for
387  * MMAP queue type have been provided
388  */
389 static int __verify_mmap_ops(struct vb2_queue *q)
390 {
391         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
392             !q->mem_ops->put || !q->mem_ops->mmap)
393                 return -EINVAL;
394
395         return 0;
396 }
397
398 /**
399  * __buffers_in_use() - return true if any buffers on the queue are in use and
400  * the queue cannot be freed (by the means of REQBUFS(0)) call
401  */
402 static bool __buffers_in_use(struct vb2_queue *q)
403 {
404         unsigned int buffer, plane;
405         struct vb2_buffer *vb;
406
407         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
408                 vb = q->bufs[buffer];
409                 for (plane = 0; plane < vb->num_planes; ++plane) {
410                         /*
411                          * If num_users() has not been provided, call_memop
412                          * will return 0, apparently nobody cares about this
413                          * case anyway. If num_users() returns more than 1,
414                          * we are not the only user of the plane's memory.
415                          */
416                         if (call_memop(q, plane, num_users,
417                                         vb->planes[plane].mem_priv) > 1)
418                                 return true;
419                 }
420         }
421
422         return false;
423 }
424
425 /**
426  * vb2_reqbufs() - Initiate streaming
427  * @q:          videobuf2 queue
428  * @req:        struct passed from userspace to vidioc_reqbufs handler in driver
429  *
430  * Should be called from vidioc_reqbufs ioctl handler of a driver.
431  * This function:
432  * 1) verifies streaming parameters passed from the userspace,
433  * 2) sets up the queue,
434  * 3) negotiates number of buffers and planes per buffer with the driver
435  *    to be used during streaming,
436  * 4) allocates internal buffer structures (struct vb2_buffer), according to
437  *    the agreed parameters,
438  * 5) for MMAP memory type, allocates actual video memory, using the
439  *    memory handling/allocation routines provided during queue initialization
440  *
441  * If req->count is 0, all the memory will be freed instead.
442  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
443  * and the queue is not busy, memory will be reallocated.
444  *
445  * The return values from this function are intended to be directly returned
446  * from vidioc_reqbufs handler in driver.
447  */
448 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
449 {
450         unsigned int num_buffers, num_planes;
451         unsigned long plane_sizes[VIDEO_MAX_PLANES];
452         int ret = 0;
453
454         if (q->fileio) {
455                 dprintk(1, "reqbufs: file io in progress\n");
456                 return -EBUSY;
457         }
458
459         if (req->memory != V4L2_MEMORY_MMAP
460                         && req->memory != V4L2_MEMORY_USERPTR) {
461                 dprintk(1, "reqbufs: unsupported memory type\n");
462                 return -EINVAL;
463         }
464
465         if (req->type != q->type) {
466                 dprintk(1, "reqbufs: requested type is incorrect\n");
467                 return -EINVAL;
468         }
469
470         if (q->streaming) {
471                 dprintk(1, "reqbufs: streaming active\n");
472                 return -EBUSY;
473         }
474
475         /*
476          * Make sure all the required memory ops for given memory type
477          * are available.
478          */
479         if (req->memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
480                 dprintk(1, "reqbufs: MMAP for current setup unsupported\n");
481                 return -EINVAL;
482         }
483
484         if (req->memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
485                 dprintk(1, "reqbufs: USERPTR for current setup unsupported\n");
486                 return -EINVAL;
487         }
488
489         /*
490          * If the same number of buffers and memory access method is requested
491          * then return immediately.
492          */
493         if (q->memory == req->memory && req->count == q->num_buffers)
494                 return 0;
495
496         if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
497                 /*
498                  * We already have buffers allocated, so first check if they
499                  * are not in use and can be freed.
500                  */
501                 if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
502                         dprintk(1, "reqbufs: memory in use, cannot free\n");
503                         return -EBUSY;
504                 }
505
506                 __vb2_queue_free(q);
507
508                 /*
509                  * In case of REQBUFS(0) return immediately without calling
510                  * driver's queue_setup() callback and allocating resources.
511                  */
512                 if (req->count == 0)
513                         return 0;
514         }
515
516         /*
517          * Make sure the requested values and current defaults are sane.
518          */
519         num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
520         memset(plane_sizes, 0, sizeof(plane_sizes));
521         memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
522
523         /*
524          * Ask the driver how many buffers and planes per buffer it requires.
525          * Driver also sets the size and allocator context for each plane.
526          */
527         ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
528                        plane_sizes, q->alloc_ctx);
529         if (ret)
530                 return ret;
531
532         /* Finally, allocate buffers and video memory */
533         ret = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes,
534                                 plane_sizes);
535         if (ret < 0) {
536                 dprintk(1, "Memory allocation failed with error: %d\n", ret);
537                 return ret;
538         }
539
540         /*
541          * Check if driver can handle the allocated number of buffers.
542          */
543         if (ret < num_buffers) {
544                 unsigned int orig_num_buffers;
545
546                 orig_num_buffers = num_buffers = ret;
547                 ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
548                                plane_sizes, q->alloc_ctx);
549                 if (ret)
550                         goto free_mem;
551
552                 if (orig_num_buffers < num_buffers) {
553                         ret = -ENOMEM;
554                         goto free_mem;
555                 }
556
557                 /*
558                  * Ok, driver accepted smaller number of buffers.
559                  */
560                 ret = num_buffers;
561         }
562
563         q->memory = req->memory;
564
565         /*
566          * Return the number of successfully allocated buffers
567          * to the userspace.
568          */
569         req->count = ret;
570
571         return 0;
572
573 free_mem:
574         __vb2_queue_free(q);
575         return ret;
576 }
577 EXPORT_SYMBOL_GPL(vb2_reqbufs);
578
579 /**
580  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
581  * @vb:         vb2_buffer to which the plane in question belongs to
582  * @plane_no:   plane number for which the address is to be returned
583  *
584  * This function returns a kernel virtual address of a given plane if
585  * such a mapping exist, NULL otherwise.
586  */
587 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
588 {
589         struct vb2_queue *q = vb->vb2_queue;
590
591         if (plane_no > vb->num_planes)
592                 return NULL;
593
594         return call_memop(q, plane_no, vaddr, vb->planes[plane_no].mem_priv);
595
596 }
597 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
598
599 /**
600  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
601  * @vb:         vb2_buffer to which the plane in question belongs to
602  * @plane_no:   plane number for which the cookie is to be returned
603  *
604  * This function returns an allocator specific cookie for a given plane if
605  * available, NULL otherwise. The allocator should provide some simple static
606  * inline function, which would convert this cookie to the allocator specific
607  * type that can be used directly by the driver to access the buffer. This can
608  * be for example physical address, pointer to scatter list or IOMMU mapping.
609  */
610 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
611 {
612         struct vb2_queue *q = vb->vb2_queue;
613
614         if (plane_no > vb->num_planes)
615                 return NULL;
616
617         return call_memop(q, plane_no, cookie, vb->planes[plane_no].mem_priv);
618 }
619 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
620
621 /**
622  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
623  * @vb:         vb2_buffer returned from the driver
624  * @state:      either VB2_BUF_STATE_DONE if the operation finished successfully
625  *              or VB2_BUF_STATE_ERROR if the operation finished with an error
626  *
627  * This function should be called by the driver after a hardware operation on
628  * a buffer is finished and the buffer may be returned to userspace. The driver
629  * cannot use this buffer anymore until it is queued back to it by videobuf
630  * by the means of buf_queue callback. Only buffers previously queued to the
631  * driver by buf_queue can be passed to this function.
632  */
633 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
634 {
635         struct vb2_queue *q = vb->vb2_queue;
636         unsigned long flags;
637
638         if (vb->state != VB2_BUF_STATE_ACTIVE)
639                 return;
640
641         if (state != VB2_BUF_STATE_DONE && state != VB2_BUF_STATE_ERROR)
642                 return;
643
644         dprintk(4, "Done processing on buffer %d, state: %d\n",
645                         vb->v4l2_buf.index, vb->state);
646
647         /* Add the buffer to the done buffers list */
648         spin_lock_irqsave(&q->done_lock, flags);
649         vb->state = state;
650         list_add_tail(&vb->done_entry, &q->done_list);
651         atomic_dec(&q->queued_count);
652         spin_unlock_irqrestore(&q->done_lock, flags);
653
654         /* Inform any processes that may be waiting for buffers */
655         wake_up(&q->done_wq);
656 }
657 EXPORT_SYMBOL_GPL(vb2_buffer_done);
658
659 /**
660  * __fill_vb2_buffer() - fill a vb2_buffer with information provided in
661  * a v4l2_buffer by the userspace
662  */
663 static int __fill_vb2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b,
664                                 struct v4l2_plane *v4l2_planes)
665 {
666         unsigned int plane;
667         int ret;
668
669         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
670                 /*
671                  * Verify that the userspace gave us a valid array for
672                  * plane information.
673                  */
674                 ret = __verify_planes_array(vb, b);
675                 if (ret)
676                         return ret;
677
678                 /* Fill in driver-provided information for OUTPUT types */
679                 if (V4L2_TYPE_IS_OUTPUT(b->type)) {
680                         /*
681                          * Will have to go up to b->length when API starts
682                          * accepting variable number of planes.
683                          */
684                         for (plane = 0; plane < vb->num_planes; ++plane) {
685                                 v4l2_planes[plane].bytesused =
686                                         b->m.planes[plane].bytesused;
687                                 v4l2_planes[plane].data_offset =
688                                         b->m.planes[plane].data_offset;
689                         }
690                 }
691
692                 if (b->memory == V4L2_MEMORY_USERPTR) {
693                         for (plane = 0; plane < vb->num_planes; ++plane) {
694                                 v4l2_planes[plane].m.userptr =
695                                         b->m.planes[plane].m.userptr;
696                                 v4l2_planes[plane].length =
697                                         b->m.planes[plane].length;
698                         }
699                 }
700         } else {
701                 /*
702                  * Single-planar buffers do not use planes array,
703                  * so fill in relevant v4l2_buffer struct fields instead.
704                  * In videobuf we use our internal V4l2_planes struct for
705                  * single-planar buffers as well, for simplicity.
706                  */
707                 if (V4L2_TYPE_IS_OUTPUT(b->type))
708                         v4l2_planes[0].bytesused = b->bytesused;
709
710                 if (b->memory == V4L2_MEMORY_USERPTR) {
711                         v4l2_planes[0].m.userptr = b->m.userptr;
712                         v4l2_planes[0].length = b->length;
713                 }
714         }
715
716         vb->v4l2_buf.field = b->field;
717         vb->v4l2_buf.timestamp = b->timestamp;
718
719         return 0;
720 }
721
722 /**
723  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
724  */
725 static int __qbuf_userptr(struct vb2_buffer *vb, struct v4l2_buffer *b)
726 {
727         struct v4l2_plane planes[VIDEO_MAX_PLANES];
728         struct vb2_queue *q = vb->vb2_queue;
729         void *mem_priv;
730         unsigned int plane;
731         int ret;
732         int write = !V4L2_TYPE_IS_OUTPUT(q->type);
733
734         /* Verify and copy relevant information provided by the userspace */
735         ret = __fill_vb2_buffer(vb, b, planes);
736         if (ret)
737                 return ret;
738
739         for (plane = 0; plane < vb->num_planes; ++plane) {
740                 /* Skip the plane if already verified */
741                 if (vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
742                     && vb->v4l2_planes[plane].length == planes[plane].length)
743                         continue;
744
745                 dprintk(3, "qbuf: userspace address for plane %d changed, "
746                                 "reacquiring memory\n", plane);
747
748                 /* Release previously acquired memory if present */
749                 if (vb->planes[plane].mem_priv)
750                         call_memop(q, plane, put_userptr,
751                                         vb->planes[plane].mem_priv);
752
753                 vb->planes[plane].mem_priv = NULL;
754
755                 /* Acquire each plane's memory */
756                 if (q->mem_ops->get_userptr) {
757                         mem_priv = q->mem_ops->get_userptr(q->alloc_ctx[plane],
758                                                         planes[plane].m.userptr,
759                                                         planes[plane].length,
760                                                         write);
761                         if (IS_ERR(mem_priv)) {
762                                 dprintk(1, "qbuf: failed acquiring userspace "
763                                                 "memory for plane %d\n", plane);
764                                 ret = PTR_ERR(mem_priv);
765                                 goto err;
766                         }
767                         vb->planes[plane].mem_priv = mem_priv;
768                 }
769         }
770
771         /*
772          * Call driver-specific initialization on the newly acquired buffer,
773          * if provided.
774          */
775         ret = call_qop(q, buf_init, vb);
776         if (ret) {
777                 dprintk(1, "qbuf: buffer initialization failed\n");
778                 goto err;
779         }
780
781         /*
782          * Now that everything is in order, copy relevant information
783          * provided by userspace.
784          */
785         for (plane = 0; plane < vb->num_planes; ++plane)
786                 vb->v4l2_planes[plane] = planes[plane];
787
788         return 0;
789 err:
790         /* In case of errors, release planes that were already acquired */
791         for (; plane > 0; --plane) {
792                 call_memop(q, plane, put_userptr,
793                                 vb->planes[plane - 1].mem_priv);
794                 vb->planes[plane - 1].mem_priv = NULL;
795         }
796
797         return ret;
798 }
799
800 /**
801  * __qbuf_mmap() - handle qbuf of an MMAP buffer
802  */
803 static int __qbuf_mmap(struct vb2_buffer *vb, struct v4l2_buffer *b)
804 {
805         return __fill_vb2_buffer(vb, b, vb->v4l2_planes);
806 }
807
808 /**
809  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
810  */
811 static void __enqueue_in_driver(struct vb2_buffer *vb)
812 {
813         struct vb2_queue *q = vb->vb2_queue;
814
815         vb->state = VB2_BUF_STATE_ACTIVE;
816         atomic_inc(&q->queued_count);
817         q->ops->buf_queue(vb);
818 }
819
820 /**
821  * vb2_qbuf() - Queue a buffer from userspace
822  * @q:          videobuf2 queue
823  * @b:          buffer structure passed from userspace to vidioc_qbuf handler
824  *              in driver
825  *
826  * Should be called from vidioc_qbuf ioctl handler of a driver.
827  * This function:
828  * 1) verifies the passed buffer,
829  * 2) calls buf_prepare callback in the driver (if provided), in which
830  *    driver-specific buffer initialization can be performed,
831  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
832  *    callback for processing.
833  *
834  * The return values from this function are intended to be directly returned
835  * from vidioc_qbuf handler in driver.
836  */
837 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
838 {
839         struct vb2_buffer *vb;
840         int ret = 0;
841
842         if (q->fileio) {
843                 dprintk(1, "qbuf: file io in progress\n");
844                 return -EBUSY;
845         }
846
847         if (b->type != q->type) {
848                 dprintk(1, "qbuf: invalid buffer type\n");
849                 return -EINVAL;
850         }
851
852         if (b->index >= q->num_buffers) {
853                 dprintk(1, "qbuf: buffer index out of range\n");
854                 return -EINVAL;
855         }
856
857         vb = q->bufs[b->index];
858         if (NULL == vb) {
859                 /* Should never happen */
860                 dprintk(1, "qbuf: buffer is NULL\n");
861                 return -EINVAL;
862         }
863
864         if (b->memory != q->memory) {
865                 dprintk(1, "qbuf: invalid memory type\n");
866                 return -EINVAL;
867         }
868
869         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
870                 dprintk(1, "qbuf: buffer already in use\n");
871                 return -EINVAL;
872         }
873
874         if (q->memory == V4L2_MEMORY_MMAP)
875                 ret = __qbuf_mmap(vb, b);
876         else if (q->memory == V4L2_MEMORY_USERPTR)
877                 ret = __qbuf_userptr(vb, b);
878         else {
879                 WARN(1, "Invalid queue type\n");
880                 return -EINVAL;
881         }
882
883         if (ret)
884                 return ret;
885
886         ret = call_qop(q, buf_prepare, vb);
887         if (ret) {
888                 dprintk(1, "qbuf: buffer preparation failed\n");
889                 return ret;
890         }
891
892         /*
893          * Add to the queued buffers list, a buffer will stay on it until
894          * dequeued in dqbuf.
895          */
896         list_add_tail(&vb->queued_entry, &q->queued_list);
897         vb->state = VB2_BUF_STATE_QUEUED;
898
899         /*
900          * If already streaming, give the buffer to driver for processing.
901          * If not, the buffer will be given to driver on next streamon.
902          */
903         if (q->streaming)
904                 __enqueue_in_driver(vb);
905
906         dprintk(1, "qbuf of buffer %d succeeded\n", vb->v4l2_buf.index);
907         return 0;
908 }
909 EXPORT_SYMBOL_GPL(vb2_qbuf);
910
911 /**
912  * __vb2_wait_for_done_vb() - wait for a buffer to become available
913  * for dequeuing
914  *
915  * Will sleep if required for nonblocking == false.
916  */
917 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
918 {
919         /*
920          * All operations on vb_done_list are performed under done_lock
921          * spinlock protection. However, buffers may be removed from
922          * it and returned to userspace only while holding both driver's
923          * lock and the done_lock spinlock. Thus we can be sure that as
924          * long as we hold the driver's lock, the list will remain not
925          * empty if list_empty() check succeeds.
926          */
927
928         for (;;) {
929                 int ret;
930
931                 if (!q->streaming) {
932                         dprintk(1, "Streaming off, will not wait for buffers\n");
933                         return -EINVAL;
934                 }
935
936                 if (!list_empty(&q->done_list)) {
937                         /*
938                          * Found a buffer that we were waiting for.
939                          */
940                         break;
941                 }
942
943                 if (nonblocking) {
944                         dprintk(1, "Nonblocking and no buffers to dequeue, "
945                                                                 "will not wait\n");
946                         return -EAGAIN;
947                 }
948
949                 /*
950                  * We are streaming and blocking, wait for another buffer to
951                  * become ready or for streamoff. Driver's lock is released to
952                  * allow streamoff or qbuf to be called while waiting.
953                  */
954                 call_qop(q, wait_prepare, q);
955
956                 /*
957                  * All locks have been released, it is safe to sleep now.
958                  */
959                 dprintk(3, "Will sleep waiting for buffers\n");
960                 ret = wait_event_interruptible(q->done_wq,
961                                 !list_empty(&q->done_list) || !q->streaming);
962
963                 /*
964                  * We need to reevaluate both conditions again after reacquiring
965                  * the locks or return an error if one occurred.
966                  */
967                 call_qop(q, wait_finish, q);
968                 if (ret)
969                         return ret;
970         }
971         return 0;
972 }
973
974 /**
975  * __vb2_get_done_vb() - get a buffer ready for dequeuing
976  *
977  * Will sleep if required for nonblocking == false.
978  */
979 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
980                                 int nonblocking)
981 {
982         unsigned long flags;
983         int ret;
984
985         /*
986          * Wait for at least one buffer to become available on the done_list.
987          */
988         ret = __vb2_wait_for_done_vb(q, nonblocking);
989         if (ret)
990                 return ret;
991
992         /*
993          * Driver's lock has been held since we last verified that done_list
994          * is not empty, so no need for another list_empty(done_list) check.
995          */
996         spin_lock_irqsave(&q->done_lock, flags);
997         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
998         list_del(&(*vb)->done_entry);
999         spin_unlock_irqrestore(&q->done_lock, flags);
1000
1001         return 0;
1002 }
1003
1004 /**
1005  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
1006  * @q:          videobuf2 queue
1007  *
1008  * This function will wait until all buffers that have been given to the driver
1009  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
1010  * wait_prepare, wait_finish pair. It is intended to be called with all locks
1011  * taken, for example from stop_streaming() callback.
1012  */
1013 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1014 {
1015         if (!q->streaming) {
1016                 dprintk(1, "Streaming off, will not wait for buffers\n");
1017                 return -EINVAL;
1018         }
1019
1020         wait_event(q->done_wq, !atomic_read(&q->queued_count));
1021         return 0;
1022 }
1023 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1024
1025 /**
1026  * vb2_dqbuf() - Dequeue a buffer to the userspace
1027  * @q:          videobuf2 queue
1028  * @b:          buffer structure passed from userspace to vidioc_dqbuf handler
1029  *              in driver
1030  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
1031  *               buffers ready for dequeuing are present. Normally the driver
1032  *               would be passing (file->f_flags & O_NONBLOCK) here
1033  *
1034  * Should be called from vidioc_dqbuf ioctl handler of a driver.
1035  * This function:
1036  * 1) verifies the passed buffer,
1037  * 2) calls buf_finish callback in the driver (if provided), in which
1038  *    driver can perform any additional operations that may be required before
1039  *    returning the buffer to userspace, such as cache sync,
1040  * 3) the buffer struct members are filled with relevant information for
1041  *    the userspace.
1042  *
1043  * The return values from this function are intended to be directly returned
1044  * from vidioc_dqbuf handler in driver.
1045  */
1046 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
1047 {
1048         struct vb2_buffer *vb = NULL;
1049         int ret;
1050
1051         if (q->fileio) {
1052                 dprintk(1, "dqbuf: file io in progress\n");
1053                 return -EBUSY;
1054         }
1055
1056         if (b->type != q->type) {
1057                 dprintk(1, "dqbuf: invalid buffer type\n");
1058                 return -EINVAL;
1059         }
1060
1061         ret = __vb2_get_done_vb(q, &vb, nonblocking);
1062         if (ret < 0) {
1063                 dprintk(1, "dqbuf: error getting next done buffer\n");
1064                 return ret;
1065         }
1066
1067         ret = call_qop(q, buf_finish, vb);
1068         if (ret) {
1069                 dprintk(1, "dqbuf: buffer finish failed\n");
1070                 return ret;
1071         }
1072
1073         switch (vb->state) {
1074         case VB2_BUF_STATE_DONE:
1075                 dprintk(3, "dqbuf: Returning done buffer\n");
1076                 break;
1077         case VB2_BUF_STATE_ERROR:
1078                 dprintk(3, "dqbuf: Returning done buffer with errors\n");
1079                 break;
1080         default:
1081                 dprintk(1, "dqbuf: Invalid buffer state\n");
1082                 return -EINVAL;
1083         }
1084
1085         /* Fill buffer information for the userspace */
1086         __fill_v4l2_buffer(vb, b);
1087         /* Remove from videobuf queue */
1088         list_del(&vb->queued_entry);
1089
1090         dprintk(1, "dqbuf of buffer %d, with state %d\n",
1091                         vb->v4l2_buf.index, vb->state);
1092
1093         vb->state = VB2_BUF_STATE_DEQUEUED;
1094         return 0;
1095 }
1096 EXPORT_SYMBOL_GPL(vb2_dqbuf);
1097
1098 /**
1099  * vb2_streamon - start streaming
1100  * @q:          videobuf2 queue
1101  * @type:       type argument passed from userspace to vidioc_streamon handler
1102  *
1103  * Should be called from vidioc_streamon handler of a driver.
1104  * This function:
1105  * 1) verifies current state
1106  * 2) starts streaming and passes any previously queued buffers to the driver
1107  *
1108  * The return values from this function are intended to be directly returned
1109  * from vidioc_streamon handler in the driver.
1110  */
1111 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
1112 {
1113         struct vb2_buffer *vb;
1114         int ret;
1115
1116         if (q->fileio) {
1117                 dprintk(1, "streamon: file io in progress\n");
1118                 return -EBUSY;
1119         }
1120
1121         if (type != q->type) {
1122                 dprintk(1, "streamon: invalid stream type\n");
1123                 return -EINVAL;
1124         }
1125
1126         if (q->streaming) {
1127                 dprintk(1, "streamon: already streaming\n");
1128                 return -EBUSY;
1129         }
1130
1131         /*
1132          * Cannot start streaming on an OUTPUT device if no buffers have
1133          * been queued yet.
1134          */
1135         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1136                 if (list_empty(&q->queued_list)) {
1137                         dprintk(1, "streamon: no output buffers queued\n");
1138                         return -EINVAL;
1139                 }
1140         }
1141
1142         /*
1143          * Let driver notice that streaming state has been enabled.
1144          */
1145         ret = call_qop(q, start_streaming, q);
1146         if (ret) {
1147                 dprintk(1, "streamon: driver refused to start streaming\n");
1148                 return ret;
1149         }
1150
1151         q->streaming = 1;
1152
1153         /*
1154          * If any buffers were queued before streamon,
1155          * we can now pass them to driver for processing.
1156          */
1157         list_for_each_entry(vb, &q->queued_list, queued_entry)
1158                 __enqueue_in_driver(vb);
1159
1160         dprintk(3, "Streamon successful\n");
1161         return 0;
1162 }
1163 EXPORT_SYMBOL_GPL(vb2_streamon);
1164
1165 /**
1166  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1167  *
1168  * Removes all queued buffers from driver's queue and all buffers queued by
1169  * userspace from videobuf's queue. Returns to state after reqbufs.
1170  */
1171 static void __vb2_queue_cancel(struct vb2_queue *q)
1172 {
1173         unsigned int i;
1174
1175         /*
1176          * Tell driver to stop all transactions and release all queued
1177          * buffers.
1178          */
1179         if (q->streaming)
1180                 call_qop(q, stop_streaming, q);
1181         q->streaming = 0;
1182
1183         /*
1184          * Remove all buffers from videobuf's list...
1185          */
1186         INIT_LIST_HEAD(&q->queued_list);
1187         /*
1188          * ...and done list; userspace will not receive any buffers it
1189          * has not already dequeued before initiating cancel.
1190          */
1191         INIT_LIST_HEAD(&q->done_list);
1192         wake_up_all(&q->done_wq);
1193
1194         /*
1195          * Reinitialize all buffers for next use.
1196          */
1197         for (i = 0; i < q->num_buffers; ++i)
1198                 q->bufs[i]->state = VB2_BUF_STATE_DEQUEUED;
1199 }
1200
1201 /**
1202  * vb2_streamoff - stop streaming
1203  * @q:          videobuf2 queue
1204  * @type:       type argument passed from userspace to vidioc_streamoff handler
1205  *
1206  * Should be called from vidioc_streamoff handler of a driver.
1207  * This function:
1208  * 1) verifies current state,
1209  * 2) stop streaming and dequeues any queued buffers, including those previously
1210  *    passed to the driver (after waiting for the driver to finish).
1211  *
1212  * This call can be used for pausing playback.
1213  * The return values from this function are intended to be directly returned
1214  * from vidioc_streamoff handler in the driver
1215  */
1216 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
1217 {
1218         if (q->fileio) {
1219                 dprintk(1, "streamoff: file io in progress\n");
1220                 return -EBUSY;
1221         }
1222
1223         if (type != q->type) {
1224                 dprintk(1, "streamoff: invalid stream type\n");
1225                 return -EINVAL;
1226         }
1227
1228         if (!q->streaming) {
1229                 dprintk(1, "streamoff: not streaming\n");
1230                 return -EINVAL;
1231         }
1232
1233         /*
1234          * Cancel will pause streaming and remove all buffers from the driver
1235          * and videobuf, effectively returning control over them to userspace.
1236          */
1237         __vb2_queue_cancel(q);
1238
1239         dprintk(3, "Streamoff successful\n");
1240         return 0;
1241 }
1242 EXPORT_SYMBOL_GPL(vb2_streamoff);
1243
1244 /**
1245  * __find_plane_by_offset() - find plane associated with the given offset off
1246  */
1247 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1248                         unsigned int *_buffer, unsigned int *_plane)
1249 {
1250         struct vb2_buffer *vb;
1251         unsigned int buffer, plane;
1252
1253         /*
1254          * Go over all buffers and their planes, comparing the given offset
1255          * with an offset assigned to each plane. If a match is found,
1256          * return its buffer and plane numbers.
1257          */
1258         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1259                 vb = q->bufs[buffer];
1260
1261                 for (plane = 0; plane < vb->num_planes; ++plane) {
1262                         if (vb->v4l2_planes[plane].m.mem_offset == off) {
1263                                 *_buffer = buffer;
1264                                 *_plane = plane;
1265                                 return 0;
1266                         }
1267                 }
1268         }
1269
1270         return -EINVAL;
1271 }
1272
1273 /**
1274  * vb2_mmap() - map video buffers into application address space
1275  * @q:          videobuf2 queue
1276  * @vma:        vma passed to the mmap file operation handler in the driver
1277  *
1278  * Should be called from mmap file operation handler of a driver.
1279  * This function maps one plane of one of the available video buffers to
1280  * userspace. To map whole video memory allocated on reqbufs, this function
1281  * has to be called once per each plane per each buffer previously allocated.
1282  *
1283  * When the userspace application calls mmap, it passes to it an offset returned
1284  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
1285  * a "cookie", which is then used to identify the plane to be mapped.
1286  * This function finds a plane with a matching offset and a mapping is performed
1287  * by the means of a provided memory operation.
1288  *
1289  * The return values from this function are intended to be directly returned
1290  * from the mmap handler in driver.
1291  */
1292 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1293 {
1294         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1295         struct vb2_plane *vb_plane;
1296         struct vb2_buffer *vb;
1297         unsigned int buffer, plane;
1298         int ret;
1299
1300         if (q->memory != V4L2_MEMORY_MMAP) {
1301                 dprintk(1, "Queue is not currently set up for mmap\n");
1302                 return -EINVAL;
1303         }
1304
1305         /*
1306          * Check memory area access mode.
1307          */
1308         if (!(vma->vm_flags & VM_SHARED)) {
1309                 dprintk(1, "Invalid vma flags, VM_SHARED needed\n");
1310                 return -EINVAL;
1311         }
1312         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1313                 if (!(vma->vm_flags & VM_WRITE)) {
1314                         dprintk(1, "Invalid vma flags, VM_WRITE needed\n");
1315                         return -EINVAL;
1316                 }
1317         } else {
1318                 if (!(vma->vm_flags & VM_READ)) {
1319                         dprintk(1, "Invalid vma flags, VM_READ needed\n");
1320                         return -EINVAL;
1321                 }
1322         }
1323
1324         /*
1325          * Find the plane corresponding to the offset passed by userspace.
1326          */
1327         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1328         if (ret)
1329                 return ret;
1330
1331         vb = q->bufs[buffer];
1332         vb_plane = &vb->planes[plane];
1333
1334         ret = q->mem_ops->mmap(vb_plane->mem_priv, vma);
1335         if (ret)
1336                 return ret;
1337
1338         vb_plane->mapped = 1;
1339         vb->num_planes_mapped++;
1340
1341         dprintk(3, "Buffer %d, plane %d successfully mapped\n", buffer, plane);
1342         return 0;
1343 }
1344 EXPORT_SYMBOL_GPL(vb2_mmap);
1345
1346 static int __vb2_init_fileio(struct vb2_queue *q, int read);
1347 static int __vb2_cleanup_fileio(struct vb2_queue *q);
1348
1349 /**
1350  * vb2_poll() - implements poll userspace operation
1351  * @q:          videobuf2 queue
1352  * @file:       file argument passed to the poll file operation handler
1353  * @wait:       wait argument passed to the poll file operation handler
1354  *
1355  * This function implements poll file operation handler for a driver.
1356  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
1357  * be informed that the file descriptor of a video device is available for
1358  * reading.
1359  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
1360  * will be reported as available for writing.
1361  *
1362  * The return values from this function are intended to be directly returned
1363  * from poll handler in driver.
1364  */
1365 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
1366 {
1367         unsigned long flags;
1368         unsigned int ret;
1369         struct vb2_buffer *vb = NULL;
1370
1371         /*
1372          * Start file I/O emulator only if streaming API has not been used yet.
1373          */
1374         if (q->num_buffers == 0 && q->fileio == NULL) {
1375                 if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ)) {
1376                         ret = __vb2_init_fileio(q, 1);
1377                         if (ret)
1378                                 return POLLERR;
1379                 }
1380                 if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE)) {
1381                         ret = __vb2_init_fileio(q, 0);
1382                         if (ret)
1383                                 return POLLERR;
1384                         /*
1385                          * Write to OUTPUT queue can be done immediately.
1386                          */
1387                         return POLLOUT | POLLWRNORM;
1388                 }
1389         }
1390
1391         /*
1392          * There is nothing to wait for if no buffers have already been queued.
1393          */
1394         if (list_empty(&q->queued_list))
1395                 return POLLERR;
1396
1397         poll_wait(file, &q->done_wq, wait);
1398
1399         /*
1400          * Take first buffer available for dequeuing.
1401          */
1402         spin_lock_irqsave(&q->done_lock, flags);
1403         if (!list_empty(&q->done_list))
1404                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
1405                                         done_entry);
1406         spin_unlock_irqrestore(&q->done_lock, flags);
1407
1408         if (vb && (vb->state == VB2_BUF_STATE_DONE
1409                         || vb->state == VB2_BUF_STATE_ERROR)) {
1410                 return (V4L2_TYPE_IS_OUTPUT(q->type)) ? POLLOUT | POLLWRNORM :
1411                         POLLIN | POLLRDNORM;
1412         }
1413         return 0;
1414 }
1415 EXPORT_SYMBOL_GPL(vb2_poll);
1416
1417 /**
1418  * vb2_queue_init() - initialize a videobuf2 queue
1419  * @q:          videobuf2 queue; this structure should be allocated in driver
1420  *
1421  * The vb2_queue structure should be allocated by the driver. The driver is
1422  * responsible of clearing it's content and setting initial values for some
1423  * required entries before calling this function.
1424  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
1425  * to the struct vb2_queue description in include/media/videobuf2-core.h
1426  * for more information.
1427  */
1428 int vb2_queue_init(struct vb2_queue *q)
1429 {
1430         BUG_ON(!q);
1431         BUG_ON(!q->ops);
1432         BUG_ON(!q->mem_ops);
1433         BUG_ON(!q->type);
1434         BUG_ON(!q->io_modes);
1435
1436         BUG_ON(!q->ops->queue_setup);
1437         BUG_ON(!q->ops->buf_queue);
1438
1439         INIT_LIST_HEAD(&q->queued_list);
1440         INIT_LIST_HEAD(&q->done_list);
1441         spin_lock_init(&q->done_lock);
1442         init_waitqueue_head(&q->done_wq);
1443
1444         if (q->buf_struct_size == 0)
1445                 q->buf_struct_size = sizeof(struct vb2_buffer);
1446
1447         return 0;
1448 }
1449 EXPORT_SYMBOL_GPL(vb2_queue_init);
1450
1451 /**
1452  * vb2_queue_release() - stop streaming, release the queue and free memory
1453  * @q:          videobuf2 queue
1454  *
1455  * This function stops streaming and performs necessary clean ups, including
1456  * freeing video buffer memory. The driver is responsible for freeing
1457  * the vb2_queue structure itself.
1458  */
1459 void vb2_queue_release(struct vb2_queue *q)
1460 {
1461         __vb2_cleanup_fileio(q);
1462         __vb2_queue_cancel(q);
1463         __vb2_queue_free(q);
1464 }
1465 EXPORT_SYMBOL_GPL(vb2_queue_release);
1466
1467 /**
1468  * struct vb2_fileio_buf - buffer context used by file io emulator
1469  *
1470  * vb2 provides a compatibility layer and emulator of file io (read and
1471  * write) calls on top of streaming API. This structure is used for
1472  * tracking context related to the buffers.
1473  */
1474 struct vb2_fileio_buf {
1475         void *vaddr;
1476         unsigned int size;
1477         unsigned int pos;
1478         unsigned int queued:1;
1479 };
1480
1481 /**
1482  * struct vb2_fileio_data - queue context used by file io emulator
1483  *
1484  * vb2 provides a compatibility layer and emulator of file io (read and
1485  * write) calls on top of streaming API. For proper operation it required
1486  * this structure to save the driver state between each call of the read
1487  * or write function.
1488  */
1489 struct vb2_fileio_data {
1490         struct v4l2_requestbuffers req;
1491         struct v4l2_buffer b;
1492         struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
1493         unsigned int index;
1494         unsigned int q_count;
1495         unsigned int dq_count;
1496         unsigned int flags;
1497 };
1498
1499 /**
1500  * __vb2_init_fileio() - initialize file io emulator
1501  * @q:          videobuf2 queue
1502  * @read:       mode selector (1 means read, 0 means write)
1503  */
1504 static int __vb2_init_fileio(struct vb2_queue *q, int read)
1505 {
1506         struct vb2_fileio_data *fileio;
1507         int i, ret;
1508         unsigned int count = 0;
1509
1510         /*
1511          * Sanity check
1512          */
1513         if ((read && !(q->io_modes & VB2_READ)) ||
1514            (!read && !(q->io_modes & VB2_WRITE)))
1515                 BUG();
1516
1517         /*
1518          * Check if device supports mapping buffers to kernel virtual space.
1519          */
1520         if (!q->mem_ops->vaddr)
1521                 return -EBUSY;
1522
1523         /*
1524          * Check if streaming api has not been already activated.
1525          */
1526         if (q->streaming || q->num_buffers > 0)
1527                 return -EBUSY;
1528
1529         /*
1530          * Start with count 1, driver can increase it in queue_setup()
1531          */
1532         count = 1;
1533
1534         dprintk(3, "setting up file io: mode %s, count %d, flags %08x\n",
1535                 (read) ? "read" : "write", count, q->io_flags);
1536
1537         fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
1538         if (fileio == NULL)
1539                 return -ENOMEM;
1540
1541         fileio->flags = q->io_flags;
1542
1543         /*
1544          * Request buffers and use MMAP type to force driver
1545          * to allocate buffers by itself.
1546          */
1547         fileio->req.count = count;
1548         fileio->req.memory = V4L2_MEMORY_MMAP;
1549         fileio->req.type = q->type;
1550         ret = vb2_reqbufs(q, &fileio->req);
1551         if (ret)
1552                 goto err_kfree;
1553
1554         /*
1555          * Check if plane_count is correct
1556          * (multiplane buffers are not supported).
1557          */
1558         if (q->bufs[0]->num_planes != 1) {
1559                 fileio->req.count = 0;
1560                 ret = -EBUSY;
1561                 goto err_reqbufs;
1562         }
1563
1564         /*
1565          * Get kernel address of each buffer.
1566          */
1567         for (i = 0; i < q->num_buffers; i++) {
1568                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
1569                 if (fileio->bufs[i].vaddr == NULL)
1570                         goto err_reqbufs;
1571                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
1572         }
1573
1574         /*
1575          * Read mode requires pre queuing of all buffers.
1576          */
1577         if (read) {
1578                 /*
1579                  * Queue all buffers.
1580                  */
1581                 for (i = 0; i < q->num_buffers; i++) {
1582                         struct v4l2_buffer *b = &fileio->b;
1583                         memset(b, 0, sizeof(*b));
1584                         b->type = q->type;
1585                         b->memory = q->memory;
1586                         b->index = i;
1587                         ret = vb2_qbuf(q, b);
1588                         if (ret)
1589                                 goto err_reqbufs;
1590                         fileio->bufs[i].queued = 1;
1591                 }
1592
1593                 /*
1594                  * Start streaming.
1595                  */
1596                 ret = vb2_streamon(q, q->type);
1597                 if (ret)
1598                         goto err_reqbufs;
1599         }
1600
1601         q->fileio = fileio;
1602
1603         return ret;
1604
1605 err_reqbufs:
1606         vb2_reqbufs(q, &fileio->req);
1607
1608 err_kfree:
1609         kfree(fileio);
1610         return ret;
1611 }
1612
1613 /**
1614  * __vb2_cleanup_fileio() - free resourced used by file io emulator
1615  * @q:          videobuf2 queue
1616  */
1617 static int __vb2_cleanup_fileio(struct vb2_queue *q)
1618 {
1619         struct vb2_fileio_data *fileio = q->fileio;
1620
1621         if (fileio) {
1622                 /*
1623                  * Hack fileio context to enable direct calls to vb2 ioctl
1624                  * interface.
1625                  */
1626                 q->fileio = NULL;
1627
1628                 vb2_streamoff(q, q->type);
1629                 fileio->req.count = 0;
1630                 vb2_reqbufs(q, &fileio->req);
1631                 kfree(fileio);
1632                 dprintk(3, "file io emulator closed\n");
1633         }
1634         return 0;
1635 }
1636
1637 /**
1638  * __vb2_perform_fileio() - perform a single file io (read or write) operation
1639  * @q:          videobuf2 queue
1640  * @data:       pointed to target userspace buffer
1641  * @count:      number of bytes to read or write
1642  * @ppos:       file handle position tracking pointer
1643  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
1644  * @read:       access mode selector (1 means read, 0 means write)
1645  */
1646 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
1647                 loff_t *ppos, int nonblock, int read)
1648 {
1649         struct vb2_fileio_data *fileio;
1650         struct vb2_fileio_buf *buf;
1651         int ret, index;
1652
1653         dprintk(3, "file io: mode %s, offset %ld, count %zd, %sblocking\n",
1654                 read ? "read" : "write", (long)*ppos, count,
1655                 nonblock ? "non" : "");
1656
1657         if (!data)
1658                 return -EINVAL;
1659
1660         /*
1661          * Initialize emulator on first call.
1662          */
1663         if (!q->fileio) {
1664                 ret = __vb2_init_fileio(q, read);
1665                 dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
1666                 if (ret)
1667                         return ret;
1668         }
1669         fileio = q->fileio;
1670
1671         /*
1672          * Hack fileio context to enable direct calls to vb2 ioctl interface.
1673          * The pointer will be restored before returning from this function.
1674          */
1675         q->fileio = NULL;
1676
1677         index = fileio->index;
1678         buf = &fileio->bufs[index];
1679
1680         /*
1681          * Check if we need to dequeue the buffer.
1682          */
1683         if (buf->queued) {
1684                 struct vb2_buffer *vb;
1685
1686                 /*
1687                  * Call vb2_dqbuf to get buffer back.
1688                  */
1689                 memset(&fileio->b, 0, sizeof(fileio->b));
1690                 fileio->b.type = q->type;
1691                 fileio->b.memory = q->memory;
1692                 fileio->b.index = index;
1693                 ret = vb2_dqbuf(q, &fileio->b, nonblock);
1694                 dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
1695                 if (ret)
1696                         goto end;
1697                 fileio->dq_count += 1;
1698
1699                 /*
1700                  * Get number of bytes filled by the driver
1701                  */
1702                 vb = q->bufs[index];
1703                 buf->size = vb2_get_plane_payload(vb, 0);
1704                 buf->queued = 0;
1705         }
1706
1707         /*
1708          * Limit count on last few bytes of the buffer.
1709          */
1710         if (buf->pos + count > buf->size) {
1711                 count = buf->size - buf->pos;
1712                 dprintk(5, "reducing read count: %zd\n", count);
1713         }
1714
1715         /*
1716          * Transfer data to userspace.
1717          */
1718         dprintk(3, "file io: copying %zd bytes - buffer %d, offset %u\n",
1719                 count, index, buf->pos);
1720         if (read)
1721                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
1722         else
1723                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
1724         if (ret) {
1725                 dprintk(3, "file io: error copying data\n");
1726                 ret = -EFAULT;
1727                 goto end;
1728         }
1729
1730         /*
1731          * Update counters.
1732          */
1733         buf->pos += count;
1734         *ppos += count;
1735
1736         /*
1737          * Queue next buffer if required.
1738          */
1739         if (buf->pos == buf->size ||
1740            (!read && (fileio->flags & VB2_FILEIO_WRITE_IMMEDIATELY))) {
1741                 /*
1742                  * Check if this is the last buffer to read.
1743                  */
1744                 if (read && (fileio->flags & VB2_FILEIO_READ_ONCE) &&
1745                     fileio->dq_count == 1) {
1746                         dprintk(3, "file io: read limit reached\n");
1747                         /*
1748                          * Restore fileio pointer and release the context.
1749                          */
1750                         q->fileio = fileio;
1751                         return __vb2_cleanup_fileio(q);
1752                 }
1753
1754                 /*
1755                  * Call vb2_qbuf and give buffer to the driver.
1756                  */
1757                 memset(&fileio->b, 0, sizeof(fileio->b));
1758                 fileio->b.type = q->type;
1759                 fileio->b.memory = q->memory;
1760                 fileio->b.index = index;
1761                 fileio->b.bytesused = buf->pos;
1762                 ret = vb2_qbuf(q, &fileio->b);
1763                 dprintk(5, "file io: vb2_dbuf result: %d\n", ret);
1764                 if (ret)
1765                         goto end;
1766
1767                 /*
1768                  * Buffer has been queued, update the status
1769                  */
1770                 buf->pos = 0;
1771                 buf->queued = 1;
1772                 buf->size = q->bufs[0]->v4l2_planes[0].length;
1773                 fileio->q_count += 1;
1774
1775                 /*
1776                  * Switch to the next buffer
1777                  */
1778                 fileio->index = (index + 1) % q->num_buffers;
1779
1780                 /*
1781                  * Start streaming if required.
1782                  */
1783                 if (!read && !q->streaming) {
1784                         ret = vb2_streamon(q, q->type);
1785                         if (ret)
1786                                 goto end;
1787                 }
1788         }
1789
1790         /*
1791          * Return proper number of bytes processed.
1792          */
1793         if (ret == 0)
1794                 ret = count;
1795 end:
1796         /*
1797          * Restore the fileio context and block vb2 ioctl interface.
1798          */
1799         q->fileio = fileio;
1800         return ret;
1801 }
1802
1803 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
1804                 loff_t *ppos, int nonblocking)
1805 {
1806         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
1807 }
1808 EXPORT_SYMBOL_GPL(vb2_read);
1809
1810 size_t vb2_write(struct vb2_queue *q, char __user *data, size_t count,
1811                 loff_t *ppos, int nonblocking)
1812 {
1813         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 0);
1814 }
1815 EXPORT_SYMBOL_GPL(vb2_write);
1816
1817 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
1818 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
1819 MODULE_LICENSE("GPL");