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 #include <linux/err.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
21 #include <linux/poll.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
27 #include <media/videobuf2-core.h>
28 #include <media/v4l2-mc.h>
30 #include <trace/events/vb2.h>
33 module_param(debug, int, 0644);
35 #define dprintk(level, fmt, arg...) \
38 pr_info("vb2-core: %s: " fmt, __func__, ## arg); \
41 #ifdef CONFIG_VIDEO_ADV_DEBUG
44 * If advanced debugging is on, then count how often each op is called
45 * successfully, which can either be per-buffer or per-queue.
47 * This makes it easy to check that the 'init' and 'cleanup'
48 * (and variations thereof) stay balanced.
51 #define log_memop(vb, op) \
52 dprintk(2, "call_memop(%p, %d, %s)%s\n", \
53 (vb)->vb2_queue, (vb)->index, #op, \
54 (vb)->vb2_queue->mem_ops->op ? "" : " (nop)")
56 #define call_memop(vb, op, args...) \
58 struct vb2_queue *_q = (vb)->vb2_queue; \
62 err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0; \
64 (vb)->cnt_mem_ ## op++; \
68 #define call_ptr_memop(vb, op, args...) \
70 struct vb2_queue *_q = (vb)->vb2_queue; \
74 ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL; \
75 if (!IS_ERR_OR_NULL(ptr)) \
76 (vb)->cnt_mem_ ## op++; \
80 #define call_void_memop(vb, op, args...) \
82 struct vb2_queue *_q = (vb)->vb2_queue; \
85 if (_q->mem_ops->op) \
86 _q->mem_ops->op(args); \
87 (vb)->cnt_mem_ ## op++; \
90 #define log_qop(q, op) \
91 dprintk(2, "call_qop(%p, %s)%s\n", q, #op, \
92 (q)->ops->op ? "" : " (nop)")
94 #define call_qop(q, op, args...) \
99 err = (q)->ops->op ? (q)->ops->op(args) : 0; \
105 #define call_void_qop(q, op, args...) \
109 (q)->ops->op(args); \
113 #define log_vb_qop(vb, op, args...) \
114 dprintk(2, "call_vb_qop(%p, %d, %s)%s\n", \
115 (vb)->vb2_queue, (vb)->index, #op, \
116 (vb)->vb2_queue->ops->op ? "" : " (nop)")
118 #define call_vb_qop(vb, op, args...) \
122 log_vb_qop(vb, op); \
123 err = (vb)->vb2_queue->ops->op ? \
124 (vb)->vb2_queue->ops->op(args) : 0; \
126 (vb)->cnt_ ## op++; \
130 #define call_void_vb_qop(vb, op, args...) \
132 log_vb_qop(vb, op); \
133 if ((vb)->vb2_queue->ops->op) \
134 (vb)->vb2_queue->ops->op(args); \
135 (vb)->cnt_ ## op++; \
140 #define call_memop(vb, op, args...) \
141 ((vb)->vb2_queue->mem_ops->op ? \
142 (vb)->vb2_queue->mem_ops->op(args) : 0)
144 #define call_ptr_memop(vb, op, args...) \
145 ((vb)->vb2_queue->mem_ops->op ? \
146 (vb)->vb2_queue->mem_ops->op(args) : NULL)
148 #define call_void_memop(vb, op, args...) \
150 if ((vb)->vb2_queue->mem_ops->op) \
151 (vb)->vb2_queue->mem_ops->op(args); \
154 #define call_qop(q, op, args...) \
155 ((q)->ops->op ? (q)->ops->op(args) : 0)
157 #define call_void_qop(q, op, args...) \
160 (q)->ops->op(args); \
163 #define call_vb_qop(vb, op, args...) \
164 ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
166 #define call_void_vb_qop(vb, op, args...) \
168 if ((vb)->vb2_queue->ops->op) \
169 (vb)->vb2_queue->ops->op(args); \
174 #define call_bufop(q, op, args...) \
177 if (q && q->buf_ops && q->buf_ops->op) \
178 ret = q->buf_ops->op(args); \
182 #define call_void_bufop(q, op, args...) \
184 if (q && q->buf_ops && q->buf_ops->op) \
185 q->buf_ops->op(args); \
188 static void __vb2_queue_cancel(struct vb2_queue *q);
189 static void __enqueue_in_driver(struct vb2_buffer *vb);
192 * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
194 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
196 struct vb2_queue *q = vb->vb2_queue;
197 enum dma_data_direction dma_dir =
198 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
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 mem_priv = call_ptr_memop(vb, alloc,
211 q->alloc_devs[plane] ? : q->dev,
212 q->dma_attrs, size, dma_dir, q->gfp_flags);
213 if (IS_ERR(mem_priv)) {
215 ret = PTR_ERR(mem_priv);
219 /* Associate allocator private data with this plane */
220 vb->planes[plane].mem_priv = mem_priv;
225 /* Free already allocated memory if one of the allocations failed */
226 for (; plane > 0; --plane) {
227 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
228 vb->planes[plane - 1].mem_priv = NULL;
235 * __vb2_buf_mem_free() - free memory of the given buffer
237 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
241 for (plane = 0; plane < vb->num_planes; ++plane) {
242 call_void_memop(vb, put, vb->planes[plane].mem_priv);
243 vb->planes[plane].mem_priv = NULL;
244 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
249 * __vb2_buf_userptr_put() - release userspace memory associated with
252 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
256 for (plane = 0; plane < vb->num_planes; ++plane) {
257 if (vb->planes[plane].mem_priv)
258 call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
259 vb->planes[plane].mem_priv = NULL;
264 * __vb2_plane_dmabuf_put() - release memory associated with
265 * a DMABUF shared plane
267 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
273 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
275 call_void_memop(vb, detach_dmabuf, p->mem_priv);
276 dma_buf_put(p->dbuf);
283 * __vb2_buf_dmabuf_put() - release memory associated with
284 * a DMABUF shared buffer
286 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
290 for (plane = 0; plane < vb->num_planes; ++plane)
291 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
295 * __setup_offsets() - setup unique offsets ("cookies") for every plane in
298 static void __setup_offsets(struct vb2_buffer *vb)
300 struct vb2_queue *q = vb->vb2_queue;
302 unsigned long off = 0;
305 struct vb2_buffer *prev = q->bufs[vb->index - 1];
306 struct vb2_plane *p = &prev->planes[prev->num_planes - 1];
308 off = PAGE_ALIGN(p->m.offset + p->length);
311 for (plane = 0; plane < vb->num_planes; ++plane) {
312 vb->planes[plane].m.offset = off;
314 dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
315 vb->index, plane, off);
317 off += vb->planes[plane].length;
318 off = PAGE_ALIGN(off);
323 * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
324 * video buffer memory for all buffers/planes on the queue and initializes the
327 * Returns the number of buffers successfully allocated.
329 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
330 unsigned int num_buffers, unsigned int num_planes,
331 const unsigned plane_sizes[VB2_MAX_PLANES])
333 unsigned int buffer, plane;
334 struct vb2_buffer *vb;
337 for (buffer = 0; buffer < num_buffers; ++buffer) {
338 /* Allocate videobuf buffer structures */
339 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
341 dprintk(1, "memory alloc for buffer struct failed\n");
345 vb->state = VB2_BUF_STATE_DEQUEUED;
347 vb->num_planes = num_planes;
348 vb->index = q->num_buffers + buffer;
351 for (plane = 0; plane < num_planes; ++plane) {
352 vb->planes[plane].length = plane_sizes[plane];
353 vb->planes[plane].min_length = plane_sizes[plane];
355 q->bufs[vb->index] = vb;
357 /* Allocate video buffer memory for the MMAP type */
358 if (memory == VB2_MEMORY_MMAP) {
359 ret = __vb2_buf_mem_alloc(vb);
361 dprintk(1, "failed allocating memory for buffer %d\n",
363 q->bufs[vb->index] = NULL;
369 * Call the driver-provided buffer initialization
370 * callback, if given. An error in initialization
371 * results in queue setup failure.
373 ret = call_vb_qop(vb, buf_init, vb);
375 dprintk(1, "buffer %d %p initialization failed\n",
377 __vb2_buf_mem_free(vb);
378 q->bufs[vb->index] = NULL;
385 dprintk(1, "allocated %d buffers, %d plane(s) each\n",
392 * __vb2_free_mem() - release all video buffer memory for a given queue
394 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
397 struct vb2_buffer *vb;
399 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
401 vb = q->bufs[buffer];
405 /* Free MMAP buffers or release USERPTR buffers */
406 if (q->memory == VB2_MEMORY_MMAP)
407 __vb2_buf_mem_free(vb);
408 else if (q->memory == VB2_MEMORY_DMABUF)
409 __vb2_buf_dmabuf_put(vb);
411 __vb2_buf_userptr_put(vb);
416 * __vb2_queue_free() - free buffers at the end of the queue - video memory and
417 * related information, if no buffers are left return the queue to an
418 * uninitialized state. Might be called even if the queue has already been freed.
420 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
425 * Sanity check: when preparing a buffer the queue lock is released for
426 * a short while (see __buf_prepare for the details), which would allow
427 * a race with a reqbufs which can call this function. Removing the
428 * buffers from underneath __buf_prepare is obviously a bad idea, so we
429 * check if any of the buffers is in the state PREPARING, and if so we
430 * just return -EAGAIN.
432 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
434 if (q->bufs[buffer] == NULL)
436 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
437 dprintk(1, "preparing buffers, cannot free\n");
442 /* Call driver-provided cleanup function for each buffer, if provided */
443 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
445 struct vb2_buffer *vb = q->bufs[buffer];
447 if (vb && vb->planes[0].mem_priv)
448 call_void_vb_qop(vb, buf_cleanup, vb);
451 /* Release video buffer memory */
452 __vb2_free_mem(q, buffers);
454 #ifdef CONFIG_VIDEO_ADV_DEBUG
456 * Check that all the calls were balances during the life-time of this
457 * queue. If not (or if the debug level is 1 or up), then dump the
458 * counters to the kernel log.
460 if (q->num_buffers) {
461 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
462 q->cnt_wait_prepare != q->cnt_wait_finish;
464 if (unbalanced || debug) {
465 pr_info("vb2: counters for queue %p:%s\n", q,
466 unbalanced ? " UNBALANCED!" : "");
467 pr_info("vb2: setup: %u start_streaming: %u stop_streaming: %u\n",
468 q->cnt_queue_setup, q->cnt_start_streaming,
469 q->cnt_stop_streaming);
470 pr_info("vb2: wait_prepare: %u wait_finish: %u\n",
471 q->cnt_wait_prepare, q->cnt_wait_finish);
473 q->cnt_queue_setup = 0;
474 q->cnt_wait_prepare = 0;
475 q->cnt_wait_finish = 0;
476 q->cnt_start_streaming = 0;
477 q->cnt_stop_streaming = 0;
479 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
480 struct vb2_buffer *vb = q->bufs[buffer];
481 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
482 vb->cnt_mem_prepare != vb->cnt_mem_finish ||
483 vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
484 vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
485 vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
486 vb->cnt_buf_queue != vb->cnt_buf_done ||
487 vb->cnt_buf_prepare != vb->cnt_buf_finish ||
488 vb->cnt_buf_init != vb->cnt_buf_cleanup;
490 if (unbalanced || debug) {
491 pr_info("vb2: counters for queue %p, buffer %d:%s\n",
492 q, buffer, unbalanced ? " UNBALANCED!" : "");
493 pr_info("vb2: buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
494 vb->cnt_buf_init, vb->cnt_buf_cleanup,
495 vb->cnt_buf_prepare, vb->cnt_buf_finish);
496 pr_info("vb2: buf_queue: %u buf_done: %u\n",
497 vb->cnt_buf_queue, vb->cnt_buf_done);
498 pr_info("vb2: alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
499 vb->cnt_mem_alloc, vb->cnt_mem_put,
500 vb->cnt_mem_prepare, vb->cnt_mem_finish,
502 pr_info("vb2: get_userptr: %u put_userptr: %u\n",
503 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
504 pr_info("vb2: attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
505 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
506 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
507 pr_info("vb2: get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
508 vb->cnt_mem_get_dmabuf,
509 vb->cnt_mem_num_users,
516 /* Free videobuf buffers */
517 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
519 kfree(q->bufs[buffer]);
520 q->bufs[buffer] = NULL;
523 q->num_buffers -= buffers;
524 if (!q->num_buffers) {
526 INIT_LIST_HEAD(&q->queued_list);
531 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
534 for (plane = 0; plane < vb->num_planes; ++plane) {
535 void *mem_priv = vb->planes[plane].mem_priv;
537 * If num_users() has not been provided, call_memop
538 * will return 0, apparently nobody cares about this
539 * case anyway. If num_users() returns more than 1,
540 * we are not the only user of the plane's memory.
542 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
547 EXPORT_SYMBOL(vb2_buffer_in_use);
550 * __buffers_in_use() - return true if any buffers on the queue are in use and
551 * the queue cannot be freed (by the means of REQBUFS(0)) call
553 static bool __buffers_in_use(struct vb2_queue *q)
556 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
557 if (vb2_buffer_in_use(q, q->bufs[buffer]))
563 void vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
565 call_void_bufop(q, fill_user_buffer, q->bufs[index], pb);
567 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
570 * __verify_userptr_ops() - verify that all memory operations required for
571 * USERPTR queue type have been provided
573 static int __verify_userptr_ops(struct vb2_queue *q)
575 if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
576 !q->mem_ops->put_userptr)
583 * __verify_mmap_ops() - verify that all memory operations required for
584 * MMAP queue type have been provided
586 static int __verify_mmap_ops(struct vb2_queue *q)
588 if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
589 !q->mem_ops->put || !q->mem_ops->mmap)
596 * __verify_dmabuf_ops() - verify that all memory operations required for
597 * DMABUF queue type have been provided
599 static int __verify_dmabuf_ops(struct vb2_queue *q)
601 if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
602 !q->mem_ops->detach_dmabuf || !q->mem_ops->map_dmabuf ||
603 !q->mem_ops->unmap_dmabuf)
609 int vb2_verify_memory_type(struct vb2_queue *q,
610 enum vb2_memory memory, unsigned int type)
612 if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
613 memory != VB2_MEMORY_DMABUF) {
614 dprintk(1, "unsupported memory type\n");
618 if (type != q->type) {
619 dprintk(1, "requested type is incorrect\n");
624 * Make sure all the required memory ops for given memory type
627 if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
628 dprintk(1, "MMAP for current setup unsupported\n");
632 if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
633 dprintk(1, "USERPTR for current setup unsupported\n");
637 if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
638 dprintk(1, "DMABUF for current setup unsupported\n");
643 * Place the busy tests at the end: -EBUSY can be ignored when
644 * create_bufs is called with count == 0, but count == 0 should still
645 * do the memory and type validation.
647 if (vb2_fileio_is_active(q)) {
648 dprintk(1, "file io in progress\n");
653 EXPORT_SYMBOL(vb2_verify_memory_type);
655 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
658 unsigned int num_buffers, allocated_buffers, num_planes = 0;
659 unsigned plane_sizes[VB2_MAX_PLANES] = { };
663 dprintk(1, "streaming active\n");
667 if (*count == 0 || q->num_buffers != 0 || q->memory != memory) {
669 * We already have buffers allocated, so first check if they
670 * are not in use and can be freed.
672 mutex_lock(&q->mmap_lock);
673 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
674 mutex_unlock(&q->mmap_lock);
675 dprintk(1, "memory in use, cannot free\n");
680 * Call queue_cancel to clean up any buffers in the PREPARED or
681 * QUEUED state which is possible if buffers were prepared or
682 * queued without ever calling STREAMON.
684 __vb2_queue_cancel(q);
685 ret = __vb2_queue_free(q, q->num_buffers);
686 mutex_unlock(&q->mmap_lock);
691 * In case of REQBUFS(0) return immediately without calling
692 * driver's queue_setup() callback and allocating resources.
699 * Make sure the requested values and current defaults are sane.
701 num_buffers = min_t(unsigned int, *count, VB2_MAX_FRAME);
702 num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
703 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
707 * Ask the driver how many buffers and planes per buffer it requires.
708 * Driver also sets the size and allocator context for each plane.
710 ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
711 plane_sizes, q->alloc_devs);
715 /* Finally, allocate buffers and video memory */
717 __vb2_queue_alloc(q, memory, num_buffers, num_planes, plane_sizes);
718 if (allocated_buffers == 0) {
719 dprintk(1, "memory allocation failed\n");
724 * There is no point in continuing if we can't allocate the minimum
725 * number of buffers needed by this vb2_queue.
727 if (allocated_buffers < q->min_buffers_needed)
731 * Check if driver can handle the allocated number of buffers.
733 if (!ret && allocated_buffers < num_buffers) {
734 num_buffers = allocated_buffers;
736 * num_planes is set by the previous queue_setup(), but since it
737 * signals to queue_setup() whether it is called from create_bufs()
738 * vs reqbufs() we zero it here to signal that queue_setup() is
739 * called for the reqbufs() case.
743 ret = call_qop(q, queue_setup, q, &num_buffers,
744 &num_planes, plane_sizes, q->alloc_devs);
746 if (!ret && allocated_buffers < num_buffers)
750 * Either the driver has accepted a smaller number of buffers,
751 * or .queue_setup() returned an error
755 mutex_lock(&q->mmap_lock);
756 q->num_buffers = allocated_buffers;
760 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
761 * from q->num_buffers.
763 __vb2_queue_free(q, allocated_buffers);
764 mutex_unlock(&q->mmap_lock);
767 mutex_unlock(&q->mmap_lock);
770 * Return the number of successfully allocated buffers
773 *count = allocated_buffers;
774 q->waiting_for_buffers = !q->is_output;
778 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
780 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
781 unsigned int *count, unsigned requested_planes,
782 const unsigned requested_sizes[])
784 unsigned int num_planes = 0, num_buffers, allocated_buffers;
785 unsigned plane_sizes[VB2_MAX_PLANES] = { };
788 if (q->num_buffers == VB2_MAX_FRAME) {
789 dprintk(1, "maximum number of buffers already allocated\n");
793 if (!q->num_buffers) {
794 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
796 q->waiting_for_buffers = !q->is_output;
799 num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
801 if (requested_planes && requested_sizes) {
802 num_planes = requested_planes;
803 memcpy(plane_sizes, requested_sizes, sizeof(plane_sizes));
807 * Ask the driver, whether the requested number of buffers, planes per
808 * buffer and their sizes are acceptable
810 ret = call_qop(q, queue_setup, q, &num_buffers,
811 &num_planes, plane_sizes, q->alloc_devs);
815 /* Finally, allocate buffers and video memory */
816 allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
817 num_planes, plane_sizes);
818 if (allocated_buffers == 0) {
819 dprintk(1, "memory allocation failed\n");
824 * Check if driver can handle the so far allocated number of buffers.
826 if (allocated_buffers < num_buffers) {
827 num_buffers = allocated_buffers;
830 * q->num_buffers contains the total number of buffers, that the
831 * queue driver has set up
833 ret = call_qop(q, queue_setup, q, &num_buffers,
834 &num_planes, plane_sizes, q->alloc_devs);
836 if (!ret && allocated_buffers < num_buffers)
840 * Either the driver has accepted a smaller number of buffers,
841 * or .queue_setup() returned an error
845 mutex_lock(&q->mmap_lock);
846 q->num_buffers += allocated_buffers;
850 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
851 * from q->num_buffers.
853 __vb2_queue_free(q, allocated_buffers);
854 mutex_unlock(&q->mmap_lock);
857 mutex_unlock(&q->mmap_lock);
860 * Return the number of successfully allocated buffers
863 *count = allocated_buffers;
867 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
869 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
871 if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
874 return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
877 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
879 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
881 if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
884 return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
886 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
888 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
890 struct vb2_queue *q = vb->vb2_queue;
894 if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
897 if (WARN_ON(state != VB2_BUF_STATE_DONE &&
898 state != VB2_BUF_STATE_ERROR &&
899 state != VB2_BUF_STATE_QUEUED &&
900 state != VB2_BUF_STATE_REQUEUEING))
901 state = VB2_BUF_STATE_ERROR;
903 #ifdef CONFIG_VIDEO_ADV_DEBUG
905 * Although this is not a callback, it still does have to balance
906 * with the buf_queue op. So update this counter manually.
910 dprintk(4, "done processing on buffer %d, state: %d\n",
914 for (plane = 0; plane < vb->num_planes; ++plane)
915 call_void_memop(vb, finish, vb->planes[plane].mem_priv);
917 spin_lock_irqsave(&q->done_lock, flags);
918 if (state == VB2_BUF_STATE_QUEUED ||
919 state == VB2_BUF_STATE_REQUEUEING) {
920 vb->state = VB2_BUF_STATE_QUEUED;
922 /* Add the buffer to the done buffers list */
923 list_add_tail(&vb->done_entry, &q->done_list);
926 atomic_dec(&q->owned_by_drv_count);
927 spin_unlock_irqrestore(&q->done_lock, flags);
929 trace_vb2_buf_done(q, vb);
932 case VB2_BUF_STATE_QUEUED:
934 case VB2_BUF_STATE_REQUEUEING:
935 if (q->start_streaming_called)
936 __enqueue_in_driver(vb);
939 /* Inform any processes that may be waiting for buffers */
940 wake_up(&q->done_wq);
944 EXPORT_SYMBOL_GPL(vb2_buffer_done);
946 void vb2_discard_done(struct vb2_queue *q)
948 struct vb2_buffer *vb;
951 spin_lock_irqsave(&q->done_lock, flags);
952 list_for_each_entry(vb, &q->done_list, done_entry)
953 vb->state = VB2_BUF_STATE_ERROR;
954 spin_unlock_irqrestore(&q->done_lock, flags);
956 EXPORT_SYMBOL_GPL(vb2_discard_done);
959 * __qbuf_mmap() - handle qbuf of an MMAP buffer
961 static int __qbuf_mmap(struct vb2_buffer *vb, const void *pb)
966 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
968 return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
972 * __qbuf_userptr() - handle qbuf of a USERPTR buffer
974 static int __qbuf_userptr(struct vb2_buffer *vb, const void *pb)
976 struct vb2_plane planes[VB2_MAX_PLANES];
977 struct vb2_queue *q = vb->vb2_queue;
981 enum dma_data_direction dma_dir =
982 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
983 bool reacquired = vb->planes[0].mem_priv == NULL;
985 memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
986 /* Copy relevant information provided by the userspace */
988 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
994 for (plane = 0; plane < vb->num_planes; ++plane) {
995 /* Skip the plane if already verified */
996 if (vb->planes[plane].m.userptr &&
997 vb->planes[plane].m.userptr == planes[plane].m.userptr
998 && vb->planes[plane].length == planes[plane].length)
1001 dprintk(3, "userspace address for plane %d changed, reacquiring memory\n",
1004 /* Check if the provided plane buffer is large enough */
1005 if (planes[plane].length < vb->planes[plane].min_length) {
1006 dprintk(1, "provided buffer size %u is less than setup size %u for plane %d\n",
1007 planes[plane].length,
1008 vb->planes[plane].min_length,
1014 /* Release previously acquired memory if present */
1015 if (vb->planes[plane].mem_priv) {
1018 call_void_vb_qop(vb, buf_cleanup, vb);
1020 call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1023 vb->planes[plane].mem_priv = NULL;
1024 vb->planes[plane].bytesused = 0;
1025 vb->planes[plane].length = 0;
1026 vb->planes[plane].m.userptr = 0;
1027 vb->planes[plane].data_offset = 0;
1029 /* Acquire each plane's memory */
1030 mem_priv = call_ptr_memop(vb, get_userptr,
1031 q->alloc_devs[plane] ? : q->dev,
1032 planes[plane].m.userptr,
1033 planes[plane].length, dma_dir);
1034 if (IS_ERR(mem_priv)) {
1035 dprintk(1, "failed acquiring userspace memory for plane %d\n",
1037 ret = PTR_ERR(mem_priv);
1040 vb->planes[plane].mem_priv = mem_priv;
1044 * Now that everything is in order, copy relevant information
1045 * provided by userspace.
1047 for (plane = 0; plane < vb->num_planes; ++plane) {
1048 vb->planes[plane].bytesused = planes[plane].bytesused;
1049 vb->planes[plane].length = planes[plane].length;
1050 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1051 vb->planes[plane].data_offset = planes[plane].data_offset;
1056 * One or more planes changed, so we must call buf_init to do
1057 * the driver-specific initialization on the newly acquired
1058 * buffer, if provided.
1060 ret = call_vb_qop(vb, buf_init, vb);
1062 dprintk(1, "buffer initialization failed\n");
1067 ret = call_vb_qop(vb, buf_prepare, vb);
1069 dprintk(1, "buffer preparation failed\n");
1070 call_void_vb_qop(vb, buf_cleanup, vb);
1076 /* In case of errors, release planes that were already acquired */
1077 for (plane = 0; plane < vb->num_planes; ++plane) {
1078 if (vb->planes[plane].mem_priv)
1079 call_void_memop(vb, put_userptr,
1080 vb->planes[plane].mem_priv);
1081 vb->planes[plane].mem_priv = NULL;
1082 vb->planes[plane].m.userptr = 0;
1083 vb->planes[plane].length = 0;
1090 * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1092 static int __qbuf_dmabuf(struct vb2_buffer *vb, const void *pb)
1094 struct vb2_plane planes[VB2_MAX_PLANES];
1095 struct vb2_queue *q = vb->vb2_queue;
1099 enum dma_data_direction dma_dir =
1100 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1101 bool reacquired = vb->planes[0].mem_priv == NULL;
1103 memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1104 /* Copy relevant information provided by the userspace */
1106 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1112 for (plane = 0; plane < vb->num_planes; ++plane) {
1113 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1115 if (IS_ERR_OR_NULL(dbuf)) {
1116 dprintk(1, "invalid dmabuf fd for plane %d\n",
1122 /* use DMABUF size if length is not provided */
1123 if (planes[plane].length == 0)
1124 planes[plane].length = dbuf->size;
1126 if (planes[plane].length < vb->planes[plane].min_length) {
1127 dprintk(1, "invalid dmabuf length %u for plane %d, minimum length %u\n",
1128 planes[plane].length, plane,
1129 vb->planes[plane].min_length);
1135 /* Skip the plane if already verified */
1136 if (dbuf == vb->planes[plane].dbuf &&
1137 vb->planes[plane].length == planes[plane].length) {
1142 dprintk(1, "buffer for plane %d changed\n", plane);
1146 call_void_vb_qop(vb, buf_cleanup, vb);
1149 /* Release previously acquired memory if present */
1150 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1151 vb->planes[plane].bytesused = 0;
1152 vb->planes[plane].length = 0;
1153 vb->planes[plane].m.fd = 0;
1154 vb->planes[plane].data_offset = 0;
1156 /* Acquire each plane's memory */
1157 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1158 q->alloc_devs[plane] ? : q->dev,
1159 dbuf, planes[plane].length, dma_dir);
1160 if (IS_ERR(mem_priv)) {
1161 dprintk(1, "failed to attach dmabuf\n");
1162 ret = PTR_ERR(mem_priv);
1167 vb->planes[plane].dbuf = dbuf;
1168 vb->planes[plane].mem_priv = mem_priv;
1172 * This pins the buffer(s) with dma_buf_map_attachment()). It's done
1173 * here instead just before the DMA, while queueing the buffer(s) so
1174 * userspace knows sooner rather than later if the dma-buf map fails.
1176 for (plane = 0; plane < vb->num_planes; ++plane) {
1177 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1179 dprintk(1, "failed to map dmabuf for plane %d\n",
1183 vb->planes[plane].dbuf_mapped = 1;
1187 * Now that everything is in order, copy relevant information
1188 * provided by userspace.
1190 for (plane = 0; plane < vb->num_planes; ++plane) {
1191 vb->planes[plane].bytesused = planes[plane].bytesused;
1192 vb->planes[plane].length = planes[plane].length;
1193 vb->planes[plane].m.fd = planes[plane].m.fd;
1194 vb->planes[plane].data_offset = planes[plane].data_offset;
1199 * Call driver-specific initialization on the newly acquired buffer,
1202 ret = call_vb_qop(vb, buf_init, vb);
1204 dprintk(1, "buffer initialization failed\n");
1209 ret = call_vb_qop(vb, buf_prepare, vb);
1211 dprintk(1, "buffer preparation failed\n");
1212 call_void_vb_qop(vb, buf_cleanup, vb);
1218 /* In case of errors, release planes that were already acquired */
1219 __vb2_buf_dmabuf_put(vb);
1225 * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1227 static void __enqueue_in_driver(struct vb2_buffer *vb)
1229 struct vb2_queue *q = vb->vb2_queue;
1232 vb->state = VB2_BUF_STATE_ACTIVE;
1233 atomic_inc(&q->owned_by_drv_count);
1235 trace_vb2_buf_queue(q, vb);
1238 for (plane = 0; plane < vb->num_planes; ++plane)
1239 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1241 call_void_vb_qop(vb, buf_queue, vb);
1244 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1246 struct vb2_queue *q = vb->vb2_queue;
1250 dprintk(1, "fatal error occurred on queue\n");
1254 vb->state = VB2_BUF_STATE_PREPARING;
1256 switch (q->memory) {
1257 case VB2_MEMORY_MMAP:
1258 ret = __qbuf_mmap(vb, pb);
1260 case VB2_MEMORY_USERPTR:
1261 ret = __qbuf_userptr(vb, pb);
1263 case VB2_MEMORY_DMABUF:
1264 ret = __qbuf_dmabuf(vb, pb);
1267 WARN(1, "Invalid queue type\n");
1272 dprintk(1, "buffer preparation failed: %d\n", ret);
1273 vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1278 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1280 struct vb2_buffer *vb;
1283 vb = q->bufs[index];
1284 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1285 dprintk(1, "invalid buffer state %d\n",
1290 ret = __buf_prepare(vb, pb);
1294 /* Fill buffer information for the userspace */
1295 call_void_bufop(q, fill_user_buffer, vb, pb);
1297 dprintk(1, "prepare of buffer %d succeeded\n", vb->index);
1301 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1304 * vb2_start_streaming() - Attempt to start streaming.
1305 * @q: videobuf2 queue
1307 * Attempt to start streaming. When this function is called there must be
1308 * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1309 * number of buffers required for the DMA engine to function). If the
1310 * @start_streaming op fails it is supposed to return all the driver-owned
1311 * buffers back to vb2 in state QUEUED. Check if that happened and if
1312 * not warn and reclaim them forcefully.
1314 static int vb2_start_streaming(struct vb2_queue *q)
1316 struct vb2_buffer *vb;
1320 * If any buffers were queued before streamon,
1321 * we can now pass them to driver for processing.
1323 list_for_each_entry(vb, &q->queued_list, queued_entry)
1324 __enqueue_in_driver(vb);
1326 /* Tell the driver to start streaming */
1327 q->start_streaming_called = 1;
1328 ret = call_qop(q, start_streaming, q,
1329 atomic_read(&q->owned_by_drv_count));
1333 q->start_streaming_called = 0;
1335 dprintk(1, "driver refused to start streaming\n");
1337 * If you see this warning, then the driver isn't cleaning up properly
1338 * after a failed start_streaming(). See the start_streaming()
1339 * documentation in videobuf2-core.h for more information how buffers
1340 * should be returned to vb2 in start_streaming().
1342 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1346 * Forcefully reclaim buffers if the driver did not
1347 * correctly return them to vb2.
1349 for (i = 0; i < q->num_buffers; ++i) {
1351 if (vb->state == VB2_BUF_STATE_ACTIVE)
1352 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1354 /* Must be zero now */
1355 WARN_ON(atomic_read(&q->owned_by_drv_count));
1358 * If done_list is not empty, then start_streaming() didn't call
1359 * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1362 WARN_ON(!list_empty(&q->done_list));
1366 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1368 struct vb2_buffer *vb;
1371 vb = q->bufs[index];
1373 switch (vb->state) {
1374 case VB2_BUF_STATE_DEQUEUED:
1375 ret = __buf_prepare(vb, pb);
1379 case VB2_BUF_STATE_PREPARED:
1381 case VB2_BUF_STATE_PREPARING:
1382 dprintk(1, "buffer still being prepared\n");
1385 dprintk(1, "invalid buffer state %d\n", vb->state);
1390 * Add to the queued buffers list, a buffer will stay on it until
1391 * dequeued in dqbuf.
1393 list_add_tail(&vb->queued_entry, &q->queued_list);
1395 q->waiting_for_buffers = false;
1396 vb->state = VB2_BUF_STATE_QUEUED;
1399 call_void_bufop(q, copy_timestamp, vb, pb);
1401 trace_vb2_qbuf(q, vb);
1404 * If already streaming, give the buffer to driver for processing.
1405 * If not, the buffer will be given to driver on next streamon.
1407 if (q->start_streaming_called)
1408 __enqueue_in_driver(vb);
1410 /* Fill buffer information for the userspace */
1412 call_void_bufop(q, fill_user_buffer, vb, pb);
1415 * If streamon has been called, and we haven't yet called
1416 * start_streaming() since not enough buffers were queued, and
1417 * we now have reached the minimum number of queued buffers,
1418 * then we can finally call start_streaming().
1420 if (q->streaming && !q->start_streaming_called &&
1421 q->queued_count >= q->min_buffers_needed) {
1422 ret = vb2_start_streaming(q);
1427 dprintk(1, "qbuf of buffer %d succeeded\n", vb->index);
1430 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1433 * __vb2_wait_for_done_vb() - wait for a buffer to become available
1436 * Will sleep if required for nonblocking == false.
1438 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1441 * All operations on vb_done_list are performed under done_lock
1442 * spinlock protection. However, buffers may be removed from
1443 * it and returned to userspace only while holding both driver's
1444 * lock and the done_lock spinlock. Thus we can be sure that as
1445 * long as we hold the driver's lock, the list will remain not
1446 * empty if list_empty() check succeeds.
1452 if (!q->streaming) {
1453 dprintk(1, "streaming off, will not wait for buffers\n");
1458 dprintk(1, "Queue in error state, will not wait for buffers\n");
1462 if (q->last_buffer_dequeued) {
1463 dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1467 if (!list_empty(&q->done_list)) {
1469 * Found a buffer that we were waiting for.
1475 dprintk(1, "nonblocking and no buffers to dequeue, will not wait\n");
1480 * We are streaming and blocking, wait for another buffer to
1481 * become ready or for streamoff. Driver's lock is released to
1482 * allow streamoff or qbuf to be called while waiting.
1484 call_void_qop(q, wait_prepare, q);
1487 * All locks have been released, it is safe to sleep now.
1489 dprintk(3, "will sleep waiting for buffers\n");
1490 ret = wait_event_interruptible(q->done_wq,
1491 !list_empty(&q->done_list) || !q->streaming ||
1495 * We need to reevaluate both conditions again after reacquiring
1496 * the locks or return an error if one occurred.
1498 call_void_qop(q, wait_finish, q);
1500 dprintk(1, "sleep was interrupted\n");
1508 * __vb2_get_done_vb() - get a buffer ready for dequeuing
1510 * Will sleep if required for nonblocking == false.
1512 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1513 void *pb, int nonblocking)
1515 unsigned long flags;
1519 * Wait for at least one buffer to become available on the done_list.
1521 ret = __vb2_wait_for_done_vb(q, nonblocking);
1526 * Driver's lock has been held since we last verified that done_list
1527 * is not empty, so no need for another list_empty(done_list) check.
1529 spin_lock_irqsave(&q->done_lock, flags);
1530 *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1532 * Only remove the buffer from done_list if all planes can be
1533 * handled. Some cases such as V4L2 file I/O and DVB have pb
1534 * == NULL; skip the check then as there's nothing to verify.
1537 ret = call_bufop(q, verify_planes_array, *vb, pb);
1539 list_del(&(*vb)->done_entry);
1540 spin_unlock_irqrestore(&q->done_lock, flags);
1545 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1547 if (!q->streaming) {
1548 dprintk(1, "streaming off, will not wait for buffers\n");
1552 if (q->start_streaming_called)
1553 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1556 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1559 * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1561 static void __vb2_dqbuf(struct vb2_buffer *vb)
1563 struct vb2_queue *q = vb->vb2_queue;
1566 /* nothing to do if the buffer is already dequeued */
1567 if (vb->state == VB2_BUF_STATE_DEQUEUED)
1570 vb->state = VB2_BUF_STATE_DEQUEUED;
1572 /* unmap DMABUF buffer */
1573 if (q->memory == VB2_MEMORY_DMABUF)
1574 for (i = 0; i < vb->num_planes; ++i) {
1575 if (!vb->planes[i].dbuf_mapped)
1577 call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1578 vb->planes[i].dbuf_mapped = 0;
1582 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1585 struct vb2_buffer *vb = NULL;
1588 ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1592 switch (vb->state) {
1593 case VB2_BUF_STATE_DONE:
1594 dprintk(3, "returning done buffer\n");
1596 case VB2_BUF_STATE_ERROR:
1597 dprintk(3, "returning done buffer with errors\n");
1600 dprintk(1, "invalid buffer state\n");
1604 call_void_vb_qop(vb, buf_finish, vb);
1607 *pindex = vb->index;
1609 /* Fill buffer information for the userspace */
1611 call_void_bufop(q, fill_user_buffer, vb, pb);
1613 /* Remove from videobuf queue */
1614 list_del(&vb->queued_entry);
1617 trace_vb2_dqbuf(q, vb);
1619 /* go back to dequeued state */
1622 dprintk(1, "dqbuf of buffer %d, with state %d\n",
1623 vb->index, vb->state);
1628 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1631 * __vb2_queue_cancel() - cancel and stop (pause) streaming
1633 * Removes all queued buffers from driver's queue and all buffers queued by
1634 * userspace from videobuf's queue. Returns to state after reqbufs.
1636 static void __vb2_queue_cancel(struct vb2_queue *q)
1641 * Tell driver to stop all transactions and release all queued
1644 if (q->start_streaming_called)
1645 call_void_qop(q, stop_streaming, q);
1648 * If you see this warning, then the driver isn't cleaning up properly
1649 * in stop_streaming(). See the stop_streaming() documentation in
1650 * videobuf2-core.h for more information how buffers should be returned
1651 * to vb2 in stop_streaming().
1653 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1654 for (i = 0; i < q->num_buffers; ++i)
1655 if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
1656 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1657 /* Must be zero now */
1658 WARN_ON(atomic_read(&q->owned_by_drv_count));
1662 q->start_streaming_called = 0;
1663 q->queued_count = 0;
1667 * Remove all buffers from videobuf's list...
1669 INIT_LIST_HEAD(&q->queued_list);
1671 * ...and done list; userspace will not receive any buffers it
1672 * has not already dequeued before initiating cancel.
1674 INIT_LIST_HEAD(&q->done_list);
1675 atomic_set(&q->owned_by_drv_count, 0);
1676 wake_up_all(&q->done_wq);
1679 * Reinitialize all buffers for next use.
1680 * Make sure to call buf_finish for any queued buffers. Normally
1681 * that's done in dqbuf, but that's not going to happen when we
1682 * cancel the whole queue. Note: this code belongs here, not in
1683 * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1684 * call to __fill_user_buffer() after buf_finish(). That order can't
1685 * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1687 for (i = 0; i < q->num_buffers; ++i) {
1688 struct vb2_buffer *vb = q->bufs[i];
1690 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1691 vb->state = VB2_BUF_STATE_PREPARED;
1692 call_void_vb_qop(vb, buf_finish, vb);
1698 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1702 if (type != q->type) {
1703 dprintk(1, "invalid stream type\n");
1708 dprintk(3, "already streaming\n");
1712 if (!q->num_buffers) {
1713 dprintk(1, "no buffers have been allocated\n");
1717 if (q->num_buffers < q->min_buffers_needed) {
1718 dprintk(1, "need at least %u allocated buffers\n",
1719 q->min_buffers_needed);
1724 * Tell driver to start streaming provided sufficient buffers
1727 if (q->queued_count >= q->min_buffers_needed) {
1728 ret = v4l_vb2q_enable_media_source(q);
1731 ret = vb2_start_streaming(q);
1733 __vb2_queue_cancel(q);
1740 dprintk(3, "successful\n");
1743 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1745 void vb2_queue_error(struct vb2_queue *q)
1749 wake_up_all(&q->done_wq);
1751 EXPORT_SYMBOL_GPL(vb2_queue_error);
1753 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1755 if (type != q->type) {
1756 dprintk(1, "invalid stream type\n");
1761 * Cancel will pause streaming and remove all buffers from the driver
1762 * and videobuf, effectively returning control over them to userspace.
1764 * Note that we do this even if q->streaming == 0: if you prepare or
1765 * queue buffers, and then call streamoff without ever having called
1766 * streamon, you would still expect those buffers to be returned to
1767 * their normal dequeued state.
1769 __vb2_queue_cancel(q);
1770 q->waiting_for_buffers = !q->is_output;
1771 q->last_buffer_dequeued = false;
1773 dprintk(3, "successful\n");
1776 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1779 * __find_plane_by_offset() - find plane associated with the given offset off
1781 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1782 unsigned int *_buffer, unsigned int *_plane)
1784 struct vb2_buffer *vb;
1785 unsigned int buffer, plane;
1788 * Go over all buffers and their planes, comparing the given offset
1789 * with an offset assigned to each plane. If a match is found,
1790 * return its buffer and plane numbers.
1792 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1793 vb = q->bufs[buffer];
1795 for (plane = 0; plane < vb->num_planes; ++plane) {
1796 if (vb->planes[plane].m.offset == off) {
1807 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1808 unsigned int index, unsigned int plane, unsigned int flags)
1810 struct vb2_buffer *vb = NULL;
1811 struct vb2_plane *vb_plane;
1813 struct dma_buf *dbuf;
1815 if (q->memory != VB2_MEMORY_MMAP) {
1816 dprintk(1, "queue is not currently set up for mmap\n");
1820 if (!q->mem_ops->get_dmabuf) {
1821 dprintk(1, "queue does not support DMA buffer exporting\n");
1825 if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1826 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1830 if (type != q->type) {
1831 dprintk(1, "invalid buffer type\n");
1835 if (index >= q->num_buffers) {
1836 dprintk(1, "buffer index out of range\n");
1840 vb = q->bufs[index];
1842 if (plane >= vb->num_planes) {
1843 dprintk(1, "buffer plane out of range\n");
1847 if (vb2_fileio_is_active(q)) {
1848 dprintk(1, "expbuf: file io in progress\n");
1852 vb_plane = &vb->planes[plane];
1854 dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1856 if (IS_ERR_OR_NULL(dbuf)) {
1857 dprintk(1, "failed to export buffer %d, plane %d\n",
1862 ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1864 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1870 dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1876 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1878 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1880 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1881 struct vb2_buffer *vb;
1882 unsigned int buffer = 0, plane = 0;
1884 unsigned long length;
1886 if (q->memory != VB2_MEMORY_MMAP) {
1887 dprintk(1, "queue is not currently set up for mmap\n");
1892 * Check memory area access mode.
1894 if (!(vma->vm_flags & VM_SHARED)) {
1895 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1899 if (!(vma->vm_flags & VM_WRITE)) {
1900 dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1904 if (!(vma->vm_flags & VM_READ)) {
1905 dprintk(1, "invalid vma flags, VM_READ needed\n");
1909 if (vb2_fileio_is_active(q)) {
1910 dprintk(1, "mmap: file io in progress\n");
1915 * Find the plane corresponding to the offset passed by userspace.
1917 ret = __find_plane_by_offset(q, off, &buffer, &plane);
1921 vb = q->bufs[buffer];
1924 * MMAP requires page_aligned buffers.
1925 * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1926 * so, we need to do the same here.
1928 length = PAGE_ALIGN(vb->planes[plane].length);
1929 if (length < (vma->vm_end - vma->vm_start)) {
1931 "MMAP invalid, as it would overflow buffer length\n");
1935 mutex_lock(&q->mmap_lock);
1936 ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1937 mutex_unlock(&q->mmap_lock);
1941 dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
1944 EXPORT_SYMBOL_GPL(vb2_mmap);
1947 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
1950 unsigned long pgoff,
1951 unsigned long flags)
1953 unsigned long off = pgoff << PAGE_SHIFT;
1954 struct vb2_buffer *vb;
1955 unsigned int buffer, plane;
1959 if (q->memory != VB2_MEMORY_MMAP) {
1960 dprintk(1, "queue is not currently set up for mmap\n");
1965 * Find the plane corresponding to the offset passed by userspace.
1967 ret = __find_plane_by_offset(q, off, &buffer, &plane);
1971 vb = q->bufs[buffer];
1973 vaddr = vb2_plane_vaddr(vb, plane);
1974 return vaddr ? (unsigned long)vaddr : -EINVAL;
1976 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
1979 int vb2_core_queue_init(struct vb2_queue *q)
1986 WARN_ON(!q->mem_ops) ||
1987 WARN_ON(!q->type) ||
1988 WARN_ON(!q->io_modes) ||
1989 WARN_ON(!q->ops->queue_setup) ||
1990 WARN_ON(!q->ops->buf_queue))
1993 INIT_LIST_HEAD(&q->queued_list);
1994 INIT_LIST_HEAD(&q->done_list);
1995 spin_lock_init(&q->done_lock);
1996 mutex_init(&q->mmap_lock);
1997 init_waitqueue_head(&q->done_wq);
1999 if (q->buf_struct_size == 0)
2000 q->buf_struct_size = sizeof(struct vb2_buffer);
2004 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2006 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2007 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2008 void vb2_core_queue_release(struct vb2_queue *q)
2010 __vb2_cleanup_fileio(q);
2011 __vb2_queue_cancel(q);
2012 mutex_lock(&q->mmap_lock);
2013 __vb2_queue_free(q, q->num_buffers);
2014 mutex_unlock(&q->mmap_lock);
2016 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2018 unsigned int vb2_core_poll(struct vb2_queue *q, struct file *file,
2021 unsigned long req_events = poll_requested_events(wait);
2022 struct vb2_buffer *vb = NULL;
2023 unsigned long flags;
2025 if (!q->is_output && !(req_events & (POLLIN | POLLRDNORM)))
2027 if (q->is_output && !(req_events & (POLLOUT | POLLWRNORM)))
2031 * Start file I/O emulator only if streaming API has not been used yet.
2033 if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2034 if (!q->is_output && (q->io_modes & VB2_READ) &&
2035 (req_events & (POLLIN | POLLRDNORM))) {
2036 if (__vb2_init_fileio(q, 1))
2039 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2040 (req_events & (POLLOUT | POLLWRNORM))) {
2041 if (__vb2_init_fileio(q, 0))
2044 * Write to OUTPUT queue can be done immediately.
2046 return POLLOUT | POLLWRNORM;
2051 * There is nothing to wait for if the queue isn't streaming, or if the
2052 * error flag is set.
2054 if (!vb2_is_streaming(q) || q->error)
2058 * If this quirk is set and QBUF hasn't been called yet then
2059 * return POLLERR as well. This only affects capture queues, output
2060 * queues will always initialize waiting_for_buffers to false.
2061 * This quirk is set by V4L2 for backwards compatibility reasons.
2063 if (q->quirk_poll_must_check_waiting_for_buffers &&
2064 q->waiting_for_buffers && (req_events & (POLLIN | POLLRDNORM)))
2068 * For output streams you can call write() as long as there are fewer
2069 * buffers queued than there are buffers available.
2071 if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2072 return POLLOUT | POLLWRNORM;
2074 if (list_empty(&q->done_list)) {
2076 * If the last buffer was dequeued from a capture queue,
2077 * return immediately. DQBUF will return -EPIPE.
2079 if (q->last_buffer_dequeued)
2080 return POLLIN | POLLRDNORM;
2082 poll_wait(file, &q->done_wq, wait);
2086 * Take first buffer available for dequeuing.
2088 spin_lock_irqsave(&q->done_lock, flags);
2089 if (!list_empty(&q->done_list))
2090 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2092 spin_unlock_irqrestore(&q->done_lock, flags);
2094 if (vb && (vb->state == VB2_BUF_STATE_DONE
2095 || vb->state == VB2_BUF_STATE_ERROR)) {
2096 return (q->is_output) ?
2097 POLLOUT | POLLWRNORM :
2098 POLLIN | POLLRDNORM;
2102 EXPORT_SYMBOL_GPL(vb2_core_poll);
2105 * struct vb2_fileio_buf - buffer context used by file io emulator
2107 * vb2 provides a compatibility layer and emulator of file io (read and
2108 * write) calls on top of streaming API. This structure is used for
2109 * tracking context related to the buffers.
2111 struct vb2_fileio_buf {
2115 unsigned int queued:1;
2119 * struct vb2_fileio_data - queue context used by file io emulator
2121 * @cur_index: the index of the buffer currently being read from or
2122 * written to. If equal to q->num_buffers then a new buffer
2124 * @initial_index: in the read() case all buffers are queued up immediately
2125 * in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2126 * buffers. However, in the write() case no buffers are initially
2127 * queued, instead whenever a buffer is full it is queued up by
2128 * __vb2_perform_fileio(). Only once all available buffers have
2129 * been queued up will __vb2_perform_fileio() start to dequeue
2130 * buffers. This means that initially __vb2_perform_fileio()
2131 * needs to know what buffer index to use when it is queuing up
2132 * the buffers for the first time. That initial index is stored
2133 * in this field. Once it is equal to q->num_buffers all
2134 * available buffers have been queued and __vb2_perform_fileio()
2135 * should start the normal dequeue/queue cycle.
2137 * vb2 provides a compatibility layer and emulator of file io (read and
2138 * write) calls on top of streaming API. For proper operation it required
2139 * this structure to save the driver state between each call of the read
2140 * or write function.
2142 struct vb2_fileio_data {
2145 unsigned int memory;
2146 struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2147 unsigned int cur_index;
2148 unsigned int initial_index;
2149 unsigned int q_count;
2150 unsigned int dq_count;
2151 unsigned read_once:1;
2152 unsigned write_immediately:1;
2156 * __vb2_init_fileio() - initialize file io emulator
2157 * @q: videobuf2 queue
2158 * @read: mode selector (1 means read, 0 means write)
2160 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2162 struct vb2_fileio_data *fileio;
2164 unsigned int count = 0;
2169 if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2170 (!read && !(q->io_modes & VB2_WRITE))))
2174 * Check if device supports mapping buffers to kernel virtual space.
2176 if (!q->mem_ops->vaddr)
2180 * Check if streaming api has not been already activated.
2182 if (q->streaming || q->num_buffers > 0)
2186 * Start with count 1, driver can increase it in queue_setup()
2190 dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2191 (read) ? "read" : "write", count, q->fileio_read_once,
2192 q->fileio_write_immediately);
2194 fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2198 fileio->read_once = q->fileio_read_once;
2199 fileio->write_immediately = q->fileio_write_immediately;
2202 * Request buffers and use MMAP type to force driver
2203 * to allocate buffers by itself.
2205 fileio->count = count;
2206 fileio->memory = VB2_MEMORY_MMAP;
2207 fileio->type = q->type;
2209 ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2214 * Check if plane_count is correct
2215 * (multiplane buffers are not supported).
2217 if (q->bufs[0]->num_planes != 1) {
2223 * Get kernel address of each buffer.
2225 for (i = 0; i < q->num_buffers; i++) {
2226 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2227 if (fileio->bufs[i].vaddr == NULL) {
2231 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2235 * Read mode requires pre queuing of all buffers.
2239 * Queue all buffers.
2241 for (i = 0; i < q->num_buffers; i++) {
2242 ret = vb2_core_qbuf(q, i, NULL);
2245 fileio->bufs[i].queued = 1;
2248 * All buffers have been queued, so mark that by setting
2249 * initial_index to q->num_buffers
2251 fileio->initial_index = q->num_buffers;
2252 fileio->cur_index = q->num_buffers;
2258 ret = vb2_core_streamon(q, q->type);
2266 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2275 * __vb2_cleanup_fileio() - free resourced used by file io emulator
2276 * @q: videobuf2 queue
2278 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2280 struct vb2_fileio_data *fileio = q->fileio;
2283 vb2_core_streamoff(q, q->type);
2286 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2288 dprintk(3, "file io emulator closed\n");
2294 * __vb2_perform_fileio() - perform a single file io (read or write) operation
2295 * @q: videobuf2 queue
2296 * @data: pointed to target userspace buffer
2297 * @count: number of bytes to read or write
2298 * @ppos: file handle position tracking pointer
2299 * @nonblock: mode selector (1 means blocking calls, 0 means nonblocking)
2300 * @read: access mode selector (1 means read, 0 means write)
2302 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2303 loff_t *ppos, int nonblock, int read)
2305 struct vb2_fileio_data *fileio;
2306 struct vb2_fileio_buf *buf;
2307 bool is_multiplanar = q->is_multiplanar;
2309 * When using write() to write data to an output video node the vb2 core
2310 * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2311 * else is able to provide this information with the write() operation.
2313 bool copy_timestamp = !read && q->copy_timestamp;
2317 dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2318 read ? "read" : "write", (long)*ppos, count,
2319 nonblock ? "non" : "");
2325 * Initialize emulator on first call.
2327 if (!vb2_fileio_is_active(q)) {
2328 ret = __vb2_init_fileio(q, read);
2329 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2336 * Check if we need to dequeue the buffer.
2338 index = fileio->cur_index;
2339 if (index >= q->num_buffers) {
2340 struct vb2_buffer *b;
2343 * Call vb2_dqbuf to get buffer back.
2345 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2346 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2349 fileio->dq_count += 1;
2351 fileio->cur_index = index;
2352 buf = &fileio->bufs[index];
2356 * Get number of bytes filled by the driver
2360 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2361 : vb2_plane_size(q->bufs[index], 0);
2362 /* Compensate for data_offset on read in the multiplanar case. */
2363 if (is_multiplanar && read &&
2364 b->planes[0].data_offset < buf->size) {
2365 buf->pos = b->planes[0].data_offset;
2366 buf->size -= buf->pos;
2369 buf = &fileio->bufs[index];
2373 * Limit count on last few bytes of the buffer.
2375 if (buf->pos + count > buf->size) {
2376 count = buf->size - buf->pos;
2377 dprintk(5, "reducing read count: %zd\n", count);
2381 * Transfer data to userspace.
2383 dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2384 count, index, buf->pos);
2386 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2388 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2390 dprintk(3, "error copying data\n");
2401 * Queue next buffer if required.
2403 if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2404 struct vb2_buffer *b = q->bufs[index];
2407 * Check if this is the last buffer to read.
2409 if (read && fileio->read_once && fileio->dq_count == 1) {
2410 dprintk(3, "read limit reached\n");
2411 return __vb2_cleanup_fileio(q);
2415 * Call vb2_qbuf and give buffer to the driver.
2417 b->planes[0].bytesused = buf->pos;
2420 b->timestamp = ktime_get_ns();
2421 ret = vb2_core_qbuf(q, index, NULL);
2422 dprintk(5, "vb2_dbuf result: %d\n", ret);
2427 * Buffer has been queued, update the status
2431 buf->size = vb2_plane_size(q->bufs[index], 0);
2432 fileio->q_count += 1;
2434 * If we are queuing up buffers for the first time, then
2435 * increase initial_index by one.
2437 if (fileio->initial_index < q->num_buffers)
2438 fileio->initial_index++;
2440 * The next buffer to use is either a buffer that's going to be
2441 * queued for the first time (initial_index < q->num_buffers)
2442 * or it is equal to q->num_buffers, meaning that the next
2443 * time we need to dequeue a buffer since we've now queued up
2444 * all the 'first time' buffers.
2446 fileio->cur_index = fileio->initial_index;
2450 * Return proper number of bytes processed.
2457 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2458 loff_t *ppos, int nonblocking)
2460 return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2462 EXPORT_SYMBOL_GPL(vb2_read);
2464 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2465 loff_t *ppos, int nonblocking)
2467 return __vb2_perform_fileio(q, (char __user *) data, count,
2468 ppos, nonblocking, 0);
2470 EXPORT_SYMBOL_GPL(vb2_write);
2472 struct vb2_threadio_data {
2473 struct task_struct *thread;
2479 static int vb2_thread(void *data)
2481 struct vb2_queue *q = data;
2482 struct vb2_threadio_data *threadio = q->threadio;
2483 bool copy_timestamp = false;
2484 unsigned prequeue = 0;
2489 prequeue = q->num_buffers;
2490 copy_timestamp = q->copy_timestamp;
2496 struct vb2_buffer *vb;
2499 * Call vb2_dqbuf to get buffer back.
2502 vb = q->bufs[index++];
2505 call_void_qop(q, wait_finish, q);
2506 if (!threadio->stop)
2507 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2508 call_void_qop(q, wait_prepare, q);
2509 dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2511 vb = q->bufs[index];
2513 if (ret || threadio->stop)
2517 if (vb->state != VB2_BUF_STATE_ERROR)
2518 if (threadio->fnc(vb, threadio->priv))
2520 call_void_qop(q, wait_finish, q);
2522 vb->timestamp = ktime_get_ns();;
2523 if (!threadio->stop)
2524 ret = vb2_core_qbuf(q, vb->index, NULL);
2525 call_void_qop(q, wait_prepare, q);
2526 if (ret || threadio->stop)
2530 /* Hmm, linux becomes *very* unhappy without this ... */
2531 while (!kthread_should_stop()) {
2532 set_current_state(TASK_INTERRUPTIBLE);
2539 * This function should not be used for anything else but the videobuf2-dvb
2540 * support. If you think you have another good use-case for this, then please
2541 * contact the linux-media mailinglist first.
2543 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2544 const char *thread_name)
2546 struct vb2_threadio_data *threadio;
2553 if (WARN_ON(q->fileio))
2556 threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2557 if (threadio == NULL)
2559 threadio->fnc = fnc;
2560 threadio->priv = priv;
2562 ret = __vb2_init_fileio(q, !q->is_output);
2563 dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2566 q->threadio = threadio;
2567 threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2568 if (IS_ERR(threadio->thread)) {
2569 ret = PTR_ERR(threadio->thread);
2570 threadio->thread = NULL;
2576 __vb2_cleanup_fileio(q);
2581 EXPORT_SYMBOL_GPL(vb2_thread_start);
2583 int vb2_thread_stop(struct vb2_queue *q)
2585 struct vb2_threadio_data *threadio = q->threadio;
2588 if (threadio == NULL)
2590 threadio->stop = true;
2591 /* Wake up all pending sleeps in the thread */
2593 err = kthread_stop(threadio->thread);
2594 __vb2_cleanup_fileio(q);
2595 threadio->thread = NULL;
2600 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2602 MODULE_DESCRIPTION("Media buffer core framework");
2603 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2604 MODULE_LICENSE("GPL");