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