Linux 4.19.133
[linux/fpc-iii.git] / drivers / media / common / videobuf2 / videobuf2-core.c
blob93d250db0b6f06616f0654f37a49c2c6b2e8741e
1 /*
2 * videobuf2-core.c - video buffer 2 core framework
4 * Copyright (C) 2010 Samsung Electronics
6 * Author: Pawel Osciak <pawel@osciak.com>
7 * Marek Szyprowski <m.szyprowski@samsung.com>
9 * The vb2_thread implementation was based on code from videobuf-dvb.c:
10 * (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
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.
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
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>
29 #include <media/videobuf2-core.h>
30 #include <media/v4l2-mc.h>
32 #include <trace/events/vb2.h>
34 static int debug;
35 module_param(debug, int, 0644);
37 #define dprintk(level, fmt, arg...) \
38 do { \
39 if (debug >= level) \
40 pr_info("%s: " fmt, __func__, ## arg); \
41 } while (0)
43 #ifdef CONFIG_VIDEO_ADV_DEBUG
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.
49 * This makes it easy to check that the 'init' and 'cleanup'
50 * (and variations thereof) stay balanced.
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)")
58 #define call_memop(vb, op, args...) \
59 ({ \
60 struct vb2_queue *_q = (vb)->vb2_queue; \
61 int err; \
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; \
70 #define call_ptr_memop(vb, op, args...) \
71 ({ \
72 struct vb2_queue *_q = (vb)->vb2_queue; \
73 void *ptr; \
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; \
82 #define call_void_memop(vb, op, args...) \
83 ({ \
84 struct vb2_queue *_q = (vb)->vb2_queue; \
86 log_memop(vb, op); \
87 if (_q->mem_ops->op) \
88 _q->mem_ops->op(args); \
89 (vb)->cnt_mem_ ## op++; \
92 #define log_qop(q, op) \
93 dprintk(2, "call_qop(%p, %s)%s\n", q, #op, \
94 (q)->ops->op ? "" : " (nop)")
96 #define call_qop(q, op, args...) \
97 ({ \
98 int err; \
100 log_qop(q, op); \
101 err = (q)->ops->op ? (q)->ops->op(args) : 0; \
102 if (!err) \
103 (q)->cnt_ ## op++; \
104 err; \
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++; \
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)")
120 #define call_vb_qop(vb, op, args...) \
121 ({ \
122 int err; \
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; \
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++; \
140 #else
142 #define call_memop(vb, op, args...) \
143 ((vb)->vb2_queue->mem_ops->op ? \
144 (vb)->vb2_queue->mem_ops->op(args) : 0)
146 #define call_ptr_memop(vb, op, args...) \
147 ((vb)->vb2_queue->mem_ops->op ? \
148 (vb)->vb2_queue->mem_ops->op(args) : NULL)
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)
156 #define call_qop(q, op, args...) \
157 ((q)->ops->op ? (q)->ops->op(args) : 0)
159 #define call_void_qop(q, op, args...) \
160 do { \
161 if ((q)->ops->op) \
162 (q)->ops->op(args); \
163 } while (0)
165 #define call_vb_qop(vb, op, args...) \
166 ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
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)
174 #endif
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; \
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); \
190 static void __vb2_queue_cancel(struct vb2_queue *q);
191 static void __enqueue_in_driver(struct vb2_buffer *vb);
194 * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
196 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
198 struct vb2_queue *q = vb->vb2_queue;
199 void *mem_priv;
200 int plane;
201 int ret = -ENOMEM;
204 * Allocate memory for all planes in this buffer
205 * NOTE: mmapped areas should be page aligned
207 for (plane = 0; plane < vb->num_planes; ++plane) {
208 unsigned long size = PAGE_ALIGN(vb->planes[plane].length);
210 /* Did it wrap around? */
211 if (size < vb->planes[plane].length)
212 goto free;
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;
223 /* Associate allocator private data with this plane */
224 vb->planes[plane].mem_priv = mem_priv;
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;
235 return ret;
239 * __vb2_buf_mem_free() - free memory of the given buffer
241 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
243 unsigned int plane;
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);
253 * __vb2_buf_userptr_put() - release userspace memory associated with
254 * a USERPTR buffer
256 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
258 unsigned int plane;
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;
268 * __vb2_plane_dmabuf_put() - release memory associated with
269 * a DMABUF shared plane
271 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
273 if (!p->mem_priv)
274 return;
276 if (p->dbuf_mapped)
277 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
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;
287 * __vb2_buf_dmabuf_put() - release memory associated with
288 * a DMABUF shared buffer
290 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
292 unsigned int plane;
294 for (plane = 0; plane < vb->num_planes; ++plane)
295 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
299 * __setup_offsets() - setup unique offsets ("cookies") for every plane in
300 * the buffer.
302 static void __setup_offsets(struct vb2_buffer *vb)
304 struct vb2_queue *q = vb->vb2_queue;
305 unsigned int plane;
306 unsigned long off = 0;
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];
312 off = PAGE_ALIGN(p->m.offset + p->length);
315 for (plane = 0; plane < vb->num_planes; ++plane) {
316 vb->planes[plane].m.offset = off;
318 dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
319 vb->index, plane, off);
321 off += vb->planes[plane].length;
322 off = PAGE_ALIGN(off);
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
331 * Returns the number of buffers successfully allocated.
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])
337 unsigned int buffer, plane;
338 struct vb2_buffer *vb;
339 int ret;
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);
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;
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];
363 q->bufs[vb->index] = vb;
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;
375 __setup_offsets(vb);
377 * Call the driver-provided buffer initialization
378 * callback, if given. An error in initialization
379 * results in queue setup failure.
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;
393 dprintk(1, "allocated %d buffers, %d plane(s) each\n",
394 buffer, num_planes);
396 return buffer;
400 * __vb2_free_mem() - release all video buffer memory for a given queue
402 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
404 unsigned int buffer;
405 struct vb2_buffer *vb;
407 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
408 ++buffer) {
409 vb = q->bufs[buffer];
410 if (!vb)
411 continue;
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);
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.
428 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
430 unsigned int buffer;
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.
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;
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];
455 if (vb && vb->planes[0].mem_priv)
456 call_void_vb_qop(vb, buf_cleanup, vb);
459 /* Release video buffer memory */
460 __vb2_free_mem(q, buffers);
462 #ifdef CONFIG_VIDEO_ADV_DEBUG
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.
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;
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);
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;
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;
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);
522 #endif
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;
531 q->num_buffers -= buffers;
532 if (!q->num_buffers) {
533 q->memory = VB2_MEMORY_UNKNOWN;
534 INIT_LIST_HEAD(&q->queued_list);
536 return 0;
539 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
541 unsigned int plane;
542 for (plane = 0; plane < vb->num_planes; ++plane) {
543 void *mem_priv = vb->planes[plane].mem_priv;
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.
550 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
551 return true;
553 return false;
555 EXPORT_SYMBOL(vb2_buffer_in_use);
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
561 static bool __buffers_in_use(struct vb2_queue *q)
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;
568 return false;
571 void vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
573 call_void_bufop(q, fill_user_buffer, q->bufs[index], pb);
575 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
578 * __verify_userptr_ops() - verify that all memory operations required for
579 * USERPTR queue type have been provided
581 static int __verify_userptr_ops(struct vb2_queue *q)
583 if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
584 !q->mem_ops->put_userptr)
585 return -EINVAL;
587 return 0;
591 * __verify_mmap_ops() - verify that all memory operations required for
592 * MMAP queue type have been provided
594 static int __verify_mmap_ops(struct vb2_queue *q)
596 if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
597 !q->mem_ops->put || !q->mem_ops->mmap)
598 return -EINVAL;
600 return 0;
604 * __verify_dmabuf_ops() - verify that all memory operations required for
605 * DMABUF queue type have been provided
607 static int __verify_dmabuf_ops(struct vb2_queue *q)
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;
614 return 0;
617 int vb2_verify_memory_type(struct vb2_queue *q,
618 enum vb2_memory memory, unsigned int type)
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;
626 if (type != q->type) {
627 dprintk(1, "requested type is incorrect\n");
628 return -EINVAL;
632 * Make sure all the required memory ops for given memory type
633 * are available.
635 if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
636 dprintk(1, "MMAP for current setup unsupported\n");
637 return -EINVAL;
640 if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
641 dprintk(1, "USERPTR for current setup unsupported\n");
642 return -EINVAL;
645 if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
646 dprintk(1, "DMABUF for current setup unsupported\n");
647 return -EINVAL;
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.
655 if (vb2_fileio_is_active(q)) {
656 dprintk(1, "file io in progress\n");
657 return -EBUSY;
659 return 0;
661 EXPORT_SYMBOL(vb2_verify_memory_type);
663 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
664 unsigned int *count)
666 unsigned int num_buffers, allocated_buffers, num_planes = 0;
667 unsigned plane_sizes[VB2_MAX_PLANES] = { };
668 int ret;
670 if (q->streaming) {
671 dprintk(1, "streaming active\n");
672 return -EBUSY;
675 if (q->waiting_in_dqbuf && *count) {
676 dprintk(1, "another dup()ped fd is waiting for a buffer\n");
677 return -EBUSY;
680 if (*count == 0 || q->num_buffers != 0 ||
681 (q->memory != VB2_MEMORY_UNKNOWN && q->memory != memory)) {
683 * We already have buffers allocated, so first check if they
684 * are not in use and can be freed.
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;
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.
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;
705 * In case of REQBUFS(0) return immediately without calling
706 * driver's queue_setup() callback and allocating resources.
708 if (*count == 0)
709 return 0;
713 * Make sure the requested values and current defaults are sane.
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;
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.
725 ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
726 plane_sizes, q->alloc_devs);
727 if (ret)
728 return ret;
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;
739 * There is no point in continuing if we can't allocate the minimum
740 * number of buffers needed by this vb2_queue.
742 if (allocated_buffers < q->min_buffers_needed)
743 ret = -ENOMEM;
746 * Check if driver can handle the allocated number of buffers.
748 if (!ret && allocated_buffers < num_buffers) {
749 num_buffers = allocated_buffers;
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.
756 num_planes = 0;
758 ret = call_qop(q, queue_setup, q, &num_buffers,
759 &num_planes, plane_sizes, q->alloc_devs);
761 if (!ret && allocated_buffers < num_buffers)
762 ret = -ENOMEM;
765 * Either the driver has accepted a smaller number of buffers,
766 * or .queue_setup() returned an error
770 mutex_lock(&q->mmap_lock);
771 q->num_buffers = allocated_buffers;
773 if (ret < 0) {
775 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
776 * from q->num_buffers.
778 __vb2_queue_free(q, allocated_buffers);
779 mutex_unlock(&q->mmap_lock);
780 return ret;
782 mutex_unlock(&q->mmap_lock);
785 * Return the number of successfully allocated buffers
786 * to the userspace.
788 *count = allocated_buffers;
789 q->waiting_for_buffers = !q->is_output;
791 return 0;
793 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
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[])
799 unsigned int num_planes = 0, num_buffers, allocated_buffers;
800 unsigned plane_sizes[VB2_MAX_PLANES] = { };
801 int ret;
803 if (q->num_buffers == VB2_MAX_FRAME) {
804 dprintk(1, "maximum number of buffers already allocated\n");
805 return -ENOBUFS;
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;
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;
821 num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
823 if (requested_planes && requested_sizes) {
824 num_planes = requested_planes;
825 memcpy(plane_sizes, requested_sizes, sizeof(plane_sizes));
829 * Ask the driver, whether the requested number of buffers, planes per
830 * buffer and their sizes are acceptable
832 ret = call_qop(q, queue_setup, q, &num_buffers,
833 &num_planes, plane_sizes, q->alloc_devs);
834 if (ret)
835 return ret;
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;
846 * Check if driver can handle the so far allocated number of buffers.
848 if (allocated_buffers < num_buffers) {
849 num_buffers = allocated_buffers;
852 * q->num_buffers contains the total number of buffers, that the
853 * queue driver has set up
855 ret = call_qop(q, queue_setup, q, &num_buffers,
856 &num_planes, plane_sizes, q->alloc_devs);
858 if (!ret && allocated_buffers < num_buffers)
859 ret = -ENOMEM;
862 * Either the driver has accepted a smaller number of buffers,
863 * or .queue_setup() returned an error
867 mutex_lock(&q->mmap_lock);
868 q->num_buffers += allocated_buffers;
870 if (ret < 0) {
872 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
873 * from q->num_buffers.
875 __vb2_queue_free(q, allocated_buffers);
876 mutex_unlock(&q->mmap_lock);
877 return -ENOMEM;
879 mutex_unlock(&q->mmap_lock);
882 * Return the number of successfully allocated buffers
883 * to the userspace.
885 *count = allocated_buffers;
887 return 0;
889 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
891 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
893 if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
894 return NULL;
896 return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
899 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
901 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
903 if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
904 return NULL;
906 return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
908 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
910 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
912 struct vb2_queue *q = vb->vb2_queue;
913 unsigned long flags;
914 unsigned int plane;
916 if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
917 return;
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;
925 #ifdef CONFIG_VIDEO_ADV_DEBUG
927 * Although this is not a callback, it still does have to balance
928 * with the buf_queue op. So update this counter manually.
930 vb->cnt_buf_done++;
931 #endif
932 dprintk(4, "done processing on buffer %d, state: %d\n",
933 vb->index, state);
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);
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;
951 atomic_dec(&q->owned_by_drv_count);
952 spin_unlock_irqrestore(&q->done_lock, flags);
954 trace_vb2_buf_done(q, vb);
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;
969 EXPORT_SYMBOL_GPL(vb2_buffer_done);
971 void vb2_discard_done(struct vb2_queue *q)
973 struct vb2_buffer *vb;
974 unsigned long flags;
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);
981 EXPORT_SYMBOL_GPL(vb2_discard_done);
984 * __prepare_mmap() - prepare an MMAP buffer
986 static int __prepare_mmap(struct vb2_buffer *vb, const void *pb)
988 int ret = 0;
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);
997 * __prepare_userptr() - prepare a USERPTR buffer
999 static int __prepare_userptr(struct vb2_buffer *vb, const void *pb)
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;
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;
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;
1024 dprintk(3, "userspace address for plane %d changed, reacquiring memory\n",
1025 plane);
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;
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);
1043 call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
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;
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;
1063 vb->planes[plane].mem_priv = mem_priv;
1067 * Now that everything is in order, copy relevant information
1068 * provided by userspace.
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;
1077 if (reacquired) {
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.
1083 ret = call_vb_qop(vb, buf_init, vb);
1084 if (ret) {
1085 dprintk(1, "buffer initialization failed\n");
1086 goto err;
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;
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;
1109 return ret;
1113 * __prepare_dmabuf() - prepare a DMABUF buffer
1115 static int __prepare_dmabuf(struct vb2_buffer *vb, const void *pb)
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;
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;
1133 for (plane = 0; plane < vb->num_planes; ++plane) {
1134 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
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;
1143 /* use DMABUF size if length is not provided */
1144 if (planes[plane].length == 0)
1145 planes[plane].length = dbuf->size;
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;
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;
1163 dprintk(3, "buffer for plane %d changed\n", plane);
1165 if (!reacquired) {
1166 reacquired = true;
1167 call_void_vb_qop(vb, buf_cleanup, vb);
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;
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;
1188 vb->planes[plane].dbuf = dbuf;
1189 vb->planes[plane].mem_priv = mem_priv;
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.
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;
1204 vb->planes[plane].dbuf_mapped = 1;
1208 * Now that everything is in order, copy relevant information
1209 * provided by userspace.
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;
1218 if (reacquired) {
1220 * Call driver-specific initialization on the newly acquired buffer,
1221 * if provided.
1223 ret = call_vb_qop(vb, buf_init, vb);
1224 if (ret) {
1225 dprintk(1, "buffer initialization failed\n");
1226 goto err;
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;
1237 return 0;
1238 err:
1239 /* In case of errors, release planes that were already acquired */
1240 __vb2_buf_dmabuf_put(vb);
1242 return ret;
1246 * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1248 static void __enqueue_in_driver(struct vb2_buffer *vb)
1250 struct vb2_queue *q = vb->vb2_queue;
1252 vb->state = VB2_BUF_STATE_ACTIVE;
1253 atomic_inc(&q->owned_by_drv_count);
1255 trace_vb2_buf_queue(q, vb);
1257 call_void_vb_qop(vb, buf_queue, vb);
1260 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1262 struct vb2_queue *q = vb->vb2_queue;
1263 unsigned int plane;
1264 int ret;
1266 if (q->error) {
1267 dprintk(1, "fatal error occurred on queue\n");
1268 return -EIO;
1271 vb->state = VB2_BUF_STATE_PREPARING;
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;
1288 if (ret) {
1289 dprintk(1, "buffer preparation failed: %d\n", ret);
1290 vb->state = VB2_BUF_STATE_DEQUEUED;
1291 return ret;
1294 /* sync buffers */
1295 for (plane = 0; plane < vb->num_planes; ++plane)
1296 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1298 vb->state = VB2_BUF_STATE_PREPARED;
1300 return 0;
1303 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1305 struct vb2_buffer *vb;
1306 int ret;
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;
1315 ret = __buf_prepare(vb, pb);
1316 if (ret)
1317 return ret;
1319 /* Fill buffer information for the userspace */
1320 call_void_bufop(q, fill_user_buffer, vb, pb);
1322 dprintk(2, "prepare of buffer %d succeeded\n", vb->index);
1324 return ret;
1326 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1329 * vb2_start_streaming() - Attempt to start streaming.
1330 * @q: videobuf2 queue
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.
1339 static int vb2_start_streaming(struct vb2_queue *q)
1341 struct vb2_buffer *vb;
1342 int ret;
1345 * If any buffers were queued before streamon,
1346 * we can now pass them to driver for processing.
1348 list_for_each_entry(vb, &q->queued_list, queued_entry)
1349 __enqueue_in_driver(vb);
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;
1358 q->start_streaming_called = 0;
1360 dprintk(1, "driver refused to start streaming\n");
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().
1367 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1368 unsigned i;
1371 * Forcefully reclaim buffers if the driver did not
1372 * correctly return them to vb2.
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);
1379 /* Must be zero now */
1380 WARN_ON(atomic_read(&q->owned_by_drv_count));
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.
1387 WARN_ON(!list_empty(&q->done_list));
1388 return ret;
1391 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1393 struct vb2_buffer *vb;
1394 int ret;
1396 if (q->error) {
1397 dprintk(1, "fatal error occurred on queue\n");
1398 return -EIO;
1401 vb = q->bufs[index];
1403 switch (vb->state) {
1404 case VB2_BUF_STATE_DEQUEUED:
1405 ret = __buf_prepare(vb, pb);
1406 if (ret)
1407 return ret;
1408 break;
1409 case VB2_BUF_STATE_PREPARED:
1410 break;
1411 case VB2_BUF_STATE_PREPARING:
1412 dprintk(1, "buffer still being prepared\n");
1413 return -EINVAL;
1414 default:
1415 dprintk(1, "invalid buffer state %d\n", vb->state);
1416 return -EINVAL;
1420 * Add to the queued buffers list, a buffer will stay on it until
1421 * dequeued in dqbuf.
1423 list_add_tail(&vb->queued_entry, &q->queued_list);
1424 q->queued_count++;
1425 q->waiting_for_buffers = false;
1426 vb->state = VB2_BUF_STATE_QUEUED;
1428 if (pb)
1429 call_void_bufop(q, copy_timestamp, vb, pb);
1431 trace_vb2_qbuf(q, vb);
1434 * If already streaming, give the buffer to driver for processing.
1435 * If not, the buffer will be given to driver on next streamon.
1437 if (q->start_streaming_called)
1438 __enqueue_in_driver(vb);
1440 /* Fill buffer information for the userspace */
1441 if (pb)
1442 call_void_bufop(q, fill_user_buffer, vb, pb);
1445 * If streamon has been called, and we haven't yet called
1446 * start_streaming() since not enough buffers were queued, and
1447 * we now have reached the minimum number of queued buffers,
1448 * then we can finally call start_streaming().
1450 if (q->streaming && !q->start_streaming_called &&
1451 q->queued_count >= q->min_buffers_needed) {
1452 ret = vb2_start_streaming(q);
1453 if (ret)
1454 return ret;
1457 dprintk(2, "qbuf of buffer %d succeeded\n", vb->index);
1458 return 0;
1460 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1463 * __vb2_wait_for_done_vb() - wait for a buffer to become available
1464 * for dequeuing
1466 * Will sleep if required for nonblocking == false.
1468 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1471 * All operations on vb_done_list are performed under done_lock
1472 * spinlock protection. However, buffers may be removed from
1473 * it and returned to userspace only while holding both driver's
1474 * lock and the done_lock spinlock. Thus we can be sure that as
1475 * long as we hold the driver's lock, the list will remain not
1476 * empty if list_empty() check succeeds.
1479 for (;;) {
1480 int ret;
1482 if (q->waiting_in_dqbuf) {
1483 dprintk(1, "another dup()ped fd is waiting for a buffer\n");
1484 return -EBUSY;
1487 if (!q->streaming) {
1488 dprintk(1, "streaming off, will not wait for buffers\n");
1489 return -EINVAL;
1492 if (q->error) {
1493 dprintk(1, "Queue in error state, will not wait for buffers\n");
1494 return -EIO;
1497 if (q->last_buffer_dequeued) {
1498 dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1499 return -EPIPE;
1502 if (!list_empty(&q->done_list)) {
1504 * Found a buffer that we were waiting for.
1506 break;
1509 if (nonblocking) {
1510 dprintk(3, "nonblocking and no buffers to dequeue, will not wait\n");
1511 return -EAGAIN;
1514 q->waiting_in_dqbuf = 1;
1516 * We are streaming and blocking, wait for another buffer to
1517 * become ready or for streamoff. Driver's lock is released to
1518 * allow streamoff or qbuf to be called while waiting.
1520 call_void_qop(q, wait_prepare, q);
1523 * All locks have been released, it is safe to sleep now.
1525 dprintk(3, "will sleep waiting for buffers\n");
1526 ret = wait_event_interruptible(q->done_wq,
1527 !list_empty(&q->done_list) || !q->streaming ||
1528 q->error);
1531 * We need to reevaluate both conditions again after reacquiring
1532 * the locks or return an error if one occurred.
1534 call_void_qop(q, wait_finish, q);
1535 q->waiting_in_dqbuf = 0;
1536 if (ret) {
1537 dprintk(1, "sleep was interrupted\n");
1538 return ret;
1541 return 0;
1545 * __vb2_get_done_vb() - get a buffer ready for dequeuing
1547 * Will sleep if required for nonblocking == false.
1549 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1550 void *pb, int nonblocking)
1552 unsigned long flags;
1553 int ret = 0;
1556 * Wait for at least one buffer to become available on the done_list.
1558 ret = __vb2_wait_for_done_vb(q, nonblocking);
1559 if (ret)
1560 return ret;
1563 * Driver's lock has been held since we last verified that done_list
1564 * is not empty, so no need for another list_empty(done_list) check.
1566 spin_lock_irqsave(&q->done_lock, flags);
1567 *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1569 * Only remove the buffer from done_list if all planes can be
1570 * handled. Some cases such as V4L2 file I/O and DVB have pb
1571 * == NULL; skip the check then as there's nothing to verify.
1573 if (pb)
1574 ret = call_bufop(q, verify_planes_array, *vb, pb);
1575 if (!ret)
1576 list_del(&(*vb)->done_entry);
1577 spin_unlock_irqrestore(&q->done_lock, flags);
1579 return ret;
1582 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1584 if (!q->streaming) {
1585 dprintk(1, "streaming off, will not wait for buffers\n");
1586 return -EINVAL;
1589 if (q->start_streaming_called)
1590 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1591 return 0;
1593 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1596 * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1598 static void __vb2_dqbuf(struct vb2_buffer *vb)
1600 struct vb2_queue *q = vb->vb2_queue;
1601 unsigned int i;
1603 /* nothing to do if the buffer is already dequeued */
1604 if (vb->state == VB2_BUF_STATE_DEQUEUED)
1605 return;
1607 vb->state = VB2_BUF_STATE_DEQUEUED;
1609 /* unmap DMABUF buffer */
1610 if (q->memory == VB2_MEMORY_DMABUF)
1611 for (i = 0; i < vb->num_planes; ++i) {
1612 if (!vb->planes[i].dbuf_mapped)
1613 continue;
1614 call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1615 vb->planes[i].dbuf_mapped = 0;
1619 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1620 bool nonblocking)
1622 struct vb2_buffer *vb = NULL;
1623 int ret;
1625 ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1626 if (ret < 0)
1627 return ret;
1629 switch (vb->state) {
1630 case VB2_BUF_STATE_DONE:
1631 dprintk(3, "returning done buffer\n");
1632 break;
1633 case VB2_BUF_STATE_ERROR:
1634 dprintk(3, "returning done buffer with errors\n");
1635 break;
1636 default:
1637 dprintk(1, "invalid buffer state\n");
1638 return -EINVAL;
1641 call_void_vb_qop(vb, buf_finish, vb);
1643 if (pindex)
1644 *pindex = vb->index;
1646 /* Fill buffer information for the userspace */
1647 if (pb)
1648 call_void_bufop(q, fill_user_buffer, vb, pb);
1650 /* Remove from videobuf queue */
1651 list_del(&vb->queued_entry);
1652 q->queued_count--;
1654 trace_vb2_dqbuf(q, vb);
1656 /* go back to dequeued state */
1657 __vb2_dqbuf(vb);
1659 dprintk(2, "dqbuf of buffer %d, with state %d\n",
1660 vb->index, vb->state);
1662 return 0;
1665 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1668 * __vb2_queue_cancel() - cancel and stop (pause) streaming
1670 * Removes all queued buffers from driver's queue and all buffers queued by
1671 * userspace from videobuf's queue. Returns to state after reqbufs.
1673 static void __vb2_queue_cancel(struct vb2_queue *q)
1675 unsigned int i;
1678 * Tell driver to stop all transactions and release all queued
1679 * buffers.
1681 if (q->start_streaming_called)
1682 call_void_qop(q, stop_streaming, q);
1685 * If you see this warning, then the driver isn't cleaning up properly
1686 * in stop_streaming(). See the stop_streaming() documentation in
1687 * videobuf2-core.h for more information how buffers should be returned
1688 * to vb2 in stop_streaming().
1690 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1691 for (i = 0; i < q->num_buffers; ++i)
1692 if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE) {
1693 pr_warn("driver bug: stop_streaming operation is leaving buf %p in active state\n",
1694 q->bufs[i]);
1695 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1697 /* Must be zero now */
1698 WARN_ON(atomic_read(&q->owned_by_drv_count));
1701 q->streaming = 0;
1702 q->start_streaming_called = 0;
1703 q->queued_count = 0;
1704 q->error = 0;
1707 * Remove all buffers from videobuf's list...
1709 INIT_LIST_HEAD(&q->queued_list);
1711 * ...and done list; userspace will not receive any buffers it
1712 * has not already dequeued before initiating cancel.
1714 INIT_LIST_HEAD(&q->done_list);
1715 atomic_set(&q->owned_by_drv_count, 0);
1716 wake_up_all(&q->done_wq);
1719 * Reinitialize all buffers for next use.
1720 * Make sure to call buf_finish for any queued buffers. Normally
1721 * that's done in dqbuf, but that's not going to happen when we
1722 * cancel the whole queue. Note: this code belongs here, not in
1723 * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1724 * call to __fill_user_buffer() after buf_finish(). That order can't
1725 * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1727 for (i = 0; i < q->num_buffers; ++i) {
1728 struct vb2_buffer *vb = q->bufs[i];
1730 if (vb->state == VB2_BUF_STATE_PREPARED ||
1731 vb->state == VB2_BUF_STATE_QUEUED) {
1732 unsigned int plane;
1734 for (plane = 0; plane < vb->num_planes; ++plane)
1735 call_void_memop(vb, finish,
1736 vb->planes[plane].mem_priv);
1739 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1740 vb->state = VB2_BUF_STATE_PREPARED;
1741 call_void_vb_qop(vb, buf_finish, vb);
1743 __vb2_dqbuf(vb);
1747 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1749 int ret;
1751 if (type != q->type) {
1752 dprintk(1, "invalid stream type\n");
1753 return -EINVAL;
1756 if (q->streaming) {
1757 dprintk(3, "already streaming\n");
1758 return 0;
1761 if (!q->num_buffers) {
1762 dprintk(1, "no buffers have been allocated\n");
1763 return -EINVAL;
1766 if (q->num_buffers < q->min_buffers_needed) {
1767 dprintk(1, "need at least %u allocated buffers\n",
1768 q->min_buffers_needed);
1769 return -EINVAL;
1773 * Tell driver to start streaming provided sufficient buffers
1774 * are available.
1776 if (q->queued_count >= q->min_buffers_needed) {
1777 ret = v4l_vb2q_enable_media_source(q);
1778 if (ret)
1779 return ret;
1780 ret = vb2_start_streaming(q);
1781 if (ret)
1782 return ret;
1785 q->streaming = 1;
1787 dprintk(3, "successful\n");
1788 return 0;
1790 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1792 void vb2_queue_error(struct vb2_queue *q)
1794 q->error = 1;
1796 wake_up_all(&q->done_wq);
1798 EXPORT_SYMBOL_GPL(vb2_queue_error);
1800 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1802 if (type != q->type) {
1803 dprintk(1, "invalid stream type\n");
1804 return -EINVAL;
1808 * Cancel will pause streaming and remove all buffers from the driver
1809 * and videobuf, effectively returning control over them to userspace.
1811 * Note that we do this even if q->streaming == 0: if you prepare or
1812 * queue buffers, and then call streamoff without ever having called
1813 * streamon, you would still expect those buffers to be returned to
1814 * their normal dequeued state.
1816 __vb2_queue_cancel(q);
1817 q->waiting_for_buffers = !q->is_output;
1818 q->last_buffer_dequeued = false;
1820 dprintk(3, "successful\n");
1821 return 0;
1823 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1826 * __find_plane_by_offset() - find plane associated with the given offset off
1828 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1829 unsigned int *_buffer, unsigned int *_plane)
1831 struct vb2_buffer *vb;
1832 unsigned int buffer, plane;
1835 * Go over all buffers and their planes, comparing the given offset
1836 * with an offset assigned to each plane. If a match is found,
1837 * return its buffer and plane numbers.
1839 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1840 vb = q->bufs[buffer];
1842 for (plane = 0; plane < vb->num_planes; ++plane) {
1843 if (vb->planes[plane].m.offset == off) {
1844 *_buffer = buffer;
1845 *_plane = plane;
1846 return 0;
1851 return -EINVAL;
1854 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1855 unsigned int index, unsigned int plane, unsigned int flags)
1857 struct vb2_buffer *vb = NULL;
1858 struct vb2_plane *vb_plane;
1859 int ret;
1860 struct dma_buf *dbuf;
1862 if (q->memory != VB2_MEMORY_MMAP) {
1863 dprintk(1, "queue is not currently set up for mmap\n");
1864 return -EINVAL;
1867 if (!q->mem_ops->get_dmabuf) {
1868 dprintk(1, "queue does not support DMA buffer exporting\n");
1869 return -EINVAL;
1872 if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1873 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1874 return -EINVAL;
1877 if (type != q->type) {
1878 dprintk(1, "invalid buffer type\n");
1879 return -EINVAL;
1882 if (index >= q->num_buffers) {
1883 dprintk(1, "buffer index out of range\n");
1884 return -EINVAL;
1887 vb = q->bufs[index];
1889 if (plane >= vb->num_planes) {
1890 dprintk(1, "buffer plane out of range\n");
1891 return -EINVAL;
1894 if (vb2_fileio_is_active(q)) {
1895 dprintk(1, "expbuf: file io in progress\n");
1896 return -EBUSY;
1899 vb_plane = &vb->planes[plane];
1901 dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1902 flags & O_ACCMODE);
1903 if (IS_ERR_OR_NULL(dbuf)) {
1904 dprintk(1, "failed to export buffer %d, plane %d\n",
1905 index, plane);
1906 return -EINVAL;
1909 ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1910 if (ret < 0) {
1911 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1912 index, plane, ret);
1913 dma_buf_put(dbuf);
1914 return ret;
1917 dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1918 index, plane, ret);
1919 *fd = ret;
1921 return 0;
1923 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1925 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1927 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1928 struct vb2_buffer *vb;
1929 unsigned int buffer = 0, plane = 0;
1930 int ret;
1931 unsigned long length;
1933 if (q->memory != VB2_MEMORY_MMAP) {
1934 dprintk(1, "queue is not currently set up for mmap\n");
1935 return -EINVAL;
1939 * Check memory area access mode.
1941 if (!(vma->vm_flags & VM_SHARED)) {
1942 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1943 return -EINVAL;
1945 if (q->is_output) {
1946 if (!(vma->vm_flags & VM_WRITE)) {
1947 dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1948 return -EINVAL;
1950 } else {
1951 if (!(vma->vm_flags & VM_READ)) {
1952 dprintk(1, "invalid vma flags, VM_READ needed\n");
1953 return -EINVAL;
1957 mutex_lock(&q->mmap_lock);
1959 if (vb2_fileio_is_active(q)) {
1960 dprintk(1, "mmap: file io in progress\n");
1961 ret = -EBUSY;
1962 goto unlock;
1966 * Find the plane corresponding to the offset passed by userspace.
1968 ret = __find_plane_by_offset(q, off, &buffer, &plane);
1969 if (ret)
1970 goto unlock;
1972 vb = q->bufs[buffer];
1975 * MMAP requires page_aligned buffers.
1976 * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1977 * so, we need to do the same here.
1979 length = PAGE_ALIGN(vb->planes[plane].length);
1980 if (length < (vma->vm_end - vma->vm_start)) {
1981 dprintk(1,
1982 "MMAP invalid, as it would overflow buffer length\n");
1983 ret = -EINVAL;
1984 goto unlock;
1987 ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1989 unlock:
1990 mutex_unlock(&q->mmap_lock);
1991 if (ret)
1992 return ret;
1994 dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
1995 return 0;
1997 EXPORT_SYMBOL_GPL(vb2_mmap);
1999 #ifndef CONFIG_MMU
2000 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
2001 unsigned long addr,
2002 unsigned long len,
2003 unsigned long pgoff,
2004 unsigned long flags)
2006 unsigned long off = pgoff << PAGE_SHIFT;
2007 struct vb2_buffer *vb;
2008 unsigned int buffer, plane;
2009 void *vaddr;
2010 int ret;
2012 if (q->memory != VB2_MEMORY_MMAP) {
2013 dprintk(1, "queue is not currently set up for mmap\n");
2014 return -EINVAL;
2018 * Find the plane corresponding to the offset passed by userspace.
2020 ret = __find_plane_by_offset(q, off, &buffer, &plane);
2021 if (ret)
2022 return ret;
2024 vb = q->bufs[buffer];
2026 vaddr = vb2_plane_vaddr(vb, plane);
2027 return vaddr ? (unsigned long)vaddr : -EINVAL;
2029 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2030 #endif
2032 int vb2_core_queue_init(struct vb2_queue *q)
2035 * Sanity check
2037 if (WARN_ON(!q) ||
2038 WARN_ON(!q->ops) ||
2039 WARN_ON(!q->mem_ops) ||
2040 WARN_ON(!q->type) ||
2041 WARN_ON(!q->io_modes) ||
2042 WARN_ON(!q->ops->queue_setup) ||
2043 WARN_ON(!q->ops->buf_queue))
2044 return -EINVAL;
2046 INIT_LIST_HEAD(&q->queued_list);
2047 INIT_LIST_HEAD(&q->done_list);
2048 spin_lock_init(&q->done_lock);
2049 mutex_init(&q->mmap_lock);
2050 init_waitqueue_head(&q->done_wq);
2052 q->memory = VB2_MEMORY_UNKNOWN;
2054 if (q->buf_struct_size == 0)
2055 q->buf_struct_size = sizeof(struct vb2_buffer);
2057 if (q->bidirectional)
2058 q->dma_dir = DMA_BIDIRECTIONAL;
2059 else
2060 q->dma_dir = q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
2062 return 0;
2064 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2066 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2067 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2068 void vb2_core_queue_release(struct vb2_queue *q)
2070 __vb2_cleanup_fileio(q);
2071 __vb2_queue_cancel(q);
2072 mutex_lock(&q->mmap_lock);
2073 __vb2_queue_free(q, q->num_buffers);
2074 mutex_unlock(&q->mmap_lock);
2076 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2078 __poll_t vb2_core_poll(struct vb2_queue *q, struct file *file,
2079 poll_table *wait)
2081 __poll_t req_events = poll_requested_events(wait);
2082 struct vb2_buffer *vb = NULL;
2083 unsigned long flags;
2085 if (!q->is_output && !(req_events & (EPOLLIN | EPOLLRDNORM)))
2086 return 0;
2087 if (q->is_output && !(req_events & (EPOLLOUT | EPOLLWRNORM)))
2088 return 0;
2091 * Start file I/O emulator only if streaming API has not been used yet.
2093 if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2094 if (!q->is_output && (q->io_modes & VB2_READ) &&
2095 (req_events & (EPOLLIN | EPOLLRDNORM))) {
2096 if (__vb2_init_fileio(q, 1))
2097 return EPOLLERR;
2099 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2100 (req_events & (EPOLLOUT | EPOLLWRNORM))) {
2101 if (__vb2_init_fileio(q, 0))
2102 return EPOLLERR;
2104 * Write to OUTPUT queue can be done immediately.
2106 return EPOLLOUT | EPOLLWRNORM;
2111 * There is nothing to wait for if the queue isn't streaming, or if the
2112 * error flag is set.
2114 if (!vb2_is_streaming(q) || q->error)
2115 return EPOLLERR;
2118 * If this quirk is set and QBUF hasn't been called yet then
2119 * return EPOLLERR as well. This only affects capture queues, output
2120 * queues will always initialize waiting_for_buffers to false.
2121 * This quirk is set by V4L2 for backwards compatibility reasons.
2123 if (q->quirk_poll_must_check_waiting_for_buffers &&
2124 q->waiting_for_buffers && (req_events & (EPOLLIN | EPOLLRDNORM)))
2125 return EPOLLERR;
2128 * For output streams you can call write() as long as there are fewer
2129 * buffers queued than there are buffers available.
2131 if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2132 return EPOLLOUT | EPOLLWRNORM;
2134 if (list_empty(&q->done_list)) {
2136 * If the last buffer was dequeued from a capture queue,
2137 * return immediately. DQBUF will return -EPIPE.
2139 if (q->last_buffer_dequeued)
2140 return EPOLLIN | EPOLLRDNORM;
2142 poll_wait(file, &q->done_wq, wait);
2146 * Take first buffer available for dequeuing.
2148 spin_lock_irqsave(&q->done_lock, flags);
2149 if (!list_empty(&q->done_list))
2150 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2151 done_entry);
2152 spin_unlock_irqrestore(&q->done_lock, flags);
2154 if (vb && (vb->state == VB2_BUF_STATE_DONE
2155 || vb->state == VB2_BUF_STATE_ERROR)) {
2156 return (q->is_output) ?
2157 EPOLLOUT | EPOLLWRNORM :
2158 EPOLLIN | EPOLLRDNORM;
2160 return 0;
2162 EXPORT_SYMBOL_GPL(vb2_core_poll);
2165 * struct vb2_fileio_buf - buffer context used by file io emulator
2167 * vb2 provides a compatibility layer and emulator of file io (read and
2168 * write) calls on top of streaming API. This structure is used for
2169 * tracking context related to the buffers.
2171 struct vb2_fileio_buf {
2172 void *vaddr;
2173 unsigned int size;
2174 unsigned int pos;
2175 unsigned int queued:1;
2179 * struct vb2_fileio_data - queue context used by file io emulator
2181 * @cur_index: the index of the buffer currently being read from or
2182 * written to. If equal to q->num_buffers then a new buffer
2183 * must be dequeued.
2184 * @initial_index: in the read() case all buffers are queued up immediately
2185 * in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2186 * buffers. However, in the write() case no buffers are initially
2187 * queued, instead whenever a buffer is full it is queued up by
2188 * __vb2_perform_fileio(). Only once all available buffers have
2189 * been queued up will __vb2_perform_fileio() start to dequeue
2190 * buffers. This means that initially __vb2_perform_fileio()
2191 * needs to know what buffer index to use when it is queuing up
2192 * the buffers for the first time. That initial index is stored
2193 * in this field. Once it is equal to q->num_buffers all
2194 * available buffers have been queued and __vb2_perform_fileio()
2195 * should start the normal dequeue/queue cycle.
2197 * vb2 provides a compatibility layer and emulator of file io (read and
2198 * write) calls on top of streaming API. For proper operation it required
2199 * this structure to save the driver state between each call of the read
2200 * or write function.
2202 struct vb2_fileio_data {
2203 unsigned int count;
2204 unsigned int type;
2205 unsigned int memory;
2206 struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2207 unsigned int cur_index;
2208 unsigned int initial_index;
2209 unsigned int q_count;
2210 unsigned int dq_count;
2211 unsigned read_once:1;
2212 unsigned write_immediately:1;
2216 * __vb2_init_fileio() - initialize file io emulator
2217 * @q: videobuf2 queue
2218 * @read: mode selector (1 means read, 0 means write)
2220 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2222 struct vb2_fileio_data *fileio;
2223 int i, ret;
2224 unsigned int count = 0;
2227 * Sanity check
2229 if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2230 (!read && !(q->io_modes & VB2_WRITE))))
2231 return -EINVAL;
2234 * Check if device supports mapping buffers to kernel virtual space.
2236 if (!q->mem_ops->vaddr)
2237 return -EBUSY;
2240 * Check if streaming api has not been already activated.
2242 if (q->streaming || q->num_buffers > 0)
2243 return -EBUSY;
2246 * Start with count 1, driver can increase it in queue_setup()
2248 count = 1;
2250 dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2251 (read) ? "read" : "write", count, q->fileio_read_once,
2252 q->fileio_write_immediately);
2254 fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2255 if (fileio == NULL)
2256 return -ENOMEM;
2258 fileio->read_once = q->fileio_read_once;
2259 fileio->write_immediately = q->fileio_write_immediately;
2262 * Request buffers and use MMAP type to force driver
2263 * to allocate buffers by itself.
2265 fileio->count = count;
2266 fileio->memory = VB2_MEMORY_MMAP;
2267 fileio->type = q->type;
2268 q->fileio = fileio;
2269 ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2270 if (ret)
2271 goto err_kfree;
2274 * Check if plane_count is correct
2275 * (multiplane buffers are not supported).
2277 if (q->bufs[0]->num_planes != 1) {
2278 ret = -EBUSY;
2279 goto err_reqbufs;
2283 * Get kernel address of each buffer.
2285 for (i = 0; i < q->num_buffers; i++) {
2286 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2287 if (fileio->bufs[i].vaddr == NULL) {
2288 ret = -EINVAL;
2289 goto err_reqbufs;
2291 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2295 * Read mode requires pre queuing of all buffers.
2297 if (read) {
2299 * Queue all buffers.
2301 for (i = 0; i < q->num_buffers; i++) {
2302 ret = vb2_core_qbuf(q, i, NULL);
2303 if (ret)
2304 goto err_reqbufs;
2305 fileio->bufs[i].queued = 1;
2308 * All buffers have been queued, so mark that by setting
2309 * initial_index to q->num_buffers
2311 fileio->initial_index = q->num_buffers;
2312 fileio->cur_index = q->num_buffers;
2316 * Start streaming.
2318 ret = vb2_core_streamon(q, q->type);
2319 if (ret)
2320 goto err_reqbufs;
2322 return ret;
2324 err_reqbufs:
2325 fileio->count = 0;
2326 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2328 err_kfree:
2329 q->fileio = NULL;
2330 kfree(fileio);
2331 return ret;
2335 * __vb2_cleanup_fileio() - free resourced used by file io emulator
2336 * @q: videobuf2 queue
2338 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2340 struct vb2_fileio_data *fileio = q->fileio;
2342 if (fileio) {
2343 vb2_core_streamoff(q, q->type);
2344 q->fileio = NULL;
2345 fileio->count = 0;
2346 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2347 kfree(fileio);
2348 dprintk(3, "file io emulator closed\n");
2350 return 0;
2354 * __vb2_perform_fileio() - perform a single file io (read or write) operation
2355 * @q: videobuf2 queue
2356 * @data: pointed to target userspace buffer
2357 * @count: number of bytes to read or write
2358 * @ppos: file handle position tracking pointer
2359 * @nonblock: mode selector (1 means blocking calls, 0 means nonblocking)
2360 * @read: access mode selector (1 means read, 0 means write)
2362 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2363 loff_t *ppos, int nonblock, int read)
2365 struct vb2_fileio_data *fileio;
2366 struct vb2_fileio_buf *buf;
2367 bool is_multiplanar = q->is_multiplanar;
2369 * When using write() to write data to an output video node the vb2 core
2370 * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2371 * else is able to provide this information with the write() operation.
2373 bool copy_timestamp = !read && q->copy_timestamp;
2374 unsigned index;
2375 int ret;
2377 dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2378 read ? "read" : "write", (long)*ppos, count,
2379 nonblock ? "non" : "");
2381 if (!data)
2382 return -EINVAL;
2384 if (q->waiting_in_dqbuf) {
2385 dprintk(3, "another dup()ped fd is %s\n",
2386 read ? "reading" : "writing");
2387 return -EBUSY;
2391 * Initialize emulator on first call.
2393 if (!vb2_fileio_is_active(q)) {
2394 ret = __vb2_init_fileio(q, read);
2395 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2396 if (ret)
2397 return ret;
2399 fileio = q->fileio;
2402 * Check if we need to dequeue the buffer.
2404 index = fileio->cur_index;
2405 if (index >= q->num_buffers) {
2406 struct vb2_buffer *b;
2409 * Call vb2_dqbuf to get buffer back.
2411 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2412 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2413 if (ret)
2414 return ret;
2415 fileio->dq_count += 1;
2417 fileio->cur_index = index;
2418 buf = &fileio->bufs[index];
2419 b = q->bufs[index];
2422 * Get number of bytes filled by the driver
2424 buf->pos = 0;
2425 buf->queued = 0;
2426 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2427 : vb2_plane_size(q->bufs[index], 0);
2428 /* Compensate for data_offset on read in the multiplanar case. */
2429 if (is_multiplanar && read &&
2430 b->planes[0].data_offset < buf->size) {
2431 buf->pos = b->planes[0].data_offset;
2432 buf->size -= buf->pos;
2434 } else {
2435 buf = &fileio->bufs[index];
2439 * Limit count on last few bytes of the buffer.
2441 if (buf->pos + count > buf->size) {
2442 count = buf->size - buf->pos;
2443 dprintk(5, "reducing read count: %zd\n", count);
2447 * Transfer data to userspace.
2449 dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2450 count, index, buf->pos);
2451 if (read)
2452 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2453 else
2454 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2455 if (ret) {
2456 dprintk(3, "error copying data\n");
2457 return -EFAULT;
2461 * Update counters.
2463 buf->pos += count;
2464 *ppos += count;
2467 * Queue next buffer if required.
2469 if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2470 struct vb2_buffer *b = q->bufs[index];
2473 * Check if this is the last buffer to read.
2475 if (read && fileio->read_once && fileio->dq_count == 1) {
2476 dprintk(3, "read limit reached\n");
2477 return __vb2_cleanup_fileio(q);
2481 * Call vb2_qbuf and give buffer to the driver.
2483 b->planes[0].bytesused = buf->pos;
2485 if (copy_timestamp)
2486 b->timestamp = ktime_get_ns();
2487 ret = vb2_core_qbuf(q, index, NULL);
2488 dprintk(5, "vb2_dbuf result: %d\n", ret);
2489 if (ret)
2490 return ret;
2493 * Buffer has been queued, update the status
2495 buf->pos = 0;
2496 buf->queued = 1;
2497 buf->size = vb2_plane_size(q->bufs[index], 0);
2498 fileio->q_count += 1;
2500 * If we are queuing up buffers for the first time, then
2501 * increase initial_index by one.
2503 if (fileio->initial_index < q->num_buffers)
2504 fileio->initial_index++;
2506 * The next buffer to use is either a buffer that's going to be
2507 * queued for the first time (initial_index < q->num_buffers)
2508 * or it is equal to q->num_buffers, meaning that the next
2509 * time we need to dequeue a buffer since we've now queued up
2510 * all the 'first time' buffers.
2512 fileio->cur_index = fileio->initial_index;
2516 * Return proper number of bytes processed.
2518 if (ret == 0)
2519 ret = count;
2520 return ret;
2523 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2524 loff_t *ppos, int nonblocking)
2526 return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2528 EXPORT_SYMBOL_GPL(vb2_read);
2530 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2531 loff_t *ppos, int nonblocking)
2533 return __vb2_perform_fileio(q, (char __user *) data, count,
2534 ppos, nonblocking, 0);
2536 EXPORT_SYMBOL_GPL(vb2_write);
2538 struct vb2_threadio_data {
2539 struct task_struct *thread;
2540 vb2_thread_fnc fnc;
2541 void *priv;
2542 bool stop;
2545 static int vb2_thread(void *data)
2547 struct vb2_queue *q = data;
2548 struct vb2_threadio_data *threadio = q->threadio;
2549 bool copy_timestamp = false;
2550 unsigned prequeue = 0;
2551 unsigned index = 0;
2552 int ret = 0;
2554 if (q->is_output) {
2555 prequeue = q->num_buffers;
2556 copy_timestamp = q->copy_timestamp;
2559 set_freezable();
2561 for (;;) {
2562 struct vb2_buffer *vb;
2565 * Call vb2_dqbuf to get buffer back.
2567 if (prequeue) {
2568 vb = q->bufs[index++];
2569 prequeue--;
2570 } else {
2571 call_void_qop(q, wait_finish, q);
2572 if (!threadio->stop)
2573 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2574 call_void_qop(q, wait_prepare, q);
2575 dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2576 if (!ret)
2577 vb = q->bufs[index];
2579 if (ret || threadio->stop)
2580 break;
2581 try_to_freeze();
2583 if (vb->state != VB2_BUF_STATE_ERROR)
2584 if (threadio->fnc(vb, threadio->priv))
2585 break;
2586 call_void_qop(q, wait_finish, q);
2587 if (copy_timestamp)
2588 vb->timestamp = ktime_get_ns();
2589 if (!threadio->stop)
2590 ret = vb2_core_qbuf(q, vb->index, NULL);
2591 call_void_qop(q, wait_prepare, q);
2592 if (ret || threadio->stop)
2593 break;
2596 /* Hmm, linux becomes *very* unhappy without this ... */
2597 while (!kthread_should_stop()) {
2598 set_current_state(TASK_INTERRUPTIBLE);
2599 schedule();
2601 return 0;
2605 * This function should not be used for anything else but the videobuf2-dvb
2606 * support. If you think you have another good use-case for this, then please
2607 * contact the linux-media mailinglist first.
2609 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2610 const char *thread_name)
2612 struct vb2_threadio_data *threadio;
2613 int ret = 0;
2615 if (q->threadio)
2616 return -EBUSY;
2617 if (vb2_is_busy(q))
2618 return -EBUSY;
2619 if (WARN_ON(q->fileio))
2620 return -EBUSY;
2622 threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2623 if (threadio == NULL)
2624 return -ENOMEM;
2625 threadio->fnc = fnc;
2626 threadio->priv = priv;
2628 ret = __vb2_init_fileio(q, !q->is_output);
2629 dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2630 if (ret)
2631 goto nomem;
2632 q->threadio = threadio;
2633 threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2634 if (IS_ERR(threadio->thread)) {
2635 ret = PTR_ERR(threadio->thread);
2636 threadio->thread = NULL;
2637 goto nothread;
2639 return 0;
2641 nothread:
2642 __vb2_cleanup_fileio(q);
2643 nomem:
2644 kfree(threadio);
2645 return ret;
2647 EXPORT_SYMBOL_GPL(vb2_thread_start);
2649 int vb2_thread_stop(struct vb2_queue *q)
2651 struct vb2_threadio_data *threadio = q->threadio;
2652 int err;
2654 if (threadio == NULL)
2655 return 0;
2656 threadio->stop = true;
2657 /* Wake up all pending sleeps in the thread */
2658 vb2_queue_error(q);
2659 err = kthread_stop(threadio->thread);
2660 __vb2_cleanup_fileio(q);
2661 threadio->thread = NULL;
2662 kfree(threadio);
2663 q->threadio = NULL;
2664 return err;
2666 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2668 MODULE_DESCRIPTION("Media buffer core framework");
2669 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2670 MODULE_LICENSE("GPL");