1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * STK1160 driver
4  *
5  * Copyright (C) 2012 Ezequiel Garcia
6  * <elezegarcia--a.t--gmail.com>
7  *
8  * Based on Easycap driver by R.M. Thomas
9  *	Copyright (C) 2010 R.M. Thomas
10  *	<rmthomas--a.t--sciolus.org>
11  */
12 
13 #include <linux/module.h>
14 #include <linux/usb.h>
15 #include <linux/mm.h>
16 #include <linux/slab.h>
17 
18 #include <linux/videodev2.h>
19 #include <media/v4l2-device.h>
20 #include <media/v4l2-common.h>
21 #include <media/v4l2-ioctl.h>
22 #include <media/v4l2-fh.h>
23 #include <media/v4l2-event.h>
24 #include <media/videobuf2-vmalloc.h>
25 
26 #include <media/i2c/saa7115.h>
27 
28 #include "stk1160.h"
29 #include "stk1160-reg.h"
30 
31 static bool keep_buffers;
32 module_param(keep_buffers, bool, 0644);
33 MODULE_PARM_DESC(keep_buffers, "don't release buffers upon stop streaming");
34 
35 enum stk1160_decimate_mode {
36 	STK1160_DECIMATE_MORE_THAN_HALF,
37 	STK1160_DECIMATE_LESS_THAN_HALF,
38 };
39 
40 struct stk1160_decimate_ctrl {
41 	bool col_en, row_en;
42 	enum stk1160_decimate_mode col_mode, row_mode;
43 	unsigned int col_n, row_n;
44 };
45 
46 /* supported video standards */
47 static struct stk1160_fmt format[] = {
48 	{
49 		.name     = "16 bpp YUY2, 4:2:2, packed",
50 		.fourcc   = V4L2_PIX_FMT_UYVY,
51 		.depth    = 16,
52 	}
53 };
54 
55 /*
56  * Helper to find the next divisor that results in modulo being zero.
57  * This is required to guarantee valid decimation unit counts.
58  */
59 static unsigned int
60 div_round_integer(unsigned int x, unsigned int y)
61 {
62 	for (;; y++) {
63 		if (x % y == 0)
64 			return x / y;
65 	}
66 }
67 
68 static void stk1160_set_std(struct stk1160 *dev)
69 {
70 	int i;
71 
72 	static struct regval std525[] = {
73 
74 		/* 720x480 */
75 
76 		/* Frame start */
77 		{STK116_CFSPO_STX_L, 0x0000},
78 		{STK116_CFSPO_STX_H, 0x0000},
79 		{STK116_CFSPO_STY_L, 0x0003},
80 		{STK116_CFSPO_STY_H, 0x0000},
81 
82 		/* Frame end */
83 		{STK116_CFEPO_ENX_L, 0x05a0},
84 		{STK116_CFEPO_ENX_H, 0x0005},
85 		{STK116_CFEPO_ENY_L, 0x00f3},
86 		{STK116_CFEPO_ENY_H, 0x0000},
87 
88 		{0xffff, 0xffff}
89 	};
90 
91 	static struct regval std625[] = {
92 
93 		/* 720x576 */
94 
95 		/* TODO: Each line of frame has some junk at the end */
96 		/* Frame start */
97 		{STK116_CFSPO,   0x0000},
98 		{STK116_CFSPO+1, 0x0000},
99 		{STK116_CFSPO+2, 0x0001},
100 		{STK116_CFSPO+3, 0x0000},
101 
102 		/* Frame end */
103 		{STK116_CFEPO,   0x05a0},
104 		{STK116_CFEPO+1, 0x0005},
105 		{STK116_CFEPO+2, 0x0121},
106 		{STK116_CFEPO+3, 0x0001},
107 
108 		{0xffff, 0xffff}
109 	};
110 
111 	if (dev->norm & V4L2_STD_525_60) {
112 		stk1160_dbg("registers to NTSC like standard\n");
113 		for (i = 0; std525[i].reg != 0xffff; i++)
114 			stk1160_write_reg(dev, std525[i].reg, std525[i].val);
115 	} else {
116 		stk1160_dbg("registers to PAL like standard\n");
117 		for (i = 0; std625[i].reg != 0xffff; i++)
118 			stk1160_write_reg(dev, std625[i].reg, std625[i].val);
119 	}
120 
121 }
122 
123 static void stk1160_set_fmt(struct stk1160 *dev,
124 			    struct stk1160_decimate_ctrl *ctrl)
125 {
126 	u32 val = 0;
127 
128 	if (ctrl) {
129 		/*
130 		 * Since the format is UYVY, the device must skip or send
131 		 * a number of rows/columns multiple of four. This way, the
132 		 * colour format is preserved. The STK1160_DEC_UNIT_SIZE bit
133 		 * does exactly this.
134 		 */
135 		val |= STK1160_DEC_UNIT_SIZE;
136 		val |= ctrl->col_en ? STK1160_H_DEC_EN : 0;
137 		val |= ctrl->row_en ? STK1160_V_DEC_EN : 0;
138 		val |= ctrl->col_mode ==
139 			STK1160_DECIMATE_MORE_THAN_HALF ?
140 			STK1160_H_DEC_MODE : 0;
141 		val |= ctrl->row_mode ==
142 			STK1160_DECIMATE_MORE_THAN_HALF ?
143 			STK1160_V_DEC_MODE : 0;
144 
145 		/* Horizontal count units */
146 		stk1160_write_reg(dev, STK1160_DMCTRL_H_UNITS, ctrl->col_n);
147 		/* Vertical count units */
148 		stk1160_write_reg(dev, STK1160_DMCTRL_V_UNITS, ctrl->row_n);
149 
150 		stk1160_dbg("decimate 0x%x, column units %d, row units %d\n",
151 			    val, ctrl->col_n, ctrl->row_n);
152 	}
153 
154 	/* Decimation control */
155 	stk1160_write_reg(dev, STK1160_DMCTRL, val);
156 }
157 
158 /*
159  * Set a new alternate setting.
160  * Returns true is dev->max_pkt_size has changed, false otherwise.
161  */
162 static bool stk1160_set_alternate(struct stk1160 *dev)
163 {
164 	int i, prev_alt = dev->alt;
165 	unsigned int min_pkt_size;
166 	bool new_pkt_size;
167 
168 	/*
169 	 * If we don't set right alternate,
170 	 * then we will get a green screen with junk.
171 	 */
172 	min_pkt_size = STK1160_MIN_PKT_SIZE;
173 
174 	for (i = 0; i < dev->num_alt; i++) {
175 		/* stop when the selected alt setting offers enough bandwidth */
176 		if (dev->alt_max_pkt_size[i] >= min_pkt_size) {
177 			dev->alt = i;
178 			break;
179 		/*
180 		 * otherwise make sure that we end up with the maximum bandwidth
181 		 * because the min_pkt_size equation might be wrong...
182 		 */
183 		} else if (dev->alt_max_pkt_size[i] >
184 			   dev->alt_max_pkt_size[dev->alt])
185 			dev->alt = i;
186 	}
187 
188 	stk1160_dbg("setting alternate %d\n", dev->alt);
189 
190 	if (dev->alt != prev_alt) {
191 		stk1160_dbg("minimum isoc packet size: %u (alt=%d)\n",
192 				min_pkt_size, dev->alt);
193 		stk1160_dbg("setting alt %d with wMaxPacketSize=%u\n",
194 			       dev->alt, dev->alt_max_pkt_size[dev->alt]);
195 		usb_set_interface(dev->udev, 0, dev->alt);
196 	}
197 
198 	new_pkt_size = dev->max_pkt_size != dev->alt_max_pkt_size[dev->alt];
199 	dev->max_pkt_size = dev->alt_max_pkt_size[dev->alt];
200 
201 	return new_pkt_size;
202 }
203 
204 static int stk1160_start_streaming(struct stk1160 *dev)
205 {
206 	bool new_pkt_size;
207 	int rc = 0;
208 	int i;
209 
210 	/* Check device presence */
211 	if (!dev->udev)
212 		return -ENODEV;
213 
214 	if (mutex_lock_interruptible(&dev->v4l_lock))
215 		return -ERESTARTSYS;
216 	/*
217 	 * For some reason it is mandatory to set alternate *first*
218 	 * and only *then* initialize isoc urbs.
219 	 * Someone please explain me why ;)
220 	 */
221 	new_pkt_size = stk1160_set_alternate(dev);
222 
223 	/*
224 	 * We (re)allocate isoc urbs if:
225 	 * there is no allocated isoc urbs, OR
226 	 * a new dev->max_pkt_size is detected
227 	 */
228 	if (!dev->isoc_ctl.num_bufs || new_pkt_size) {
229 		rc = stk1160_alloc_isoc(dev);
230 		if (rc < 0)
231 			goto out_stop_hw;
232 	}
233 
234 	/* submit urbs and enables IRQ */
235 	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
236 		rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_KERNEL);
237 		if (rc) {
238 			stk1160_err("cannot submit urb[%d] (%d)\n", i, rc);
239 			goto out_uninit;
240 		}
241 	}
242 
243 	/* Start saa711x */
244 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
245 
246 	dev->sequence = 0;
247 
248 	/* Start stk1160 */
249 	stk1160_write_reg(dev, STK1160_DCTRL, 0xb3);
250 	stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
251 
252 	stk1160_dbg("streaming started\n");
253 
254 	mutex_unlock(&dev->v4l_lock);
255 
256 	return 0;
257 
258 out_uninit:
259 	stk1160_uninit_isoc(dev);
260 out_stop_hw:
261 	usb_set_interface(dev->udev, 0, 0);
262 	stk1160_clear_queue(dev);
263 
264 	mutex_unlock(&dev->v4l_lock);
265 
266 	return rc;
267 }
268 
269 /* Must be called with v4l_lock hold */
270 static void stk1160_stop_hw(struct stk1160 *dev)
271 {
272 	/* If the device is not physically present, there is nothing to do */
273 	if (!dev->udev)
274 		return;
275 
276 	/* set alternate 0 */
277 	dev->alt = 0;
278 	stk1160_dbg("setting alternate %d\n", dev->alt);
279 	usb_set_interface(dev->udev, 0, 0);
280 
281 	/* Stop stk1160 */
282 	stk1160_write_reg(dev, STK1160_DCTRL, 0x00);
283 	stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
284 
285 	/* Stop saa711x */
286 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
287 }
288 
289 static int stk1160_stop_streaming(struct stk1160 *dev)
290 {
291 	if (mutex_lock_interruptible(&dev->v4l_lock))
292 		return -ERESTARTSYS;
293 
294 	/*
295 	 * Once URBs are cancelled, the URB complete handler
296 	 * won't be running. This is required to safely release the
297 	 * current buffer (dev->isoc_ctl.buf).
298 	 */
299 	stk1160_cancel_isoc(dev);
300 
301 	/*
302 	 * It is possible to keep buffers around using a module parameter.
303 	 * This is intended to avoid memory fragmentation.
304 	 */
305 	if (!keep_buffers)
306 		stk1160_free_isoc(dev);
307 
308 	stk1160_stop_hw(dev);
309 
310 	stk1160_clear_queue(dev);
311 
312 	stk1160_dbg("streaming stopped\n");
313 
314 	mutex_unlock(&dev->v4l_lock);
315 
316 	return 0;
317 }
318 
319 static const struct v4l2_file_operations stk1160_fops = {
320 	.owner = THIS_MODULE,
321 	.open = v4l2_fh_open,
322 	.release = vb2_fop_release,
323 	.read = vb2_fop_read,
324 	.poll = vb2_fop_poll,
325 	.mmap = vb2_fop_mmap,
326 	.unlocked_ioctl = video_ioctl2,
327 };
328 
329 /*
330  * vidioc ioctls
331  */
332 static int vidioc_querycap(struct file *file,
333 		void *priv, struct v4l2_capability *cap)
334 {
335 	struct stk1160 *dev = video_drvdata(file);
336 
337 	strscpy(cap->driver, "stk1160", sizeof(cap->driver));
338 	strscpy(cap->card, "stk1160", sizeof(cap->card));
339 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
340 	return 0;
341 }
342 
343 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
344 		struct v4l2_fmtdesc *f)
345 {
346 	if (f->index != 0)
347 		return -EINVAL;
348 
349 	strscpy(f->description, format[f->index].name, sizeof(f->description));
350 	f->pixelformat = format[f->index].fourcc;
351 	return 0;
352 }
353 
354 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
355 					struct v4l2_format *f)
356 {
357 	struct stk1160 *dev = video_drvdata(file);
358 
359 	f->fmt.pix.width = dev->width;
360 	f->fmt.pix.height = dev->height;
361 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
362 	f->fmt.pix.pixelformat = dev->fmt->fourcc;
363 	f->fmt.pix.bytesperline = dev->width * 2;
364 	f->fmt.pix.sizeimage = dev->height * f->fmt.pix.bytesperline;
365 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
366 
367 	return 0;
368 }
369 
370 static int stk1160_try_fmt(struct stk1160 *dev, struct v4l2_format *f,
371 			    struct stk1160_decimate_ctrl *ctrl)
372 {
373 	unsigned int width, height;
374 	unsigned int base_width, base_height;
375 	unsigned int col_n, row_n;
376 	enum stk1160_decimate_mode col_mode, row_mode;
377 	bool col_en, row_en;
378 
379 	base_width = 720;
380 	base_height = (dev->norm & V4L2_STD_525_60) ? 480 : 576;
381 
382 	/* Minimum width and height is 5% the frame size */
383 	width = clamp_t(unsigned int, f->fmt.pix.width,
384 			base_width / 20, base_width);
385 	height = clamp_t(unsigned int, f->fmt.pix.height,
386 			base_height / 20, base_height);
387 
388 	/* Let's set default no decimation values */
389 	col_n = 0;
390 	row_n = 0;
391 	col_en = false;
392 	row_en = false;
393 	f->fmt.pix.width = base_width;
394 	f->fmt.pix.height = base_height;
395 	row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
396 	col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
397 
398 	if (width < base_width && width > base_width / 2) {
399 		/*
400 		 * The device will send count units for each
401 		 * unit skipped. This means count unit is:
402 		 *
403 		 * n = width / (frame width - width)
404 		 *
405 		 * And the width is:
406 		 *
407 		 * width = (n / n + 1) * frame width
408 		 */
409 		col_n = div_round_integer(width, base_width - width);
410 		if (col_n > 0 && col_n <= 255) {
411 			col_en = true;
412 			col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
413 			f->fmt.pix.width = (base_width * col_n) / (col_n + 1);
414 		}
415 
416 	} else if (width <= base_width / 2) {
417 
418 		/*
419 		 * The device will skip count units for each
420 		 * unit sent. This means count is:
421 		 *
422 		 * n = (frame width / width) - 1
423 		 *
424 		 * And the width is:
425 		 *
426 		 * width = frame width / (n + 1)
427 		 */
428 		col_n = div_round_integer(base_width, width) - 1;
429 		if (col_n > 0 && col_n <= 255) {
430 			col_en = true;
431 			col_mode = STK1160_DECIMATE_MORE_THAN_HALF;
432 			f->fmt.pix.width = base_width / (col_n + 1);
433 		}
434 	}
435 
436 	if (height < base_height && height > base_height / 2) {
437 		row_n = div_round_integer(height, base_height - height);
438 		if (row_n > 0 && row_n <= 255) {
439 			row_en = true;
440 			row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
441 			f->fmt.pix.height = (base_height * row_n) / (row_n + 1);
442 		}
443 
444 	} else if (height <= base_height / 2) {
445 		row_n = div_round_integer(base_height, height) - 1;
446 		if (row_n > 0 && row_n <= 255) {
447 			row_en = true;
448 			row_mode = STK1160_DECIMATE_MORE_THAN_HALF;
449 			f->fmt.pix.height = base_height / (row_n + 1);
450 		}
451 	}
452 
453 	f->fmt.pix.pixelformat = dev->fmt->fourcc;
454 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
455 	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
456 	f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
457 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
458 
459 	if (ctrl) {
460 		ctrl->col_en = col_en;
461 		ctrl->col_n = col_n;
462 		ctrl->col_mode = col_mode;
463 		ctrl->row_en = row_en;
464 		ctrl->row_n = row_n;
465 		ctrl->row_mode = row_mode;
466 	}
467 
468 	stk1160_dbg("width %d, height %d\n",
469 		    f->fmt.pix.width, f->fmt.pix.height);
470 	return 0;
471 }
472 
473 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
474 				  struct v4l2_format *f)
475 {
476 	struct stk1160 *dev = video_drvdata(file);
477 
478 	return stk1160_try_fmt(dev, f, NULL);
479 }
480 
481 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
482 					struct v4l2_format *f)
483 {
484 	struct stk1160 *dev = video_drvdata(file);
485 	struct vb2_queue *q = &dev->vb_vidq;
486 	struct stk1160_decimate_ctrl ctrl;
487 	int rc;
488 
489 	if (vb2_is_busy(q))
490 		return -EBUSY;
491 
492 	rc = stk1160_try_fmt(dev, f, &ctrl);
493 	if (rc < 0)
494 		return rc;
495 	dev->width = f->fmt.pix.width;
496 	dev->height = f->fmt.pix.height;
497 	stk1160_set_fmt(dev, &ctrl);
498 
499 	return 0;
500 }
501 
502 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
503 {
504 	struct stk1160 *dev = video_drvdata(file);
505 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, querystd, norm);
506 	return 0;
507 }
508 
509 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
510 {
511 	struct stk1160 *dev = video_drvdata(file);
512 
513 	*norm = dev->norm;
514 	return 0;
515 }
516 
517 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
518 {
519 	struct stk1160 *dev = video_drvdata(file);
520 	struct vb2_queue *q = &dev->vb_vidq;
521 
522 	if (dev->norm == norm)
523 		return 0;
524 
525 	if (vb2_is_busy(q))
526 		return -EBUSY;
527 
528 	/* Check device presence */
529 	if (!dev->udev)
530 		return -ENODEV;
531 
532 	/* We need to set this now, before we call stk1160_set_std */
533 	dev->width = 720;
534 	dev->height = (norm & V4L2_STD_525_60) ? 480 : 576;
535 	dev->norm = norm;
536 
537 	stk1160_set_std(dev);
538 
539 	/* Calling with NULL disables frame decimation */
540 	stk1160_set_fmt(dev, NULL);
541 
542 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
543 			dev->norm);
544 
545 	return 0;
546 }
547 
548 
549 static int vidioc_enum_input(struct file *file, void *priv,
550 				struct v4l2_input *i)
551 {
552 	struct stk1160 *dev = video_drvdata(file);
553 
554 	if (i->index > STK1160_MAX_INPUT)
555 		return -EINVAL;
556 
557 	/* S-Video special handling */
558 	if (i->index == STK1160_SVIDEO_INPUT)
559 		sprintf(i->name, "S-Video");
560 	else
561 		sprintf(i->name, "Composite%d", i->index);
562 
563 	i->type = V4L2_INPUT_TYPE_CAMERA;
564 	i->std = dev->vdev.tvnorms;
565 	return 0;
566 }
567 
568 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
569 {
570 	struct stk1160 *dev = video_drvdata(file);
571 	*i = dev->ctl_input;
572 	return 0;
573 }
574 
575 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
576 {
577 	struct stk1160 *dev = video_drvdata(file);
578 
579 	if (i > STK1160_MAX_INPUT)
580 		return -EINVAL;
581 
582 	dev->ctl_input = i;
583 
584 	stk1160_select_input(dev);
585 
586 	return 0;
587 }
588 
589 #ifdef CONFIG_VIDEO_ADV_DEBUG
590 static int vidioc_g_register(struct file *file, void *priv,
591 			     struct v4l2_dbg_register *reg)
592 {
593 	struct stk1160 *dev = video_drvdata(file);
594 	int rc;
595 	u8 val;
596 
597 	/* Match host */
598 	rc = stk1160_read_reg(dev, reg->reg, &val);
599 	reg->val = val;
600 	reg->size = 1;
601 
602 	return rc;
603 }
604 
605 static int vidioc_s_register(struct file *file, void *priv,
606 			     const struct v4l2_dbg_register *reg)
607 {
608 	struct stk1160 *dev = video_drvdata(file);
609 
610 	/* Match host */
611 	return stk1160_write_reg(dev, reg->reg, reg->val);
612 }
613 #endif
614 
615 static const struct v4l2_ioctl_ops stk1160_ioctl_ops = {
616 	.vidioc_querycap      = vidioc_querycap,
617 	.vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
618 	.vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
619 	.vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
620 	.vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
621 	.vidioc_querystd      = vidioc_querystd,
622 	.vidioc_g_std         = vidioc_g_std,
623 	.vidioc_s_std         = vidioc_s_std,
624 	.vidioc_enum_input    = vidioc_enum_input,
625 	.vidioc_g_input       = vidioc_g_input,
626 	.vidioc_s_input       = vidioc_s_input,
627 
628 	/* vb2 takes care of these */
629 	.vidioc_reqbufs       = vb2_ioctl_reqbufs,
630 	.vidioc_querybuf      = vb2_ioctl_querybuf,
631 	.vidioc_qbuf          = vb2_ioctl_qbuf,
632 	.vidioc_dqbuf         = vb2_ioctl_dqbuf,
633 	.vidioc_streamon      = vb2_ioctl_streamon,
634 	.vidioc_streamoff     = vb2_ioctl_streamoff,
635 	.vidioc_expbuf        = vb2_ioctl_expbuf,
636 
637 	.vidioc_log_status  = v4l2_ctrl_log_status,
638 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
639 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
640 
641 #ifdef CONFIG_VIDEO_ADV_DEBUG
642 	.vidioc_g_register = vidioc_g_register,
643 	.vidioc_s_register = vidioc_s_register,
644 #endif
645 };
646 
647 /********************************************************************/
648 
649 /*
650  * Videobuf2 operations
651  */
652 static int queue_setup(struct vb2_queue *vq,
653 				unsigned int *nbuffers, unsigned int *nplanes,
654 				unsigned int sizes[], struct device *alloc_devs[])
655 {
656 	struct stk1160 *dev = vb2_get_drv_priv(vq);
657 	unsigned long size;
658 
659 	size = dev->width * dev->height * 2;
660 
661 	/*
662 	 * Here we can change the number of buffers being requested.
663 	 * So, we set a minimum and a maximum like this:
664 	 */
665 	*nbuffers = clamp_t(unsigned int, *nbuffers,
666 			STK1160_MIN_VIDEO_BUFFERS, STK1160_MAX_VIDEO_BUFFERS);
667 
668 	if (*nplanes)
669 		return sizes[0] < size ? -EINVAL : 0;
670 
671 	/* This means a packed colorformat */
672 	*nplanes = 1;
673 
674 	sizes[0] = size;
675 
676 	stk1160_dbg("%s: buffer count %d, each %ld bytes\n",
677 		    __func__, *nbuffers, size);
678 
679 	return 0;
680 }
681 
682 static void buffer_queue(struct vb2_buffer *vb)
683 {
684 	unsigned long flags;
685 	struct stk1160 *dev = vb2_get_drv_priv(vb->vb2_queue);
686 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
687 	struct stk1160_buffer *buf =
688 		container_of(vbuf, struct stk1160_buffer, vb);
689 
690 	spin_lock_irqsave(&dev->buf_lock, flags);
691 	if (!dev->udev) {
692 		/*
693 		 * If the device is disconnected return the buffer to userspace
694 		 * directly. The next QBUF call will fail with -ENODEV.
695 		 */
696 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
697 	} else {
698 
699 		buf->mem = vb2_plane_vaddr(vb, 0);
700 		buf->length = vb2_plane_size(vb, 0);
701 		buf->bytesused = 0;
702 		buf->pos = 0;
703 
704 		/*
705 		 * If buffer length is less from expected then we return
706 		 * the buffer to userspace directly.
707 		 */
708 		if (buf->length < dev->width * dev->height * 2)
709 			vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
710 		else
711 			list_add_tail(&buf->list, &dev->avail_bufs);
712 
713 	}
714 	spin_unlock_irqrestore(&dev->buf_lock, flags);
715 }
716 
717 static int start_streaming(struct vb2_queue *vq, unsigned int count)
718 {
719 	struct stk1160 *dev = vb2_get_drv_priv(vq);
720 	return stk1160_start_streaming(dev);
721 }
722 
723 /* abort streaming and wait for last buffer */
724 static void stop_streaming(struct vb2_queue *vq)
725 {
726 	struct stk1160 *dev = vb2_get_drv_priv(vq);
727 	stk1160_stop_streaming(dev);
728 }
729 
730 static const struct vb2_ops stk1160_video_qops = {
731 	.queue_setup		= queue_setup,
732 	.buf_queue		= buffer_queue,
733 	.start_streaming	= start_streaming,
734 	.stop_streaming		= stop_streaming,
735 	.wait_prepare		= vb2_ops_wait_prepare,
736 	.wait_finish		= vb2_ops_wait_finish,
737 };
738 
739 static const struct video_device v4l_template = {
740 	.name = "stk1160",
741 	.tvnorms = V4L2_STD_525_60 | V4L2_STD_625_50,
742 	.fops = &stk1160_fops,
743 	.ioctl_ops = &stk1160_ioctl_ops,
744 	.release = video_device_release_empty,
745 };
746 
747 /********************************************************************/
748 
749 /* Must be called with both v4l_lock and vb_queue_lock hold */
750 void stk1160_clear_queue(struct stk1160 *dev)
751 {
752 	struct stk1160_buffer *buf;
753 	unsigned long flags;
754 
755 	/* Release all active buffers */
756 	spin_lock_irqsave(&dev->buf_lock, flags);
757 	while (!list_empty(&dev->avail_bufs)) {
758 		buf = list_first_entry(&dev->avail_bufs,
759 			struct stk1160_buffer, list);
760 		list_del(&buf->list);
761 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
762 		stk1160_dbg("buffer [%p/%d] aborted\n",
763 			    buf, buf->vb.vb2_buf.index);
764 	}
765 
766 	/* It's important to release the current buffer */
767 	if (dev->isoc_ctl.buf) {
768 		buf = dev->isoc_ctl.buf;
769 		dev->isoc_ctl.buf = NULL;
770 
771 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
772 		stk1160_dbg("buffer [%p/%d] aborted\n",
773 			    buf, buf->vb.vb2_buf.index);
774 	}
775 	spin_unlock_irqrestore(&dev->buf_lock, flags);
776 }
777 
778 int stk1160_vb2_setup(struct stk1160 *dev)
779 {
780 	int rc;
781 	struct vb2_queue *q;
782 
783 	q = &dev->vb_vidq;
784 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
785 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
786 	q->drv_priv = dev;
787 	q->buf_struct_size = sizeof(struct stk1160_buffer);
788 	q->ops = &stk1160_video_qops;
789 	q->mem_ops = &vb2_vmalloc_memops;
790 	q->lock = &dev->vb_queue_lock;
791 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
792 
793 	rc = vb2_queue_init(q);
794 	if (rc < 0)
795 		return rc;
796 
797 	/* initialize video dma queue */
798 	INIT_LIST_HEAD(&dev->avail_bufs);
799 
800 	return 0;
801 }
802 
803 int stk1160_video_register(struct stk1160 *dev)
804 {
805 	int rc;
806 
807 	/* Initialize video_device with a template structure */
808 	dev->vdev = v4l_template;
809 	dev->vdev.queue = &dev->vb_vidq;
810 
811 	/*
812 	 * Provide mutexes for v4l2 core and for videobuf2 queue.
813 	 * It will be used to protect *only* v4l2 ioctls.
814 	 */
815 	dev->vdev.lock = &dev->v4l_lock;
816 
817 	/* This will be used to set video_device parent */
818 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
819 	dev->vdev.device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
820 				V4L2_CAP_READWRITE;
821 
822 	/* NTSC is default */
823 	dev->norm = V4L2_STD_NTSC_M;
824 	dev->width = 720;
825 	dev->height = 480;
826 
827 	/* set default format */
828 	dev->fmt = &format[0];
829 	stk1160_set_std(dev);
830 
831 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
832 			dev->norm);
833 
834 	video_set_drvdata(&dev->vdev, dev);
835 	rc = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
836 	if (rc < 0) {
837 		stk1160_err("video_register_device failed (%d)\n", rc);
838 		return rc;
839 	}
840 
841 	v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
842 		  video_device_node_name(&dev->vdev));
843 
844 	return 0;
845 }
846