videobuf2-core.c 97.2 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
 *	   Marek Szyprowski <m.szyprowski@samsung.com>
 *
H
Hans Verkuil 已提交
9 10 11
 * The vb2_thread implementation was based on code from videobuf-dvb.c:
 *	(c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
 *
12 13 14 15 16 17 18 19 20 21 22 23
 * 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>
H
Hans Verkuil 已提交
24 25
#include <linux/freezer.h>
#include <linux/kthread.h>
26

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

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

H
Hans Verkuil 已提交
36 37 38
#define dprintk(level, fmt, arg...)					      \
	do {								      \
		if (debug >= level)					      \
39
			pr_info("vb2: %s: " fmt, __func__, ## arg); \
40 41
	} while (0)

42 43 44
#ifdef CONFIG_VIDEO_ADV_DEBUG

/*
45 46
 * If advanced debugging is on, then count how often each op is called
 * successfully, which can either be per-buffer or per-queue.
47
 *
48
 * This makes it easy to check that the 'init' and 'cleanup'
49 50 51
 * (and variations thereof) stay balanced.
 */

52 53 54 55 56
#define log_memop(vb, op)						\
	dprintk(2, "call_memop(%p, %d, %s)%s\n",			\
		(vb)->vb2_queue, (vb)->v4l2_buf.index, #op,		\
		(vb)->vb2_queue->mem_ops->op ? "" : " (nop)")

57 58 59
#define call_memop(vb, op, args...)					\
({									\
	struct vb2_queue *_q = (vb)->vb2_queue;				\
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	int err;							\
									\
	log_memop(vb, op);						\
	err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0;		\
	if (!err)							\
		(vb)->cnt_mem_ ## op++;					\
	err;								\
})

#define call_ptr_memop(vb, op, args...)					\
({									\
	struct vb2_queue *_q = (vb)->vb2_queue;				\
	void *ptr;							\
									\
	log_memop(vb, op);						\
	ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL;		\
	if (!IS_ERR_OR_NULL(ptr))					\
		(vb)->cnt_mem_ ## op++;					\
	ptr;								\
})

#define call_void_memop(vb, op, args...)				\
({									\
	struct vb2_queue *_q = (vb)->vb2_queue;				\
									\
	log_memop(vb, op);						\
	if (_q->mem_ops->op)						\
		_q->mem_ops->op(args);					\
88 89
	(vb)->cnt_mem_ ## op++;						\
})
90 91 92 93

#define log_qop(q, op)							\
	dprintk(2, "call_qop(%p, %s)%s\n", q, #op,			\
		(q)->ops->op ? "" : " (nop)")
94 95 96

#define call_qop(q, op, args...)					\
({									\
97 98 99 100 101 102 103 104 105 106 107 108 109 110
	int err;							\
									\
	log_qop(q, op);							\
	err = (q)->ops->op ? (q)->ops->op(args) : 0;			\
	if (!err)							\
		(q)->cnt_ ## op++;					\
	err;								\
})

#define call_void_qop(q, op, args...)					\
({									\
	log_qop(q, op);							\
	if ((q)->ops->op)						\
		(q)->ops->op(args);					\
111 112
	(q)->cnt_ ## op++;						\
})
113 114 115 116 117

#define log_vb_qop(vb, op, args...)					\
	dprintk(2, "call_vb_qop(%p, %d, %s)%s\n",			\
		(vb)->vb2_queue, (vb)->v4l2_buf.index, #op,		\
		(vb)->vb2_queue->ops->op ? "" : " (nop)")
118 119 120

#define call_vb_qop(vb, op, args...)					\
({									\
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	int err;							\
									\
	log_vb_qop(vb, op);						\
	err = (vb)->vb2_queue->ops->op ?				\
		(vb)->vb2_queue->ops->op(args) : 0;			\
	if (!err)							\
		(vb)->cnt_ ## op++;					\
	err;								\
})

#define call_void_vb_qop(vb, op, args...)				\
({									\
	log_vb_qop(vb, op);						\
	if ((vb)->vb2_queue->ops->op)					\
		(vb)->vb2_queue->ops->op(args);				\
136 137 138 139 140 141
	(vb)->cnt_ ## op++;						\
})

#else

#define call_memop(vb, op, args...)					\
142 143 144 145 146 147 148 149 150 151 152 153
	((vb)->vb2_queue->mem_ops->op ?					\
		(vb)->vb2_queue->mem_ops->op(args) : 0)

#define call_ptr_memop(vb, op, args...)					\
	((vb)->vb2_queue->mem_ops->op ?					\
		(vb)->vb2_queue->mem_ops->op(args) : NULL)

#define call_void_memop(vb, op, args...)				\
	do {								\
		if ((vb)->vb2_queue->mem_ops->op)			\
			(vb)->vb2_queue->mem_ops->op(args);		\
	} while (0)
154 155

#define call_qop(q, op, args...)					\
156
	((q)->ops->op ? (q)->ops->op(args) : 0)
157 158 159 160 161 162

#define call_void_qop(q, op, args...)					\
	do {								\
		if ((q)->ops->op)					\
			(q)->ops->op(args);				\
	} while (0)
163 164 165

#define call_vb_qop(vb, op, args...)					\
	((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
166 167 168 169 170 171

#define call_void_vb_qop(vb, op, args...)				\
	do {								\
		if ((vb)->vb2_queue->ops->op)				\
			(vb)->vb2_queue->ops->op(args);			\
	} while (0)
172 173

#endif
174

175
/* Flags that are set by the vb2 core */
176
#define V4L2_BUFFER_MASK_FLAGS	(V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
177
				 V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
178 179
				 V4L2_BUF_FLAG_PREPARED | \
				 V4L2_BUF_FLAG_TIMESTAMP_MASK)
180 181 182
/* Output buffer flags that should be passed on to the driver */
#define V4L2_BUFFER_OUT_FLAGS	(V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | \
				 V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_TIMECODE)
183

184
static void __vb2_queue_cancel(struct vb2_queue *q);
185
static void __enqueue_in_driver(struct vb2_buffer *vb);
186

187 188 189
/**
 * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
 */
190
static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
191 192
{
	struct vb2_queue *q = vb->vb2_queue;
193 194
	enum dma_data_direction dma_dir =
		V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
195 196 197
	void *mem_priv;
	int plane;

198 199 200 201
	/*
	 * Allocate memory for all planes in this buffer
	 * NOTE: mmapped areas should be page aligned
	 */
202
	for (plane = 0; plane < vb->num_planes; ++plane) {
203 204
		unsigned long size = PAGE_ALIGN(q->plane_sizes[plane]);

205
		mem_priv = call_ptr_memop(vb, alloc, q->alloc_ctx[plane],
206
				      size, dma_dir, q->gfp_flags);
207
		if (IS_ERR_OR_NULL(mem_priv))
208 209 210 211
			goto free;

		/* Associate allocator private data with this plane */
		vb->planes[plane].mem_priv = mem_priv;
212
		vb->v4l2_planes[plane].length = q->plane_sizes[plane];
213 214 215 216 217
	}

	return 0;
free:
	/* Free already allocated memory if one of the allocations failed */
218
	for (; plane > 0; --plane) {
219
		call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
220 221
		vb->planes[plane - 1].mem_priv = NULL;
	}
222 223 224 225 226 227 228 229 230 231 232 233

	return -ENOMEM;
}

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

	for (plane = 0; plane < vb->num_planes; ++plane) {
234
		call_void_memop(vb, put, vb->planes[plane].mem_priv);
235
		vb->planes[plane].mem_priv = NULL;
236
		dprintk(3, "freed plane %d of buffer %d\n", plane,
237
			vb->v4l2_buf.index);
238 239 240 241 242 243 244 245 246 247 248 249
	}
}

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

	for (plane = 0; plane < vb->num_planes; ++plane) {
250
		if (vb->planes[plane].mem_priv)
251
			call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
252
		vb->planes[plane].mem_priv = NULL;
253 254 255
	}
}

256 257 258 259
/**
 * __vb2_plane_dmabuf_put() - release memory associated with
 * a DMABUF shared plane
 */
260
static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
261 262 263 264 265
{
	if (!p->mem_priv)
		return;

	if (p->dbuf_mapped)
266
		call_void_memop(vb, unmap_dmabuf, p->mem_priv);
267

268
	call_void_memop(vb, detach_dmabuf, p->mem_priv);
269 270 271 272 273 274 275 276 277 278 279 280 281
	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)
{
	unsigned int plane;

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

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/**
 * __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];
	}
}

304 305 306 307
/**
 * __setup_offsets() - setup unique offsets ("cookies") for every plane in
 * every buffer on the queue
 */
308
static void __setup_offsets(struct vb2_queue *q, unsigned int n)
309 310 311
{
	unsigned int buffer, plane;
	struct vb2_buffer *vb;
312
	unsigned long off;
313

314 315 316 317 318 319 320 321 322 323
	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) {
324 325 326 327 328 329 330
		vb = q->bufs[buffer];
		if (!vb)
			continue;

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

331
			dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
					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,
348
			     unsigned int num_buffers, unsigned int num_planes)
349 350 351 352 353 354 355 356 357
{
	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) {
358
			dprintk(1, "memory alloc for buffer struct failed\n");
359 360 361 362 363 364 365 366 367 368
			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;
369
		vb->v4l2_buf.index = q->num_buffers + buffer;
370 371 372 373 374
		vb->v4l2_buf.type = q->type;
		vb->v4l2_buf.memory = memory;

		/* Allocate video buffer memory for the MMAP type */
		if (memory == V4L2_MEMORY_MMAP) {
375
			ret = __vb2_buf_mem_alloc(vb);
376
			if (ret) {
377
				dprintk(1, "failed allocating memory for "
378 379 380 381 382 383 384 385 386
						"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.
			 */
387
			ret = call_vb_qop(vb, buf_init, vb);
388
			if (ret) {
389
				dprintk(1, "buffer %d %p initialization"
390 391 392 393 394 395 396
					" failed\n", buffer, vb);
				__vb2_buf_mem_free(vb);
				kfree(vb);
				break;
			}
		}

397
		q->bufs[q->num_buffers + buffer] = vb;
398 399
	}

400
	__setup_lengths(q, buffer);
401 402
	if (memory == V4L2_MEMORY_MMAP)
		__setup_offsets(q, buffer);
403

404
	dprintk(1, "allocated %d buffers, %d plane(s) each\n",
405
			buffer, num_planes);
406 407 408 409 410 411 412

	return buffer;
}

/**
 * __vb2_free_mem() - release all video buffer memory for a given queue
 */
413
static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
414 415 416 417
{
	unsigned int buffer;
	struct vb2_buffer *vb;

418 419
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
420 421 422 423 424 425 426
		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);
427 428
		else if (q->memory == V4L2_MEMORY_DMABUF)
			__vb2_buf_dmabuf_put(vb);
429 430 431 432 433 434
		else
			__vb2_buf_userptr_put(vb);
	}
}

/**
435 436 437
 * __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.
438
 */
439
static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
440 441 442
{
	unsigned int buffer;

443 444 445 446 447 448 449 450 451 452 453 454 455
	/*
	 * 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) {
H
Hans Verkuil 已提交
456
			dprintk(1, "preparing buffers, cannot free\n");
457 458 459 460
			return -EAGAIN;
		}
	}

461
	/* Call driver-provided cleanup function for each buffer, if provided */
462 463
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
464 465 466
		struct vb2_buffer *vb = q->bufs[buffer];

		if (vb && vb->planes[0].mem_priv)
467
			call_void_vb_qop(vb, buf_cleanup, vb);
468 469 470
	}

	/* Release video buffer memory */
471
	__vb2_free_mem(q, buffers);
472

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
#ifdef CONFIG_VIDEO_ADV_DEBUG
	/*
	 * Check that all the calls were balances during the life-time of this
	 * queue. If not (or if the debug level is 1 or up), then dump the
	 * counters to the kernel log.
	 */
	if (q->num_buffers) {
		bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
				  q->cnt_wait_prepare != q->cnt_wait_finish;

		if (unbalanced || debug) {
			pr_info("vb2: counters for queue %p:%s\n", q,
				unbalanced ? " UNBALANCED!" : "");
			pr_info("vb2:     setup: %u start_streaming: %u stop_streaming: %u\n",
				q->cnt_queue_setup, q->cnt_start_streaming,
				q->cnt_stop_streaming);
			pr_info("vb2:     wait_prepare: %u wait_finish: %u\n",
				q->cnt_wait_prepare, q->cnt_wait_finish);
		}
		q->cnt_queue_setup = 0;
		q->cnt_wait_prepare = 0;
		q->cnt_wait_finish = 0;
		q->cnt_start_streaming = 0;
		q->cnt_stop_streaming = 0;
	}
	for (buffer = 0; buffer < q->num_buffers; ++buffer) {
		struct vb2_buffer *vb = q->bufs[buffer];
		bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
				  vb->cnt_mem_prepare != vb->cnt_mem_finish ||
				  vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
				  vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
				  vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
				  vb->cnt_buf_queue != vb->cnt_buf_done ||
				  vb->cnt_buf_prepare != vb->cnt_buf_finish ||
				  vb->cnt_buf_init != vb->cnt_buf_cleanup;

		if (unbalanced || debug) {
			pr_info("vb2:   counters for queue %p, buffer %d:%s\n",
				q, buffer, unbalanced ? " UNBALANCED!" : "");
			pr_info("vb2:     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
				vb->cnt_buf_init, vb->cnt_buf_cleanup,
				vb->cnt_buf_prepare, vb->cnt_buf_finish);
			pr_info("vb2:     buf_queue: %u buf_done: %u\n",
				vb->cnt_buf_queue, vb->cnt_buf_done);
			pr_info("vb2:     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
				vb->cnt_mem_alloc, vb->cnt_mem_put,
				vb->cnt_mem_prepare, vb->cnt_mem_finish,
				vb->cnt_mem_mmap);
			pr_info("vb2:     get_userptr: %u put_userptr: %u\n",
				vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
			pr_info("vb2:     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
				vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
				vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
			pr_info("vb2:     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
				vb->cnt_mem_get_dmabuf,
				vb->cnt_mem_num_users,
				vb->cnt_mem_vaddr,
				vb->cnt_mem_cookie);
		}
	}
#endif

535
	/* Free videobuf buffers */
536 537
	for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
	     ++buffer) {
538 539 540 541
		kfree(q->bufs[buffer]);
		q->bufs[buffer] = NULL;
	}

542
	q->num_buffers -= buffers;
543
	if (!q->num_buffers) {
544
		q->memory = 0;
545 546
		INIT_LIST_HEAD(&q->queued_list);
	}
547
	return 0;
548 549 550 551 552 553
}

/**
 * __verify_planes_array() - verify that the planes array passed in struct
 * v4l2_buffer from userspace can be safely used
 */
554
static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
555
{
556 557 558
	if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
		return 0;

559 560
	/* Is memory for copying plane information present? */
	if (NULL == b->m.planes) {
561
		dprintk(1, "multi-planar buffer passed but "
562 563 564 565 566
			   "planes array not provided\n");
		return -EINVAL;
	}

	if (b->length < vb->num_planes || b->length > VIDEO_MAX_PLANES) {
567
		dprintk(1, "incorrect planes array length, "
568 569 570 571 572 573 574
			   "expected %d, got %d\n", vb->num_planes, b->length);
		return -EINVAL;
	}

	return 0;
}

575 576 577 578 579 580 581
/**
 * __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;
582
	unsigned int bytesused;
583 584 585 586 587 588 589
	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) {
590 591
			length = (b->memory == V4L2_MEMORY_USERPTR ||
				  b->memory == V4L2_MEMORY_DMABUF)
592 593
			       ? b->m.planes[plane].length
			       : vb->v4l2_planes[plane].length;
594 595
			bytesused = b->m.planes[plane].bytesused
				  ? b->m.planes[plane].bytesused : length;
596 597 598

			if (b->m.planes[plane].bytesused > length)
				return -EINVAL;
599 600

			if (b->m.planes[plane].data_offset > 0 &&
601
			    b->m.planes[plane].data_offset >= bytesused)
602 603 604 605 606
				return -EINVAL;
		}
	} else {
		length = (b->memory == V4L2_MEMORY_USERPTR)
		       ? b->length : vb->v4l2_planes[0].length;
607
		bytesused = b->bytesused ? b->bytesused : length;
608 609 610 611 612 613 614 615

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

	return 0;
}

616 617 618 619 620 621 622 623
/**
 * __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) {
624
		void *mem_priv = vb->planes[plane].mem_priv;
625 626 627 628 629 630
		/*
		 * 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.
		 */
631
		if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
			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;
}

651 652 653 654
/**
 * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
 * returned to userspace
 */
655
static void __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
656 657 658
{
	struct vb2_queue *q = vb->vb2_queue;

659
	/* Copy back data such as timestamp, flags, etc. */
660
	memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
661
	b->reserved2 = vb->v4l2_buf.reserved2;
662 663 664 665 666
	b->reserved = vb->v4l2_buf.reserved;

	if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
		/*
		 * Fill in plane-related data if userspace provided an array
667
		 * for it. The caller has already verified memory and size.
668
		 */
669
		b->length = vb->num_planes;
670 671 672 673 674 675 676 677 678 679 680 681 682
		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;
683 684
		else if (q->memory == V4L2_MEMORY_DMABUF)
			b->m.fd = vb->v4l2_planes[0].m.fd;
685 686
	}

687 688 689
	/*
	 * Clear any buffer state related flags.
	 */
690
	b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
691 692 693 694 695 696 697 698 699 700
	b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;
	if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
	    V4L2_BUF_FLAG_TIMESTAMP_COPY) {
		/*
		 * For non-COPY timestamps, drop timestamp source bits
		 * and obtain the timestamp source from the queue.
		 */
		b->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
		b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
	}
701 702 703 704 705 706 707 708 709 710 711 712

	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;
713
	case VB2_BUF_STATE_PREPARED:
714 715
		b->flags |= V4L2_BUF_FLAG_PREPARED;
		break;
716
	case VB2_BUF_STATE_PREPARING:
717
	case VB2_BUF_STATE_DEQUEUED:
718 719 720 721
		/* nothing */
		break;
	}

722
	if (__buffer_in_use(q, vb))
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
		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;
742
	int ret;
743 744

	if (b->type != q->type) {
H
Hans Verkuil 已提交
745
		dprintk(1, "wrong buffer type\n");
746 747 748 749
		return -EINVAL;
	}

	if (b->index >= q->num_buffers) {
H
Hans Verkuil 已提交
750
		dprintk(1, "buffer index out of range\n");
751 752 753
		return -EINVAL;
	}
	vb = q->bufs[b->index];
754 755 756 757
	ret = __verify_planes_array(vb, b);
	if (!ret)
		__fill_v4l2_buffer(vb, b);
	return ret;
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
}
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;
}

787 788 789 790 791 792 793 794 795 796 797 798 799 800
/**
 * __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;
}

801
/**
802 803 804 805 806 807
 * __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)
{
808 809
	if (memory != V4L2_MEMORY_MMAP && memory != V4L2_MEMORY_USERPTR &&
	    memory != V4L2_MEMORY_DMABUF) {
H
Hans Verkuil 已提交
810
		dprintk(1, "unsupported memory type\n");
811 812 813 814
		return -EINVAL;
	}

	if (type != q->type) {
H
Hans Verkuil 已提交
815
		dprintk(1, "requested type is incorrect\n");
816 817 818 819 820 821 822 823
		return -EINVAL;
	}

	/*
	 * Make sure all the required memory ops for given memory type
	 * are available.
	 */
	if (memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
H
Hans Verkuil 已提交
824
		dprintk(1, "MMAP for current setup unsupported\n");
825 826 827 828
		return -EINVAL;
	}

	if (memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
H
Hans Verkuil 已提交
829
		dprintk(1, "USERPTR for current setup unsupported\n");
830 831 832
		return -EINVAL;
	}

833
	if (memory == V4L2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
H
Hans Verkuil 已提交
834
		dprintk(1, "DMABUF for current setup unsupported\n");
835 836 837
		return -EINVAL;
	}

838 839 840 841 842
	/*
	 * 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.
	 */
843
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
844
		dprintk(1, "file io in progress\n");
845 846 847 848 849 850 851
		return -EBUSY;
	}
	return 0;
}

/**
 * __reqbufs() - Initiate streaming
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
 * @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.
 */
873
static int __reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
874
{
875
	unsigned int num_buffers, allocated_buffers, num_planes = 0;
876
	int ret;
877 878

	if (q->streaming) {
H
Hans Verkuil 已提交
879
		dprintk(1, "streaming active\n");
880 881 882
		return -EBUSY;
	}

883
	if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
884 885 886 887
		/*
		 * We already have buffers allocated, so first check if they
		 * are not in use and can be freed.
		 */
888
		mutex_lock(&q->mmap_lock);
889
		if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
890
			mutex_unlock(&q->mmap_lock);
H
Hans Verkuil 已提交
891
			dprintk(1, "memory in use, cannot free\n");
892 893 894
			return -EBUSY;
		}

895 896 897 898 899 900
		/*
		 * Call queue_cancel to clean up any buffers in the PREPARED or
		 * QUEUED state which is possible if buffers were prepared or
		 * queued without ever calling STREAMON.
		 */
		__vb2_queue_cancel(q);
901
		ret = __vb2_queue_free(q, q->num_buffers);
902
		mutex_unlock(&q->mmap_lock);
903 904
		if (ret)
			return ret;
905 906 907 908 909 910 911

		/*
		 * In case of REQBUFS(0) return immediately without calling
		 * driver's queue_setup() callback and allocating resources.
		 */
		if (req->count == 0)
			return 0;
912 913 914 915 916 917
	}

	/*
	 * Make sure the requested values and current defaults are sane.
	 */
	num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
918
	num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
919
	memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
920
	memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
921
	q->memory = req->memory;
922 923 924 925 926

	/*
	 * Ask the driver how many buffers and planes per buffer it requires.
	 * Driver also sets the size and allocator context for each plane.
	 */
927
	ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
928
		       q->plane_sizes, q->alloc_ctx);
929
	if (ret)
930 931 932
		return ret;

	/* Finally, allocate buffers and video memory */
933 934
	allocated_buffers = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes);
	if (allocated_buffers == 0) {
935
		dprintk(1, "memory allocation failed\n");
936
		return -ENOMEM;
937 938
	}

939 940 941 942 943 944 945
	/*
	 * There is no point in continuing if we can't allocate the minimum
	 * number of buffers needed by this vb2_queue.
	 */
	if (allocated_buffers < q->min_buffers_needed)
		ret = -ENOMEM;

946 947 948
	/*
	 * Check if driver can handle the allocated number of buffers.
	 */
949
	if (!ret && allocated_buffers < num_buffers) {
950
		num_buffers = allocated_buffers;
951

952 953
		ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
			       &num_planes, q->plane_sizes, q->alloc_ctx);
954

955
		if (!ret && allocated_buffers < num_buffers)
956 957 958
			ret = -ENOMEM;

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

964
	mutex_lock(&q->mmap_lock);
965 966 967
	q->num_buffers = allocated_buffers;

	if (ret < 0) {
968 969 970 971
		/*
		 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
		 * from q->num_buffers.
		 */
972
		__vb2_queue_free(q, allocated_buffers);
973
		mutex_unlock(&q->mmap_lock);
974
		return ret;
975
	}
976
	mutex_unlock(&q->mmap_lock);
977 978 979 980 981

	/*
	 * Return the number of successfully allocated buffers
	 * to the userspace.
	 */
982
	req->count = allocated_buffers;
983
	q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
984 985 986

	return 0;
}
987 988 989 990 991 992 993 994 995 996 997 998 999

/**
 * 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);
}
1000 1001
EXPORT_SYMBOL_GPL(vb2_reqbufs);

1002
/**
1003
 * __create_bufs() - Allocate buffers and any required auxiliary structs
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
 * @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.
 */
1017
static int __create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
1018 1019
{
	unsigned int num_planes = 0, num_buffers, allocated_buffers;
1020
	int ret;
1021 1022

	if (q->num_buffers == VIDEO_MAX_FRAME) {
H
Hans Verkuil 已提交
1023
		dprintk(1, "maximum number of buffers already allocated\n");
1024 1025 1026 1027 1028 1029 1030
		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;
1031
		q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	}

	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);
1042
	if (ret)
1043 1044 1045
		return ret;

	/* Finally, allocate buffers and video memory */
1046
	allocated_buffers = __vb2_queue_alloc(q, create->memory, num_buffers,
1047
				num_planes);
1048
	if (allocated_buffers == 0) {
1049
		dprintk(1, "memory allocation failed\n");
1050
		return -ENOMEM;
1051 1052 1053 1054 1055
	}

	/*
	 * Check if driver can handle the so far allocated number of buffers.
	 */
1056 1057
	if (allocated_buffers < num_buffers) {
		num_buffers = allocated_buffers;
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

		/*
		 * 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
		 */
	}

1075
	mutex_lock(&q->mmap_lock);
1076 1077 1078
	q->num_buffers += allocated_buffers;

	if (ret < 0) {
1079 1080 1081 1082
		/*
		 * Note: __vb2_queue_free() will subtract 'allocated_buffers'
		 * from q->num_buffers.
		 */
1083
		__vb2_queue_free(q, allocated_buffers);
1084
		mutex_unlock(&q->mmap_lock);
1085
		return -ENOMEM;
1086
	}
1087
	mutex_unlock(&q->mmap_lock);
1088 1089 1090 1091 1092 1093 1094 1095 1096

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

	return 0;
}
1097 1098

/**
1099 1100
 * vb2_create_bufs() - Wrapper for __create_bufs() that also verifies the
 * memory and type values.
1101 1102 1103 1104 1105 1106 1107 1108 1109
 * @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;
1110 1111
	if (create->count == 0)
		return ret != -EBUSY ? ret : 0;
1112 1113
	return ret ? ret : __create_bufs(q, create);
}
1114 1115
EXPORT_SYMBOL_GPL(vb2_create_bufs);

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
/**
 * 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)
{
1126
	if (plane_no > vb->num_planes || !vb->planes[plane_no].mem_priv)
1127 1128
		return NULL;

1129
	return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

}
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)
{
1147
	if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
1148 1149
		return NULL;

1150
	return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
1151 1152 1153 1154 1155 1156
}
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
1157 1158 1159
 * @state:	either VB2_BUF_STATE_DONE if the operation finished successfully,
 *		VB2_BUF_STATE_ERROR if the operation finished with an error or
 *		VB2_BUF_STATE_QUEUED if the driver wants to requeue buffers.
1160 1161
 *		If start_streaming fails then it should return buffers with state
 *		VB2_BUF_STATE_QUEUED to put them back into the queue.
1162 1163 1164 1165 1166 1167
 *
 * 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.
1168 1169 1170 1171 1172
 *
 * While streaming a buffer can only be returned in state DONE or ERROR.
 * The start_streaming op can also return them in case the DMA engine cannot
 * be started for some reason. In that case the buffers should be returned with
 * state QUEUED.
1173 1174 1175 1176 1177
 */
void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
{
	struct vb2_queue *q = vb->vb2_queue;
	unsigned long flags;
1178
	unsigned int plane;
1179

1180
	if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
1181 1182
		return;

1183 1184 1185 1186
	if (WARN_ON(state != VB2_BUF_STATE_DONE &&
		    state != VB2_BUF_STATE_ERROR &&
		    state != VB2_BUF_STATE_QUEUED))
		state = VB2_BUF_STATE_ERROR;
1187

1188 1189 1190 1191 1192 1193 1194
#ifdef CONFIG_VIDEO_ADV_DEBUG
	/*
	 * Although this is not a callback, it still does have to balance
	 * with the buf_queue op. So update this counter manually.
	 */
	vb->cnt_buf_done++;
#endif
1195
	dprintk(4, "done processing on buffer %d, state: %d\n",
1196
			vb->v4l2_buf.index, state);
1197

1198 1199
	/* sync buffers */
	for (plane = 0; plane < vb->num_planes; ++plane)
1200
		call_void_memop(vb, finish, vb->planes[plane].mem_priv);
1201

1202 1203 1204
	/* Add the buffer to the done buffers list */
	spin_lock_irqsave(&q->done_lock, flags);
	vb->state = state;
1205 1206
	if (state != VB2_BUF_STATE_QUEUED)
		list_add_tail(&vb->done_entry, &q->done_list);
1207
	atomic_dec(&q->owned_by_drv_count);
1208 1209
	spin_unlock_irqrestore(&q->done_lock, flags);

1210 1211 1212
	if (state == VB2_BUF_STATE_QUEUED) {
		if (q->start_streaming_called)
			__enqueue_in_driver(vb);
1213
		return;
1214
	}
1215

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

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
/**
 * vb2_discard_done() - discard all buffers marked as DONE
 * @q:		videobuf2 queue
 *
 * This function is intended to be used with suspend/resume operations. It
 * discards all 'done' buffers as they would be too old to be requested after
 * resume.
 *
 * Drivers must stop the hardware and synchronize with interrupt handlers and/or
 * delayed works before calling this function to make sure no buffer will be
 * touched by the driver and/or hardware.
 */
void vb2_discard_done(struct vb2_queue *q)
{
	struct vb2_buffer *vb;
	unsigned long flags;

	spin_lock_irqsave(&q->done_lock, flags);
	list_for_each_entry(vb, &q->done_list, done_entry)
		vb->state = VB2_BUF_STATE_ERROR;
	spin_unlock_irqrestore(&q->done_lock, flags);
}
EXPORT_SYMBOL_GPL(vb2_discard_done);

1245
/**
1246 1247 1248
 * __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.
1249
 */
1250
static void __fill_vb2_buffer(struct vb2_buffer *vb, const struct v4l2_buffer *b,
1251 1252 1253 1254
				struct v4l2_plane *v4l2_planes)
{
	unsigned int plane;

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
	if (V4L2_TYPE_IS_OUTPUT(b->type)) {
		if (WARN_ON_ONCE(b->bytesused == 0)) {
			pr_warn_once("use of bytesused == 0 is deprecated and will be removed in the future,\n");
			if (vb->vb2_queue->allow_zero_bytesused)
				pr_warn_once("use VIDIOC_DECODER_CMD(V4L2_DEC_CMD_STOP) instead.\n");
			else
				pr_warn_once("use the actual size instead.\n");
		}
	}

1265 1266 1267 1268 1269 1270 1271 1272 1273
	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
		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;
			}
		}
1274 1275 1276 1277 1278 1279 1280 1281
		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;
			}
		}
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

		/* 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.
			 *
			 * If bytesused == 0 for the output buffer, then fall
			 * back to the full buffer size. In that case
			 * userspace clearly never bothered to set it and
			 * it's a safe assumption that they really meant to
			 * use the full plane sizes.
1294 1295 1296 1297 1298 1299
			 *
			 * Some drivers, e.g. old codec drivers, use bytesused == 0
			 * as a way to indicate that streaming is finished.
			 * In that case, the driver should use the
			 * allow_zero_bytesused flag to keep old userspace
			 * applications working.
1300 1301 1302 1303 1304
			 */
			for (plane = 0; plane < vb->num_planes; ++plane) {
				struct v4l2_plane *pdst = &v4l2_planes[plane];
				struct v4l2_plane *psrc = &b->m.planes[plane];

1305 1306 1307 1308 1309
				if (vb->vb2_queue->allow_zero_bytesused)
					pdst->bytesused = psrc->bytesused;
				else
					pdst->bytesused = psrc->bytesused ?
						psrc->bytesused : pdst->length;
1310 1311 1312
				pdst->data_offset = psrc->data_offset;
			}
		}
1313 1314 1315 1316 1317 1318
	} 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.
1319
		 *
1320 1321
		 * If bytesused == 0 for the output buffer, then fall back
		 * to the full buffer size as that's a sensible default.
1322 1323 1324 1325 1326
		 *
		 * Some drivers, e.g. old codec drivers, use bytesused == 0 as
		 * a way to indicate that streaming is finished. In that case,
		 * the driver should use the allow_zero_bytesused flag to keep
		 * old userspace applications working.
1327 1328 1329 1330 1331
		 */
		if (b->memory == V4L2_MEMORY_USERPTR) {
			v4l2_planes[0].m.userptr = b->m.userptr;
			v4l2_planes[0].length = b->length;
		}
1332 1333 1334 1335 1336

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

1338 1339 1340 1341 1342 1343 1344
		if (V4L2_TYPE_IS_OUTPUT(b->type)) {
			if (vb->vb2_queue->allow_zero_bytesused)
				v4l2_planes[0].bytesused = b->bytesused;
			else
				v4l2_planes[0].bytesused = b->bytesused ?
					b->bytesused : v4l2_planes[0].length;
		} else
1345 1346
			v4l2_planes[0].bytesused = 0;

1347 1348
	}

1349
	/* Zero flags that the vb2 core handles */
1350
	vb->v4l2_buf.flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
	if ((vb->vb2_queue->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) !=
	    V4L2_BUF_FLAG_TIMESTAMP_COPY || !V4L2_TYPE_IS_OUTPUT(b->type)) {
		/*
		 * Non-COPY timestamps and non-OUTPUT queues will get
		 * their timestamp and timestamp source flags from the
		 * queue.
		 */
		vb->v4l2_buf.flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
	}

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	if (V4L2_TYPE_IS_OUTPUT(b->type)) {
		/*
		 * For output buffers mask out the timecode flag:
		 * this will be handled later in vb2_internal_qbuf().
		 * The 'field' is valid metadata for this output buffer
		 * and so that needs to be copied here.
		 */
		vb->v4l2_buf.flags &= ~V4L2_BUF_FLAG_TIMECODE;
		vb->v4l2_buf.field = b->field;
	} else {
		/* Zero any output buffer flags as this is a capture buffer */
		vb->v4l2_buf.flags &= ~V4L2_BUFFER_OUT_FLAGS;
	}
1374 1375
}

1376 1377 1378 1379 1380 1381 1382 1383 1384
/**
 * __qbuf_mmap() - handle qbuf of an MMAP buffer
 */
static int __qbuf_mmap(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
	__fill_vb2_buffer(vb, b, vb->v4l2_planes);
	return call_vb_qop(vb, buf_prepare, vb);
}

1385 1386 1387
/**
 * __qbuf_userptr() - handle qbuf of a USERPTR buffer
 */
1388
static int __qbuf_userptr(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1389 1390 1391 1392 1393 1394
{
	struct v4l2_plane planes[VIDEO_MAX_PLANES];
	struct vb2_queue *q = vb->vb2_queue;
	void *mem_priv;
	unsigned int plane;
	int ret;
1395 1396
	enum dma_data_direction dma_dir =
		V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1397
	bool reacquired = vb->planes[0].mem_priv == NULL;
1398

1399
	memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1400 1401
	/* Copy relevant information provided by the userspace */
	__fill_vb2_buffer(vb, b, planes);
1402 1403 1404

	for (plane = 0; plane < vb->num_planes; ++plane) {
		/* Skip the plane if already verified */
1405 1406
		if (vb->v4l2_planes[plane].m.userptr &&
		    vb->v4l2_planes[plane].m.userptr == planes[plane].m.userptr
1407 1408 1409
		    && vb->v4l2_planes[plane].length == planes[plane].length)
			continue;

H
Hans Verkuil 已提交
1410
		dprintk(3, "userspace address for plane %d changed, "
1411 1412
				"reacquiring memory\n", plane);

1413 1414
		/* Check if the provided plane buffer is large enough */
		if (planes[plane].length < q->plane_sizes[plane]) {
H
Hans Verkuil 已提交
1415
			dprintk(1, "provided buffer size %u is less than "
1416 1417 1418
						"setup size %u for plane %d\n",
						planes[plane].length,
						q->plane_sizes[plane], plane);
1419
			ret = -EINVAL;
1420 1421 1422
			goto err;
		}

1423
		/* Release previously acquired memory if present */
1424 1425 1426
		if (vb->planes[plane].mem_priv) {
			if (!reacquired) {
				reacquired = true;
1427
				call_void_vb_qop(vb, buf_cleanup, vb);
1428
			}
1429
			call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1430
		}
1431 1432

		vb->planes[plane].mem_priv = NULL;
1433
		memset(&vb->v4l2_planes[plane], 0, sizeof(struct v4l2_plane));
1434 1435

		/* Acquire each plane's memory */
1436
		mem_priv = call_ptr_memop(vb, get_userptr, q->alloc_ctx[plane],
1437
				      planes[plane].m.userptr,
1438
				      planes[plane].length, dma_dir);
1439
		if (IS_ERR_OR_NULL(mem_priv)) {
H
Hans Verkuil 已提交
1440
			dprintk(1, "failed acquiring userspace "
1441
						"memory for plane %d\n", plane);
1442 1443
			ret = mem_priv ? PTR_ERR(mem_priv) : -EINVAL;
			goto err;
1444
		}
1445
		vb->planes[plane].mem_priv = mem_priv;
1446 1447 1448 1449 1450 1451 1452 1453 1454
	}

	/*
	 * 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];

1455 1456 1457 1458 1459 1460 1461 1462
	if (reacquired) {
		/*
		 * One or more planes changed, so we must call buf_init to do
		 * the driver-specific initialization on the newly acquired
		 * buffer, if provided.
		 */
		ret = call_vb_qop(vb, buf_init, vb);
		if (ret) {
H
Hans Verkuil 已提交
1463
			dprintk(1, "buffer initialization failed\n");
1464 1465 1466 1467 1468 1469
			goto err;
		}
	}

	ret = call_vb_qop(vb, buf_prepare, vb);
	if (ret) {
H
Hans Verkuil 已提交
1470
		dprintk(1, "buffer preparation failed\n");
1471
		call_void_vb_qop(vb, buf_cleanup, vb);
1472 1473 1474
		goto err;
	}

1475 1476 1477
	return 0;
err:
	/* In case of errors, release planes that were already acquired */
1478 1479
	for (plane = 0; plane < vb->num_planes; ++plane) {
		if (vb->planes[plane].mem_priv)
1480
			call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1481 1482 1483
		vb->planes[plane].mem_priv = NULL;
		vb->v4l2_planes[plane].m.userptr = 0;
		vb->v4l2_planes[plane].length = 0;
1484 1485 1486 1487 1488
	}

	return ret;
}

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
/**
 * __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;
1499 1500
	enum dma_data_direction dma_dir =
		V4L2_TYPE_IS_OUTPUT(q->type) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1501
	bool reacquired = vb->planes[0].mem_priv == NULL;
1502

1503
	memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1504
	/* Copy relevant information provided by the userspace */
1505 1506 1507 1508 1509 1510
	__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)) {
H
Hans Verkuil 已提交
1511
			dprintk(1, "invalid dmabuf fd for plane %d\n",
1512 1513 1514 1515 1516 1517 1518 1519 1520
				plane);
			ret = -EINVAL;
			goto err;
		}

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

1521
		if (planes[plane].length < q->plane_sizes[plane]) {
H
Hans Verkuil 已提交
1522
			dprintk(1, "invalid dmabuf length for plane %d\n",
1523
				plane);
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
			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;
		}

H
Hans Verkuil 已提交
1535
		dprintk(1, "buffer for plane %d changed\n", plane);
1536

1537 1538
		if (!reacquired) {
			reacquired = true;
1539
			call_void_vb_qop(vb, buf_cleanup, vb);
1540 1541
		}

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

		/* Acquire each plane's memory */
1547
		mem_priv = call_ptr_memop(vb, attach_dmabuf, q->alloc_ctx[plane],
1548
			dbuf, planes[plane].length, dma_dir);
1549
		if (IS_ERR(mem_priv)) {
H
Hans Verkuil 已提交
1550
			dprintk(1, "failed to attach dmabuf\n");
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
			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) {
1565
		ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1566
		if (ret) {
H
Hans Verkuil 已提交
1567
			dprintk(1, "failed to map dmabuf for plane %d\n",
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
				plane);
			goto err;
		}
		vb->planes[plane].dbuf_mapped = 1;
	}

	/*
	 * 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];

1581 1582 1583 1584 1585 1586 1587
	if (reacquired) {
		/*
		 * Call driver-specific initialization on the newly acquired buffer,
		 * if provided.
		 */
		ret = call_vb_qop(vb, buf_init, vb);
		if (ret) {
H
Hans Verkuil 已提交
1588
			dprintk(1, "buffer initialization failed\n");
1589 1590 1591 1592 1593 1594
			goto err;
		}
	}

	ret = call_vb_qop(vb, buf_prepare, vb);
	if (ret) {
H
Hans Verkuil 已提交
1595
		dprintk(1, "buffer preparation failed\n");
1596
		call_void_vb_qop(vb, buf_cleanup, vb);
1597 1598 1599
		goto err;
	}

1600 1601 1602 1603 1604 1605 1606 1607
	return 0;
err:
	/* In case of errors, release planes that were already acquired */
	__vb2_buf_dmabuf_put(vb);

	return ret;
}

1608 1609 1610 1611 1612 1613
/**
 * __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;
1614
	unsigned int plane;
1615 1616

	vb->state = VB2_BUF_STATE_ACTIVE;
1617
	atomic_inc(&q->owned_by_drv_count);
1618 1619 1620

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

1623
	call_void_vb_qop(vb, buf_queue, vb);
1624 1625
}

1626
static int __buf_prepare(struct vb2_buffer *vb, const struct v4l2_buffer *b)
1627 1628 1629 1630
{
	struct vb2_queue *q = vb->vb2_queue;
	int ret;

1631
	ret = __verify_length(vb, b);
1632
	if (ret < 0) {
H
Hans Verkuil 已提交
1633
		dprintk(1, "plane parameters verification failed: %d\n", ret);
1634
		return ret;
1635
	}
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
	if (b->field == V4L2_FIELD_ALTERNATE && V4L2_TYPE_IS_OUTPUT(q->type)) {
		/*
		 * If the format's field is ALTERNATE, then the buffer's field
		 * should be either TOP or BOTTOM, not ALTERNATE since that
		 * makes no sense. The driver has to know whether the
		 * buffer represents a top or a bottom field in order to
		 * program any DMA correctly. Using ALTERNATE is wrong, since
		 * that just says that it is either a top or a bottom field,
		 * but not which of the two it is.
		 */
		dprintk(1, "the field is incorrectly set to ALTERNATE for an output buffer\n");
		return -EINVAL;
	}
1649

1650 1651 1652 1653 1654
	if (q->error) {
		dprintk(1, "fatal error occurred on queue\n");
		return -EIO;
	}

1655
	vb->state = VB2_BUF_STATE_PREPARING;
1656 1657 1658 1659
	vb->v4l2_buf.timestamp.tv_sec = 0;
	vb->v4l2_buf.timestamp.tv_usec = 0;
	vb->v4l2_buf.sequence = 0;

1660 1661 1662 1663 1664 1665 1666
	switch (q->memory) {
	case V4L2_MEMORY_MMAP:
		ret = __qbuf_mmap(vb, b);
		break;
	case V4L2_MEMORY_USERPTR:
		ret = __qbuf_userptr(vb, b);
		break;
1667 1668 1669
	case V4L2_MEMORY_DMABUF:
		ret = __qbuf_dmabuf(vb, b);
		break;
1670 1671 1672 1673 1674 1675
	default:
		WARN(1, "Invalid queue type\n");
		ret = -EINVAL;
	}

	if (ret)
H
Hans Verkuil 已提交
1676
		dprintk(1, "buffer preparation failed: %d\n", ret);
1677
	vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1678 1679 1680 1681

	return ret;
}

1682
static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
1683
				    const char *opname)
1684 1685
{
	if (b->type != q->type) {
H
Hans Verkuil 已提交
1686
		dprintk(1, "%s: invalid buffer type\n", opname);
1687
		return -EINVAL;
1688 1689 1690
	}

	if (b->index >= q->num_buffers) {
H
Hans Verkuil 已提交
1691
		dprintk(1, "%s: buffer index out of range\n", opname);
1692
		return -EINVAL;
1693 1694
	}

1695
	if (q->bufs[b->index] == NULL) {
1696
		/* Should never happen */
H
Hans Verkuil 已提交
1697
		dprintk(1, "%s: buffer is NULL\n", opname);
1698
		return -EINVAL;
1699 1700 1701
	}

	if (b->memory != q->memory) {
H
Hans Verkuil 已提交
1702
		dprintk(1, "%s: invalid memory type\n", opname);
1703
		return -EINVAL;
1704 1705
	}

1706
	return __verify_planes_array(q->bufs[b->index], b);
1707
}
1708

1709
/**
1710
 * vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
1711
 * @q:		videobuf2 queue
1712 1713
 * @b:		buffer structure passed from userspace to vidioc_prepare_buf
 *		handler in driver
1714
 *
1715
 * Should be called from vidioc_prepare_buf ioctl handler of a driver.
1716 1717
 * This function:
 * 1) verifies the passed buffer,
1718 1719
 * 2) calls buf_prepare callback in the driver (if provided), in which
 *    driver-specific buffer initialization can be performed,
1720 1721
 *
 * The return values from this function are intended to be directly returned
1722
 * from vidioc_prepare_buf handler in driver.
1723
 */
1724
int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
1725
{
1726
	struct vb2_buffer *vb;
1727 1728
	int ret;

1729
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
1730
		dprintk(1, "file io in progress\n");
1731 1732
		return -EBUSY;
	}
1733

1734
	ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
1735 1736 1737 1738 1739
	if (ret)
		return ret;

	vb = q->bufs[b->index];
	if (vb->state != VB2_BUF_STATE_DEQUEUED) {
H
Hans Verkuil 已提交
1740
		dprintk(1, "invalid buffer state %d\n",
1741 1742 1743 1744 1745 1746 1747 1748 1749
			vb->state);
		return -EINVAL;
	}

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

H
Hans Verkuil 已提交
1750
		dprintk(1, "prepare of buffer %d succeeded\n", vb->v4l2_buf.index);
1751 1752
	}
	return ret;
1753 1754
}
EXPORT_SYMBOL_GPL(vb2_prepare_buf);
1755

1756 1757 1758 1759
/**
 * vb2_start_streaming() - Attempt to start streaming.
 * @q:		videobuf2 queue
 *
1760 1761 1762 1763 1764 1765
 * Attempt to start streaming. When this function is called there must be
 * at least q->min_buffers_needed buffers queued up (i.e. the minimum
 * number of buffers required for the DMA engine to function). If the
 * @start_streaming op fails it is supposed to return all the driver-owned
 * buffers back to vb2 in state QUEUED. Check if that happened and if
 * not warn and reclaim them forcefully.
1766 1767 1768
 */
static int vb2_start_streaming(struct vb2_queue *q)
{
1769
	struct vb2_buffer *vb;
1770 1771 1772
	int ret;

	/*
1773 1774
	 * If any buffers were queued before streamon,
	 * we can now pass them to driver for processing.
1775
	 */
1776 1777 1778 1779
	list_for_each_entry(vb, &q->queued_list, queued_entry)
		__enqueue_in_driver(vb);

	/* Tell the driver to start streaming */
1780
	q->start_streaming_called = 1;
1781 1782 1783
	ret = call_qop(q, start_streaming, q,
		       atomic_read(&q->owned_by_drv_count));
	if (!ret)
1784
		return 0;
1785

1786 1787
	q->start_streaming_called = 0;

H
Hans Verkuil 已提交
1788
	dprintk(1, "driver refused to start streaming\n");
1789 1790 1791 1792 1793 1794
	/*
	 * If you see this warning, then the driver isn't cleaning up properly
	 * after a failed start_streaming(). See the start_streaming()
	 * documentation in videobuf2-core.h for more information how buffers
	 * should be returned to vb2 in start_streaming().
	 */
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
	if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
		unsigned i;

		/*
		 * Forcefully reclaim buffers if the driver did not
		 * correctly return them to vb2.
		 */
		for (i = 0; i < q->num_buffers; ++i) {
			vb = q->bufs[i];
			if (vb->state == VB2_BUF_STATE_ACTIVE)
				vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
		}
		/* Must be zero now */
		WARN_ON(atomic_read(&q->owned_by_drv_count));
1809
	}
1810 1811 1812 1813 1814 1815
	/*
	 * If done_list is not empty, then start_streaming() didn't call
	 * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
	 * STATE_DONE.
	 */
	WARN_ON(!list_empty(&q->done_list));
1816 1817 1818
	return ret;
}

1819
static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
1820
{
1821 1822 1823 1824 1825 1826 1827
	int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
	struct vb2_buffer *vb;

	if (ret)
		return ret;

	vb = q->bufs[b->index];
1828

1829 1830 1831 1832
	switch (vb->state) {
	case VB2_BUF_STATE_DEQUEUED:
		ret = __buf_prepare(vb, b);
		if (ret)
1833
			return ret;
1834
		break;
1835 1836
	case VB2_BUF_STATE_PREPARED:
		break;
1837
	case VB2_BUF_STATE_PREPARING:
H
Hans Verkuil 已提交
1838
		dprintk(1, "buffer still being prepared\n");
1839
		return -EINVAL;
1840
	default:
H
Hans Verkuil 已提交
1841
		dprintk(1, "invalid buffer state %d\n", vb->state);
1842
		return -EINVAL;
1843 1844 1845 1846 1847 1848 1849
	}

	/*
	 * 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);
1850
	q->queued_count++;
1851
	q->waiting_for_buffers = false;
1852
	vb->state = VB2_BUF_STATE_QUEUED;
1853 1854 1855 1856 1857
	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
		/*
		 * For output buffers copy the timestamp if needed,
		 * and the timecode field and flag if needed.
		 */
1858 1859
		if ((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
		    V4L2_BUF_FLAG_TIMESTAMP_COPY)
1860 1861 1862 1863 1864
			vb->v4l2_buf.timestamp = b->timestamp;
		vb->v4l2_buf.flags |= b->flags & V4L2_BUF_FLAG_TIMECODE;
		if (b->flags & V4L2_BUF_FLAG_TIMECODE)
			vb->v4l2_buf.timecode = b->timecode;
	}
1865 1866 1867 1868 1869

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

1873 1874
	/* Fill buffer information for the userspace */
	__fill_v4l2_buffer(vb, b);
1875

1876 1877 1878 1879 1880 1881 1882 1883
	/*
	 * If streamon has been called, and we haven't yet called
	 * start_streaming() since not enough buffers were queued, and
	 * we now have reached the minimum number of queued buffers,
	 * then we can finally call start_streaming().
	 */
	if (q->streaming && !q->start_streaming_called &&
	    q->queued_count >= q->min_buffers_needed) {
1884 1885 1886 1887 1888
		ret = vb2_start_streaming(q);
		if (ret)
			return ret;
	}

H
Hans Verkuil 已提交
1889
	dprintk(1, "qbuf of buffer %d succeeded\n", vb->v4l2_buf.index);
1890
	return 0;
1891
}
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911

/**
 * 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)
{
1912
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
1913
		dprintk(1, "file io in progress\n");
1914 1915 1916 1917 1918
		return -EBUSY;
	}

	return vb2_internal_qbuf(q, b);
}
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
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) {
1942
			dprintk(1, "streaming off, will not wait for buffers\n");
1943 1944 1945
			return -EINVAL;
		}

1946 1947 1948 1949 1950
		if (q->error) {
			dprintk(1, "Queue in error state, will not wait for buffers\n");
			return -EIO;
		}

1951 1952 1953 1954 1955
		if (q->last_buffer_dequeued) {
			dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
			return -EPIPE;
		}

1956 1957 1958 1959 1960 1961 1962 1963
		if (!list_empty(&q->done_list)) {
			/*
			 * Found a buffer that we were waiting for.
			 */
			break;
		}

		if (nonblocking) {
1964
			dprintk(1, "nonblocking and no buffers to dequeue, "
1965 1966 1967 1968 1969 1970 1971 1972 1973
								"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.
		 */
1974
		call_void_qop(q, wait_prepare, q);
1975 1976 1977 1978

		/*
		 * All locks have been released, it is safe to sleep now.
		 */
1979
		dprintk(3, "will sleep waiting for buffers\n");
1980
		ret = wait_event_interruptible(q->done_wq,
1981 1982
				!list_empty(&q->done_list) || !q->streaming ||
				q->error);
1983 1984 1985 1986 1987

		/*
		 * We need to reevaluate both conditions again after reacquiring
		 * the locks or return an error if one occurred.
		 */
1988
		call_void_qop(q, wait_finish, q);
1989
		if (ret) {
1990
			dprintk(1, "sleep was interrupted\n");
1991
			return ret;
1992
		}
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
	}
	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,
2003
				struct v4l2_buffer *b, int nonblocking)
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
{
	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);
2021 2022 2023 2024 2025 2026 2027
	/*
	 * 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);
2028 2029
	spin_unlock_irqrestore(&q->done_lock, flags);

2030
	return ret;
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
}

/**
 * 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) {
2045
		dprintk(1, "streaming off, will not wait for buffers\n");
2046 2047 2048
		return -EINVAL;
	}

2049
	if (q->start_streaming_called)
2050
		wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
2051 2052 2053 2054
	return 0;
}
EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
/**
 * __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;
2074
			call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
2075 2076 2077 2078
			vb->planes[i].dbuf_mapped = 0;
		}
}

2079
static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
2080 2081 2082 2083 2084
{
	struct vb2_buffer *vb = NULL;
	int ret;

	if (b->type != q->type) {
H
Hans Verkuil 已提交
2085
		dprintk(1, "invalid buffer type\n");
2086 2087
		return -EINVAL;
	}
2088 2089
	ret = __vb2_get_done_vb(q, &vb, b, nonblocking);
	if (ret < 0)
2090 2091 2092 2093
		return ret;

	switch (vb->state) {
	case VB2_BUF_STATE_DONE:
2094
		dprintk(3, "returning done buffer\n");
2095 2096
		break;
	case VB2_BUF_STATE_ERROR:
2097
		dprintk(3, "returning done buffer with errors\n");
2098 2099
		break;
	default:
2100
		dprintk(1, "invalid buffer state\n");
2101 2102 2103
		return -EINVAL;
	}

2104
	call_void_vb_qop(vb, buf_finish, vb);
2105

2106 2107 2108 2109
	/* Fill buffer information for the userspace */
	__fill_v4l2_buffer(vb, b);
	/* Remove from videobuf queue */
	list_del(&vb->queued_entry);
2110
	q->queued_count--;
2111 2112 2113
	if (!V4L2_TYPE_IS_OUTPUT(q->type) &&
	    vb->v4l2_buf.flags & V4L2_BUF_FLAG_LAST)
		q->last_buffer_dequeued = true;
2114 2115
	/* go back to dequeued state */
	__vb2_dqbuf(vb);
2116 2117 2118 2119 2120 2121

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

	return 0;
}
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145

/**
 * 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)
{
2146
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
2147
		dprintk(1, "file io in progress\n");
2148 2149 2150 2151
		return -EBUSY;
	}
	return vb2_internal_dqbuf(q, b, nonblocking);
}
2152 2153
EXPORT_SYMBOL_GPL(vb2_dqbuf);

2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
/**
 * __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;

	/*
	 * Tell driver to stop all transactions and release all queued
	 * buffers.
	 */
2168
	if (q->start_streaming_called)
2169
		call_void_qop(q, stop_streaming, q);
2170

2171 2172 2173 2174 2175 2176
	/*
	 * If you see this warning, then the driver isn't cleaning up properly
	 * in stop_streaming(). See the stop_streaming() documentation in
	 * videobuf2-core.h for more information how buffers should be returned
	 * to vb2 in stop_streaming().
	 */
2177 2178 2179 2180 2181 2182 2183
	if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
		for (i = 0; i < q->num_buffers; ++i)
			if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
				vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
		/* Must be zero now */
		WARN_ON(atomic_read(&q->owned_by_drv_count));
	}
2184

2185 2186 2187
	q->streaming = 0;
	q->start_streaming_called = 0;
	q->queued_count = 0;
2188
	q->error = 0;
2189

2190 2191 2192 2193 2194 2195 2196 2197 2198
	/*
	 * 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);
2199
	atomic_set(&q->owned_by_drv_count, 0);
2200 2201 2202 2203
	wake_up_all(&q->done_wq);

	/*
	 * Reinitialize all buffers for next use.
2204 2205 2206 2207 2208 2209
	 * Make sure to call buf_finish for any queued buffers. Normally
	 * that's done in dqbuf, but that's not going to happen when we
	 * cancel the whole queue. Note: this code belongs here, not in
	 * __vb2_dqbuf() since in vb2_internal_dqbuf() there is a critical
	 * call to __fill_v4l2_buffer() after buf_finish(). That order can't
	 * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
2210
	 */
2211 2212 2213 2214 2215
	for (i = 0; i < q->num_buffers; ++i) {
		struct vb2_buffer *vb = q->bufs[i];

		if (vb->state != VB2_BUF_STATE_DEQUEUED) {
			vb->state = VB2_BUF_STATE_PREPARED;
2216
			call_void_vb_qop(vb, buf_finish, vb);
2217 2218 2219
		}
		__vb2_dqbuf(vb);
	}
2220 2221
}

2222
static int vb2_internal_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
2223
{
2224
	int ret;
2225 2226

	if (type != q->type) {
H
Hans Verkuil 已提交
2227
		dprintk(1, "invalid stream type\n");
2228 2229 2230 2231
		return -EINVAL;
	}

	if (q->streaming) {
H
Hans Verkuil 已提交
2232
		dprintk(3, "already streaming\n");
2233
		return 0;
2234 2235
	}

2236
	if (!q->num_buffers) {
H
Hans Verkuil 已提交
2237
		dprintk(1, "no buffers have been allocated\n");
2238 2239 2240
		return -EINVAL;
	}

2241
	if (q->num_buffers < q->min_buffers_needed) {
H
Hans Verkuil 已提交
2242
		dprintk(1, "need at least %u allocated buffers\n",
2243 2244 2245
				q->min_buffers_needed);
		return -EINVAL;
	}
2246

2247
	/*
2248 2249
	 * Tell driver to start streaming provided sufficient buffers
	 * are available.
2250
	 */
2251 2252 2253 2254 2255 2256
	if (q->queued_count >= q->min_buffers_needed) {
		ret = vb2_start_streaming(q);
		if (ret) {
			__vb2_queue_cancel(q);
			return ret;
		}
2257 2258 2259
	}

	q->streaming = 1;
2260

H
Hans Verkuil 已提交
2261
	dprintk(3, "successful\n");
2262 2263 2264
	return 0;
}

2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
/**
 * vb2_queue_error() - signal a fatal error on the queue
 * @q:		videobuf2 queue
 *
 * Flag that a fatal unrecoverable error has occurred and wake up all processes
 * waiting on the queue. Polling will now set POLLERR and queuing and dequeuing
 * buffers will return -EIO.
 *
 * The error flag will be cleared when cancelling the queue, either from
 * vb2_streamoff or vb2_queue_release. Drivers should thus not call this
 * function before starting the stream, otherwise the error flag will remain set
 * until the queue is released when closing the device node.
 */
void vb2_queue_error(struct vb2_queue *q)
{
	q->error = 1;

	wake_up_all(&q->done_wq);
}
EXPORT_SYMBOL_GPL(vb2_queue_error);

2286
/**
2287
 * vb2_streamon - start streaming
2288
 * @q:		videobuf2 queue
2289
 * @type:	type argument passed from userspace to vidioc_streamon handler
2290
 *
2291
 * Should be called from vidioc_streamon handler of a driver.
2292
 * This function:
2293 2294
 * 1) verifies current state
 * 2) passes any previously queued buffers to the driver and starts streaming
2295 2296
 *
 * The return values from this function are intended to be directly returned
2297
 * from vidioc_streamon handler in the driver.
2298
 */
2299
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
2300
{
2301
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
2302
		dprintk(1, "file io in progress\n");
2303 2304
		return -EBUSY;
	}
2305 2306 2307
	return vb2_internal_streamon(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamon);
2308

2309 2310
static int vb2_internal_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
{
2311
	if (type != q->type) {
H
Hans Verkuil 已提交
2312
		dprintk(1, "invalid stream type\n");
2313 2314 2315 2316 2317 2318
		return -EINVAL;
	}

	/*
	 * Cancel will pause streaming and remove all buffers from the driver
	 * and videobuf, effectively returning control over them to userspace.
2319 2320 2321 2322 2323
	 *
	 * Note that we do this even if q->streaming == 0: if you prepare or
	 * queue buffers, and then call streamoff without ever having called
	 * streamon, you would still expect those buffers to be returned to
	 * their normal dequeued state.
2324 2325
	 */
	__vb2_queue_cancel(q);
2326
	q->waiting_for_buffers = !V4L2_TYPE_IS_OUTPUT(q->type);
2327
	q->last_buffer_dequeued = false;
2328

H
Hans Verkuil 已提交
2329
	dprintk(3, "successful\n");
2330 2331
	return 0;
}
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349

/**
 * 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)
{
2350
	if (vb2_fileio_is_active(q)) {
H
Hans Verkuil 已提交
2351
		dprintk(1, "file io in progress\n");
2352 2353 2354 2355
		return -EBUSY;
	}
	return vb2_internal_streamoff(q, type);
}
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
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;
}

2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
/**
 * 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) {
2404
		dprintk(1, "queue is not currently set up for mmap\n");
2405 2406 2407 2408
		return -EINVAL;
	}

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

2413
	if (eb->flags & ~(O_CLOEXEC | O_ACCMODE)) {
2414
		dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
2415 2416 2417 2418
		return -EINVAL;
	}

	if (eb->type != q->type) {
H
Hans Verkuil 已提交
2419
		dprintk(1, "invalid buffer type\n");
2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
		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;
	}

2435 2436 2437 2438 2439
	if (vb2_fileio_is_active(q)) {
		dprintk(1, "expbuf: file io in progress\n");
		return -EBUSY;
	}

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

2442
	dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv, eb->flags & O_ACCMODE);
2443
	if (IS_ERR_OR_NULL(dbuf)) {
2444
		dprintk(1, "failed to export buffer %d, plane %d\n",
2445 2446 2447 2448
			eb->index, eb->plane);
		return -EINVAL;
	}

2449
	ret = dma_buf_fd(dbuf, eb->flags & ~O_ACCMODE);
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
	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);

2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
/**
 * 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;
H
Hans Verkuil 已提交
2488
	unsigned int buffer = 0, plane = 0;
2489
	int ret;
2490
	unsigned long length;
2491 2492

	if (q->memory != V4L2_MEMORY_MMAP) {
2493
		dprintk(1, "queue is not currently set up for mmap\n");
2494 2495 2496 2497 2498 2499 2500
		return -EINVAL;
	}

	/*
	 * Check memory area access mode.
	 */
	if (!(vma->vm_flags & VM_SHARED)) {
2501
		dprintk(1, "invalid vma flags, VM_SHARED needed\n");
2502 2503 2504 2505
		return -EINVAL;
	}
	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
		if (!(vma->vm_flags & VM_WRITE)) {
2506
			dprintk(1, "invalid vma flags, VM_WRITE needed\n");
2507 2508 2509 2510
			return -EINVAL;
		}
	} else {
		if (!(vma->vm_flags & VM_READ)) {
2511
			dprintk(1, "invalid vma flags, VM_READ needed\n");
2512 2513 2514
			return -EINVAL;
		}
	}
2515 2516 2517 2518
	if (vb2_fileio_is_active(q)) {
		dprintk(1, "mmap: file io in progress\n");
		return -EBUSY;
	}
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528

	/*
	 * 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];

2529 2530 2531 2532 2533 2534 2535 2536 2537
	/*
	 * 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");
2538 2539 2540
		return -EINVAL;
	}

2541
	mutex_lock(&q->mmap_lock);
2542
	ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
2543
	mutex_unlock(&q->mmap_lock);
2544
	if (ret)
2545 2546
		return ret;

2547
	dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
2548 2549 2550 2551
	return 0;
}
EXPORT_SYMBOL_GPL(vb2_mmap);

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
#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;
2562
	void *vaddr;
2563 2564 2565
	int ret;

	if (q->memory != V4L2_MEMORY_MMAP) {
2566
		dprintk(1, "queue is not currently set up for mmap\n");
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
		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];

2579 2580
	vaddr = vb2_plane_vaddr(vb, plane);
	return vaddr ? (unsigned long)vaddr : -EINVAL;
2581 2582 2583 2584
}
EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
#endif

2585 2586
static int __vb2_init_fileio(struct vb2_queue *q, int read);
static int __vb2_cleanup_fileio(struct vb2_queue *q);
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600

/**
 * 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.
 *
2601 2602 2603
 * If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
 * pending events.
 *
2604 2605 2606 2607 2608
 * 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)
{
2609
	struct video_device *vfd = video_devdata(file);
2610
	unsigned long req_events = poll_requested_events(wait);
2611
	struct vb2_buffer *vb = NULL;
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
	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);
	}
2623

2624 2625 2626 2627 2628
	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;

2629
	/*
2630
	 * Start file I/O emulator only if streaming API has not been used yet.
2631
	 */
2632
	if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2633 2634
		if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ) &&
				(req_events & (POLLIN | POLLRDNORM))) {
2635 2636
			if (__vb2_init_fileio(q, 1))
				return res | POLLERR;
2637
		}
2638 2639
		if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE) &&
				(req_events & (POLLOUT | POLLWRNORM))) {
2640 2641
			if (__vb2_init_fileio(q, 0))
				return res | POLLERR;
2642 2643 2644
			/*
			 * Write to OUTPUT queue can be done immediately.
			 */
2645
			return res | POLLOUT | POLLWRNORM;
2646 2647 2648
		}
	}

2649
	/*
2650 2651
	 * There is nothing to wait for if the queue isn't streaming, or if the
	 * error flag is set.
2652
	 */
2653 2654 2655 2656 2657 2658 2659 2660
	if (!vb2_is_streaming(q) || q->error)
		return res | POLLERR;
	/*
	 * For compatibility with vb1: if QBUF hasn't been called yet, then
	 * return POLLERR as well. This only affects capture queues, output
	 * queues will always initialize waiting_for_buffers to false.
	 */
	if (q->waiting_for_buffers)
2661
		return res | POLLERR;
2662

2663 2664 2665 2666 2667 2668 2669
	/*
	 * For output streams you can write as long as there are fewer buffers
	 * queued than there are buffers available.
	 */
	if (V4L2_TYPE_IS_OUTPUT(q->type) && q->queued_count < q->num_buffers)
		return res | POLLOUT | POLLWRNORM;

2670 2671 2672 2673 2674 2675 2676 2677
	if (list_empty(&q->done_list)) {
		/*
		 * If the last buffer was dequeued from a capture queue,
		 * return immediately. DQBUF will return -EPIPE.
		 */
		if (q->last_buffer_dequeued)
			return res | POLLIN | POLLRDNORM;

2678
		poll_wait(file, &q->done_wq, wait);
2679
	}
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691

	/*
	 * 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)) {
2692 2693 2694
		return (V4L2_TYPE_IS_OUTPUT(q->type)) ?
				res | POLLOUT | POLLWRNORM :
				res | POLLIN | POLLRDNORM;
2695
	}
2696
	return res;
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
}
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)
{
2713 2714 2715 2716 2717 2718 2719 2720 2721
	/*
	 * 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) ||
2722
	    WARN_ON(!q->ops->buf_queue)   ||
2723 2724 2725
	    WARN_ON(q->timestamp_flags &
		    ~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
		      V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
2726
		return -EINVAL;
2727

2728
	/* Warn that the driver should choose an appropriate timestamp type */
2729 2730
	WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
		V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
2731

2732 2733 2734
	INIT_LIST_HEAD(&q->queued_list);
	INIT_LIST_HEAD(&q->done_list);
	spin_lock_init(&q->done_lock);
2735
	mutex_init(&q->mmap_lock);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
	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)
{
2755
	__vb2_cleanup_fileio(q);
2756
	__vb2_queue_cancel(q);
2757
	mutex_lock(&q->mmap_lock);
2758
	__vb2_queue_free(q, q->num_buffers);
2759
	mutex_unlock(&q->mmap_lock);
2760 2761 2762
}
EXPORT_SYMBOL_GPL(vb2_queue_release);

2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
/**
 * 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
 *
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
 * @cur_index:	the index of the buffer currently being read from or
 *		written to. If equal to q->num_buffers then a new buffer
 *		must be dequeued.
 * @initial_index: in the read() case all buffers are queued up immediately
 *		in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
 *		buffers. However, in the write() case no buffers are initially
 *		queued, instead whenever a buffer is full it is queued up by
 *		__vb2_perform_fileio(). Only once all available buffers have
 *		been queued up will __vb2_perform_fileio() start to dequeue
 *		buffers. This means that initially __vb2_perform_fileio()
 *		needs to know what buffer index to use when it is queuing up
 *		the buffers for the first time. That initial index is stored
 *		in this field. Once it is equal to q->num_buffers all
 *		available buffers have been queued and __vb2_perform_fileio()
 *		should start the normal dequeue/queue cycle.
 *
2796 2797 2798 2799 2800 2801 2802
 * 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;
2803
	struct v4l2_plane p;
2804 2805
	struct v4l2_buffer b;
	struct vb2_fileio_buf bufs[VIDEO_MAX_FRAME];
2806 2807
	unsigned int cur_index;
	unsigned int initial_index;
2808 2809
	unsigned int q_count;
	unsigned int dq_count;
2810 2811
	unsigned read_once:1;
	unsigned write_immediately:1;
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
};

/**
 * __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
	 */
2828 2829 2830
	if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
		    (!read && !(q->io_modes & VB2_WRITE))))
		return -EINVAL;
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848

	/*
	 * 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;

2849 2850 2851
	dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
		(read) ? "read" : "write", count, q->fileio_read_once,
		q->fileio_write_immediately);
2852 2853 2854 2855 2856

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

2857 2858
	fileio->read_once = q->fileio_read_once;
	fileio->write_immediately = q->fileio_write_immediately;
2859 2860 2861 2862 2863 2864 2865 2866

	/*
	 * 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;
2867 2868
	q->fileio = fileio;
	ret = __reqbufs(q, &fileio->req);
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
	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);
2886 2887
		if (fileio->bufs[i].vaddr == NULL) {
			ret = -EINVAL;
2888
			goto err_reqbufs;
2889
		}
2890 2891 2892 2893 2894 2895 2896
		fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
	}

	/*
	 * Read mode requires pre queuing of all buffers.
	 */
	if (read) {
2897 2898
		bool is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);

2899 2900 2901 2902 2903
		/*
		 * Queue all buffers.
		 */
		for (i = 0; i < q->num_buffers; i++) {
			struct v4l2_buffer *b = &fileio->b;
2904

2905 2906
			memset(b, 0, sizeof(*b));
			b->type = q->type;
2907 2908 2909 2910 2911
			if (is_multiplanar) {
				memset(&fileio->p, 0, sizeof(fileio->p));
				b->m.planes = &fileio->p;
				b->length = 1;
			}
2912 2913
			b->memory = q->memory;
			b->index = i;
2914
			ret = vb2_internal_qbuf(q, b);
2915 2916 2917 2918
			if (ret)
				goto err_reqbufs;
			fileio->bufs[i].queued = 1;
		}
2919 2920 2921 2922 2923 2924
		/*
		 * All buffers have been queued, so mark that by setting
		 * initial_index to q->num_buffers
		 */
		fileio->initial_index = q->num_buffers;
		fileio->cur_index = q->num_buffers;
2925 2926
	}

2927 2928 2929
	/*
	 * Start streaming.
	 */
2930
	ret = vb2_internal_streamon(q, q->type);
2931 2932 2933
	if (ret)
		goto err_reqbufs;

2934 2935 2936
	return ret;

err_reqbufs:
2937
	fileio->req.count = 0;
2938
	__reqbufs(q, &fileio->req);
2939 2940

err_kfree:
2941
	q->fileio = NULL;
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
	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) {
2955
		vb2_internal_streamoff(q, q->type);
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
		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;
2979
	bool is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
2980 2981 2982 2983 2984 2985 2986 2987
	/*
	 * When using write() to write data to an output video node the vb2 core
	 * should set timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
	 * else is able to provide this information with the write() operation.
	 */
	bool set_timestamp = !read &&
		(q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
		V4L2_BUF_FLAG_TIMESTAMP_COPY;
2988 2989
	int ret, index;

H
Hans Verkuil 已提交
2990
	dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2991 2992 2993 2994 2995 2996 2997 2998 2999
		read ? "read" : "write", (long)*ppos, count,
		nonblock ? "non" : "");

	if (!data)
		return -EINVAL;

	/*
	 * Initialize emulator on first call.
	 */
3000
	if (!vb2_fileio_is_active(q)) {
3001
		ret = __vb2_init_fileio(q, read);
H
Hans Verkuil 已提交
3002
		dprintk(3, "vb2_init_fileio result: %d\n", ret);
3003 3004 3005 3006 3007 3008 3009 3010
		if (ret)
			return ret;
	}
	fileio = q->fileio;

	/*
	 * Check if we need to dequeue the buffer.
	 */
3011
	index = fileio->cur_index;
3012
	if (index >= q->num_buffers) {
3013 3014 3015 3016 3017 3018
		/*
		 * Call vb2_dqbuf to get buffer back.
		 */
		memset(&fileio->b, 0, sizeof(fileio->b));
		fileio->b.type = q->type;
		fileio->b.memory = q->memory;
3019 3020 3021 3022 3023
		if (is_multiplanar) {
			memset(&fileio->p, 0, sizeof(fileio->p));
			fileio->b.m.planes = &fileio->p;
			fileio->b.length = 1;
		}
3024
		ret = vb2_internal_dqbuf(q, &fileio->b, nonblock);
H
Hans Verkuil 已提交
3025
		dprintk(5, "vb2_dqbuf result: %d\n", ret);
3026
		if (ret)
3027
			return ret;
3028 3029
		fileio->dq_count += 1;

3030
		fileio->cur_index = index = fileio->b.index;
3031 3032
		buf = &fileio->bufs[index];

3033 3034 3035
		/*
		 * Get number of bytes filled by the driver
		 */
3036
		buf->pos = 0;
3037
		buf->queued = 0;
3038 3039
		buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
				 : vb2_plane_size(q->bufs[index], 0);
3040 3041 3042 3043 3044 3045
		/* Compensate for data_offset on read in the multiplanar case. */
		if (is_multiplanar && read &&
		    fileio->b.m.planes[0].data_offset < buf->size) {
			buf->pos = fileio->b.m.planes[0].data_offset;
			buf->size -= buf->pos;
		}
3046 3047
	} else {
		buf = &fileio->bufs[index];
3048 3049 3050 3051 3052 3053 3054
	}

	/*
	 * Limit count on last few bytes of the buffer.
	 */
	if (buf->pos + count > buf->size) {
		count = buf->size - buf->pos;
3055
		dprintk(5, "reducing read count: %zd\n", count);
3056 3057 3058 3059 3060
	}

	/*
	 * Transfer data to userspace.
	 */
H
Hans Verkuil 已提交
3061
	dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
3062 3063 3064 3065 3066 3067
		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) {
H
Hans Verkuil 已提交
3068
		dprintk(3, "error copying data\n");
3069
		return -EFAULT;
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
	}

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

	/*
	 * Queue next buffer if required.
	 */
3081
	if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
3082 3083 3084
		/*
		 * Check if this is the last buffer to read.
		 */
3085
		if (read && fileio->read_once && fileio->dq_count == 1) {
H
Hans Verkuil 已提交
3086
			dprintk(3, "read limit reached\n");
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
			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;
3098 3099 3100 3101 3102 3103
		if (is_multiplanar) {
			memset(&fileio->p, 0, sizeof(fileio->p));
			fileio->p.bytesused = buf->pos;
			fileio->b.m.planes = &fileio->p;
			fileio->b.length = 1;
		}
3104 3105
		if (set_timestamp)
			v4l2_get_timestamp(&fileio->b.timestamp);
3106
		ret = vb2_internal_qbuf(q, &fileio->b);
H
Hans Verkuil 已提交
3107
		dprintk(5, "vb2_dbuf result: %d\n", ret);
3108
		if (ret)
3109
			return ret;
3110 3111 3112 3113 3114 3115

		/*
		 * Buffer has been queued, update the status
		 */
		buf->pos = 0;
		buf->queued = 1;
3116
		buf->size = vb2_plane_size(q->bufs[index], 0);
3117
		fileio->q_count += 1;
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
		/*
		 * If we are queuing up buffers for the first time, then
		 * increase initial_index by one.
		 */
		if (fileio->initial_index < q->num_buffers)
			fileio->initial_index++;
		/*
		 * The next buffer to use is either a buffer that's going to be
		 * queued for the first time (initial_index < q->num_buffers)
		 * or it is equal to q->num_buffers, meaning that the next
		 * time we need to dequeue a buffer since we've now queued up
		 * all the 'first time' buffers.
		 */
		fileio->cur_index = fileio->initial_index;
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
	}

	/*
	 * 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);

3149
size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
3150 3151
		loff_t *ppos, int nonblocking)
{
3152 3153
	return __vb2_perform_fileio(q, (char __user *) data, count,
							ppos, nonblocking, 0);
3154 3155 3156
}
EXPORT_SYMBOL_GPL(vb2_write);

H
Hans Verkuil 已提交
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
struct vb2_threadio_data {
	struct task_struct *thread;
	vb2_thread_fnc fnc;
	void *priv;
	bool stop;
};

static int vb2_thread(void *data)
{
	struct vb2_queue *q = data;
	struct vb2_threadio_data *threadio = q->threadio;
	struct vb2_fileio_data *fileio = q->fileio;
	bool set_timestamp = false;
	int prequeue = 0;
	int index = 0;
	int ret = 0;

	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
		prequeue = q->num_buffers;
		set_timestamp =
			(q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
			V4L2_BUF_FLAG_TIMESTAMP_COPY;
	}

	set_freezable();

	for (;;) {
		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;
		if (prequeue) {
			fileio->b.index = index++;
			prequeue--;
		} else {
			call_void_qop(q, wait_finish, q);
3197 3198
			if (!threadio->stop)
				ret = vb2_internal_dqbuf(q, &fileio->b, 0);
H
Hans Verkuil 已提交
3199 3200 3201
			call_void_qop(q, wait_prepare, q);
			dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
		}
3202
		if (ret || threadio->stop)
H
Hans Verkuil 已提交
3203 3204 3205 3206 3207
			break;
		try_to_freeze();

		vb = q->bufs[fileio->b.index];
		if (!(fileio->b.flags & V4L2_BUF_FLAG_ERROR))
3208 3209
			if (threadio->fnc(vb, threadio->priv))
				break;
H
Hans Verkuil 已提交
3210 3211 3212
		call_void_qop(q, wait_finish, q);
		if (set_timestamp)
			v4l2_get_timestamp(&fileio->b.timestamp);
3213 3214
		if (!threadio->stop)
			ret = vb2_internal_qbuf(q, &fileio->b);
H
Hans Verkuil 已提交
3215
		call_void_qop(q, wait_prepare, q);
3216
		if (ret || threadio->stop)
H
Hans Verkuil 已提交
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
			break;
	}

	/* Hmm, linux becomes *very* unhappy without this ... */
	while (!kthread_should_stop()) {
		set_current_state(TASK_INTERRUPTIBLE);
		schedule();
	}
	return 0;
}

/*
 * This function should not be used for anything else but the videobuf2-dvb
 * support. If you think you have another good use-case for this, then please
 * contact the linux-media mailinglist first.
 */
int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
		     const char *thread_name)
{
	struct vb2_threadio_data *threadio;
	int ret = 0;

	if (q->threadio)
		return -EBUSY;
	if (vb2_is_busy(q))
		return -EBUSY;
	if (WARN_ON(q->fileio))
		return -EBUSY;

	threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
	if (threadio == NULL)
		return -ENOMEM;
	threadio->fnc = fnc;
	threadio->priv = priv;

	ret = __vb2_init_fileio(q, !V4L2_TYPE_IS_OUTPUT(q->type));
	dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
	if (ret)
		goto nomem;
	q->threadio = threadio;
	threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
	if (IS_ERR(threadio->thread)) {
		ret = PTR_ERR(threadio->thread);
		threadio->thread = NULL;
		goto nothread;
	}
	return 0;

nothread:
	__vb2_cleanup_fileio(q);
nomem:
	kfree(threadio);
	return ret;
}
EXPORT_SYMBOL_GPL(vb2_thread_start);

int vb2_thread_stop(struct vb2_queue *q)
{
	struct vb2_threadio_data *threadio = q->threadio;
	int err;

	if (threadio == NULL)
		return 0;
	threadio->stop = true;
3281 3282
	/* Wake up all pending sleeps in the thread */
	vb2_queue_error(q);
3283
	err = kthread_stop(threadio->thread);
3284
	__vb2_cleanup_fileio(q);
H
Hans Verkuil 已提交
3285 3286 3287 3288 3289 3290
	threadio->thread = NULL;
	kfree(threadio);
	q->threadio = NULL;
	return err;
}
EXPORT_SYMBOL_GPL(vb2_thread_stop);
3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408

/*
 * 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);

3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
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);

3419 3420 3421 3422 3423 3424
/* v4l2_file_operations helpers */

int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
{
	struct video_device *vdev = video_devdata(file);

3425
	return vb2_mmap(vdev->queue, vma);
3426 3427 3428
}
EXPORT_SYMBOL_GPL(vb2_fop_mmap);

3429
int _vb2_fop_release(struct file *file, struct mutex *lock)
3430 3431 3432
{
	struct video_device *vdev = video_devdata(file);

3433 3434
	if (lock)
		mutex_lock(lock);
3435 3436 3437 3438
	if (file->private_data == vdev->queue->owner) {
		vb2_queue_release(vdev->queue);
		vdev->queue->owner = NULL;
	}
3439 3440
	if (lock)
		mutex_unlock(lock);
3441 3442
	return v4l2_fh_release(file);
}
3443 3444 3445 3446 3447 3448 3449 3450 3451
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);
}
3452 3453
EXPORT_SYMBOL_GPL(vb2_fop_release);

3454
ssize_t vb2_fop_write(struct file *file, const char __user *buf,
3455 3456 3457 3458 3459 3460
		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;

3461 3462
	if (!(vdev->queue->io_modes & VB2_WRITE))
		return -EINVAL;
3463
	if (lock && mutex_lock_interruptible(lock))
3464 3465 3466 3467 3468
		return -ERESTARTSYS;
	if (vb2_queue_is_busy(vdev, file))
		goto exit;
	err = vb2_write(vdev->queue, buf, count, ppos,
		       file->f_flags & O_NONBLOCK);
3469
	if (vdev->queue->fileio)
3470 3471
		vdev->queue->owner = file->private_data;
exit:
3472
	if (lock)
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
		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;

3485 3486
	if (!(vdev->queue->io_modes & VB2_READ))
		return -EINVAL;
3487
	if (lock && mutex_lock_interruptible(lock))
3488 3489 3490 3491 3492
		return -ERESTARTSYS;
	if (vb2_queue_is_busy(vdev, file))
		goto exit;
	err = vb2_read(vdev->queue, buf, count, ppos,
		       file->f_flags & O_NONBLOCK);
3493
	if (vdev->queue->fileio)
3494 3495
		vdev->queue->owner = file->private_data;
exit:
3496
	if (lock)
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
		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 res;
	void *fileio;

3510 3511 3512 3513 3514
	/*
	 * If this helper doesn't know how to lock, then you shouldn't be using
	 * it but you should write your own.
	 */
	WARN_ON(!lock);
3515

3516
	if (lock && mutex_lock_interruptible(lock))
3517 3518 3519 3520 3521 3522 3523
		return POLLERR;

	fileio = q->fileio;

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

	/* If fileio was started, then we have a new queue owner. */
3524
	if (!fileio && q->fileio)
3525
		q->owner = file->private_data;
3526
	if (lock)
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
		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);

3538
	return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
}
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);

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