Merge branch 'linux-linaro-lsk-v4.4-android' of git://git.linaro.org/kernel/linux...
[firefly-linux-kernel-4.4.55.git] / drivers / media / v4l2-core / videobuf2-v4l2.c
1 /*
2  * videobuf2-v4l2.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  * The vb2_thread implementation was based on code from videobuf-dvb.c:
10  *      (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation.
15  */
16
17 #include <linux/err.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/mm.h>
21 #include <linux/poll.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
26
27 #include <media/v4l2-dev.h>
28 #include <media/v4l2-fh.h>
29 #include <media/v4l2-event.h>
30 #include <media/v4l2-common.h>
31
32 #include <media/videobuf2-v4l2.h>
33
34 #include "videobuf2-internal.h"
35
36 /* Flags that are set by the vb2 core */
37 #define V4L2_BUFFER_MASK_FLAGS  (V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
38                                  V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
39                                  V4L2_BUF_FLAG_PREPARED | \
40                                  V4L2_BUF_FLAG_TIMESTAMP_MASK)
41 /* Output buffer flags that should be passed on to the driver */
42 #define V4L2_BUFFER_OUT_FLAGS   (V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | \
43                                  V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_TIMECODE)
44
45 /**
46  * __verify_planes_array() - verify that the planes array passed in struct
47  * v4l2_buffer from userspace can be safely used
48  */
49 static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
50 {
51         if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
52                 return 0;
53
54         /* Is memory for copying plane information present? */
55         if (NULL == b->m.planes) {
56                 dprintk(1, "multi-planar buffer passed but "
57                            "planes array not provided\n");
58                 return -EINVAL;
59         }
60
61         if (b->length < vb->num_planes || b->length > VB2_MAX_PLANES) {
62                 dprintk(1, "incorrect planes array length, "
63                            "expected %d, got %d\n", vb->num_planes, b->length);
64                 return -EINVAL;
65         }
66
67         return 0;
68 }
69
70 static int __verify_planes_array_core(struct vb2_buffer *vb, const void *pb)
71 {
72         return __verify_planes_array(vb, pb);
73 }
74
75 /**
76  * __verify_length() - Verify that the bytesused value for each plane fits in
77  * the plane length and that the data offset doesn't exceed the bytesused value.
78  */
79 static int __verify_length(struct vb2_buffer *vb, const struct v4l2_buffer *b)
80 {
81         unsigned int length;
82         unsigned int bytesused;
83         unsigned int plane;
84
85         if (!V4L2_TYPE_IS_OUTPUT(b->type))
86                 return 0;
87
88         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
89                 for (plane = 0; plane < vb->num_planes; ++plane) {
90                         length = (b->memory == VB2_MEMORY_USERPTR ||
91                                   b->memory == VB2_MEMORY_DMABUF)
92                                ? b->m.planes[plane].length
93                                 : vb->planes[plane].length;
94                         bytesused = b->m.planes[plane].bytesused
95                                   ? b->m.planes[plane].bytesused : length;
96
97                         if (b->m.planes[plane].bytesused > length)
98                                 return -EINVAL;
99
100                         if (b->m.planes[plane].data_offset > 0 &&
101                             b->m.planes[plane].data_offset >= bytesused)
102                                 return -EINVAL;
103                 }
104         } else {
105                 length = (b->memory == VB2_MEMORY_USERPTR)
106                         ? b->length : vb->planes[0].length;
107
108                 if (b->bytesused > length)
109                         return -EINVAL;
110         }
111
112         return 0;
113 }
114
115 static int __set_timestamp(struct vb2_buffer *vb, const void *pb)
116 {
117         const struct v4l2_buffer *b = pb;
118         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
119         struct vb2_queue *q = vb->vb2_queue;
120
121         if (q->is_output) {
122                 /*
123                  * For output buffers copy the timestamp if needed,
124                  * and the timecode field and flag if needed.
125                  */
126                 if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
127                                 V4L2_BUF_FLAG_TIMESTAMP_COPY)
128                         vbuf->timestamp = b->timestamp;
129                 vbuf->flags |= b->flags & V4L2_BUF_FLAG_TIMECODE;
130                 if (b->flags & V4L2_BUF_FLAG_TIMECODE)
131                         vbuf->timecode = b->timecode;
132         }
133         return 0;
134 };
135
136 static void vb2_warn_zero_bytesused(struct vb2_buffer *vb)
137 {
138         static bool check_once;
139
140         if (check_once)
141                 return;
142
143         check_once = true;
144         WARN_ON(1);
145
146         pr_warn("use of bytesused == 0 is deprecated and will be removed in the future,\n");
147         if (vb->vb2_queue->allow_zero_bytesused)
148                 pr_warn("use VIDIOC_DECODER_CMD(V4L2_DEC_CMD_STOP) instead.\n");
149         else
150                 pr_warn("use the actual size instead.\n");
151 }
152
153 static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
154                                     const char *opname)
155 {
156         if (b->type != q->type) {
157                 dprintk(1, "%s: invalid buffer type\n", opname);
158                 return -EINVAL;
159         }
160
161         if (b->index >= q->num_buffers) {
162                 dprintk(1, "%s: buffer index out of range\n", opname);
163                 return -EINVAL;
164         }
165
166         if (q->bufs[b->index] == NULL) {
167                 /* Should never happen */
168                 dprintk(1, "%s: buffer is NULL\n", opname);
169                 return -EINVAL;
170         }
171
172         if (b->memory != q->memory) {
173                 dprintk(1, "%s: invalid memory type\n", opname);
174                 return -EINVAL;
175         }
176
177         return __verify_planes_array(q->bufs[b->index], b);
178 }
179
180 /**
181  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
182  * returned to userspace
183  */
184 static int __fill_v4l2_buffer(struct vb2_buffer *vb, void *pb)
185 {
186         struct v4l2_buffer *b = pb;
187         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
188         struct vb2_queue *q = vb->vb2_queue;
189         unsigned int plane;
190
191         /* Copy back data such as timestamp, flags, etc. */
192         b->index = vb->index;
193         b->type = vb->type;
194         b->memory = vb->memory;
195         b->bytesused = 0;
196
197         b->flags = vbuf->flags;
198         b->field = vbuf->field;
199         b->timestamp = vbuf->timestamp;
200         b->timecode = vbuf->timecode;
201         b->sequence = vbuf->sequence;
202         b->config_store = vbuf->config_store;
203         b->reserved = 0;
204
205         if (q->is_multiplanar) {
206                 /*
207                  * Fill in plane-related data if userspace provided an array
208                  * for it. The caller has already verified memory and size.
209                  */
210                 b->length = vb->num_planes;
211                 for (plane = 0; plane < vb->num_planes; ++plane) {
212                         struct v4l2_plane *pdst = &b->m.planes[plane];
213                         struct vb2_plane *psrc = &vb->planes[plane];
214
215                         pdst->bytesused = psrc->bytesused;
216                         pdst->length = psrc->length;
217                         if (q->memory == VB2_MEMORY_MMAP)
218                                 pdst->m.mem_offset = psrc->m.offset;
219                         else if (q->memory == VB2_MEMORY_USERPTR)
220                                 pdst->m.userptr = psrc->m.userptr;
221                         else if (q->memory == VB2_MEMORY_DMABUF)
222                                 pdst->m.fd = psrc->m.fd;
223                         pdst->data_offset = psrc->data_offset;
224                         memset(pdst->reserved, 0, sizeof(pdst->reserved));
225                 }
226         } else {
227                 /*
228                  * We use length and offset in v4l2_planes array even for
229                  * single-planar buffers, but userspace does not.
230                  */
231                 b->length = vb->planes[0].length;
232                 b->bytesused = vb->planes[0].bytesused;
233                 if (q->memory == VB2_MEMORY_MMAP)
234                         b->m.offset = vb->planes[0].m.offset;
235                 else if (q->memory == VB2_MEMORY_USERPTR)
236                         b->m.userptr = vb->planes[0].m.userptr;
237                 else if (q->memory == VB2_MEMORY_DMABUF)
238                         b->m.fd = vb->planes[0].m.fd;
239         }
240
241         /*
242          * Clear any buffer state related flags.
243          */
244         b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
245         b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;
246         if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
247             V4L2_BUF_FLAG_TIMESTAMP_COPY) {
248                 /*
249                  * For non-COPY timestamps, drop timestamp source bits
250                  * and obtain the timestamp source from the queue.
251                  */
252                 b->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
253                 b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
254         }
255
256         switch (vb->state) {
257         case VB2_BUF_STATE_QUEUED:
258         case VB2_BUF_STATE_ACTIVE:
259                 b->flags |= V4L2_BUF_FLAG_QUEUED;
260                 break;
261         case VB2_BUF_STATE_ERROR:
262                 b->flags |= V4L2_BUF_FLAG_ERROR;
263                 /* fall through */
264         case VB2_BUF_STATE_DONE:
265                 b->flags |= V4L2_BUF_FLAG_DONE;
266                 break;
267         case VB2_BUF_STATE_PREPARED:
268                 b->flags |= V4L2_BUF_FLAG_PREPARED;
269                 break;
270         case VB2_BUF_STATE_PREPARING:
271         case VB2_BUF_STATE_DEQUEUED:
272         case VB2_BUF_STATE_REQUEUEING:
273                 /* nothing */
274                 break;
275         }
276
277         if (vb2_buffer_in_use(q, vb))
278                 b->flags |= V4L2_BUF_FLAG_MAPPED;
279
280         return 0;
281 }
282
283 /**
284  * __fill_vb2_buffer() - fill a vb2_buffer with information provided in a
285  * v4l2_buffer by the userspace. It also verifies that struct
286  * v4l2_buffer has a valid number of planes.
287  */
288 static int __fill_vb2_buffer(struct vb2_buffer *vb,
289                 const void *pb, struct vb2_plane *planes)
290 {
291         struct vb2_queue *q = vb->vb2_queue;
292         const struct v4l2_buffer *b = pb;
293         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
294         unsigned int plane;
295         int ret;
296
297         ret = __verify_length(vb, b);
298         if (ret < 0) {
299                 dprintk(1, "plane parameters verification failed: %d\n", ret);
300                 return ret;
301         }
302         if (b->field == V4L2_FIELD_ALTERNATE && q->is_output) {
303                 /*
304                  * If the format's field is ALTERNATE, then the buffer's field
305                  * should be either TOP or BOTTOM, not ALTERNATE since that
306                  * makes no sense. The driver has to know whether the
307                  * buffer represents a top or a bottom field in order to
308                  * program any DMA correctly. Using ALTERNATE is wrong, since
309                  * that just says that it is either a top or a bottom field,
310                  * but not which of the two it is.
311                  */
312                 dprintk(1, "the field is incorrectly set to ALTERNATE "
313                                         "for an output buffer\n");
314                 return -EINVAL;
315         }
316         vbuf->timestamp.tv_sec = 0;
317         vbuf->timestamp.tv_usec = 0;
318         vbuf->sequence = 0;
319
320         if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
321                 if (b->memory == VB2_MEMORY_USERPTR) {
322                         for (plane = 0; plane < vb->num_planes; ++plane) {
323                                 planes[plane].m.userptr =
324                                         b->m.planes[plane].m.userptr;
325                                 planes[plane].length =
326                                         b->m.planes[plane].length;
327                         }
328                 }
329                 if (b->memory == VB2_MEMORY_DMABUF) {
330                         for (plane = 0; plane < vb->num_planes; ++plane) {
331                                 planes[plane].m.fd =
332                                         b->m.planes[plane].m.fd;
333                                 planes[plane].length =
334                                         b->m.planes[plane].length;
335                         }
336                 }
337
338                 /* Fill in driver-provided information for OUTPUT types */
339                 if (V4L2_TYPE_IS_OUTPUT(b->type)) {
340                         /*
341                          * Will have to go up to b->length when API starts
342                          * accepting variable number of planes.
343                          *
344                          * If bytesused == 0 for the output buffer, then fall
345                          * back to the full buffer size. In that case
346                          * userspace clearly never bothered to set it and
347                          * it's a safe assumption that they really meant to
348                          * use the full plane sizes.
349                          *
350                          * Some drivers, e.g. old codec drivers, use bytesused == 0
351                          * as a way to indicate that streaming is finished.
352                          * In that case, the driver should use the
353                          * allow_zero_bytesused flag to keep old userspace
354                          * applications working.
355                          */
356                         for (plane = 0; plane < vb->num_planes; ++plane) {
357                                 struct vb2_plane *pdst = &planes[plane];
358                                 struct v4l2_plane *psrc = &b->m.planes[plane];
359
360                                 if (psrc->bytesused == 0)
361                                         vb2_warn_zero_bytesused(vb);
362
363                                 if (vb->vb2_queue->allow_zero_bytesused)
364                                         pdst->bytesused = psrc->bytesused;
365                                 else
366                                         pdst->bytesused = psrc->bytesused ?
367                                                 psrc->bytesused : pdst->length;
368                                 pdst->data_offset = psrc->data_offset;
369                         }
370                 }
371         } else {
372                 /*
373                  * Single-planar buffers do not use planes array,
374                  * so fill in relevant v4l2_buffer struct fields instead.
375                  * In videobuf we use our internal V4l2_planes struct for
376                  * single-planar buffers as well, for simplicity.
377                  *
378                  * If bytesused == 0 for the output buffer, then fall back
379                  * to the full buffer size as that's a sensible default.
380                  *
381                  * Some drivers, e.g. old codec drivers, use bytesused == 0 as
382                  * a way to indicate that streaming is finished. In that case,
383                  * the driver should use the allow_zero_bytesused flag to keep
384                  * old userspace applications working.
385                  */
386                 if (b->memory == VB2_MEMORY_USERPTR) {
387                         planes[0].m.userptr = b->m.userptr;
388                         planes[0].length = b->length;
389                 }
390
391                 if (b->memory == VB2_MEMORY_DMABUF) {
392                         planes[0].m.fd = b->m.fd;
393                         planes[0].length = b->length;
394                 }
395
396                 if (V4L2_TYPE_IS_OUTPUT(b->type)) {
397                         if (b->bytesused == 0)
398                                 vb2_warn_zero_bytesused(vb);
399
400                         if (vb->vb2_queue->allow_zero_bytesused)
401                                 planes[0].bytesused = b->bytesused;
402                         else
403                                 planes[0].bytesused = b->bytesused ?
404                                         b->bytesused : planes[0].length;
405                 } else
406                         planes[0].bytesused = 0;
407
408         }
409
410         /* Zero flags that the vb2 core handles */
411         vbuf->flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
412         if ((vb->vb2_queue->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
413             V4L2_BUF_FLAG_TIMESTAMP_COPY || !V4L2_TYPE_IS_OUTPUT(b->type)) {
414                 /*
415                  * Non-COPY timestamps and non-OUTPUT queues will get
416                  * their timestamp and timestamp source flags from the
417                  * queue.
418                  */
419                 vbuf->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
420         }
421
422         vbuf->config_store = b->config_store;
423
424         if (V4L2_TYPE_IS_OUTPUT(b->type)) {
425                 /*
426                  * For output buffers mask out the timecode flag:
427                  * this will be handled later in vb2_internal_qbuf().
428                  * The 'field' is valid metadata for this output buffer
429                  * and so that needs to be copied here.
430                  */
431                 vbuf->flags &= ~V4L2_BUF_FLAG_TIMECODE;
432                 vbuf->field = b->field;
433         } else {
434                 /* Zero any output buffer flags as this is a capture buffer */
435                 vbuf->flags &= ~V4L2_BUFFER_OUT_FLAGS;
436         }
437
438         return 0;
439 }
440
441 static const struct vb2_buf_ops v4l2_buf_ops = {
442         .verify_planes_array    = __verify_planes_array_core,
443         .fill_user_buffer       = __fill_v4l2_buffer,
444         .fill_vb2_buffer        = __fill_vb2_buffer,
445         .set_timestamp          = __set_timestamp,
446 };
447
448 /**
449  * vb2_querybuf() - query video buffer information
450  * @q:          videobuf queue
451  * @b:          buffer struct passed from userspace to vidioc_querybuf handler
452  *              in driver
453  *
454  * Should be called from vidioc_querybuf ioctl handler in driver.
455  * This function will verify the passed v4l2_buffer structure and fill the
456  * relevant information for the userspace.
457  *
458  * The return values from this function are intended to be directly returned
459  * from vidioc_querybuf handler in driver.
460  */
461 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
462 {
463         struct vb2_buffer *vb;
464         int ret;
465
466         if (b->type != q->type) {
467                 dprintk(1, "wrong buffer type\n");
468                 return -EINVAL;
469         }
470
471         if (b->index >= q->num_buffers) {
472                 dprintk(1, "buffer index out of range\n");
473                 return -EINVAL;
474         }
475         vb = q->bufs[b->index];
476         ret = __verify_planes_array(vb, b);
477
478         return ret ? ret : vb2_core_querybuf(q, b->index, b);
479 }
480 EXPORT_SYMBOL(vb2_querybuf);
481
482 /**
483  * vb2_reqbufs() - Wrapper for vb2_core_reqbufs() that also verifies
484  * the memory and type values.
485  * @q:          videobuf2 queue
486  * @req:        struct passed from userspace to vidioc_reqbufs handler
487  *              in driver
488  */
489 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
490 {
491         int ret = vb2_verify_memory_type(q, req->memory, req->type);
492
493         return ret ? ret : vb2_core_reqbufs(q, req->memory, &req->count);
494 }
495 EXPORT_SYMBOL_GPL(vb2_reqbufs);
496
497 /**
498  * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
499  * @q:          videobuf2 queue
500  * @b:          buffer structure passed from userspace to vidioc_prepare_buf
501  *              handler in driver
502  *
503  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
504  * This function:
505  * 1) verifies the passed buffer,
506  * 2) calls buf_prepare callback in the driver (if provided), in which
507  *    driver-specific buffer initialization can be performed,
508  *
509  * The return values from this function are intended to be directly returned
510  * from vidioc_prepare_buf handler in driver.
511  */
512 int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
513 {
514         int ret;
515
516         if (vb2_fileio_is_active(q)) {
517                 dprintk(1, "file io in progress\n");
518                 return -EBUSY;
519         }
520
521         ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
522
523         return ret ? ret : vb2_core_prepare_buf(q, b->index, b);
524 }
525 EXPORT_SYMBOL_GPL(vb2_prepare_buf);
526
527 /**
528  * vb2_create_bufs() - Wrapper for vb2_core_create_bufs() that also verifies
529  * the memory and type values.
530  * @q:          videobuf2 queue
531  * @create:     creation parameters, passed from userspace to vidioc_create_bufs
532  *              handler in driver
533  */
534 int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
535 {
536         int ret = vb2_verify_memory_type(q, create->memory,
537                         create->format.type);
538
539         create->index = q->num_buffers;
540         if (create->count == 0)
541                 return ret != -EBUSY ? ret : 0;
542         return ret ? ret : vb2_core_create_bufs(q, create->memory,
543                 &create->count, &create->format);
544 }
545 EXPORT_SYMBOL_GPL(vb2_create_bufs);
546
547 static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
548 {
549         int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
550
551         return ret ? ret : vb2_core_qbuf(q, b->index, b);
552 }
553
554 /**
555  * vb2_qbuf() - Queue a buffer from userspace
556  * @q:          videobuf2 queue
557  * @b:          buffer structure passed from userspace to vidioc_qbuf handler
558  *              in driver
559  *
560  * Should be called from vidioc_qbuf ioctl handler of a driver.
561  * This function:
562  * 1) verifies the passed buffer,
563  * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
564  *    which driver-specific buffer initialization can be performed,
565  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
566  *    callback for processing.
567  *
568  * The return values from this function are intended to be directly returned
569  * from vidioc_qbuf handler in driver.
570  */
571 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
572 {
573         if (vb2_fileio_is_active(q)) {
574                 dprintk(1, "file io in progress\n");
575                 return -EBUSY;
576         }
577
578         return vb2_internal_qbuf(q, b);
579 }
580 EXPORT_SYMBOL_GPL(vb2_qbuf);
581
582 static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b,
583                 bool nonblocking)
584 {
585         int ret;
586
587         if (b->type != q->type) {
588                 dprintk(1, "invalid buffer type\n");
589                 return -EINVAL;
590         }
591
592         ret = vb2_core_dqbuf(q, b, nonblocking);
593
594         if (!ret && !q->is_output &&
595                         b->flags & V4L2_BUF_FLAG_LAST)
596                 q->last_buffer_dequeued = true;
597
598         return ret;
599 }
600
601 /**
602  * vb2_dqbuf() - Dequeue a buffer to the userspace
603  * @q:          videobuf2 queue
604  * @b:          buffer structure passed from userspace to vidioc_dqbuf handler
605  *              in driver
606  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
607  *               buffers ready for dequeuing are present. Normally the driver
608  *               would be passing (file->f_flags & O_NONBLOCK) here
609  *
610  * Should be called from vidioc_dqbuf ioctl handler of a driver.
611  * This function:
612  * 1) verifies the passed buffer,
613  * 2) calls buf_finish callback in the driver (if provided), in which
614  *    driver can perform any additional operations that may be required before
615  *    returning the buffer to userspace, such as cache sync,
616  * 3) the buffer struct members are filled with relevant information for
617  *    the userspace.
618  *
619  * The return values from this function are intended to be directly returned
620  * from vidioc_dqbuf handler in driver.
621  */
622 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
623 {
624         if (vb2_fileio_is_active(q)) {
625                 dprintk(1, "file io in progress\n");
626                 return -EBUSY;
627         }
628         return vb2_internal_dqbuf(q, b, nonblocking);
629 }
630 EXPORT_SYMBOL_GPL(vb2_dqbuf);
631
632 /**
633  * vb2_streamon - start streaming
634  * @q:          videobuf2 queue
635  * @type:       type argument passed from userspace to vidioc_streamon handler
636  *
637  * Should be called from vidioc_streamon handler of a driver.
638  * This function:
639  * 1) verifies current state
640  * 2) passes any previously queued buffers to the driver and starts streaming
641  *
642  * The return values from this function are intended to be directly returned
643  * from vidioc_streamon handler in the driver.
644  */
645 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
646 {
647         if (vb2_fileio_is_active(q)) {
648                 dprintk(1, "file io in progress\n");
649                 return -EBUSY;
650         }
651         return vb2_core_streamon(q, type);
652 }
653 EXPORT_SYMBOL_GPL(vb2_streamon);
654
655 /**
656  * vb2_streamoff - stop streaming
657  * @q:          videobuf2 queue
658  * @type:       type argument passed from userspace to vidioc_streamoff handler
659  *
660  * Should be called from vidioc_streamoff handler of a driver.
661  * This function:
662  * 1) verifies current state,
663  * 2) stop streaming and dequeues any queued buffers, including those previously
664  *    passed to the driver (after waiting for the driver to finish).
665  *
666  * This call can be used for pausing playback.
667  * The return values from this function are intended to be directly returned
668  * from vidioc_streamoff handler in the driver
669  */
670 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
671 {
672         if (vb2_fileio_is_active(q)) {
673                 dprintk(1, "file io in progress\n");
674                 return -EBUSY;
675         }
676         return vb2_core_streamoff(q, type);
677 }
678 EXPORT_SYMBOL_GPL(vb2_streamoff);
679
680 /**
681  * vb2_expbuf() - Export a buffer as a file descriptor
682  * @q:          videobuf2 queue
683  * @eb:         export buffer structure passed from userspace to vidioc_expbuf
684  *              handler in driver
685  *
686  * The return values from this function are intended to be directly returned
687  * from vidioc_expbuf handler in driver.
688  */
689 int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
690 {
691         return vb2_core_expbuf(q, &eb->fd, eb->type, eb->index,
692                                 eb->plane, eb->flags);
693 }
694 EXPORT_SYMBOL_GPL(vb2_expbuf);
695
696 /**
697  * vb2_queue_init() - initialize a videobuf2 queue
698  * @q:          videobuf2 queue; this structure should be allocated in driver
699  *
700  * The vb2_queue structure should be allocated by the driver. The driver is
701  * responsible of clearing it's content and setting initial values for some
702  * required entries before calling this function.
703  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
704  * to the struct vb2_queue description in include/media/videobuf2-core.h
705  * for more information.
706  */
707 int vb2_queue_init(struct vb2_queue *q)
708 {
709         /*
710          * Sanity check
711          */
712         if (WARN_ON(!q)                   ||
713             WARN_ON(q->timestamp_flags &
714                     ~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
715                       V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
716                 return -EINVAL;
717
718         /* Warn that the driver should choose an appropriate timestamp type */
719         WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
720                 V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
721
722         /* Warn that vb2_memory should match with v4l2_memory */
723         if (WARN_ON(VB2_MEMORY_MMAP != (int)V4L2_MEMORY_MMAP)
724                 || WARN_ON(VB2_MEMORY_USERPTR != (int)V4L2_MEMORY_USERPTR)
725                 || WARN_ON(VB2_MEMORY_DMABUF != (int)V4L2_MEMORY_DMABUF))
726                 return -EINVAL;
727
728         if (q->buf_struct_size == 0)
729                 q->buf_struct_size = sizeof(struct vb2_v4l2_buffer);
730
731         q->buf_ops = &v4l2_buf_ops;
732         q->is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
733         q->is_output = V4L2_TYPE_IS_OUTPUT(q->type);
734
735         return vb2_core_queue_init(q);
736 }
737 EXPORT_SYMBOL_GPL(vb2_queue_init);
738
739 static int __vb2_init_fileio(struct vb2_queue *q, int read);
740 static int __vb2_cleanup_fileio(struct vb2_queue *q);
741
742 /**
743  * vb2_queue_release() - stop streaming, release the queue and free memory
744  * @q:          videobuf2 queue
745  *
746  * This function stops streaming and performs necessary clean ups, including
747  * freeing video buffer memory. The driver is responsible for freeing
748  * the vb2_queue structure itself.
749  */
750 void vb2_queue_release(struct vb2_queue *q)
751 {
752         __vb2_cleanup_fileio(q);
753         vb2_core_queue_release(q);
754 }
755 EXPORT_SYMBOL_GPL(vb2_queue_release);
756
757 /**
758  * vb2_poll() - implements poll userspace operation
759  * @q:          videobuf2 queue
760  * @file:       file argument passed to the poll file operation handler
761  * @wait:       wait argument passed to the poll file operation handler
762  *
763  * This function implements poll file operation handler for a driver.
764  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
765  * be informed that the file descriptor of a video device is available for
766  * reading.
767  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
768  * will be reported as available for writing.
769  *
770  * If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
771  * pending events.
772  *
773  * The return values from this function are intended to be directly returned
774  * from poll handler in driver.
775  */
776 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
777 {
778         struct video_device *vfd = video_devdata(file);
779         unsigned long req_events = poll_requested_events(wait);
780         struct vb2_buffer *vb = NULL;
781         unsigned int res = 0;
782         unsigned long flags;
783
784         if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
785                 struct v4l2_fh *fh = file->private_data;
786
787                 if (v4l2_event_pending(fh))
788                         res = POLLPRI;
789                 else if (req_events & POLLPRI)
790                         poll_wait(file, &fh->wait, wait);
791         }
792
793         if (!q->is_output && !(req_events & (POLLIN | POLLRDNORM)))
794                 return res;
795         if (q->is_output && !(req_events & (POLLOUT | POLLWRNORM)))
796                 return res;
797
798         /*
799          * Start file I/O emulator only if streaming API has not been used yet.
800          */
801         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
802                 if (!q->is_output && (q->io_modes & VB2_READ) &&
803                                 (req_events & (POLLIN | POLLRDNORM))) {
804                         if (__vb2_init_fileio(q, 1))
805                                 return res | POLLERR;
806                 }
807                 if (q->is_output && (q->io_modes & VB2_WRITE) &&
808                                 (req_events & (POLLOUT | POLLWRNORM))) {
809                         if (__vb2_init_fileio(q, 0))
810                                 return res | POLLERR;
811                         /*
812                          * Write to OUTPUT queue can be done immediately.
813                          */
814                         return res | POLLOUT | POLLWRNORM;
815                 }
816         }
817
818         /*
819          * There is nothing to wait for if the queue isn't streaming, or if the
820          * error flag is set.
821          */
822         if (!vb2_is_streaming(q) || q->error)
823                 return res | POLLERR;
824         /*
825          * For compatibility with vb1: if QBUF hasn't been called yet, then
826          * return POLLERR as well. This only affects capture queues, output
827          * queues will always initialize waiting_for_buffers to false.
828          */
829         if (q->waiting_for_buffers)
830                 return res | POLLERR;
831
832         /*
833          * For output streams you can call write() as long as there are fewer
834          * buffers queued than there are buffers available.
835          */
836         if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
837                 return res | POLLOUT | POLLWRNORM;
838
839         if (list_empty(&q->done_list)) {
840                 /*
841                  * If the last buffer was dequeued from a capture queue,
842                  * return immediately. DQBUF will return -EPIPE.
843                  */
844                 if (q->last_buffer_dequeued)
845                         return res | POLLIN | POLLRDNORM;
846
847                 poll_wait(file, &q->done_wq, wait);
848         }
849
850         /*
851          * Take first buffer available for dequeuing.
852          */
853         spin_lock_irqsave(&q->done_lock, flags);
854         if (!list_empty(&q->done_list))
855                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
856                                         done_entry);
857         spin_unlock_irqrestore(&q->done_lock, flags);
858
859         if (vb && (vb->state == VB2_BUF_STATE_DONE
860                         || vb->state == VB2_BUF_STATE_ERROR)) {
861                 return (q->is_output) ?
862                                 res | POLLOUT | POLLWRNORM :
863                                 res | POLLIN | POLLRDNORM;
864         }
865         return res;
866 }
867 EXPORT_SYMBOL_GPL(vb2_poll);
868
869 /**
870  * struct vb2_fileio_buf - buffer context used by file io emulator
871  *
872  * vb2 provides a compatibility layer and emulator of file io (read and
873  * write) calls on top of streaming API. This structure is used for
874  * tracking context related to the buffers.
875  */
876 struct vb2_fileio_buf {
877         void *vaddr;
878         unsigned int size;
879         unsigned int pos;
880         unsigned int queued:1;
881 };
882
883 /**
884  * struct vb2_fileio_data - queue context used by file io emulator
885  *
886  * @cur_index:  the index of the buffer currently being read from or
887  *              written to. If equal to q->num_buffers then a new buffer
888  *              must be dequeued.
889  * @initial_index: in the read() case all buffers are queued up immediately
890  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
891  *              buffers. However, in the write() case no buffers are initially
892  *              queued, instead whenever a buffer is full it is queued up by
893  *              __vb2_perform_fileio(). Only once all available buffers have
894  *              been queued up will __vb2_perform_fileio() start to dequeue
895  *              buffers. This means that initially __vb2_perform_fileio()
896  *              needs to know what buffer index to use when it is queuing up
897  *              the buffers for the first time. That initial index is stored
898  *              in this field. Once it is equal to q->num_buffers all
899  *              available buffers have been queued and __vb2_perform_fileio()
900  *              should start the normal dequeue/queue cycle.
901  *
902  * vb2 provides a compatibility layer and emulator of file io (read and
903  * write) calls on top of streaming API. For proper operation it required
904  * this structure to save the driver state between each call of the read
905  * or write function.
906  */
907 struct vb2_fileio_data {
908         struct v4l2_requestbuffers req;
909         struct v4l2_plane p;
910         struct v4l2_buffer b;
911         struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
912         unsigned int cur_index;
913         unsigned int initial_index;
914         unsigned int q_count;
915         unsigned int dq_count;
916         unsigned read_once:1;
917         unsigned write_immediately:1;
918 };
919
920 /**
921  * __vb2_init_fileio() - initialize file io emulator
922  * @q:          videobuf2 queue
923  * @read:       mode selector (1 means read, 0 means write)
924  */
925 static int __vb2_init_fileio(struct vb2_queue *q, int read)
926 {
927         struct vb2_fileio_data *fileio;
928         int i, ret;
929         unsigned int count = 0;
930
931         /*
932          * Sanity check
933          */
934         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
935                     (!read && !(q->io_modes & VB2_WRITE))))
936                 return -EINVAL;
937
938         /*
939          * Check if device supports mapping buffers to kernel virtual space.
940          */
941         if (!q->mem_ops->vaddr)
942                 return -EBUSY;
943
944         /*
945          * Check if streaming api has not been already activated.
946          */
947         if (q->streaming || q->num_buffers > 0)
948                 return -EBUSY;
949
950         /*
951          * Start with count 1, driver can increase it in queue_setup()
952          */
953         count = 1;
954
955         dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
956                 (read) ? "read" : "write", count, q->fileio_read_once,
957                 q->fileio_write_immediately);
958
959         fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
960         if (fileio == NULL)
961                 return -ENOMEM;
962
963         fileio->read_once = q->fileio_read_once;
964         fileio->write_immediately = q->fileio_write_immediately;
965
966         /*
967          * Request buffers and use MMAP type to force driver
968          * to allocate buffers by itself.
969          */
970         fileio->req.count = count;
971         fileio->req.memory = VB2_MEMORY_MMAP;
972         fileio->req.type = q->type;
973         q->fileio = fileio;
974         ret = vb2_core_reqbufs(q, fileio->req.memory, &fileio->req.count);
975         if (ret)
976                 goto err_kfree;
977
978         /*
979          * Check if plane_count is correct
980          * (multiplane buffers are not supported).
981          */
982         if (q->bufs[0]->num_planes != 1) {
983                 ret = -EBUSY;
984                 goto err_reqbufs;
985         }
986
987         /*
988          * Get kernel address of each buffer.
989          */
990         for (i = 0; i < q->num_buffers; i++) {
991                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
992                 if (fileio->bufs[i].vaddr == NULL) {
993                         ret = -EINVAL;
994                         goto err_reqbufs;
995                 }
996                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
997         }
998
999         /*
1000          * Read mode requires pre queuing of all buffers.
1001          */
1002         if (read) {
1003                 bool is_multiplanar = q->is_multiplanar;
1004
1005                 /*
1006                  * Queue all buffers.
1007                  */
1008                 for (i = 0; i < q->num_buffers; i++) {
1009                         struct v4l2_buffer *b = &fileio->b;
1010
1011                         memset(b, 0, sizeof(*b));
1012                         b->type = q->type;
1013                         if (is_multiplanar) {
1014                                 memset(&fileio->p, 0, sizeof(fileio->p));
1015                                 b->m.planes = &fileio->p;
1016                                 b->length = 1;
1017                         }
1018                         b->memory = q->memory;
1019                         b->index = i;
1020                         ret = vb2_internal_qbuf(q, b);
1021                         if (ret)
1022                                 goto err_reqbufs;
1023                         fileio->bufs[i].queued = 1;
1024                 }
1025                 /*
1026                  * All buffers have been queued, so mark that by setting
1027                  * initial_index to q->num_buffers
1028                  */
1029                 fileio->initial_index = q->num_buffers;
1030                 fileio->cur_index = q->num_buffers;
1031         }
1032
1033         /*
1034          * Start streaming.
1035          */
1036         ret = vb2_core_streamon(q, q->type);
1037         if (ret)
1038                 goto err_reqbufs;
1039
1040         return ret;
1041
1042 err_reqbufs:
1043         fileio->req.count = 0;
1044         vb2_core_reqbufs(q, fileio->req.memory, &fileio->req.count);
1045
1046 err_kfree:
1047         q->fileio = NULL;
1048         kfree(fileio);
1049         return ret;
1050 }
1051
1052 /**
1053  * __vb2_cleanup_fileio() - free resourced used by file io emulator
1054  * @q:          videobuf2 queue
1055  */
1056 static int __vb2_cleanup_fileio(struct vb2_queue *q)
1057 {
1058         struct vb2_fileio_data *fileio = q->fileio;
1059
1060         if (fileio) {
1061                 vb2_core_streamoff(q, q->type);
1062                 q->fileio = NULL;
1063                 fileio->req.count = 0;
1064                 vb2_reqbufs(q, &fileio->req);
1065                 kfree(fileio);
1066                 dprintk(3, "file io emulator closed\n");
1067         }
1068         return 0;
1069 }
1070
1071 /**
1072  * __vb2_perform_fileio() - perform a single file io (read or write) operation
1073  * @q:          videobuf2 queue
1074  * @data:       pointed to target userspace buffer
1075  * @count:      number of bytes to read or write
1076  * @ppos:       file handle position tracking pointer
1077  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
1078  * @read:       access mode selector (1 means read, 0 means write)
1079  */
1080 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
1081                 loff_t *ppos, int nonblock, int read)
1082 {
1083         struct vb2_fileio_data *fileio;
1084         struct vb2_fileio_buf *buf;
1085         bool is_multiplanar = q->is_multiplanar;
1086         /*
1087          * When using write() to write data to an output video node the vb2 core
1088          * should set timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
1089          * else is able to provide this information with the write() operation.
1090          */
1091         bool set_timestamp = !read &&
1092                 (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
1093                 V4L2_BUF_FLAG_TIMESTAMP_COPY;
1094         int ret, index;
1095
1096         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
1097                 read ? "read" : "write", (long)*ppos, count,
1098                 nonblock ? "non" : "");
1099
1100         if (!data)
1101                 return -EINVAL;
1102
1103         /*
1104          * Initialize emulator on first call.
1105          */
1106         if (!vb2_fileio_is_active(q)) {
1107                 ret = __vb2_init_fileio(q, read);
1108                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
1109                 if (ret)
1110                         return ret;
1111         }
1112         fileio = q->fileio;
1113
1114         /*
1115          * Check if we need to dequeue the buffer.
1116          */
1117         index = fileio->cur_index;
1118         if (index >= q->num_buffers) {
1119                 /*
1120                  * Call vb2_dqbuf to get buffer back.
1121                  */
1122                 memset(&fileio->b, 0, sizeof(fileio->b));
1123                 fileio->b.type = q->type;
1124                 fileio->b.memory = q->memory;
1125                 if (is_multiplanar) {
1126                         memset(&fileio->p, 0, sizeof(fileio->p));
1127                         fileio->b.m.planes = &fileio->p;
1128                         fileio->b.length = 1;
1129                 }
1130                 ret = vb2_internal_dqbuf(q, &fileio->b, nonblock);
1131                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
1132                 if (ret)
1133                         return ret;
1134                 fileio->dq_count += 1;
1135
1136                 fileio->cur_index = index = fileio->b.index;
1137                 buf = &fileio->bufs[index];
1138
1139                 /*
1140                  * Get number of bytes filled by the driver
1141                  */
1142                 buf->pos = 0;
1143                 buf->queued = 0;
1144                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
1145                                  : vb2_plane_size(q->bufs[index], 0);
1146                 /* Compensate for data_offset on read in the multiplanar case. */
1147                 if (is_multiplanar && read &&
1148                     fileio->b.m.planes[0].data_offset < buf->size) {
1149                         buf->pos = fileio->b.m.planes[0].data_offset;
1150                         buf->size -= buf->pos;
1151                 }
1152         } else {
1153                 buf = &fileio->bufs[index];
1154         }
1155
1156         /*
1157          * Limit count on last few bytes of the buffer.
1158          */
1159         if (buf->pos + count > buf->size) {
1160                 count = buf->size - buf->pos;
1161                 dprintk(5, "reducing read count: %zd\n", count);
1162         }
1163
1164         /*
1165          * Transfer data to userspace.
1166          */
1167         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
1168                 count, index, buf->pos);
1169         if (read)
1170                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
1171         else
1172                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
1173         if (ret) {
1174                 dprintk(3, "error copying data\n");
1175                 return -EFAULT;
1176         }
1177
1178         /*
1179          * Update counters.
1180          */
1181         buf->pos += count;
1182         *ppos += count;
1183
1184         /*
1185          * Queue next buffer if required.
1186          */
1187         if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
1188                 /*
1189                  * Check if this is the last buffer to read.
1190                  */
1191                 if (read && fileio->read_once && fileio->dq_count == 1) {
1192                         dprintk(3, "read limit reached\n");
1193                         return __vb2_cleanup_fileio(q);
1194                 }
1195
1196                 /*
1197                  * Call vb2_qbuf and give buffer to the driver.
1198                  */
1199                 memset(&fileio->b, 0, sizeof(fileio->b));
1200                 fileio->b.type = q->type;
1201                 fileio->b.memory = q->memory;
1202                 fileio->b.index = index;
1203                 fileio->b.bytesused = buf->pos;
1204                 if (is_multiplanar) {
1205                         memset(&fileio->p, 0, sizeof(fileio->p));
1206                         fileio->p.bytesused = buf->pos;
1207                         fileio->b.m.planes = &fileio->p;
1208                         fileio->b.length = 1;
1209                 }
1210                 if (set_timestamp)
1211                         v4l2_get_timestamp(&fileio->b.timestamp);
1212                 ret = vb2_internal_qbuf(q, &fileio->b);
1213                 dprintk(5, "vb2_dbuf result: %d\n", ret);
1214                 if (ret)
1215                         return ret;
1216
1217                 /*
1218                  * Buffer has been queued, update the status
1219                  */
1220                 buf->pos = 0;
1221                 buf->queued = 1;
1222                 buf->size = vb2_plane_size(q->bufs[index], 0);
1223                 fileio->q_count += 1;
1224                 /*
1225                  * If we are queuing up buffers for the first time, then
1226                  * increase initial_index by one.
1227                  */
1228                 if (fileio->initial_index < q->num_buffers)
1229                         fileio->initial_index++;
1230                 /*
1231                  * The next buffer to use is either a buffer that's going to be
1232                  * queued for the first time (initial_index < q->num_buffers)
1233                  * or it is equal to q->num_buffers, meaning that the next
1234                  * time we need to dequeue a buffer since we've now queued up
1235                  * all the 'first time' buffers.
1236                  */
1237                 fileio->cur_index = fileio->initial_index;
1238         }
1239
1240         /*
1241          * Return proper number of bytes processed.
1242          */
1243         if (ret == 0)
1244                 ret = count;
1245         return ret;
1246 }
1247
1248 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
1249                 loff_t *ppos, int nonblocking)
1250 {
1251         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
1252 }
1253 EXPORT_SYMBOL_GPL(vb2_read);
1254
1255 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
1256                 loff_t *ppos, int nonblocking)
1257 {
1258         return __vb2_perform_fileio(q, (char __user *) data, count,
1259                                                         ppos, nonblocking, 0);
1260 }
1261 EXPORT_SYMBOL_GPL(vb2_write);
1262
1263 struct vb2_threadio_data {
1264         struct task_struct *thread;
1265         vb2_thread_fnc fnc;
1266         void *priv;
1267         bool stop;
1268 };
1269
1270 static int vb2_thread(void *data)
1271 {
1272         struct vb2_queue *q = data;
1273         struct vb2_threadio_data *threadio = q->threadio;
1274         struct vb2_fileio_data *fileio = q->fileio;
1275         bool set_timestamp = false;
1276         int prequeue = 0;
1277         int index = 0;
1278         int ret = 0;
1279
1280         if (q->is_output) {
1281                 prequeue = q->num_buffers;
1282                 set_timestamp =
1283                         (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
1284                         V4L2_BUF_FLAG_TIMESTAMP_COPY;
1285         }
1286
1287         set_freezable();
1288
1289         for (;;) {
1290                 struct vb2_buffer *vb;
1291
1292                 /*
1293                  * Call vb2_dqbuf to get buffer back.
1294                  */
1295                 memset(&fileio->b, 0, sizeof(fileio->b));
1296                 fileio->b.type = q->type;
1297                 fileio->b.memory = q->memory;
1298                 if (prequeue) {
1299                         fileio->b.index = index++;
1300                         prequeue--;
1301                 } else {
1302                         call_void_qop(q, wait_finish, q);
1303                         if (!threadio->stop)
1304                                 ret = vb2_internal_dqbuf(q, &fileio->b, 0);
1305                         call_void_qop(q, wait_prepare, q);
1306                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
1307                 }
1308                 if (ret || threadio->stop)
1309                         break;
1310                 try_to_freeze();
1311
1312                 vb = q->bufs[fileio->b.index];
1313                 if (!(fileio->b.flags & V4L2_BUF_FLAG_ERROR))
1314                         if (threadio->fnc(vb, threadio->priv))
1315                                 break;
1316                 call_void_qop(q, wait_finish, q);
1317                 if (set_timestamp)
1318                         v4l2_get_timestamp(&fileio->b.timestamp);
1319                 if (!threadio->stop)
1320                         ret = vb2_internal_qbuf(q, &fileio->b);
1321                 call_void_qop(q, wait_prepare, q);
1322                 if (ret || threadio->stop)
1323                         break;
1324         }
1325
1326         /* Hmm, linux becomes *very* unhappy without this ... */
1327         while (!kthread_should_stop()) {
1328                 set_current_state(TASK_INTERRUPTIBLE);
1329                 schedule();
1330         }
1331         return 0;
1332 }
1333
1334 /*
1335  * This function should not be used for anything else but the videobuf2-dvb
1336  * support. If you think you have another good use-case for this, then please
1337  * contact the linux-media mailinglist first.
1338  */
1339 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
1340                      const char *thread_name)
1341 {
1342         struct vb2_threadio_data *threadio;
1343         int ret = 0;
1344
1345         if (q->threadio)
1346                 return -EBUSY;
1347         if (vb2_is_busy(q))
1348                 return -EBUSY;
1349         if (WARN_ON(q->fileio))
1350                 return -EBUSY;
1351
1352         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
1353         if (threadio == NULL)
1354                 return -ENOMEM;
1355         threadio->fnc = fnc;
1356         threadio->priv = priv;
1357
1358         ret = __vb2_init_fileio(q, !q->is_output);
1359         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
1360         if (ret)
1361                 goto nomem;
1362         q->threadio = threadio;
1363         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
1364         if (IS_ERR(threadio->thread)) {
1365                 ret = PTR_ERR(threadio->thread);
1366                 threadio->thread = NULL;
1367                 goto nothread;
1368         }
1369         return 0;
1370
1371 nothread:
1372         __vb2_cleanup_fileio(q);
1373 nomem:
1374         kfree(threadio);
1375         return ret;
1376 }
1377 EXPORT_SYMBOL_GPL(vb2_thread_start);
1378
1379 int vb2_thread_stop(struct vb2_queue *q)
1380 {
1381         struct vb2_threadio_data *threadio = q->threadio;
1382         int err;
1383
1384         if (threadio == NULL)
1385                 return 0;
1386         threadio->stop = true;
1387         /* Wake up all pending sleeps in the thread */
1388         vb2_queue_error(q);
1389         err = kthread_stop(threadio->thread);
1390         __vb2_cleanup_fileio(q);
1391         threadio->thread = NULL;
1392         kfree(threadio);
1393         q->threadio = NULL;
1394         return err;
1395 }
1396 EXPORT_SYMBOL_GPL(vb2_thread_stop);
1397
1398 /*
1399  * The following functions are not part of the vb2 core API, but are helper
1400  * functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
1401  * and struct vb2_ops.
1402  * They contain boilerplate code that most if not all drivers have to do
1403  * and so they simplify the driver code.
1404  */
1405
1406 /* The queue is busy if there is a owner and you are not that owner. */
1407 static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
1408 {
1409         return vdev->queue->owner && vdev->queue->owner != file->private_data;
1410 }
1411
1412 /* vb2 ioctl helpers */
1413
1414 int vb2_ioctl_reqbufs(struct file *file, void *priv,
1415                           struct v4l2_requestbuffers *p)
1416 {
1417         struct video_device *vdev = video_devdata(file);
1418         int res = vb2_verify_memory_type(vdev->queue, p->memory, p->type);
1419
1420         if (res)
1421                 return res;
1422         if (vb2_queue_is_busy(vdev, file))
1423                 return -EBUSY;
1424         res = vb2_core_reqbufs(vdev->queue, p->memory, &p->count);
1425         /* If count == 0, then the owner has released all buffers and he
1426            is no longer owner of the queue. Otherwise we have a new owner. */
1427         if (res == 0)
1428                 vdev->queue->owner = p->count ? file->private_data : NULL;
1429         return res;
1430 }
1431 EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);
1432
1433 int vb2_ioctl_create_bufs(struct file *file, void *priv,
1434                           struct v4l2_create_buffers *p)
1435 {
1436         struct video_device *vdev = video_devdata(file);
1437         int res = vb2_verify_memory_type(vdev->queue, p->memory,
1438                         p->format.type);
1439
1440         p->index = vdev->queue->num_buffers;
1441         /*
1442          * If count == 0, then just check if memory and type are valid.
1443          * Any -EBUSY result from vb2_verify_memory_type can be mapped to 0.
1444          */
1445         if (p->count == 0)
1446                 return res != -EBUSY ? res : 0;
1447         if (res)
1448                 return res;
1449         if (vb2_queue_is_busy(vdev, file))
1450                 return -EBUSY;
1451         res = vb2_core_create_bufs(vdev->queue, p->memory, &p->count,
1452                         &p->format);
1453         if (res == 0)
1454                 vdev->queue->owner = file->private_data;
1455         return res;
1456 }
1457 EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);
1458
1459 int vb2_ioctl_prepare_buf(struct file *file, void *priv,
1460                           struct v4l2_buffer *p)
1461 {
1462         struct video_device *vdev = video_devdata(file);
1463
1464         if (vb2_queue_is_busy(vdev, file))
1465                 return -EBUSY;
1466         return vb2_prepare_buf(vdev->queue, p);
1467 }
1468 EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);
1469
1470 int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
1471 {
1472         struct video_device *vdev = video_devdata(file);
1473
1474         /* No need to call vb2_queue_is_busy(), anyone can query buffers. */
1475         return vb2_querybuf(vdev->queue, p);
1476 }
1477 EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);
1478
1479 int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1480 {
1481         struct video_device *vdev = video_devdata(file);
1482
1483         if (vb2_queue_is_busy(vdev, file))
1484                 return -EBUSY;
1485         return vb2_qbuf(vdev->queue, p);
1486 }
1487 EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);
1488
1489 int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1490 {
1491         struct video_device *vdev = video_devdata(file);
1492
1493         if (vb2_queue_is_busy(vdev, file))
1494                 return -EBUSY;
1495         return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
1496 }
1497 EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);
1498
1499 int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
1500 {
1501         struct video_device *vdev = video_devdata(file);
1502
1503         if (vb2_queue_is_busy(vdev, file))
1504                 return -EBUSY;
1505         return vb2_streamon(vdev->queue, i);
1506 }
1507 EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);
1508
1509 int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1510 {
1511         struct video_device *vdev = video_devdata(file);
1512
1513         if (vb2_queue_is_busy(vdev, file))
1514                 return -EBUSY;
1515         return vb2_streamoff(vdev->queue, i);
1516 }
1517 EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);
1518
1519 int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
1520 {
1521         struct video_device *vdev = video_devdata(file);
1522
1523         if (vb2_queue_is_busy(vdev, file))
1524                 return -EBUSY;
1525         return vb2_expbuf(vdev->queue, p);
1526 }
1527 EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);
1528
1529 /* v4l2_file_operations helpers */
1530
1531 int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
1532 {
1533         struct video_device *vdev = video_devdata(file);
1534
1535         return vb2_mmap(vdev->queue, vma);
1536 }
1537 EXPORT_SYMBOL_GPL(vb2_fop_mmap);
1538
1539 int _vb2_fop_release(struct file *file, struct mutex *lock)
1540 {
1541         struct video_device *vdev = video_devdata(file);
1542
1543         if (lock)
1544                 mutex_lock(lock);
1545         if (file->private_data == vdev->queue->owner) {
1546                 vb2_queue_release(vdev->queue);
1547                 vdev->queue->owner = NULL;
1548         }
1549         if (lock)
1550                 mutex_unlock(lock);
1551         return v4l2_fh_release(file);
1552 }
1553 EXPORT_SYMBOL_GPL(_vb2_fop_release);
1554
1555 int vb2_fop_release(struct file *file)
1556 {
1557         struct video_device *vdev = video_devdata(file);
1558         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1559
1560         return _vb2_fop_release(file, lock);
1561 }
1562 EXPORT_SYMBOL_GPL(vb2_fop_release);
1563
1564 ssize_t vb2_fop_write(struct file *file, const char __user *buf,
1565                 size_t count, loff_t *ppos)
1566 {
1567         struct video_device *vdev = video_devdata(file);
1568         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1569         int err = -EBUSY;
1570
1571         if (!(vdev->queue->io_modes & VB2_WRITE))
1572                 return -EINVAL;
1573         if (lock && mutex_lock_interruptible(lock))
1574                 return -ERESTARTSYS;
1575         if (vb2_queue_is_busy(vdev, file))
1576                 goto exit;
1577         err = vb2_write(vdev->queue, buf, count, ppos,
1578                        file->f_flags & O_NONBLOCK);
1579         if (vdev->queue->fileio)
1580                 vdev->queue->owner = file->private_data;
1581 exit:
1582         if (lock)
1583                 mutex_unlock(lock);
1584         return err;
1585 }
1586 EXPORT_SYMBOL_GPL(vb2_fop_write);
1587
1588 ssize_t vb2_fop_read(struct file *file, char __user *buf,
1589                 size_t count, loff_t *ppos)
1590 {
1591         struct video_device *vdev = video_devdata(file);
1592         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1593         int err = -EBUSY;
1594
1595         if (!(vdev->queue->io_modes & VB2_READ))
1596                 return -EINVAL;
1597         if (lock && mutex_lock_interruptible(lock))
1598                 return -ERESTARTSYS;
1599         if (vb2_queue_is_busy(vdev, file))
1600                 goto exit;
1601         err = vb2_read(vdev->queue, buf, count, ppos,
1602                        file->f_flags & O_NONBLOCK);
1603         if (vdev->queue->fileio)
1604                 vdev->queue->owner = file->private_data;
1605 exit:
1606         if (lock)
1607                 mutex_unlock(lock);
1608         return err;
1609 }
1610 EXPORT_SYMBOL_GPL(vb2_fop_read);
1611
1612 unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
1613 {
1614         struct video_device *vdev = video_devdata(file);
1615         struct vb2_queue *q = vdev->queue;
1616         struct mutex *lock = q->lock ? q->lock : vdev->lock;
1617         unsigned res;
1618         void *fileio;
1619
1620         /*
1621          * If this helper doesn't know how to lock, then you shouldn't be using
1622          * it but you should write your own.
1623          */
1624         WARN_ON(!lock);
1625
1626         if (lock && mutex_lock_interruptible(lock))
1627                 return POLLERR;
1628
1629         fileio = q->fileio;
1630
1631         res = vb2_poll(vdev->queue, file, wait);
1632
1633         /* If fileio was started, then we have a new queue owner. */
1634         if (!fileio && q->fileio)
1635                 q->owner = file->private_data;
1636         if (lock)
1637                 mutex_unlock(lock);
1638         return res;
1639 }
1640 EXPORT_SYMBOL_GPL(vb2_fop_poll);
1641
1642 #ifndef CONFIG_MMU
1643 unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
1644                 unsigned long len, unsigned long pgoff, unsigned long flags)
1645 {
1646         struct video_device *vdev = video_devdata(file);
1647
1648         return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
1649 }
1650 EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
1651 #endif
1652
1653 /* vb2_ops helpers. Only use if vq->lock is non-NULL. */
1654
1655 void vb2_ops_wait_prepare(struct vb2_queue *vq)
1656 {
1657         mutex_unlock(vq->lock);
1658 }
1659 EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);
1660
1661 void vb2_ops_wait_finish(struct vb2_queue *vq)
1662 {
1663         mutex_lock(vq->lock);
1664 }
1665 EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);
1666
1667 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
1668 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
1669 MODULE_LICENSE("GPL");