x86/mm/pat: Don't report PAT on CPUs that don't support it
[linux/fpc-iii.git] / drivers / media / v4l2-core / videobuf2-core.c
blob28e1bf64923e7f23d2b4b88c615aaa9f082da948
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 #include <linux/err.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/mm.h>
21 #include <linux/poll.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
27 #include <media/videobuf2-core.h>
28 #include <media/v4l2-mc.h>
30 #include <trace/events/vb2.h>
32 static int debug;
33 module_param(debug, int, 0644);
35 #define dprintk(level, fmt, arg...) \
36 do { \
37 if (debug >= level) \
38 pr_info("vb2-core: %s: " fmt, __func__, ## arg); \
39 } while (0)
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...) \
57 ({ \
58 struct vb2_queue *_q = (vb)->vb2_queue; \
59 int err; \
61 log_memop(vb, op); \
62 err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0; \
63 if (!err) \
64 (vb)->cnt_mem_ ## op++; \
65 err; \
68 #define call_ptr_memop(vb, op, args...) \
69 ({ \
70 struct vb2_queue *_q = (vb)->vb2_queue; \
71 void *ptr; \
73 log_memop(vb, op); \
74 ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL; \
75 if (!IS_ERR_OR_NULL(ptr)) \
76 (vb)->cnt_mem_ ## op++; \
77 ptr; \
80 #define call_void_memop(vb, op, args...) \
81 ({ \
82 struct vb2_queue *_q = (vb)->vb2_queue; \
84 log_memop(vb, op); \
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...) \
95 ({ \
96 int err; \
98 log_qop(q, op); \
99 err = (q)->ops->op ? (q)->ops->op(args) : 0; \
100 if (!err) \
101 (q)->cnt_ ## op++; \
102 err; \
105 #define call_void_qop(q, op, args...) \
106 ({ \
107 log_qop(q, op); \
108 if ((q)->ops->op) \
109 (q)->ops->op(args); \
110 (q)->cnt_ ## op++; \
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...) \
119 ({ \
120 int err; \
122 log_vb_qop(vb, op); \
123 err = (vb)->vb2_queue->ops->op ? \
124 (vb)->vb2_queue->ops->op(args) : 0; \
125 if (!err) \
126 (vb)->cnt_ ## op++; \
127 err; \
130 #define call_void_vb_qop(vb, op, args...) \
131 ({ \
132 log_vb_qop(vb, op); \
133 if ((vb)->vb2_queue->ops->op) \
134 (vb)->vb2_queue->ops->op(args); \
135 (vb)->cnt_ ## op++; \
138 #else
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...) \
149 do { \
150 if ((vb)->vb2_queue->mem_ops->op) \
151 (vb)->vb2_queue->mem_ops->op(args); \
152 } while (0)
154 #define call_qop(q, op, args...) \
155 ((q)->ops->op ? (q)->ops->op(args) : 0)
157 #define call_void_qop(q, op, args...) \
158 do { \
159 if ((q)->ops->op) \
160 (q)->ops->op(args); \
161 } while (0)
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...) \
167 do { \
168 if ((vb)->vb2_queue->ops->op) \
169 (vb)->vb2_queue->ops->op(args); \
170 } while (0)
172 #endif
174 #define call_bufop(q, op, args...) \
175 ({ \
176 int ret = 0; \
177 if (q && q->buf_ops && q->buf_ops->op) \
178 ret = q->buf_ops->op(args); \
179 ret; \
182 #define call_void_bufop(q, op, args...) \
183 ({ \
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;
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 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)) {
214 if (mem_priv)
215 ret = PTR_ERR(mem_priv);
216 goto free;
219 /* Associate allocator private data with this plane */
220 vb->planes[plane].mem_priv = mem_priv;
223 return 0;
224 free:
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;
231 return ret;
235 * __vb2_buf_mem_free() - free memory of the given buffer
237 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
239 unsigned int plane;
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
250 * a USERPTR buffer
252 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
254 unsigned int plane;
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)
269 if (!p->mem_priv)
270 return;
272 if (p->dbuf_mapped)
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);
277 p->mem_priv = NULL;
278 p->dbuf = NULL;
279 p->dbuf_mapped = 0;
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)
288 unsigned int plane;
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
296 * the buffer.
298 static void __setup_offsets(struct vb2_buffer *vb)
300 struct vb2_queue *q = vb->vb2_queue;
301 unsigned int plane;
302 unsigned long off = 0;
304 if (vb->index) {
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
325 * queue
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;
335 int ret;
337 for (buffer = 0; buffer < num_buffers; ++buffer) {
338 /* Allocate videobuf buffer structures */
339 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
340 if (!vb) {
341 dprintk(1, "memory alloc for buffer struct failed\n");
342 break;
345 vb->state = VB2_BUF_STATE_DEQUEUED;
346 vb->vb2_queue = q;
347 vb->num_planes = num_planes;
348 vb->index = q->num_buffers + buffer;
349 vb->type = q->type;
350 vb->memory = memory;
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);
360 if (ret) {
361 dprintk(1, "failed allocating memory for buffer %d\n",
362 buffer);
363 q->bufs[vb->index] = NULL;
364 kfree(vb);
365 break;
367 __setup_offsets(vb);
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);
374 if (ret) {
375 dprintk(1, "buffer %d %p initialization failed\n",
376 buffer, vb);
377 __vb2_buf_mem_free(vb);
378 q->bufs[vb->index] = NULL;
379 kfree(vb);
380 break;
385 dprintk(1, "allocated %d buffers, %d plane(s) each\n",
386 buffer, num_planes);
388 return buffer;
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)
396 unsigned int buffer;
397 struct vb2_buffer *vb;
399 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
400 ++buffer) {
401 vb = q->bufs[buffer];
402 if (!vb)
403 continue;
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);
410 else
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)
422 unsigned int buffer;
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;
433 ++buffer) {
434 if (q->bufs[buffer] == NULL)
435 continue;
436 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
437 dprintk(1, "preparing buffers, cannot free\n");
438 return -EAGAIN;
442 /* Call driver-provided cleanup function for each buffer, if provided */
443 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
444 ++buffer) {
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,
501 vb->cnt_mem_mmap);
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,
510 vb->cnt_mem_vaddr,
511 vb->cnt_mem_cookie);
514 #endif
516 /* Free videobuf buffers */
517 for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
518 ++buffer) {
519 kfree(q->bufs[buffer]);
520 q->bufs[buffer] = NULL;
523 q->num_buffers -= buffers;
524 if (!q->num_buffers) {
525 q->memory = 0;
526 INIT_LIST_HEAD(&q->queued_list);
528 return 0;
531 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
533 unsigned int plane;
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)
543 return true;
545 return false;
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)
555 unsigned int buffer;
556 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
557 if (vb2_buffer_in_use(q, q->bufs[buffer]))
558 return true;
560 return false;
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)
577 return -EINVAL;
579 return 0;
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)
590 return -EINVAL;
592 return 0;
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)
604 return -EINVAL;
606 return 0;
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");
615 return -EINVAL;
618 if (type != q->type) {
619 dprintk(1, "requested type is incorrect\n");
620 return -EINVAL;
624 * Make sure all the required memory ops for given memory type
625 * are available.
627 if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
628 dprintk(1, "MMAP for current setup unsupported\n");
629 return -EINVAL;
632 if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
633 dprintk(1, "USERPTR for current setup unsupported\n");
634 return -EINVAL;
637 if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
638 dprintk(1, "DMABUF for current setup unsupported\n");
639 return -EINVAL;
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");
649 return -EBUSY;
651 return 0;
653 EXPORT_SYMBOL(vb2_verify_memory_type);
655 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
656 unsigned int *count)
658 unsigned int num_buffers, allocated_buffers, num_planes = 0;
659 unsigned plane_sizes[VB2_MAX_PLANES] = { };
660 int ret;
662 if (q->streaming) {
663 dprintk(1, "streaming active\n");
664 return -EBUSY;
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");
676 return -EBUSY;
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);
687 if (ret)
688 return ret;
691 * In case of REQBUFS(0) return immediately without calling
692 * driver's queue_setup() callback and allocating resources.
694 if (*count == 0)
695 return 0;
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));
704 q->memory = memory;
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);
712 if (ret)
713 return ret;
715 /* Finally, allocate buffers and video memory */
716 allocated_buffers =
717 __vb2_queue_alloc(q, memory, num_buffers, num_planes, plane_sizes);
718 if (allocated_buffers == 0) {
719 dprintk(1, "memory allocation failed\n");
720 return -ENOMEM;
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)
728 ret = -ENOMEM;
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.
741 num_planes = 0;
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)
747 ret = -ENOMEM;
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;
758 if (ret < 0) {
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);
765 return ret;
767 mutex_unlock(&q->mmap_lock);
770 * Return the number of successfully allocated buffers
771 * to the userspace.
773 *count = allocated_buffers;
774 q->waiting_for_buffers = !q->is_output;
776 return 0;
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] = { };
786 int ret;
788 if (q->num_buffers == VB2_MAX_FRAME) {
789 dprintk(1, "maximum number of buffers already allocated\n");
790 return -ENOBUFS;
793 if (!q->num_buffers) {
794 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
795 q->memory = memory;
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);
812 if (ret)
813 return ret;
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");
820 return -ENOMEM;
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)
837 ret = -ENOMEM;
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;
848 if (ret < 0) {
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);
855 return -ENOMEM;
857 mutex_unlock(&q->mmap_lock);
860 * Return the number of successfully allocated buffers
861 * to the userspace.
863 *count = allocated_buffers;
865 return 0;
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)
872 return NULL;
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)
882 return NULL;
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;
891 unsigned long flags;
892 unsigned int plane;
894 if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
895 return;
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.
908 vb->cnt_buf_done++;
909 #endif
910 dprintk(4, "done processing on buffer %d, state: %d\n",
911 vb->index, state);
913 /* sync buffers */
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;
921 } else {
922 /* Add the buffer to the done buffers list */
923 list_add_tail(&vb->done_entry, &q->done_list);
924 vb->state = state;
926 atomic_dec(&q->owned_by_drv_count);
927 spin_unlock_irqrestore(&q->done_lock, flags);
929 trace_vb2_buf_done(q, vb);
931 switch (state) {
932 case VB2_BUF_STATE_QUEUED:
933 return;
934 case VB2_BUF_STATE_REQUEUEING:
935 if (q->start_streaming_called)
936 __enqueue_in_driver(vb);
937 return;
938 default:
939 /* Inform any processes that may be waiting for buffers */
940 wake_up(&q->done_wq);
941 break;
944 EXPORT_SYMBOL_GPL(vb2_buffer_done);
946 void vb2_discard_done(struct vb2_queue *q)
948 struct vb2_buffer *vb;
949 unsigned long flags;
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)
963 int ret = 0;
965 if (pb)
966 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
967 vb, pb, vb->planes);
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;
978 void *mem_priv;
979 unsigned int plane;
980 int ret = 0;
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 */
987 if (pb)
988 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
989 vb, pb, planes);
990 if (ret)
991 return ret;
993 for (plane = 0; plane < vb->num_planes; ++plane) {
994 /* Skip the plane if already verified */
995 if (vb->planes[plane].m.userptr &&
996 vb->planes[plane].m.userptr == planes[plane].m.userptr
997 && vb->planes[plane].length == planes[plane].length)
998 continue;
1000 dprintk(3, "userspace address for plane %d changed, reacquiring memory\n",
1001 plane);
1003 /* Check if the provided plane buffer is large enough */
1004 if (planes[plane].length < vb->planes[plane].min_length) {
1005 dprintk(1, "provided buffer size %u is less than setup size %u for plane %d\n",
1006 planes[plane].length,
1007 vb->planes[plane].min_length,
1008 plane);
1009 ret = -EINVAL;
1010 goto err;
1013 /* Release previously acquired memory if present */
1014 if (vb->planes[plane].mem_priv) {
1015 if (!reacquired) {
1016 reacquired = true;
1017 call_void_vb_qop(vb, buf_cleanup, vb);
1019 call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1022 vb->planes[plane].mem_priv = NULL;
1023 vb->planes[plane].bytesused = 0;
1024 vb->planes[plane].length = 0;
1025 vb->planes[plane].m.userptr = 0;
1026 vb->planes[plane].data_offset = 0;
1028 /* Acquire each plane's memory */
1029 mem_priv = call_ptr_memop(vb, get_userptr,
1030 q->alloc_devs[plane] ? : q->dev,
1031 planes[plane].m.userptr,
1032 planes[plane].length, dma_dir);
1033 if (IS_ERR(mem_priv)) {
1034 dprintk(1, "failed acquiring userspace memory for plane %d\n",
1035 plane);
1036 ret = PTR_ERR(mem_priv);
1037 goto err;
1039 vb->planes[plane].mem_priv = mem_priv;
1043 * Now that everything is in order, copy relevant information
1044 * provided by userspace.
1046 for (plane = 0; plane < vb->num_planes; ++plane) {
1047 vb->planes[plane].bytesused = planes[plane].bytesused;
1048 vb->planes[plane].length = planes[plane].length;
1049 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1050 vb->planes[plane].data_offset = planes[plane].data_offset;
1053 if (reacquired) {
1055 * One or more planes changed, so we must call buf_init to do
1056 * the driver-specific initialization on the newly acquired
1057 * buffer, if provided.
1059 ret = call_vb_qop(vb, buf_init, vb);
1060 if (ret) {
1061 dprintk(1, "buffer initialization failed\n");
1062 goto err;
1066 ret = call_vb_qop(vb, buf_prepare, vb);
1067 if (ret) {
1068 dprintk(1, "buffer preparation failed\n");
1069 call_void_vb_qop(vb, buf_cleanup, vb);
1070 goto err;
1073 return 0;
1074 err:
1075 /* In case of errors, release planes that were already acquired */
1076 for (plane = 0; plane < vb->num_planes; ++plane) {
1077 if (vb->planes[plane].mem_priv)
1078 call_void_memop(vb, put_userptr,
1079 vb->planes[plane].mem_priv);
1080 vb->planes[plane].mem_priv = NULL;
1081 vb->planes[plane].m.userptr = 0;
1082 vb->planes[plane].length = 0;
1085 return ret;
1089 * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1091 static int __qbuf_dmabuf(struct vb2_buffer *vb, const void *pb)
1093 struct vb2_plane planes[VB2_MAX_PLANES];
1094 struct vb2_queue *q = vb->vb2_queue;
1095 void *mem_priv;
1096 unsigned int plane;
1097 int ret = 0;
1098 enum dma_data_direction dma_dir =
1099 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1100 bool reacquired = vb->planes[0].mem_priv == NULL;
1102 memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1103 /* Copy relevant information provided by the userspace */
1104 if (pb)
1105 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1106 vb, pb, planes);
1107 if (ret)
1108 return ret;
1110 for (plane = 0; plane < vb->num_planes; ++plane) {
1111 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1113 if (IS_ERR_OR_NULL(dbuf)) {
1114 dprintk(1, "invalid dmabuf fd for plane %d\n",
1115 plane);
1116 ret = -EINVAL;
1117 goto err;
1120 /* use DMABUF size if length is not provided */
1121 if (planes[plane].length == 0)
1122 planes[plane].length = dbuf->size;
1124 if (planes[plane].length < vb->planes[plane].min_length) {
1125 dprintk(1, "invalid dmabuf length %u for plane %d, minimum length %u\n",
1126 planes[plane].length, plane,
1127 vb->planes[plane].min_length);
1128 dma_buf_put(dbuf);
1129 ret = -EINVAL;
1130 goto err;
1133 /* Skip the plane if already verified */
1134 if (dbuf == vb->planes[plane].dbuf &&
1135 vb->planes[plane].length == planes[plane].length) {
1136 dma_buf_put(dbuf);
1137 continue;
1140 dprintk(1, "buffer for plane %d changed\n", plane);
1142 if (!reacquired) {
1143 reacquired = true;
1144 call_void_vb_qop(vb, buf_cleanup, vb);
1147 /* Release previously acquired memory if present */
1148 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1149 vb->planes[plane].bytesused = 0;
1150 vb->planes[plane].length = 0;
1151 vb->planes[plane].m.fd = 0;
1152 vb->planes[plane].data_offset = 0;
1154 /* Acquire each plane's memory */
1155 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1156 q->alloc_devs[plane] ? : q->dev,
1157 dbuf, planes[plane].length, dma_dir);
1158 if (IS_ERR(mem_priv)) {
1159 dprintk(1, "failed to attach dmabuf\n");
1160 ret = PTR_ERR(mem_priv);
1161 dma_buf_put(dbuf);
1162 goto err;
1165 vb->planes[plane].dbuf = dbuf;
1166 vb->planes[plane].mem_priv = mem_priv;
1170 * This pins the buffer(s) with dma_buf_map_attachment()). It's done
1171 * here instead just before the DMA, while queueing the buffer(s) so
1172 * userspace knows sooner rather than later if the dma-buf map fails.
1174 for (plane = 0; plane < vb->num_planes; ++plane) {
1175 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1176 if (ret) {
1177 dprintk(1, "failed to map dmabuf for plane %d\n",
1178 plane);
1179 goto err;
1181 vb->planes[plane].dbuf_mapped = 1;
1185 * Now that everything is in order, copy relevant information
1186 * provided by userspace.
1188 for (plane = 0; plane < vb->num_planes; ++plane) {
1189 vb->planes[plane].bytesused = planes[plane].bytesused;
1190 vb->planes[plane].length = planes[plane].length;
1191 vb->planes[plane].m.fd = planes[plane].m.fd;
1192 vb->planes[plane].data_offset = planes[plane].data_offset;
1195 if (reacquired) {
1197 * Call driver-specific initialization on the newly acquired buffer,
1198 * if provided.
1200 ret = call_vb_qop(vb, buf_init, vb);
1201 if (ret) {
1202 dprintk(1, "buffer initialization failed\n");
1203 goto err;
1207 ret = call_vb_qop(vb, buf_prepare, vb);
1208 if (ret) {
1209 dprintk(1, "buffer preparation failed\n");
1210 call_void_vb_qop(vb, buf_cleanup, vb);
1211 goto err;
1214 return 0;
1215 err:
1216 /* In case of errors, release planes that were already acquired */
1217 __vb2_buf_dmabuf_put(vb);
1219 return ret;
1223 * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1225 static void __enqueue_in_driver(struct vb2_buffer *vb)
1227 struct vb2_queue *q = vb->vb2_queue;
1228 unsigned int plane;
1230 vb->state = VB2_BUF_STATE_ACTIVE;
1231 atomic_inc(&q->owned_by_drv_count);
1233 trace_vb2_buf_queue(q, vb);
1235 /* sync buffers */
1236 for (plane = 0; plane < vb->num_planes; ++plane)
1237 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1239 call_void_vb_qop(vb, buf_queue, vb);
1242 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1244 struct vb2_queue *q = vb->vb2_queue;
1245 int ret;
1247 if (q->error) {
1248 dprintk(1, "fatal error occurred on queue\n");
1249 return -EIO;
1252 vb->state = VB2_BUF_STATE_PREPARING;
1254 switch (q->memory) {
1255 case VB2_MEMORY_MMAP:
1256 ret = __qbuf_mmap(vb, pb);
1257 break;
1258 case VB2_MEMORY_USERPTR:
1259 ret = __qbuf_userptr(vb, pb);
1260 break;
1261 case VB2_MEMORY_DMABUF:
1262 ret = __qbuf_dmabuf(vb, pb);
1263 break;
1264 default:
1265 WARN(1, "Invalid queue type\n");
1266 ret = -EINVAL;
1269 if (ret)
1270 dprintk(1, "buffer preparation failed: %d\n", ret);
1271 vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1273 return ret;
1276 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1278 struct vb2_buffer *vb;
1279 int ret;
1281 vb = q->bufs[index];
1282 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1283 dprintk(1, "invalid buffer state %d\n",
1284 vb->state);
1285 return -EINVAL;
1288 ret = __buf_prepare(vb, pb);
1289 if (ret)
1290 return ret;
1292 /* Fill buffer information for the userspace */
1293 call_void_bufop(q, fill_user_buffer, vb, pb);
1295 dprintk(1, "prepare of buffer %d succeeded\n", vb->index);
1297 return ret;
1299 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1302 * vb2_start_streaming() - Attempt to start streaming.
1303 * @q: videobuf2 queue
1305 * Attempt to start streaming. When this function is called there must be
1306 * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1307 * number of buffers required for the DMA engine to function). If the
1308 * @start_streaming op fails it is supposed to return all the driver-owned
1309 * buffers back to vb2 in state QUEUED. Check if that happened and if
1310 * not warn and reclaim them forcefully.
1312 static int vb2_start_streaming(struct vb2_queue *q)
1314 struct vb2_buffer *vb;
1315 int ret;
1318 * If any buffers were queued before streamon,
1319 * we can now pass them to driver for processing.
1321 list_for_each_entry(vb, &q->queued_list, queued_entry)
1322 __enqueue_in_driver(vb);
1324 /* Tell the driver to start streaming */
1325 q->start_streaming_called = 1;
1326 ret = call_qop(q, start_streaming, q,
1327 atomic_read(&q->owned_by_drv_count));
1328 if (!ret)
1329 return 0;
1331 q->start_streaming_called = 0;
1333 dprintk(1, "driver refused to start streaming\n");
1335 * If you see this warning, then the driver isn't cleaning up properly
1336 * after a failed start_streaming(). See the start_streaming()
1337 * documentation in videobuf2-core.h for more information how buffers
1338 * should be returned to vb2 in start_streaming().
1340 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1341 unsigned i;
1344 * Forcefully reclaim buffers if the driver did not
1345 * correctly return them to vb2.
1347 for (i = 0; i < q->num_buffers; ++i) {
1348 vb = q->bufs[i];
1349 if (vb->state == VB2_BUF_STATE_ACTIVE)
1350 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1352 /* Must be zero now */
1353 WARN_ON(atomic_read(&q->owned_by_drv_count));
1356 * If done_list is not empty, then start_streaming() didn't call
1357 * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1358 * STATE_DONE.
1360 WARN_ON(!list_empty(&q->done_list));
1361 return ret;
1364 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1366 struct vb2_buffer *vb;
1367 int ret;
1369 vb = q->bufs[index];
1371 switch (vb->state) {
1372 case VB2_BUF_STATE_DEQUEUED:
1373 ret = __buf_prepare(vb, pb);
1374 if (ret)
1375 return ret;
1376 break;
1377 case VB2_BUF_STATE_PREPARED:
1378 break;
1379 case VB2_BUF_STATE_PREPARING:
1380 dprintk(1, "buffer still being prepared\n");
1381 return -EINVAL;
1382 default:
1383 dprintk(1, "invalid buffer state %d\n", vb->state);
1384 return -EINVAL;
1388 * Add to the queued buffers list, a buffer will stay on it until
1389 * dequeued in dqbuf.
1391 list_add_tail(&vb->queued_entry, &q->queued_list);
1392 q->queued_count++;
1393 q->waiting_for_buffers = false;
1394 vb->state = VB2_BUF_STATE_QUEUED;
1396 if (pb)
1397 call_void_bufop(q, copy_timestamp, vb, pb);
1399 trace_vb2_qbuf(q, vb);
1402 * If already streaming, give the buffer to driver for processing.
1403 * If not, the buffer will be given to driver on next streamon.
1405 if (q->start_streaming_called)
1406 __enqueue_in_driver(vb);
1408 /* Fill buffer information for the userspace */
1409 if (pb)
1410 call_void_bufop(q, fill_user_buffer, vb, pb);
1413 * If streamon has been called, and we haven't yet called
1414 * start_streaming() since not enough buffers were queued, and
1415 * we now have reached the minimum number of queued buffers,
1416 * then we can finally call start_streaming().
1418 if (q->streaming && !q->start_streaming_called &&
1419 q->queued_count >= q->min_buffers_needed) {
1420 ret = vb2_start_streaming(q);
1421 if (ret)
1422 return ret;
1425 dprintk(1, "qbuf of buffer %d succeeded\n", vb->index);
1426 return 0;
1428 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1431 * __vb2_wait_for_done_vb() - wait for a buffer to become available
1432 * for dequeuing
1434 * Will sleep if required for nonblocking == false.
1436 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1439 * All operations on vb_done_list are performed under done_lock
1440 * spinlock protection. However, buffers may be removed from
1441 * it and returned to userspace only while holding both driver's
1442 * lock and the done_lock spinlock. Thus we can be sure that as
1443 * long as we hold the driver's lock, the list will remain not
1444 * empty if list_empty() check succeeds.
1447 for (;;) {
1448 int ret;
1450 if (!q->streaming) {
1451 dprintk(1, "streaming off, will not wait for buffers\n");
1452 return -EINVAL;
1455 if (q->error) {
1456 dprintk(1, "Queue in error state, will not wait for buffers\n");
1457 return -EIO;
1460 if (q->last_buffer_dequeued) {
1461 dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1462 return -EPIPE;
1465 if (!list_empty(&q->done_list)) {
1467 * Found a buffer that we were waiting for.
1469 break;
1472 if (nonblocking) {
1473 dprintk(1, "nonblocking and no buffers to dequeue, will not wait\n");
1474 return -EAGAIN;
1478 * We are streaming and blocking, wait for another buffer to
1479 * become ready or for streamoff. Driver's lock is released to
1480 * allow streamoff or qbuf to be called while waiting.
1482 call_void_qop(q, wait_prepare, q);
1485 * All locks have been released, it is safe to sleep now.
1487 dprintk(3, "will sleep waiting for buffers\n");
1488 ret = wait_event_interruptible(q->done_wq,
1489 !list_empty(&q->done_list) || !q->streaming ||
1490 q->error);
1493 * We need to reevaluate both conditions again after reacquiring
1494 * the locks or return an error if one occurred.
1496 call_void_qop(q, wait_finish, q);
1497 if (ret) {
1498 dprintk(1, "sleep was interrupted\n");
1499 return ret;
1502 return 0;
1506 * __vb2_get_done_vb() - get a buffer ready for dequeuing
1508 * Will sleep if required for nonblocking == false.
1510 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1511 void *pb, int nonblocking)
1513 unsigned long flags;
1514 int ret = 0;
1517 * Wait for at least one buffer to become available on the done_list.
1519 ret = __vb2_wait_for_done_vb(q, nonblocking);
1520 if (ret)
1521 return ret;
1524 * Driver's lock has been held since we last verified that done_list
1525 * is not empty, so no need for another list_empty(done_list) check.
1527 spin_lock_irqsave(&q->done_lock, flags);
1528 *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1530 * Only remove the buffer from done_list if all planes can be
1531 * handled. Some cases such as V4L2 file I/O and DVB have pb
1532 * == NULL; skip the check then as there's nothing to verify.
1534 if (pb)
1535 ret = call_bufop(q, verify_planes_array, *vb, pb);
1536 if (!ret)
1537 list_del(&(*vb)->done_entry);
1538 spin_unlock_irqrestore(&q->done_lock, flags);
1540 return ret;
1543 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1545 if (!q->streaming) {
1546 dprintk(1, "streaming off, will not wait for buffers\n");
1547 return -EINVAL;
1550 if (q->start_streaming_called)
1551 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1552 return 0;
1554 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1557 * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1559 static void __vb2_dqbuf(struct vb2_buffer *vb)
1561 struct vb2_queue *q = vb->vb2_queue;
1562 unsigned int i;
1564 /* nothing to do if the buffer is already dequeued */
1565 if (vb->state == VB2_BUF_STATE_DEQUEUED)
1566 return;
1568 vb->state = VB2_BUF_STATE_DEQUEUED;
1570 /* unmap DMABUF buffer */
1571 if (q->memory == VB2_MEMORY_DMABUF)
1572 for (i = 0; i < vb->num_planes; ++i) {
1573 if (!vb->planes[i].dbuf_mapped)
1574 continue;
1575 call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1576 vb->planes[i].dbuf_mapped = 0;
1580 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1581 bool nonblocking)
1583 struct vb2_buffer *vb = NULL;
1584 int ret;
1586 ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1587 if (ret < 0)
1588 return ret;
1590 switch (vb->state) {
1591 case VB2_BUF_STATE_DONE:
1592 dprintk(3, "returning done buffer\n");
1593 break;
1594 case VB2_BUF_STATE_ERROR:
1595 dprintk(3, "returning done buffer with errors\n");
1596 break;
1597 default:
1598 dprintk(1, "invalid buffer state\n");
1599 return -EINVAL;
1602 call_void_vb_qop(vb, buf_finish, vb);
1604 if (pindex)
1605 *pindex = vb->index;
1607 /* Fill buffer information for the userspace */
1608 if (pb)
1609 call_void_bufop(q, fill_user_buffer, vb, pb);
1611 /* Remove from videobuf queue */
1612 list_del(&vb->queued_entry);
1613 q->queued_count--;
1615 trace_vb2_dqbuf(q, vb);
1617 /* go back to dequeued state */
1618 __vb2_dqbuf(vb);
1620 dprintk(1, "dqbuf of buffer %d, with state %d\n",
1621 vb->index, vb->state);
1623 return 0;
1626 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1629 * __vb2_queue_cancel() - cancel and stop (pause) streaming
1631 * Removes all queued buffers from driver's queue and all buffers queued by
1632 * userspace from videobuf's queue. Returns to state after reqbufs.
1634 static void __vb2_queue_cancel(struct vb2_queue *q)
1636 unsigned int i;
1639 * Tell driver to stop all transactions and release all queued
1640 * buffers.
1642 if (q->start_streaming_called)
1643 call_void_qop(q, stop_streaming, q);
1646 * If you see this warning, then the driver isn't cleaning up properly
1647 * in stop_streaming(). See the stop_streaming() documentation in
1648 * videobuf2-core.h for more information how buffers should be returned
1649 * to vb2 in stop_streaming().
1651 if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1652 for (i = 0; i < q->num_buffers; ++i)
1653 if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
1654 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1655 /* Must be zero now */
1656 WARN_ON(atomic_read(&q->owned_by_drv_count));
1659 q->streaming = 0;
1660 q->start_streaming_called = 0;
1661 q->queued_count = 0;
1662 q->error = 0;
1665 * Remove all buffers from videobuf's list...
1667 INIT_LIST_HEAD(&q->queued_list);
1669 * ...and done list; userspace will not receive any buffers it
1670 * has not already dequeued before initiating cancel.
1672 INIT_LIST_HEAD(&q->done_list);
1673 atomic_set(&q->owned_by_drv_count, 0);
1674 wake_up_all(&q->done_wq);
1677 * Reinitialize all buffers for next use.
1678 * Make sure to call buf_finish for any queued buffers. Normally
1679 * that's done in dqbuf, but that's not going to happen when we
1680 * cancel the whole queue. Note: this code belongs here, not in
1681 * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1682 * call to __fill_user_buffer() after buf_finish(). That order can't
1683 * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1685 for (i = 0; i < q->num_buffers; ++i) {
1686 struct vb2_buffer *vb = q->bufs[i];
1688 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1689 vb->state = VB2_BUF_STATE_PREPARED;
1690 call_void_vb_qop(vb, buf_finish, vb);
1692 __vb2_dqbuf(vb);
1696 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1698 int ret;
1700 if (type != q->type) {
1701 dprintk(1, "invalid stream type\n");
1702 return -EINVAL;
1705 if (q->streaming) {
1706 dprintk(3, "already streaming\n");
1707 return 0;
1710 if (!q->num_buffers) {
1711 dprintk(1, "no buffers have been allocated\n");
1712 return -EINVAL;
1715 if (q->num_buffers < q->min_buffers_needed) {
1716 dprintk(1, "need at least %u allocated buffers\n",
1717 q->min_buffers_needed);
1718 return -EINVAL;
1722 * Tell driver to start streaming provided sufficient buffers
1723 * are available.
1725 if (q->queued_count >= q->min_buffers_needed) {
1726 ret = v4l_vb2q_enable_media_source(q);
1727 if (ret)
1728 return ret;
1729 ret = vb2_start_streaming(q);
1730 if (ret) {
1731 __vb2_queue_cancel(q);
1732 return ret;
1736 q->streaming = 1;
1738 dprintk(3, "successful\n");
1739 return 0;
1741 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1743 void vb2_queue_error(struct vb2_queue *q)
1745 q->error = 1;
1747 wake_up_all(&q->done_wq);
1749 EXPORT_SYMBOL_GPL(vb2_queue_error);
1751 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1753 if (type != q->type) {
1754 dprintk(1, "invalid stream type\n");
1755 return -EINVAL;
1759 * Cancel will pause streaming and remove all buffers from the driver
1760 * and videobuf, effectively returning control over them to userspace.
1762 * Note that we do this even if q->streaming == 0: if you prepare or
1763 * queue buffers, and then call streamoff without ever having called
1764 * streamon, you would still expect those buffers to be returned to
1765 * their normal dequeued state.
1767 __vb2_queue_cancel(q);
1768 q->waiting_for_buffers = !q->is_output;
1769 q->last_buffer_dequeued = false;
1771 dprintk(3, "successful\n");
1772 return 0;
1774 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1777 * __find_plane_by_offset() - find plane associated with the given offset off
1779 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1780 unsigned int *_buffer, unsigned int *_plane)
1782 struct vb2_buffer *vb;
1783 unsigned int buffer, plane;
1786 * Go over all buffers and their planes, comparing the given offset
1787 * with an offset assigned to each plane. If a match is found,
1788 * return its buffer and plane numbers.
1790 for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1791 vb = q->bufs[buffer];
1793 for (plane = 0; plane < vb->num_planes; ++plane) {
1794 if (vb->planes[plane].m.offset == off) {
1795 *_buffer = buffer;
1796 *_plane = plane;
1797 return 0;
1802 return -EINVAL;
1805 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1806 unsigned int index, unsigned int plane, unsigned int flags)
1808 struct vb2_buffer *vb = NULL;
1809 struct vb2_plane *vb_plane;
1810 int ret;
1811 struct dma_buf *dbuf;
1813 if (q->memory != VB2_MEMORY_MMAP) {
1814 dprintk(1, "queue is not currently set up for mmap\n");
1815 return -EINVAL;
1818 if (!q->mem_ops->get_dmabuf) {
1819 dprintk(1, "queue does not support DMA buffer exporting\n");
1820 return -EINVAL;
1823 if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1824 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1825 return -EINVAL;
1828 if (type != q->type) {
1829 dprintk(1, "invalid buffer type\n");
1830 return -EINVAL;
1833 if (index >= q->num_buffers) {
1834 dprintk(1, "buffer index out of range\n");
1835 return -EINVAL;
1838 vb = q->bufs[index];
1840 if (plane >= vb->num_planes) {
1841 dprintk(1, "buffer plane out of range\n");
1842 return -EINVAL;
1845 if (vb2_fileio_is_active(q)) {
1846 dprintk(1, "expbuf: file io in progress\n");
1847 return -EBUSY;
1850 vb_plane = &vb->planes[plane];
1852 dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1853 flags & O_ACCMODE);
1854 if (IS_ERR_OR_NULL(dbuf)) {
1855 dprintk(1, "failed to export buffer %d, plane %d\n",
1856 index, plane);
1857 return -EINVAL;
1860 ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1861 if (ret < 0) {
1862 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1863 index, plane, ret);
1864 dma_buf_put(dbuf);
1865 return ret;
1868 dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1869 index, plane, ret);
1870 *fd = ret;
1872 return 0;
1874 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1876 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1878 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1879 struct vb2_buffer *vb;
1880 unsigned int buffer = 0, plane = 0;
1881 int ret;
1882 unsigned long length;
1884 if (q->memory != VB2_MEMORY_MMAP) {
1885 dprintk(1, "queue is not currently set up for mmap\n");
1886 return -EINVAL;
1890 * Check memory area access mode.
1892 if (!(vma->vm_flags & VM_SHARED)) {
1893 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1894 return -EINVAL;
1896 if (q->is_output) {
1897 if (!(vma->vm_flags & VM_WRITE)) {
1898 dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1899 return -EINVAL;
1901 } else {
1902 if (!(vma->vm_flags & VM_READ)) {
1903 dprintk(1, "invalid vma flags, VM_READ needed\n");
1904 return -EINVAL;
1907 if (vb2_fileio_is_active(q)) {
1908 dprintk(1, "mmap: file io in progress\n");
1909 return -EBUSY;
1913 * Find the plane corresponding to the offset passed by userspace.
1915 ret = __find_plane_by_offset(q, off, &buffer, &plane);
1916 if (ret)
1917 return ret;
1919 vb = q->bufs[buffer];
1922 * MMAP requires page_aligned buffers.
1923 * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1924 * so, we need to do the same here.
1926 length = PAGE_ALIGN(vb->planes[plane].length);
1927 if (length < (vma->vm_end - vma->vm_start)) {
1928 dprintk(1,
1929 "MMAP invalid, as it would overflow buffer length\n");
1930 return -EINVAL;
1933 mutex_lock(&q->mmap_lock);
1934 ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1935 mutex_unlock(&q->mmap_lock);
1936 if (ret)
1937 return ret;
1939 dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
1940 return 0;
1942 EXPORT_SYMBOL_GPL(vb2_mmap);
1944 #ifndef CONFIG_MMU
1945 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
1946 unsigned long addr,
1947 unsigned long len,
1948 unsigned long pgoff,
1949 unsigned long flags)
1951 unsigned long off = pgoff << PAGE_SHIFT;
1952 struct vb2_buffer *vb;
1953 unsigned int buffer, plane;
1954 void *vaddr;
1955 int ret;
1957 if (q->memory != VB2_MEMORY_MMAP) {
1958 dprintk(1, "queue is not currently set up for mmap\n");
1959 return -EINVAL;
1963 * Find the plane corresponding to the offset passed by userspace.
1965 ret = __find_plane_by_offset(q, off, &buffer, &plane);
1966 if (ret)
1967 return ret;
1969 vb = q->bufs[buffer];
1971 vaddr = vb2_plane_vaddr(vb, plane);
1972 return vaddr ? (unsigned long)vaddr : -EINVAL;
1974 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
1975 #endif
1977 int vb2_core_queue_init(struct vb2_queue *q)
1980 * Sanity check
1982 if (WARN_ON(!q) ||
1983 WARN_ON(!q->ops) ||
1984 WARN_ON(!q->mem_ops) ||
1985 WARN_ON(!q->type) ||
1986 WARN_ON(!q->io_modes) ||
1987 WARN_ON(!q->ops->queue_setup) ||
1988 WARN_ON(!q->ops->buf_queue))
1989 return -EINVAL;
1991 INIT_LIST_HEAD(&q->queued_list);
1992 INIT_LIST_HEAD(&q->done_list);
1993 spin_lock_init(&q->done_lock);
1994 mutex_init(&q->mmap_lock);
1995 init_waitqueue_head(&q->done_wq);
1997 if (q->buf_struct_size == 0)
1998 q->buf_struct_size = sizeof(struct vb2_buffer);
2000 return 0;
2002 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2004 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2005 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2006 void vb2_core_queue_release(struct vb2_queue *q)
2008 __vb2_cleanup_fileio(q);
2009 __vb2_queue_cancel(q);
2010 mutex_lock(&q->mmap_lock);
2011 __vb2_queue_free(q, q->num_buffers);
2012 mutex_unlock(&q->mmap_lock);
2014 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2016 unsigned int vb2_core_poll(struct vb2_queue *q, struct file *file,
2017 poll_table *wait)
2019 unsigned long req_events = poll_requested_events(wait);
2020 struct vb2_buffer *vb = NULL;
2021 unsigned long flags;
2023 if (!q->is_output && !(req_events & (POLLIN | POLLRDNORM)))
2024 return 0;
2025 if (q->is_output && !(req_events & (POLLOUT | POLLWRNORM)))
2026 return 0;
2029 * Start file I/O emulator only if streaming API has not been used yet.
2031 if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2032 if (!q->is_output && (q->io_modes & VB2_READ) &&
2033 (req_events & (POLLIN | POLLRDNORM))) {
2034 if (__vb2_init_fileio(q, 1))
2035 return POLLERR;
2037 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2038 (req_events & (POLLOUT | POLLWRNORM))) {
2039 if (__vb2_init_fileio(q, 0))
2040 return POLLERR;
2042 * Write to OUTPUT queue can be done immediately.
2044 return POLLOUT | POLLWRNORM;
2049 * There is nothing to wait for if the queue isn't streaming, or if the
2050 * error flag is set.
2052 if (!vb2_is_streaming(q) || q->error)
2053 return POLLERR;
2056 * If this quirk is set and QBUF hasn't been called yet then
2057 * return POLLERR as well. This only affects capture queues, output
2058 * queues will always initialize waiting_for_buffers to false.
2059 * This quirk is set by V4L2 for backwards compatibility reasons.
2061 if (q->quirk_poll_must_check_waiting_for_buffers &&
2062 q->waiting_for_buffers && (req_events & (POLLIN | POLLRDNORM)))
2063 return POLLERR;
2066 * For output streams you can call write() as long as there are fewer
2067 * buffers queued than there are buffers available.
2069 if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2070 return POLLOUT | POLLWRNORM;
2072 if (list_empty(&q->done_list)) {
2074 * If the last buffer was dequeued from a capture queue,
2075 * return immediately. DQBUF will return -EPIPE.
2077 if (q->last_buffer_dequeued)
2078 return POLLIN | POLLRDNORM;
2080 poll_wait(file, &q->done_wq, wait);
2084 * Take first buffer available for dequeuing.
2086 spin_lock_irqsave(&q->done_lock, flags);
2087 if (!list_empty(&q->done_list))
2088 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2089 done_entry);
2090 spin_unlock_irqrestore(&q->done_lock, flags);
2092 if (vb && (vb->state == VB2_BUF_STATE_DONE
2093 || vb->state == VB2_BUF_STATE_ERROR)) {
2094 return (q->is_output) ?
2095 POLLOUT | POLLWRNORM :
2096 POLLIN | POLLRDNORM;
2098 return 0;
2100 EXPORT_SYMBOL_GPL(vb2_core_poll);
2103 * struct vb2_fileio_buf - buffer context used by file io emulator
2105 * vb2 provides a compatibility layer and emulator of file io (read and
2106 * write) calls on top of streaming API. This structure is used for
2107 * tracking context related to the buffers.
2109 struct vb2_fileio_buf {
2110 void *vaddr;
2111 unsigned int size;
2112 unsigned int pos;
2113 unsigned int queued:1;
2117 * struct vb2_fileio_data - queue context used by file io emulator
2119 * @cur_index: the index of the buffer currently being read from or
2120 * written to. If equal to q->num_buffers then a new buffer
2121 * must be dequeued.
2122 * @initial_index: in the read() case all buffers are queued up immediately
2123 * in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2124 * buffers. However, in the write() case no buffers are initially
2125 * queued, instead whenever a buffer is full it is queued up by
2126 * __vb2_perform_fileio(). Only once all available buffers have
2127 * been queued up will __vb2_perform_fileio() start to dequeue
2128 * buffers. This means that initially __vb2_perform_fileio()
2129 * needs to know what buffer index to use when it is queuing up
2130 * the buffers for the first time. That initial index is stored
2131 * in this field. Once it is equal to q->num_buffers all
2132 * available buffers have been queued and __vb2_perform_fileio()
2133 * should start the normal dequeue/queue cycle.
2135 * vb2 provides a compatibility layer and emulator of file io (read and
2136 * write) calls on top of streaming API. For proper operation it required
2137 * this structure to save the driver state between each call of the read
2138 * or write function.
2140 struct vb2_fileio_data {
2141 unsigned int count;
2142 unsigned int type;
2143 unsigned int memory;
2144 struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2145 unsigned int cur_index;
2146 unsigned int initial_index;
2147 unsigned int q_count;
2148 unsigned int dq_count;
2149 unsigned read_once:1;
2150 unsigned write_immediately:1;
2154 * __vb2_init_fileio() - initialize file io emulator
2155 * @q: videobuf2 queue
2156 * @read: mode selector (1 means read, 0 means write)
2158 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2160 struct vb2_fileio_data *fileio;
2161 int i, ret;
2162 unsigned int count = 0;
2165 * Sanity check
2167 if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2168 (!read && !(q->io_modes & VB2_WRITE))))
2169 return -EINVAL;
2172 * Check if device supports mapping buffers to kernel virtual space.
2174 if (!q->mem_ops->vaddr)
2175 return -EBUSY;
2178 * Check if streaming api has not been already activated.
2180 if (q->streaming || q->num_buffers > 0)
2181 return -EBUSY;
2184 * Start with count 1, driver can increase it in queue_setup()
2186 count = 1;
2188 dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2189 (read) ? "read" : "write", count, q->fileio_read_once,
2190 q->fileio_write_immediately);
2192 fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2193 if (fileio == NULL)
2194 return -ENOMEM;
2196 fileio->read_once = q->fileio_read_once;
2197 fileio->write_immediately = q->fileio_write_immediately;
2200 * Request buffers and use MMAP type to force driver
2201 * to allocate buffers by itself.
2203 fileio->count = count;
2204 fileio->memory = VB2_MEMORY_MMAP;
2205 fileio->type = q->type;
2206 q->fileio = fileio;
2207 ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2208 if (ret)
2209 goto err_kfree;
2212 * Check if plane_count is correct
2213 * (multiplane buffers are not supported).
2215 if (q->bufs[0]->num_planes != 1) {
2216 ret = -EBUSY;
2217 goto err_reqbufs;
2221 * Get kernel address of each buffer.
2223 for (i = 0; i < q->num_buffers; i++) {
2224 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2225 if (fileio->bufs[i].vaddr == NULL) {
2226 ret = -EINVAL;
2227 goto err_reqbufs;
2229 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2233 * Read mode requires pre queuing of all buffers.
2235 if (read) {
2237 * Queue all buffers.
2239 for (i = 0; i < q->num_buffers; i++) {
2240 ret = vb2_core_qbuf(q, i, NULL);
2241 if (ret)
2242 goto err_reqbufs;
2243 fileio->bufs[i].queued = 1;
2246 * All buffers have been queued, so mark that by setting
2247 * initial_index to q->num_buffers
2249 fileio->initial_index = q->num_buffers;
2250 fileio->cur_index = q->num_buffers;
2254 * Start streaming.
2256 ret = vb2_core_streamon(q, q->type);
2257 if (ret)
2258 goto err_reqbufs;
2260 return ret;
2262 err_reqbufs:
2263 fileio->count = 0;
2264 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2266 err_kfree:
2267 q->fileio = NULL;
2268 kfree(fileio);
2269 return ret;
2273 * __vb2_cleanup_fileio() - free resourced used by file io emulator
2274 * @q: videobuf2 queue
2276 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2278 struct vb2_fileio_data *fileio = q->fileio;
2280 if (fileio) {
2281 vb2_core_streamoff(q, q->type);
2282 q->fileio = NULL;
2283 fileio->count = 0;
2284 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2285 kfree(fileio);
2286 dprintk(3, "file io emulator closed\n");
2288 return 0;
2292 * __vb2_perform_fileio() - perform a single file io (read or write) operation
2293 * @q: videobuf2 queue
2294 * @data: pointed to target userspace buffer
2295 * @count: number of bytes to read or write
2296 * @ppos: file handle position tracking pointer
2297 * @nonblock: mode selector (1 means blocking calls, 0 means nonblocking)
2298 * @read: access mode selector (1 means read, 0 means write)
2300 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2301 loff_t *ppos, int nonblock, int read)
2303 struct vb2_fileio_data *fileio;
2304 struct vb2_fileio_buf *buf;
2305 bool is_multiplanar = q->is_multiplanar;
2307 * When using write() to write data to an output video node the vb2 core
2308 * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2309 * else is able to provide this information with the write() operation.
2311 bool copy_timestamp = !read && q->copy_timestamp;
2312 unsigned index;
2313 int ret;
2315 dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2316 read ? "read" : "write", (long)*ppos, count,
2317 nonblock ? "non" : "");
2319 if (!data)
2320 return -EINVAL;
2323 * Initialize emulator on first call.
2325 if (!vb2_fileio_is_active(q)) {
2326 ret = __vb2_init_fileio(q, read);
2327 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2328 if (ret)
2329 return ret;
2331 fileio = q->fileio;
2334 * Check if we need to dequeue the buffer.
2336 index = fileio->cur_index;
2337 if (index >= q->num_buffers) {
2338 struct vb2_buffer *b;
2341 * Call vb2_dqbuf to get buffer back.
2343 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2344 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2345 if (ret)
2346 return ret;
2347 fileio->dq_count += 1;
2349 fileio->cur_index = index;
2350 buf = &fileio->bufs[index];
2351 b = q->bufs[index];
2354 * Get number of bytes filled by the driver
2356 buf->pos = 0;
2357 buf->queued = 0;
2358 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2359 : vb2_plane_size(q->bufs[index], 0);
2360 /* Compensate for data_offset on read in the multiplanar case. */
2361 if (is_multiplanar && read &&
2362 b->planes[0].data_offset < buf->size) {
2363 buf->pos = b->planes[0].data_offset;
2364 buf->size -= buf->pos;
2366 } else {
2367 buf = &fileio->bufs[index];
2371 * Limit count on last few bytes of the buffer.
2373 if (buf->pos + count > buf->size) {
2374 count = buf->size - buf->pos;
2375 dprintk(5, "reducing read count: %zd\n", count);
2379 * Transfer data to userspace.
2381 dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2382 count, index, buf->pos);
2383 if (read)
2384 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2385 else
2386 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2387 if (ret) {
2388 dprintk(3, "error copying data\n");
2389 return -EFAULT;
2393 * Update counters.
2395 buf->pos += count;
2396 *ppos += count;
2399 * Queue next buffer if required.
2401 if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2402 struct vb2_buffer *b = q->bufs[index];
2405 * Check if this is the last buffer to read.
2407 if (read && fileio->read_once && fileio->dq_count == 1) {
2408 dprintk(3, "read limit reached\n");
2409 return __vb2_cleanup_fileio(q);
2413 * Call vb2_qbuf and give buffer to the driver.
2415 b->planes[0].bytesused = buf->pos;
2417 if (copy_timestamp)
2418 b->timestamp = ktime_get_ns();
2419 ret = vb2_core_qbuf(q, index, NULL);
2420 dprintk(5, "vb2_dbuf result: %d\n", ret);
2421 if (ret)
2422 return ret;
2425 * Buffer has been queued, update the status
2427 buf->pos = 0;
2428 buf->queued = 1;
2429 buf->size = vb2_plane_size(q->bufs[index], 0);
2430 fileio->q_count += 1;
2432 * If we are queuing up buffers for the first time, then
2433 * increase initial_index by one.
2435 if (fileio->initial_index < q->num_buffers)
2436 fileio->initial_index++;
2438 * The next buffer to use is either a buffer that's going to be
2439 * queued for the first time (initial_index < q->num_buffers)
2440 * or it is equal to q->num_buffers, meaning that the next
2441 * time we need to dequeue a buffer since we've now queued up
2442 * all the 'first time' buffers.
2444 fileio->cur_index = fileio->initial_index;
2448 * Return proper number of bytes processed.
2450 if (ret == 0)
2451 ret = count;
2452 return ret;
2455 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2456 loff_t *ppos, int nonblocking)
2458 return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2460 EXPORT_SYMBOL_GPL(vb2_read);
2462 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2463 loff_t *ppos, int nonblocking)
2465 return __vb2_perform_fileio(q, (char __user *) data, count,
2466 ppos, nonblocking, 0);
2468 EXPORT_SYMBOL_GPL(vb2_write);
2470 struct vb2_threadio_data {
2471 struct task_struct *thread;
2472 vb2_thread_fnc fnc;
2473 void *priv;
2474 bool stop;
2477 static int vb2_thread(void *data)
2479 struct vb2_queue *q = data;
2480 struct vb2_threadio_data *threadio = q->threadio;
2481 bool copy_timestamp = false;
2482 unsigned prequeue = 0;
2483 unsigned index = 0;
2484 int ret = 0;
2486 if (q->is_output) {
2487 prequeue = q->num_buffers;
2488 copy_timestamp = q->copy_timestamp;
2491 set_freezable();
2493 for (;;) {
2494 struct vb2_buffer *vb;
2497 * Call vb2_dqbuf to get buffer back.
2499 if (prequeue) {
2500 vb = q->bufs[index++];
2501 prequeue--;
2502 } else {
2503 call_void_qop(q, wait_finish, q);
2504 if (!threadio->stop)
2505 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2506 call_void_qop(q, wait_prepare, q);
2507 dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2508 if (!ret)
2509 vb = q->bufs[index];
2511 if (ret || threadio->stop)
2512 break;
2513 try_to_freeze();
2515 if (vb->state != VB2_BUF_STATE_ERROR)
2516 if (threadio->fnc(vb, threadio->priv))
2517 break;
2518 call_void_qop(q, wait_finish, q);
2519 if (copy_timestamp)
2520 vb->timestamp = ktime_get_ns();;
2521 if (!threadio->stop)
2522 ret = vb2_core_qbuf(q, vb->index, NULL);
2523 call_void_qop(q, wait_prepare, q);
2524 if (ret || threadio->stop)
2525 break;
2528 /* Hmm, linux becomes *very* unhappy without this ... */
2529 while (!kthread_should_stop()) {
2530 set_current_state(TASK_INTERRUPTIBLE);
2531 schedule();
2533 return 0;
2537 * This function should not be used for anything else but the videobuf2-dvb
2538 * support. If you think you have another good use-case for this, then please
2539 * contact the linux-media mailinglist first.
2541 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2542 const char *thread_name)
2544 struct vb2_threadio_data *threadio;
2545 int ret = 0;
2547 if (q->threadio)
2548 return -EBUSY;
2549 if (vb2_is_busy(q))
2550 return -EBUSY;
2551 if (WARN_ON(q->fileio))
2552 return -EBUSY;
2554 threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2555 if (threadio == NULL)
2556 return -ENOMEM;
2557 threadio->fnc = fnc;
2558 threadio->priv = priv;
2560 ret = __vb2_init_fileio(q, !q->is_output);
2561 dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2562 if (ret)
2563 goto nomem;
2564 q->threadio = threadio;
2565 threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2566 if (IS_ERR(threadio->thread)) {
2567 ret = PTR_ERR(threadio->thread);
2568 threadio->thread = NULL;
2569 goto nothread;
2571 return 0;
2573 nothread:
2574 __vb2_cleanup_fileio(q);
2575 nomem:
2576 kfree(threadio);
2577 return ret;
2579 EXPORT_SYMBOL_GPL(vb2_thread_start);
2581 int vb2_thread_stop(struct vb2_queue *q)
2583 struct vb2_threadio_data *threadio = q->threadio;
2584 int err;
2586 if (threadio == NULL)
2587 return 0;
2588 threadio->stop = true;
2589 /* Wake up all pending sleeps in the thread */
2590 vb2_queue_error(q);
2591 err = kthread_stop(threadio->thread);
2592 __vb2_cleanup_fileio(q);
2593 threadio->thread = NULL;
2594 kfree(threadio);
2595 q->threadio = NULL;
2596 return err;
2598 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2600 MODULE_DESCRIPTION("Media buffer core framework");
2601 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2602 MODULE_LICENSE("GPL");