videobuf2-core.c 74.8 KB
Newer Older
1 2 3 4 5
/*
 * videobuf2-core.c - V4L2 driver helper framework
 *
 * Copyright (C) 2010 Samsung Electronics
 *
6
 * Author: Pawel Osciak <pawel@osciak.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *	   Marek Szyprowski <m.szyprowski@samsung.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation.
 */

#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/sched.h>

22 23 24
#include <media/v4l2-dev.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
25 26 27 28 29 30 31 32 33 34 35
#include <media/videobuf2-core.h>

static int debug;
module_param(debug, int, 0644);

#define dprintk(level, fmt, arg...)					\
	do {								\
		if (debug >= level)					\
			printk(KERN_DEBUG "vb2: " fmt, ## arg);		\
	} while (0)

36
#define call_memop(q, op, args...)					\
37 38 39 40 41 42
	(((q)->mem_ops->op) ?						\
		((q)->mem_ops->op(args)) : 0)

#define call_qop(q, op, args...)					\
	(((q)->ops->op) ? ((q)->ops->op(args)) : 0)

43
#define V4L2_BUFFER_MASK_FLAGS	(V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
44
				 V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
45 46
				 V4L2_BUF_FLAG_PREPARED | \
				 V4L2_BUF_FLAG_TIMESTAMP_MASK)
47

48 49 50
/**
 * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
 */
51
static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
52 53 54 55 56
{
	struct vb2_queue *q = vb->vb2_queue;
	void *mem_priv;
	int plane;

57 58 59 60
	/*
	 * Allocate memory for all planes in this buffer
	 * NOTE: mmapped areas should be page aligned
	 */
61
	for (plane = 0; plane < vb->num_planes; ++plane) {
62 63
		unsigned long size = PAGE_ALIGN(q->plane_sizes[plane]);

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 68 69 70
			goto free;

		/* Associate allocator private data with this plane */
		vb->planes[plane].mem_priv = mem_priv;
71
		vb->v4l2_planes[plane].length = q->plane_sizes[plane];
72 73 74 75 76
	}

	return 0;
free:
	/* 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 80
		vb->planes[plane - 1].mem_priv = NULL;
	}
81 82 83 84 85 86 87 88 89 90 91 92 93

	return -ENOMEM;
}

/**
 * __vb2_buf_mem_free() - free memory of the given buffer
 */
static void __vb2_buf_mem_free(struct vb2_buffer *vb)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned int plane;

	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 97
		dprintk(3, "Freed plane %d of buffer %d\n", plane,
			vb->v4l2_buf.index);
98 99 100 101 102 103 104 105 106 107 108 109 110
	}
}

/**
 * __vb2_buf_userptr_put() - release userspace memory associated with
 * a USERPTR buffer
 */
static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned int plane;

	for (plane = 0; plane < vb->num_planes; ++plane) {
111 112 113
		if (vb->planes[plane].mem_priv)
			call_memop(q, put_userptr, vb->planes[plane].mem_priv);
		vb->planes[plane].mem_priv = NULL;
114 115 116
	}
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
/**
 * __vb2_plane_dmabuf_put() - release memory associated with
 * a DMABUF shared plane
 */
static void __vb2_plane_dmabuf_put(struct vb2_queue *q, struct vb2_plane *p)
{
	if (!p->mem_priv)
		return;

	if (p->dbuf_mapped)
		call_memop(q, unmap_dmabuf, p->mem_priv);

	call_memop(q, detach_dmabuf, p->mem_priv);
	dma_buf_put(p->dbuf);
	memset(p, 0, sizeof(*p));
}

/**
 * __vb2_buf_dmabuf_put() - release memory associated with
 * a DMABUF shared buffer
 */
static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned int plane;

	for (plane = 0; plane < vb->num_planes; ++plane)
		__vb2_plane_dmabuf_put(q, &vb->planes[plane]);
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/**
 * __setup_lengths() - setup initial lengths for every plane in
 * every buffer on the queue
 */
static void __setup_lengths(struct vb2_queue *q, unsigned int n)
{
	unsigned int buffer, plane;
	struct vb2_buffer *vb;

	for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
		vb = q->bufs[buffer];
		if (!vb)
			continue;

		for (plane = 0; plane < vb->num_planes; ++plane)
			vb->v4l2_planes[plane].length = q->plane_sizes[plane];
	}
}

166 167 168 169
/**
 * __setup_offsets() - setup unique offsets ("cookies") for every plane in
 * every buffer on the queue
 */
170
static void __setup_offsets(struct vb2_queue *q, unsigned int n)
171 172 173
{
	unsigned int buffer, plane;
	struct vb2_buffer *vb;
174
	unsigned long off;
175

176 177 178 179 180 181 182 183 184 185
	if (q->num_buffers) {
		struct v4l2_plane *p;
		vb = q->bufs[q->num_buffers - 1];
		p = &vb->v4l2_planes[vb->num_planes - 1];
		off = PAGE_ALIGN(p->m.mem_offset + p->length);
	} else {
		off = 0;
	}

	for (buffer = q->num_buffers; buffer < q->num_buffers + n; ++buffer) {
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
		vb = q->bufs[buffer];
		if (!vb)
			continue;

		for (plane = 0; plane < vb->num_planes; ++plane) {
			vb->v4l2_planes[plane].m.mem_offset = off;

			dprintk(3, "Buffer %d, plane %d offset 0x%08lx\n",
					buffer, plane, off);

			off += vb->v4l2_planes[plane].length;
			off = PAGE_ALIGN(off);
		}
	}
}

/**
 * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
 * video buffer memory for all buffers/planes on the queue and initializes the
 * queue
 *
 * Returns the number of buffers successfully allocated.
 */
static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
210
			     unsigned int num_buffers, unsigned int num_planes)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
{
	unsigned int buffer;
	struct vb2_buffer *vb;
	int ret;

	for (buffer = 0; buffer < num_buffers; ++buffer) {
		/* Allocate videobuf buffer structures */
		vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
		if (!vb) {
			dprintk(1, "Memory alloc for buffer struct failed\n");
			break;
		}

		/* Length stores number of planes for multiplanar buffers */
		if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
			vb->v4l2_buf.length = num_planes;

		vb->state = VB2_BUF_STATE_DEQUEUED;
		vb->vb2_queue = q;
		vb->num_planes = num_planes;
231
		vb->v4l2_buf.index = q->num_buffers + buffer;
232 233 234 235 236
		vb->v4l2_buf.type = q->type;
		vb->v4l2_buf.memory = memory;

		/* Allocate video buffer memory for the MMAP type */
		if (memory == V4L2_MEMORY_MMAP) {
237
			ret = __vb2_buf_mem_alloc(vb);
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
			if (ret) {
				dprintk(1, "Failed allocating memory for "
						"buffer %d\n", buffer);
				kfree(vb);
				break;
			}
			/*
			 * Call the driver-provided buffer initialization
			 * callback, if given. An error in initialization
			 * results in queue setup failure.
			 */
			ret = call_qop(q, buf_init, vb);
			if (ret) {
				dprintk(1, "Buffer %d %p initialization"
					" failed\n", buffer, vb);
				__vb2_buf_mem_free(vb);
				kfree(vb);
				break;
			}
		}

259
		q->bufs[q->num_buffers + buffer] = vb;
260 261
	}

262
	__setup_lengths(q, buffer);
263 264
	if (memory == V4L2_MEMORY_MMAP)
		__setup_offsets(q, buffer);
265 266

	dprintk(1, "Allocated %d buffers, %d plane(s) each\n",
267
			buffer, num_planes);
268 269 270 271 272 273 274

	return buffer;
}

/**
 * __vb2_free_mem() - release all video buffer memory for a given queue
 */
275
static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
276 277 278 279
{
	unsigned int buffer;
	struct vb2_buffer *vb;

280 281
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
282 283 284 285 286 287 288
		vb = q->bufs[buffer];
		if (!vb)
			continue;

		/* Free MMAP buffers or release USERPTR buffers */
		if (q->memory == V4L2_MEMORY_MMAP)
			__vb2_buf_mem_free(vb);
289 290
		else if (q->memory == V4L2_MEMORY_DMABUF)
			__vb2_buf_dmabuf_put(vb);
291 292 293 294 295 296
		else
			__vb2_buf_userptr_put(vb);
	}
}

/**
297 298 299
 * __vb2_queue_free() - free buffers at the end of the queue - video memory and
 * related information, if no buffers are left return the queue to an
 * uninitialized state. Might be called even if the queue has already been freed.
300
 */
301
static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
302 303 304
{
	unsigned int buffer;

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	/*
	 * Sanity check: when preparing a buffer the queue lock is released for
	 * a short while (see __buf_prepare for the details), which would allow
	 * a race with a reqbufs which can call this function. Removing the
	 * buffers from underneath __buf_prepare is obviously a bad idea, so we
	 * check if any of the buffers is in the state PREPARING, and if so we
	 * just return -EAGAIN.
	 */
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
		if (q->bufs[buffer] == NULL)
			continue;
		if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
			dprintk(1, "reqbufs: preparing buffers, cannot free\n");
			return -EAGAIN;
		}
	}

323 324
	/* Call driver-provided cleanup function for each buffer, if provided */
	if (q->ops->buf_cleanup) {
325 326
		for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
		     ++buffer) {
327 328 329 330 331 332 333
			if (NULL == q->bufs[buffer])
				continue;
			q->ops->buf_cleanup(q->bufs[buffer]);
		}
	}

	/* Release video buffer memory */
334
	__vb2_free_mem(q, buffers);
335 336

	/* Free videobuf buffers */
337 338
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
339 340 341 342
		kfree(q->bufs[buffer]);
		q->bufs[buffer] = NULL;
	}

343 344 345
	q->num_buffers -= buffers;
	if (!q->num_buffers)
		q->memory = 0;
346
	INIT_LIST_HEAD(&q->queued_list);
347
	return 0;
348 349 350 351 352 353
}

/**
 * __verify_planes_array() - verify that the planes array passed in struct
 * v4l2_buffer from userspace can be safely used
 */
354
static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
355
{
356 357 358
	if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
		return 0;

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
	/* Is memory for copying plane information present? */
	if (NULL == b->m.planes) {
		dprintk(1, "Multi-planar buffer passed but "
			   "planes array not provided\n");
		return -EINVAL;
	}

	if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
		dprintk(1, "Incorrect planes array length, "
			   "expected %d, got %d\n", vb->num_planes, b->length);
		return -EINVAL;
	}

	return 0;
}

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
/**
 * __verify_length() - Verify that the bytesused value for each plane fits in
 * the plane length and that the data offset doesn't exceed the bytesused value.
 */
static int __verify_length(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
	unsigned int length;
	unsigned int plane;

	if (!V4L2_TYPE_IS_OUTPUT(b->type))
		return 0;

	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
		for (plane = 0; plane < vb->num_planes; ++plane) {
			length = (b->memory == V4L2_MEMORY_USERPTR)
			       ? b->m.planes[plane].length
			       : vb->v4l2_planes[plane].length;

			if (b->m.planes[plane].bytesused > length)
				return -EINVAL;
395 396 397

			if (b->m.planes[plane].data_offset > 0 &&
			    b->m.planes[plane].data_offset >=
398 399 400 401 402 403 404 405 406 407 408 409 410 411
			    b->m.planes[plane].bytesused)
				return -EINVAL;
		}
	} else {
		length = (b->memory == V4L2_MEMORY_USERPTR)
		       ? b->length : vb->v4l2_planes[0].length;

		if (b->bytesused > length)
			return -EINVAL;
	}

	return 0;
}

412 413 414 415 416 417 418 419
/**
 * __buffer_in_use() - return true if the buffer is in use and
 * the queue cannot be freed (by the means of REQBUFS(0)) call
 */
static bool __buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
{
	unsigned int plane;
	for (plane = 0; plane < vb->num_planes; ++plane) {
420
		void *mem_priv = vb->planes[plane].mem_priv;
421 422 423 424 425 426
		/*
		 * If num_users() has not been provided, call_memop
		 * will return 0, apparently nobody cares about this
		 * case anyway. If num_users() returns more than 1,
		 * we are not the only user of the plane's memory.
		 */
427
		if (mem_priv && call_memop(q, num_users, mem_priv) > 1)
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
			return true;
	}
	return false;
}

/**
 * __buffers_in_use() - return true if any buffers on the queue are in use and
 * the queue cannot be freed (by the means of REQBUFS(0)) call
 */
static bool __buffers_in_use(struct vb2_queue *q)
{
	unsigned int buffer;
	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
		if (__buffer_in_use(q, q->bufs[buffer]))
			return true;
	}
	return false;
}

447 448 449 450
/**
 * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
 * returned to userspace
 */
451
static void __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
452 453 454
{
	struct vb2_queue *q = vb->vb2_queue;

455
	/* Copy back data such as timestamp, flags, etc. */
456
	memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
457
	b->reserved2 = vb->v4l2_buf.reserved2;
458 459 460 461 462
	b->reserved = vb->v4l2_buf.reserved;

	if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
		/*
		 * Fill in plane-related data if userspace provided an array
463
		 * for it. The caller has already verified memory and size.
464
		 */
465
		b->length = vb->num_planes;
466 467 468 469 470 471 472 473 474 475 476 477 478
		memcpy(b->m.planes, vb->v4l2_planes,
			b->length * sizeof(struct v4l2_plane));
	} else {
		/*
		 * We use length and offset in v4l2_planes array even for
		 * single-planar buffers, but userspace does not.
		 */
		b->length = vb->v4l2_planes[0].length;
		b->bytesused = vb->v4l2_planes[0].bytesused;
		if (q->memory == V4L2_MEMORY_MMAP)
			b->m.offset = vb->v4l2_planes[0].m.mem_offset;
		else if (q->memory == V4L2_MEMORY_USERPTR)
			b->m.userptr = vb->v4l2_planes[0].m.userptr;
479 480
		else if (q->memory == V4L2_MEMORY_DMABUF)
			b->m.fd = vb->v4l2_planes[0].m.fd;
481 482
	}

483 484 485
	/*
	 * Clear any buffer state related flags.
	 */
486
	b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
487
	b->flags |= q->timestamp_type;
488 489 490 491 492 493 494 495 496 497 498 499

	switch (vb->state) {
	case VB2_BUF_STATE_QUEUED:
	case VB2_BUF_STATE_ACTIVE:
		b->flags |= V4L2_BUF_FLAG_QUEUED;
		break;
	case VB2_BUF_STATE_ERROR:
		b->flags |= V4L2_BUF_FLAG_ERROR;
		/* fall through */
	case VB2_BUF_STATE_DONE:
		b->flags |= V4L2_BUF_FLAG_DONE;
		break;
500
	case VB2_BUF_STATE_PREPARED:
501 502
		b->flags |= V4L2_BUF_FLAG_PREPARED;
		break;
503
	case VB2_BUF_STATE_PREPARING:
504
	case VB2_BUF_STATE_DEQUEUED:
505 506 507 508
		/* nothing */
		break;
	}

509
	if (__buffer_in_use(q, vb))
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
		b->flags |= V4L2_BUF_FLAG_MAPPED;
}

/**
 * vb2_querybuf() - query video buffer information
 * @q:		videobuf queue
 * @b:		buffer struct passed from userspace to vidioc_querybuf handler
 *		in driver
 *
 * Should be called from vidioc_querybuf ioctl handler in driver.
 * This function will verify the passed v4l2_buffer structure and fill the
 * relevant information for the userspace.
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_querybuf handler in driver.
 */
int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
	struct vb2_buffer *vb;
529
	int ret;
530 531 532 533 534 535 536 537 538 539 540

	if (b->type != q->type) {
		dprintk(1, "querybuf: wrong buffer type\n");
		return -EINVAL;
	}

	if (b->index >= q->num_buffers) {
		dprintk(1, "querybuf: buffer index out of range\n");
		return -EINVAL;
	}
	vb = q->bufs[b->index];
541 542 543 544
	ret = __verify_planes_array(vb, b);
	if (!ret)
		__fill_v4l2_buffer(vb, b);
	return ret;
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
}
EXPORT_SYMBOL(vb2_querybuf);

/**
 * __verify_userptr_ops() - verify that all memory operations required for
 * USERPTR queue type have been provided
 */
static int __verify_userptr_ops(struct vb2_queue *q)
{
	if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
	    !q->mem_ops->put_userptr)
		return -EINVAL;

	return 0;
}

/**
 * __verify_mmap_ops() - verify that all memory operations required for
 * MMAP queue type have been provided
 */
static int __verify_mmap_ops(struct vb2_queue *q)
{
	if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
	    !q->mem_ops->put || !q->mem_ops->mmap)
		return -EINVAL;

	return 0;
}

574 575 576 577 578 579 580 581 582 583 584 585 586 587
/**
 * __verify_dmabuf_ops() - verify that all memory operations required for
 * DMABUF queue type have been provided
 */
static int __verify_dmabuf_ops(struct vb2_queue *q)
{
	if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
	    !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
	    !q->mem_ops->unmap_dmabuf)
		return -EINVAL;

	return 0;
}

588
/**
589 590 591 592 593 594
 * __verify_memory_type() - Check whether the memory type and buffer type
 * passed to a buffer operation are compatible with the queue.
 */
static int __verify_memory_type(struct vb2_queue *q,
		enum v4l2_memory memory, enum v4l2_buf_type type)
{
595 596
	if (memory != V4L2_MEMORY_MMAP && memory != V4L2_MEMORY_USERPTR &&
	    memory != V4L2_MEMORY_DMABUF) {
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
		dprintk(1, "reqbufs: unsupported memory type\n");
		return -EINVAL;
	}

	if (type != q->type) {
		dprintk(1, "reqbufs: requested type is incorrect\n");
		return -EINVAL;
	}

	/*
	 * Make sure all the required memory ops for given memory type
	 * are available.
	 */
	if (memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
		dprintk(1, "reqbufs: MMAP for current setup unsupported\n");
		return -EINVAL;
	}

	if (memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
		dprintk(1, "reqbufs: USERPTR for current setup unsupported\n");
		return -EINVAL;
	}

620 621 622 623 624
	if (memory == V4L2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
		dprintk(1, "reqbufs: DMABUF for current setup unsupported\n");
		return -EINVAL;
	}

625 626 627 628 629 630 631 632 633 634 635 636 637 638
	/*
	 * Place the busy tests at the end: -EBUSY can be ignored when
	 * create_bufs is called with count == 0, but count == 0 should still
	 * do the memory and type validation.
	 */
	if (q->fileio) {
		dprintk(1, "reqbufs: file io in progress\n");
		return -EBUSY;
	}
	return 0;
}

/**
 * __reqbufs() - Initiate streaming
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
 * @q:		videobuf2 queue
 * @req:	struct passed from userspace to vidioc_reqbufs handler in driver
 *
 * Should be called from vidioc_reqbufs ioctl handler of a driver.
 * This function:
 * 1) verifies streaming parameters passed from the userspace,
 * 2) sets up the queue,
 * 3) negotiates number of buffers and planes per buffer with the driver
 *    to be used during streaming,
 * 4) allocates internal buffer structures (struct vb2_buffer), according to
 *    the agreed parameters,
 * 5) for MMAP memory type, allocates actual video memory, using the
 *    memory handling/allocation routines provided during queue initialization
 *
 * If req->count is 0, all the memory will be freed instead.
 * If the queue has been allocated previously (by a previous vb2_reqbufs) call
 * and the queue is not busy, memory will be reallocated.
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_reqbufs handler in driver.
 */
660
static int __reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
661
{
662
	unsigned int num_buffers, allocated_buffers, num_planes = 0;
663
	int ret;
664 665 666 667 668 669

	if (q->streaming) {
		dprintk(1, "reqbufs: streaming active\n");
		return -EBUSY;
	}

670
	if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
671 672 673 674 675 676 677 678 679
		/*
		 * We already have buffers allocated, so first check if they
		 * are not in use and can be freed.
		 */
		if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
			dprintk(1, "reqbufs: memory in use, cannot free\n");
			return -EBUSY;
		}

680 681 682
		ret = __vb2_queue_free(q, q->num_buffers);
		if (ret)
			return ret;
683 684 685 686 687 688 689

		/*
		 * In case of REQBUFS(0) return immediately without calling
		 * driver's queue_setup() callback and allocating resources.
		 */
		if (req->count == 0)
			return 0;
690 691 692 693 694 695
	}

	/*
	 * Make sure the requested values and current defaults are sane.
	 */
	num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
696
	memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
697
	memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
698
	q->memory = req->memory;
699 700 701 702 703

	/*
	 * Ask the driver how many buffers and planes per buffer it requires.
	 * Driver also sets the size and allocator context for each plane.
	 */
704
	ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
705
		       q->plane_sizes, q->alloc_ctx);
706 707 708 709
	if (ret)
		return ret;

	/* Finally, allocate buffers and video memory */
710
	ret = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes);
711 712 713
	if (ret == 0) {
		dprintk(1, "Memory allocation failed\n");
		return -ENOMEM;
714 715
	}

716 717
	allocated_buffers = ret;

718 719 720
	/*
	 * Check if driver can handle the allocated number of buffers.
	 */
721 722
	if (allocated_buffers < num_buffers) {
		num_buffers = allocated_buffers;
723

724 725
		ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
			       &num_planes, q->plane_sizes, q->alloc_ctx);
726

727
		if (!ret && allocated_buffers < num_buffers)
728 729 730
			ret = -ENOMEM;

		/*
731 732
		 * Either the driver has accepted a smaller number of buffers,
		 * or .queue_setup() returned an error
733
		 */
734 735 736 737 738 739 740
	}

	q->num_buffers = allocated_buffers;

	if (ret < 0) {
		__vb2_queue_free(q, allocated_buffers);
		return ret;
741 742 743 744 745 746
	}

	/*
	 * Return the number of successfully allocated buffers
	 * to the userspace.
	 */
747
	req->count = allocated_buffers;
748 749 750

	return 0;
}
751 752 753 754 755 756 757 758 759 760 761 762 763

/**
 * vb2_reqbufs() - Wrapper for __reqbufs() that also verifies the memory and
 * type values.
 * @q:		videobuf2 queue
 * @req:	struct passed from userspace to vidioc_reqbufs handler in driver
 */
int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
{
	int ret = __verify_memory_type(q, req->memory, req->type);

	return ret ? ret : __reqbufs(q, req);
}
764 765
EXPORT_SYMBOL_GPL(vb2_reqbufs);

766
/**
767
 * __create_bufs() - Allocate buffers and any required auxiliary structs
768 769 770 771 772 773 774 775 776 777 778 779 780
 * @q:		videobuf2 queue
 * @create:	creation parameters, passed from userspace to vidioc_create_bufs
 *		handler in driver
 *
 * Should be called from vidioc_create_bufs ioctl handler of a driver.
 * This function:
 * 1) verifies parameter sanity
 * 2) calls the .queue_setup() queue operation
 * 3) performs any necessary memory allocations
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_create_bufs handler in driver.
 */
781
static int __create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
782 783
{
	unsigned int num_planes = 0, num_buffers, allocated_buffers;
784
	int ret;
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

	if (q->num_buffers == VIDEO_MAX_FRAME) {
		dprintk(1, "%s(): maximum number of buffers already allocated\n",
			__func__);
		return -ENOBUFS;
	}

	if (!q->num_buffers) {
		memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
		memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
		q->memory = create->memory;
	}

	num_buffers = min(create->count, VIDEO_MAX_FRAME - q->num_buffers);

	/*
	 * Ask the driver, whether the requested number of buffers, planes per
	 * buffer and their sizes are acceptable
	 */
	ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
		       &num_planes, q->plane_sizes, q->alloc_ctx);
	if (ret)
		return ret;

	/* Finally, allocate buffers and video memory */
	ret = __vb2_queue_alloc(q, create->memory, num_buffers,
				num_planes);
812 813 814
	if (ret == 0) {
		dprintk(1, "Memory allocation failed\n");
		return -ENOMEM;
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
	}

	allocated_buffers = ret;

	/*
	 * Check if driver can handle the so far allocated number of buffers.
	 */
	if (ret < num_buffers) {
		num_buffers = ret;

		/*
		 * q->num_buffers contains the total number of buffers, that the
		 * queue driver has set up
		 */
		ret = call_qop(q, queue_setup, q, &create->format, &num_buffers,
			       &num_planes, q->plane_sizes, q->alloc_ctx);

		if (!ret && allocated_buffers < num_buffers)
			ret = -ENOMEM;

		/*
		 * Either the driver has accepted a smaller number of buffers,
		 * or .queue_setup() returned an error
		 */
	}

	q->num_buffers += allocated_buffers;

	if (ret < 0) {
		__vb2_queue_free(q, allocated_buffers);
845
		return -ENOMEM;
846 847 848 849 850 851 852 853 854 855
	}

	/*
	 * Return the number of successfully allocated buffers
	 * to the userspace.
	 */
	create->count = allocated_buffers;

	return 0;
}
856 857

/**
858 859
 * vb2_create_bufs() - Wrapper for __create_bufs() that also verifies the
 * memory and type values.
860 861 862 863 864 865 866 867 868
 * @q:		videobuf2 queue
 * @create:	creation parameters, passed from userspace to vidioc_create_bufs
 *		handler in driver
 */
int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
{
	int ret = __verify_memory_type(q, create->memory, create->format.type);

	create->index = q->num_buffers;
869 870
	if (create->count == 0)
		return ret != -EBUSY ? ret : 0;
871 872
	return ret ? ret : __create_bufs(q, create);
}
873 874
EXPORT_SYMBOL_GPL(vb2_create_bufs);

875 876 877 878 879 880 881 882 883 884 885 886
/**
 * vb2_plane_vaddr() - Return a kernel virtual address of a given plane
 * @vb:		vb2_buffer to which the plane in question belongs to
 * @plane_no:	plane number for which the address is to be returned
 *
 * This function returns a kernel virtual address of a given plane if
 * such a mapping exist, NULL otherwise.
 */
void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
{
	struct vb2_queue *q = vb->vb2_queue;

887
	if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
888 889
		return NULL;

890
	return call_memop(q, vaddr, vb->planes[plane_no].mem_priv);
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909

}
EXPORT_SYMBOL_GPL(vb2_plane_vaddr);

/**
 * vb2_plane_cookie() - Return allocator specific cookie for the given plane
 * @vb:		vb2_buffer to which the plane in question belongs to
 * @plane_no:	plane number for which the cookie is to be returned
 *
 * This function returns an allocator specific cookie for a given plane if
 * available, NULL otherwise. The allocator should provide some simple static
 * inline function, which would convert this cookie to the allocator specific
 * type that can be used directly by the driver to access the buffer. This can
 * be for example physical address, pointer to scatter list or IOMMU mapping.
 */
void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
{
	struct vb2_queue *q = vb->vb2_queue;

910
	if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
911 912
		return NULL;

913
	return call_memop(q, cookie, vb->planes[plane_no].mem_priv);
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
}
EXPORT_SYMBOL_GPL(vb2_plane_cookie);

/**
 * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
 * @vb:		vb2_buffer returned from the driver
 * @state:	either VB2_BUF_STATE_DONE if the operation finished successfully
 *		or VB2_BUF_STATE_ERROR if the operation finished with an error
 *
 * This function should be called by the driver after a hardware operation on
 * a buffer is finished and the buffer may be returned to userspace. The driver
 * cannot use this buffer anymore until it is queued back to it by videobuf
 * by the means of buf_queue callback. Only buffers previously queued to the
 * driver by buf_queue can be passed to this function.
 */
void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned long flags;
933
	unsigned int plane;
934 935 936 937 938 939 940 941

	if (vb->state != VB2_BUF_STATE_ACTIVE)
		return;

	if (state != VB2_BUF_STATE_DONE && state != VB2_BUF_STATE_ERROR)
		return;

	dprintk(4, "Done processing on buffer %d, state: %d\n",
942
			vb->v4l2_buf.index, state);
943

944 945 946 947
	/* sync buffers */
	for (plane = 0; plane < vb->num_planes; ++plane)
		call_memop(q, finish, vb->planes[plane].mem_priv);

948 949 950 951 952 953 954 955 956 957 958 959 960
	/* Add the buffer to the done buffers list */
	spin_lock_irqsave(&q->done_lock, flags);
	vb->state = state;
	list_add_tail(&vb->done_entry, &q->done_list);
	atomic_dec(&q->queued_count);
	spin_unlock_irqrestore(&q->done_lock, flags);

	/* Inform any processes that may be waiting for buffers */
	wake_up(&q->done_wq);
}
EXPORT_SYMBOL_GPL(vb2_buffer_done);

/**
961 962 963
 * __fill_vb2_buffer() - fill a vb2_buffer with information provided in a
 * v4l2_buffer by the userspace. The caller has already verified that struct
 * v4l2_buffer has a valid number of planes.
964
 */
965
static void __fill_vb2_buffer(struct vb2_buffer *vb, const struct v4l2_buffer *b,
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
				struct v4l2_plane *v4l2_planes)
{
	unsigned int plane;

	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
		/* Fill in driver-provided information for OUTPUT types */
		if (V4L2_TYPE_IS_OUTPUT(b->type)) {
			/*
			 * Will have to go up to b->length when API starts
			 * accepting variable number of planes.
			 */
			for (plane = 0; plane < vb->num_planes; ++plane) {
				v4l2_planes[plane].bytesused =
					b->m.planes[plane].bytesused;
				v4l2_planes[plane].data_offset =
					b->m.planes[plane].data_offset;
			}
		}

		if (b->memory == V4L2_MEMORY_USERPTR) {
			for (plane = 0; plane < vb->num_planes; ++plane) {
				v4l2_planes[plane].m.userptr =
					b->m.planes[plane].m.userptr;
				v4l2_planes[plane].length =
					b->m.planes[plane].length;
			}
		}
993 994 995 996 997 998 999 1000 1001 1002
		if (b->memory == V4L2_MEMORY_DMABUF) {
			for (plane = 0; plane < vb->num_planes; ++plane) {
				v4l2_planes[plane].m.fd =
					b->m.planes[plane].m.fd;
				v4l2_planes[plane].length =
					b->m.planes[plane].length;
				v4l2_planes[plane].data_offset =
					b->m.planes[plane].data_offset;
			}
		}
1003 1004 1005 1006 1007 1008 1009
	} else {
		/*
		 * Single-planar buffers do not use planes array,
		 * so fill in relevant v4l2_buffer struct fields instead.
		 * In videobuf we use our internal V4l2_planes struct for
		 * single-planar buffers as well, for simplicity.
		 */
1010
		if (V4L2_TYPE_IS_OUTPUT(b->type)) {
1011
			v4l2_planes[0].bytesused = b->bytesused;
1012 1013
			v4l2_planes[0].data_offset = 0;
		}
1014 1015 1016 1017 1018

		if (b->memory == V4L2_MEMORY_USERPTR) {
			v4l2_planes[0].m.userptr = b->m.userptr;
			v4l2_planes[0].length = b->length;
		}
1019 1020 1021 1022 1023 1024 1025

		if (b->memory == V4L2_MEMORY_DMABUF) {
			v4l2_planes[0].m.fd = b->m.fd;
			v4l2_planes[0].length = b->length;
			v4l2_planes[0].data_offset = 0;
		}

1026 1027 1028 1029
	}

	vb->v4l2_buf.field = b->field;
	vb->v4l2_buf.timestamp = b->timestamp;
1030
	vb->v4l2_buf.flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
1031 1032 1033 1034 1035
}

/**
 * __qbuf_userptr() - handle qbuf of a USERPTR buffer
 */
1036
static int __qbuf_userptr(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1037 1038 1039 1040 1041 1042 1043 1044
{
	struct v4l2_plane planes[VIDEO_MAX_PLANES];
	struct vb2_queue *q = vb->vb2_queue;
	void *mem_priv;
	unsigned int plane;
	int ret;
	int write = !V4L2_TYPE_IS_OUTPUT(q->type);

1045 1046
	/* Copy relevant information provided by the userspace */
	__fill_vb2_buffer(vb, b, planes);
1047 1048 1049

	for (plane = 0; plane < vb->num_planes; ++plane) {
		/* Skip the plane if already verified */
1050 1051
		if (vb->v4l2_planes[plane].m.userptr &&
		    vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
1052 1053 1054 1055 1056 1057
		    && vb->v4l2_planes[plane].length == planes[plane].length)
			continue;

		dprintk(3, "qbuf: userspace address for plane %d changed, "
				"reacquiring memory\n", plane);

1058 1059
		/* Check if the provided plane buffer is large enough */
		if (planes[plane].length < q->plane_sizes[plane]) {
1060 1061 1062 1063
			dprintk(1, "qbuf: provided buffer size %u is less than "
						"setup size %u for plane %d\n",
						planes[plane].length,
						q->plane_sizes[plane], plane);
1064
			ret = -EINVAL;
1065 1066 1067
			goto err;
		}

1068 1069
		/* Release previously acquired memory if present */
		if (vb->planes[plane].mem_priv)
1070
			call_memop(q, put_userptr, vb->planes[plane].mem_priv);
1071 1072

		vb->planes[plane].mem_priv = NULL;
1073 1074
		vb->v4l2_planes[plane].m.userptr = 0;
		vb->v4l2_planes[plane].length = 0;
1075 1076

		/* Acquire each plane's memory */
1077 1078 1079 1080 1081
		mem_priv = call_memop(q, get_userptr, q->alloc_ctx[plane],
				      planes[plane].m.userptr,
				      planes[plane].length, write);
		if (IS_ERR_OR_NULL(mem_priv)) {
			dprintk(1, "qbuf: failed acquiring userspace "
1082
						"memory for plane %d\n", plane);
1083 1084
			ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
			goto err;
1085
		}
1086
		vb->planes[plane].mem_priv = mem_priv;
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	}

	/*
	 * Call driver-specific initialization on the newly acquired buffer,
	 * if provided.
	 */
	ret = call_qop(q, buf_init, vb);
	if (ret) {
		dprintk(1, "qbuf: buffer initialization failed\n");
		goto err;
	}

	/*
	 * Now that everything is in order, copy relevant information
	 * provided by userspace.
	 */
	for (plane = 0; plane < vb->num_planes; ++plane)
		vb->v4l2_planes[plane] = planes[plane];

	return 0;
err:
	/* In case of errors, release planes that were already acquired */
1109 1110
	for (plane = 0; plane < vb->num_planes; ++plane) {
		if (vb->planes[plane].mem_priv)
1111
			call_memop(q, put_userptr, vb->planes[plane].mem_priv);
1112 1113 1114
		vb->planes[plane].mem_priv = NULL;
		vb->v4l2_planes[plane].m.userptr = 0;
		vb->v4l2_planes[plane].length = 0;
1115 1116 1117 1118 1119 1120 1121 1122
	}

	return ret;
}

/**
 * __qbuf_mmap() - handle qbuf of an MMAP buffer
 */
1123
static int __qbuf_mmap(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1124
{
1125 1126
	__fill_vb2_buffer(vb, b, vb->v4l2_planes);
	return 0;
1127 1128
}

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
/**
 * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
 */
static int __qbuf_dmabuf(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
	struct v4l2_plane planes[VIDEO_MAX_PLANES];
	struct vb2_queue *q = vb->vb2_queue;
	void *mem_priv;
	unsigned int plane;
	int ret;
	int write = !V4L2_TYPE_IS_OUTPUT(q->type);

	/* Verify and copy relevant information provided by the userspace */
	__fill_vb2_buffer(vb, b, planes);

	for (plane = 0; plane < vb->num_planes; ++plane) {
		struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);

		if (IS_ERR_OR_NULL(dbuf)) {
			dprintk(1, "qbuf: invalid dmabuf fd for plane %d\n",
				plane);
			ret = -EINVAL;
			goto err;
		}

		/* use DMABUF size if length is not provided */
		if (planes[plane].length == 0)
			planes[plane].length = dbuf->size;

		if (planes[plane].length < planes[plane].data_offset +
		    q->plane_sizes[plane]) {
1160 1161
			dprintk(1, "qbuf: invalid dmabuf length for plane %d\n",
				plane);
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
			ret = -EINVAL;
			goto err;
		}

		/* Skip the plane if already verified */
		if (dbuf == vb->planes[plane].dbuf &&
		    vb->v4l2_planes[plane].length == planes[plane].length) {
			dma_buf_put(dbuf);
			continue;
		}

		dprintk(1, "qbuf: buffer for plane %d changed\n", plane);

		/* Release previously acquired memory if present */
		__vb2_plane_dmabuf_put(q, &vb->planes[plane]);
		memset(&vb->v4l2_planes[plane], 0, sizeof(struct v4l2_plane));

		/* Acquire each plane's memory */
		mem_priv = call_memop(q, attach_dmabuf, q->alloc_ctx[plane],
			dbuf, planes[plane].length, write);
		if (IS_ERR(mem_priv)) {
			dprintk(1, "qbuf: failed to attach dmabuf\n");
			ret = PTR_ERR(mem_priv);
			dma_buf_put(dbuf);
			goto err;
		}

		vb->planes[plane].dbuf = dbuf;
		vb->planes[plane].mem_priv = mem_priv;
	}

	/* TODO: This pins the buffer(s) with  dma_buf_map_attachment()).. but
	 * really we want to do this just before the DMA, not while queueing
	 * the buffer(s)..
	 */
	for (plane = 0; plane < vb->num_planes; ++plane) {
		ret = call_memop(q, map_dmabuf, vb->planes[plane].mem_priv);
		if (ret) {
			dprintk(1, "qbuf: failed to map dmabuf for plane %d\n",
				plane);
			goto err;
		}
		vb->planes[plane].dbuf_mapped = 1;
	}

	/*
	 * Call driver-specific initialization on the newly acquired buffer,
	 * if provided.
	 */
	ret = call_qop(q, buf_init, vb);
	if (ret) {
		dprintk(1, "qbuf: buffer initialization failed\n");
		goto err;
	}

	/*
	 * Now that everything is in order, copy relevant information
	 * provided by userspace.
	 */
	for (plane = 0; plane < vb->num_planes; ++plane)
		vb->v4l2_planes[plane] = planes[plane];

	return 0;
err:
	/* In case of errors, release planes that were already acquired */
	__vb2_buf_dmabuf_put(vb);

	return ret;
}

1232 1233 1234 1235 1236 1237
/**
 * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
 */
static void __enqueue_in_driver(struct vb2_buffer *vb)
{
	struct vb2_queue *q = vb->vb2_queue;
1238
	unsigned int plane;
1239 1240 1241

	vb->state = VB2_BUF_STATE_ACTIVE;
	atomic_inc(&q->queued_count);
1242 1243 1244 1245 1246

	/* sync buffers */
	for (plane = 0; plane < vb->num_planes; ++plane)
		call_memop(q, prepare, vb->planes[plane].mem_priv);

1247 1248 1249
	q->ops->buf_queue(vb);
}

1250
static int __buf_prepare(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1251 1252
{
	struct vb2_queue *q = vb->vb2_queue;
1253
	struct rw_semaphore *mmap_sem;
1254 1255
	int ret;

1256
	ret = __verify_length(vb, b);
1257 1258 1259
	if (ret < 0) {
		dprintk(1, "%s(): plane parameters verification failed: %d\n",
			__func__, ret);
1260
		return ret;
1261
	}
1262

1263
	vb->state = VB2_BUF_STATE_PREPARING;
1264 1265 1266 1267 1268
	switch (q->memory) {
	case V4L2_MEMORY_MMAP:
		ret = __qbuf_mmap(vb, b);
		break;
	case V4L2_MEMORY_USERPTR:
1269
		/*
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
		 * In case of user pointer buffers vb2 allocators need to get
		 * direct access to userspace pages. This requires getting
		 * the mmap semaphore for read access in the current process
		 * structure. The same semaphore is taken before calling mmap
		 * operation, while both qbuf/prepare_buf and mmap are called
		 * by the driver or v4l2 core with the driver's lock held.
		 * To avoid an AB-BA deadlock (mmap_sem then driver's lock in
		 * mmap and driver's lock then mmap_sem in qbuf/prepare_buf),
		 * the videobuf2 core releases the driver's lock, takes
		 * mmap_sem and then takes the driver's lock again.
1280 1281 1282 1283 1284 1285
		 */
		mmap_sem = &current->mm->mmap_sem;
		call_qop(q, wait_prepare, q);
		down_read(mmap_sem);
		call_qop(q, wait_finish, q);

1286
		ret = __qbuf_userptr(vb, b);
1287 1288

		up_read(mmap_sem);
1289
		break;
1290 1291 1292
	case V4L2_MEMORY_DMABUF:
		ret = __qbuf_dmabuf(vb, b);
		break;
1293 1294 1295 1296 1297 1298 1299 1300 1301
	default:
		WARN(1, "Invalid queue type\n");
		ret = -EINVAL;
	}

	if (!ret)
		ret = call_qop(q, buf_prepare, vb);
	if (ret)
		dprintk(1, "qbuf: buffer preparation failed: %d\n", ret);
1302
	vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1303 1304 1305 1306

	return ret;
}

1307
static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
1308
				    const char *opname)
1309 1310
{
	if (b->type != q->type) {
1311
		dprintk(1, "%s(): invalid buffer type\n", opname);
1312
		return -EINVAL;
1313 1314 1315
	}

	if (b->index >= q->num_buffers) {
1316
		dprintk(1, "%s(): buffer index out of range\n", opname);
1317
		return -EINVAL;
1318 1319
	}

1320
	if (q->bufs[b->index] == NULL) {
1321
		/* Should never happen */
1322
		dprintk(1, "%s(): buffer is NULL\n", opname);
1323
		return -EINVAL;
1324 1325 1326
	}

	if (b->memory != q->memory) {
1327
		dprintk(1, "%s(): invalid memory type\n", opname);
1328
		return -EINVAL;
1329 1330
	}

1331
	return __verify_planes_array(q->bufs[b->index], b);
1332
}
1333

1334
/**
1335
 * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
1336
 * @q:		videobuf2 queue
1337 1338
 * @b:		buffer structure passed from userspace to vidioc_prepare_buf
 *		handler in driver
1339
 *
1340
 * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1341 1342
 * This function:
 * 1) verifies the passed buffer,
1343 1344
 * 2) calls buf_prepare callback in the driver (if provided), in which
 *    driver-specific buffer initialization can be performed,
1345 1346
 *
 * The return values from this function are intended to be directly returned
1347
 * from vidioc_prepare_buf handler in driver.
1348
 */
1349
int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
1350
{
1351
	struct vb2_buffer *vb;
1352 1353 1354 1355 1356 1357
	int ret;

	if (q->fileio) {
		dprintk(1, "%s(): file io in progress\n", __func__);
		return -EBUSY;
	}
1358

1359
	ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
	if (ret)
		return ret;

	vb = q->bufs[b->index];
	if (vb->state != VB2_BUF_STATE_DEQUEUED) {
		dprintk(1, "%s(): invalid buffer state %d\n", __func__,
			vb->state);
		return -EINVAL;
	}

	ret = __buf_prepare(vb, b);
	if (!ret) {
		/* Fill buffer information for the userspace */
		__fill_v4l2_buffer(vb, b);

		dprintk(1, "%s() of buffer %d succeeded\n", __func__, vb->v4l2_buf.index);
	}
	return ret;
1378 1379
}
EXPORT_SYMBOL_GPL(vb2_prepare_buf);
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
/**
 * vb2_start_streaming() - Attempt to start streaming.
 * @q:		videobuf2 queue
 *
 * If there are not enough buffers, then retry_start_streaming is set to
 * 1 and 0 is returned. The next time a buffer is queued and
 * retry_start_streaming is 1, this function will be called again to
 * retry starting the DMA engine.
 */
static int vb2_start_streaming(struct vb2_queue *q)
{
	int ret;

	/* Tell the driver to start streaming */
	ret = call_qop(q, start_streaming, q, atomic_read(&q->queued_count));

	/*
	 * If there are not enough buffers queued to start streaming, then
	 * the start_streaming operation will return -ENOBUFS and you have to
	 * retry when the next buffer is queued.
	 */
	if (ret == -ENOBUFS) {
		dprintk(1, "qbuf: not enough buffers, retry when more buffers are queued.\n");
		q->retry_start_streaming = 1;
		return 0;
	}
	if (ret)
		dprintk(1, "qbuf: driver refused to start streaming\n");
	else
		q->retry_start_streaming = 0;
	return ret;
}

1414
static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
1415
{
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
	int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
	struct vb2_buffer *vb;

	if (ret)
		return ret;

	vb = q->bufs[b->index];
	if (vb->state != VB2_BUF_STATE_DEQUEUED) {
		dprintk(1, "%s(): invalid buffer state %d\n", __func__,
			vb->state);
		return -EINVAL;
	}
1428

1429 1430 1431 1432
	switch (vb->state) {
	case VB2_BUF_STATE_DEQUEUED:
		ret = __buf_prepare(vb, b);
		if (ret)
1433
			return ret;
1434
		break;
1435 1436
	case VB2_BUF_STATE_PREPARED:
		break;
1437 1438 1439
	case VB2_BUF_STATE_PREPARING:
		dprintk(1, "qbuf: buffer still being prepared\n");
		return -EINVAL;
1440
	default:
1441
		dprintk(1, "qbuf: buffer already in use\n");
1442
		return -EINVAL;
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
	}

	/*
	 * Add to the queued buffers list, a buffer will stay on it until
	 * dequeued in dqbuf.
	 */
	list_add_tail(&vb->queued_entry, &q->queued_list);
	vb->state = VB2_BUF_STATE_QUEUED;

	/*
	 * If already streaming, give the buffer to driver for processing.
	 * If not, the buffer will be given to driver on next streamon.
	 */
	if (q->streaming)
		__enqueue_in_driver(vb);

1459 1460
	/* Fill buffer information for the userspace */
	__fill_v4l2_buffer(vb, b);
1461

1462 1463 1464 1465 1466 1467
	if (q->retry_start_streaming) {
		ret = vb2_start_streaming(q);
		if (ret)
			return ret;
	}

1468 1469
	dprintk(1, "%s() of buffer %d succeeded\n", __func__, vb->v4l2_buf.index);
	return 0;
1470
}
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

/**
 * vb2_qbuf() - Queue a buffer from userspace
 * @q:		videobuf2 queue
 * @b:		buffer structure passed from userspace to vidioc_qbuf handler
 *		in driver
 *
 * Should be called from vidioc_qbuf ioctl handler of a driver.
 * This function:
 * 1) verifies the passed buffer,
 * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
 *    which driver-specific buffer initialization can be performed,
 * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
 *    callback for processing.
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_qbuf handler in driver.
 */
int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
	if (q->fileio) {
		dprintk(1, "%s(): file io in progress\n", __func__);
		return -EBUSY;
	}

	return vb2_internal_qbuf(q, b);
}
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
EXPORT_SYMBOL_GPL(vb2_qbuf);

/**
 * __vb2_wait_for_done_vb() - wait for a buffer to become available
 * for dequeuing
 *
 * Will sleep if required for nonblocking == false.
 */
static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
{
	/*
	 * All operations on vb_done_list are performed under done_lock
	 * spinlock protection. However, buffers may be removed from
	 * it and returned to userspace only while holding both driver's
	 * lock and the done_lock spinlock. Thus we can be sure that as
	 * long as we hold the driver's lock, the list will remain not
	 * empty if list_empty() check succeeds.
	 */

	for (;;) {
		int ret;

		if (!q->streaming) {
			dprintk(1, "Streaming off, will not wait for buffers\n");
			return -EINVAL;
		}

		if (!list_empty(&q->done_list)) {
			/*
			 * Found a buffer that we were waiting for.
			 */
			break;
		}

		if (nonblocking) {
			dprintk(1, "Nonblocking and no buffers to dequeue, "
								"will not wait\n");
			return -EAGAIN;
		}

		/*
		 * We are streaming and blocking, wait for another buffer to
		 * become ready or for streamoff. Driver's lock is released to
		 * allow streamoff or qbuf to be called while waiting.
		 */
		call_qop(q, wait_prepare, q);

		/*
		 * All locks have been released, it is safe to sleep now.
		 */
		dprintk(3, "Will sleep waiting for buffers\n");
		ret = wait_event_interruptible(q->done_wq,
				!list_empty(&q->done_list) || !q->streaming);

		/*
		 * We need to reevaluate both conditions again after reacquiring
		 * the locks or return an error if one occurred.
		 */
		call_qop(q, wait_finish, q);
1557 1558
		if (ret) {
			dprintk(1, "Sleep was interrupted\n");
1559
			return ret;
1560
		}
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	}
	return 0;
}

/**
 * __vb2_get_done_vb() - get a buffer ready for dequeuing
 *
 * Will sleep if required for nonblocking == false.
 */
static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1571
				struct v4l2_buffer *b, int nonblocking)
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
{
	unsigned long flags;
	int ret;

	/*
	 * Wait for at least one buffer to become available on the done_list.
	 */
	ret = __vb2_wait_for_done_vb(q, nonblocking);
	if (ret)
		return ret;

	/*
	 * Driver's lock has been held since we last verified that done_list
	 * is not empty, so no need for another list_empty(done_list) check.
	 */
	spin_lock_irqsave(&q->done_lock, flags);
	*vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1589 1590 1591 1592 1593 1594 1595
	/*
	 * Only remove the buffer from done_list if v4l2_buffer can handle all
	 * the planes.
	 */
	ret = __verify_planes_array(*vb, b);
	if (!ret)
		list_del(&(*vb)->done_entry);
1596 1597
	spin_unlock_irqrestore(&q->done_lock, flags);

1598
	return ret;
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
}

/**
 * vb2_wait_for_all_buffers() - wait until all buffers are given back to vb2
 * @q:		videobuf2 queue
 *
 * This function will wait until all buffers that have been given to the driver
 * by buf_queue() are given back to vb2 with vb2_buffer_done(). It doesn't call
 * wait_prepare, wait_finish pair. It is intended to be called with all locks
 * taken, for example from stop_streaming() callback.
 */
int vb2_wait_for_all_buffers(struct vb2_queue *q)
{
	if (!q->streaming) {
		dprintk(1, "Streaming off, will not wait for buffers\n");
		return -EINVAL;
	}

1617 1618
	if (!q->retry_start_streaming)
		wait_event(q->done_wq, !atomic_read(&q->queued_count));
1619 1620 1621 1622
	return 0;
}
EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
/**
 * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
 */
static void __vb2_dqbuf(struct vb2_buffer *vb)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned int i;

	/* nothing to do if the buffer is already dequeued */
	if (vb->state == VB2_BUF_STATE_DEQUEUED)
		return;

	vb->state = VB2_BUF_STATE_DEQUEUED;

	/* unmap DMABUF buffer */
	if (q->memory == V4L2_MEMORY_DMABUF)
		for (i = 0; i < vb->num_planes; ++i) {
			if (!vb->planes[i].dbuf_mapped)
				continue;
			call_memop(q, unmap_dmabuf, vb->planes[i].mem_priv);
			vb->planes[i].dbuf_mapped = 0;
		}
}

1647
static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
1648 1649 1650 1651 1652 1653 1654 1655
{
	struct vb2_buffer *vb = NULL;
	int ret;

	if (b->type != q->type) {
		dprintk(1, "dqbuf: invalid buffer type\n");
		return -EINVAL;
	}
1656 1657
	ret = __vb2_get_done_vb(q, &vb, b, nonblocking);
	if (ret < 0)
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
		return ret;

	ret = call_qop(q, buf_finish, vb);
	if (ret) {
		dprintk(1, "dqbuf: buffer finish failed\n");
		return ret;
	}

	switch (vb->state) {
	case VB2_BUF_STATE_DONE:
		dprintk(3, "dqbuf: Returning done buffer\n");
		break;
	case VB2_BUF_STATE_ERROR:
		dprintk(3, "dqbuf: Returning done buffer with errors\n");
		break;
	default:
		dprintk(1, "dqbuf: Invalid buffer state\n");
		return -EINVAL;
	}

	/* Fill buffer information for the userspace */
	__fill_v4l2_buffer(vb, b);
	/* Remove from videobuf queue */
	list_del(&vb->queued_entry);
1682 1683
	/* go back to dequeued state */
	__vb2_dqbuf(vb);
1684 1685 1686 1687 1688 1689

	dprintk(1, "dqbuf of buffer %d, with state %d\n",
			vb->v4l2_buf.index, vb->state);

	return 0;
}
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

/**
 * vb2_dqbuf() - Dequeue a buffer to the userspace
 * @q:		videobuf2 queue
 * @b:		buffer structure passed from userspace to vidioc_dqbuf handler
 *		in driver
 * @nonblocking: if true, this call will not sleep waiting for a buffer if no
 *		 buffers ready for dequeuing are present. Normally the driver
 *		 would be passing (file->f_flags & O_NONBLOCK) here
 *
 * Should be called from vidioc_dqbuf ioctl handler of a driver.
 * This function:
 * 1) verifies the passed buffer,
 * 2) calls buf_finish callback in the driver (if provided), in which
 *    driver can perform any additional operations that may be required before
 *    returning the buffer to userspace, such as cache sync,
 * 3) the buffer struct members are filled with relevant information for
 *    the userspace.
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_dqbuf handler in driver.
 */
int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
{
	if (q->fileio) {
		dprintk(1, "dqbuf: file io in progress\n");
		return -EBUSY;
	}
	return vb2_internal_dqbuf(q, b, nonblocking);
}
1720 1721
EXPORT_SYMBOL_GPL(vb2_dqbuf);

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
/**
 * __vb2_queue_cancel() - cancel and stop (pause) streaming
 *
 * Removes all queued buffers from driver's queue and all buffers queued by
 * userspace from videobuf's queue. Returns to state after reqbufs.
 */
static void __vb2_queue_cancel(struct vb2_queue *q)
{
	unsigned int i;

1732 1733 1734 1735 1736
	if (q->retry_start_streaming) {
		q->retry_start_streaming = 0;
		q->streaming = 0;
	}

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
	/*
	 * Tell driver to stop all transactions and release all queued
	 * buffers.
	 */
	if (q->streaming)
		call_qop(q, stop_streaming, q);
	q->streaming = 0;

	/*
	 * Remove all buffers from videobuf's list...
	 */
	INIT_LIST_HEAD(&q->queued_list);
	/*
	 * ...and done list; userspace will not receive any buffers it
	 * has not already dequeued before initiating cancel.
	 */
	INIT_LIST_HEAD(&q->done_list);
	atomic_set(&q->queued_count, 0);
	wake_up_all(&q->done_wq);

	/*
	 * Reinitialize all buffers for next use.
	 */
	for (i = 0; i < q->num_buffers; ++i)
1761
		__vb2_dqbuf(q->bufs[i]);
1762 1763
}

1764
static int vb2_internal_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
1765 1766
{
	struct vb2_buffer *vb;
1767
	int ret;
1768 1769 1770 1771 1772 1773 1774

	if (type != q->type) {
		dprintk(1, "streamon: invalid stream type\n");
		return -EINVAL;
	}

	if (q->streaming) {
1775 1776
		dprintk(3, "streamon successful: already streaming\n");
		return 0;
1777 1778 1779
	}

	/*
1780 1781
	 * If any buffers were queued before streamon,
	 * we can now pass them to driver for processing.
1782
	 */
1783 1784
	list_for_each_entry(vb, &q->queued_list, queued_entry)
		__enqueue_in_driver(vb);
1785

1786 1787
	/* Tell driver to start streaming. */
	ret = vb2_start_streaming(q);
1788
	if (ret) {
1789
		__vb2_queue_cancel(q);
1790 1791 1792 1793
		return ret;
	}

	q->streaming = 1;
1794 1795 1796 1797 1798 1799

	dprintk(3, "Streamon successful\n");
	return 0;
}

/**
1800
 * vb2_streamon - start streaming
1801
 * @q:		videobuf2 queue
1802
 * @type:	type argument passed from userspace to vidioc_streamon handler
1803
 *
1804
 * Should be called from vidioc_streamon handler of a driver.
1805
 * This function:
1806 1807
 * 1) verifies current state
 * 2) passes any previously queued buffers to the driver and starts streaming
1808 1809
 *
 * The return values from this function are intended to be directly returned
1810
 * from vidioc_streamon handler in the driver.
1811
 */
1812
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
1813
{
1814
	if (q->fileio) {
1815
		dprintk(1, "streamon: file io in progress\n");
1816 1817
		return -EBUSY;
	}
1818 1819 1820
	return vb2_internal_streamon(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamon);
1821

1822 1823
static int vb2_internal_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
{
1824 1825 1826 1827 1828 1829
	if (type != q->type) {
		dprintk(1, "streamoff: invalid stream type\n");
		return -EINVAL;
	}

	if (!q->streaming) {
1830 1831
		dprintk(3, "streamoff successful: not streaming\n");
		return 0;
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
	}

	/*
	 * Cancel will pause streaming and remove all buffers from the driver
	 * and videobuf, effectively returning control over them to userspace.
	 */
	__vb2_queue_cancel(q);

	dprintk(3, "Streamoff successful\n");
	return 0;
}
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866

/**
 * vb2_streamoff - stop streaming
 * @q:		videobuf2 queue
 * @type:	type argument passed from userspace to vidioc_streamoff handler
 *
 * Should be called from vidioc_streamoff handler of a driver.
 * This function:
 * 1) verifies current state,
 * 2) stop streaming and dequeues any queued buffers, including those previously
 *    passed to the driver (after waiting for the driver to finish).
 *
 * This call can be used for pausing playback.
 * The return values from this function are intended to be directly returned
 * from vidioc_streamoff handler in the driver
 */
int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
{
	if (q->fileio) {
		dprintk(1, "streamoff: file io in progress\n");
		return -EBUSY;
	}
	return vb2_internal_streamoff(q, type);
}
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
EXPORT_SYMBOL_GPL(vb2_streamoff);

/**
 * __find_plane_by_offset() - find plane associated with the given offset off
 */
static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
			unsigned int *_buffer, unsigned int *_plane)
{
	struct vb2_buffer *vb;
	unsigned int buffer, plane;

	/*
	 * Go over all buffers and their planes, comparing the given offset
	 * with an offset assigned to each plane. If a match is found,
	 * return its buffer and plane numbers.
	 */
	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
		vb = q->bufs[buffer];

		for (plane = 0; plane < vb->num_planes; ++plane) {
			if (vb->v4l2_planes[plane].m.mem_offset == off) {
				*_buffer = buffer;
				*_plane = plane;
				return 0;
			}
		}
	}

	return -EINVAL;
}

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
/**
 * vb2_expbuf() - Export a buffer as a file descriptor
 * @q:		videobuf2 queue
 * @eb:		export buffer structure passed from userspace to vidioc_expbuf
 *		handler in driver
 *
 * The return values from this function are intended to be directly returned
 * from vidioc_expbuf handler in driver.
 */
int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
{
	struct vb2_buffer *vb = NULL;
	struct vb2_plane *vb_plane;
	int ret;
	struct dma_buf *dbuf;

	if (q->memory != V4L2_MEMORY_MMAP) {
		dprintk(1, "Queue is not currently set up for mmap\n");
		return -EINVAL;
	}

	if (!q->mem_ops->get_dmabuf) {
		dprintk(1, "Queue does not support DMA buffer exporting\n");
		return -EINVAL;
	}

1924 1925
	if (eb->flags & ~(O_CLOEXEC | O_ACCMODE)) {
		dprintk(1, "Queue does support only O_CLOEXEC and access mode flags\n");
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
		return -EINVAL;
	}

	if (eb->type != q->type) {
		dprintk(1, "qbuf: invalid buffer type\n");
		return -EINVAL;
	}

	if (eb->index >= q->num_buffers) {
		dprintk(1, "buffer index out of range\n");
		return -EINVAL;
	}

	vb = q->bufs[eb->index];

	if (eb->plane >= vb->num_planes) {
		dprintk(1, "buffer plane out of range\n");
		return -EINVAL;
	}

	vb_plane = &vb->planes[eb->plane];

1948
	dbuf = call_memop(q, get_dmabuf, vb_plane->mem_priv, eb->flags & O_ACCMODE);
1949 1950 1951 1952 1953 1954
	if (IS_ERR_OR_NULL(dbuf)) {
		dprintk(1, "Failed to export buffer %d, plane %d\n",
			eb->index, eb->plane);
		return -EINVAL;
	}

1955
	ret = dma_buf_fd(dbuf, eb->flags & ~O_ACCMODE);
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
	if (ret < 0) {
		dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
			eb->index, eb->plane, ret);
		dma_buf_put(dbuf);
		return ret;
	}

	dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
		eb->index, eb->plane, ret);
	eb->fd = ret;

	return 0;
}
EXPORT_SYMBOL_GPL(vb2_expbuf);

1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
/**
 * vb2_mmap() - map video buffers into application address space
 * @q:		videobuf2 queue
 * @vma:	vma passed to the mmap file operation handler in the driver
 *
 * Should be called from mmap file operation handler of a driver.
 * This function maps one plane of one of the available video buffers to
 * userspace. To map whole video memory allocated on reqbufs, this function
 * has to be called once per each plane per each buffer previously allocated.
 *
 * When the userspace application calls mmap, it passes to it an offset returned
 * to it earlier by the means of vidioc_querybuf handler. That offset acts as
 * a "cookie", which is then used to identify the plane to be mapped.
 * This function finds a plane with a matching offset and a mapping is performed
 * by the means of a provided memory operation.
 *
 * The return values from this function are intended to be directly returned
 * from the mmap handler in driver.
 */
int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
{
	unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
	struct vb2_buffer *vb;
	unsigned int buffer, plane;
	int ret;
1996
	unsigned long length;
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030

	if (q->memory != V4L2_MEMORY_MMAP) {
		dprintk(1, "Queue is not currently set up for mmap\n");
		return -EINVAL;
	}

	/*
	 * Check memory area access mode.
	 */
	if (!(vma->vm_flags & VM_SHARED)) {
		dprintk(1, "Invalid vma flags, VM_SHARED needed\n");
		return -EINVAL;
	}
	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
		if (!(vma->vm_flags & VM_WRITE)) {
			dprintk(1, "Invalid vma flags, VM_WRITE needed\n");
			return -EINVAL;
		}
	} else {
		if (!(vma->vm_flags & VM_READ)) {
			dprintk(1, "Invalid vma flags, VM_READ needed\n");
			return -EINVAL;
		}
	}

	/*
	 * Find the plane corresponding to the offset passed by userspace.
	 */
	ret = __find_plane_by_offset(q, off, &buffer, &plane);
	if (ret)
		return ret;

	vb = q->bufs[buffer];

2031 2032 2033 2034 2035 2036 2037 2038 2039
	/*
	 * MMAP requires page_aligned buffers.
	 * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
	 * so, we need to do the same here.
	 */
	length = PAGE_ALIGN(vb->v4l2_planes[plane].length);
	if (length < (vma->vm_end - vma->vm_start)) {
		dprintk(1,
			"MMAP invalid, as it would overflow buffer length\n");
2040 2041 2042
		return -EINVAL;
	}

2043
	ret = call_memop(q, mmap, vb->planes[plane].mem_priv, vma);
2044 2045 2046 2047 2048 2049 2050 2051
	if (ret)
		return ret;

	dprintk(3, "Buffer %d, plane %d successfully mapped\n", buffer, plane);
	return 0;
}
EXPORT_SYMBOL_GPL(vb2_mmap);

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
#ifndef CONFIG_MMU
unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
				    unsigned long addr,
				    unsigned long len,
				    unsigned long pgoff,
				    unsigned long flags)
{
	unsigned long off = pgoff << PAGE_SHIFT;
	struct vb2_buffer *vb;
	unsigned int buffer, plane;
	int ret;

	if (q->memory != V4L2_MEMORY_MMAP) {
		dprintk(1, "Queue is not currently set up for mmap\n");
		return -EINVAL;
	}

	/*
	 * Find the plane corresponding to the offset passed by userspace.
	 */
	ret = __find_plane_by_offset(q, off, &buffer, &plane);
	if (ret)
		return ret;

	vb = q->bufs[buffer];

	return (unsigned long)vb2_plane_vaddr(vb, plane);
}
EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
#endif

2083 2084
static int __vb2_init_fileio(struct vb2_queue *q, int read);
static int __vb2_cleanup_fileio(struct vb2_queue *q);
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098

/**
 * vb2_poll() - implements poll userspace operation
 * @q:		videobuf2 queue
 * @file:	file argument passed to the poll file operation handler
 * @wait:	wait argument passed to the poll file operation handler
 *
 * This function implements poll file operation handler for a driver.
 * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
 * be informed that the file descriptor of a video device is available for
 * reading.
 * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
 * will be reported as available for writing.
 *
2099 2100 2101
 * If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
 * pending events.
 *
2102 2103 2104 2105 2106
 * The return values from this function are intended to be directly returned
 * from poll handler in driver.
 */
unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
{
2107
	struct video_device *vfd = video_devdata(file);
2108
	unsigned long req_events = poll_requested_events(wait);
2109
	struct vb2_buffer *vb = NULL;
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
	unsigned int res = 0;
	unsigned long flags;

	if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
		struct v4l2_fh *fh = file->private_data;

		if (v4l2_event_pending(fh))
			res = POLLPRI;
		else if (req_events & POLLPRI)
			poll_wait(file, &fh->wait, wait);
	}
2121

2122 2123 2124 2125 2126
	if (!V4L2_TYPE_IS_OUTPUT(q->type) && !(req_events & (POLLIN | POLLRDNORM)))
		return res;
	if (V4L2_TYPE_IS_OUTPUT(q->type) && !(req_events & (POLLOUT | POLLWRNORM)))
		return res;

2127
	/*
2128
	 * Start file I/O emulator only if streaming API has not been used yet.
2129 2130
	 */
	if (q->num_buffers == 0 && q->fileio == NULL) {
2131 2132
		if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ) &&
				(req_events & (POLLIN | POLLRDNORM))) {
2133 2134
			if (__vb2_init_fileio(q, 1))
				return res | POLLERR;
2135
		}
2136 2137
		if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE) &&
				(req_events & (POLLOUT | POLLWRNORM))) {
2138 2139
			if (__vb2_init_fileio(q, 0))
				return res | POLLERR;
2140 2141 2142
			/*
			 * Write to OUTPUT queue can be done immediately.
			 */
2143
			return res | POLLOUT | POLLWRNORM;
2144 2145 2146
		}
	}

2147 2148 2149 2150
	/*
	 * There is nothing to wait for if no buffers have already been queued.
	 */
	if (list_empty(&q->queued_list))
2151
		return res | POLLERR;
2152

2153 2154
	if (list_empty(&q->done_list))
		poll_wait(file, &q->done_wq, wait);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166

	/*
	 * Take first buffer available for dequeuing.
	 */
	spin_lock_irqsave(&q->done_lock, flags);
	if (!list_empty(&q->done_list))
		vb = list_first_entry(&q->done_list, struct vb2_buffer,
					done_entry);
	spin_unlock_irqrestore(&q->done_lock, flags);

	if (vb && (vb->state == VB2_BUF_STATE_DONE
			|| vb->state == VB2_BUF_STATE_ERROR)) {
2167 2168 2169
		return (V4L2_TYPE_IS_OUTPUT(q->type)) ?
				res | POLLOUT | POLLWRNORM :
				res | POLLIN | POLLRDNORM;
2170
	}
2171
	return res;
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
}
EXPORT_SYMBOL_GPL(vb2_poll);

/**
 * vb2_queue_init() - initialize a videobuf2 queue
 * @q:		videobuf2 queue; this structure should be allocated in driver
 *
 * The vb2_queue structure should be allocated by the driver. The driver is
 * responsible of clearing it's content and setting initial values for some
 * required entries before calling this function.
 * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
 * to the struct vb2_queue description in include/media/videobuf2-core.h
 * for more information.
 */
int vb2_queue_init(struct vb2_queue *q)
{
2188 2189 2190 2191 2192 2193 2194 2195 2196
	/*
	 * Sanity check
	 */
	if (WARN_ON(!q)			  ||
	    WARN_ON(!q->ops)		  ||
	    WARN_ON(!q->mem_ops)	  ||
	    WARN_ON(!q->type)		  ||
	    WARN_ON(!q->io_modes)	  ||
	    WARN_ON(!q->ops->queue_setup) ||
2197 2198
	    WARN_ON(!q->ops->buf_queue)   ||
	    WARN_ON(q->timestamp_type & ~V4L2_BUF_FLAG_TIMESTAMP_MASK))
2199
		return -EINVAL;
2200

2201 2202 2203
	/* Warn that the driver should choose an appropriate timestamp type */
	WARN_ON(q->timestamp_type == V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);

2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
	INIT_LIST_HEAD(&q->queued_list);
	INIT_LIST_HEAD(&q->done_list);
	spin_lock_init(&q->done_lock);
	init_waitqueue_head(&q->done_wq);

	if (q->buf_struct_size == 0)
		q->buf_struct_size = sizeof(struct vb2_buffer);

	return 0;
}
EXPORT_SYMBOL_GPL(vb2_queue_init);

/**
 * vb2_queue_release() - stop streaming, release the queue and free memory
 * @q:		videobuf2 queue
 *
 * This function stops streaming and performs necessary clean ups, including
 * freeing video buffer memory. The driver is responsible for freeing
 * the vb2_queue structure itself.
 */
void vb2_queue_release(struct vb2_queue *q)
{
2226
	__vb2_cleanup_fileio(q);
2227
	__vb2_queue_cancel(q);
2228
	__vb2_queue_free(q, q->num_buffers);
2229 2230 2231
}
EXPORT_SYMBOL_GPL(vb2_queue_release);

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
/**
 * struct vb2_fileio_buf - buffer context used by file io emulator
 *
 * vb2 provides a compatibility layer and emulator of file io (read and
 * write) calls on top of streaming API. This structure is used for
 * tracking context related to the buffers.
 */
struct vb2_fileio_buf {
	void *vaddr;
	unsigned int size;
	unsigned int pos;
	unsigned int queued:1;
};

/**
 * struct vb2_fileio_data - queue context used by file io emulator
 *
 * vb2 provides a compatibility layer and emulator of file io (read and
 * write) calls on top of streaming API. For proper operation it required
 * this structure to save the driver state between each call of the read
 * or write function.
 */
struct vb2_fileio_data {
	struct v4l2_requestbuffers req;
	struct v4l2_buffer b;
	struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
	unsigned int index;
	unsigned int q_count;
	unsigned int dq_count;
	unsigned int flags;
};

/**
 * __vb2_init_fileio() - initialize file io emulator
 * @q:		videobuf2 queue
 * @read:	mode selector (1 means read, 0 means write)
 */
static int __vb2_init_fileio(struct vb2_queue *q, int read)
{
	struct vb2_fileio_data *fileio;
	int i, ret;
	unsigned int count = 0;

	/*
	 * Sanity check
	 */
	if ((read && !(q->io_modes & VB2_READ)) ||
	   (!read && !(q->io_modes & VB2_WRITE)))
		BUG();

	/*
	 * Check if device supports mapping buffers to kernel virtual space.
	 */
	if (!q->mem_ops->vaddr)
		return -EBUSY;

	/*
	 * Check if streaming api has not been already activated.
	 */
	if (q->streaming || q->num_buffers > 0)
		return -EBUSY;

	/*
	 * Start with count 1, driver can increase it in queue_setup()
	 */
	count = 1;

	dprintk(3, "setting up file io: mode %s, count %d, flags %08x\n",
		(read) ? "read" : "write", count, q->io_flags);

	fileio = kzalloc(sizeof(struct vb2_fileio_data), GFP_KERNEL);
	if (fileio == NULL)
		return -ENOMEM;

	fileio->flags = q->io_flags;

	/*
	 * Request buffers and use MMAP type to force driver
	 * to allocate buffers by itself.
	 */
	fileio->req.count = count;
	fileio->req.memory = V4L2_MEMORY_MMAP;
	fileio->req.type = q->type;
	ret = vb2_reqbufs(q, &fileio->req);
	if (ret)
		goto err_kfree;

	/*
	 * Check if plane_count is correct
	 * (multiplane buffers are not supported).
	 */
	if (q->bufs[0]->num_planes != 1) {
		ret = -EBUSY;
		goto err_reqbufs;
	}

	/*
	 * Get kernel address of each buffer.
	 */
	for (i = 0; i < q->num_buffers; i++) {
		fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2333 2334
		if (fileio->bufs[i].vaddr == NULL) {
			ret = -EINVAL;
2335
			goto err_reqbufs;
2336
		}
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
		fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
	}

	/*
	 * Read mode requires pre queuing of all buffers.
	 */
	if (read) {
		/*
		 * Queue all buffers.
		 */
		for (i = 0; i < q->num_buffers; i++) {
			struct v4l2_buffer *b = &fileio->b;
			memset(b, 0, sizeof(*b));
			b->type = q->type;
			b->memory = q->memory;
			b->index = i;
			ret = vb2_qbuf(q, b);
			if (ret)
				goto err_reqbufs;
			fileio->bufs[i].queued = 1;
		}
	}

2360 2361 2362 2363 2364 2365 2366
	/*
	 * Start streaming.
	 */
	ret = vb2_streamon(q, q->type);
	if (ret)
		goto err_reqbufs;

2367 2368 2369 2370 2371
	q->fileio = fileio;

	return ret;

err_reqbufs:
2372
	fileio->req.count = 0;
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
	vb2_reqbufs(q, &fileio->req);

err_kfree:
	kfree(fileio);
	return ret;
}

/**
 * __vb2_cleanup_fileio() - free resourced used by file io emulator
 * @q:		videobuf2 queue
 */
static int __vb2_cleanup_fileio(struct vb2_queue *q)
{
	struct vb2_fileio_data *fileio = q->fileio;

	if (fileio) {
2389
		vb2_internal_streamoff(q, q->type);
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
		q->fileio = NULL;
		fileio->req.count = 0;
		vb2_reqbufs(q, &fileio->req);
		kfree(fileio);
		dprintk(3, "file io emulator closed\n");
	}
	return 0;
}

/**
 * __vb2_perform_fileio() - perform a single file io (read or write) operation
 * @q:		videobuf2 queue
 * @data:	pointed to target userspace buffer
 * @count:	number of bytes to read or write
 * @ppos:	file handle position tracking pointer
 * @nonblock:	mode selector (1 means blocking calls, 0 means nonblocking)
 * @read:	access mode selector (1 means read, 0 means write)
 */
static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
		loff_t *ppos, int nonblock, int read)
{
	struct vb2_fileio_data *fileio;
	struct vb2_fileio_buf *buf;
	int ret, index;

2415
	dprintk(3, "file io: mode %s, offset %ld, count %zd, %sblocking\n",
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
		read ? "read" : "write", (long)*ppos, count,
		nonblock ? "non" : "");

	if (!data)
		return -EINVAL;

	/*
	 * Initialize emulator on first call.
	 */
	if (!q->fileio) {
		ret = __vb2_init_fileio(q, read);
		dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
		if (ret)
			return ret;
	}
	fileio = q->fileio;

	index = fileio->index;
	buf = &fileio->bufs[index];

	/*
	 * Check if we need to dequeue the buffer.
	 */
	if (buf->queued) {
		struct vb2_buffer *vb;

		/*
		 * Call vb2_dqbuf to get buffer back.
		 */
		memset(&fileio->b, 0, sizeof(fileio->b));
		fileio->b.type = q->type;
		fileio->b.memory = q->memory;
2448
		ret = vb2_internal_dqbuf(q, &fileio->b, nonblock);
2449 2450
		dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
		if (ret)
2451
			return ret;
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
		fileio->dq_count += 1;

		/*
		 * Get number of bytes filled by the driver
		 */
		vb = q->bufs[index];
		buf->size = vb2_get_plane_payload(vb, 0);
		buf->queued = 0;
	}

	/*
	 * Limit count on last few bytes of the buffer.
	 */
	if (buf->pos + count > buf->size) {
		count = buf->size - buf->pos;
2467
		dprintk(5, "reducing read count: %zd\n", count);
2468 2469 2470 2471 2472
	}

	/*
	 * Transfer data to userspace.
	 */
2473
	dprintk(3, "file io: copying %zd bytes - buffer %d, offset %u\n",
2474 2475 2476 2477 2478 2479 2480
		count, index, buf->pos);
	if (read)
		ret = copy_to_user(data, buf->vaddr + buf->pos, count);
	else
		ret = copy_from_user(buf->vaddr + buf->pos, data, count);
	if (ret) {
		dprintk(3, "file io: error copying data\n");
2481
		return -EFAULT;
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
	}

	/*
	 * Update counters.
	 */
	buf->pos += count;
	*ppos += count;

	/*
	 * Queue next buffer if required.
	 */
	if (buf->pos == buf->size ||
	   (!read && (fileio->flags & VB2_FILEIO_WRITE_IMMEDIATELY))) {
		/*
		 * Check if this is the last buffer to read.
		 */
		if (read && (fileio->flags & VB2_FILEIO_READ_ONCE) &&
		    fileio->dq_count == 1) {
			dprintk(3, "file io: read limit reached\n");
			return __vb2_cleanup_fileio(q);
		}

		/*
		 * Call vb2_qbuf and give buffer to the driver.
		 */
		memset(&fileio->b, 0, sizeof(fileio->b));
		fileio->b.type = q->type;
		fileio->b.memory = q->memory;
		fileio->b.index = index;
		fileio->b.bytesused = buf->pos;
2512
		ret = vb2_internal_qbuf(q, &fileio->b);
2513 2514
		dprintk(5, "file io: vb2_dbuf result: %d\n", ret);
		if (ret)
2515
			return ret;
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545

		/*
		 * Buffer has been queued, update the status
		 */
		buf->pos = 0;
		buf->queued = 1;
		buf->size = q->bufs[0]->v4l2_planes[0].length;
		fileio->q_count += 1;

		/*
		 * Switch to the next buffer
		 */
		fileio->index = (index + 1) % q->num_buffers;
	}

	/*
	 * Return proper number of bytes processed.
	 */
	if (ret == 0)
		ret = count;
	return ret;
}

size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
		loff_t *ppos, int nonblocking)
{
	return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
}
EXPORT_SYMBOL_GPL(vb2_read);

2546
size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2547 2548
		loff_t *ppos, int nonblocking)
{
2549 2550
	return __vb2_perform_fileio(q, (char __user *) data, count,
							ppos, nonblocking, 0);
2551 2552 2553
}
EXPORT_SYMBOL_GPL(vb2_write);

2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671

/*
 * The following functions are not part of the vb2 core API, but are helper
 * functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
 * and struct vb2_ops.
 * They contain boilerplate code that most if not all drivers have to do
 * and so they simplify the driver code.
 */

/* The queue is busy if there is a owner and you are not that owner. */
static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
{
	return vdev->queue->owner && vdev->queue->owner != file->private_data;
}

/* vb2 ioctl helpers */

int vb2_ioctl_reqbufs(struct file *file, void *priv,
			  struct v4l2_requestbuffers *p)
{
	struct video_device *vdev = video_devdata(file);
	int res = __verify_memory_type(vdev->queue, p->memory, p->type);

	if (res)
		return res;
	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	res = __reqbufs(vdev->queue, p);
	/* If count == 0, then the owner has released all buffers and he
	   is no longer owner of the queue. Otherwise we have a new owner. */
	if (res == 0)
		vdev->queue->owner = p->count ? file->private_data : NULL;
	return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);

int vb2_ioctl_create_bufs(struct file *file, void *priv,
			  struct v4l2_create_buffers *p)
{
	struct video_device *vdev = video_devdata(file);
	int res = __verify_memory_type(vdev->queue, p->memory, p->format.type);

	p->index = vdev->queue->num_buffers;
	/* If count == 0, then just check if memory and type are valid.
	   Any -EBUSY result from __verify_memory_type can be mapped to 0. */
	if (p->count == 0)
		return res != -EBUSY ? res : 0;
	if (res)
		return res;
	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	res = __create_bufs(vdev->queue, p);
	if (res == 0)
		vdev->queue->owner = file->private_data;
	return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);

int vb2_ioctl_prepare_buf(struct file *file, void *priv,
			  struct v4l2_buffer *p)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_prepare_buf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);

int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
	struct video_device *vdev = video_devdata(file);

	/* No need to call vb2_queue_is_busy(), anyone can query buffers. */
	return vb2_querybuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);

int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_qbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);

int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);

int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_streamon(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);

int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_streamoff(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);

2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
{
	struct video_device *vdev = video_devdata(file);

	if (vb2_queue_is_busy(vdev, file))
		return -EBUSY;
	return vb2_expbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);

2682 2683 2684 2685 2686
/* v4l2_file_operations helpers */

int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
{
	struct video_device *vdev = video_devdata(file);
2687 2688
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
	int err;
2689

2690 2691 2692 2693 2694 2695
	if (lock && mutex_lock_interruptible(lock))
		return -ERESTARTSYS;
	err = vb2_mmap(vdev->queue, vma);
	if (lock)
		mutex_unlock(lock);
	return err;
2696 2697 2698
}
EXPORT_SYMBOL_GPL(vb2_fop_mmap);

2699
int _vb2_fop_release(struct file *file, struct mutex *lock)
2700 2701 2702 2703
{
	struct video_device *vdev = video_devdata(file);

	if (file->private_data == vdev->queue->owner) {
2704 2705
		if (lock)
			mutex_lock(lock);
2706 2707
		vb2_queue_release(vdev->queue);
		vdev->queue->owner = NULL;
2708 2709
		if (lock)
			mutex_unlock(lock);
2710 2711 2712
	}
	return v4l2_fh_release(file);
}
2713 2714 2715 2716 2717 2718 2719 2720 2721
EXPORT_SYMBOL_GPL(_vb2_fop_release);

int vb2_fop_release(struct file *file)
{
	struct video_device *vdev = video_devdata(file);
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;

	return _vb2_fop_release(file, lock);
}
2722 2723
EXPORT_SYMBOL_GPL(vb2_fop_release);

2724
ssize_t vb2_fop_write(struct file *file, const char __user *buf,
2725 2726 2727 2728 2729 2730
		size_t count, loff_t *ppos)
{
	struct video_device *vdev = video_devdata(file);
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
	int err = -EBUSY;

2731
	if (lock && mutex_lock_interruptible(lock))
2732 2733 2734 2735 2736
		return -ERESTARTSYS;
	if (vb2_queue_is_busy(vdev, file))
		goto exit;
	err = vb2_write(vdev->queue, buf, count, ppos,
		       file->f_flags & O_NONBLOCK);
2737
	if (vdev->queue->fileio)
2738 2739
		vdev->queue->owner = file->private_data;
exit:
2740
	if (lock)
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
		mutex_unlock(lock);
	return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_write);

ssize_t vb2_fop_read(struct file *file, char __user *buf,
		size_t count, loff_t *ppos)
{
	struct video_device *vdev = video_devdata(file);
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
	int err = -EBUSY;

2753
	if (lock && mutex_lock_interruptible(lock))
2754 2755 2756 2757 2758
		return -ERESTARTSYS;
	if (vb2_queue_is_busy(vdev, file))
		goto exit;
	err = vb2_read(vdev->queue, buf, count, ppos,
		       file->f_flags & O_NONBLOCK);
2759
	if (vdev->queue->fileio)
2760 2761
		vdev->queue->owner = file->private_data;
exit:
2762
	if (lock)
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
		mutex_unlock(lock);
	return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_read);

unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
{
	struct video_device *vdev = video_devdata(file);
	struct vb2_queue *q = vdev->queue;
	struct mutex *lock = q->lock ? q->lock : vdev->lock;
	unsigned long req_events = poll_requested_events(wait);
	unsigned res;
	void *fileio;
	bool must_lock = false;

	/* Try to be smart: only lock if polling might start fileio,
	   otherwise locking will only introduce unwanted delays. */
	if (q->num_buffers == 0 && q->fileio == NULL) {
		if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ) &&
				(req_events & (POLLIN | POLLRDNORM)))
			must_lock = true;
		else if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE) &&
				(req_events & (POLLOUT | POLLWRNORM)))
			must_lock = true;
	}

	/* If locking is needed, but this helper doesn't know how, then you
	   shouldn't be using this helper but you should write your own. */
2791
	WARN_ON(must_lock && !lock);
2792

2793
	if (must_lock && lock && mutex_lock_interruptible(lock))
2794 2795 2796 2797 2798 2799 2800 2801 2802
		return POLLERR;

	fileio = q->fileio;

	res = vb2_poll(vdev->queue, file, wait);

	/* If fileio was started, then we have a new queue owner. */
	if (must_lock && !fileio && q->fileio)
		q->owner = file->private_data;
2803
	if (must_lock && lock)
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
		mutex_unlock(lock);
	return res;
}
EXPORT_SYMBOL_GPL(vb2_fop_poll);

#ifndef CONFIG_MMU
unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
		unsigned long len, unsigned long pgoff, unsigned long flags)
{
	struct video_device *vdev = video_devdata(file);
2814 2815
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
	int ret;
2816

2817 2818 2819 2820 2821 2822
	if (lock && mutex_lock_interruptible(lock))
		return -ERESTARTSYS;
	ret = vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
	if (lock)
		mutex_unlock(lock);
	return ret;
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
}
EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
#endif

/* vb2_ops helpers. Only use if vq->lock is non-NULL. */

void vb2_ops_wait_prepare(struct vb2_queue *vq)
{
	mutex_unlock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);

void vb2_ops_wait_finish(struct vb2_queue *vq)
{
	mutex_lock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);

2841
MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
2842
MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2843
MODULE_LICENSE("GPL");