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