1 /*
2  * videobuf2-core.c - V4L2 driver helper 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  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation.
12  */
13 
14 #include <linux/err.h>
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/mm.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/sched.h>
21 
22 #include <media/videobuf2-core.h>
23 
24 static int debug;
25 module_param(debug, int, 0644);
26 
27 #define dprintk(level, fmt, arg...)					\
28 	do {								\
29 		if (debug >= level)					\
30 			printk(KERN_DEBUG "vb2: " fmt, ## arg);		\
31 	} while (0)
32 
33 #define call_memop(q, plane, op, args...)				\
34 	(((q)->mem_ops->op) ?						\
35 		((q)->mem_ops->op(args)) : 0)
36 
37 #define call_qop(q, op, args...)					\
38 	(((q)->ops->op) ? ((q)->ops->op(args)) : 0)
39 
40 #define V4L2_BUFFER_STATE_FLAGS	(V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
41 				 V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR)
42 
43 /**
44  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
45  */
__vb2_buf_mem_alloc(struct vb2_buffer * vb,unsigned long * plane_sizes)46 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb,
47 				unsigned long *plane_sizes)
48 {
49 	struct vb2_queue *q = vb->vb2_queue;
50 	void *mem_priv;
51 	int plane;
52 
53 	/* Allocate memory for all planes in this buffer */
54 	for (plane = 0; plane < vb->num_planes; ++plane) {
55 		mem_priv = call_memop(q, plane, alloc, q->alloc_ctx[plane],
56 					plane_sizes[plane]);
57 		if (IS_ERR_OR_NULL(mem_priv))
58 			goto free;
59 
60 		/* Associate allocator private data with this plane */
61 		vb->planes[plane].mem_priv = mem_priv;
62 		vb->v4l2_planes[plane].length = plane_sizes[plane];
63 	}
64 
65 	return 0;
66 free:
67 	/* Free already allocated memory if one of the allocations failed */
68 	for (; plane > 0; --plane)
69 		call_memop(q, plane, put, vb->planes[plane - 1].mem_priv);
70 
71 	return -ENOMEM;
72 }
73 
74 /**
75  * __vb2_buf_mem_free() - free memory of the given buffer
76  */
__vb2_buf_mem_free(struct vb2_buffer * vb)77 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
78 {
79 	struct vb2_queue *q = vb->vb2_queue;
80 	unsigned int plane;
81 
82 	for (plane = 0; plane < vb->num_planes; ++plane) {
83 		call_memop(q, plane, put, vb->planes[plane].mem_priv);
84 		vb->planes[plane].mem_priv = NULL;
85 		dprintk(3, "Freed plane %d of buffer %d\n",
86 				plane, vb->v4l2_buf.index);
87 	}
88 }
89 
90 /**
91  * __vb2_buf_userptr_put() - release userspace memory associated with
92  * a USERPTR buffer
93  */
__vb2_buf_userptr_put(struct vb2_buffer * vb)94 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
95 {
96 	struct vb2_queue *q = vb->vb2_queue;
97 	unsigned int plane;
98 
99 	for (plane = 0; plane < vb->num_planes; ++plane) {
100 		void *mem_priv = vb->planes[plane].mem_priv;
101 
102 		if (mem_priv) {
103 			call_memop(q, plane, put_userptr, mem_priv);
104 			vb->planes[plane].mem_priv = NULL;
105 		}
106 	}
107 }
108 
109 /**
110  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
111  * every buffer on the queue
112  */
__setup_offsets(struct vb2_queue * q)113 static void __setup_offsets(struct vb2_queue *q)
114 {
115 	unsigned int buffer, plane;
116 	struct vb2_buffer *vb;
117 	unsigned long off = 0;
118 
119 	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
120 		vb = q->bufs[buffer];
121 		if (!vb)
122 			continue;
123 
124 		for (plane = 0; plane < vb->num_planes; ++plane) {
125 			vb->v4l2_planes[plane].m.mem_offset = off;
126 
127 			dprintk(3, "Buffer %d, plane %d offset 0x%08lx\n",
128 					buffer, plane, off);
129 
130 			off += vb->v4l2_planes[plane].length;
131 			off = PAGE_ALIGN(off);
132 		}
133 	}
134 }
135 
136 /**
137  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
138  * video buffer memory for all buffers/planes on the queue and initializes the
139  * queue
140  *
141  * Returns the number of buffers successfully allocated.
142  */
__vb2_queue_alloc(struct vb2_queue * q,enum v4l2_memory memory,unsigned int num_buffers,unsigned int num_planes,unsigned long plane_sizes[])143 static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
144 			     unsigned int num_buffers, unsigned int num_planes,
145 			     unsigned long plane_sizes[])
146 {
147 	unsigned int buffer;
148 	struct vb2_buffer *vb;
149 	int ret;
150 
151 	for (buffer = 0; buffer < num_buffers; ++buffer) {
152 		/* Allocate videobuf buffer structures */
153 		vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
154 		if (!vb) {
155 			dprintk(1, "Memory alloc for buffer struct failed\n");
156 			break;
157 		}
158 
159 		/* Length stores number of planes for multiplanar buffers */
160 		if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
161 			vb->v4l2_buf.length = num_planes;
162 
163 		vb->state = VB2_BUF_STATE_DEQUEUED;
164 		vb->vb2_queue = q;
165 		vb->num_planes = num_planes;
166 		vb->v4l2_buf.index = buffer;
167 		vb->v4l2_buf.type = q->type;
168 		vb->v4l2_buf.memory = memory;
169 
170 		/* Allocate video buffer memory for the MMAP type */
171 		if (memory == V4L2_MEMORY_MMAP) {
172 			ret = __vb2_buf_mem_alloc(vb, plane_sizes);
173 			if (ret) {
174 				dprintk(1, "Failed allocating memory for "
175 						"buffer %d\n", buffer);
176 				kfree(vb);
177 				break;
178 			}
179 			/*
180 			 * Call the driver-provided buffer initialization
181 			 * callback, if given. An error in initialization
182 			 * results in queue setup failure.
183 			 */
184 			ret = call_qop(q, buf_init, vb);
185 			if (ret) {
186 				dprintk(1, "Buffer %d %p initialization"
187 					" failed\n", buffer, vb);
188 				__vb2_buf_mem_free(vb);
189 				kfree(vb);
190 				break;
191 			}
192 		}
193 
194 		q->bufs[buffer] = vb;
195 	}
196 
197 	q->num_buffers = buffer;
198 
199 	__setup_offsets(q);
200 
201 	dprintk(1, "Allocated %d buffers, %d plane(s) each\n",
202 			q->num_buffers, num_planes);
203 
204 	return buffer;
205 }
206 
207 /**
208  * __vb2_free_mem() - release all video buffer memory for a given queue
209  */
__vb2_free_mem(struct vb2_queue * q)210 static void __vb2_free_mem(struct vb2_queue *q)
211 {
212 	unsigned int buffer;
213 	struct vb2_buffer *vb;
214 
215 	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
216 		vb = q->bufs[buffer];
217 		if (!vb)
218 			continue;
219 
220 		/* Free MMAP buffers or release USERPTR buffers */
221 		if (q->memory == V4L2_MEMORY_MMAP)
222 			__vb2_buf_mem_free(vb);
223 		else
224 			__vb2_buf_userptr_put(vb);
225 	}
226 }
227 
228 /**
229  * __vb2_queue_free() - free the queue - video memory and related information
230  * and return the queue to an uninitialized state. Might be called even if the
231  * queue has already been freed.
232  */
__vb2_queue_free(struct vb2_queue * q)233 static void __vb2_queue_free(struct vb2_queue *q)
234 {
235 	unsigned int buffer;
236 
237 	/* Call driver-provided cleanup function for each buffer, if provided */
238 	if (q->ops->buf_cleanup) {
239 		for (buffer = 0; buffer < q->num_buffers; ++buffer) {
240 			if (NULL == q->bufs[buffer])
241 				continue;
242 			q->ops->buf_cleanup(q->bufs[buffer]);
243 		}
244 	}
245 
246 	/* Release video buffer memory */
247 	__vb2_free_mem(q);
248 
249 	/* Free videobuf buffers */
250 	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
251 		kfree(q->bufs[buffer]);
252 		q->bufs[buffer] = NULL;
253 	}
254 
255 	q->num_buffers = 0;
256 	q->memory = 0;
257 }
258 
259 /**
260  * __verify_planes_array() - verify that the planes array passed in struct
261  * v4l2_buffer from userspace can be safely used
262  */
__verify_planes_array(struct vb2_buffer * vb,struct v4l2_buffer * b)263 static int __verify_planes_array(struct vb2_buffer *vb, struct v4l2_buffer *b)
264 {
265 	/* Is memory for copying plane information present? */
266 	if (NULL == b->m.planes) {
267 		dprintk(1, "Multi-planar buffer passed but "
268 			   "planes array not provided\n");
269 		return -EINVAL;
270 	}
271 
272 	if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
273 		dprintk(1, "Incorrect planes array length, "
274 			   "expected %d, got %d\n", vb->num_planes, b->length);
275 		return -EINVAL;
276 	}
277 
278 	return 0;
279 }
280 
281 /**
282  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
283  * returned to userspace
284  */
__fill_v4l2_buffer(struct vb2_buffer * vb,struct v4l2_buffer * b)285 static int __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
286 {
287 	struct vb2_queue *q = vb->vb2_queue;
288 	int ret = 0;
289 
290 	/* Copy back data such as timestamp, flags, input, etc. */
291 	memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
292 	b->input = vb->v4l2_buf.input;
293 	b->reserved = vb->v4l2_buf.reserved;
294 
295 	if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
296 		ret = __verify_planes_array(vb, b);
297 		if (ret)
298 			return ret;
299 
300 		/*
301 		 * Fill in plane-related data if userspace provided an array
302 		 * for it. The memory and size is verified above.
303 		 */
304 		memcpy(b->m.planes, vb->v4l2_planes,
305 			b->length * sizeof(struct v4l2_plane));
306 	} else {
307 		/*
308 		 * We use length and offset in v4l2_planes array even for
309 		 * single-planar buffers, but userspace does not.
310 		 */
311 		b->length = vb->v4l2_planes[0].length;
312 		b->bytesused = vb->v4l2_planes[0].bytesused;
313 		if (q->memory == V4L2_MEMORY_MMAP)
314 			b->m.offset = vb->v4l2_planes[0].m.mem_offset;
315 		else if (q->memory == V4L2_MEMORY_USERPTR)
316 			b->m.userptr = vb->v4l2_planes[0].m.userptr;
317 	}
318 
319 	/*
320 	 * Clear any buffer state related flags.
321 	 */
322 	b->flags &= ~V4L2_BUFFER_STATE_FLAGS;
323 
324 	switch (vb->state) {
325 	case VB2_BUF_STATE_QUEUED:
326 	case VB2_BUF_STATE_ACTIVE:
327 		b->flags |= V4L2_BUF_FLAG_QUEUED;
328 		break;
329 	case VB2_BUF_STATE_ERROR:
330 		b->flags |= V4L2_BUF_FLAG_ERROR;
331 		/* fall through */
332 	case VB2_BUF_STATE_DONE:
333 		b->flags |= V4L2_BUF_FLAG_DONE;
334 		break;
335 	case VB2_BUF_STATE_DEQUEUED:
336 		/* nothing */
337 		break;
338 	}
339 
340 	if (vb->num_planes_mapped == vb->num_planes)
341 		b->flags |= V4L2_BUF_FLAG_MAPPED;
342 
343 	return ret;
344 }
345 
346 /**
347  * vb2_querybuf() - query video buffer information
348  * @q:		videobuf queue
349  * @b:		buffer struct passed from userspace to vidioc_querybuf handler
350  *		in driver
351  *
352  * Should be called from vidioc_querybuf ioctl handler in driver.
353  * This function will verify the passed v4l2_buffer structure and fill the
354  * relevant information for the userspace.
355  *
356  * The return values from this function are intended to be directly returned
357  * from vidioc_querybuf handler in driver.
358  */
vb2_querybuf(struct vb2_queue * q,struct v4l2_buffer * b)359 int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
360 {
361 	struct vb2_buffer *vb;
362 
363 	if (b->type != q->type) {
364 		dprintk(1, "querybuf: wrong buffer type\n");
365 		return -EINVAL;
366 	}
367 
368 	if (b->index >= q->num_buffers) {
369 		dprintk(1, "querybuf: buffer index out of range\n");
370 		return -EINVAL;
371 	}
372 	vb = q->bufs[b->index];
373 
374 	return __fill_v4l2_buffer(vb, b);
375 }
376 EXPORT_SYMBOL(vb2_querybuf);
377 
378 /**
379  * __verify_userptr_ops() - verify that all memory operations required for
380  * USERPTR queue type have been provided
381  */
__verify_userptr_ops(struct vb2_queue * q)382 static int __verify_userptr_ops(struct vb2_queue *q)
383 {
384 	if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
385 	    !q->mem_ops->put_userptr)
386 		return -EINVAL;
387 
388 	return 0;
389 }
390 
391 /**
392  * __verify_mmap_ops() - verify that all memory operations required for
393  * MMAP queue type have been provided
394  */
__verify_mmap_ops(struct vb2_queue * q)395 static int __verify_mmap_ops(struct vb2_queue *q)
396 {
397 	if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
398 	    !q->mem_ops->put || !q->mem_ops->mmap)
399 		return -EINVAL;
400 
401 	return 0;
402 }
403 
404 /**
405  * __buffers_in_use() - return true if any buffers on the queue are in use and
406  * the queue cannot be freed (by the means of REQBUFS(0)) call
407  */
__buffers_in_use(struct vb2_queue * q)408 static bool __buffers_in_use(struct vb2_queue *q)
409 {
410 	unsigned int buffer, plane;
411 	struct vb2_buffer *vb;
412 
413 	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
414 		vb = q->bufs[buffer];
415 		for (plane = 0; plane < vb->num_planes; ++plane) {
416 			/*
417 			 * If num_users() has not been provided, call_memop
418 			 * will return 0, apparently nobody cares about this
419 			 * case anyway. If num_users() returns more than 1,
420 			 * we are not the only user of the plane's memory.
421 			 */
422 			if (call_memop(q, plane, num_users,
423 					vb->planes[plane].mem_priv) > 1)
424 				return true;
425 		}
426 	}
427 
428 	return false;
429 }
430 
431 /**
432  * vb2_reqbufs() - Initiate streaming
433  * @q:		videobuf2 queue
434  * @req:	struct passed from userspace to vidioc_reqbufs handler in driver
435  *
436  * Should be called from vidioc_reqbufs ioctl handler of a driver.
437  * This function:
438  * 1) verifies streaming parameters passed from the userspace,
439  * 2) sets up the queue,
440  * 3) negotiates number of buffers and planes per buffer with the driver
441  *    to be used during streaming,
442  * 4) allocates internal buffer structures (struct vb2_buffer), according to
443  *    the agreed parameters,
444  * 5) for MMAP memory type, allocates actual video memory, using the
445  *    memory handling/allocation routines provided during queue initialization
446  *
447  * If req->count is 0, all the memory will be freed instead.
448  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
449  * and the queue is not busy, memory will be reallocated.
450  *
451  * The return values from this function are intended to be directly returned
452  * from vidioc_reqbufs handler in driver.
453  */
vb2_reqbufs(struct vb2_queue * q,struct v4l2_requestbuffers * req)454 int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
455 {
456 	unsigned int num_buffers, num_planes;
457 	unsigned long plane_sizes[VIDEO_MAX_PLANES];
458 	int ret = 0;
459 
460 	if (q->fileio) {
461 		dprintk(1, "reqbufs: file io in progress\n");
462 		return -EBUSY;
463 	}
464 
465 	if (req->memory != V4L2_MEMORY_MMAP
466 			&& req->memory != V4L2_MEMORY_USERPTR) {
467 		dprintk(1, "reqbufs: unsupported memory type\n");
468 		return -EINVAL;
469 	}
470 
471 	if (req->type != q->type) {
472 		dprintk(1, "reqbufs: requested type is incorrect\n");
473 		return -EINVAL;
474 	}
475 
476 	if (q->streaming) {
477 		dprintk(1, "reqbufs: streaming active\n");
478 		return -EBUSY;
479 	}
480 
481 	/*
482 	 * Make sure all the required memory ops for given memory type
483 	 * are available.
484 	 */
485 	if (req->memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
486 		dprintk(1, "reqbufs: MMAP for current setup unsupported\n");
487 		return -EINVAL;
488 	}
489 
490 	if (req->memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
491 		dprintk(1, "reqbufs: USERPTR for current setup unsupported\n");
492 		return -EINVAL;
493 	}
494 
495 	/*
496 	 * If the same number of buffers and memory access method is requested
497 	 * then return immediately.
498 	 */
499 	if (q->memory == req->memory && req->count == q->num_buffers)
500 		return 0;
501 
502 	if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
503 		/*
504 		 * We already have buffers allocated, so first check if they
505 		 * are not in use and can be freed.
506 		 */
507 		if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
508 			dprintk(1, "reqbufs: memory in use, cannot free\n");
509 			return -EBUSY;
510 		}
511 
512 		__vb2_queue_free(q);
513 
514 		/*
515 		 * In case of REQBUFS(0) return immediately without calling
516 		 * driver's queue_setup() callback and allocating resources.
517 		 */
518 		if (req->count == 0)
519 			return 0;
520 	}
521 
522 	/*
523 	 * Make sure the requested values and current defaults are sane.
524 	 */
525 	num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
526 	memset(plane_sizes, 0, sizeof(plane_sizes));
527 	memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
528 	q->memory = req->memory;
529 
530 	/*
531 	 * Ask the driver how many buffers and planes per buffer it requires.
532 	 * Driver also sets the size and allocator context for each plane.
533 	 */
534 	ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
535 		       plane_sizes, q->alloc_ctx);
536 	if (ret)
537 		return ret;
538 
539 	/* Finally, allocate buffers and video memory */
540 	ret = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes,
541 				plane_sizes);
542 	if (ret < 0) {
543 		dprintk(1, "Memory allocation failed with error: %d\n", ret);
544 		return ret;
545 	}
546 
547 	/*
548 	 * Check if driver can handle the allocated number of buffers.
549 	 */
550 	if (ret < num_buffers) {
551 		unsigned int orig_num_buffers;
552 
553 		orig_num_buffers = num_buffers = ret;
554 		ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
555 			       plane_sizes, q->alloc_ctx);
556 		if (ret)
557 			goto free_mem;
558 
559 		if (orig_num_buffers < num_buffers) {
560 			ret = -ENOMEM;
561 			goto free_mem;
562 		}
563 
564 		/*
565 		 * Ok, driver accepted smaller number of buffers.
566 		 */
567 		ret = num_buffers;
568 	}
569 
570 	/*
571 	 * Return the number of successfully allocated buffers
572 	 * to the userspace.
573 	 */
574 	req->count = ret;
575 
576 	return 0;
577 
578 free_mem:
579 	__vb2_queue_free(q);
580 	return ret;
581 }
582 EXPORT_SYMBOL_GPL(vb2_reqbufs);
583 
584 /**
585  * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
586  * @vb:		vb2_buffer to which the plane in question belongs to
587  * @plane_no:	plane number for which the address is to be returned
588  *
589  * This function returns a kernel virtual address of a given plane if
590  * such a mapping exist, NULL otherwise.
591  */
vb2_plane_vaddr(struct vb2_buffer * vb,unsigned int plane_no)592 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
593 {
594 	struct vb2_queue *q = vb->vb2_queue;
595 
596 	if (plane_no > vb->num_planes)
597 		return NULL;
598 
599 	return call_memop(q, plane_no, vaddr, vb->planes[plane_no].mem_priv);
600 
601 }
602 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
603 
604 /**
605  * vb2_plane_cookie() - Return allocator specific cookie for the given plane
606  * @vb:		vb2_buffer to which the plane in question belongs to
607  * @plane_no:	plane number for which the cookie is to be returned
608  *
609  * This function returns an allocator specific cookie for a given plane if
610  * available, NULL otherwise. The allocator should provide some simple static
611  * inline function, which would convert this cookie to the allocator specific
612  * type that can be used directly by the driver to access the buffer. This can
613  * be for example physical address, pointer to scatter list or IOMMU mapping.
614  */
vb2_plane_cookie(struct vb2_buffer * vb,unsigned int plane_no)615 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
616 {
617 	struct vb2_queue *q = vb->vb2_queue;
618 
619 	if (plane_no > vb->num_planes)
620 		return NULL;
621 
622 	return call_memop(q, plane_no, cookie, vb->planes[plane_no].mem_priv);
623 }
624 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
625 
626 /**
627  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
628  * @vb:		vb2_buffer returned from the driver
629  * @state:	either VB2_BUF_STATE_DONE if the operation finished successfully
630  *		or VB2_BUF_STATE_ERROR if the operation finished with an error
631  *
632  * This function should be called by the driver after a hardware operation on
633  * a buffer is finished and the buffer may be returned to userspace. The driver
634  * cannot use this buffer anymore until it is queued back to it by videobuf
635  * by the means of buf_queue callback. Only buffers previously queued to the
636  * driver by buf_queue can be passed to this function.
637  */
vb2_buffer_done(struct vb2_buffer * vb,enum vb2_buffer_state state)638 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
639 {
640 	struct vb2_queue *q = vb->vb2_queue;
641 	unsigned long flags;
642 
643 	if (vb->state != VB2_BUF_STATE_ACTIVE)
644 		return;
645 
646 	if (state != VB2_BUF_STATE_DONE && state != VB2_BUF_STATE_ERROR)
647 		return;
648 
649 	dprintk(4, "Done processing on buffer %d, state: %d\n",
650 			vb->v4l2_buf.index, vb->state);
651 
652 	/* Add the buffer to the done buffers list */
653 	spin_lock_irqsave(&q->done_lock, flags);
654 	vb->state = state;
655 	list_add_tail(&vb->done_entry, &q->done_list);
656 	atomic_dec(&q->queued_count);
657 	spin_unlock_irqrestore(&q->done_lock, flags);
658 
659 	/* Inform any processes that may be waiting for buffers */
660 	wake_up(&q->done_wq);
661 }
662 EXPORT_SYMBOL_GPL(vb2_buffer_done);
663 
664 /**
665  * __fill_vb2_buffer() - fill a vb2_buffer with information provided in
666  * a v4l2_buffer by the userspace
667  */
__fill_vb2_buffer(struct vb2_buffer * vb,struct v4l2_buffer * b,struct v4l2_plane * v4l2_planes)668 static int __fill_vb2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b,
669 				struct v4l2_plane *v4l2_planes)
670 {
671 	unsigned int plane;
672 	int ret;
673 
674 	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
675 		/*
676 		 * Verify that the userspace gave us a valid array for
677 		 * plane information.
678 		 */
679 		ret = __verify_planes_array(vb, b);
680 		if (ret)
681 			return ret;
682 
683 		/* Fill in driver-provided information for OUTPUT types */
684 		if (V4L2_TYPE_IS_OUTPUT(b->type)) {
685 			/*
686 			 * Will have to go up to b->length when API starts
687 			 * accepting variable number of planes.
688 			 */
689 			for (plane = 0; plane < vb->num_planes; ++plane) {
690 				v4l2_planes[plane].bytesused =
691 					b->m.planes[plane].bytesused;
692 				v4l2_planes[plane].data_offset =
693 					b->m.planes[plane].data_offset;
694 			}
695 		}
696 
697 		if (b->memory == V4L2_MEMORY_USERPTR) {
698 			for (plane = 0; plane < vb->num_planes; ++plane) {
699 				v4l2_planes[plane].m.userptr =
700 					b->m.planes[plane].m.userptr;
701 				v4l2_planes[plane].length =
702 					b->m.planes[plane].length;
703 			}
704 		}
705 	} else {
706 		/*
707 		 * Single-planar buffers do not use planes array,
708 		 * so fill in relevant v4l2_buffer struct fields instead.
709 		 * In videobuf we use our internal V4l2_planes struct for
710 		 * single-planar buffers as well, for simplicity.
711 		 */
712 		if (V4L2_TYPE_IS_OUTPUT(b->type))
713 			v4l2_planes[0].bytesused = b->bytesused;
714 
715 		if (b->memory == V4L2_MEMORY_USERPTR) {
716 			v4l2_planes[0].m.userptr = b->m.userptr;
717 			v4l2_planes[0].length = b->length;
718 		}
719 	}
720 
721 	vb->v4l2_buf.field = b->field;
722 	vb->v4l2_buf.timestamp = b->timestamp;
723 	vb->v4l2_buf.input = b->input;
724 	vb->v4l2_buf.flags = b->flags & ~V4L2_BUFFER_STATE_FLAGS;
725 
726 	return 0;
727 }
728 
729 /**
730  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
731  */
__qbuf_userptr(struct vb2_buffer * vb,struct v4l2_buffer * b)732 static int __qbuf_userptr(struct vb2_buffer *vb, struct v4l2_buffer *b)
733 {
734 	struct v4l2_plane planes[VIDEO_MAX_PLANES];
735 	struct vb2_queue *q = vb->vb2_queue;
736 	void *mem_priv;
737 	unsigned int plane;
738 	int ret;
739 	int write = !V4L2_TYPE_IS_OUTPUT(q->type);
740 
741 	/* Verify and copy relevant information provided by the userspace */
742 	ret = __fill_vb2_buffer(vb, b, planes);
743 	if (ret)
744 		return ret;
745 
746 	for (plane = 0; plane < vb->num_planes; ++plane) {
747 		/* Skip the plane if already verified */
748 		if (vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
749 		    && vb->v4l2_planes[plane].length == planes[plane].length)
750 			continue;
751 
752 		dprintk(3, "qbuf: userspace address for plane %d changed, "
753 				"reacquiring memory\n", plane);
754 
755 		/* Release previously acquired memory if present */
756 		if (vb->planes[plane].mem_priv)
757 			call_memop(q, plane, put_userptr,
758 					vb->planes[plane].mem_priv);
759 
760 		vb->planes[plane].mem_priv = NULL;
761 
762 		/* Acquire each plane's memory */
763 		if (q->mem_ops->get_userptr) {
764 			mem_priv = q->mem_ops->get_userptr(q->alloc_ctx[plane],
765 							planes[plane].m.userptr,
766 							planes[plane].length,
767 							write);
768 			if (IS_ERR(mem_priv)) {
769 				dprintk(1, "qbuf: failed acquiring userspace "
770 						"memory for plane %d\n", plane);
771 				ret = PTR_ERR(mem_priv);
772 				goto err;
773 			}
774 			vb->planes[plane].mem_priv = mem_priv;
775 		}
776 	}
777 
778 	/*
779 	 * Call driver-specific initialization on the newly acquired buffer,
780 	 * if provided.
781 	 */
782 	ret = call_qop(q, buf_init, vb);
783 	if (ret) {
784 		dprintk(1, "qbuf: buffer initialization failed\n");
785 		goto err;
786 	}
787 
788 	/*
789 	 * Now that everything is in order, copy relevant information
790 	 * provided by userspace.
791 	 */
792 	for (plane = 0; plane < vb->num_planes; ++plane)
793 		vb->v4l2_planes[plane] = planes[plane];
794 
795 	return 0;
796 err:
797 	/* In case of errors, release planes that were already acquired */
798 	for (; plane > 0; --plane) {
799 		call_memop(q, plane, put_userptr,
800 				vb->planes[plane - 1].mem_priv);
801 		vb->planes[plane - 1].mem_priv = NULL;
802 	}
803 
804 	return ret;
805 }
806 
807 /**
808  * __qbuf_mmap() - handle qbuf of an MMAP buffer
809  */
__qbuf_mmap(struct vb2_buffer * vb,struct v4l2_buffer * b)810 static int __qbuf_mmap(struct vb2_buffer *vb, struct v4l2_buffer *b)
811 {
812 	return __fill_vb2_buffer(vb, b, vb->v4l2_planes);
813 }
814 
815 /**
816  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
817  */
__enqueue_in_driver(struct vb2_buffer * vb)818 static void __enqueue_in_driver(struct vb2_buffer *vb)
819 {
820 	struct vb2_queue *q = vb->vb2_queue;
821 
822 	vb->state = VB2_BUF_STATE_ACTIVE;
823 	atomic_inc(&q->queued_count);
824 	q->ops->buf_queue(vb);
825 }
826 
827 /**
828  * vb2_qbuf() - Queue a buffer from userspace
829  * @q:		videobuf2 queue
830  * @b:		buffer structure passed from userspace to vidioc_qbuf handler
831  *		in driver
832  *
833  * Should be called from vidioc_qbuf ioctl handler of a driver.
834  * This function:
835  * 1) verifies the passed buffer,
836  * 2) calls buf_prepare callback in the driver (if provided), in which
837  *    driver-specific buffer initialization can be performed,
838  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
839  *    callback for processing.
840  *
841  * The return values from this function are intended to be directly returned
842  * from vidioc_qbuf handler in driver.
843  */
vb2_qbuf(struct vb2_queue * q,struct v4l2_buffer * b)844 int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
845 {
846 	struct vb2_buffer *vb;
847 	int ret = 0;
848 
849 	if (q->fileio) {
850 		dprintk(1, "qbuf: file io in progress\n");
851 		return -EBUSY;
852 	}
853 
854 	if (b->type != q->type) {
855 		dprintk(1, "qbuf: invalid buffer type\n");
856 		return -EINVAL;
857 	}
858 
859 	if (b->index >= q->num_buffers) {
860 		dprintk(1, "qbuf: buffer index out of range\n");
861 		return -EINVAL;
862 	}
863 
864 	vb = q->bufs[b->index];
865 	if (NULL == vb) {
866 		/* Should never happen */
867 		dprintk(1, "qbuf: buffer is NULL\n");
868 		return -EINVAL;
869 	}
870 
871 	if (b->memory != q->memory) {
872 		dprintk(1, "qbuf: invalid memory type\n");
873 		return -EINVAL;
874 	}
875 
876 	if (vb->state != VB2_BUF_STATE_DEQUEUED) {
877 		dprintk(1, "qbuf: buffer already in use\n");
878 		return -EINVAL;
879 	}
880 
881 	if (q->memory == V4L2_MEMORY_MMAP)
882 		ret = __qbuf_mmap(vb, b);
883 	else if (q->memory == V4L2_MEMORY_USERPTR)
884 		ret = __qbuf_userptr(vb, b);
885 	else {
886 		WARN(1, "Invalid queue type\n");
887 		return -EINVAL;
888 	}
889 
890 	if (ret)
891 		return ret;
892 
893 	ret = call_qop(q, buf_prepare, vb);
894 	if (ret) {
895 		dprintk(1, "qbuf: buffer preparation failed\n");
896 		return ret;
897 	}
898 
899 	/*
900 	 * Add to the queued buffers list, a buffer will stay on it until
901 	 * dequeued in dqbuf.
902 	 */
903 	list_add_tail(&vb->queued_entry, &q->queued_list);
904 	vb->state = VB2_BUF_STATE_QUEUED;
905 
906 	/*
907 	 * If already streaming, give the buffer to driver for processing.
908 	 * If not, the buffer will be given to driver on next streamon.
909 	 */
910 	if (q->streaming)
911 		__enqueue_in_driver(vb);
912 
913 	dprintk(1, "qbuf of buffer %d succeeded\n", vb->v4l2_buf.index);
914 	return 0;
915 }
916 EXPORT_SYMBOL_GPL(vb2_qbuf);
917 
918 /**
919  * __vb2_wait_for_done_vb() - wait for a buffer to become available
920  * for dequeuing
921  *
922  * Will sleep if required for nonblocking == false.
923  */
__vb2_wait_for_done_vb(struct vb2_queue * q,int nonblocking)924 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
925 {
926 	/*
927 	 * All operations on vb_done_list are performed under done_lock
928 	 * spinlock protection. However, buffers may be removed from
929 	 * it and returned to userspace only while holding both driver's
930 	 * lock and the done_lock spinlock. Thus we can be sure that as
931 	 * long as we hold the driver's lock, the list will remain not
932 	 * empty if list_empty() check succeeds.
933 	 */
934 
935 	for (;;) {
936 		int ret;
937 
938 		if (!q->streaming) {
939 			dprintk(1, "Streaming off, will not wait for buffers\n");
940 			return -EINVAL;
941 		}
942 
943 		if (!list_empty(&q->done_list)) {
944 			/*
945 			 * Found a buffer that we were waiting for.
946 			 */
947 			break;
948 		}
949 
950 		if (nonblocking) {
951 			dprintk(1, "Nonblocking and no buffers to dequeue, "
952 								"will not wait\n");
953 			return -EAGAIN;
954 		}
955 
956 		/*
957 		 * We are streaming and blocking, wait for another buffer to
958 		 * become ready or for streamoff. Driver's lock is released to
959 		 * allow streamoff or qbuf to be called while waiting.
960 		 */
961 		call_qop(q, wait_prepare, q);
962 
963 		/*
964 		 * All locks have been released, it is safe to sleep now.
965 		 */
966 		dprintk(3, "Will sleep waiting for buffers\n");
967 		ret = wait_event_interruptible(q->done_wq,
968 				!list_empty(&q->done_list) || !q->streaming);
969 
970 		/*
971 		 * We need to reevaluate both conditions again after reacquiring
972 		 * the locks or return an error if one occurred.
973 		 */
974 		call_qop(q, wait_finish, q);
975 		if (ret)
976 			return ret;
977 	}
978 	return 0;
979 }
980 
981 /**
982  * __vb2_get_done_vb() - get a buffer ready for dequeuing
983  *
984  * Will sleep if required for nonblocking == false.
985  */
__vb2_get_done_vb(struct vb2_queue * q,struct vb2_buffer ** vb,int nonblocking)986 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
987 				int nonblocking)
988 {
989 	unsigned long flags;
990 	int ret;
991 
992 	/*
993 	 * Wait for at least one buffer to become available on the done_list.
994 	 */
995 	ret = __vb2_wait_for_done_vb(q, nonblocking);
996 	if (ret)
997 		return ret;
998 
999 	/*
1000 	 * Driver's lock has been held since we last verified that done_list
1001 	 * is not empty, so no need for another list_empty(done_list) check.
1002 	 */
1003 	spin_lock_irqsave(&q->done_lock, flags);
1004 	*vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1005 	list_del(&(*vb)->done_entry);
1006 	spin_unlock_irqrestore(&q->done_lock, flags);
1007 
1008 	return 0;
1009 }
1010 
1011 /**
1012  * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
1013  * @q:		videobuf2 queue
1014  *
1015  * This function will wait until all buffers that have been given to the driver
1016  * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
1017  * wait_prepare, wait_finish pair. It is intended to be called with all locks
1018  * taken, for example from stop_streaming() callback.
1019  */
vb2_wait_for_all_buffers(struct vb2_queue * q)1020 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1021 {
1022 	if (!q->streaming) {
1023 		dprintk(1, "Streaming off, will not wait for buffers\n");
1024 		return -EINVAL;
1025 	}
1026 
1027 	wait_event(q->done_wq, !atomic_read(&q->queued_count));
1028 	return 0;
1029 }
1030 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1031 
1032 /**
1033  * vb2_dqbuf() - Dequeue a buffer to the userspace
1034  * @q:		videobuf2 queue
1035  * @b:		buffer structure passed from userspace to vidioc_dqbuf handler
1036  *		in driver
1037  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
1038  *		 buffers ready for dequeuing are present. Normally the driver
1039  *		 would be passing (file->f_flags & O_NONBLOCK) here
1040  *
1041  * Should be called from vidioc_dqbuf ioctl handler of a driver.
1042  * This function:
1043  * 1) verifies the passed buffer,
1044  * 2) calls buf_finish callback in the driver (if provided), in which
1045  *    driver can perform any additional operations that may be required before
1046  *    returning the buffer to userspace, such as cache sync,
1047  * 3) the buffer struct members are filled with relevant information for
1048  *    the userspace.
1049  *
1050  * The return values from this function are intended to be directly returned
1051  * from vidioc_dqbuf handler in driver.
1052  */
vb2_dqbuf(struct vb2_queue * q,struct v4l2_buffer * b,bool nonblocking)1053 int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
1054 {
1055 	struct vb2_buffer *vb = NULL;
1056 	int ret;
1057 
1058 	if (q->fileio) {
1059 		dprintk(1, "dqbuf: file io in progress\n");
1060 		return -EBUSY;
1061 	}
1062 
1063 	if (b->type != q->type) {
1064 		dprintk(1, "dqbuf: invalid buffer type\n");
1065 		return -EINVAL;
1066 	}
1067 
1068 	ret = __vb2_get_done_vb(q, &vb, nonblocking);
1069 	if (ret < 0) {
1070 		dprintk(1, "dqbuf: error getting next done buffer\n");
1071 		return ret;
1072 	}
1073 
1074 	ret = call_qop(q, buf_finish, vb);
1075 	if (ret) {
1076 		dprintk(1, "dqbuf: buffer finish failed\n");
1077 		return ret;
1078 	}
1079 
1080 	switch (vb->state) {
1081 	case VB2_BUF_STATE_DONE:
1082 		dprintk(3, "dqbuf: Returning done buffer\n");
1083 		break;
1084 	case VB2_BUF_STATE_ERROR:
1085 		dprintk(3, "dqbuf: Returning done buffer with errors\n");
1086 		break;
1087 	default:
1088 		dprintk(1, "dqbuf: Invalid buffer state\n");
1089 		return -EINVAL;
1090 	}
1091 
1092 	/* Fill buffer information for the userspace */
1093 	__fill_v4l2_buffer(vb, b);
1094 	/* Remove from videobuf queue */
1095 	list_del(&vb->queued_entry);
1096 
1097 	dprintk(1, "dqbuf of buffer %d, with state %d\n",
1098 			vb->v4l2_buf.index, vb->state);
1099 
1100 	vb->state = VB2_BUF_STATE_DEQUEUED;
1101 	return 0;
1102 }
1103 EXPORT_SYMBOL_GPL(vb2_dqbuf);
1104 
1105 /**
1106  * vb2_streamon - start streaming
1107  * @q:		videobuf2 queue
1108  * @type:	type argument passed from userspace to vidioc_streamon handler
1109  *
1110  * Should be called from vidioc_streamon handler of a driver.
1111  * This function:
1112  * 1) verifies current state
1113  * 2) starts streaming and passes any previously queued buffers to the driver
1114  *
1115  * The return values from this function are intended to be directly returned
1116  * from vidioc_streamon handler in the driver.
1117  */
vb2_streamon(struct vb2_queue * q,enum v4l2_buf_type type)1118 int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
1119 {
1120 	struct vb2_buffer *vb;
1121 	int ret;
1122 
1123 	if (q->fileio) {
1124 		dprintk(1, "streamon: file io in progress\n");
1125 		return -EBUSY;
1126 	}
1127 
1128 	if (type != q->type) {
1129 		dprintk(1, "streamon: invalid stream type\n");
1130 		return -EINVAL;
1131 	}
1132 
1133 	if (q->streaming) {
1134 		dprintk(1, "streamon: already streaming\n");
1135 		return -EBUSY;
1136 	}
1137 
1138 	/*
1139 	 * Cannot start streaming on an OUTPUT device if no buffers have
1140 	 * been queued yet.
1141 	 */
1142 	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1143 		if (list_empty(&q->queued_list)) {
1144 			dprintk(1, "streamon: no output buffers queued\n");
1145 			return -EINVAL;
1146 		}
1147 	}
1148 
1149 	/*
1150 	 * Let driver notice that streaming state has been enabled.
1151 	 */
1152 	ret = call_qop(q, start_streaming, q);
1153 	if (ret) {
1154 		dprintk(1, "streamon: driver refused to start streaming\n");
1155 		return ret;
1156 	}
1157 
1158 	q->streaming = 1;
1159 
1160 	/*
1161 	 * If any buffers were queued before streamon,
1162 	 * we can now pass them to driver for processing.
1163 	 */
1164 	list_for_each_entry(vb, &q->queued_list, queued_entry)
1165 		__enqueue_in_driver(vb);
1166 
1167 	dprintk(3, "Streamon successful\n");
1168 	return 0;
1169 }
1170 EXPORT_SYMBOL_GPL(vb2_streamon);
1171 
1172 /**
1173  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1174  *
1175  * Removes all queued buffers from driver's queue and all buffers queued by
1176  * userspace from videobuf's queue. Returns to state after reqbufs.
1177  */
__vb2_queue_cancel(struct vb2_queue * q)1178 static void __vb2_queue_cancel(struct vb2_queue *q)
1179 {
1180 	unsigned int i;
1181 
1182 	/*
1183 	 * Tell driver to stop all transactions and release all queued
1184 	 * buffers.
1185 	 */
1186 	if (q->streaming)
1187 		call_qop(q, stop_streaming, q);
1188 	q->streaming = 0;
1189 
1190 	/*
1191 	 * Remove all buffers from videobuf's list...
1192 	 */
1193 	INIT_LIST_HEAD(&q->queued_list);
1194 	/*
1195 	 * ...and done list; userspace will not receive any buffers it
1196 	 * has not already dequeued before initiating cancel.
1197 	 */
1198 	INIT_LIST_HEAD(&q->done_list);
1199 	wake_up_all(&q->done_wq);
1200 
1201 	/*
1202 	 * Reinitialize all buffers for next use.
1203 	 */
1204 	for (i = 0; i < q->num_buffers; ++i)
1205 		q->bufs[i]->state = VB2_BUF_STATE_DEQUEUED;
1206 }
1207 
1208 /**
1209  * vb2_streamoff - stop streaming
1210  * @q:		videobuf2 queue
1211  * @type:	type argument passed from userspace to vidioc_streamoff handler
1212  *
1213  * Should be called from vidioc_streamoff handler of a driver.
1214  * This function:
1215  * 1) verifies current state,
1216  * 2) stop streaming and dequeues any queued buffers, including those previously
1217  *    passed to the driver (after waiting for the driver to finish).
1218  *
1219  * This call can be used for pausing playback.
1220  * The return values from this function are intended to be directly returned
1221  * from vidioc_streamoff handler in the driver
1222  */
vb2_streamoff(struct vb2_queue * q,enum v4l2_buf_type type)1223 int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
1224 {
1225 	if (q->fileio) {
1226 		dprintk(1, "streamoff: file io in progress\n");
1227 		return -EBUSY;
1228 	}
1229 
1230 	if (type != q->type) {
1231 		dprintk(1, "streamoff: invalid stream type\n");
1232 		return -EINVAL;
1233 	}
1234 
1235 	if (!q->streaming) {
1236 		dprintk(1, "streamoff: not streaming\n");
1237 		return -EINVAL;
1238 	}
1239 
1240 	/*
1241 	 * Cancel will pause streaming and remove all buffers from the driver
1242 	 * and videobuf, effectively returning control over them to userspace.
1243 	 */
1244 	__vb2_queue_cancel(q);
1245 
1246 	dprintk(3, "Streamoff successful\n");
1247 	return 0;
1248 }
1249 EXPORT_SYMBOL_GPL(vb2_streamoff);
1250 
1251 /**
1252  * __find_plane_by_offset() - find plane associated with the given offset off
1253  */
__find_plane_by_offset(struct vb2_queue * q,unsigned long off,unsigned int * _buffer,unsigned int * _plane)1254 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1255 			unsigned int *_buffer, unsigned int *_plane)
1256 {
1257 	struct vb2_buffer *vb;
1258 	unsigned int buffer, plane;
1259 
1260 	/*
1261 	 * Go over all buffers and their planes, comparing the given offset
1262 	 * with an offset assigned to each plane. If a match is found,
1263 	 * return its buffer and plane numbers.
1264 	 */
1265 	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1266 		vb = q->bufs[buffer];
1267 
1268 		for (plane = 0; plane < vb->num_planes; ++plane) {
1269 			if (vb->v4l2_planes[plane].m.mem_offset == off) {
1270 				*_buffer = buffer;
1271 				*_plane = plane;
1272 				return 0;
1273 			}
1274 		}
1275 	}
1276 
1277 	return -EINVAL;
1278 }
1279 
1280 /**
1281  * vb2_mmap() - map video buffers into application address space
1282  * @q:		videobuf2 queue
1283  * @vma:	vma passed to the mmap file operation handler in the driver
1284  *
1285  * Should be called from mmap file operation handler of a driver.
1286  * This function maps one plane of one of the available video buffers to
1287  * userspace. To map whole video memory allocated on reqbufs, this function
1288  * has to be called once per each plane per each buffer previously allocated.
1289  *
1290  * When the userspace application calls mmap, it passes to it an offset returned
1291  * to it earlier by the means of vidioc_querybuf handler. That offset acts as
1292  * a "cookie", which is then used to identify the plane to be mapped.
1293  * This function finds a plane with a matching offset and a mapping is performed
1294  * by the means of a provided memory operation.
1295  *
1296  * The return values from this function are intended to be directly returned
1297  * from the mmap handler in driver.
1298  */
vb2_mmap(struct vb2_queue * q,struct vm_area_struct * vma)1299 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1300 {
1301 	unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1302 	struct vb2_plane *vb_plane;
1303 	struct vb2_buffer *vb;
1304 	unsigned int buffer, plane;
1305 	int ret;
1306 
1307 	if (q->memory != V4L2_MEMORY_MMAP) {
1308 		dprintk(1, "Queue is not currently set up for mmap\n");
1309 		return -EINVAL;
1310 	}
1311 
1312 	/*
1313 	 * Check memory area access mode.
1314 	 */
1315 	if (!(vma->vm_flags & VM_SHARED)) {
1316 		dprintk(1, "Invalid vma flags, VM_SHARED needed\n");
1317 		return -EINVAL;
1318 	}
1319 	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
1320 		if (!(vma->vm_flags & VM_WRITE)) {
1321 			dprintk(1, "Invalid vma flags, VM_WRITE needed\n");
1322 			return -EINVAL;
1323 		}
1324 	} else {
1325 		if (!(vma->vm_flags & VM_READ)) {
1326 			dprintk(1, "Invalid vma flags, VM_READ needed\n");
1327 			return -EINVAL;
1328 		}
1329 	}
1330 
1331 	/*
1332 	 * Find the plane corresponding to the offset passed by userspace.
1333 	 */
1334 	ret = __find_plane_by_offset(q, off, &buffer, &plane);
1335 	if (ret)
1336 		return ret;
1337 
1338 	vb = q->bufs[buffer];
1339 	vb_plane = &vb->planes[plane];
1340 
1341 	ret = q->mem_ops->mmap(vb_plane->mem_priv, vma);
1342 	if (ret)
1343 		return ret;
1344 
1345 	vb_plane->mapped = 1;
1346 	vb->num_planes_mapped++;
1347 
1348 	dprintk(3, "Buffer %d, plane %d successfully mapped\n", buffer, plane);
1349 	return 0;
1350 }
1351 EXPORT_SYMBOL_GPL(vb2_mmap);
1352 
1353 static int __vb2_init_fileio(struct vb2_queue *q, int read);
1354 static int __vb2_cleanup_fileio(struct vb2_queue *q);
1355 
1356 /**
1357  * vb2_poll() - implements poll userspace operation
1358  * @q:		videobuf2 queue
1359  * @file:	file argument passed to the poll file operation handler
1360  * @wait:	wait argument passed to the poll file operation handler
1361  *
1362  * This function implements poll file operation handler for a driver.
1363  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
1364  * be informed that the file descriptor of a video device is available for
1365  * reading.
1366  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
1367  * will be reported as available for writing.
1368  *
1369  * The return values from this function are intended to be directly returned
1370  * from poll handler in driver.
1371  */
vb2_poll(struct vb2_queue * q,struct file * file,poll_table * wait)1372 unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
1373 {
1374 	unsigned long flags;
1375 	unsigned int ret;
1376 	struct vb2_buffer *vb = NULL;
1377 
1378 	/*
1379 	 * Start file I/O emulator only if streaming API has not been used yet.
1380 	 */
1381 	if (q->num_buffers == 0 && q->fileio == NULL) {
1382 		if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ)) {
1383 			ret = __vb2_init_fileio(q, 1);
1384 			if (ret)
1385 				return POLLERR;
1386 		}
1387 		if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE)) {
1388 			ret = __vb2_init_fileio(q, 0);
1389 			if (ret)
1390 				return POLLERR;
1391 			/*
1392 			 * Write to OUTPUT queue can be done immediately.
1393 			 */
1394 			return POLLOUT | POLLWRNORM;
1395 		}
1396 	}
1397 
1398 	/*
1399 	 * There is nothing to wait for if no buffers have already been queued.
1400 	 */
1401 	if (list_empty(&q->queued_list))
1402 		return POLLERR;
1403 
1404 	poll_wait(file, &q->done_wq, wait);
1405 
1406 	/*
1407 	 * Take first buffer available for dequeuing.
1408 	 */
1409 	spin_lock_irqsave(&q->done_lock, flags);
1410 	if (!list_empty(&q->done_list))
1411 		vb = list_first_entry(&q->done_list, struct vb2_buffer,
1412 					done_entry);
1413 	spin_unlock_irqrestore(&q->done_lock, flags);
1414 
1415 	if (vb && (vb->state == VB2_BUF_STATE_DONE
1416 			|| vb->state == VB2_BUF_STATE_ERROR)) {
1417 		return (V4L2_TYPE_IS_OUTPUT(q->type)) ? POLLOUT | POLLWRNORM :
1418 			POLLIN | POLLRDNORM;
1419 	}
1420 	return 0;
1421 }
1422 EXPORT_SYMBOL_GPL(vb2_poll);
1423 
1424 /**
1425  * vb2_queue_init() - initialize a videobuf2 queue
1426  * @q:		videobuf2 queue; this structure should be allocated in driver
1427  *
1428  * The vb2_queue structure should be allocated by the driver. The driver is
1429  * responsible of clearing it's content and setting initial values for some
1430  * required entries before calling this function.
1431  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
1432  * to the struct vb2_queue description in include/media/videobuf2-core.h
1433  * for more information.
1434  */
vb2_queue_init(struct vb2_queue * q)1435 int vb2_queue_init(struct vb2_queue *q)
1436 {
1437 	BUG_ON(!q);
1438 	BUG_ON(!q->ops);
1439 	BUG_ON(!q->mem_ops);
1440 	BUG_ON(!q->type);
1441 	BUG_ON(!q->io_modes);
1442 
1443 	BUG_ON(!q->ops->queue_setup);
1444 	BUG_ON(!q->ops->buf_queue);
1445 
1446 	INIT_LIST_HEAD(&q->queued_list);
1447 	INIT_LIST_HEAD(&q->done_list);
1448 	spin_lock_init(&q->done_lock);
1449 	init_waitqueue_head(&q->done_wq);
1450 
1451 	if (q->buf_struct_size == 0)
1452 		q->buf_struct_size = sizeof(struct vb2_buffer);
1453 
1454 	return 0;
1455 }
1456 EXPORT_SYMBOL_GPL(vb2_queue_init);
1457 
1458 /**
1459  * vb2_queue_release() - stop streaming, release the queue and free memory
1460  * @q:		videobuf2 queue
1461  *
1462  * This function stops streaming and performs necessary clean ups, including
1463  * freeing video buffer memory. The driver is responsible for freeing
1464  * the vb2_queue structure itself.
1465  */
vb2_queue_release(struct vb2_queue * q)1466 void vb2_queue_release(struct vb2_queue *q)
1467 {
1468 	__vb2_cleanup_fileio(q);
1469 	__vb2_queue_cancel(q);
1470 	__vb2_queue_free(q);
1471 }
1472 EXPORT_SYMBOL_GPL(vb2_queue_release);
1473 
1474 /**
1475  * struct vb2_fileio_buf - buffer context used by file io emulator
1476  *
1477  * vb2 provides a compatibility layer and emulator of file io (read and
1478  * write) calls on top of streaming API. This structure is used for
1479  * tracking context related to the buffers.
1480  */
1481 struct vb2_fileio_buf {
1482 	void *vaddr;
1483 	unsigned int size;
1484 	unsigned int pos;
1485 	unsigned int queued:1;
1486 };
1487 
1488 /**
1489  * struct vb2_fileio_data - queue context used by file io emulator
1490  *
1491  * vb2 provides a compatibility layer and emulator of file io (read and
1492  * write) calls on top of streaming API. For proper operation it required
1493  * this structure to save the driver state between each call of the read
1494  * or write function.
1495  */
1496 struct vb2_fileio_data {
1497 	struct v4l2_requestbuffers req;
1498 	struct v4l2_buffer b;
1499 	struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
1500 	unsigned int index;
1501 	unsigned int q_count;
1502 	unsigned int dq_count;
1503 	unsigned int flags;
1504 };
1505 
1506 /**
1507  * __vb2_init_fileio() - initialize file io emulator
1508  * @q:		videobuf2 queue
1509  * @read:	mode selector (1 means read, 0 means write)
1510  */
__vb2_init_fileio(struct vb2_queue * q,int read)1511 static int __vb2_init_fileio(struct vb2_queue *q, int read)
1512 {
1513 	struct vb2_fileio_data *fileio;
1514 	int i, ret;
1515 	unsigned int count = 0;
1516 
1517 	/*
1518 	 * Sanity check
1519 	 */
1520 	if ((read && !(q->io_modes & VB2_READ)) ||
1521 	   (!read && !(q->io_modes & VB2_WRITE)))
1522 		BUG();
1523 
1524 	/*
1525 	 * Check if device supports mapping buffers to kernel virtual space.
1526 	 */
1527 	if (!q->mem_ops->vaddr)
1528 		return -EBUSY;
1529 
1530 	/*
1531 	 * Check if streaming api has not been already activated.
1532 	 */
1533 	if (q->streaming || q->num_buffers > 0)
1534 		return -EBUSY;
1535 
1536 	/*
1537 	 * Start with count 1, driver can increase it in queue_setup()
1538 	 */
1539 	count = 1;
1540 
1541 	dprintk(3, "setting up file io: mode %s, count %d, flags %08x\n",
1542 		(read) ? "read" : "write", count, q->io_flags);
1543 
1544 	fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
1545 	if (fileio == NULL)
1546 		return -ENOMEM;
1547 
1548 	fileio->flags = q->io_flags;
1549 
1550 	/*
1551 	 * Request buffers and use MMAP type to force driver
1552 	 * to allocate buffers by itself.
1553 	 */
1554 	fileio->req.count = count;
1555 	fileio->req.memory = V4L2_MEMORY_MMAP;
1556 	fileio->req.type = q->type;
1557 	ret = vb2_reqbufs(q, &fileio->req);
1558 	if (ret)
1559 		goto err_kfree;
1560 
1561 	/*
1562 	 * Check if plane_count is correct
1563 	 * (multiplane buffers are not supported).
1564 	 */
1565 	if (q->bufs[0]->num_planes != 1) {
1566 		fileio->req.count = 0;
1567 		ret = -EBUSY;
1568 		goto err_reqbufs;
1569 	}
1570 
1571 	/*
1572 	 * Get kernel address of each buffer.
1573 	 */
1574 	for (i = 0; i < q->num_buffers; i++) {
1575 		fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
1576 		if (fileio->bufs[i].vaddr == NULL)
1577 			goto err_reqbufs;
1578 		fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
1579 	}
1580 
1581 	/*
1582 	 * Read mode requires pre queuing of all buffers.
1583 	 */
1584 	if (read) {
1585 		/*
1586 		 * Queue all buffers.
1587 		 */
1588 		for (i = 0; i < q->num_buffers; i++) {
1589 			struct v4l2_buffer *b = &fileio->b;
1590 			memset(b, 0, sizeof(*b));
1591 			b->type = q->type;
1592 			b->memory = q->memory;
1593 			b->index = i;
1594 			ret = vb2_qbuf(q, b);
1595 			if (ret)
1596 				goto err_reqbufs;
1597 			fileio->bufs[i].queued = 1;
1598 		}
1599 
1600 		/*
1601 		 * Start streaming.
1602 		 */
1603 		ret = vb2_streamon(q, q->type);
1604 		if (ret)
1605 			goto err_reqbufs;
1606 	}
1607 
1608 	q->fileio = fileio;
1609 
1610 	return ret;
1611 
1612 err_reqbufs:
1613 	vb2_reqbufs(q, &fileio->req);
1614 
1615 err_kfree:
1616 	kfree(fileio);
1617 	return ret;
1618 }
1619 
1620 /**
1621  * __vb2_cleanup_fileio() - free resourced used by file io emulator
1622  * @q:		videobuf2 queue
1623  */
__vb2_cleanup_fileio(struct vb2_queue * q)1624 static int __vb2_cleanup_fileio(struct vb2_queue *q)
1625 {
1626 	struct vb2_fileio_data *fileio = q->fileio;
1627 
1628 	if (fileio) {
1629 		/*
1630 		 * Hack fileio context to enable direct calls to vb2 ioctl
1631 		 * interface.
1632 		 */
1633 		q->fileio = NULL;
1634 
1635 		vb2_streamoff(q, q->type);
1636 		fileio->req.count = 0;
1637 		vb2_reqbufs(q, &fileio->req);
1638 		kfree(fileio);
1639 		dprintk(3, "file io emulator closed\n");
1640 	}
1641 	return 0;
1642 }
1643 
1644 /**
1645  * __vb2_perform_fileio() - perform a single file io (read or write) operation
1646  * @q:		videobuf2 queue
1647  * @data:	pointed to target userspace buffer
1648  * @count:	number of bytes to read or write
1649  * @ppos:	file handle position tracking pointer
1650  * @nonblock:	mode selector (1 means blocking calls, 0 means nonblocking)
1651  * @read:	access mode selector (1 means read, 0 means write)
1652  */
__vb2_perform_fileio(struct vb2_queue * q,char __user * data,size_t count,loff_t * ppos,int nonblock,int read)1653 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
1654 		loff_t *ppos, int nonblock, int read)
1655 {
1656 	struct vb2_fileio_data *fileio;
1657 	struct vb2_fileio_buf *buf;
1658 	int ret, index;
1659 
1660 	dprintk(3, "file io: mode %s, offset %ld, count %zd, %sblocking\n",
1661 		read ? "read" : "write", (long)*ppos, count,
1662 		nonblock ? "non" : "");
1663 
1664 	if (!data)
1665 		return -EINVAL;
1666 
1667 	/*
1668 	 * Initialize emulator on first call.
1669 	 */
1670 	if (!q->fileio) {
1671 		ret = __vb2_init_fileio(q, read);
1672 		dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
1673 		if (ret)
1674 			return ret;
1675 	}
1676 	fileio = q->fileio;
1677 
1678 	/*
1679 	 * Hack fileio context to enable direct calls to vb2 ioctl interface.
1680 	 * The pointer will be restored before returning from this function.
1681 	 */
1682 	q->fileio = NULL;
1683 
1684 	index = fileio->index;
1685 	buf = &fileio->bufs[index];
1686 
1687 	/*
1688 	 * Check if we need to dequeue the buffer.
1689 	 */
1690 	if (buf->queued) {
1691 		struct vb2_buffer *vb;
1692 
1693 		/*
1694 		 * Call vb2_dqbuf to get buffer back.
1695 		 */
1696 		memset(&fileio->b, 0, sizeof(fileio->b));
1697 		fileio->b.type = q->type;
1698 		fileio->b.memory = q->memory;
1699 		fileio->b.index = index;
1700 		ret = vb2_dqbuf(q, &fileio->b, nonblock);
1701 		dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
1702 		if (ret)
1703 			goto end;
1704 		fileio->dq_count += 1;
1705 
1706 		/*
1707 		 * Get number of bytes filled by the driver
1708 		 */
1709 		vb = q->bufs[index];
1710 		buf->size = vb2_get_plane_payload(vb, 0);
1711 		buf->queued = 0;
1712 	}
1713 
1714 	/*
1715 	 * Limit count on last few bytes of the buffer.
1716 	 */
1717 	if (buf->pos + count > buf->size) {
1718 		count = buf->size - buf->pos;
1719 		dprintk(5, "reducing read count: %zd\n", count);
1720 	}
1721 
1722 	/*
1723 	 * Transfer data to userspace.
1724 	 */
1725 	dprintk(3, "file io: copying %zd bytes - buffer %d, offset %u\n",
1726 		count, index, buf->pos);
1727 	if (read)
1728 		ret = copy_to_user(data, buf->vaddr + buf->pos, count);
1729 	else
1730 		ret = copy_from_user(buf->vaddr + buf->pos, data, count);
1731 	if (ret) {
1732 		dprintk(3, "file io: error copying data\n");
1733 		ret = -EFAULT;
1734 		goto end;
1735 	}
1736 
1737 	/*
1738 	 * Update counters.
1739 	 */
1740 	buf->pos += count;
1741 	*ppos += count;
1742 
1743 	/*
1744 	 * Queue next buffer if required.
1745 	 */
1746 	if (buf->pos == buf->size ||
1747 	   (!read && (fileio->flags & VB2_FILEIO_WRITE_IMMEDIATELY))) {
1748 		/*
1749 		 * Check if this is the last buffer to read.
1750 		 */
1751 		if (read && (fileio->flags & VB2_FILEIO_READ_ONCE) &&
1752 		    fileio->dq_count == 1) {
1753 			dprintk(3, "file io: read limit reached\n");
1754 			/*
1755 			 * Restore fileio pointer and release the context.
1756 			 */
1757 			q->fileio = fileio;
1758 			return __vb2_cleanup_fileio(q);
1759 		}
1760 
1761 		/*
1762 		 * Call vb2_qbuf and give buffer to the driver.
1763 		 */
1764 		memset(&fileio->b, 0, sizeof(fileio->b));
1765 		fileio->b.type = q->type;
1766 		fileio->b.memory = q->memory;
1767 		fileio->b.index = index;
1768 		fileio->b.bytesused = buf->pos;
1769 		ret = vb2_qbuf(q, &fileio->b);
1770 		dprintk(5, "file io: vb2_dbuf result: %d\n", ret);
1771 		if (ret)
1772 			goto end;
1773 
1774 		/*
1775 		 * Buffer has been queued, update the status
1776 		 */
1777 		buf->pos = 0;
1778 		buf->queued = 1;
1779 		buf->size = q->bufs[0]->v4l2_planes[0].length;
1780 		fileio->q_count += 1;
1781 
1782 		/*
1783 		 * Switch to the next buffer
1784 		 */
1785 		fileio->index = (index + 1) % q->num_buffers;
1786 
1787 		/*
1788 		 * Start streaming if required.
1789 		 */
1790 		if (!read && !q->streaming) {
1791 			ret = vb2_streamon(q, q->type);
1792 			if (ret)
1793 				goto end;
1794 		}
1795 	}
1796 
1797 	/*
1798 	 * Return proper number of bytes processed.
1799 	 */
1800 	if (ret == 0)
1801 		ret = count;
1802 end:
1803 	/*
1804 	 * Restore the fileio context and block vb2 ioctl interface.
1805 	 */
1806 	q->fileio = fileio;
1807 	return ret;
1808 }
1809 
vb2_read(struct vb2_queue * q,char __user * data,size_t count,loff_t * ppos,int nonblocking)1810 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
1811 		loff_t *ppos, int nonblocking)
1812 {
1813 	return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
1814 }
1815 EXPORT_SYMBOL_GPL(vb2_read);
1816 
vb2_write(struct vb2_queue * q,char __user * data,size_t count,loff_t * ppos,int nonblocking)1817 size_t vb2_write(struct vb2_queue *q, char __user *data, size_t count,
1818 		loff_t *ppos, int nonblocking)
1819 {
1820 	return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 0);
1821 }
1822 EXPORT_SYMBOL_GPL(vb2_write);
1823 
1824 MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
1825 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
1826 MODULE_LICENSE("GPL");
1827