1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Video Capture Subdev for Freescale i.MX5/6 SOC
4  *
5  * Copyright (c) 2012-2016 Mentor Graphics Inc.
6  */
7 #include <linux/delay.h>
8 #include <linux/fs.h>
9 #include <linux/module.h>
10 #include <linux/of_platform.h>
11 #include <linux/pinctrl/consumer.h>
12 #include <linux/platform_device.h>
13 #include <linux/sched.h>
14 #include <linux/slab.h>
15 #include <linux/spinlock.h>
16 #include <linux/timer.h>
17 #include <media/v4l2-ctrls.h>
18 #include <media/v4l2-device.h>
19 #include <media/v4l2-event.h>
20 #include <media/v4l2-fwnode.h>
21 #include <media/v4l2-ioctl.h>
22 #include <media/v4l2-mc.h>
23 #include <media/v4l2-subdev.h>
24 #include <media/videobuf2-dma-contig.h>
25 #include <video/imx-ipu-v3.h>
26 #include <media/imx.h>
27 #include "imx-media.h"
28 
29 #define IMX_CAPTURE_NAME "imx-capture"
30 
31 struct capture_priv {
32 	struct imx_media_dev *md;		/* Media device */
33 	struct device *dev;			/* Physical device */
34 
35 	struct imx_media_video_dev vdev;	/* Video device */
36 	struct media_pad vdev_pad;		/* Video device pad */
37 
38 	struct v4l2_subdev *src_sd;		/* Source subdev */
39 	int src_sd_pad;				/* Source subdev pad */
40 
41 	struct mutex mutex;			/* Protect vdev operations */
42 
43 	struct vb2_queue q;			/* The videobuf2 queue */
44 	struct list_head ready_q;		/* List of queued buffers */
45 	spinlock_t q_lock;			/* Protect ready_q */
46 
47 	struct v4l2_ctrl_handler ctrl_hdlr;	/* Controls inherited from subdevs */
48 
49 	bool legacy_api;			/* Use the legacy (pre-MC) API */
50 };
51 
52 #define to_capture_priv(v) container_of(v, struct capture_priv, vdev)
53 
54 /* In bytes, per queue */
55 #define VID_MEM_LIMIT	SZ_64M
56 
57 /* -----------------------------------------------------------------------------
58  * MC-Centric Video IOCTLs
59  */
60 
61 static const struct imx_media_pixfmt *capture_find_format(u32 code, u32 fourcc)
62 {
63 	const struct imx_media_pixfmt *cc;
64 
65 	cc = imx_media_find_ipu_format(code, PIXFMT_SEL_YUV_RGB);
66 	if (cc) {
67 		enum imx_pixfmt_sel fmt_sel = cc->cs == IPUV3_COLORSPACE_YUV
68 					    ? PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
69 
70 		cc = imx_media_find_pixel_format(fourcc, fmt_sel);
71 		if (!cc) {
72 			imx_media_enum_pixel_formats(&fourcc, 0, fmt_sel, 0);
73 			cc = imx_media_find_pixel_format(fourcc, fmt_sel);
74 		}
75 
76 		return cc;
77 	}
78 
79 	return imx_media_find_mbus_format(code, PIXFMT_SEL_ANY);
80 }
81 
82 static int capture_querycap(struct file *file, void *fh,
83 			    struct v4l2_capability *cap)
84 {
85 	struct capture_priv *priv = video_drvdata(file);
86 
87 	strscpy(cap->driver, IMX_CAPTURE_NAME, sizeof(cap->driver));
88 	strscpy(cap->card, IMX_CAPTURE_NAME, sizeof(cap->card));
89 	snprintf(cap->bus_info, sizeof(cap->bus_info),
90 		 "platform:%s", dev_name(priv->dev));
91 
92 	return 0;
93 }
94 
95 static int capture_enum_fmt_vid_cap(struct file *file, void *fh,
96 				    struct v4l2_fmtdesc *f)
97 {
98 	return imx_media_enum_pixel_formats(&f->pixelformat, f->index,
99 					    PIXFMT_SEL_ANY, f->mbus_code);
100 }
101 
102 static int capture_enum_framesizes(struct file *file, void *fh,
103 				   struct v4l2_frmsizeenum *fsize)
104 {
105 	const struct imx_media_pixfmt *cc;
106 
107 	if (fsize->index > 0)
108 		return -EINVAL;
109 
110 	cc = imx_media_find_pixel_format(fsize->pixel_format, PIXFMT_SEL_ANY);
111 	if (!cc)
112 		return -EINVAL;
113 
114 	/*
115 	 * TODO: The constraints are hardware-specific and may depend on the
116 	 * pixel format. This should come from the driver using
117 	 * imx_media_capture.
118 	 */
119 	fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
120 	fsize->stepwise.min_width = 1;
121 	fsize->stepwise.max_width = 65535;
122 	fsize->stepwise.min_height = 1;
123 	fsize->stepwise.max_height = 65535;
124 	fsize->stepwise.step_width = 1;
125 	fsize->stepwise.step_height = 1;
126 
127 	return 0;
128 }
129 
130 static int capture_g_fmt_vid_cap(struct file *file, void *fh,
131 				 struct v4l2_format *f)
132 {
133 	struct capture_priv *priv = video_drvdata(file);
134 
135 	f->fmt.pix = priv->vdev.fmt;
136 
137 	return 0;
138 }
139 
140 static const struct imx_media_pixfmt *
141 __capture_try_fmt(struct v4l2_pix_format *pixfmt, struct v4l2_rect *compose)
142 {
143 	struct v4l2_mbus_framefmt fmt_src;
144 	const struct imx_media_pixfmt *cc;
145 
146 	/*
147 	 * Find the pixel format, default to the first supported format if not
148 	 * found.
149 	 */
150 	cc = imx_media_find_pixel_format(pixfmt->pixelformat, PIXFMT_SEL_ANY);
151 	if (!cc) {
152 		imx_media_enum_pixel_formats(&pixfmt->pixelformat, 0,
153 					     PIXFMT_SEL_ANY, 0);
154 		cc = imx_media_find_pixel_format(pixfmt->pixelformat,
155 						 PIXFMT_SEL_ANY);
156 	}
157 
158 	/* Allow IDMAC interweave but enforce field order from source. */
159 	if (V4L2_FIELD_IS_INTERLACED(pixfmt->field)) {
160 		switch (pixfmt->field) {
161 		case V4L2_FIELD_SEQ_TB:
162 			pixfmt->field = V4L2_FIELD_INTERLACED_TB;
163 			break;
164 		case V4L2_FIELD_SEQ_BT:
165 			pixfmt->field = V4L2_FIELD_INTERLACED_BT;
166 			break;
167 		default:
168 			break;
169 		}
170 	}
171 
172 	v4l2_fill_mbus_format(&fmt_src, pixfmt, 0);
173 	imx_media_mbus_fmt_to_pix_fmt(pixfmt, &fmt_src, cc);
174 
175 	if (compose) {
176 		compose->width = fmt_src.width;
177 		compose->height = fmt_src.height;
178 	}
179 
180 	return cc;
181 }
182 
183 static int capture_try_fmt_vid_cap(struct file *file, void *fh,
184 				   struct v4l2_format *f)
185 {
186 	__capture_try_fmt(&f->fmt.pix, NULL);
187 	return 0;
188 }
189 
190 static int capture_s_fmt_vid_cap(struct file *file, void *fh,
191 				 struct v4l2_format *f)
192 {
193 	struct capture_priv *priv = video_drvdata(file);
194 	const struct imx_media_pixfmt *cc;
195 
196 	if (vb2_is_busy(&priv->q)) {
197 		dev_err(priv->dev, "%s queue busy\n", __func__);
198 		return -EBUSY;
199 	}
200 
201 	cc = __capture_try_fmt(&f->fmt.pix, &priv->vdev.compose);
202 
203 	priv->vdev.cc = cc;
204 	priv->vdev.fmt = f->fmt.pix;
205 
206 	return 0;
207 }
208 
209 static int capture_g_selection(struct file *file, void *fh,
210 			       struct v4l2_selection *s)
211 {
212 	struct capture_priv *priv = video_drvdata(file);
213 
214 	switch (s->target) {
215 	case V4L2_SEL_TGT_COMPOSE:
216 	case V4L2_SEL_TGT_COMPOSE_DEFAULT:
217 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
218 		/* The compose rectangle is fixed to the source format. */
219 		s->r = priv->vdev.compose;
220 		break;
221 	case V4L2_SEL_TGT_COMPOSE_PADDED:
222 		/*
223 		 * The hardware writes with a configurable but fixed DMA burst
224 		 * size. If the source format width is not burst size aligned,
225 		 * the written frame contains padding to the right.
226 		 */
227 		s->r.left = 0;
228 		s->r.top = 0;
229 		s->r.width = priv->vdev.fmt.width;
230 		s->r.height = priv->vdev.fmt.height;
231 		break;
232 	default:
233 		return -EINVAL;
234 	}
235 
236 	return 0;
237 }
238 
239 static int capture_subscribe_event(struct v4l2_fh *fh,
240 				   const struct v4l2_event_subscription *sub)
241 {
242 	switch (sub->type) {
243 	case V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR:
244 		return v4l2_event_subscribe(fh, sub, 0, NULL);
245 	default:
246 		return -EINVAL;
247 	}
248 }
249 
250 static const struct v4l2_ioctl_ops capture_ioctl_ops = {
251 	.vidioc_querycap		= capture_querycap,
252 
253 	.vidioc_enum_fmt_vid_cap	= capture_enum_fmt_vid_cap,
254 	.vidioc_enum_framesizes		= capture_enum_framesizes,
255 
256 	.vidioc_g_fmt_vid_cap		= capture_g_fmt_vid_cap,
257 	.vidioc_try_fmt_vid_cap		= capture_try_fmt_vid_cap,
258 	.vidioc_s_fmt_vid_cap		= capture_s_fmt_vid_cap,
259 
260 	.vidioc_g_selection		= capture_g_selection,
261 
262 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
263 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
264 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
265 	.vidioc_querybuf		= vb2_ioctl_querybuf,
266 	.vidioc_qbuf			= vb2_ioctl_qbuf,
267 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
268 	.vidioc_expbuf			= vb2_ioctl_expbuf,
269 	.vidioc_streamon		= vb2_ioctl_streamon,
270 	.vidioc_streamoff		= vb2_ioctl_streamoff,
271 
272 	.vidioc_subscribe_event		= capture_subscribe_event,
273 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
274 };
275 
276 /* -----------------------------------------------------------------------------
277  * Legacy Video IOCTLs
278  */
279 
280 static int capture_legacy_enum_framesizes(struct file *file, void *fh,
281 					  struct v4l2_frmsizeenum *fsize)
282 {
283 	struct capture_priv *priv = video_drvdata(file);
284 	const struct imx_media_pixfmt *cc;
285 	struct v4l2_subdev_frame_size_enum fse = {
286 		.index = fsize->index,
287 		.pad = priv->src_sd_pad,
288 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
289 	};
290 	int ret;
291 
292 	cc = imx_media_find_pixel_format(fsize->pixel_format, PIXFMT_SEL_ANY);
293 	if (!cc)
294 		return -EINVAL;
295 
296 	fse.code = cc->codes ? cc->codes[0] : 0;
297 
298 	ret = v4l2_subdev_call(priv->src_sd, pad, enum_frame_size, NULL, &fse);
299 	if (ret)
300 		return ret;
301 
302 	if (fse.min_width == fse.max_width &&
303 	    fse.min_height == fse.max_height) {
304 		fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
305 		fsize->discrete.width = fse.min_width;
306 		fsize->discrete.height = fse.min_height;
307 	} else {
308 		fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
309 		fsize->stepwise.min_width = fse.min_width;
310 		fsize->stepwise.max_width = fse.max_width;
311 		fsize->stepwise.min_height = fse.min_height;
312 		fsize->stepwise.max_height = fse.max_height;
313 		fsize->stepwise.step_width = 1;
314 		fsize->stepwise.step_height = 1;
315 	}
316 
317 	return 0;
318 }
319 
320 static int capture_legacy_enum_frameintervals(struct file *file, void *fh,
321 					      struct v4l2_frmivalenum *fival)
322 {
323 	struct capture_priv *priv = video_drvdata(file);
324 	const struct imx_media_pixfmt *cc;
325 	struct v4l2_subdev_frame_interval_enum fie = {
326 		.index = fival->index,
327 		.pad = priv->src_sd_pad,
328 		.width = fival->width,
329 		.height = fival->height,
330 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
331 	};
332 	int ret;
333 
334 	cc = imx_media_find_pixel_format(fival->pixel_format, PIXFMT_SEL_ANY);
335 	if (!cc)
336 		return -EINVAL;
337 
338 	fie.code = cc->codes ? cc->codes[0] : 0;
339 
340 	ret = v4l2_subdev_call(priv->src_sd, pad, enum_frame_interval,
341 			       NULL, &fie);
342 	if (ret)
343 		return ret;
344 
345 	fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
346 	fival->discrete = fie.interval;
347 
348 	return 0;
349 }
350 
351 static int capture_legacy_enum_fmt_vid_cap(struct file *file, void *fh,
352 					   struct v4l2_fmtdesc *f)
353 {
354 	struct capture_priv *priv = video_drvdata(file);
355 	const struct imx_media_pixfmt *cc_src;
356 	struct v4l2_subdev_format fmt_src = {
357 		.pad = priv->src_sd_pad,
358 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
359 	};
360 	u32 fourcc;
361 	int ret;
362 
363 	ret = v4l2_subdev_call(priv->src_sd, pad, get_fmt, NULL, &fmt_src);
364 	if (ret) {
365 		dev_err(priv->dev, "failed to get src_sd format\n");
366 		return ret;
367 	}
368 
369 	cc_src = imx_media_find_ipu_format(fmt_src.format.code,
370 					   PIXFMT_SEL_YUV_RGB);
371 	if (cc_src) {
372 		enum imx_pixfmt_sel fmt_sel =
373 			(cc_src->cs == IPUV3_COLORSPACE_YUV) ?
374 			PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
375 
376 		ret = imx_media_enum_pixel_formats(&fourcc, f->index, fmt_sel,
377 						   0);
378 		if (ret)
379 			return ret;
380 	} else {
381 		cc_src = imx_media_find_mbus_format(fmt_src.format.code,
382 						    PIXFMT_SEL_ANY);
383 		if (WARN_ON(!cc_src))
384 			return -EINVAL;
385 
386 		if (f->index != 0)
387 			return -EINVAL;
388 		fourcc = cc_src->fourcc;
389 	}
390 
391 	f->pixelformat = fourcc;
392 
393 	return 0;
394 }
395 
396 static const struct imx_media_pixfmt *
397 __capture_legacy_try_fmt(struct capture_priv *priv,
398 			 struct v4l2_subdev_format *fmt_src,
399 			 struct v4l2_pix_format *pixfmt)
400 {
401 	const struct imx_media_pixfmt *cc;
402 
403 	cc = capture_find_format(fmt_src->format.code, pixfmt->pixelformat);
404 	if (WARN_ON(!cc))
405 		return NULL;
406 
407 	/* allow IDMAC interweave but enforce field order from source */
408 	if (V4L2_FIELD_IS_INTERLACED(pixfmt->field)) {
409 		switch (fmt_src->format.field) {
410 		case V4L2_FIELD_SEQ_TB:
411 			fmt_src->format.field = V4L2_FIELD_INTERLACED_TB;
412 			break;
413 		case V4L2_FIELD_SEQ_BT:
414 			fmt_src->format.field = V4L2_FIELD_INTERLACED_BT;
415 			break;
416 		default:
417 			break;
418 		}
419 	}
420 
421 	imx_media_mbus_fmt_to_pix_fmt(pixfmt, &fmt_src->format, cc);
422 
423 	return cc;
424 }
425 
426 static int capture_legacy_try_fmt_vid_cap(struct file *file, void *fh,
427 					  struct v4l2_format *f)
428 {
429 	struct capture_priv *priv = video_drvdata(file);
430 	struct v4l2_subdev_format fmt_src = {
431 		.pad = priv->src_sd_pad,
432 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
433 	};
434 	int ret;
435 
436 	ret = v4l2_subdev_call(priv->src_sd, pad, get_fmt, NULL, &fmt_src);
437 	if (ret)
438 		return ret;
439 
440 	if (!__capture_legacy_try_fmt(priv, &fmt_src, &f->fmt.pix))
441 		return -EINVAL;
442 
443 	return 0;
444 }
445 
446 static int capture_legacy_s_fmt_vid_cap(struct file *file, void *fh,
447 					struct v4l2_format *f)
448 {
449 	struct capture_priv *priv = video_drvdata(file);
450 	struct v4l2_subdev_format fmt_src = {
451 		.pad = priv->src_sd_pad,
452 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
453 	};
454 	const struct imx_media_pixfmt *cc;
455 	int ret;
456 
457 	if (vb2_is_busy(&priv->q)) {
458 		dev_err(priv->dev, "%s queue busy\n", __func__);
459 		return -EBUSY;
460 	}
461 
462 	ret = v4l2_subdev_call(priv->src_sd, pad, get_fmt, NULL, &fmt_src);
463 	if (ret)
464 		return ret;
465 
466 	cc = __capture_legacy_try_fmt(priv, &fmt_src, &f->fmt.pix);
467 	if (!cc)
468 		return -EINVAL;
469 
470 	priv->vdev.cc = cc;
471 	priv->vdev.fmt = f->fmt.pix;
472 	priv->vdev.compose.width = fmt_src.format.width;
473 	priv->vdev.compose.height = fmt_src.format.height;
474 
475 	return 0;
476 }
477 
478 static int capture_legacy_querystd(struct file *file, void *fh,
479 				   v4l2_std_id *std)
480 {
481 	struct capture_priv *priv = video_drvdata(file);
482 
483 	return v4l2_subdev_call(priv->src_sd, video, querystd, std);
484 }
485 
486 static int capture_legacy_g_std(struct file *file, void *fh, v4l2_std_id *std)
487 {
488 	struct capture_priv *priv = video_drvdata(file);
489 
490 	return v4l2_subdev_call(priv->src_sd, video, g_std, std);
491 }
492 
493 static int capture_legacy_s_std(struct file *file, void *fh, v4l2_std_id std)
494 {
495 	struct capture_priv *priv = video_drvdata(file);
496 
497 	if (vb2_is_busy(&priv->q))
498 		return -EBUSY;
499 
500 	return v4l2_subdev_call(priv->src_sd, video, s_std, std);
501 }
502 
503 static int capture_legacy_g_parm(struct file *file, void *fh,
504 				 struct v4l2_streamparm *a)
505 {
506 	struct capture_priv *priv = video_drvdata(file);
507 	struct v4l2_subdev_frame_interval fi = {
508 		.pad = priv->src_sd_pad,
509 	};
510 	int ret;
511 
512 	if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
513 		return -EINVAL;
514 
515 	ret = v4l2_subdev_call(priv->src_sd, video, g_frame_interval, &fi);
516 	if (ret < 0)
517 		return ret;
518 
519 	a->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
520 	a->parm.capture.timeperframe = fi.interval;
521 
522 	return 0;
523 }
524 
525 static int capture_legacy_s_parm(struct file *file, void *fh,
526 				 struct v4l2_streamparm *a)
527 {
528 	struct capture_priv *priv = video_drvdata(file);
529 	struct v4l2_subdev_frame_interval fi = {
530 		.pad = priv->src_sd_pad,
531 	};
532 	int ret;
533 
534 	if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
535 		return -EINVAL;
536 
537 	fi.interval = a->parm.capture.timeperframe;
538 	ret = v4l2_subdev_call(priv->src_sd, video, s_frame_interval, &fi);
539 	if (ret < 0)
540 		return ret;
541 
542 	a->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
543 	a->parm.capture.timeperframe = fi.interval;
544 
545 	return 0;
546 }
547 
548 static int capture_legacy_subscribe_event(struct v4l2_fh *fh,
549 					  const struct v4l2_event_subscription *sub)
550 {
551 	switch (sub->type) {
552 	case V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR:
553 		return v4l2_event_subscribe(fh, sub, 0, NULL);
554 	case V4L2_EVENT_SOURCE_CHANGE:
555 		return v4l2_src_change_event_subscribe(fh, sub);
556 	case V4L2_EVENT_CTRL:
557 		return v4l2_ctrl_subscribe_event(fh, sub);
558 	default:
559 		return -EINVAL;
560 	}
561 }
562 
563 static const struct v4l2_ioctl_ops capture_legacy_ioctl_ops = {
564 	.vidioc_querycap		= capture_querycap,
565 
566 	.vidioc_enum_framesizes		= capture_legacy_enum_framesizes,
567 	.vidioc_enum_frameintervals	= capture_legacy_enum_frameintervals,
568 
569 	.vidioc_enum_fmt_vid_cap	= capture_legacy_enum_fmt_vid_cap,
570 	.vidioc_g_fmt_vid_cap		= capture_g_fmt_vid_cap,
571 	.vidioc_try_fmt_vid_cap		= capture_legacy_try_fmt_vid_cap,
572 	.vidioc_s_fmt_vid_cap		= capture_legacy_s_fmt_vid_cap,
573 
574 	.vidioc_querystd		= capture_legacy_querystd,
575 	.vidioc_g_std			= capture_legacy_g_std,
576 	.vidioc_s_std			= capture_legacy_s_std,
577 
578 	.vidioc_g_selection		= capture_g_selection,
579 
580 	.vidioc_g_parm			= capture_legacy_g_parm,
581 	.vidioc_s_parm			= capture_legacy_s_parm,
582 
583 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
584 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
585 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
586 	.vidioc_querybuf		= vb2_ioctl_querybuf,
587 	.vidioc_qbuf			= vb2_ioctl_qbuf,
588 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
589 	.vidioc_expbuf			= vb2_ioctl_expbuf,
590 	.vidioc_streamon		= vb2_ioctl_streamon,
591 	.vidioc_streamoff		= vb2_ioctl_streamoff,
592 
593 	.vidioc_subscribe_event		= capture_legacy_subscribe_event,
594 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
595 };
596 
597 /* -----------------------------------------------------------------------------
598  * Queue Operations
599  */
600 
601 static int capture_queue_setup(struct vb2_queue *vq,
602 			       unsigned int *nbuffers,
603 			       unsigned int *nplanes,
604 			       unsigned int sizes[],
605 			       struct device *alloc_devs[])
606 {
607 	struct capture_priv *priv = vb2_get_drv_priv(vq);
608 	struct v4l2_pix_format *pix = &priv->vdev.fmt;
609 	unsigned int count = *nbuffers;
610 
611 	if (vq->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
612 		return -EINVAL;
613 
614 	if (*nplanes) {
615 		if (*nplanes != 1 || sizes[0] < pix->sizeimage)
616 			return -EINVAL;
617 		count += vq->num_buffers;
618 	}
619 
620 	count = min_t(__u32, VID_MEM_LIMIT / pix->sizeimage, count);
621 
622 	if (*nplanes)
623 		*nbuffers = (count < vq->num_buffers) ? 0 :
624 			count - vq->num_buffers;
625 	else
626 		*nbuffers = count;
627 
628 	*nplanes = 1;
629 	sizes[0] = pix->sizeimage;
630 
631 	return 0;
632 }
633 
634 static int capture_buf_init(struct vb2_buffer *vb)
635 {
636 	struct imx_media_buffer *buf = to_imx_media_vb(vb);
637 
638 	INIT_LIST_HEAD(&buf->list);
639 
640 	return 0;
641 }
642 
643 static int capture_buf_prepare(struct vb2_buffer *vb)
644 {
645 	struct vb2_queue *vq = vb->vb2_queue;
646 	struct capture_priv *priv = vb2_get_drv_priv(vq);
647 	struct v4l2_pix_format *pix = &priv->vdev.fmt;
648 
649 	if (vb2_plane_size(vb, 0) < pix->sizeimage) {
650 		dev_err(priv->dev,
651 			"data will not fit into plane (%lu < %lu)\n",
652 			vb2_plane_size(vb, 0), (long)pix->sizeimage);
653 		return -EINVAL;
654 	}
655 
656 	vb2_set_plane_payload(vb, 0, pix->sizeimage);
657 
658 	return 0;
659 }
660 
661 static void capture_buf_queue(struct vb2_buffer *vb)
662 {
663 	struct capture_priv *priv = vb2_get_drv_priv(vb->vb2_queue);
664 	struct imx_media_buffer *buf = to_imx_media_vb(vb);
665 	unsigned long flags;
666 
667 	spin_lock_irqsave(&priv->q_lock, flags);
668 
669 	list_add_tail(&buf->list, &priv->ready_q);
670 
671 	spin_unlock_irqrestore(&priv->q_lock, flags);
672 }
673 
674 static int capture_validate_fmt(struct capture_priv *priv)
675 {
676 	struct v4l2_subdev_format fmt_src = {
677 		.pad = priv->src_sd_pad,
678 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
679 	};
680 	const struct imx_media_pixfmt *cc;
681 	int ret;
682 
683 	/* Retrieve the media bus format on the source subdev. */
684 	ret = v4l2_subdev_call(priv->src_sd, pad, get_fmt, NULL, &fmt_src);
685 	if (ret)
686 		return ret;
687 
688 	/*
689 	 * Verify that the media bus size matches the size set on the video
690 	 * node. It is sufficient to check the compose rectangle size without
691 	 * checking the rounded size from vdev.fmt, as the rounded size is
692 	 * derived directly from the compose rectangle size, and will thus
693 	 * always match if the compose rectangle matches.
694 	 */
695 	if (priv->vdev.compose.width != fmt_src.format.width ||
696 	    priv->vdev.compose.height != fmt_src.format.height)
697 		return -EPIPE;
698 
699 	/*
700 	 * Verify that the media bus code is compatible with the pixel format
701 	 * set on the video node.
702 	 */
703 	cc = capture_find_format(fmt_src.format.code, 0);
704 	if (!cc || priv->vdev.cc->cs != cc->cs)
705 		return -EPIPE;
706 
707 	return 0;
708 }
709 
710 static int capture_start_streaming(struct vb2_queue *vq, unsigned int count)
711 {
712 	struct capture_priv *priv = vb2_get_drv_priv(vq);
713 	struct imx_media_buffer *buf, *tmp;
714 	unsigned long flags;
715 	int ret;
716 
717 	ret = capture_validate_fmt(priv);
718 	if (ret) {
719 		dev_err(priv->dev, "capture format not valid\n");
720 		goto return_bufs;
721 	}
722 
723 	ret = imx_media_pipeline_set_stream(priv->md, &priv->src_sd->entity,
724 					    true);
725 	if (ret) {
726 		dev_err(priv->dev, "pipeline start failed with %d\n", ret);
727 		goto return_bufs;
728 	}
729 
730 	return 0;
731 
732 return_bufs:
733 	spin_lock_irqsave(&priv->q_lock, flags);
734 	list_for_each_entry_safe(buf, tmp, &priv->ready_q, list) {
735 		list_del(&buf->list);
736 		vb2_buffer_done(&buf->vbuf.vb2_buf, VB2_BUF_STATE_QUEUED);
737 	}
738 	spin_unlock_irqrestore(&priv->q_lock, flags);
739 	return ret;
740 }
741 
742 static void capture_stop_streaming(struct vb2_queue *vq)
743 {
744 	struct capture_priv *priv = vb2_get_drv_priv(vq);
745 	struct imx_media_buffer *frame;
746 	struct imx_media_buffer *tmp;
747 	unsigned long flags;
748 	int ret;
749 
750 	ret = imx_media_pipeline_set_stream(priv->md, &priv->src_sd->entity,
751 					    false);
752 	if (ret)
753 		dev_warn(priv->dev, "pipeline stop failed with %d\n", ret);
754 
755 	/* release all active buffers */
756 	spin_lock_irqsave(&priv->q_lock, flags);
757 	list_for_each_entry_safe(frame, tmp, &priv->ready_q, list) {
758 		list_del(&frame->list);
759 		vb2_buffer_done(&frame->vbuf.vb2_buf, VB2_BUF_STATE_ERROR);
760 	}
761 	spin_unlock_irqrestore(&priv->q_lock, flags);
762 }
763 
764 static const struct vb2_ops capture_qops = {
765 	.queue_setup	 = capture_queue_setup,
766 	.buf_init        = capture_buf_init,
767 	.buf_prepare	 = capture_buf_prepare,
768 	.buf_queue	 = capture_buf_queue,
769 	.wait_prepare	 = vb2_ops_wait_prepare,
770 	.wait_finish	 = vb2_ops_wait_finish,
771 	.start_streaming = capture_start_streaming,
772 	.stop_streaming  = capture_stop_streaming,
773 };
774 
775 /* -----------------------------------------------------------------------------
776  * File Operations
777  */
778 
779 static int capture_open(struct file *file)
780 {
781 	struct capture_priv *priv = video_drvdata(file);
782 	struct video_device *vfd = priv->vdev.vfd;
783 	int ret;
784 
785 	if (mutex_lock_interruptible(&priv->mutex))
786 		return -ERESTARTSYS;
787 
788 	ret = v4l2_fh_open(file);
789 	if (ret) {
790 		dev_err(priv->dev, "v4l2_fh_open failed\n");
791 		goto out;
792 	}
793 
794 	ret = v4l2_pipeline_pm_get(&vfd->entity);
795 	if (ret)
796 		v4l2_fh_release(file);
797 
798 out:
799 	mutex_unlock(&priv->mutex);
800 	return ret;
801 }
802 
803 static int capture_release(struct file *file)
804 {
805 	struct capture_priv *priv = video_drvdata(file);
806 	struct video_device *vfd = priv->vdev.vfd;
807 	struct vb2_queue *vq = &priv->q;
808 
809 	mutex_lock(&priv->mutex);
810 
811 	if (file->private_data == vq->owner) {
812 		vb2_queue_release(vq);
813 		vq->owner = NULL;
814 	}
815 
816 	v4l2_pipeline_pm_put(&vfd->entity);
817 
818 	v4l2_fh_release(file);
819 	mutex_unlock(&priv->mutex);
820 	return 0;
821 }
822 
823 static const struct v4l2_file_operations capture_fops = {
824 	.owner		= THIS_MODULE,
825 	.open		= capture_open,
826 	.release	= capture_release,
827 	.poll		= vb2_fop_poll,
828 	.unlocked_ioctl	= video_ioctl2,
829 	.mmap		= vb2_fop_mmap,
830 };
831 
832 /* -----------------------------------------------------------------------------
833  * Public API
834  */
835 
836 struct imx_media_buffer *
837 imx_media_capture_device_next_buf(struct imx_media_video_dev *vdev)
838 {
839 	struct capture_priv *priv = to_capture_priv(vdev);
840 	struct imx_media_buffer *buf = NULL;
841 	unsigned long flags;
842 
843 	spin_lock_irqsave(&priv->q_lock, flags);
844 
845 	/* get next queued buffer */
846 	if (!list_empty(&priv->ready_q)) {
847 		buf = list_entry(priv->ready_q.next, struct imx_media_buffer,
848 				 list);
849 		list_del(&buf->list);
850 	}
851 
852 	spin_unlock_irqrestore(&priv->q_lock, flags);
853 
854 	return buf;
855 }
856 EXPORT_SYMBOL_GPL(imx_media_capture_device_next_buf);
857 
858 void imx_media_capture_device_error(struct imx_media_video_dev *vdev)
859 {
860 	struct capture_priv *priv = to_capture_priv(vdev);
861 	struct vb2_queue *vq = &priv->q;
862 	unsigned long flags;
863 
864 	if (!vb2_is_streaming(vq))
865 		return;
866 
867 	spin_lock_irqsave(&priv->q_lock, flags);
868 	vb2_queue_error(vq);
869 	spin_unlock_irqrestore(&priv->q_lock, flags);
870 }
871 EXPORT_SYMBOL_GPL(imx_media_capture_device_error);
872 
873 static int capture_init_format(struct capture_priv *priv)
874 {
875 	struct v4l2_subdev_format fmt_src = {
876 		.pad = priv->src_sd_pad,
877 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
878 	};
879 	struct imx_media_video_dev *vdev = &priv->vdev;
880 	int ret;
881 
882 	if (priv->legacy_api) {
883 		ret = v4l2_subdev_call(priv->src_sd, pad, get_fmt, NULL,
884 				       &fmt_src);
885 		if (ret) {
886 			dev_err(priv->dev, "failed to get source format\n");
887 			return ret;
888 		}
889 	} else {
890 		fmt_src.format.code = MEDIA_BUS_FMT_UYVY8_2X8;
891 		fmt_src.format.width = IMX_MEDIA_DEF_PIX_WIDTH;
892 		fmt_src.format.height = IMX_MEDIA_DEF_PIX_HEIGHT;
893 	}
894 
895 	imx_media_mbus_fmt_to_pix_fmt(&vdev->fmt, &fmt_src.format, NULL);
896 	vdev->compose.width = fmt_src.format.width;
897 	vdev->compose.height = fmt_src.format.height;
898 
899 	vdev->cc = imx_media_find_pixel_format(vdev->fmt.pixelformat,
900 					       PIXFMT_SEL_ANY);
901 
902 	return 0;
903 }
904 
905 int imx_media_capture_device_register(struct imx_media_video_dev *vdev,
906 				      u32 link_flags)
907 {
908 	struct capture_priv *priv = to_capture_priv(vdev);
909 	struct v4l2_subdev *sd = priv->src_sd;
910 	struct v4l2_device *v4l2_dev = sd->v4l2_dev;
911 	struct video_device *vfd = vdev->vfd;
912 	int ret;
913 
914 	/* get media device */
915 	priv->md = container_of(v4l2_dev->mdev, struct imx_media_dev, md);
916 
917 	vfd->v4l2_dev = v4l2_dev;
918 
919 	/* Initialize the default format and compose rectangle. */
920 	ret = capture_init_format(priv);
921 	if (ret < 0)
922 		return ret;
923 
924 	/* Register the video device. */
925 	ret = video_register_device(vfd, VFL_TYPE_VIDEO, -1);
926 	if (ret) {
927 		dev_err(priv->dev, "Failed to register video device\n");
928 		return ret;
929 	}
930 
931 	dev_info(priv->dev, "Registered %s as /dev/%s\n", vfd->name,
932 		 video_device_node_name(vfd));
933 
934 	/* Create the link from the src_sd devnode pad to device node. */
935 	if (link_flags & MEDIA_LNK_FL_IMMUTABLE)
936 		link_flags |= MEDIA_LNK_FL_ENABLED;
937 	ret = media_create_pad_link(&sd->entity, priv->src_sd_pad,
938 				    &vfd->entity, 0, link_flags);
939 	if (ret) {
940 		dev_err(priv->dev, "failed to create link to device node\n");
941 		video_unregister_device(vfd);
942 		return ret;
943 	}
944 
945 	/* Add vdev to the video devices list. */
946 	imx_media_add_video_device(priv->md, vdev);
947 
948 	return 0;
949 }
950 EXPORT_SYMBOL_GPL(imx_media_capture_device_register);
951 
952 void imx_media_capture_device_unregister(struct imx_media_video_dev *vdev)
953 {
954 	struct capture_priv *priv = to_capture_priv(vdev);
955 	struct video_device *vfd = priv->vdev.vfd;
956 
957 	media_entity_cleanup(&vfd->entity);
958 	video_unregister_device(vfd);
959 }
960 EXPORT_SYMBOL_GPL(imx_media_capture_device_unregister);
961 
962 struct imx_media_video_dev *
963 imx_media_capture_device_init(struct device *dev, struct v4l2_subdev *src_sd,
964 			      int pad, bool legacy_api)
965 {
966 	struct capture_priv *priv;
967 	struct video_device *vfd;
968 	struct vb2_queue *vq;
969 	int ret;
970 
971 	priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
972 	if (!priv)
973 		return ERR_PTR(-ENOMEM);
974 
975 	priv->src_sd = src_sd;
976 	priv->src_sd_pad = pad;
977 	priv->dev = dev;
978 	priv->legacy_api = legacy_api;
979 
980 	mutex_init(&priv->mutex);
981 	INIT_LIST_HEAD(&priv->ready_q);
982 	spin_lock_init(&priv->q_lock);
983 
984 	/* Allocate and initialize the video device. */
985 	vfd = video_device_alloc();
986 	if (!vfd)
987 		return ERR_PTR(-ENOMEM);
988 
989 	vfd->fops = &capture_fops;
990 	vfd->ioctl_ops = legacy_api ? &capture_legacy_ioctl_ops
991 		       : &capture_ioctl_ops;
992 	vfd->minor = -1;
993 	vfd->release = video_device_release;
994 	vfd->vfl_dir = VFL_DIR_RX;
995 	vfd->tvnorms = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM;
996 	vfd->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING
997 			 | (!legacy_api ? V4L2_CAP_IO_MC : 0);
998 	vfd->lock = &priv->mutex;
999 	vfd->queue = &priv->q;
1000 
1001 	snprintf(vfd->name, sizeof(vfd->name), "%s capture", src_sd->name);
1002 
1003 	video_set_drvdata(vfd, priv);
1004 	priv->vdev.vfd = vfd;
1005 	INIT_LIST_HEAD(&priv->vdev.list);
1006 
1007 	/* Initialize the video device pad. */
1008 	priv->vdev_pad.flags = MEDIA_PAD_FL_SINK;
1009 	ret = media_entity_pads_init(&vfd->entity, 1, &priv->vdev_pad);
1010 	if (ret) {
1011 		video_device_release(vfd);
1012 		return ERR_PTR(ret);
1013 	}
1014 
1015 	/* Initialize the vb2 queue. */
1016 	vq = &priv->q;
1017 	vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1018 	vq->io_modes = VB2_MMAP | VB2_DMABUF;
1019 	vq->drv_priv = priv;
1020 	vq->buf_struct_size = sizeof(struct imx_media_buffer);
1021 	vq->ops = &capture_qops;
1022 	vq->mem_ops = &vb2_dma_contig_memops;
1023 	vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1024 	vq->lock = &priv->mutex;
1025 	vq->min_buffers_needed = 2;
1026 	vq->dev = priv->dev;
1027 
1028 	ret = vb2_queue_init(vq);
1029 	if (ret) {
1030 		dev_err(priv->dev, "vb2_queue_init failed\n");
1031 		video_device_release(vfd);
1032 		return ERR_PTR(ret);
1033 	}
1034 
1035 	if (legacy_api) {
1036 		/* Initialize the control handler. */
1037 		v4l2_ctrl_handler_init(&priv->ctrl_hdlr, 0);
1038 		vfd->ctrl_handler = &priv->ctrl_hdlr;
1039 	}
1040 
1041 	return &priv->vdev;
1042 }
1043 EXPORT_SYMBOL_GPL(imx_media_capture_device_init);
1044 
1045 void imx_media_capture_device_remove(struct imx_media_video_dev *vdev)
1046 {
1047 	struct capture_priv *priv = to_capture_priv(vdev);
1048 
1049 	v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
1050 }
1051 EXPORT_SYMBOL_GPL(imx_media_capture_device_remove);
1052 
1053 MODULE_DESCRIPTION("i.MX5/6 v4l2 video capture interface driver");
1054 MODULE_AUTHOR("Steve Longerbeam <steve_longerbeam@mentor.com>");
1055 MODULE_LICENSE("GPL");
1056