1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Memory-to-memory device framework for Video for Linux 2 and videobuf.
4  *
5  * Helper functions for devices that use videobuf buffers for both their
6  * source and destination.
7  *
8  * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd.
9  * Pawel Osciak, <pawel@osciak.com>
10  * Marek Szyprowski, <m.szyprowski@samsung.com>
11  */
12 #include <linux/module.h>
13 #include <linux/sched.h>
14 #include <linux/slab.h>
15 
16 #include <media/media-device.h>
17 #include <media/videobuf2-v4l2.h>
18 #include <media/v4l2-mem2mem.h>
19 #include <media/v4l2-dev.h>
20 #include <media/v4l2-device.h>
21 #include <media/v4l2-fh.h>
22 #include <media/v4l2-event.h>
23 
24 MODULE_DESCRIPTION("Mem to mem device framework for videobuf");
25 MODULE_AUTHOR("Pawel Osciak, <pawel@osciak.com>");
26 MODULE_LICENSE("GPL");
27 
28 static bool debug;
29 module_param(debug, bool, 0644);
30 
31 #define dprintk(fmt, arg...)						\
32 	do {								\
33 		if (debug)						\
34 			printk(KERN_DEBUG "%s: " fmt, __func__, ## arg);\
35 	} while (0)
36 
37 
38 /* Instance is already queued on the job_queue */
39 #define TRANS_QUEUED		(1 << 0)
40 /* Instance is currently running in hardware */
41 #define TRANS_RUNNING		(1 << 1)
42 /* Instance is currently aborting */
43 #define TRANS_ABORT		(1 << 2)
44 
45 
46 /* Offset base for buffers on the destination queue - used to distinguish
47  * between source and destination buffers when mmapping - they receive the same
48  * offsets but for different queues */
49 #define DST_QUEUE_OFF_BASE	(1 << 30)
50 
51 enum v4l2_m2m_entity_type {
52 	MEM2MEM_ENT_TYPE_SOURCE,
53 	MEM2MEM_ENT_TYPE_SINK,
54 	MEM2MEM_ENT_TYPE_PROC
55 };
56 
57 static const char * const m2m_entity_name[] = {
58 	"source",
59 	"sink",
60 	"proc"
61 };
62 
63 /**
64  * struct v4l2_m2m_dev - per-device context
65  * @source:		&struct media_entity pointer with the source entity
66  *			Used only when the M2M device is registered via
67  *			v4l2_m2m_unregister_media_controller().
68  * @source_pad:		&struct media_pad with the source pad.
69  *			Used only when the M2M device is registered via
70  *			v4l2_m2m_unregister_media_controller().
71  * @sink:		&struct media_entity pointer with the sink entity
72  *			Used only when the M2M device is registered via
73  *			v4l2_m2m_unregister_media_controller().
74  * @sink_pad:		&struct media_pad with the sink pad.
75  *			Used only when the M2M device is registered via
76  *			v4l2_m2m_unregister_media_controller().
77  * @proc:		&struct media_entity pointer with the M2M device itself.
78  * @proc_pads:		&struct media_pad with the @proc pads.
79  *			Used only when the M2M device is registered via
80  *			v4l2_m2m_unregister_media_controller().
81  * @intf_devnode:	&struct media_intf devnode pointer with the interface
82  *			with controls the M2M device.
83  * @curr_ctx:		currently running instance
84  * @job_queue:		instances queued to run
85  * @job_spinlock:	protects job_queue
86  * @job_work:		worker to run queued jobs.
87  * @m2m_ops:		driver callbacks
88  */
89 struct v4l2_m2m_dev {
90 	struct v4l2_m2m_ctx	*curr_ctx;
91 #ifdef CONFIG_MEDIA_CONTROLLER
92 	struct media_entity	*source;
93 	struct media_pad	source_pad;
94 	struct media_entity	sink;
95 	struct media_pad	sink_pad;
96 	struct media_entity	proc;
97 	struct media_pad	proc_pads[2];
98 	struct media_intf_devnode *intf_devnode;
99 #endif
100 
101 	struct list_head	job_queue;
102 	spinlock_t		job_spinlock;
103 	struct work_struct	job_work;
104 
105 	const struct v4l2_m2m_ops *m2m_ops;
106 };
107 
108 static struct v4l2_m2m_queue_ctx *get_queue_ctx(struct v4l2_m2m_ctx *m2m_ctx,
109 						enum v4l2_buf_type type)
110 {
111 	if (V4L2_TYPE_IS_OUTPUT(type))
112 		return &m2m_ctx->out_q_ctx;
113 	else
114 		return &m2m_ctx->cap_q_ctx;
115 }
116 
117 struct vb2_queue *v4l2_m2m_get_vq(struct v4l2_m2m_ctx *m2m_ctx,
118 				       enum v4l2_buf_type type)
119 {
120 	struct v4l2_m2m_queue_ctx *q_ctx;
121 
122 	q_ctx = get_queue_ctx(m2m_ctx, type);
123 	if (!q_ctx)
124 		return NULL;
125 
126 	return &q_ctx->q;
127 }
128 EXPORT_SYMBOL(v4l2_m2m_get_vq);
129 
130 struct vb2_v4l2_buffer *v4l2_m2m_next_buf(struct v4l2_m2m_queue_ctx *q_ctx)
131 {
132 	struct v4l2_m2m_buffer *b;
133 	unsigned long flags;
134 
135 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
136 
137 	if (list_empty(&q_ctx->rdy_queue)) {
138 		spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
139 		return NULL;
140 	}
141 
142 	b = list_first_entry(&q_ctx->rdy_queue, struct v4l2_m2m_buffer, list);
143 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
144 	return &b->vb;
145 }
146 EXPORT_SYMBOL_GPL(v4l2_m2m_next_buf);
147 
148 struct vb2_v4l2_buffer *v4l2_m2m_last_buf(struct v4l2_m2m_queue_ctx *q_ctx)
149 {
150 	struct v4l2_m2m_buffer *b;
151 	unsigned long flags;
152 
153 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
154 
155 	if (list_empty(&q_ctx->rdy_queue)) {
156 		spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
157 		return NULL;
158 	}
159 
160 	b = list_last_entry(&q_ctx->rdy_queue, struct v4l2_m2m_buffer, list);
161 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
162 	return &b->vb;
163 }
164 EXPORT_SYMBOL_GPL(v4l2_m2m_last_buf);
165 
166 struct vb2_v4l2_buffer *v4l2_m2m_buf_remove(struct v4l2_m2m_queue_ctx *q_ctx)
167 {
168 	struct v4l2_m2m_buffer *b;
169 	unsigned long flags;
170 
171 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
172 	if (list_empty(&q_ctx->rdy_queue)) {
173 		spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
174 		return NULL;
175 	}
176 	b = list_first_entry(&q_ctx->rdy_queue, struct v4l2_m2m_buffer, list);
177 	list_del(&b->list);
178 	q_ctx->num_rdy--;
179 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
180 
181 	return &b->vb;
182 }
183 EXPORT_SYMBOL_GPL(v4l2_m2m_buf_remove);
184 
185 void v4l2_m2m_buf_remove_by_buf(struct v4l2_m2m_queue_ctx *q_ctx,
186 				struct vb2_v4l2_buffer *vbuf)
187 {
188 	struct v4l2_m2m_buffer *b;
189 	unsigned long flags;
190 
191 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
192 	b = container_of(vbuf, struct v4l2_m2m_buffer, vb);
193 	list_del(&b->list);
194 	q_ctx->num_rdy--;
195 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
196 }
197 EXPORT_SYMBOL_GPL(v4l2_m2m_buf_remove_by_buf);
198 
199 struct vb2_v4l2_buffer *
200 v4l2_m2m_buf_remove_by_idx(struct v4l2_m2m_queue_ctx *q_ctx, unsigned int idx)
201 
202 {
203 	struct v4l2_m2m_buffer *b, *tmp;
204 	struct vb2_v4l2_buffer *ret = NULL;
205 	unsigned long flags;
206 
207 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
208 	list_for_each_entry_safe(b, tmp, &q_ctx->rdy_queue, list) {
209 		if (b->vb.vb2_buf.index == idx) {
210 			list_del(&b->list);
211 			q_ctx->num_rdy--;
212 			ret = &b->vb;
213 			break;
214 		}
215 	}
216 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
217 
218 	return ret;
219 }
220 EXPORT_SYMBOL_GPL(v4l2_m2m_buf_remove_by_idx);
221 
222 /*
223  * Scheduling handlers
224  */
225 
226 void *v4l2_m2m_get_curr_priv(struct v4l2_m2m_dev *m2m_dev)
227 {
228 	unsigned long flags;
229 	void *ret = NULL;
230 
231 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
232 	if (m2m_dev->curr_ctx)
233 		ret = m2m_dev->curr_ctx->priv;
234 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
235 
236 	return ret;
237 }
238 EXPORT_SYMBOL(v4l2_m2m_get_curr_priv);
239 
240 /**
241  * v4l2_m2m_try_run() - select next job to perform and run it if possible
242  * @m2m_dev: per-device context
243  *
244  * Get next transaction (if present) from the waiting jobs list and run it.
245  *
246  * Note that this function can run on a given v4l2_m2m_ctx context,
247  * but call .device_run for another context.
248  */
249 static void v4l2_m2m_try_run(struct v4l2_m2m_dev *m2m_dev)
250 {
251 	unsigned long flags;
252 
253 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
254 	if (NULL != m2m_dev->curr_ctx) {
255 		spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
256 		dprintk("Another instance is running, won't run now\n");
257 		return;
258 	}
259 
260 	if (list_empty(&m2m_dev->job_queue)) {
261 		spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
262 		dprintk("No job pending\n");
263 		return;
264 	}
265 
266 	m2m_dev->curr_ctx = list_first_entry(&m2m_dev->job_queue,
267 				   struct v4l2_m2m_ctx, queue);
268 	m2m_dev->curr_ctx->job_flags |= TRANS_RUNNING;
269 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
270 
271 	dprintk("Running job on m2m_ctx: %p\n", m2m_dev->curr_ctx);
272 	m2m_dev->m2m_ops->device_run(m2m_dev->curr_ctx->priv);
273 }
274 
275 /*
276  * __v4l2_m2m_try_queue() - queue a job
277  * @m2m_dev: m2m device
278  * @m2m_ctx: m2m context
279  *
280  * Check if this context is ready to queue a job.
281  *
282  * This function can run in interrupt context.
283  */
284 static void __v4l2_m2m_try_queue(struct v4l2_m2m_dev *m2m_dev,
285 				 struct v4l2_m2m_ctx *m2m_ctx)
286 {
287 	unsigned long flags_job;
288 	struct vb2_v4l2_buffer *dst, *src;
289 
290 	dprintk("Trying to schedule a job for m2m_ctx: %p\n", m2m_ctx);
291 
292 	if (!m2m_ctx->out_q_ctx.q.streaming
293 	    || !m2m_ctx->cap_q_ctx.q.streaming) {
294 		dprintk("Streaming needs to be on for both queues\n");
295 		return;
296 	}
297 
298 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags_job);
299 
300 	/* If the context is aborted then don't schedule it */
301 	if (m2m_ctx->job_flags & TRANS_ABORT) {
302 		dprintk("Aborted context\n");
303 		goto job_unlock;
304 	}
305 
306 	if (m2m_ctx->job_flags & TRANS_QUEUED) {
307 		dprintk("On job queue already\n");
308 		goto job_unlock;
309 	}
310 
311 	src = v4l2_m2m_next_src_buf(m2m_ctx);
312 	dst = v4l2_m2m_next_dst_buf(m2m_ctx);
313 	if (!src && !m2m_ctx->out_q_ctx.buffered) {
314 		dprintk("No input buffers available\n");
315 		goto job_unlock;
316 	}
317 	if (!dst && !m2m_ctx->cap_q_ctx.buffered) {
318 		dprintk("No output buffers available\n");
319 		goto job_unlock;
320 	}
321 
322 	m2m_ctx->new_frame = true;
323 
324 	if (src && dst && dst->is_held &&
325 	    dst->vb2_buf.copied_timestamp &&
326 	    dst->vb2_buf.timestamp != src->vb2_buf.timestamp) {
327 		dst->is_held = false;
328 		v4l2_m2m_dst_buf_remove(m2m_ctx);
329 		v4l2_m2m_buf_done(dst, VB2_BUF_STATE_DONE);
330 		dst = v4l2_m2m_next_dst_buf(m2m_ctx);
331 
332 		if (!dst && !m2m_ctx->cap_q_ctx.buffered) {
333 			dprintk("No output buffers available after returning held buffer\n");
334 			goto job_unlock;
335 		}
336 	}
337 
338 	if (src && dst && (m2m_ctx->out_q_ctx.q.subsystem_flags &
339 			   VB2_V4L2_FL_SUPPORTS_M2M_HOLD_CAPTURE_BUF))
340 		m2m_ctx->new_frame = !dst->vb2_buf.copied_timestamp ||
341 			dst->vb2_buf.timestamp != src->vb2_buf.timestamp;
342 
343 	if (m2m_ctx->has_stopped) {
344 		dprintk("Device has stopped\n");
345 		goto job_unlock;
346 	}
347 
348 	if (m2m_dev->m2m_ops->job_ready
349 		&& (!m2m_dev->m2m_ops->job_ready(m2m_ctx->priv))) {
350 		dprintk("Driver not ready\n");
351 		goto job_unlock;
352 	}
353 
354 	list_add_tail(&m2m_ctx->queue, &m2m_dev->job_queue);
355 	m2m_ctx->job_flags |= TRANS_QUEUED;
356 
357 job_unlock:
358 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags_job);
359 }
360 
361 /**
362  * v4l2_m2m_try_schedule() - schedule and possibly run a job for any context
363  * @m2m_ctx: m2m context
364  *
365  * Check if this context is ready to queue a job. If suitable,
366  * run the next queued job on the mem2mem device.
367  *
368  * This function shouldn't run in interrupt context.
369  *
370  * Note that v4l2_m2m_try_schedule() can schedule one job for this context,
371  * and then run another job for another context.
372  */
373 void v4l2_m2m_try_schedule(struct v4l2_m2m_ctx *m2m_ctx)
374 {
375 	struct v4l2_m2m_dev *m2m_dev = m2m_ctx->m2m_dev;
376 
377 	__v4l2_m2m_try_queue(m2m_dev, m2m_ctx);
378 	v4l2_m2m_try_run(m2m_dev);
379 }
380 EXPORT_SYMBOL_GPL(v4l2_m2m_try_schedule);
381 
382 /**
383  * v4l2_m2m_device_run_work() - run pending jobs for the context
384  * @work: Work structure used for scheduling the execution of this function.
385  */
386 static void v4l2_m2m_device_run_work(struct work_struct *work)
387 {
388 	struct v4l2_m2m_dev *m2m_dev =
389 		container_of(work, struct v4l2_m2m_dev, job_work);
390 
391 	v4l2_m2m_try_run(m2m_dev);
392 }
393 
394 /**
395  * v4l2_m2m_cancel_job() - cancel pending jobs for the context
396  * @m2m_ctx: m2m context with jobs to be canceled
397  *
398  * In case of streamoff or release called on any context,
399  * 1] If the context is currently running, then abort job will be called
400  * 2] If the context is queued, then the context will be removed from
401  *    the job_queue
402  */
403 static void v4l2_m2m_cancel_job(struct v4l2_m2m_ctx *m2m_ctx)
404 {
405 	struct v4l2_m2m_dev *m2m_dev;
406 	unsigned long flags;
407 
408 	m2m_dev = m2m_ctx->m2m_dev;
409 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
410 
411 	m2m_ctx->job_flags |= TRANS_ABORT;
412 	if (m2m_ctx->job_flags & TRANS_RUNNING) {
413 		spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
414 		if (m2m_dev->m2m_ops->job_abort)
415 			m2m_dev->m2m_ops->job_abort(m2m_ctx->priv);
416 		dprintk("m2m_ctx %p running, will wait to complete\n", m2m_ctx);
417 		wait_event(m2m_ctx->finished,
418 				!(m2m_ctx->job_flags & TRANS_RUNNING));
419 	} else if (m2m_ctx->job_flags & TRANS_QUEUED) {
420 		list_del(&m2m_ctx->queue);
421 		m2m_ctx->job_flags &= ~(TRANS_QUEUED | TRANS_RUNNING);
422 		spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
423 		dprintk("m2m_ctx: %p had been on queue and was removed\n",
424 			m2m_ctx);
425 	} else {
426 		/* Do nothing, was not on queue/running */
427 		spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
428 	}
429 }
430 
431 /*
432  * Schedule the next job, called from v4l2_m2m_job_finish() or
433  * v4l2_m2m_buf_done_and_job_finish().
434  */
435 static void v4l2_m2m_schedule_next_job(struct v4l2_m2m_dev *m2m_dev,
436 				       struct v4l2_m2m_ctx *m2m_ctx)
437 {
438 	/*
439 	 * This instance might have more buffers ready, but since we do not
440 	 * allow more than one job on the job_queue per instance, each has
441 	 * to be scheduled separately after the previous one finishes.
442 	 */
443 	__v4l2_m2m_try_queue(m2m_dev, m2m_ctx);
444 
445 	/*
446 	 * We might be running in atomic context,
447 	 * but the job must be run in non-atomic context.
448 	 */
449 	schedule_work(&m2m_dev->job_work);
450 }
451 
452 /*
453  * Assumes job_spinlock is held, called from v4l2_m2m_job_finish() or
454  * v4l2_m2m_buf_done_and_job_finish().
455  */
456 static bool _v4l2_m2m_job_finish(struct v4l2_m2m_dev *m2m_dev,
457 				 struct v4l2_m2m_ctx *m2m_ctx)
458 {
459 	if (!m2m_dev->curr_ctx || m2m_dev->curr_ctx != m2m_ctx) {
460 		dprintk("Called by an instance not currently running\n");
461 		return false;
462 	}
463 
464 	list_del(&m2m_dev->curr_ctx->queue);
465 	m2m_dev->curr_ctx->job_flags &= ~(TRANS_QUEUED | TRANS_RUNNING);
466 	wake_up(&m2m_dev->curr_ctx->finished);
467 	m2m_dev->curr_ctx = NULL;
468 	return true;
469 }
470 
471 void v4l2_m2m_job_finish(struct v4l2_m2m_dev *m2m_dev,
472 			 struct v4l2_m2m_ctx *m2m_ctx)
473 {
474 	unsigned long flags;
475 	bool schedule_next;
476 
477 	/*
478 	 * This function should not be used for drivers that support
479 	 * holding capture buffers. Those should use
480 	 * v4l2_m2m_buf_done_and_job_finish() instead.
481 	 */
482 	WARN_ON(m2m_ctx->out_q_ctx.q.subsystem_flags &
483 		VB2_V4L2_FL_SUPPORTS_M2M_HOLD_CAPTURE_BUF);
484 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
485 	schedule_next = _v4l2_m2m_job_finish(m2m_dev, m2m_ctx);
486 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
487 
488 	if (schedule_next)
489 		v4l2_m2m_schedule_next_job(m2m_dev, m2m_ctx);
490 }
491 EXPORT_SYMBOL(v4l2_m2m_job_finish);
492 
493 void v4l2_m2m_buf_done_and_job_finish(struct v4l2_m2m_dev *m2m_dev,
494 				      struct v4l2_m2m_ctx *m2m_ctx,
495 				      enum vb2_buffer_state state)
496 {
497 	struct vb2_v4l2_buffer *src_buf, *dst_buf;
498 	bool schedule_next = false;
499 	unsigned long flags;
500 
501 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
502 	src_buf = v4l2_m2m_src_buf_remove(m2m_ctx);
503 	dst_buf = v4l2_m2m_next_dst_buf(m2m_ctx);
504 
505 	if (WARN_ON(!src_buf || !dst_buf))
506 		goto unlock;
507 	v4l2_m2m_buf_done(src_buf, state);
508 	dst_buf->is_held = src_buf->flags & V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF;
509 	if (!dst_buf->is_held) {
510 		v4l2_m2m_dst_buf_remove(m2m_ctx);
511 		v4l2_m2m_buf_done(dst_buf, state);
512 	}
513 	schedule_next = _v4l2_m2m_job_finish(m2m_dev, m2m_ctx);
514 unlock:
515 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
516 
517 	if (schedule_next)
518 		v4l2_m2m_schedule_next_job(m2m_dev, m2m_ctx);
519 }
520 EXPORT_SYMBOL(v4l2_m2m_buf_done_and_job_finish);
521 
522 int v4l2_m2m_reqbufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
523 		     struct v4l2_requestbuffers *reqbufs)
524 {
525 	struct vb2_queue *vq;
526 	int ret;
527 
528 	vq = v4l2_m2m_get_vq(m2m_ctx, reqbufs->type);
529 	ret = vb2_reqbufs(vq, reqbufs);
530 	/* If count == 0, then the owner has released all buffers and he
531 	   is no longer owner of the queue. Otherwise we have an owner. */
532 	if (ret == 0)
533 		vq->owner = reqbufs->count ? file->private_data : NULL;
534 
535 	return ret;
536 }
537 EXPORT_SYMBOL_GPL(v4l2_m2m_reqbufs);
538 
539 int v4l2_m2m_querybuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
540 		      struct v4l2_buffer *buf)
541 {
542 	struct vb2_queue *vq;
543 	int ret = 0;
544 	unsigned int i;
545 
546 	vq = v4l2_m2m_get_vq(m2m_ctx, buf->type);
547 	ret = vb2_querybuf(vq, buf);
548 
549 	/* Adjust MMAP memory offsets for the CAPTURE queue */
550 	if (buf->memory == V4L2_MEMORY_MMAP && !V4L2_TYPE_IS_OUTPUT(vq->type)) {
551 		if (V4L2_TYPE_IS_MULTIPLANAR(vq->type)) {
552 			for (i = 0; i < buf->length; ++i)
553 				buf->m.planes[i].m.mem_offset
554 					+= DST_QUEUE_OFF_BASE;
555 		} else {
556 			buf->m.offset += DST_QUEUE_OFF_BASE;
557 		}
558 	}
559 
560 	return ret;
561 }
562 EXPORT_SYMBOL_GPL(v4l2_m2m_querybuf);
563 
564 /*
565  * This will add the LAST flag and mark the buffer management
566  * state as stopped.
567  * This is called when the last capture buffer must be flagged as LAST
568  * in draining mode from the encoder/decoder driver buf_queue() callback
569  * or from v4l2_update_last_buf_state() when a capture buffer is available.
570  */
571 void v4l2_m2m_last_buffer_done(struct v4l2_m2m_ctx *m2m_ctx,
572 			       struct vb2_v4l2_buffer *vbuf)
573 {
574 	vbuf->flags |= V4L2_BUF_FLAG_LAST;
575 	vb2_buffer_done(&vbuf->vb2_buf, VB2_BUF_STATE_DONE);
576 
577 	v4l2_m2m_mark_stopped(m2m_ctx);
578 }
579 EXPORT_SYMBOL_GPL(v4l2_m2m_last_buffer_done);
580 
581 /* When stop command is issued, update buffer management state */
582 static int v4l2_update_last_buf_state(struct v4l2_m2m_ctx *m2m_ctx)
583 {
584 	struct vb2_v4l2_buffer *next_dst_buf;
585 
586 	if (m2m_ctx->is_draining)
587 		return -EBUSY;
588 
589 	if (m2m_ctx->has_stopped)
590 		return 0;
591 
592 	m2m_ctx->last_src_buf = v4l2_m2m_last_src_buf(m2m_ctx);
593 	m2m_ctx->is_draining = true;
594 
595 	/*
596 	 * The processing of the last output buffer queued before
597 	 * the STOP command is expected to mark the buffer management
598 	 * state as stopped with v4l2_m2m_mark_stopped().
599 	 */
600 	if (m2m_ctx->last_src_buf)
601 		return 0;
602 
603 	/*
604 	 * In case the output queue is empty, try to mark the last capture
605 	 * buffer as LAST.
606 	 */
607 	next_dst_buf = v4l2_m2m_dst_buf_remove(m2m_ctx);
608 	if (!next_dst_buf) {
609 		/*
610 		 * Wait for the next queued one in encoder/decoder driver
611 		 * buf_queue() callback using the v4l2_m2m_dst_buf_is_last()
612 		 * helper or in v4l2_m2m_qbuf() if encoder/decoder is not yet
613 		 * streaming.
614 		 */
615 		m2m_ctx->next_buf_last = true;
616 		return 0;
617 	}
618 
619 	v4l2_m2m_last_buffer_done(m2m_ctx, next_dst_buf);
620 
621 	return 0;
622 }
623 
624 /*
625  * Updates the encoding/decoding buffer management state, should
626  * be called from encoder/decoder drivers start_streaming()
627  */
628 void v4l2_m2m_update_start_streaming_state(struct v4l2_m2m_ctx *m2m_ctx,
629 					   struct vb2_queue *q)
630 {
631 	/* If start streaming again, untag the last output buffer */
632 	if (V4L2_TYPE_IS_OUTPUT(q->type))
633 		m2m_ctx->last_src_buf = NULL;
634 }
635 EXPORT_SYMBOL_GPL(v4l2_m2m_update_start_streaming_state);
636 
637 /*
638  * Updates the encoding/decoding buffer management state, should
639  * be called from encoder/decoder driver stop_streaming()
640  */
641 void v4l2_m2m_update_stop_streaming_state(struct v4l2_m2m_ctx *m2m_ctx,
642 					  struct vb2_queue *q)
643 {
644 	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
645 		/*
646 		 * If in draining state, either mark next dst buffer as
647 		 * done or flag next one to be marked as done either
648 		 * in encoder/decoder driver buf_queue() callback using
649 		 * the v4l2_m2m_dst_buf_is_last() helper or in v4l2_m2m_qbuf()
650 		 * if encoder/decoder is not yet streaming
651 		 */
652 		if (m2m_ctx->is_draining) {
653 			struct vb2_v4l2_buffer *next_dst_buf;
654 
655 			m2m_ctx->last_src_buf = NULL;
656 			next_dst_buf = v4l2_m2m_dst_buf_remove(m2m_ctx);
657 			if (!next_dst_buf)
658 				m2m_ctx->next_buf_last = true;
659 			else
660 				v4l2_m2m_last_buffer_done(m2m_ctx,
661 							  next_dst_buf);
662 		}
663 	} else {
664 		v4l2_m2m_clear_state(m2m_ctx);
665 	}
666 }
667 EXPORT_SYMBOL_GPL(v4l2_m2m_update_stop_streaming_state);
668 
669 static void v4l2_m2m_force_last_buf_done(struct v4l2_m2m_ctx *m2m_ctx,
670 					 struct vb2_queue *q)
671 {
672 	struct vb2_buffer *vb;
673 	struct vb2_v4l2_buffer *vbuf;
674 	unsigned int i;
675 
676 	if (WARN_ON(q->is_output))
677 		return;
678 	if (list_empty(&q->queued_list))
679 		return;
680 
681 	vb = list_first_entry(&q->queued_list, struct vb2_buffer, queued_entry);
682 	for (i = 0; i < vb->num_planes; i++)
683 		vb2_set_plane_payload(vb, i, 0);
684 
685 	/*
686 	 * Since the buffer hasn't been queued to the ready queue,
687 	 * mark is active and owned before marking it LAST and DONE
688 	 */
689 	vb->state = VB2_BUF_STATE_ACTIVE;
690 	atomic_inc(&q->owned_by_drv_count);
691 
692 	vbuf = to_vb2_v4l2_buffer(vb);
693 	vbuf->field = V4L2_FIELD_NONE;
694 
695 	v4l2_m2m_last_buffer_done(m2m_ctx, vbuf);
696 }
697 
698 int v4l2_m2m_qbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
699 		  struct v4l2_buffer *buf)
700 {
701 	struct video_device *vdev = video_devdata(file);
702 	struct vb2_queue *vq;
703 	int ret;
704 
705 	vq = v4l2_m2m_get_vq(m2m_ctx, buf->type);
706 	if (!V4L2_TYPE_IS_OUTPUT(vq->type) &&
707 	    (buf->flags & V4L2_BUF_FLAG_REQUEST_FD)) {
708 		dprintk("%s: requests cannot be used with capture buffers\n",
709 			__func__);
710 		return -EPERM;
711 	}
712 
713 	ret = vb2_qbuf(vq, vdev->v4l2_dev->mdev, buf);
714 	if (ret)
715 		return ret;
716 
717 	/*
718 	 * If the capture queue is streaming, but streaming hasn't started
719 	 * on the device, but was asked to stop, mark the previously queued
720 	 * buffer as DONE with LAST flag since it won't be queued on the
721 	 * device.
722 	 */
723 	if (!V4L2_TYPE_IS_OUTPUT(vq->type) &&
724 	    vb2_is_streaming(vq) && !vb2_start_streaming_called(vq) &&
725 	   (v4l2_m2m_has_stopped(m2m_ctx) || v4l2_m2m_dst_buf_is_last(m2m_ctx)))
726 		v4l2_m2m_force_last_buf_done(m2m_ctx, vq);
727 	else if (!(buf->flags & V4L2_BUF_FLAG_IN_REQUEST))
728 		v4l2_m2m_try_schedule(m2m_ctx);
729 
730 	return 0;
731 }
732 EXPORT_SYMBOL_GPL(v4l2_m2m_qbuf);
733 
734 int v4l2_m2m_dqbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
735 		   struct v4l2_buffer *buf)
736 {
737 	struct vb2_queue *vq;
738 
739 	vq = v4l2_m2m_get_vq(m2m_ctx, buf->type);
740 	return vb2_dqbuf(vq, buf, file->f_flags & O_NONBLOCK);
741 }
742 EXPORT_SYMBOL_GPL(v4l2_m2m_dqbuf);
743 
744 int v4l2_m2m_prepare_buf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
745 			 struct v4l2_buffer *buf)
746 {
747 	struct video_device *vdev = video_devdata(file);
748 	struct vb2_queue *vq;
749 
750 	vq = v4l2_m2m_get_vq(m2m_ctx, buf->type);
751 	return vb2_prepare_buf(vq, vdev->v4l2_dev->mdev, buf);
752 }
753 EXPORT_SYMBOL_GPL(v4l2_m2m_prepare_buf);
754 
755 int v4l2_m2m_create_bufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
756 			 struct v4l2_create_buffers *create)
757 {
758 	struct vb2_queue *vq;
759 
760 	vq = v4l2_m2m_get_vq(m2m_ctx, create->format.type);
761 	return vb2_create_bufs(vq, create);
762 }
763 EXPORT_SYMBOL_GPL(v4l2_m2m_create_bufs);
764 
765 int v4l2_m2m_expbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
766 		  struct v4l2_exportbuffer *eb)
767 {
768 	struct vb2_queue *vq;
769 
770 	vq = v4l2_m2m_get_vq(m2m_ctx, eb->type);
771 	return vb2_expbuf(vq, eb);
772 }
773 EXPORT_SYMBOL_GPL(v4l2_m2m_expbuf);
774 
775 int v4l2_m2m_streamon(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
776 		      enum v4l2_buf_type type)
777 {
778 	struct vb2_queue *vq;
779 	int ret;
780 
781 	vq = v4l2_m2m_get_vq(m2m_ctx, type);
782 	ret = vb2_streamon(vq, type);
783 	if (!ret)
784 		v4l2_m2m_try_schedule(m2m_ctx);
785 
786 	return ret;
787 }
788 EXPORT_SYMBOL_GPL(v4l2_m2m_streamon);
789 
790 int v4l2_m2m_streamoff(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
791 		       enum v4l2_buf_type type)
792 {
793 	struct v4l2_m2m_dev *m2m_dev;
794 	struct v4l2_m2m_queue_ctx *q_ctx;
795 	unsigned long flags_job, flags;
796 	int ret;
797 
798 	/* wait until the current context is dequeued from job_queue */
799 	v4l2_m2m_cancel_job(m2m_ctx);
800 
801 	q_ctx = get_queue_ctx(m2m_ctx, type);
802 	ret = vb2_streamoff(&q_ctx->q, type);
803 	if (ret)
804 		return ret;
805 
806 	m2m_dev = m2m_ctx->m2m_dev;
807 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags_job);
808 	/* We should not be scheduled anymore, since we're dropping a queue. */
809 	if (m2m_ctx->job_flags & TRANS_QUEUED)
810 		list_del(&m2m_ctx->queue);
811 	m2m_ctx->job_flags = 0;
812 
813 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
814 	/* Drop queue, since streamoff returns device to the same state as after
815 	 * calling reqbufs. */
816 	INIT_LIST_HEAD(&q_ctx->rdy_queue);
817 	q_ctx->num_rdy = 0;
818 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
819 
820 	if (m2m_dev->curr_ctx == m2m_ctx) {
821 		m2m_dev->curr_ctx = NULL;
822 		wake_up(&m2m_ctx->finished);
823 	}
824 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags_job);
825 
826 	return 0;
827 }
828 EXPORT_SYMBOL_GPL(v4l2_m2m_streamoff);
829 
830 static __poll_t v4l2_m2m_poll_for_data(struct file *file,
831 				       struct v4l2_m2m_ctx *m2m_ctx,
832 				       struct poll_table_struct *wait)
833 {
834 	struct vb2_queue *src_q, *dst_q;
835 	struct vb2_buffer *src_vb = NULL, *dst_vb = NULL;
836 	__poll_t rc = 0;
837 	unsigned long flags;
838 
839 	src_q = v4l2_m2m_get_src_vq(m2m_ctx);
840 	dst_q = v4l2_m2m_get_dst_vq(m2m_ctx);
841 
842 	poll_wait(file, &src_q->done_wq, wait);
843 	poll_wait(file, &dst_q->done_wq, wait);
844 
845 	/*
846 	 * There has to be at least one buffer queued on each queued_list, which
847 	 * means either in driver already or waiting for driver to claim it
848 	 * and start processing.
849 	 */
850 	if ((!src_q->streaming || src_q->error ||
851 	     list_empty(&src_q->queued_list)) &&
852 	    (!dst_q->streaming || dst_q->error ||
853 	     list_empty(&dst_q->queued_list)))
854 		return EPOLLERR;
855 
856 	spin_lock_irqsave(&dst_q->done_lock, flags);
857 	if (list_empty(&dst_q->done_list)) {
858 		/*
859 		 * If the last buffer was dequeued from the capture queue,
860 		 * return immediately. DQBUF will return -EPIPE.
861 		 */
862 		if (dst_q->last_buffer_dequeued) {
863 			spin_unlock_irqrestore(&dst_q->done_lock, flags);
864 			return EPOLLIN | EPOLLRDNORM;
865 		}
866 	}
867 	spin_unlock_irqrestore(&dst_q->done_lock, flags);
868 
869 	spin_lock_irqsave(&src_q->done_lock, flags);
870 	if (!list_empty(&src_q->done_list))
871 		src_vb = list_first_entry(&src_q->done_list, struct vb2_buffer,
872 						done_entry);
873 	if (src_vb && (src_vb->state == VB2_BUF_STATE_DONE
874 			|| src_vb->state == VB2_BUF_STATE_ERROR))
875 		rc |= EPOLLOUT | EPOLLWRNORM;
876 	spin_unlock_irqrestore(&src_q->done_lock, flags);
877 
878 	spin_lock_irqsave(&dst_q->done_lock, flags);
879 	if (!list_empty(&dst_q->done_list))
880 		dst_vb = list_first_entry(&dst_q->done_list, struct vb2_buffer,
881 						done_entry);
882 	if (dst_vb && (dst_vb->state == VB2_BUF_STATE_DONE
883 			|| dst_vb->state == VB2_BUF_STATE_ERROR))
884 		rc |= EPOLLIN | EPOLLRDNORM;
885 	spin_unlock_irqrestore(&dst_q->done_lock, flags);
886 
887 	return rc;
888 }
889 
890 __poll_t v4l2_m2m_poll(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
891 		       struct poll_table_struct *wait)
892 {
893 	struct video_device *vfd = video_devdata(file);
894 	__poll_t req_events = poll_requested_events(wait);
895 	__poll_t rc = 0;
896 
897 	if (req_events & (EPOLLOUT | EPOLLWRNORM | EPOLLIN | EPOLLRDNORM))
898 		rc = v4l2_m2m_poll_for_data(file, m2m_ctx, wait);
899 
900 	if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
901 		struct v4l2_fh *fh = file->private_data;
902 
903 		poll_wait(file, &fh->wait, wait);
904 		if (v4l2_event_pending(fh))
905 			rc |= EPOLLPRI;
906 	}
907 
908 	return rc;
909 }
910 EXPORT_SYMBOL_GPL(v4l2_m2m_poll);
911 
912 int v4l2_m2m_mmap(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
913 			 struct vm_area_struct *vma)
914 {
915 	unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
916 	struct vb2_queue *vq;
917 
918 	if (offset < DST_QUEUE_OFF_BASE) {
919 		vq = v4l2_m2m_get_src_vq(m2m_ctx);
920 	} else {
921 		vq = v4l2_m2m_get_dst_vq(m2m_ctx);
922 		vma->vm_pgoff -= (DST_QUEUE_OFF_BASE >> PAGE_SHIFT);
923 	}
924 
925 	return vb2_mmap(vq, vma);
926 }
927 EXPORT_SYMBOL(v4l2_m2m_mmap);
928 
929 #if defined(CONFIG_MEDIA_CONTROLLER)
930 void v4l2_m2m_unregister_media_controller(struct v4l2_m2m_dev *m2m_dev)
931 {
932 	media_remove_intf_links(&m2m_dev->intf_devnode->intf);
933 	media_devnode_remove(m2m_dev->intf_devnode);
934 
935 	media_entity_remove_links(m2m_dev->source);
936 	media_entity_remove_links(&m2m_dev->sink);
937 	media_entity_remove_links(&m2m_dev->proc);
938 	media_device_unregister_entity(m2m_dev->source);
939 	media_device_unregister_entity(&m2m_dev->sink);
940 	media_device_unregister_entity(&m2m_dev->proc);
941 	kfree(m2m_dev->source->name);
942 	kfree(m2m_dev->sink.name);
943 	kfree(m2m_dev->proc.name);
944 }
945 EXPORT_SYMBOL_GPL(v4l2_m2m_unregister_media_controller);
946 
947 static int v4l2_m2m_register_entity(struct media_device *mdev,
948 	struct v4l2_m2m_dev *m2m_dev, enum v4l2_m2m_entity_type type,
949 	struct video_device *vdev, int function)
950 {
951 	struct media_entity *entity;
952 	struct media_pad *pads;
953 	char *name;
954 	unsigned int len;
955 	int num_pads;
956 	int ret;
957 
958 	switch (type) {
959 	case MEM2MEM_ENT_TYPE_SOURCE:
960 		entity = m2m_dev->source;
961 		pads = &m2m_dev->source_pad;
962 		pads[0].flags = MEDIA_PAD_FL_SOURCE;
963 		num_pads = 1;
964 		break;
965 	case MEM2MEM_ENT_TYPE_SINK:
966 		entity = &m2m_dev->sink;
967 		pads = &m2m_dev->sink_pad;
968 		pads[0].flags = MEDIA_PAD_FL_SINK;
969 		num_pads = 1;
970 		break;
971 	case MEM2MEM_ENT_TYPE_PROC:
972 		entity = &m2m_dev->proc;
973 		pads = m2m_dev->proc_pads;
974 		pads[0].flags = MEDIA_PAD_FL_SINK;
975 		pads[1].flags = MEDIA_PAD_FL_SOURCE;
976 		num_pads = 2;
977 		break;
978 	default:
979 		return -EINVAL;
980 	}
981 
982 	entity->obj_type = MEDIA_ENTITY_TYPE_BASE;
983 	if (type != MEM2MEM_ENT_TYPE_PROC) {
984 		entity->info.dev.major = VIDEO_MAJOR;
985 		entity->info.dev.minor = vdev->minor;
986 	}
987 	len = strlen(vdev->name) + 2 + strlen(m2m_entity_name[type]);
988 	name = kmalloc(len, GFP_KERNEL);
989 	if (!name)
990 		return -ENOMEM;
991 	snprintf(name, len, "%s-%s", vdev->name, m2m_entity_name[type]);
992 	entity->name = name;
993 	entity->function = function;
994 
995 	ret = media_entity_pads_init(entity, num_pads, pads);
996 	if (ret)
997 		return ret;
998 	ret = media_device_register_entity(mdev, entity);
999 	if (ret)
1000 		return ret;
1001 
1002 	return 0;
1003 }
1004 
1005 int v4l2_m2m_register_media_controller(struct v4l2_m2m_dev *m2m_dev,
1006 		struct video_device *vdev, int function)
1007 {
1008 	struct media_device *mdev = vdev->v4l2_dev->mdev;
1009 	struct media_link *link;
1010 	int ret;
1011 
1012 	if (!mdev)
1013 		return 0;
1014 
1015 	/* A memory-to-memory device consists in two
1016 	 * DMA engine and one video processing entities.
1017 	 * The DMA engine entities are linked to a V4L interface
1018 	 */
1019 
1020 	/* Create the three entities with their pads */
1021 	m2m_dev->source = &vdev->entity;
1022 	ret = v4l2_m2m_register_entity(mdev, m2m_dev,
1023 			MEM2MEM_ENT_TYPE_SOURCE, vdev, MEDIA_ENT_F_IO_V4L);
1024 	if (ret)
1025 		return ret;
1026 	ret = v4l2_m2m_register_entity(mdev, m2m_dev,
1027 			MEM2MEM_ENT_TYPE_PROC, vdev, function);
1028 	if (ret)
1029 		goto err_rel_entity0;
1030 	ret = v4l2_m2m_register_entity(mdev, m2m_dev,
1031 			MEM2MEM_ENT_TYPE_SINK, vdev, MEDIA_ENT_F_IO_V4L);
1032 	if (ret)
1033 		goto err_rel_entity1;
1034 
1035 	/* Connect the three entities */
1036 	ret = media_create_pad_link(m2m_dev->source, 0, &m2m_dev->proc, 0,
1037 			MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED);
1038 	if (ret)
1039 		goto err_rel_entity2;
1040 
1041 	ret = media_create_pad_link(&m2m_dev->proc, 1, &m2m_dev->sink, 0,
1042 			MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED);
1043 	if (ret)
1044 		goto err_rm_links0;
1045 
1046 	/* Create video interface */
1047 	m2m_dev->intf_devnode = media_devnode_create(mdev,
1048 			MEDIA_INTF_T_V4L_VIDEO, 0,
1049 			VIDEO_MAJOR, vdev->minor);
1050 	if (!m2m_dev->intf_devnode) {
1051 		ret = -ENOMEM;
1052 		goto err_rm_links1;
1053 	}
1054 
1055 	/* Connect the two DMA engines to the interface */
1056 	link = media_create_intf_link(m2m_dev->source,
1057 			&m2m_dev->intf_devnode->intf,
1058 			MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED);
1059 	if (!link) {
1060 		ret = -ENOMEM;
1061 		goto err_rm_devnode;
1062 	}
1063 
1064 	link = media_create_intf_link(&m2m_dev->sink,
1065 			&m2m_dev->intf_devnode->intf,
1066 			MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED);
1067 	if (!link) {
1068 		ret = -ENOMEM;
1069 		goto err_rm_intf_link;
1070 	}
1071 	return 0;
1072 
1073 err_rm_intf_link:
1074 	media_remove_intf_links(&m2m_dev->intf_devnode->intf);
1075 err_rm_devnode:
1076 	media_devnode_remove(m2m_dev->intf_devnode);
1077 err_rm_links1:
1078 	media_entity_remove_links(&m2m_dev->sink);
1079 err_rm_links0:
1080 	media_entity_remove_links(&m2m_dev->proc);
1081 	media_entity_remove_links(m2m_dev->source);
1082 err_rel_entity2:
1083 	media_device_unregister_entity(&m2m_dev->proc);
1084 	kfree(m2m_dev->proc.name);
1085 err_rel_entity1:
1086 	media_device_unregister_entity(&m2m_dev->sink);
1087 	kfree(m2m_dev->sink.name);
1088 err_rel_entity0:
1089 	media_device_unregister_entity(m2m_dev->source);
1090 	kfree(m2m_dev->source->name);
1091 	return ret;
1092 	return 0;
1093 }
1094 EXPORT_SYMBOL_GPL(v4l2_m2m_register_media_controller);
1095 #endif
1096 
1097 struct v4l2_m2m_dev *v4l2_m2m_init(const struct v4l2_m2m_ops *m2m_ops)
1098 {
1099 	struct v4l2_m2m_dev *m2m_dev;
1100 
1101 	if (!m2m_ops || WARN_ON(!m2m_ops->device_run))
1102 		return ERR_PTR(-EINVAL);
1103 
1104 	m2m_dev = kzalloc(sizeof *m2m_dev, GFP_KERNEL);
1105 	if (!m2m_dev)
1106 		return ERR_PTR(-ENOMEM);
1107 
1108 	m2m_dev->curr_ctx = NULL;
1109 	m2m_dev->m2m_ops = m2m_ops;
1110 	INIT_LIST_HEAD(&m2m_dev->job_queue);
1111 	spin_lock_init(&m2m_dev->job_spinlock);
1112 	INIT_WORK(&m2m_dev->job_work, v4l2_m2m_device_run_work);
1113 
1114 	return m2m_dev;
1115 }
1116 EXPORT_SYMBOL_GPL(v4l2_m2m_init);
1117 
1118 void v4l2_m2m_release(struct v4l2_m2m_dev *m2m_dev)
1119 {
1120 	kfree(m2m_dev);
1121 }
1122 EXPORT_SYMBOL_GPL(v4l2_m2m_release);
1123 
1124 struct v4l2_m2m_ctx *v4l2_m2m_ctx_init(struct v4l2_m2m_dev *m2m_dev,
1125 		void *drv_priv,
1126 		int (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq))
1127 {
1128 	struct v4l2_m2m_ctx *m2m_ctx;
1129 	struct v4l2_m2m_queue_ctx *out_q_ctx, *cap_q_ctx;
1130 	int ret;
1131 
1132 	m2m_ctx = kzalloc(sizeof *m2m_ctx, GFP_KERNEL);
1133 	if (!m2m_ctx)
1134 		return ERR_PTR(-ENOMEM);
1135 
1136 	m2m_ctx->priv = drv_priv;
1137 	m2m_ctx->m2m_dev = m2m_dev;
1138 	init_waitqueue_head(&m2m_ctx->finished);
1139 
1140 	out_q_ctx = &m2m_ctx->out_q_ctx;
1141 	cap_q_ctx = &m2m_ctx->cap_q_ctx;
1142 
1143 	INIT_LIST_HEAD(&out_q_ctx->rdy_queue);
1144 	INIT_LIST_HEAD(&cap_q_ctx->rdy_queue);
1145 	spin_lock_init(&out_q_ctx->rdy_spinlock);
1146 	spin_lock_init(&cap_q_ctx->rdy_spinlock);
1147 
1148 	INIT_LIST_HEAD(&m2m_ctx->queue);
1149 
1150 	ret = queue_init(drv_priv, &out_q_ctx->q, &cap_q_ctx->q);
1151 
1152 	if (ret)
1153 		goto err;
1154 	/*
1155 	 * Both queues should use same the mutex to lock the m2m context.
1156 	 * This lock is used in some v4l2_m2m_* helpers.
1157 	 */
1158 	if (WARN_ON(out_q_ctx->q.lock != cap_q_ctx->q.lock)) {
1159 		ret = -EINVAL;
1160 		goto err;
1161 	}
1162 	m2m_ctx->q_lock = out_q_ctx->q.lock;
1163 
1164 	return m2m_ctx;
1165 err:
1166 	kfree(m2m_ctx);
1167 	return ERR_PTR(ret);
1168 }
1169 EXPORT_SYMBOL_GPL(v4l2_m2m_ctx_init);
1170 
1171 void v4l2_m2m_ctx_release(struct v4l2_m2m_ctx *m2m_ctx)
1172 {
1173 	/* wait until the current context is dequeued from job_queue */
1174 	v4l2_m2m_cancel_job(m2m_ctx);
1175 
1176 	vb2_queue_release(&m2m_ctx->cap_q_ctx.q);
1177 	vb2_queue_release(&m2m_ctx->out_q_ctx.q);
1178 
1179 	kfree(m2m_ctx);
1180 }
1181 EXPORT_SYMBOL_GPL(v4l2_m2m_ctx_release);
1182 
1183 void v4l2_m2m_buf_queue(struct v4l2_m2m_ctx *m2m_ctx,
1184 		struct vb2_v4l2_buffer *vbuf)
1185 {
1186 	struct v4l2_m2m_buffer *b = container_of(vbuf,
1187 				struct v4l2_m2m_buffer, vb);
1188 	struct v4l2_m2m_queue_ctx *q_ctx;
1189 	unsigned long flags;
1190 
1191 	q_ctx = get_queue_ctx(m2m_ctx, vbuf->vb2_buf.vb2_queue->type);
1192 	if (!q_ctx)
1193 		return;
1194 
1195 	spin_lock_irqsave(&q_ctx->rdy_spinlock, flags);
1196 	list_add_tail(&b->list, &q_ctx->rdy_queue);
1197 	q_ctx->num_rdy++;
1198 	spin_unlock_irqrestore(&q_ctx->rdy_spinlock, flags);
1199 }
1200 EXPORT_SYMBOL_GPL(v4l2_m2m_buf_queue);
1201 
1202 void v4l2_m2m_buf_copy_metadata(const struct vb2_v4l2_buffer *out_vb,
1203 				struct vb2_v4l2_buffer *cap_vb,
1204 				bool copy_frame_flags)
1205 {
1206 	u32 mask = V4L2_BUF_FLAG_TIMECODE | V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
1207 
1208 	if (copy_frame_flags)
1209 		mask |= V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME |
1210 			V4L2_BUF_FLAG_BFRAME;
1211 
1212 	cap_vb->vb2_buf.timestamp = out_vb->vb2_buf.timestamp;
1213 
1214 	if (out_vb->flags & V4L2_BUF_FLAG_TIMECODE)
1215 		cap_vb->timecode = out_vb->timecode;
1216 	cap_vb->field = out_vb->field;
1217 	cap_vb->flags &= ~mask;
1218 	cap_vb->flags |= out_vb->flags & mask;
1219 	cap_vb->vb2_buf.copied_timestamp = 1;
1220 }
1221 EXPORT_SYMBOL_GPL(v4l2_m2m_buf_copy_metadata);
1222 
1223 void v4l2_m2m_request_queue(struct media_request *req)
1224 {
1225 	struct media_request_object *obj, *obj_safe;
1226 	struct v4l2_m2m_ctx *m2m_ctx = NULL;
1227 
1228 	/*
1229 	 * Queue all objects. Note that buffer objects are at the end of the
1230 	 * objects list, after all other object types. Once buffer objects
1231 	 * are queued, the driver might delete them immediately (if the driver
1232 	 * processes the buffer at once), so we have to use
1233 	 * list_for_each_entry_safe() to handle the case where the object we
1234 	 * queue is deleted.
1235 	 */
1236 	list_for_each_entry_safe(obj, obj_safe, &req->objects, list) {
1237 		struct v4l2_m2m_ctx *m2m_ctx_obj;
1238 		struct vb2_buffer *vb;
1239 
1240 		if (!obj->ops->queue)
1241 			continue;
1242 
1243 		if (vb2_request_object_is_buffer(obj)) {
1244 			/* Sanity checks */
1245 			vb = container_of(obj, struct vb2_buffer, req_obj);
1246 			WARN_ON(!V4L2_TYPE_IS_OUTPUT(vb->vb2_queue->type));
1247 			m2m_ctx_obj = container_of(vb->vb2_queue,
1248 						   struct v4l2_m2m_ctx,
1249 						   out_q_ctx.q);
1250 			WARN_ON(m2m_ctx && m2m_ctx_obj != m2m_ctx);
1251 			m2m_ctx = m2m_ctx_obj;
1252 		}
1253 
1254 		/*
1255 		 * The buffer we queue here can in theory be immediately
1256 		 * unbound, hence the use of list_for_each_entry_safe()
1257 		 * above and why we call the queue op last.
1258 		 */
1259 		obj->ops->queue(obj);
1260 	}
1261 
1262 	WARN_ON(!m2m_ctx);
1263 
1264 	if (m2m_ctx)
1265 		v4l2_m2m_try_schedule(m2m_ctx);
1266 }
1267 EXPORT_SYMBOL_GPL(v4l2_m2m_request_queue);
1268 
1269 /* Videobuf2 ioctl helpers */
1270 
1271 int v4l2_m2m_ioctl_reqbufs(struct file *file, void *priv,
1272 				struct v4l2_requestbuffers *rb)
1273 {
1274 	struct v4l2_fh *fh = file->private_data;
1275 
1276 	return v4l2_m2m_reqbufs(file, fh->m2m_ctx, rb);
1277 }
1278 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_reqbufs);
1279 
1280 int v4l2_m2m_ioctl_create_bufs(struct file *file, void *priv,
1281 				struct v4l2_create_buffers *create)
1282 {
1283 	struct v4l2_fh *fh = file->private_data;
1284 
1285 	return v4l2_m2m_create_bufs(file, fh->m2m_ctx, create);
1286 }
1287 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_create_bufs);
1288 
1289 int v4l2_m2m_ioctl_querybuf(struct file *file, void *priv,
1290 				struct v4l2_buffer *buf)
1291 {
1292 	struct v4l2_fh *fh = file->private_data;
1293 
1294 	return v4l2_m2m_querybuf(file, fh->m2m_ctx, buf);
1295 }
1296 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_querybuf);
1297 
1298 int v4l2_m2m_ioctl_qbuf(struct file *file, void *priv,
1299 				struct v4l2_buffer *buf)
1300 {
1301 	struct v4l2_fh *fh = file->private_data;
1302 
1303 	return v4l2_m2m_qbuf(file, fh->m2m_ctx, buf);
1304 }
1305 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_qbuf);
1306 
1307 int v4l2_m2m_ioctl_dqbuf(struct file *file, void *priv,
1308 				struct v4l2_buffer *buf)
1309 {
1310 	struct v4l2_fh *fh = file->private_data;
1311 
1312 	return v4l2_m2m_dqbuf(file, fh->m2m_ctx, buf);
1313 }
1314 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_dqbuf);
1315 
1316 int v4l2_m2m_ioctl_prepare_buf(struct file *file, void *priv,
1317 			       struct v4l2_buffer *buf)
1318 {
1319 	struct v4l2_fh *fh = file->private_data;
1320 
1321 	return v4l2_m2m_prepare_buf(file, fh->m2m_ctx, buf);
1322 }
1323 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_prepare_buf);
1324 
1325 int v4l2_m2m_ioctl_expbuf(struct file *file, void *priv,
1326 				struct v4l2_exportbuffer *eb)
1327 {
1328 	struct v4l2_fh *fh = file->private_data;
1329 
1330 	return v4l2_m2m_expbuf(file, fh->m2m_ctx, eb);
1331 }
1332 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_expbuf);
1333 
1334 int v4l2_m2m_ioctl_streamon(struct file *file, void *priv,
1335 				enum v4l2_buf_type type)
1336 {
1337 	struct v4l2_fh *fh = file->private_data;
1338 
1339 	return v4l2_m2m_streamon(file, fh->m2m_ctx, type);
1340 }
1341 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_streamon);
1342 
1343 int v4l2_m2m_ioctl_streamoff(struct file *file, void *priv,
1344 				enum v4l2_buf_type type)
1345 {
1346 	struct v4l2_fh *fh = file->private_data;
1347 
1348 	return v4l2_m2m_streamoff(file, fh->m2m_ctx, type);
1349 }
1350 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_streamoff);
1351 
1352 int v4l2_m2m_ioctl_try_encoder_cmd(struct file *file, void *fh,
1353 				   struct v4l2_encoder_cmd *ec)
1354 {
1355 	if (ec->cmd != V4L2_ENC_CMD_STOP && ec->cmd != V4L2_ENC_CMD_START)
1356 		return -EINVAL;
1357 
1358 	ec->flags = 0;
1359 	return 0;
1360 }
1361 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_try_encoder_cmd);
1362 
1363 int v4l2_m2m_ioctl_try_decoder_cmd(struct file *file, void *fh,
1364 				   struct v4l2_decoder_cmd *dc)
1365 {
1366 	if (dc->cmd != V4L2_DEC_CMD_STOP && dc->cmd != V4L2_DEC_CMD_START)
1367 		return -EINVAL;
1368 
1369 	dc->flags = 0;
1370 
1371 	if (dc->cmd == V4L2_DEC_CMD_STOP) {
1372 		dc->stop.pts = 0;
1373 	} else if (dc->cmd == V4L2_DEC_CMD_START) {
1374 		dc->start.speed = 0;
1375 		dc->start.format = V4L2_DEC_START_FMT_NONE;
1376 	}
1377 	return 0;
1378 }
1379 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_try_decoder_cmd);
1380 
1381 /*
1382  * Updates the encoding state on ENC_CMD_STOP/ENC_CMD_START
1383  * Should be called from the encoder driver encoder_cmd() callback
1384  */
1385 int v4l2_m2m_encoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
1386 			 struct v4l2_encoder_cmd *ec)
1387 {
1388 	if (ec->cmd != V4L2_ENC_CMD_STOP && ec->cmd != V4L2_ENC_CMD_START)
1389 		return -EINVAL;
1390 
1391 	if (ec->cmd == V4L2_ENC_CMD_STOP)
1392 		return v4l2_update_last_buf_state(m2m_ctx);
1393 
1394 	if (m2m_ctx->is_draining)
1395 		return -EBUSY;
1396 
1397 	if (m2m_ctx->has_stopped)
1398 		m2m_ctx->has_stopped = false;
1399 
1400 	return 0;
1401 }
1402 EXPORT_SYMBOL_GPL(v4l2_m2m_encoder_cmd);
1403 
1404 /*
1405  * Updates the decoding state on DEC_CMD_STOP/DEC_CMD_START
1406  * Should be called from the decoder driver decoder_cmd() callback
1407  */
1408 int v4l2_m2m_decoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx,
1409 			 struct v4l2_decoder_cmd *dc)
1410 {
1411 	if (dc->cmd != V4L2_DEC_CMD_STOP && dc->cmd != V4L2_DEC_CMD_START)
1412 		return -EINVAL;
1413 
1414 	if (dc->cmd == V4L2_DEC_CMD_STOP)
1415 		return v4l2_update_last_buf_state(m2m_ctx);
1416 
1417 	if (m2m_ctx->is_draining)
1418 		return -EBUSY;
1419 
1420 	if (m2m_ctx->has_stopped)
1421 		m2m_ctx->has_stopped = false;
1422 
1423 	return 0;
1424 }
1425 EXPORT_SYMBOL_GPL(v4l2_m2m_decoder_cmd);
1426 
1427 int v4l2_m2m_ioctl_encoder_cmd(struct file *file, void *priv,
1428 			       struct v4l2_encoder_cmd *ec)
1429 {
1430 	struct v4l2_fh *fh = file->private_data;
1431 
1432 	return v4l2_m2m_encoder_cmd(file, fh->m2m_ctx, ec);
1433 }
1434 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_encoder_cmd);
1435 
1436 int v4l2_m2m_ioctl_decoder_cmd(struct file *file, void *priv,
1437 			       struct v4l2_decoder_cmd *dc)
1438 {
1439 	struct v4l2_fh *fh = file->private_data;
1440 
1441 	return v4l2_m2m_decoder_cmd(file, fh->m2m_ctx, dc);
1442 }
1443 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_decoder_cmd);
1444 
1445 int v4l2_m2m_ioctl_stateless_try_decoder_cmd(struct file *file, void *fh,
1446 					     struct v4l2_decoder_cmd *dc)
1447 {
1448 	if (dc->cmd != V4L2_DEC_CMD_FLUSH)
1449 		return -EINVAL;
1450 
1451 	dc->flags = 0;
1452 
1453 	return 0;
1454 }
1455 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_stateless_try_decoder_cmd);
1456 
1457 int v4l2_m2m_ioctl_stateless_decoder_cmd(struct file *file, void *priv,
1458 					 struct v4l2_decoder_cmd *dc)
1459 {
1460 	struct v4l2_fh *fh = file->private_data;
1461 	struct vb2_v4l2_buffer *out_vb, *cap_vb;
1462 	struct v4l2_m2m_dev *m2m_dev = fh->m2m_ctx->m2m_dev;
1463 	unsigned long flags;
1464 	int ret;
1465 
1466 	ret = v4l2_m2m_ioctl_stateless_try_decoder_cmd(file, priv, dc);
1467 	if (ret < 0)
1468 		return ret;
1469 
1470 	spin_lock_irqsave(&m2m_dev->job_spinlock, flags);
1471 	out_vb = v4l2_m2m_last_src_buf(fh->m2m_ctx);
1472 	cap_vb = v4l2_m2m_last_dst_buf(fh->m2m_ctx);
1473 
1474 	/*
1475 	 * If there is an out buffer pending, then clear any HOLD flag.
1476 	 *
1477 	 * By clearing this flag we ensure that when this output
1478 	 * buffer is processed any held capture buffer will be released.
1479 	 */
1480 	if (out_vb) {
1481 		out_vb->flags &= ~V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF;
1482 	} else if (cap_vb && cap_vb->is_held) {
1483 		/*
1484 		 * If there were no output buffers, but there is a
1485 		 * capture buffer that is held, then release that
1486 		 * buffer.
1487 		 */
1488 		cap_vb->is_held = false;
1489 		v4l2_m2m_dst_buf_remove(fh->m2m_ctx);
1490 		v4l2_m2m_buf_done(cap_vb, VB2_BUF_STATE_DONE);
1491 	}
1492 	spin_unlock_irqrestore(&m2m_dev->job_spinlock, flags);
1493 
1494 	return 0;
1495 }
1496 EXPORT_SYMBOL_GPL(v4l2_m2m_ioctl_stateless_decoder_cmd);
1497 
1498 /*
1499  * v4l2_file_operations helpers. It is assumed here same lock is used
1500  * for the output and the capture buffer queue.
1501  */
1502 
1503 int v4l2_m2m_fop_mmap(struct file *file, struct vm_area_struct *vma)
1504 {
1505 	struct v4l2_fh *fh = file->private_data;
1506 
1507 	return v4l2_m2m_mmap(file, fh->m2m_ctx, vma);
1508 }
1509 EXPORT_SYMBOL_GPL(v4l2_m2m_fop_mmap);
1510 
1511 __poll_t v4l2_m2m_fop_poll(struct file *file, poll_table *wait)
1512 {
1513 	struct v4l2_fh *fh = file->private_data;
1514 	struct v4l2_m2m_ctx *m2m_ctx = fh->m2m_ctx;
1515 	__poll_t ret;
1516 
1517 	if (m2m_ctx->q_lock)
1518 		mutex_lock(m2m_ctx->q_lock);
1519 
1520 	ret = v4l2_m2m_poll(file, m2m_ctx, wait);
1521 
1522 	if (m2m_ctx->q_lock)
1523 		mutex_unlock(m2m_ctx->q_lock);
1524 
1525 	return ret;
1526 }
1527 EXPORT_SYMBOL_GPL(v4l2_m2m_fop_poll);
1528 
1529