Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / 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->reserved2 = 0;
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         if (V4L2_TYPE_IS_OUTPUT(b->type)) {
423                 /*
424                  * For output buffers mask out the timecode flag:
425                  * this will be handled later in vb2_internal_qbuf().
426                  * The 'field' is valid metadata for this output buffer
427                  * and so that needs to be copied here.
428                  */
429                 vbuf->flags &= ~V4L2_BUF_FLAG_TIMECODE;
430                 vbuf->field = b->field;
431         } else {
432                 /* Zero any output buffer flags as this is a capture buffer */
433                 vbuf->flags &= ~V4L2_BUFFER_OUT_FLAGS;
434         }
435
436         return 0;
437 }
438
439 static const struct vb2_buf_ops v4l2_buf_ops = {
440         .verify_planes_array    = __verify_planes_array_core,
441         .fill_user_buffer       = __fill_v4l2_buffer,
442         .fill_vb2_buffer        = __fill_vb2_buffer,
443         .set_timestamp          = __set_timestamp,
444 };
445
446 /**
447  * vb2_querybuf() - query video buffer information
448  * @q:          videobuf queue
449  * @b:          buffer struct passed from userspace to vidioc_querybuf handler
450  *              in driver
451  *
452  * Should be called from vidioc_querybuf ioctl handler in driver.
453  * This function will verify the passed v4l2_buffer structure and fill the
454  * relevant information for the userspace.
455  *
456  * The return values from this function are intended to be directly returned
457  * from vidioc_querybuf handler in driver.
458  */
459 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
460 {
461         struct vb2_buffer *vb;
462         int ret;
463
464         if (b->type != q->type) {
465                 dprintk(1, "wrong buffer type\n");
466                 return -EINVAL;
467         }
468
469         if (b->index >= q->num_buffers) {
470                 dprintk(1, "buffer index out of range\n");
471                 return -EINVAL;
472         }
473         vb = q->bufs[b->index];
474         ret = __verify_planes_array(vb, b);
475
476         return ret ? ret : vb2_core_querybuf(q, b->index, b);
477 }
478 EXPORT_SYMBOL(vb2_querybuf);
479
480 /**
481  * vb2_reqbufs() - Wrapper for vb2_core_reqbufs() that also verifies
482  * the memory and type values.
483  * @q:          videobuf2 queue
484  * @req:        struct passed from userspace to vidioc_reqbufs handler
485  *              in driver
486  */
487 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
488 {
489         int ret = vb2_verify_memory_type(q, req->memory, req->type);
490
491         return ret ? ret : vb2_core_reqbufs(q, req->memory, &req->count);
492 }
493 EXPORT_SYMBOL_GPL(vb2_reqbufs);
494
495 /**
496  * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
497  * @q:          videobuf2 queue
498  * @b:          buffer structure passed from userspace to vidioc_prepare_buf
499  *              handler in driver
500  *
501  * Should be called from vidioc_prepare_buf ioctl handler of a driver.
502  * This function:
503  * 1) verifies the passed buffer,
504  * 2) calls buf_prepare callback in the driver (if provided), in which
505  *    driver-specific buffer initialization can be performed,
506  *
507  * The return values from this function are intended to be directly returned
508  * from vidioc_prepare_buf handler in driver.
509  */
510 int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
511 {
512         int ret;
513
514         if (vb2_fileio_is_active(q)) {
515                 dprintk(1, "file io in progress\n");
516                 return -EBUSY;
517         }
518
519         ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
520
521         return ret ? ret : vb2_core_prepare_buf(q, b->index, b);
522 }
523 EXPORT_SYMBOL_GPL(vb2_prepare_buf);
524
525 /**
526  * vb2_create_bufs() - Wrapper for vb2_core_create_bufs() that also verifies
527  * the memory and type values.
528  * @q:          videobuf2 queue
529  * @create:     creation parameters, passed from userspace to vidioc_create_bufs
530  *              handler in driver
531  */
532 int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
533 {
534         int ret = vb2_verify_memory_type(q, create->memory,
535                         create->format.type);
536
537         create->index = q->num_buffers;
538         if (create->count == 0)
539                 return ret != -EBUSY ? ret : 0;
540         return ret ? ret : vb2_core_create_bufs(q, create->memory,
541                 &create->count, &create->format);
542 }
543 EXPORT_SYMBOL_GPL(vb2_create_bufs);
544
545 static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
546 {
547         int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
548
549         return ret ? ret : vb2_core_qbuf(q, b->index, b);
550 }
551
552 /**
553  * vb2_qbuf() - Queue a buffer from userspace
554  * @q:          videobuf2 queue
555  * @b:          buffer structure passed from userspace to vidioc_qbuf handler
556  *              in driver
557  *
558  * Should be called from vidioc_qbuf ioctl handler of a driver.
559  * This function:
560  * 1) verifies the passed buffer,
561  * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
562  *    which driver-specific buffer initialization can be performed,
563  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
564  *    callback for processing.
565  *
566  * The return values from this function are intended to be directly returned
567  * from vidioc_qbuf handler in driver.
568  */
569 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
570 {
571         if (vb2_fileio_is_active(q)) {
572                 dprintk(1, "file io in progress\n");
573                 return -EBUSY;
574         }
575
576         return vb2_internal_qbuf(q, b);
577 }
578 EXPORT_SYMBOL_GPL(vb2_qbuf);
579
580 static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b,
581                 bool nonblocking)
582 {
583         int ret;
584
585         if (b->type != q->type) {
586                 dprintk(1, "invalid buffer type\n");
587                 return -EINVAL;
588         }
589
590         ret = vb2_core_dqbuf(q, b, nonblocking);
591
592         if (!ret && !q->is_output &&
593                         b->flags & V4L2_BUF_FLAG_LAST)
594                 q->last_buffer_dequeued = true;
595
596         return ret;
597 }
598
599 /**
600  * vb2_dqbuf() - Dequeue a buffer to the userspace
601  * @q:          videobuf2 queue
602  * @b:          buffer structure passed from userspace to vidioc_dqbuf handler
603  *              in driver
604  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
605  *               buffers ready for dequeuing are present. Normally the driver
606  *               would be passing (file->f_flags & O_NONBLOCK) here
607  *
608  * Should be called from vidioc_dqbuf ioctl handler of a driver.
609  * This function:
610  * 1) verifies the passed buffer,
611  * 2) calls buf_finish callback in the driver (if provided), in which
612  *    driver can perform any additional operations that may be required before
613  *    returning the buffer to userspace, such as cache sync,
614  * 3) the buffer struct members are filled with relevant information for
615  *    the userspace.
616  *
617  * The return values from this function are intended to be directly returned
618  * from vidioc_dqbuf handler in driver.
619  */
620 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
621 {
622         if (vb2_fileio_is_active(q)) {
623                 dprintk(1, "file io in progress\n");
624                 return -EBUSY;
625         }
626         return vb2_internal_dqbuf(q, b, nonblocking);
627 }
628 EXPORT_SYMBOL_GPL(vb2_dqbuf);
629
630 /**
631  * vb2_streamon - start streaming
632  * @q:          videobuf2 queue
633  * @type:       type argument passed from userspace to vidioc_streamon handler
634  *
635  * Should be called from vidioc_streamon handler of a driver.
636  * This function:
637  * 1) verifies current state
638  * 2) passes any previously queued buffers to the driver and starts streaming
639  *
640  * The return values from this function are intended to be directly returned
641  * from vidioc_streamon handler in the driver.
642  */
643 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
644 {
645         if (vb2_fileio_is_active(q)) {
646                 dprintk(1, "file io in progress\n");
647                 return -EBUSY;
648         }
649         return vb2_core_streamon(q, type);
650 }
651 EXPORT_SYMBOL_GPL(vb2_streamon);
652
653 /**
654  * vb2_streamoff - stop streaming
655  * @q:          videobuf2 queue
656  * @type:       type argument passed from userspace to vidioc_streamoff handler
657  *
658  * Should be called from vidioc_streamoff handler of a driver.
659  * This function:
660  * 1) verifies current state,
661  * 2) stop streaming and dequeues any queued buffers, including those previously
662  *    passed to the driver (after waiting for the driver to finish).
663  *
664  * This call can be used for pausing playback.
665  * The return values from this function are intended to be directly returned
666  * from vidioc_streamoff handler in the driver
667  */
668 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
669 {
670         if (vb2_fileio_is_active(q)) {
671                 dprintk(1, "file io in progress\n");
672                 return -EBUSY;
673         }
674         return vb2_core_streamoff(q, type);
675 }
676 EXPORT_SYMBOL_GPL(vb2_streamoff);
677
678 /**
679  * vb2_expbuf() - Export a buffer as a file descriptor
680  * @q:          videobuf2 queue
681  * @eb:         export buffer structure passed from userspace to vidioc_expbuf
682  *              handler in driver
683  *
684  * The return values from this function are intended to be directly returned
685  * from vidioc_expbuf handler in driver.
686  */
687 int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
688 {
689         return vb2_core_expbuf(q, &eb->fd, eb->type, eb->index,
690                                 eb->plane, eb->flags);
691 }
692 EXPORT_SYMBOL_GPL(vb2_expbuf);
693
694 /**
695  * vb2_queue_init() - initialize a videobuf2 queue
696  * @q:          videobuf2 queue; this structure should be allocated in driver
697  *
698  * The vb2_queue structure should be allocated by the driver. The driver is
699  * responsible of clearing it's content and setting initial values for some
700  * required entries before calling this function.
701  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
702  * to the struct vb2_queue description in include/media/videobuf2-core.h
703  * for more information.
704  */
705 int vb2_queue_init(struct vb2_queue *q)
706 {
707         /*
708          * Sanity check
709          */
710         if (WARN_ON(!q)                   ||
711             WARN_ON(q->timestamp_flags &
712                     ~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
713                       V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
714                 return -EINVAL;
715
716         /* Warn that the driver should choose an appropriate timestamp type */
717         WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
718                 V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
719
720         /* Warn that vb2_memory should match with v4l2_memory */
721         if (WARN_ON(VB2_MEMORY_MMAP != (int)V4L2_MEMORY_MMAP)
722                 || WARN_ON(VB2_MEMORY_USERPTR != (int)V4L2_MEMORY_USERPTR)
723                 || WARN_ON(VB2_MEMORY_DMABUF != (int)V4L2_MEMORY_DMABUF))
724                 return -EINVAL;
725
726         if (q->buf_struct_size == 0)
727                 q->buf_struct_size = sizeof(struct vb2_v4l2_buffer);
728
729         q->buf_ops = &v4l2_buf_ops;
730         q->is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
731         q->is_output = V4L2_TYPE_IS_OUTPUT(q->type);
732
733         return vb2_core_queue_init(q);
734 }
735 EXPORT_SYMBOL_GPL(vb2_queue_init);
736
737 static int __vb2_init_fileio(struct vb2_queue *q, int read);
738 static int __vb2_cleanup_fileio(struct vb2_queue *q);
739
740 /**
741  * vb2_queue_release() - stop streaming, release the queue and free memory
742  * @q:          videobuf2 queue
743  *
744  * This function stops streaming and performs necessary clean ups, including
745  * freeing video buffer memory. The driver is responsible for freeing
746  * the vb2_queue structure itself.
747  */
748 void vb2_queue_release(struct vb2_queue *q)
749 {
750         __vb2_cleanup_fileio(q);
751         vb2_core_queue_release(q);
752 }
753 EXPORT_SYMBOL_GPL(vb2_queue_release);
754
755 /**
756  * vb2_poll() - implements poll userspace operation
757  * @q:          videobuf2 queue
758  * @file:       file argument passed to the poll file operation handler
759  * @wait:       wait argument passed to the poll file operation handler
760  *
761  * This function implements poll file operation handler for a driver.
762  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
763  * be informed that the file descriptor of a video device is available for
764  * reading.
765  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
766  * will be reported as available for writing.
767  *
768  * If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
769  * pending events.
770  *
771  * The return values from this function are intended to be directly returned
772  * from poll handler in driver.
773  */
774 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
775 {
776         struct video_device *vfd = video_devdata(file);
777         unsigned long req_events = poll_requested_events(wait);
778         struct vb2_buffer *vb = NULL;
779         unsigned int res = 0;
780         unsigned long flags;
781
782         if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
783                 struct v4l2_fh *fh = file->private_data;
784
785                 if (v4l2_event_pending(fh))
786                         res = POLLPRI;
787                 else if (req_events & POLLPRI)
788                         poll_wait(file, &fh->wait, wait);
789         }
790
791         if (!q->is_output && !(req_events & (POLLIN | POLLRDNORM)))
792                 return res;
793         if (q->is_output && !(req_events & (POLLOUT | POLLWRNORM)))
794                 return res;
795
796         /*
797          * Start file I/O emulator only if streaming API has not been used yet.
798          */
799         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
800                 if (!q->is_output && (q->io_modes & VB2_READ) &&
801                                 (req_events & (POLLIN | POLLRDNORM))) {
802                         if (__vb2_init_fileio(q, 1))
803                                 return res | POLLERR;
804                 }
805                 if (q->is_output && (q->io_modes & VB2_WRITE) &&
806                                 (req_events & (POLLOUT | POLLWRNORM))) {
807                         if (__vb2_init_fileio(q, 0))
808                                 return res | POLLERR;
809                         /*
810                          * Write to OUTPUT queue can be done immediately.
811                          */
812                         return res | POLLOUT | POLLWRNORM;
813                 }
814         }
815
816         /*
817          * There is nothing to wait for if the queue isn't streaming, or if the
818          * error flag is set.
819          */
820         if (!vb2_is_streaming(q) || q->error)
821                 return res | POLLERR;
822         /*
823          * For compatibility with vb1: if QBUF hasn't been called yet, then
824          * return POLLERR as well. This only affects capture queues, output
825          * queues will always initialize waiting_for_buffers to false.
826          */
827         if (q->waiting_for_buffers)
828                 return res | POLLERR;
829
830         /*
831          * For output streams you can call write() as long as there are fewer
832          * buffers queued than there are buffers available.
833          */
834         if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
835                 return res | POLLOUT | POLLWRNORM;
836
837         if (list_empty(&q->done_list)) {
838                 /*
839                  * If the last buffer was dequeued from a capture queue,
840                  * return immediately. DQBUF will return -EPIPE.
841                  */
842                 if (q->last_buffer_dequeued)
843                         return res | POLLIN | POLLRDNORM;
844
845                 poll_wait(file, &q->done_wq, wait);
846         }
847
848         /*
849          * Take first buffer available for dequeuing.
850          */
851         spin_lock_irqsave(&q->done_lock, flags);
852         if (!list_empty(&q->done_list))
853                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
854                                         done_entry);
855         spin_unlock_irqrestore(&q->done_lock, flags);
856
857         if (vb && (vb->state == VB2_BUF_STATE_DONE
858                         || vb->state == VB2_BUF_STATE_ERROR)) {
859                 return (q->is_output) ?
860                                 res | POLLOUT | POLLWRNORM :
861                                 res | POLLIN | POLLRDNORM;
862         }
863         return res;
864 }
865 EXPORT_SYMBOL_GPL(vb2_poll);
866
867 /**
868  * struct vb2_fileio_buf - buffer context used by file io emulator
869  *
870  * vb2 provides a compatibility layer and emulator of file io (read and
871  * write) calls on top of streaming API. This structure is used for
872  * tracking context related to the buffers.
873  */
874 struct vb2_fileio_buf {
875         void *vaddr;
876         unsigned int size;
877         unsigned int pos;
878         unsigned int queued:1;
879 };
880
881 /**
882  * struct vb2_fileio_data - queue context used by file io emulator
883  *
884  * @cur_index:  the index of the buffer currently being read from or
885  *              written to. If equal to q->num_buffers then a new buffer
886  *              must be dequeued.
887  * @initial_index: in the read() case all buffers are queued up immediately
888  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
889  *              buffers. However, in the write() case no buffers are initially
890  *              queued, instead whenever a buffer is full it is queued up by
891  *              __vb2_perform_fileio(). Only once all available buffers have
892  *              been queued up will __vb2_perform_fileio() start to dequeue
893  *              buffers. This means that initially __vb2_perform_fileio()
894  *              needs to know what buffer index to use when it is queuing up
895  *              the buffers for the first time. That initial index is stored
896  *              in this field. Once it is equal to q->num_buffers all
897  *              available buffers have been queued and __vb2_perform_fileio()
898  *              should start the normal dequeue/queue cycle.
899  *
900  * vb2 provides a compatibility layer and emulator of file io (read and
901  * write) calls on top of streaming API. For proper operation it required
902  * this structure to save the driver state between each call of the read
903  * or write function.
904  */
905 struct vb2_fileio_data {
906         struct v4l2_requestbuffers req;
907         struct v4l2_plane p;
908         struct v4l2_buffer b;
909         struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
910         unsigned int cur_index;
911         unsigned int initial_index;
912         unsigned int q_count;
913         unsigned int dq_count;
914         unsigned read_once:1;
915         unsigned write_immediately:1;
916 };
917
918 /**
919  * __vb2_init_fileio() - initialize file io emulator
920  * @q:          videobuf2 queue
921  * @read:       mode selector (1 means read, 0 means write)
922  */
923 static int __vb2_init_fileio(struct vb2_queue *q, int read)
924 {
925         struct vb2_fileio_data *fileio;
926         int i, ret;
927         unsigned int count = 0;
928
929         /*
930          * Sanity check
931          */
932         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
933                     (!read && !(q->io_modes & VB2_WRITE))))
934                 return -EINVAL;
935
936         /*
937          * Check if device supports mapping buffers to kernel virtual space.
938          */
939         if (!q->mem_ops->vaddr)
940                 return -EBUSY;
941
942         /*
943          * Check if streaming api has not been already activated.
944          */
945         if (q->streaming || q->num_buffers > 0)
946                 return -EBUSY;
947
948         /*
949          * Start with count 1, driver can increase it in queue_setup()
950          */
951         count = 1;
952
953         dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
954                 (read) ? "read" : "write", count, q->fileio_read_once,
955                 q->fileio_write_immediately);
956
957         fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
958         if (fileio == NULL)
959                 return -ENOMEM;
960
961         fileio->read_once = q->fileio_read_once;
962         fileio->write_immediately = q->fileio_write_immediately;
963
964         /*
965          * Request buffers and use MMAP type to force driver
966          * to allocate buffers by itself.
967          */
968         fileio->req.count = count;
969         fileio->req.memory = VB2_MEMORY_MMAP;
970         fileio->req.type = q->type;
971         q->fileio = fileio;
972         ret = vb2_core_reqbufs(q, fileio->req.memory, &fileio->req.count);
973         if (ret)
974                 goto err_kfree;
975
976         /*
977          * Check if plane_count is correct
978          * (multiplane buffers are not supported).
979          */
980         if (q->bufs[0]->num_planes != 1) {
981                 ret = -EBUSY;
982                 goto err_reqbufs;
983         }
984
985         /*
986          * Get kernel address of each buffer.
987          */
988         for (i = 0; i < q->num_buffers; i++) {
989                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
990                 if (fileio->bufs[i].vaddr == NULL) {
991                         ret = -EINVAL;
992                         goto err_reqbufs;
993                 }
994                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
995         }
996
997         /*
998          * Read mode requires pre queuing of all buffers.
999          */
1000         if (read) {
1001                 bool is_multiplanar = q->is_multiplanar;
1002
1003                 /*
1004                  * Queue all buffers.
1005                  */
1006                 for (i = 0; i < q->num_buffers; i++) {
1007                         struct v4l2_buffer *b = &fileio->b;
1008
1009                         memset(b, 0, sizeof(*b));
1010                         b->type = q->type;
1011                         if (is_multiplanar) {
1012                                 memset(&fileio->p, 0, sizeof(fileio->p));
1013                                 b->m.planes = &fileio->p;
1014                                 b->length = 1;
1015                         }
1016                         b->memory = q->memory;
1017                         b->index = i;
1018                         ret = vb2_internal_qbuf(q, b);
1019                         if (ret)
1020                                 goto err_reqbufs;
1021                         fileio->bufs[i].queued = 1;
1022                 }
1023                 /*
1024                  * All buffers have been queued, so mark that by setting
1025                  * initial_index to q->num_buffers
1026                  */
1027                 fileio->initial_index = q->num_buffers;
1028                 fileio->cur_index = q->num_buffers;
1029         }
1030
1031         /*
1032          * Start streaming.
1033          */
1034         ret = vb2_core_streamon(q, q->type);
1035         if (ret)
1036                 goto err_reqbufs;
1037
1038         return ret;
1039
1040 err_reqbufs:
1041         fileio->req.count = 0;
1042         vb2_core_reqbufs(q, fileio->req.memory, &fileio->req.count);
1043
1044 err_kfree:
1045         q->fileio = NULL;
1046         kfree(fileio);
1047         return ret;
1048 }
1049
1050 /**
1051  * __vb2_cleanup_fileio() - free resourced used by file io emulator
1052  * @q:          videobuf2 queue
1053  */
1054 static int __vb2_cleanup_fileio(struct vb2_queue *q)
1055 {
1056         struct vb2_fileio_data *fileio = q->fileio;
1057
1058         if (fileio) {
1059                 vb2_core_streamoff(q, q->type);
1060                 q->fileio = NULL;
1061                 fileio->req.count = 0;
1062                 vb2_reqbufs(q, &fileio->req);
1063                 kfree(fileio);
1064                 dprintk(3, "file io emulator closed\n");
1065         }
1066         return 0;
1067 }
1068
1069 /**
1070  * __vb2_perform_fileio() - perform a single file io (read or write) operation
1071  * @q:          videobuf2 queue
1072  * @data:       pointed to target userspace buffer
1073  * @count:      number of bytes to read or write
1074  * @ppos:       file handle position tracking pointer
1075  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
1076  * @read:       access mode selector (1 means read, 0 means write)
1077  */
1078 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
1079                 loff_t *ppos, int nonblock, int read)
1080 {
1081         struct vb2_fileio_data *fileio;
1082         struct vb2_fileio_buf *buf;
1083         bool is_multiplanar = q->is_multiplanar;
1084         /*
1085          * When using write() to write data to an output video node the vb2 core
1086          * should set timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
1087          * else is able to provide this information with the write() operation.
1088          */
1089         bool set_timestamp = !read &&
1090                 (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
1091                 V4L2_BUF_FLAG_TIMESTAMP_COPY;
1092         int ret, index;
1093
1094         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
1095                 read ? "read" : "write", (long)*ppos, count,
1096                 nonblock ? "non" : "");
1097
1098         if (!data)
1099                 return -EINVAL;
1100
1101         /*
1102          * Initialize emulator on first call.
1103          */
1104         if (!vb2_fileio_is_active(q)) {
1105                 ret = __vb2_init_fileio(q, read);
1106                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
1107                 if (ret)
1108                         return ret;
1109         }
1110         fileio = q->fileio;
1111
1112         /*
1113          * Check if we need to dequeue the buffer.
1114          */
1115         index = fileio->cur_index;
1116         if (index >= q->num_buffers) {
1117                 /*
1118                  * Call vb2_dqbuf to get buffer back.
1119                  */
1120                 memset(&fileio->b, 0, sizeof(fileio->b));
1121                 fileio->b.type = q->type;
1122                 fileio->b.memory = q->memory;
1123                 if (is_multiplanar) {
1124                         memset(&fileio->p, 0, sizeof(fileio->p));
1125                         fileio->b.m.planes = &fileio->p;
1126                         fileio->b.length = 1;
1127                 }
1128                 ret = vb2_internal_dqbuf(q, &fileio->b, nonblock);
1129                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
1130                 if (ret)
1131                         return ret;
1132                 fileio->dq_count += 1;
1133
1134                 fileio->cur_index = index = fileio->b.index;
1135                 buf = &fileio->bufs[index];
1136
1137                 /*
1138                  * Get number of bytes filled by the driver
1139                  */
1140                 buf->pos = 0;
1141                 buf->queued = 0;
1142                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
1143                                  : vb2_plane_size(q->bufs[index], 0);
1144                 /* Compensate for data_offset on read in the multiplanar case. */
1145                 if (is_multiplanar && read &&
1146                     fileio->b.m.planes[0].data_offset < buf->size) {
1147                         buf->pos = fileio->b.m.planes[0].data_offset;
1148                         buf->size -= buf->pos;
1149                 }
1150         } else {
1151                 buf = &fileio->bufs[index];
1152         }
1153
1154         /*
1155          * Limit count on last few bytes of the buffer.
1156          */
1157         if (buf->pos + count > buf->size) {
1158                 count = buf->size - buf->pos;
1159                 dprintk(5, "reducing read count: %zd\n", count);
1160         }
1161
1162         /*
1163          * Transfer data to userspace.
1164          */
1165         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
1166                 count, index, buf->pos);
1167         if (read)
1168                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
1169         else
1170                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
1171         if (ret) {
1172                 dprintk(3, "error copying data\n");
1173                 return -EFAULT;
1174         }
1175
1176         /*
1177          * Update counters.
1178          */
1179         buf->pos += count;
1180         *ppos += count;
1181
1182         /*
1183          * Queue next buffer if required.
1184          */
1185         if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
1186                 /*
1187                  * Check if this is the last buffer to read.
1188                  */
1189                 if (read && fileio->read_once && fileio->dq_count == 1) {
1190                         dprintk(3, "read limit reached\n");
1191                         return __vb2_cleanup_fileio(q);
1192                 }
1193
1194                 /*
1195                  * Call vb2_qbuf and give buffer to the driver.
1196                  */
1197                 memset(&fileio->b, 0, sizeof(fileio->b));
1198                 fileio->b.type = q->type;
1199                 fileio->b.memory = q->memory;
1200                 fileio->b.index = index;
1201                 fileio->b.bytesused = buf->pos;
1202                 if (is_multiplanar) {
1203                         memset(&fileio->p, 0, sizeof(fileio->p));
1204                         fileio->p.bytesused = buf->pos;
1205                         fileio->b.m.planes = &fileio->p;
1206                         fileio->b.length = 1;
1207                 }
1208                 if (set_timestamp)
1209                         v4l2_get_timestamp(&fileio->b.timestamp);
1210                 ret = vb2_internal_qbuf(q, &fileio->b);
1211                 dprintk(5, "vb2_dbuf result: %d\n", ret);
1212                 if (ret)
1213                         return ret;
1214
1215                 /*
1216                  * Buffer has been queued, update the status
1217                  */
1218                 buf->pos = 0;
1219                 buf->queued = 1;
1220                 buf->size = vb2_plane_size(q->bufs[index], 0);
1221                 fileio->q_count += 1;
1222                 /*
1223                  * If we are queuing up buffers for the first time, then
1224                  * increase initial_index by one.
1225                  */
1226                 if (fileio->initial_index < q->num_buffers)
1227                         fileio->initial_index++;
1228                 /*
1229                  * The next buffer to use is either a buffer that's going to be
1230                  * queued for the first time (initial_index < q->num_buffers)
1231                  * or it is equal to q->num_buffers, meaning that the next
1232                  * time we need to dequeue a buffer since we've now queued up
1233                  * all the 'first time' buffers.
1234                  */
1235                 fileio->cur_index = fileio->initial_index;
1236         }
1237
1238         /*
1239          * Return proper number of bytes processed.
1240          */
1241         if (ret == 0)
1242                 ret = count;
1243         return ret;
1244 }
1245
1246 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
1247                 loff_t *ppos, int nonblocking)
1248 {
1249         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
1250 }
1251 EXPORT_SYMBOL_GPL(vb2_read);
1252
1253 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
1254                 loff_t *ppos, int nonblocking)
1255 {
1256         return __vb2_perform_fileio(q, (char __user *) data, count,
1257                                                         ppos, nonblocking, 0);
1258 }
1259 EXPORT_SYMBOL_GPL(vb2_write);
1260
1261 struct vb2_threadio_data {
1262         struct task_struct *thread;
1263         vb2_thread_fnc fnc;
1264         void *priv;
1265         bool stop;
1266 };
1267
1268 static int vb2_thread(void *data)
1269 {
1270         struct vb2_queue *q = data;
1271         struct vb2_threadio_data *threadio = q->threadio;
1272         struct vb2_fileio_data *fileio = q->fileio;
1273         bool set_timestamp = false;
1274         int prequeue = 0;
1275         int index = 0;
1276         int ret = 0;
1277
1278         if (q->is_output) {
1279                 prequeue = q->num_buffers;
1280                 set_timestamp =
1281                         (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
1282                         V4L2_BUF_FLAG_TIMESTAMP_COPY;
1283         }
1284
1285         set_freezable();
1286
1287         for (;;) {
1288                 struct vb2_buffer *vb;
1289
1290                 /*
1291                  * Call vb2_dqbuf to get buffer back.
1292                  */
1293                 memset(&fileio->b, 0, sizeof(fileio->b));
1294                 fileio->b.type = q->type;
1295                 fileio->b.memory = q->memory;
1296                 if (prequeue) {
1297                         fileio->b.index = index++;
1298                         prequeue--;
1299                 } else {
1300                         call_void_qop(q, wait_finish, q);
1301                         if (!threadio->stop)
1302                                 ret = vb2_internal_dqbuf(q, &fileio->b, 0);
1303                         call_void_qop(q, wait_prepare, q);
1304                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
1305                 }
1306                 if (ret || threadio->stop)
1307                         break;
1308                 try_to_freeze();
1309
1310                 vb = q->bufs[fileio->b.index];
1311                 if (!(fileio->b.flags & V4L2_BUF_FLAG_ERROR))
1312                         if (threadio->fnc(vb, threadio->priv))
1313                                 break;
1314                 call_void_qop(q, wait_finish, q);
1315                 if (set_timestamp)
1316                         v4l2_get_timestamp(&fileio->b.timestamp);
1317                 if (!threadio->stop)
1318                         ret = vb2_internal_qbuf(q, &fileio->b);
1319                 call_void_qop(q, wait_prepare, q);
1320                 if (ret || threadio->stop)
1321                         break;
1322         }
1323
1324         /* Hmm, linux becomes *very* unhappy without this ... */
1325         while (!kthread_should_stop()) {
1326                 set_current_state(TASK_INTERRUPTIBLE);
1327                 schedule();
1328         }
1329         return 0;
1330 }
1331
1332 /*
1333  * This function should not be used for anything else but the videobuf2-dvb
1334  * support. If you think you have another good use-case for this, then please
1335  * contact the linux-media mailinglist first.
1336  */
1337 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
1338                      const char *thread_name)
1339 {
1340         struct vb2_threadio_data *threadio;
1341         int ret = 0;
1342
1343         if (q->threadio)
1344                 return -EBUSY;
1345         if (vb2_is_busy(q))
1346                 return -EBUSY;
1347         if (WARN_ON(q->fileio))
1348                 return -EBUSY;
1349
1350         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
1351         if (threadio == NULL)
1352                 return -ENOMEM;
1353         threadio->fnc = fnc;
1354         threadio->priv = priv;
1355
1356         ret = __vb2_init_fileio(q, !q->is_output);
1357         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
1358         if (ret)
1359                 goto nomem;
1360         q->threadio = threadio;
1361         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
1362         if (IS_ERR(threadio->thread)) {
1363                 ret = PTR_ERR(threadio->thread);
1364                 threadio->thread = NULL;
1365                 goto nothread;
1366         }
1367         return 0;
1368
1369 nothread:
1370         __vb2_cleanup_fileio(q);
1371 nomem:
1372         kfree(threadio);
1373         return ret;
1374 }
1375 EXPORT_SYMBOL_GPL(vb2_thread_start);
1376
1377 int vb2_thread_stop(struct vb2_queue *q)
1378 {
1379         struct vb2_threadio_data *threadio = q->threadio;
1380         int err;
1381
1382         if (threadio == NULL)
1383                 return 0;
1384         threadio->stop = true;
1385         /* Wake up all pending sleeps in the thread */
1386         vb2_queue_error(q);
1387         err = kthread_stop(threadio->thread);
1388         __vb2_cleanup_fileio(q);
1389         threadio->thread = NULL;
1390         kfree(threadio);
1391         q->threadio = NULL;
1392         return err;
1393 }
1394 EXPORT_SYMBOL_GPL(vb2_thread_stop);
1395
1396 /*
1397  * The following functions are not part of the vb2 core API, but are helper
1398  * functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
1399  * and struct vb2_ops.
1400  * They contain boilerplate code that most if not all drivers have to do
1401  * and so they simplify the driver code.
1402  */
1403
1404 /* The queue is busy if there is a owner and you are not that owner. */
1405 static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
1406 {
1407         return vdev->queue->owner && vdev->queue->owner != file->private_data;
1408 }
1409
1410 /* vb2 ioctl helpers */
1411
1412 int vb2_ioctl_reqbufs(struct file *file, void *priv,
1413                           struct v4l2_requestbuffers *p)
1414 {
1415         struct video_device *vdev = video_devdata(file);
1416         int res = vb2_verify_memory_type(vdev->queue, p->memory, p->type);
1417
1418         if (res)
1419                 return res;
1420         if (vb2_queue_is_busy(vdev, file))
1421                 return -EBUSY;
1422         res = vb2_core_reqbufs(vdev->queue, p->memory, &p->count);
1423         /* If count == 0, then the owner has released all buffers and he
1424            is no longer owner of the queue. Otherwise we have a new owner. */
1425         if (res == 0)
1426                 vdev->queue->owner = p->count ? file->private_data : NULL;
1427         return res;
1428 }
1429 EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);
1430
1431 int vb2_ioctl_create_bufs(struct file *file, void *priv,
1432                           struct v4l2_create_buffers *p)
1433 {
1434         struct video_device *vdev = video_devdata(file);
1435         int res = vb2_verify_memory_type(vdev->queue, p->memory,
1436                         p->format.type);
1437
1438         p->index = vdev->queue->num_buffers;
1439         /*
1440          * If count == 0, then just check if memory and type are valid.
1441          * Any -EBUSY result from vb2_verify_memory_type can be mapped to 0.
1442          */
1443         if (p->count == 0)
1444                 return res != -EBUSY ? res : 0;
1445         if (res)
1446                 return res;
1447         if (vb2_queue_is_busy(vdev, file))
1448                 return -EBUSY;
1449         res = vb2_core_create_bufs(vdev->queue, p->memory, &p->count,
1450                         &p->format);
1451         if (res == 0)
1452                 vdev->queue->owner = file->private_data;
1453         return res;
1454 }
1455 EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);
1456
1457 int vb2_ioctl_prepare_buf(struct file *file, void *priv,
1458                           struct v4l2_buffer *p)
1459 {
1460         struct video_device *vdev = video_devdata(file);
1461
1462         if (vb2_queue_is_busy(vdev, file))
1463                 return -EBUSY;
1464         return vb2_prepare_buf(vdev->queue, p);
1465 }
1466 EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);
1467
1468 int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
1469 {
1470         struct video_device *vdev = video_devdata(file);
1471
1472         /* No need to call vb2_queue_is_busy(), anyone can query buffers. */
1473         return vb2_querybuf(vdev->queue, p);
1474 }
1475 EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);
1476
1477 int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1478 {
1479         struct video_device *vdev = video_devdata(file);
1480
1481         if (vb2_queue_is_busy(vdev, file))
1482                 return -EBUSY;
1483         return vb2_qbuf(vdev->queue, p);
1484 }
1485 EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);
1486
1487 int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1488 {
1489         struct video_device *vdev = video_devdata(file);
1490
1491         if (vb2_queue_is_busy(vdev, file))
1492                 return -EBUSY;
1493         return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
1494 }
1495 EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);
1496
1497 int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
1498 {
1499         struct video_device *vdev = video_devdata(file);
1500
1501         if (vb2_queue_is_busy(vdev, file))
1502                 return -EBUSY;
1503         return vb2_streamon(vdev->queue, i);
1504 }
1505 EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);
1506
1507 int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1508 {
1509         struct video_device *vdev = video_devdata(file);
1510
1511         if (vb2_queue_is_busy(vdev, file))
1512                 return -EBUSY;
1513         return vb2_streamoff(vdev->queue, i);
1514 }
1515 EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);
1516
1517 int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
1518 {
1519         struct video_device *vdev = video_devdata(file);
1520
1521         if (vb2_queue_is_busy(vdev, file))
1522                 return -EBUSY;
1523         return vb2_expbuf(vdev->queue, p);
1524 }
1525 EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);
1526
1527 /* v4l2_file_operations helpers */
1528
1529 int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
1530 {
1531         struct video_device *vdev = video_devdata(file);
1532
1533         return vb2_mmap(vdev->queue, vma);
1534 }
1535 EXPORT_SYMBOL_GPL(vb2_fop_mmap);
1536
1537 int _vb2_fop_release(struct file *file, struct mutex *lock)
1538 {
1539         struct video_device *vdev = video_devdata(file);
1540
1541         if (lock)
1542                 mutex_lock(lock);
1543         if (file->private_data == vdev->queue->owner) {
1544                 vb2_queue_release(vdev->queue);
1545                 vdev->queue->owner = NULL;
1546         }
1547         if (lock)
1548                 mutex_unlock(lock);
1549         return v4l2_fh_release(file);
1550 }
1551 EXPORT_SYMBOL_GPL(_vb2_fop_release);
1552
1553 int vb2_fop_release(struct file *file)
1554 {
1555         struct video_device *vdev = video_devdata(file);
1556         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1557
1558         return _vb2_fop_release(file, lock);
1559 }
1560 EXPORT_SYMBOL_GPL(vb2_fop_release);
1561
1562 ssize_t vb2_fop_write(struct file *file, const char __user *buf,
1563                 size_t count, loff_t *ppos)
1564 {
1565         struct video_device *vdev = video_devdata(file);
1566         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1567         int err = -EBUSY;
1568
1569         if (!(vdev->queue->io_modes & VB2_WRITE))
1570                 return -EINVAL;
1571         if (lock && mutex_lock_interruptible(lock))
1572                 return -ERESTARTSYS;
1573         if (vb2_queue_is_busy(vdev, file))
1574                 goto exit;
1575         err = vb2_write(vdev->queue, buf, count, ppos,
1576                        file->f_flags & O_NONBLOCK);
1577         if (vdev->queue->fileio)
1578                 vdev->queue->owner = file->private_data;
1579 exit:
1580         if (lock)
1581                 mutex_unlock(lock);
1582         return err;
1583 }
1584 EXPORT_SYMBOL_GPL(vb2_fop_write);
1585
1586 ssize_t vb2_fop_read(struct file *file, char __user *buf,
1587                 size_t count, loff_t *ppos)
1588 {
1589         struct video_device *vdev = video_devdata(file);
1590         struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
1591         int err = -EBUSY;
1592
1593         if (!(vdev->queue->io_modes & VB2_READ))
1594                 return -EINVAL;
1595         if (lock && mutex_lock_interruptible(lock))
1596                 return -ERESTARTSYS;
1597         if (vb2_queue_is_busy(vdev, file))
1598                 goto exit;
1599         err = vb2_read(vdev->queue, buf, count, ppos,
1600                        file->f_flags & O_NONBLOCK);
1601         if (vdev->queue->fileio)
1602                 vdev->queue->owner = file->private_data;
1603 exit:
1604         if (lock)
1605                 mutex_unlock(lock);
1606         return err;
1607 }
1608 EXPORT_SYMBOL_GPL(vb2_fop_read);
1609
1610 unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
1611 {
1612         struct video_device *vdev = video_devdata(file);
1613         struct vb2_queue *q = vdev->queue;
1614         struct mutex *lock = q->lock ? q->lock : vdev->lock;
1615         unsigned res;
1616         void *fileio;
1617
1618         /*
1619          * If this helper doesn't know how to lock, then you shouldn't be using
1620          * it but you should write your own.
1621          */
1622         WARN_ON(!lock);
1623
1624         if (lock && mutex_lock_interruptible(lock))
1625                 return POLLERR;
1626
1627         fileio = q->fileio;
1628
1629         res = vb2_poll(vdev->queue, file, wait);
1630
1631         /* If fileio was started, then we have a new queue owner. */
1632         if (!fileio && q->fileio)
1633                 q->owner = file->private_data;
1634         if (lock)
1635                 mutex_unlock(lock);
1636         return res;
1637 }
1638 EXPORT_SYMBOL_GPL(vb2_fop_poll);
1639
1640 #ifndef CONFIG_MMU
1641 unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
1642                 unsigned long len, unsigned long pgoff, unsigned long flags)
1643 {
1644         struct video_device *vdev = video_devdata(file);
1645
1646         return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
1647 }
1648 EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
1649 #endif
1650
1651 /* vb2_ops helpers. Only use if vq->lock is non-NULL. */
1652
1653 void vb2_ops_wait_prepare(struct vb2_queue *vq)
1654 {
1655         mutex_unlock(vq->lock);
1656 }
1657 EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);
1658
1659 void vb2_ops_wait_finish(struct vb2_queue *vq)
1660 {
1661         mutex_lock(vq->lock);
1662 }
1663 EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);
1664
1665 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
1666 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
1667 MODULE_LICENSE("GPL");