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