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