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