GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / media / common / videobuf2 / videobuf2-core.c
1 /*
2  * videobuf2-core.c - video buffer 2 core 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 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18
19 #include <linux/err.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/mm.h>
23 #include <linux/poll.h>
24 #include <linux/slab.h>
25 #include <linux/sched.h>
26 #include <linux/freezer.h>
27 #include <linux/kthread.h>
28
29 #include <media/videobuf2-core.h>
30 #include <media/v4l2-mc.h>
31
32 #include <trace/events/vb2.h>
33
34 static int debug;
35 module_param(debug, int, 0644);
36
37 #define dprintk(level, fmt, arg...)                             \
38         do {                                                    \
39                 if (debug >= level)                             \
40                         pr_info("%s: " fmt, __func__, ## arg);  \
41         } while (0)
42
43 #ifdef CONFIG_VIDEO_ADV_DEBUG
44
45 /*
46  * If advanced debugging is on, then count how often each op is called
47  * successfully, which can either be per-buffer or per-queue.
48  *
49  * This makes it easy to check that the 'init' and 'cleanup'
50  * (and variations thereof) stay balanced.
51  */
52
53 #define log_memop(vb, op)                                               \
54         dprintk(2, "call_memop(%p, %d, %s)%s\n",                        \
55                 (vb)->vb2_queue, (vb)->index, #op,                      \
56                 (vb)->vb2_queue->mem_ops->op ? "" : " (nop)")
57
58 #define call_memop(vb, op, args...)                                     \
59 ({                                                                      \
60         struct vb2_queue *_q = (vb)->vb2_queue;                         \
61         int err;                                                        \
62                                                                         \
63         log_memop(vb, op);                                              \
64         err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0;              \
65         if (!err)                                                       \
66                 (vb)->cnt_mem_ ## op++;                                 \
67         err;                                                            \
68 })
69
70 #define call_ptr_memop(vb, op, args...)                                 \
71 ({                                                                      \
72         struct vb2_queue *_q = (vb)->vb2_queue;                         \
73         void *ptr;                                                      \
74                                                                         \
75         log_memop(vb, op);                                              \
76         ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL;           \
77         if (!IS_ERR_OR_NULL(ptr))                                       \
78                 (vb)->cnt_mem_ ## op++;                                 \
79         ptr;                                                            \
80 })
81
82 #define call_void_memop(vb, op, args...)                                \
83 ({                                                                      \
84         struct vb2_queue *_q = (vb)->vb2_queue;                         \
85                                                                         \
86         log_memop(vb, op);                                              \
87         if (_q->mem_ops->op)                                            \
88                 _q->mem_ops->op(args);                                  \
89         (vb)->cnt_mem_ ## op++;                                         \
90 })
91
92 #define log_qop(q, op)                                                  \
93         dprintk(2, "call_qop(%p, %s)%s\n", q, #op,                      \
94                 (q)->ops->op ? "" : " (nop)")
95
96 #define call_qop(q, op, args...)                                        \
97 ({                                                                      \
98         int err;                                                        \
99                                                                         \
100         log_qop(q, op);                                                 \
101         err = (q)->ops->op ? (q)->ops->op(args) : 0;                    \
102         if (!err)                                                       \
103                 (q)->cnt_ ## op++;                                      \
104         err;                                                            \
105 })
106
107 #define call_void_qop(q, op, args...)                                   \
108 ({                                                                      \
109         log_qop(q, op);                                                 \
110         if ((q)->ops->op)                                               \
111                 (q)->ops->op(args);                                     \
112         (q)->cnt_ ## op++;                                              \
113 })
114
115 #define log_vb_qop(vb, op, args...)                                     \
116         dprintk(2, "call_vb_qop(%p, %d, %s)%s\n",                       \
117                 (vb)->vb2_queue, (vb)->index, #op,                      \
118                 (vb)->vb2_queue->ops->op ? "" : " (nop)")
119
120 #define call_vb_qop(vb, op, args...)                                    \
121 ({                                                                      \
122         int err;                                                        \
123                                                                         \
124         log_vb_qop(vb, op);                                             \
125         err = (vb)->vb2_queue->ops->op ?                                \
126                 (vb)->vb2_queue->ops->op(args) : 0;                     \
127         if (!err)                                                       \
128                 (vb)->cnt_ ## op++;                                     \
129         err;                                                            \
130 })
131
132 #define call_void_vb_qop(vb, op, args...)                               \
133 ({                                                                      \
134         log_vb_qop(vb, op);                                             \
135         if ((vb)->vb2_queue->ops->op)                                   \
136                 (vb)->vb2_queue->ops->op(args);                         \
137         (vb)->cnt_ ## op++;                                             \
138 })
139
140 #else
141
142 #define call_memop(vb, op, args...)                                     \
143         ((vb)->vb2_queue->mem_ops->op ?                                 \
144                 (vb)->vb2_queue->mem_ops->op(args) : 0)
145
146 #define call_ptr_memop(vb, op, args...)                                 \
147         ((vb)->vb2_queue->mem_ops->op ?                                 \
148                 (vb)->vb2_queue->mem_ops->op(args) : NULL)
149
150 #define call_void_memop(vb, op, args...)                                \
151         do {                                                            \
152                 if ((vb)->vb2_queue->mem_ops->op)                       \
153                         (vb)->vb2_queue->mem_ops->op(args);             \
154         } while (0)
155
156 #define call_qop(q, op, args...)                                        \
157         ((q)->ops->op ? (q)->ops->op(args) : 0)
158
159 #define call_void_qop(q, op, args...)                                   \
160         do {                                                            \
161                 if ((q)->ops->op)                                       \
162                         (q)->ops->op(args);                             \
163         } while (0)
164
165 #define call_vb_qop(vb, op, args...)                                    \
166         ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
167
168 #define call_void_vb_qop(vb, op, args...)                               \
169         do {                                                            \
170                 if ((vb)->vb2_queue->ops->op)                           \
171                         (vb)->vb2_queue->ops->op(args);                 \
172         } while (0)
173
174 #endif
175
176 #define call_bufop(q, op, args...)                                      \
177 ({                                                                      \
178         int ret = 0;                                                    \
179         if (q && q->buf_ops && q->buf_ops->op)                          \
180                 ret = q->buf_ops->op(args);                             \
181         ret;                                                            \
182 })
183
184 #define call_void_bufop(q, op, args...)                                 \
185 ({                                                                      \
186         if (q && q->buf_ops && q->buf_ops->op)                          \
187                 q->buf_ops->op(args);                                   \
188 })
189
190 static void __vb2_queue_cancel(struct vb2_queue *q);
191 static void __enqueue_in_driver(struct vb2_buffer *vb);
192
193 /*
194  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
195  */
196 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
197 {
198         struct vb2_queue *q = vb->vb2_queue;
199         void *mem_priv;
200         int plane;
201         int ret = -ENOMEM;
202
203         /*
204          * Allocate memory for all planes in this buffer
205          * NOTE: mmapped areas should be page aligned
206          */
207         for (plane = 0; plane < vb->num_planes; ++plane) {
208                 unsigned long size = PAGE_ALIGN(vb->planes[plane].length);
209
210                 /* Did it wrap around? */
211                 if (size < vb->planes[plane].length)
212                         goto free;
213
214                 mem_priv = call_ptr_memop(vb, alloc,
215                                 q->alloc_devs[plane] ? : q->dev,
216                                 q->dma_attrs, size, q->dma_dir, q->gfp_flags);
217                 if (IS_ERR_OR_NULL(mem_priv)) {
218                         if (mem_priv)
219                                 ret = PTR_ERR(mem_priv);
220                         goto free;
221                 }
222
223                 /* Associate allocator private data with this plane */
224                 vb->planes[plane].mem_priv = mem_priv;
225         }
226
227         return 0;
228 free:
229         /* Free already allocated memory if one of the allocations failed */
230         for (; plane > 0; --plane) {
231                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
232                 vb->planes[plane - 1].mem_priv = NULL;
233         }
234
235         return ret;
236 }
237
238 /*
239  * __vb2_buf_mem_free() - free memory of the given buffer
240  */
241 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
242 {
243         unsigned int plane;
244
245         for (plane = 0; plane < vb->num_planes; ++plane) {
246                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
247                 vb->planes[plane].mem_priv = NULL;
248                 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
249         }
250 }
251
252 /*
253  * __vb2_buf_userptr_put() - release userspace memory associated with
254  * a USERPTR buffer
255  */
256 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
257 {
258         unsigned int plane;
259
260         for (plane = 0; plane < vb->num_planes; ++plane) {
261                 if (vb->planes[plane].mem_priv)
262                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
263                 vb->planes[plane].mem_priv = NULL;
264         }
265 }
266
267 /*
268  * __vb2_plane_dmabuf_put() - release memory associated with
269  * a DMABUF shared plane
270  */
271 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
272 {
273         if (!p->mem_priv)
274                 return;
275
276         if (p->dbuf_mapped)
277                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
278
279         call_void_memop(vb, detach_dmabuf, p->mem_priv);
280         dma_buf_put(p->dbuf);
281         p->mem_priv = NULL;
282         p->dbuf = NULL;
283         p->dbuf_mapped = 0;
284 }
285
286 /*
287  * __vb2_buf_dmabuf_put() - release memory associated with
288  * a DMABUF shared buffer
289  */
290 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
291 {
292         unsigned int plane;
293
294         for (plane = 0; plane < vb->num_planes; ++plane)
295                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
296 }
297
298 /*
299  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
300  * the buffer.
301  */
302 static void __setup_offsets(struct vb2_buffer *vb)
303 {
304         struct vb2_queue *q = vb->vb2_queue;
305         unsigned int plane;
306         unsigned long off = 0;
307
308         if (vb->index) {
309                 struct vb2_buffer *prev = q->bufs[vb->index - 1];
310                 struct vb2_plane *p = &prev->planes[prev->num_planes - 1];
311
312                 off = PAGE_ALIGN(p->m.offset + p->length);
313         }
314
315         for (plane = 0; plane < vb->num_planes; ++plane) {
316                 vb->planes[plane].m.offset = off;
317
318                 dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
319                                 vb->index, plane, off);
320
321                 off += vb->planes[plane].length;
322                 off = PAGE_ALIGN(off);
323         }
324 }
325
326 /*
327  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
328  * video buffer memory for all buffers/planes on the queue and initializes the
329  * queue
330  *
331  * Returns the number of buffers successfully allocated.
332  */
333 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
334                              unsigned int num_buffers, unsigned int num_planes,
335                              const unsigned plane_sizes[VB2_MAX_PLANES])
336 {
337         unsigned int buffer, plane;
338         struct vb2_buffer *vb;
339         int ret;
340
341         /* Ensure that q->num_buffers+num_buffers is below VB2_MAX_FRAME */
342         num_buffers = min_t(unsigned int, num_buffers,
343                             VB2_MAX_FRAME - q->num_buffers);
344
345         for (buffer = 0; buffer < num_buffers; ++buffer) {
346                 /* Allocate videobuf buffer structures */
347                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
348                 if (!vb) {
349                         dprintk(1, "memory alloc for buffer struct failed\n");
350                         break;
351                 }
352
353                 vb->state = VB2_BUF_STATE_DEQUEUED;
354                 vb->vb2_queue = q;
355                 vb->num_planes = num_planes;
356                 vb->index = q->num_buffers + buffer;
357                 vb->type = q->type;
358                 vb->memory = memory;
359                 for (plane = 0; plane < num_planes; ++plane) {
360                         vb->planes[plane].length = plane_sizes[plane];
361                         vb->planes[plane].min_length = plane_sizes[plane];
362                 }
363                 q->bufs[vb->index] = vb;
364
365                 /* Allocate video buffer memory for the MMAP type */
366                 if (memory == VB2_MEMORY_MMAP) {
367                         ret = __vb2_buf_mem_alloc(vb);
368                         if (ret) {
369                                 dprintk(1, "failed allocating memory for buffer %d\n",
370                                         buffer);
371                                 q->bufs[vb->index] = NULL;
372                                 kfree(vb);
373                                 break;
374                         }
375                         __setup_offsets(vb);
376                         /*
377                          * Call the driver-provided buffer initialization
378                          * callback, if given. An error in initialization
379                          * results in queue setup failure.
380                          */
381                         ret = call_vb_qop(vb, buf_init, vb);
382                         if (ret) {
383                                 dprintk(1, "buffer %d %p initialization failed\n",
384                                         buffer, vb);
385                                 __vb2_buf_mem_free(vb);
386                                 q->bufs[vb->index] = NULL;
387                                 kfree(vb);
388                                 break;
389                         }
390                 }
391         }
392
393         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
394                         buffer, num_planes);
395
396         return buffer;
397 }
398
399 /*
400  * __vb2_free_mem() - release all video buffer memory for a given queue
401  */
402 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
403 {
404         unsigned int buffer;
405         struct vb2_buffer *vb;
406
407         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
408              ++buffer) {
409                 vb = q->bufs[buffer];
410                 if (!vb)
411                         continue;
412
413                 /* Free MMAP buffers or release USERPTR buffers */
414                 if (q->memory == VB2_MEMORY_MMAP)
415                         __vb2_buf_mem_free(vb);
416                 else if (q->memory == VB2_MEMORY_DMABUF)
417                         __vb2_buf_dmabuf_put(vb);
418                 else
419                         __vb2_buf_userptr_put(vb);
420         }
421 }
422
423 /*
424  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
425  * related information, if no buffers are left return the queue to an
426  * uninitialized state. Might be called even if the queue has already been freed.
427  */
428 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
429 {
430         unsigned int buffer;
431
432         /*
433          * Sanity check: when preparing a buffer the queue lock is released for
434          * a short while (see __buf_prepare for the details), which would allow
435          * a race with a reqbufs which can call this function. Removing the
436          * buffers from underneath __buf_prepare is obviously a bad idea, so we
437          * check if any of the buffers is in the state PREPARING, and if so we
438          * just return -EAGAIN.
439          */
440         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
441              ++buffer) {
442                 if (q->bufs[buffer] == NULL)
443                         continue;
444                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
445                         dprintk(1, "preparing buffers, cannot free\n");
446                         return -EAGAIN;
447                 }
448         }
449
450         /* Call driver-provided cleanup function for each buffer, if provided */
451         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
452              ++buffer) {
453                 struct vb2_buffer *vb = q->bufs[buffer];
454
455                 if (vb && vb->planes[0].mem_priv)
456                         call_void_vb_qop(vb, buf_cleanup, vb);
457         }
458
459         /* Release video buffer memory */
460         __vb2_free_mem(q, buffers);
461
462 #ifdef CONFIG_VIDEO_ADV_DEBUG
463         /*
464          * Check that all the calls were balances during the life-time of this
465          * queue. If not (or if the debug level is 1 or up), then dump the
466          * counters to the kernel log.
467          */
468         if (q->num_buffers) {
469                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
470                                   q->cnt_wait_prepare != q->cnt_wait_finish;
471
472                 if (unbalanced || debug) {
473                         pr_info("counters for queue %p:%s\n", q,
474                                 unbalanced ? " UNBALANCED!" : "");
475                         pr_info("     setup: %u start_streaming: %u stop_streaming: %u\n",
476                                 q->cnt_queue_setup, q->cnt_start_streaming,
477                                 q->cnt_stop_streaming);
478                         pr_info("     wait_prepare: %u wait_finish: %u\n",
479                                 q->cnt_wait_prepare, q->cnt_wait_finish);
480                 }
481                 q->cnt_queue_setup = 0;
482                 q->cnt_wait_prepare = 0;
483                 q->cnt_wait_finish = 0;
484                 q->cnt_start_streaming = 0;
485                 q->cnt_stop_streaming = 0;
486         }
487         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
488                 struct vb2_buffer *vb = q->bufs[buffer];
489                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
490                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
491                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
492                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
493                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
494                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
495                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
496                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
497
498                 if (unbalanced || debug) {
499                         pr_info("   counters for queue %p, buffer %d:%s\n",
500                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
501                         pr_info("     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
502                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
503                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
504                         pr_info("     buf_queue: %u buf_done: %u\n",
505                                 vb->cnt_buf_queue, vb->cnt_buf_done);
506                         pr_info("     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
507                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
508                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
509                                 vb->cnt_mem_mmap);
510                         pr_info("     get_userptr: %u put_userptr: %u\n",
511                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
512                         pr_info("     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
513                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
514                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
515                         pr_info("     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
516                                 vb->cnt_mem_get_dmabuf,
517                                 vb->cnt_mem_num_users,
518                                 vb->cnt_mem_vaddr,
519                                 vb->cnt_mem_cookie);
520                 }
521         }
522 #endif
523
524         /* Free videobuf buffers */
525         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
526              ++buffer) {
527                 kfree(q->bufs[buffer]);
528                 q->bufs[buffer] = NULL;
529         }
530
531         q->num_buffers -= buffers;
532         if (!q->num_buffers) {
533                 q->memory = VB2_MEMORY_UNKNOWN;
534                 INIT_LIST_HEAD(&q->queued_list);
535         }
536         return 0;
537 }
538
539 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
540 {
541         unsigned int plane;
542         for (plane = 0; plane < vb->num_planes; ++plane) {
543                 void *mem_priv = vb->planes[plane].mem_priv;
544                 /*
545                  * If num_users() has not been provided, call_memop
546                  * will return 0, apparently nobody cares about this
547                  * case anyway. If num_users() returns more than 1,
548                  * we are not the only user of the plane's memory.
549                  */
550                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
551                         return true;
552         }
553         return false;
554 }
555 EXPORT_SYMBOL(vb2_buffer_in_use);
556
557 /*
558  * __buffers_in_use() - return true if any buffers on the queue are in use and
559  * the queue cannot be freed (by the means of REQBUFS(0)) call
560  */
561 static bool __buffers_in_use(struct vb2_queue *q)
562 {
563         unsigned int buffer;
564         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
565                 if (vb2_buffer_in_use(q, q->bufs[buffer]))
566                         return true;
567         }
568         return false;
569 }
570
571 void vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
572 {
573         call_void_bufop(q, fill_user_buffer, q->bufs[index], pb);
574 }
575 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
576
577 /*
578  * __verify_userptr_ops() - verify that all memory operations required for
579  * USERPTR queue type have been provided
580  */
581 static int __verify_userptr_ops(struct vb2_queue *q)
582 {
583         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
584             !q->mem_ops->put_userptr)
585                 return -EINVAL;
586
587         return 0;
588 }
589
590 /*
591  * __verify_mmap_ops() - verify that all memory operations required for
592  * MMAP queue type have been provided
593  */
594 static int __verify_mmap_ops(struct vb2_queue *q)
595 {
596         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
597             !q->mem_ops->put || !q->mem_ops->mmap)
598                 return -EINVAL;
599
600         return 0;
601 }
602
603 /*
604  * __verify_dmabuf_ops() - verify that all memory operations required for
605  * DMABUF queue type have been provided
606  */
607 static int __verify_dmabuf_ops(struct vb2_queue *q)
608 {
609         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
610             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
611             !q->mem_ops->unmap_dmabuf)
612                 return -EINVAL;
613
614         return 0;
615 }
616
617 int vb2_verify_memory_type(struct vb2_queue *q,
618                 enum vb2_memory memory, unsigned int type)
619 {
620         if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
621             memory != VB2_MEMORY_DMABUF) {
622                 dprintk(1, "unsupported memory type\n");
623                 return -EINVAL;
624         }
625
626         if (type != q->type) {
627                 dprintk(1, "requested type is incorrect\n");
628                 return -EINVAL;
629         }
630
631         /*
632          * Make sure all the required memory ops for given memory type
633          * are available.
634          */
635         if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
636                 dprintk(1, "MMAP for current setup unsupported\n");
637                 return -EINVAL;
638         }
639
640         if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
641                 dprintk(1, "USERPTR for current setup unsupported\n");
642                 return -EINVAL;
643         }
644
645         if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
646                 dprintk(1, "DMABUF for current setup unsupported\n");
647                 return -EINVAL;
648         }
649
650         /*
651          * Place the busy tests at the end: -EBUSY can be ignored when
652          * create_bufs is called with count == 0, but count == 0 should still
653          * do the memory and type validation.
654          */
655         if (vb2_fileio_is_active(q)) {
656                 dprintk(1, "file io in progress\n");
657                 return -EBUSY;
658         }
659         return 0;
660 }
661 EXPORT_SYMBOL(vb2_verify_memory_type);
662
663 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
664                 unsigned int *count)
665 {
666         unsigned int num_buffers, allocated_buffers, num_planes = 0;
667         unsigned plane_sizes[VB2_MAX_PLANES] = { };
668         int ret;
669
670         if (q->streaming) {
671                 dprintk(1, "streaming active\n");
672                 return -EBUSY;
673         }
674
675         if (q->waiting_in_dqbuf && *count) {
676                 dprintk(1, "another dup()ped fd is waiting for a buffer\n");
677                 return -EBUSY;
678         }
679
680         if (*count == 0 || q->num_buffers != 0 ||
681             (q->memory != VB2_MEMORY_UNKNOWN && q->memory != memory)) {
682                 /*
683                  * We already have buffers allocated, so first check if they
684                  * are not in use and can be freed.
685                  */
686                 mutex_lock(&q->mmap_lock);
687                 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
688                         mutex_unlock(&q->mmap_lock);
689                         dprintk(1, "memory in use, cannot free\n");
690                         return -EBUSY;
691                 }
692
693                 /*
694                  * Call queue_cancel to clean up any buffers in the PREPARED or
695                  * QUEUED state which is possible if buffers were prepared or
696                  * queued without ever calling STREAMON.
697                  */
698                 __vb2_queue_cancel(q);
699                 ret = __vb2_queue_free(q, q->num_buffers);
700                 mutex_unlock(&q->mmap_lock);
701                 if (ret)
702                         return ret;
703
704                 /*
705                  * In case of REQBUFS(0) return immediately without calling
706                  * driver's queue_setup() callback and allocating resources.
707                  */
708                 if (*count == 0)
709                         return 0;
710         }
711
712         /*
713          * Make sure the requested values and current defaults are sane.
714          */
715         WARN_ON(q->min_buffers_needed > VB2_MAX_FRAME);
716         num_buffers = max_t(unsigned int, *count, q->min_buffers_needed);
717         num_buffers = min_t(unsigned int, num_buffers, VB2_MAX_FRAME);
718         memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
719         q->memory = memory;
720
721         /*
722          * Ask the driver how many buffers and planes per buffer it requires.
723          * Driver also sets the size and allocator context for each plane.
724          */
725         ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
726                        plane_sizes, q->alloc_devs);
727         if (ret)
728                 return ret;
729
730         /* Finally, allocate buffers and video memory */
731         allocated_buffers =
732                 __vb2_queue_alloc(q, memory, num_buffers, num_planes, plane_sizes);
733         if (allocated_buffers == 0) {
734                 dprintk(1, "memory allocation failed\n");
735                 return -ENOMEM;
736         }
737
738         /*
739          * There is no point in continuing if we can't allocate the minimum
740          * number of buffers needed by this vb2_queue.
741          */
742         if (allocated_buffers < q->min_buffers_needed)
743                 ret = -ENOMEM;
744
745         /*
746          * Check if driver can handle the allocated number of buffers.
747          */
748         if (!ret && allocated_buffers < num_buffers) {
749                 num_buffers = allocated_buffers;
750                 /*
751                  * num_planes is set by the previous queue_setup(), but since it
752                  * signals to queue_setup() whether it is called from create_bufs()
753                  * vs reqbufs() we zero it here to signal that queue_setup() is
754                  * called for the reqbufs() case.
755                  */
756                 num_planes = 0;
757
758                 ret = call_qop(q, queue_setup, q, &num_buffers,
759                                &num_planes, plane_sizes, q->alloc_devs);
760
761                 if (!ret && allocated_buffers < num_buffers)
762                         ret = -ENOMEM;
763
764                 /*
765                  * Either the driver has accepted a smaller number of buffers,
766                  * or .queue_setup() returned an error
767                  */
768         }
769
770         mutex_lock(&q->mmap_lock);
771         q->num_buffers = allocated_buffers;
772
773         if (ret < 0) {
774                 /*
775                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
776                  * from q->num_buffers.
777                  */
778                 __vb2_queue_free(q, allocated_buffers);
779                 mutex_unlock(&q->mmap_lock);
780                 return ret;
781         }
782         mutex_unlock(&q->mmap_lock);
783
784         /*
785          * Return the number of successfully allocated buffers
786          * to the userspace.
787          */
788         *count = allocated_buffers;
789         q->waiting_for_buffers = !q->is_output;
790
791         return 0;
792 }
793 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
794
795 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
796                 unsigned int *count, unsigned requested_planes,
797                 const unsigned requested_sizes[])
798 {
799         unsigned int num_planes = 0, num_buffers, allocated_buffers;
800         unsigned plane_sizes[VB2_MAX_PLANES] = { };
801         int ret;
802
803         if (q->num_buffers == VB2_MAX_FRAME) {
804                 dprintk(1, "maximum number of buffers already allocated\n");
805                 return -ENOBUFS;
806         }
807
808         if (!q->num_buffers) {
809                 if (q->waiting_in_dqbuf && *count) {
810                         dprintk(1, "another dup()ped fd is waiting for a buffer\n");
811                         return -EBUSY;
812                 }
813                 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
814                 q->memory = memory;
815                 q->waiting_for_buffers = !q->is_output;
816         } else if (q->memory != memory) {
817                 dprintk(1, "memory model mismatch\n");
818                 return -EINVAL;
819         }
820
821         num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
822
823         if (requested_planes && requested_sizes) {
824                 num_planes = requested_planes;
825                 memcpy(plane_sizes, requested_sizes, sizeof(plane_sizes));
826         }
827
828         /*
829          * Ask the driver, whether the requested number of buffers, planes per
830          * buffer and their sizes are acceptable
831          */
832         ret = call_qop(q, queue_setup, q, &num_buffers,
833                        &num_planes, plane_sizes, q->alloc_devs);
834         if (ret)
835                 return ret;
836
837         /* Finally, allocate buffers and video memory */
838         allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
839                                 num_planes, plane_sizes);
840         if (allocated_buffers == 0) {
841                 dprintk(1, "memory allocation failed\n");
842                 return -ENOMEM;
843         }
844
845         /*
846          * Check if driver can handle the so far allocated number of buffers.
847          */
848         if (allocated_buffers < num_buffers) {
849                 num_buffers = allocated_buffers;
850
851                 /*
852                  * q->num_buffers contains the total number of buffers, that the
853                  * queue driver has set up
854                  */
855                 ret = call_qop(q, queue_setup, q, &num_buffers,
856                                &num_planes, plane_sizes, q->alloc_devs);
857
858                 if (!ret && allocated_buffers < num_buffers)
859                         ret = -ENOMEM;
860
861                 /*
862                  * Either the driver has accepted a smaller number of buffers,
863                  * or .queue_setup() returned an error
864                  */
865         }
866
867         mutex_lock(&q->mmap_lock);
868         q->num_buffers += allocated_buffers;
869
870         if (ret < 0) {
871                 /*
872                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
873                  * from q->num_buffers.
874                  */
875                 __vb2_queue_free(q, allocated_buffers);
876                 mutex_unlock(&q->mmap_lock);
877                 return -ENOMEM;
878         }
879         mutex_unlock(&q->mmap_lock);
880
881         /*
882          * Return the number of successfully allocated buffers
883          * to the userspace.
884          */
885         *count = allocated_buffers;
886
887         return 0;
888 }
889 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
890
891 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
892 {
893         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
894                 return NULL;
895
896         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
897
898 }
899 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
900
901 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
902 {
903         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
904                 return NULL;
905
906         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
907 }
908 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
909
910 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
911 {
912         struct vb2_queue *q = vb->vb2_queue;
913         unsigned long flags;
914         unsigned int plane;
915
916         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
917                 return;
918
919         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
920                     state != VB2_BUF_STATE_ERROR &&
921                     state != VB2_BUF_STATE_QUEUED &&
922                     state != VB2_BUF_STATE_REQUEUEING))
923                 state = VB2_BUF_STATE_ERROR;
924
925 #ifdef CONFIG_VIDEO_ADV_DEBUG
926         /*
927          * Although this is not a callback, it still does have to balance
928          * with the buf_queue op. So update this counter manually.
929          */
930         vb->cnt_buf_done++;
931 #endif
932         dprintk(4, "done processing on buffer %d, state: %d\n",
933                         vb->index, state);
934
935         if (state != VB2_BUF_STATE_QUEUED &&
936             state != VB2_BUF_STATE_REQUEUEING) {
937                 /* sync buffers */
938                 for (plane = 0; plane < vb->num_planes; ++plane)
939                         call_void_memop(vb, finish, vb->planes[plane].mem_priv);
940         }
941
942         spin_lock_irqsave(&q->done_lock, flags);
943         if (state == VB2_BUF_STATE_QUEUED ||
944             state == VB2_BUF_STATE_REQUEUEING) {
945                 vb->state = VB2_BUF_STATE_QUEUED;
946         } else {
947                 /* Add the buffer to the done buffers list */
948                 list_add_tail(&vb->done_entry, &q->done_list);
949                 vb->state = state;
950         }
951         atomic_dec(&q->owned_by_drv_count);
952         spin_unlock_irqrestore(&q->done_lock, flags);
953
954         trace_vb2_buf_done(q, vb);
955
956         switch (state) {
957         case VB2_BUF_STATE_QUEUED:
958                 return;
959         case VB2_BUF_STATE_REQUEUEING:
960                 if (q->start_streaming_called)
961                         __enqueue_in_driver(vb);
962                 return;
963         default:
964                 /* Inform any processes that may be waiting for buffers */
965                 wake_up(&q->done_wq);
966                 break;
967         }
968 }
969 EXPORT_SYMBOL_GPL(vb2_buffer_done);
970
971 void vb2_discard_done(struct vb2_queue *q)
972 {
973         struct vb2_buffer *vb;
974         unsigned long flags;
975
976         spin_lock_irqsave(&q->done_lock, flags);
977         list_for_each_entry(vb, &q->done_list, done_entry)
978                 vb->state = VB2_BUF_STATE_ERROR;
979         spin_unlock_irqrestore(&q->done_lock, flags);
980 }
981 EXPORT_SYMBOL_GPL(vb2_discard_done);
982
983 /*
984  * __prepare_mmap() - prepare an MMAP buffer
985  */
986 static int __prepare_mmap(struct vb2_buffer *vb, const void *pb)
987 {
988         int ret = 0;
989
990         if (pb)
991                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
992                                  vb, pb, vb->planes);
993         return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
994 }
995
996 /*
997  * __prepare_userptr() - prepare a USERPTR buffer
998  */
999 static int __prepare_userptr(struct vb2_buffer *vb, const void *pb)
1000 {
1001         struct vb2_plane planes[VB2_MAX_PLANES];
1002         struct vb2_queue *q = vb->vb2_queue;
1003         void *mem_priv;
1004         unsigned int plane;
1005         int ret = 0;
1006         bool reacquired = vb->planes[0].mem_priv == NULL;
1007
1008         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1009         /* Copy relevant information provided by the userspace */
1010         if (pb) {
1011                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1012                                  vb, pb, planes);
1013                 if (ret)
1014                         return ret;
1015         }
1016
1017         for (plane = 0; plane < vb->num_planes; ++plane) {
1018                 /* Skip the plane if already verified */
1019                 if (vb->planes[plane].m.userptr &&
1020                         vb->planes[plane].m.userptr == planes[plane].m.userptr
1021                         && vb->planes[plane].length == planes[plane].length)
1022                         continue;
1023
1024                 dprintk(3, "userspace address for plane %d changed, reacquiring memory\n",
1025                         plane);
1026
1027                 /* Check if the provided plane buffer is large enough */
1028                 if (planes[plane].length < vb->planes[plane].min_length) {
1029                         dprintk(1, "provided buffer size %u is less than setup size %u for plane %d\n",
1030                                                 planes[plane].length,
1031                                                 vb->planes[plane].min_length,
1032                                                 plane);
1033                         ret = -EINVAL;
1034                         goto err;
1035                 }
1036
1037                 /* Release previously acquired memory if present */
1038                 if (vb->planes[plane].mem_priv) {
1039                         if (!reacquired) {
1040                                 reacquired = true;
1041                                 call_void_vb_qop(vb, buf_cleanup, vb);
1042                         }
1043                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1044                 }
1045
1046                 vb->planes[plane].mem_priv = NULL;
1047                 vb->planes[plane].bytesused = 0;
1048                 vb->planes[plane].length = 0;
1049                 vb->planes[plane].m.userptr = 0;
1050                 vb->planes[plane].data_offset = 0;
1051
1052                 /* Acquire each plane's memory */
1053                 mem_priv = call_ptr_memop(vb, get_userptr,
1054                                 q->alloc_devs[plane] ? : q->dev,
1055                                 planes[plane].m.userptr,
1056                                 planes[plane].length, q->dma_dir);
1057                 if (IS_ERR(mem_priv)) {
1058                         dprintk(1, "failed acquiring userspace memory for plane %d\n",
1059                                 plane);
1060                         ret = PTR_ERR(mem_priv);
1061                         goto err;
1062                 }
1063                 vb->planes[plane].mem_priv = mem_priv;
1064         }
1065
1066         /*
1067          * Now that everything is in order, copy relevant information
1068          * provided by userspace.
1069          */
1070         for (plane = 0; plane < vb->num_planes; ++plane) {
1071                 vb->planes[plane].bytesused = planes[plane].bytesused;
1072                 vb->planes[plane].length = planes[plane].length;
1073                 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1074                 vb->planes[plane].data_offset = planes[plane].data_offset;
1075         }
1076
1077         if (reacquired) {
1078                 /*
1079                  * One or more planes changed, so we must call buf_init to do
1080                  * the driver-specific initialization on the newly acquired
1081                  * buffer, if provided.
1082                  */
1083                 ret = call_vb_qop(vb, buf_init, vb);
1084                 if (ret) {
1085                         dprintk(1, "buffer initialization failed\n");
1086                         goto err;
1087                 }
1088         }
1089
1090         ret = call_vb_qop(vb, buf_prepare, vb);
1091         if (ret) {
1092                 dprintk(1, "buffer preparation failed\n");
1093                 call_void_vb_qop(vb, buf_cleanup, vb);
1094                 goto err;
1095         }
1096
1097         return 0;
1098 err:
1099         /* In case of errors, release planes that were already acquired */
1100         for (plane = 0; plane < vb->num_planes; ++plane) {
1101                 if (vb->planes[plane].mem_priv)
1102                         call_void_memop(vb, put_userptr,
1103                                 vb->planes[plane].mem_priv);
1104                 vb->planes[plane].mem_priv = NULL;
1105                 vb->planes[plane].m.userptr = 0;
1106                 vb->planes[plane].length = 0;
1107         }
1108
1109         return ret;
1110 }
1111
1112 /*
1113  * __prepare_dmabuf() - prepare a DMABUF buffer
1114  */
1115 static int __prepare_dmabuf(struct vb2_buffer *vb, const void *pb)
1116 {
1117         struct vb2_plane planes[VB2_MAX_PLANES];
1118         struct vb2_queue *q = vb->vb2_queue;
1119         void *mem_priv;
1120         unsigned int plane;
1121         int ret = 0;
1122         bool reacquired = vb->planes[0].mem_priv == NULL;
1123
1124         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1125         /* Copy relevant information provided by the userspace */
1126         if (pb) {
1127                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1128                                  vb, pb, planes);
1129                 if (ret)
1130                         return ret;
1131         }
1132
1133         for (plane = 0; plane < vb->num_planes; ++plane) {
1134                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1135
1136                 if (IS_ERR_OR_NULL(dbuf)) {
1137                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1138                                 plane);
1139                         ret = -EINVAL;
1140                         goto err;
1141                 }
1142
1143                 /* use DMABUF size if length is not provided */
1144                 if (planes[plane].length == 0)
1145                         planes[plane].length = dbuf->size;
1146
1147                 if (planes[plane].length < vb->planes[plane].min_length) {
1148                         dprintk(1, "invalid dmabuf length %u for plane %d, minimum length %u\n",
1149                                 planes[plane].length, plane,
1150                                 vb->planes[plane].min_length);
1151                         dma_buf_put(dbuf);
1152                         ret = -EINVAL;
1153                         goto err;
1154                 }
1155
1156                 /* Skip the plane if already verified */
1157                 if (dbuf == vb->planes[plane].dbuf &&
1158                         vb->planes[plane].length == planes[plane].length) {
1159                         dma_buf_put(dbuf);
1160                         continue;
1161                 }
1162
1163                 dprintk(3, "buffer for plane %d changed\n", plane);
1164
1165                 if (!reacquired) {
1166                         reacquired = true;
1167                         call_void_vb_qop(vb, buf_cleanup, vb);
1168                 }
1169
1170                 /* Release previously acquired memory if present */
1171                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1172                 vb->planes[plane].bytesused = 0;
1173                 vb->planes[plane].length = 0;
1174                 vb->planes[plane].m.fd = 0;
1175                 vb->planes[plane].data_offset = 0;
1176
1177                 /* Acquire each plane's memory */
1178                 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1179                                 q->alloc_devs[plane] ? : q->dev,
1180                                 dbuf, planes[plane].length, q->dma_dir);
1181                 if (IS_ERR(mem_priv)) {
1182                         dprintk(1, "failed to attach dmabuf\n");
1183                         ret = PTR_ERR(mem_priv);
1184                         dma_buf_put(dbuf);
1185                         goto err;
1186                 }
1187
1188                 vb->planes[plane].dbuf = dbuf;
1189                 vb->planes[plane].mem_priv = mem_priv;
1190         }
1191
1192         /*
1193          * This pins the buffer(s) with dma_buf_map_attachment()). It's done
1194          * here instead just before the DMA, while queueing the buffer(s) so
1195          * userspace knows sooner rather than later if the dma-buf map fails.
1196          */
1197         for (plane = 0; plane < vb->num_planes; ++plane) {
1198                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1199                 if (ret) {
1200                         dprintk(1, "failed to map dmabuf for plane %d\n",
1201                                 plane);
1202                         goto err;
1203                 }
1204                 vb->planes[plane].dbuf_mapped = 1;
1205         }
1206
1207         /*
1208          * Now that everything is in order, copy relevant information
1209          * provided by userspace.
1210          */
1211         for (plane = 0; plane < vb->num_planes; ++plane) {
1212                 vb->planes[plane].bytesused = planes[plane].bytesused;
1213                 vb->planes[plane].length = planes[plane].length;
1214                 vb->planes[plane].m.fd = planes[plane].m.fd;
1215                 vb->planes[plane].data_offset = planes[plane].data_offset;
1216         }
1217
1218         if (reacquired) {
1219                 /*
1220                  * Call driver-specific initialization on the newly acquired buffer,
1221                  * if provided.
1222                  */
1223                 ret = call_vb_qop(vb, buf_init, vb);
1224                 if (ret) {
1225                         dprintk(1, "buffer initialization failed\n");
1226                         goto err;
1227                 }
1228         }
1229
1230         ret = call_vb_qop(vb, buf_prepare, vb);
1231         if (ret) {
1232                 dprintk(1, "buffer preparation failed\n");
1233                 call_void_vb_qop(vb, buf_cleanup, vb);
1234                 goto err;
1235         }
1236
1237         return 0;
1238 err:
1239         /* In case of errors, release planes that were already acquired */
1240         __vb2_buf_dmabuf_put(vb);
1241
1242         return ret;
1243 }
1244
1245 /*
1246  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1247  */
1248 static void __enqueue_in_driver(struct vb2_buffer *vb)
1249 {
1250         struct vb2_queue *q = vb->vb2_queue;
1251
1252         vb->state = VB2_BUF_STATE_ACTIVE;
1253         atomic_inc(&q->owned_by_drv_count);
1254
1255         trace_vb2_buf_queue(q, vb);
1256
1257         call_void_vb_qop(vb, buf_queue, vb);
1258 }
1259
1260 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1261 {
1262         struct vb2_queue *q = vb->vb2_queue;
1263         unsigned int plane;
1264         int ret;
1265
1266         if (q->error) {
1267                 dprintk(1, "fatal error occurred on queue\n");
1268                 return -EIO;
1269         }
1270
1271         vb->state = VB2_BUF_STATE_PREPARING;
1272
1273         switch (q->memory) {
1274         case VB2_MEMORY_MMAP:
1275                 ret = __prepare_mmap(vb, pb);
1276                 break;
1277         case VB2_MEMORY_USERPTR:
1278                 ret = __prepare_userptr(vb, pb);
1279                 break;
1280         case VB2_MEMORY_DMABUF:
1281                 ret = __prepare_dmabuf(vb, pb);
1282                 break;
1283         default:
1284                 WARN(1, "Invalid queue type\n");
1285                 ret = -EINVAL;
1286         }
1287
1288         if (ret) {
1289                 dprintk(1, "buffer preparation failed: %d\n", ret);
1290                 vb->state = VB2_BUF_STATE_DEQUEUED;
1291                 return ret;
1292         }
1293
1294         /* sync buffers */
1295         for (plane = 0; plane < vb->num_planes; ++plane)
1296                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1297
1298         vb->state = VB2_BUF_STATE_PREPARED;
1299
1300         return 0;
1301 }
1302
1303 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1304 {
1305         struct vb2_buffer *vb;
1306         int ret;
1307
1308         vb = q->bufs[index];
1309         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1310                 dprintk(1, "invalid buffer state %d\n",
1311                         vb->state);
1312                 return -EINVAL;
1313         }
1314
1315         ret = __buf_prepare(vb, pb);
1316         if (ret)
1317                 return ret;
1318
1319         /* Fill buffer information for the userspace */
1320         call_void_bufop(q, fill_user_buffer, vb, pb);
1321
1322         dprintk(2, "prepare of buffer %d succeeded\n", vb->index);
1323
1324         return ret;
1325 }
1326 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1327
1328 /*
1329  * vb2_start_streaming() - Attempt to start streaming.
1330  * @q:          videobuf2 queue
1331  *
1332  * Attempt to start streaming. When this function is called there must be
1333  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1334  * number of buffers required for the DMA engine to function). If the
1335  * @start_streaming op fails it is supposed to return all the driver-owned
1336  * buffers back to vb2 in state QUEUED. Check if that happened and if
1337  * not warn and reclaim them forcefully.
1338  */
1339 static int vb2_start_streaming(struct vb2_queue *q)
1340 {
1341         struct vb2_buffer *vb;
1342         int ret;
1343
1344         /*
1345          * If any buffers were queued before streamon,
1346          * we can now pass them to driver for processing.
1347          */
1348         list_for_each_entry(vb, &q->queued_list, queued_entry)
1349                 __enqueue_in_driver(vb);
1350
1351         /* Tell the driver to start streaming */
1352         q->start_streaming_called = 1;
1353         ret = call_qop(q, start_streaming, q,
1354                        atomic_read(&q->owned_by_drv_count));
1355         if (!ret)
1356                 return 0;
1357
1358         q->start_streaming_called = 0;
1359
1360         dprintk(1, "driver refused to start streaming\n");
1361         /*
1362          * If you see this warning, then the driver isn't cleaning up properly
1363          * after a failed start_streaming(). See the start_streaming()
1364          * documentation in videobuf2-core.h for more information how buffers
1365          * should be returned to vb2 in start_streaming().
1366          */
1367         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1368                 unsigned i;
1369
1370                 /*
1371                  * Forcefully reclaim buffers if the driver did not
1372                  * correctly return them to vb2.
1373                  */
1374                 for (i = 0; i < q->num_buffers; ++i) {
1375                         vb = q->bufs[i];
1376                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1377                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1378                 }
1379                 /* Must be zero now */
1380                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1381         }
1382         /*
1383          * If done_list is not empty, then start_streaming() didn't call
1384          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1385          * STATE_DONE.
1386          */
1387         WARN_ON(!list_empty(&q->done_list));
1388         return ret;
1389 }
1390
1391 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1392 {
1393         struct vb2_buffer *vb;
1394         enum vb2_buffer_state orig_state;
1395         int ret;
1396
1397         if (q->error) {
1398                 dprintk(1, "fatal error occurred on queue\n");
1399                 return -EIO;
1400         }
1401
1402         vb = q->bufs[index];
1403
1404         switch (vb->state) {
1405         case VB2_BUF_STATE_DEQUEUED:
1406                 ret = __buf_prepare(vb, pb);
1407                 if (ret)
1408                         return ret;
1409                 break;
1410         case VB2_BUF_STATE_PREPARED:
1411                 break;
1412         case VB2_BUF_STATE_PREPARING:
1413                 dprintk(1, "buffer still being prepared\n");
1414                 return -EINVAL;
1415         default:
1416                 dprintk(1, "invalid buffer state %d\n", vb->state);
1417                 return -EINVAL;
1418         }
1419
1420         /*
1421          * Add to the queued buffers list, a buffer will stay on it until
1422          * dequeued in dqbuf.
1423          */
1424         orig_state = vb->state;
1425         list_add_tail(&vb->queued_entry, &q->queued_list);
1426         q->queued_count++;
1427         q->waiting_for_buffers = false;
1428         vb->state = VB2_BUF_STATE_QUEUED;
1429
1430         if (pb)
1431                 call_void_bufop(q, copy_timestamp, vb, pb);
1432
1433         trace_vb2_qbuf(q, vb);
1434
1435         /*
1436          * If already streaming, give the buffer to driver for processing.
1437          * If not, the buffer will be given to driver on next streamon.
1438          */
1439         if (q->start_streaming_called)
1440                 __enqueue_in_driver(vb);
1441
1442         /* Fill buffer information for the userspace */
1443         if (pb)
1444                 call_void_bufop(q, fill_user_buffer, vb, pb);
1445
1446         /*
1447          * If streamon has been called, and we haven't yet called
1448          * start_streaming() since not enough buffers were queued, and
1449          * we now have reached the minimum number of queued buffers,
1450          * then we can finally call start_streaming().
1451          */
1452         if (q->streaming && !q->start_streaming_called &&
1453             q->queued_count >= q->min_buffers_needed) {
1454                 ret = vb2_start_streaming(q);
1455                 if (ret) {
1456                         /*
1457                          * Since vb2_core_qbuf will return with an error,
1458                          * we should return it to state DEQUEUED since
1459                          * the error indicates that the buffer wasn't queued.
1460                          */
1461                         list_del(&vb->queued_entry);
1462                         q->queued_count--;
1463                         vb->state = orig_state;
1464                         return ret;
1465                 }
1466         }
1467
1468         dprintk(2, "qbuf of buffer %d succeeded\n", vb->index);
1469         return 0;
1470 }
1471 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1472
1473 /*
1474  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1475  * for dequeuing
1476  *
1477  * Will sleep if required for nonblocking == false.
1478  */
1479 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1480 {
1481         /*
1482          * All operations on vb_done_list are performed under done_lock
1483          * spinlock protection. However, buffers may be removed from
1484          * it and returned to userspace only while holding both driver's
1485          * lock and the done_lock spinlock. Thus we can be sure that as
1486          * long as we hold the driver's lock, the list will remain not
1487          * empty if list_empty() check succeeds.
1488          */
1489
1490         for (;;) {
1491                 int ret;
1492
1493                 if (q->waiting_in_dqbuf) {
1494                         dprintk(1, "another dup()ped fd is waiting for a buffer\n");
1495                         return -EBUSY;
1496                 }
1497
1498                 if (!q->streaming) {
1499                         dprintk(1, "streaming off, will not wait for buffers\n");
1500                         return -EINVAL;
1501                 }
1502
1503                 if (q->error) {
1504                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1505                         return -EIO;
1506                 }
1507
1508                 if (q->last_buffer_dequeued) {
1509                         dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1510                         return -EPIPE;
1511                 }
1512
1513                 if (!list_empty(&q->done_list)) {
1514                         /*
1515                          * Found a buffer that we were waiting for.
1516                          */
1517                         break;
1518                 }
1519
1520                 if (nonblocking) {
1521                         dprintk(3, "nonblocking and no buffers to dequeue, will not wait\n");
1522                         return -EAGAIN;
1523                 }
1524
1525                 q->waiting_in_dqbuf = 1;
1526                 /*
1527                  * We are streaming and blocking, wait for another buffer to
1528                  * become ready or for streamoff. Driver's lock is released to
1529                  * allow streamoff or qbuf to be called while waiting.
1530                  */
1531                 call_void_qop(q, wait_prepare, q);
1532
1533                 /*
1534                  * All locks have been released, it is safe to sleep now.
1535                  */
1536                 dprintk(3, "will sleep waiting for buffers\n");
1537                 ret = wait_event_interruptible(q->done_wq,
1538                                 !list_empty(&q->done_list) || !q->streaming ||
1539                                 q->error);
1540
1541                 /*
1542                  * We need to reevaluate both conditions again after reacquiring
1543                  * the locks or return an error if one occurred.
1544                  */
1545                 call_void_qop(q, wait_finish, q);
1546                 q->waiting_in_dqbuf = 0;
1547                 if (ret) {
1548                         dprintk(1, "sleep was interrupted\n");
1549                         return ret;
1550                 }
1551         }
1552         return 0;
1553 }
1554
1555 /*
1556  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1557  *
1558  * Will sleep if required for nonblocking == false.
1559  */
1560 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1561                              void *pb, int nonblocking)
1562 {
1563         unsigned long flags;
1564         int ret = 0;
1565
1566         /*
1567          * Wait for at least one buffer to become available on the done_list.
1568          */
1569         ret = __vb2_wait_for_done_vb(q, nonblocking);
1570         if (ret)
1571                 return ret;
1572
1573         /*
1574          * Driver's lock has been held since we last verified that done_list
1575          * is not empty, so no need for another list_empty(done_list) check.
1576          */
1577         spin_lock_irqsave(&q->done_lock, flags);
1578         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1579         /*
1580          * Only remove the buffer from done_list if all planes can be
1581          * handled. Some cases such as V4L2 file I/O and DVB have pb
1582          * == NULL; skip the check then as there's nothing to verify.
1583          */
1584         if (pb)
1585                 ret = call_bufop(q, verify_planes_array, *vb, pb);
1586         if (!ret)
1587                 list_del(&(*vb)->done_entry);
1588         spin_unlock_irqrestore(&q->done_lock, flags);
1589
1590         return ret;
1591 }
1592
1593 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1594 {
1595         if (!q->streaming) {
1596                 dprintk(1, "streaming off, will not wait for buffers\n");
1597                 return -EINVAL;
1598         }
1599
1600         if (q->start_streaming_called)
1601                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1602         return 0;
1603 }
1604 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1605
1606 /*
1607  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1608  */
1609 static void __vb2_dqbuf(struct vb2_buffer *vb)
1610 {
1611         struct vb2_queue *q = vb->vb2_queue;
1612         unsigned int i;
1613
1614         /* nothing to do if the buffer is already dequeued */
1615         if (vb->state == VB2_BUF_STATE_DEQUEUED)
1616                 return;
1617
1618         vb->state = VB2_BUF_STATE_DEQUEUED;
1619
1620         /* unmap DMABUF buffer */
1621         if (q->memory == VB2_MEMORY_DMABUF)
1622                 for (i = 0; i < vb->num_planes; ++i) {
1623                         if (!vb->planes[i].dbuf_mapped)
1624                                 continue;
1625                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1626                         vb->planes[i].dbuf_mapped = 0;
1627                 }
1628 }
1629
1630 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1631                    bool nonblocking)
1632 {
1633         struct vb2_buffer *vb = NULL;
1634         int ret;
1635
1636         ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1637         if (ret < 0)
1638                 return ret;
1639
1640         switch (vb->state) {
1641         case VB2_BUF_STATE_DONE:
1642                 dprintk(3, "returning done buffer\n");
1643                 break;
1644         case VB2_BUF_STATE_ERROR:
1645                 dprintk(3, "returning done buffer with errors\n");
1646                 break;
1647         default:
1648                 dprintk(1, "invalid buffer state\n");
1649                 return -EINVAL;
1650         }
1651
1652         call_void_vb_qop(vb, buf_finish, vb);
1653
1654         if (pindex)
1655                 *pindex = vb->index;
1656
1657         /* Fill buffer information for the userspace */
1658         if (pb)
1659                 call_void_bufop(q, fill_user_buffer, vb, pb);
1660
1661         /* Remove from videobuf queue */
1662         list_del(&vb->queued_entry);
1663         q->queued_count--;
1664
1665         trace_vb2_dqbuf(q, vb);
1666
1667         /* go back to dequeued state */
1668         __vb2_dqbuf(vb);
1669
1670         dprintk(2, "dqbuf of buffer %d, with state %d\n",
1671                         vb->index, vb->state);
1672
1673         return 0;
1674
1675 }
1676 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1677
1678 /*
1679  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1680  *
1681  * Removes all queued buffers from driver's queue and all buffers queued by
1682  * userspace from videobuf's queue. Returns to state after reqbufs.
1683  */
1684 static void __vb2_queue_cancel(struct vb2_queue *q)
1685 {
1686         unsigned int i;
1687
1688         /*
1689          * Tell driver to stop all transactions and release all queued
1690          * buffers.
1691          */
1692         if (q->start_streaming_called)
1693                 call_void_qop(q, stop_streaming, q);
1694
1695         /*
1696          * If you see this warning, then the driver isn't cleaning up properly
1697          * in stop_streaming(). See the stop_streaming() documentation in
1698          * videobuf2-core.h for more information how buffers should be returned
1699          * to vb2 in stop_streaming().
1700          */
1701         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1702                 for (i = 0; i < q->num_buffers; ++i)
1703                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE) {
1704                                 pr_warn("driver bug: stop_streaming operation is leaving buf %p in active state\n",
1705                                         q->bufs[i]);
1706                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1707                         }
1708                 /* Must be zero now */
1709                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1710         }
1711
1712         q->streaming = 0;
1713         q->start_streaming_called = 0;
1714         q->queued_count = 0;
1715         q->error = 0;
1716
1717         /*
1718          * Remove all buffers from videobuf's list...
1719          */
1720         INIT_LIST_HEAD(&q->queued_list);
1721         /*
1722          * ...and done list; userspace will not receive any buffers it
1723          * has not already dequeued before initiating cancel.
1724          */
1725         INIT_LIST_HEAD(&q->done_list);
1726         atomic_set(&q->owned_by_drv_count, 0);
1727         wake_up_all(&q->done_wq);
1728
1729         /*
1730          * Reinitialize all buffers for next use.
1731          * Make sure to call buf_finish for any queued buffers. Normally
1732          * that's done in dqbuf, but that's not going to happen when we
1733          * cancel the whole queue. Note: this code belongs here, not in
1734          * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1735          * call to __fill_user_buffer() after buf_finish(). That order can't
1736          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1737          */
1738         for (i = 0; i < q->num_buffers; ++i) {
1739                 struct vb2_buffer *vb = q->bufs[i];
1740
1741                 if (vb->state == VB2_BUF_STATE_PREPARED ||
1742                     vb->state == VB2_BUF_STATE_QUEUED) {
1743                         unsigned int plane;
1744
1745                         for (plane = 0; plane < vb->num_planes; ++plane)
1746                                 call_void_memop(vb, finish,
1747                                                 vb->planes[plane].mem_priv);
1748                 }
1749
1750                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1751                         vb->state = VB2_BUF_STATE_PREPARED;
1752                         call_void_vb_qop(vb, buf_finish, vb);
1753                 }
1754                 __vb2_dqbuf(vb);
1755         }
1756 }
1757
1758 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1759 {
1760         int ret;
1761
1762         if (type != q->type) {
1763                 dprintk(1, "invalid stream type\n");
1764                 return -EINVAL;
1765         }
1766
1767         if (q->streaming) {
1768                 dprintk(3, "already streaming\n");
1769                 return 0;
1770         }
1771
1772         if (!q->num_buffers) {
1773                 dprintk(1, "no buffers have been allocated\n");
1774                 return -EINVAL;
1775         }
1776
1777         if (q->num_buffers < q->min_buffers_needed) {
1778                 dprintk(1, "need at least %u allocated buffers\n",
1779                                 q->min_buffers_needed);
1780                 return -EINVAL;
1781         }
1782
1783         /*
1784          * Tell driver to start streaming provided sufficient buffers
1785          * are available.
1786          */
1787         if (q->queued_count >= q->min_buffers_needed) {
1788                 ret = v4l_vb2q_enable_media_source(q);
1789                 if (ret)
1790                         return ret;
1791                 ret = vb2_start_streaming(q);
1792                 if (ret)
1793                         return ret;
1794         }
1795
1796         q->streaming = 1;
1797
1798         dprintk(3, "successful\n");
1799         return 0;
1800 }
1801 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1802
1803 void vb2_queue_error(struct vb2_queue *q)
1804 {
1805         q->error = 1;
1806
1807         wake_up_all(&q->done_wq);
1808 }
1809 EXPORT_SYMBOL_GPL(vb2_queue_error);
1810
1811 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1812 {
1813         if (type != q->type) {
1814                 dprintk(1, "invalid stream type\n");
1815                 return -EINVAL;
1816         }
1817
1818         /*
1819          * Cancel will pause streaming and remove all buffers from the driver
1820          * and videobuf, effectively returning control over them to userspace.
1821          *
1822          * Note that we do this even if q->streaming == 0: if you prepare or
1823          * queue buffers, and then call streamoff without ever having called
1824          * streamon, you would still expect those buffers to be returned to
1825          * their normal dequeued state.
1826          */
1827         __vb2_queue_cancel(q);
1828         q->waiting_for_buffers = !q->is_output;
1829         q->last_buffer_dequeued = false;
1830
1831         dprintk(3, "successful\n");
1832         return 0;
1833 }
1834 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1835
1836 /*
1837  * __find_plane_by_offset() - find plane associated with the given offset off
1838  */
1839 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1840                         unsigned int *_buffer, unsigned int *_plane)
1841 {
1842         struct vb2_buffer *vb;
1843         unsigned int buffer, plane;
1844
1845         /*
1846          * Go over all buffers and their planes, comparing the given offset
1847          * with an offset assigned to each plane. If a match is found,
1848          * return its buffer and plane numbers.
1849          */
1850         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1851                 vb = q->bufs[buffer];
1852
1853                 for (plane = 0; plane < vb->num_planes; ++plane) {
1854                         if (vb->planes[plane].m.offset == off) {
1855                                 *_buffer = buffer;
1856                                 *_plane = plane;
1857                                 return 0;
1858                         }
1859                 }
1860         }
1861
1862         return -EINVAL;
1863 }
1864
1865 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1866                 unsigned int index, unsigned int plane, unsigned int flags)
1867 {
1868         struct vb2_buffer *vb = NULL;
1869         struct vb2_plane *vb_plane;
1870         int ret;
1871         struct dma_buf *dbuf;
1872
1873         if (q->memory != VB2_MEMORY_MMAP) {
1874                 dprintk(1, "queue is not currently set up for mmap\n");
1875                 return -EINVAL;
1876         }
1877
1878         if (!q->mem_ops->get_dmabuf) {
1879                 dprintk(1, "queue does not support DMA buffer exporting\n");
1880                 return -EINVAL;
1881         }
1882
1883         if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1884                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1885                 return -EINVAL;
1886         }
1887
1888         if (type != q->type) {
1889                 dprintk(1, "invalid buffer type\n");
1890                 return -EINVAL;
1891         }
1892
1893         if (index >= q->num_buffers) {
1894                 dprintk(1, "buffer index out of range\n");
1895                 return -EINVAL;
1896         }
1897
1898         vb = q->bufs[index];
1899
1900         if (plane >= vb->num_planes) {
1901                 dprintk(1, "buffer plane out of range\n");
1902                 return -EINVAL;
1903         }
1904
1905         if (vb2_fileio_is_active(q)) {
1906                 dprintk(1, "expbuf: file io in progress\n");
1907                 return -EBUSY;
1908         }
1909
1910         vb_plane = &vb->planes[plane];
1911
1912         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1913                                 flags & O_ACCMODE);
1914         if (IS_ERR_OR_NULL(dbuf)) {
1915                 dprintk(1, "failed to export buffer %d, plane %d\n",
1916                         index, plane);
1917                 return -EINVAL;
1918         }
1919
1920         ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1921         if (ret < 0) {
1922                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1923                         index, plane, ret);
1924                 dma_buf_put(dbuf);
1925                 return ret;
1926         }
1927
1928         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1929                 index, plane, ret);
1930         *fd = ret;
1931
1932         return 0;
1933 }
1934 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1935
1936 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1937 {
1938         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1939         struct vb2_buffer *vb;
1940         unsigned int buffer = 0, plane = 0;
1941         int ret;
1942         unsigned long length;
1943
1944         if (q->memory != VB2_MEMORY_MMAP) {
1945                 dprintk(1, "queue is not currently set up for mmap\n");
1946                 return -EINVAL;
1947         }
1948
1949         /*
1950          * Check memory area access mode.
1951          */
1952         if (!(vma->vm_flags & VM_SHARED)) {
1953                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1954                 return -EINVAL;
1955         }
1956         if (q->is_output) {
1957                 if (!(vma->vm_flags & VM_WRITE)) {
1958                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1959                         return -EINVAL;
1960                 }
1961         } else {
1962                 if (!(vma->vm_flags & VM_READ)) {
1963                         dprintk(1, "invalid vma flags, VM_READ needed\n");
1964                         return -EINVAL;
1965                 }
1966         }
1967
1968         mutex_lock(&q->mmap_lock);
1969
1970         if (vb2_fileio_is_active(q)) {
1971                 dprintk(1, "mmap: file io in progress\n");
1972                 ret = -EBUSY;
1973                 goto unlock;
1974         }
1975
1976         /*
1977          * Find the plane corresponding to the offset passed by userspace.
1978          */
1979         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1980         if (ret)
1981                 goto unlock;
1982
1983         vb = q->bufs[buffer];
1984
1985         /*
1986          * MMAP requires page_aligned buffers.
1987          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1988          * so, we need to do the same here.
1989          */
1990         length = PAGE_ALIGN(vb->planes[plane].length);
1991         if (length < (vma->vm_end - vma->vm_start)) {
1992                 dprintk(1,
1993                         "MMAP invalid, as it would overflow buffer length\n");
1994                 ret = -EINVAL;
1995                 goto unlock;
1996         }
1997
1998         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1999
2000 unlock:
2001         mutex_unlock(&q->mmap_lock);
2002         if (ret)
2003                 return ret;
2004
2005         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
2006         return 0;
2007 }
2008 EXPORT_SYMBOL_GPL(vb2_mmap);
2009
2010 #ifndef CONFIG_MMU
2011 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2012                                     unsigned long addr,
2013                                     unsigned long len,
2014                                     unsigned long pgoff,
2015                                     unsigned long flags)
2016 {
2017         unsigned long off = pgoff << PAGE_SHIFT;
2018         struct vb2_buffer *vb;
2019         unsigned int buffer, plane;
2020         void *vaddr;
2021         int ret;
2022
2023         if (q->memory != VB2_MEMORY_MMAP) {
2024                 dprintk(1, "queue is not currently set up for mmap\n");
2025                 return -EINVAL;
2026         }
2027
2028         /*
2029          * Find the plane corresponding to the offset passed by userspace.
2030          */
2031         ret = __find_plane_by_offset(q, off, &buffer, &plane);
2032         if (ret)
2033                 return ret;
2034
2035         vb = q->bufs[buffer];
2036
2037         vaddr = vb2_plane_vaddr(vb, plane);
2038         return vaddr ? (unsigned long)vaddr : -EINVAL;
2039 }
2040 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2041 #endif
2042
2043 int vb2_core_queue_init(struct vb2_queue *q)
2044 {
2045         /*
2046          * Sanity check
2047          */
2048         if (WARN_ON(!q)                   ||
2049             WARN_ON(!q->ops)              ||
2050             WARN_ON(!q->mem_ops)          ||
2051             WARN_ON(!q->type)             ||
2052             WARN_ON(!q->io_modes)         ||
2053             WARN_ON(!q->ops->queue_setup) ||
2054             WARN_ON(!q->ops->buf_queue))
2055                 return -EINVAL;
2056
2057         INIT_LIST_HEAD(&q->queued_list);
2058         INIT_LIST_HEAD(&q->done_list);
2059         spin_lock_init(&q->done_lock);
2060         mutex_init(&q->mmap_lock);
2061         init_waitqueue_head(&q->done_wq);
2062
2063         q->memory = VB2_MEMORY_UNKNOWN;
2064
2065         if (q->buf_struct_size == 0)
2066                 q->buf_struct_size = sizeof(struct vb2_buffer);
2067
2068         if (q->bidirectional)
2069                 q->dma_dir = DMA_BIDIRECTIONAL;
2070         else
2071                 q->dma_dir = q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
2072
2073         return 0;
2074 }
2075 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2076
2077 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2078 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2079 void vb2_core_queue_release(struct vb2_queue *q)
2080 {
2081         __vb2_cleanup_fileio(q);
2082         __vb2_queue_cancel(q);
2083         mutex_lock(&q->mmap_lock);
2084         __vb2_queue_free(q, q->num_buffers);
2085         mutex_unlock(&q->mmap_lock);
2086 }
2087 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2088
2089 __poll_t vb2_core_poll(struct vb2_queue *q, struct file *file,
2090                 poll_table *wait)
2091 {
2092         __poll_t req_events = poll_requested_events(wait);
2093         struct vb2_buffer *vb = NULL;
2094         unsigned long flags;
2095
2096         if (!q->is_output && !(req_events & (EPOLLIN | EPOLLRDNORM)))
2097                 return 0;
2098         if (q->is_output && !(req_events & (EPOLLOUT | EPOLLWRNORM)))
2099                 return 0;
2100
2101         /*
2102          * Start file I/O emulator only if streaming API has not been used yet.
2103          */
2104         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2105                 if (!q->is_output && (q->io_modes & VB2_READ) &&
2106                                 (req_events & (EPOLLIN | EPOLLRDNORM))) {
2107                         if (__vb2_init_fileio(q, 1))
2108                                 return EPOLLERR;
2109                 }
2110                 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2111                                 (req_events & (EPOLLOUT | EPOLLWRNORM))) {
2112                         if (__vb2_init_fileio(q, 0))
2113                                 return EPOLLERR;
2114                         /*
2115                          * Write to OUTPUT queue can be done immediately.
2116                          */
2117                         return EPOLLOUT | EPOLLWRNORM;
2118                 }
2119         }
2120
2121         /*
2122          * There is nothing to wait for if the queue isn't streaming, or if the
2123          * error flag is set.
2124          */
2125         if (!vb2_is_streaming(q) || q->error)
2126                 return EPOLLERR;
2127
2128         /*
2129          * If this quirk is set and QBUF hasn't been called yet then
2130          * return EPOLLERR as well. This only affects capture queues, output
2131          * queues will always initialize waiting_for_buffers to false.
2132          * This quirk is set by V4L2 for backwards compatibility reasons.
2133          */
2134         if (q->quirk_poll_must_check_waiting_for_buffers &&
2135             q->waiting_for_buffers && (req_events & (EPOLLIN | EPOLLRDNORM)))
2136                 return EPOLLERR;
2137
2138         /*
2139          * For output streams you can call write() as long as there are fewer
2140          * buffers queued than there are buffers available.
2141          */
2142         if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2143                 return EPOLLOUT | EPOLLWRNORM;
2144
2145         if (list_empty(&q->done_list)) {
2146                 /*
2147                  * If the last buffer was dequeued from a capture queue,
2148                  * return immediately. DQBUF will return -EPIPE.
2149                  */
2150                 if (q->last_buffer_dequeued)
2151                         return EPOLLIN | EPOLLRDNORM;
2152
2153                 poll_wait(file, &q->done_wq, wait);
2154         }
2155
2156         /*
2157          * Take first buffer available for dequeuing.
2158          */
2159         spin_lock_irqsave(&q->done_lock, flags);
2160         if (!list_empty(&q->done_list))
2161                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2162                                         done_entry);
2163         spin_unlock_irqrestore(&q->done_lock, flags);
2164
2165         if (vb && (vb->state == VB2_BUF_STATE_DONE
2166                         || vb->state == VB2_BUF_STATE_ERROR)) {
2167                 return (q->is_output) ?
2168                                 EPOLLOUT | EPOLLWRNORM :
2169                                 EPOLLIN | EPOLLRDNORM;
2170         }
2171         return 0;
2172 }
2173 EXPORT_SYMBOL_GPL(vb2_core_poll);
2174
2175 /*
2176  * struct vb2_fileio_buf - buffer context used by file io emulator
2177  *
2178  * vb2 provides a compatibility layer and emulator of file io (read and
2179  * write) calls on top of streaming API. This structure is used for
2180  * tracking context related to the buffers.
2181  */
2182 struct vb2_fileio_buf {
2183         void *vaddr;
2184         unsigned int size;
2185         unsigned int pos;
2186         unsigned int queued:1;
2187 };
2188
2189 /*
2190  * struct vb2_fileio_data - queue context used by file io emulator
2191  *
2192  * @cur_index:  the index of the buffer currently being read from or
2193  *              written to. If equal to q->num_buffers then a new buffer
2194  *              must be dequeued.
2195  * @initial_index: in the read() case all buffers are queued up immediately
2196  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2197  *              buffers. However, in the write() case no buffers are initially
2198  *              queued, instead whenever a buffer is full it is queued up by
2199  *              __vb2_perform_fileio(). Only once all available buffers have
2200  *              been queued up will __vb2_perform_fileio() start to dequeue
2201  *              buffers. This means that initially __vb2_perform_fileio()
2202  *              needs to know what buffer index to use when it is queuing up
2203  *              the buffers for the first time. That initial index is stored
2204  *              in this field. Once it is equal to q->num_buffers all
2205  *              available buffers have been queued and __vb2_perform_fileio()
2206  *              should start the normal dequeue/queue cycle.
2207  *
2208  * vb2 provides a compatibility layer and emulator of file io (read and
2209  * write) calls on top of streaming API. For proper operation it required
2210  * this structure to save the driver state between each call of the read
2211  * or write function.
2212  */
2213 struct vb2_fileio_data {
2214         unsigned int count;
2215         unsigned int type;
2216         unsigned int memory;
2217         struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2218         unsigned int cur_index;
2219         unsigned int initial_index;
2220         unsigned int q_count;
2221         unsigned int dq_count;
2222         unsigned read_once:1;
2223         unsigned write_immediately:1;
2224 };
2225
2226 /*
2227  * __vb2_init_fileio() - initialize file io emulator
2228  * @q:          videobuf2 queue
2229  * @read:       mode selector (1 means read, 0 means write)
2230  */
2231 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2232 {
2233         struct vb2_fileio_data *fileio;
2234         int i, ret;
2235         unsigned int count = 0;
2236
2237         /*
2238          * Sanity check
2239          */
2240         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2241                     (!read && !(q->io_modes & VB2_WRITE))))
2242                 return -EINVAL;
2243
2244         /*
2245          * Check if device supports mapping buffers to kernel virtual space.
2246          */
2247         if (!q->mem_ops->vaddr)
2248                 return -EBUSY;
2249
2250         /*
2251          * Check if streaming api has not been already activated.
2252          */
2253         if (q->streaming || q->num_buffers > 0)
2254                 return -EBUSY;
2255
2256         /*
2257          * Start with count 1, driver can increase it in queue_setup()
2258          */
2259         count = 1;
2260
2261         dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2262                 (read) ? "read" : "write", count, q->fileio_read_once,
2263                 q->fileio_write_immediately);
2264
2265         fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2266         if (fileio == NULL)
2267                 return -ENOMEM;
2268
2269         fileio->read_once = q->fileio_read_once;
2270         fileio->write_immediately = q->fileio_write_immediately;
2271
2272         /*
2273          * Request buffers and use MMAP type to force driver
2274          * to allocate buffers by itself.
2275          */
2276         fileio->count = count;
2277         fileio->memory = VB2_MEMORY_MMAP;
2278         fileio->type = q->type;
2279         q->fileio = fileio;
2280         ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2281         if (ret)
2282                 goto err_kfree;
2283
2284         /*
2285          * Check if plane_count is correct
2286          * (multiplane buffers are not supported).
2287          */
2288         if (q->bufs[0]->num_planes != 1) {
2289                 ret = -EBUSY;
2290                 goto err_reqbufs;
2291         }
2292
2293         /*
2294          * Get kernel address of each buffer.
2295          */
2296         for (i = 0; i < q->num_buffers; i++) {
2297                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2298                 if (fileio->bufs[i].vaddr == NULL) {
2299                         ret = -EINVAL;
2300                         goto err_reqbufs;
2301                 }
2302                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2303         }
2304
2305         /*
2306          * Read mode requires pre queuing of all buffers.
2307          */
2308         if (read) {
2309                 /*
2310                  * Queue all buffers.
2311                  */
2312                 for (i = 0; i < q->num_buffers; i++) {
2313                         ret = vb2_core_qbuf(q, i, NULL);
2314                         if (ret)
2315                                 goto err_reqbufs;
2316                         fileio->bufs[i].queued = 1;
2317                 }
2318                 /*
2319                  * All buffers have been queued, so mark that by setting
2320                  * initial_index to q->num_buffers
2321                  */
2322                 fileio->initial_index = q->num_buffers;
2323                 fileio->cur_index = q->num_buffers;
2324         }
2325
2326         /*
2327          * Start streaming.
2328          */
2329         ret = vb2_core_streamon(q, q->type);
2330         if (ret)
2331                 goto err_reqbufs;
2332
2333         return ret;
2334
2335 err_reqbufs:
2336         fileio->count = 0;
2337         vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2338
2339 err_kfree:
2340         q->fileio = NULL;
2341         kfree(fileio);
2342         return ret;
2343 }
2344
2345 /*
2346  * __vb2_cleanup_fileio() - free resourced used by file io emulator
2347  * @q:          videobuf2 queue
2348  */
2349 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2350 {
2351         struct vb2_fileio_data *fileio = q->fileio;
2352
2353         if (fileio) {
2354                 vb2_core_streamoff(q, q->type);
2355                 q->fileio = NULL;
2356                 fileio->count = 0;
2357                 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2358                 kfree(fileio);
2359                 dprintk(3, "file io emulator closed\n");
2360         }
2361         return 0;
2362 }
2363
2364 /*
2365  * __vb2_perform_fileio() - perform a single file io (read or write) operation
2366  * @q:          videobuf2 queue
2367  * @data:       pointed to target userspace buffer
2368  * @count:      number of bytes to read or write
2369  * @ppos:       file handle position tracking pointer
2370  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
2371  * @read:       access mode selector (1 means read, 0 means write)
2372  */
2373 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2374                 loff_t *ppos, int nonblock, int read)
2375 {
2376         struct vb2_fileio_data *fileio;
2377         struct vb2_fileio_buf *buf;
2378         bool is_multiplanar = q->is_multiplanar;
2379         /*
2380          * When using write() to write data to an output video node the vb2 core
2381          * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2382          * else is able to provide this information with the write() operation.
2383          */
2384         bool copy_timestamp = !read && q->copy_timestamp;
2385         unsigned index;
2386         int ret;
2387
2388         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2389                 read ? "read" : "write", (long)*ppos, count,
2390                 nonblock ? "non" : "");
2391
2392         if (!data)
2393                 return -EINVAL;
2394
2395         if (q->waiting_in_dqbuf) {
2396                 dprintk(3, "another dup()ped fd is %s\n",
2397                         read ? "reading" : "writing");
2398                 return -EBUSY;
2399         }
2400
2401         /*
2402          * Initialize emulator on first call.
2403          */
2404         if (!vb2_fileio_is_active(q)) {
2405                 ret = __vb2_init_fileio(q, read);
2406                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2407                 if (ret)
2408                         return ret;
2409         }
2410         fileio = q->fileio;
2411
2412         /*
2413          * Check if we need to dequeue the buffer.
2414          */
2415         index = fileio->cur_index;
2416         if (index >= q->num_buffers) {
2417                 struct vb2_buffer *b;
2418
2419                 /*
2420                  * Call vb2_dqbuf to get buffer back.
2421                  */
2422                 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2423                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2424                 if (ret)
2425                         return ret;
2426                 fileio->dq_count += 1;
2427
2428                 fileio->cur_index = index;
2429                 buf = &fileio->bufs[index];
2430                 b = q->bufs[index];
2431
2432                 /*
2433                  * Get number of bytes filled by the driver
2434                  */
2435                 buf->pos = 0;
2436                 buf->queued = 0;
2437                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2438                                  : vb2_plane_size(q->bufs[index], 0);
2439                 /* Compensate for data_offset on read in the multiplanar case. */
2440                 if (is_multiplanar && read &&
2441                                 b->planes[0].data_offset < buf->size) {
2442                         buf->pos = b->planes[0].data_offset;
2443                         buf->size -= buf->pos;
2444                 }
2445         } else {
2446                 buf = &fileio->bufs[index];
2447         }
2448
2449         /*
2450          * Limit count on last few bytes of the buffer.
2451          */
2452         if (buf->pos + count > buf->size) {
2453                 count = buf->size - buf->pos;
2454                 dprintk(5, "reducing read count: %zd\n", count);
2455         }
2456
2457         /*
2458          * Transfer data to userspace.
2459          */
2460         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2461                 count, index, buf->pos);
2462         if (read)
2463                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2464         else
2465                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2466         if (ret) {
2467                 dprintk(3, "error copying data\n");
2468                 return -EFAULT;
2469         }
2470
2471         /*
2472          * Update counters.
2473          */
2474         buf->pos += count;
2475         *ppos += count;
2476
2477         /*
2478          * Queue next buffer if required.
2479          */
2480         if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2481                 struct vb2_buffer *b = q->bufs[index];
2482
2483                 /*
2484                  * Check if this is the last buffer to read.
2485                  */
2486                 if (read && fileio->read_once && fileio->dq_count == 1) {
2487                         dprintk(3, "read limit reached\n");
2488                         return __vb2_cleanup_fileio(q);
2489                 }
2490
2491                 /*
2492                  * Call vb2_qbuf and give buffer to the driver.
2493                  */
2494                 b->planes[0].bytesused = buf->pos;
2495
2496                 if (copy_timestamp)
2497                         b->timestamp = ktime_get_ns();
2498                 ret = vb2_core_qbuf(q, index, NULL);
2499                 dprintk(5, "vb2_dbuf result: %d\n", ret);
2500                 if (ret)
2501                         return ret;
2502
2503                 /*
2504                  * Buffer has been queued, update the status
2505                  */
2506                 buf->pos = 0;
2507                 buf->queued = 1;
2508                 buf->size = vb2_plane_size(q->bufs[index], 0);
2509                 fileio->q_count += 1;
2510                 /*
2511                  * If we are queuing up buffers for the first time, then
2512                  * increase initial_index by one.
2513                  */
2514                 if (fileio->initial_index < q->num_buffers)
2515                         fileio->initial_index++;
2516                 /*
2517                  * The next buffer to use is either a buffer that's going to be
2518                  * queued for the first time (initial_index < q->num_buffers)
2519                  * or it is equal to q->num_buffers, meaning that the next
2520                  * time we need to dequeue a buffer since we've now queued up
2521                  * all the 'first time' buffers.
2522                  */
2523                 fileio->cur_index = fileio->initial_index;
2524         }
2525
2526         /*
2527          * Return proper number of bytes processed.
2528          */
2529         if (ret == 0)
2530                 ret = count;
2531         return ret;
2532 }
2533
2534 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2535                 loff_t *ppos, int nonblocking)
2536 {
2537         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2538 }
2539 EXPORT_SYMBOL_GPL(vb2_read);
2540
2541 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2542                 loff_t *ppos, int nonblocking)
2543 {
2544         return __vb2_perform_fileio(q, (char __user *) data, count,
2545                                                         ppos, nonblocking, 0);
2546 }
2547 EXPORT_SYMBOL_GPL(vb2_write);
2548
2549 struct vb2_threadio_data {
2550         struct task_struct *thread;
2551         vb2_thread_fnc fnc;
2552         void *priv;
2553         bool stop;
2554 };
2555
2556 static int vb2_thread(void *data)
2557 {
2558         struct vb2_queue *q = data;
2559         struct vb2_threadio_data *threadio = q->threadio;
2560         bool copy_timestamp = false;
2561         unsigned prequeue = 0;
2562         unsigned index = 0;
2563         int ret = 0;
2564
2565         if (q->is_output) {
2566                 prequeue = q->num_buffers;
2567                 copy_timestamp = q->copy_timestamp;
2568         }
2569
2570         set_freezable();
2571
2572         for (;;) {
2573                 struct vb2_buffer *vb;
2574
2575                 /*
2576                  * Call vb2_dqbuf to get buffer back.
2577                  */
2578                 if (prequeue) {
2579                         vb = q->bufs[index++];
2580                         prequeue--;
2581                 } else {
2582                         call_void_qop(q, wait_finish, q);
2583                         if (!threadio->stop)
2584                                 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2585                         call_void_qop(q, wait_prepare, q);
2586                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2587                         if (!ret)
2588                                 vb = q->bufs[index];
2589                 }
2590                 if (ret || threadio->stop)
2591                         break;
2592                 try_to_freeze();
2593
2594                 if (vb->state != VB2_BUF_STATE_ERROR)
2595                         if (threadio->fnc(vb, threadio->priv))
2596                                 break;
2597                 call_void_qop(q, wait_finish, q);
2598                 if (copy_timestamp)
2599                         vb->timestamp = ktime_get_ns();
2600                 if (!threadio->stop)
2601                         ret = vb2_core_qbuf(q, vb->index, NULL);
2602                 call_void_qop(q, wait_prepare, q);
2603                 if (ret || threadio->stop)
2604                         break;
2605         }
2606
2607         /* Hmm, linux becomes *very* unhappy without this ... */
2608         while (!kthread_should_stop()) {
2609                 set_current_state(TASK_INTERRUPTIBLE);
2610                 schedule();
2611         }
2612         return 0;
2613 }
2614
2615 /*
2616  * This function should not be used for anything else but the videobuf2-dvb
2617  * support. If you think you have another good use-case for this, then please
2618  * contact the linux-media mailinglist first.
2619  */
2620 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2621                      const char *thread_name)
2622 {
2623         struct vb2_threadio_data *threadio;
2624         int ret = 0;
2625
2626         if (q->threadio)
2627                 return -EBUSY;
2628         if (vb2_is_busy(q))
2629                 return -EBUSY;
2630         if (WARN_ON(q->fileio))
2631                 return -EBUSY;
2632
2633         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2634         if (threadio == NULL)
2635                 return -ENOMEM;
2636         threadio->fnc = fnc;
2637         threadio->priv = priv;
2638
2639         ret = __vb2_init_fileio(q, !q->is_output);
2640         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2641         if (ret)
2642                 goto nomem;
2643         q->threadio = threadio;
2644         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2645         if (IS_ERR(threadio->thread)) {
2646                 ret = PTR_ERR(threadio->thread);
2647                 threadio->thread = NULL;
2648                 goto nothread;
2649         }
2650         return 0;
2651
2652 nothread:
2653         __vb2_cleanup_fileio(q);
2654 nomem:
2655         kfree(threadio);
2656         return ret;
2657 }
2658 EXPORT_SYMBOL_GPL(vb2_thread_start);
2659
2660 int vb2_thread_stop(struct vb2_queue *q)
2661 {
2662         struct vb2_threadio_data *threadio = q->threadio;
2663         int err;
2664
2665         if (threadio == NULL)
2666                 return 0;
2667         threadio->stop = true;
2668         /* Wake up all pending sleeps in the thread */
2669         vb2_queue_error(q);
2670         err = kthread_stop(threadio->thread);
2671         __vb2_cleanup_fileio(q);
2672         threadio->thread = NULL;
2673         kfree(threadio);
2674         q->threadio = NULL;
2675         return err;
2676 }
2677 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2678
2679 MODULE_DESCRIPTION("Media buffer core framework");
2680 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2681 MODULE_LICENSE("GPL");