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