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 	cap->device_caps =
341 		V4L2_CAP_VIDEO_CAPTURE |
342 		V4L2_CAP_STREAMING |
343 		V4L2_CAP_READWRITE;
344 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
345 	return 0;
346 }
347 
348 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
349 		struct v4l2_fmtdesc *f)
350 {
351 	if (f->index != 0)
352 		return -EINVAL;
353 
354 	strscpy(f->description, format[f->index].name, sizeof(f->description));
355 	f->pixelformat = format[f->index].fourcc;
356 	return 0;
357 }
358 
359 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
360 					struct v4l2_format *f)
361 {
362 	struct stk1160 *dev = video_drvdata(file);
363 
364 	f->fmt.pix.width = dev->width;
365 	f->fmt.pix.height = dev->height;
366 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
367 	f->fmt.pix.pixelformat = dev->fmt->fourcc;
368 	f->fmt.pix.bytesperline = dev->width * 2;
369 	f->fmt.pix.sizeimage = dev->height * f->fmt.pix.bytesperline;
370 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
371 
372 	return 0;
373 }
374 
375 static int stk1160_try_fmt(struct stk1160 *dev, struct v4l2_format *f,
376 			    struct stk1160_decimate_ctrl *ctrl)
377 {
378 	unsigned int width, height;
379 	unsigned int base_width, base_height;
380 	unsigned int col_n, row_n;
381 	enum stk1160_decimate_mode col_mode, row_mode;
382 	bool col_en, row_en;
383 
384 	base_width = 720;
385 	base_height = (dev->norm & V4L2_STD_525_60) ? 480 : 576;
386 
387 	/* Minimum width and height is 5% the frame size */
388 	width = clamp_t(unsigned int, f->fmt.pix.width,
389 			base_width / 20, base_width);
390 	height = clamp_t(unsigned int, f->fmt.pix.height,
391 			base_height / 20, base_height);
392 
393 	/* Let's set default no decimation values */
394 	col_n = 0;
395 	row_n = 0;
396 	col_en = false;
397 	row_en = false;
398 	f->fmt.pix.width = base_width;
399 	f->fmt.pix.height = base_height;
400 	row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
401 	col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
402 
403 	if (width < base_width && width > base_width / 2) {
404 		/*
405 		 * The device will send count units for each
406 		 * unit skipped. This means count unit is:
407 		 *
408 		 * n = width / (frame width - width)
409 		 *
410 		 * And the width is:
411 		 *
412 		 * width = (n / n + 1) * frame width
413 		 */
414 		col_n = div_round_integer(width, base_width - width);
415 		if (col_n > 0 && col_n <= 255) {
416 			col_en = true;
417 			col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
418 			f->fmt.pix.width = (base_width * col_n) / (col_n + 1);
419 		}
420 
421 	} else if (width <= base_width / 2) {
422 
423 		/*
424 		 * The device will skip count units for each
425 		 * unit sent. This means count is:
426 		 *
427 		 * n = (frame width / width) - 1
428 		 *
429 		 * And the width is:
430 		 *
431 		 * width = frame width / (n + 1)
432 		 */
433 		col_n = div_round_integer(base_width, width) - 1;
434 		if (col_n > 0 && col_n <= 255) {
435 			col_en = true;
436 			col_mode = STK1160_DECIMATE_MORE_THAN_HALF;
437 			f->fmt.pix.width = base_width / (col_n + 1);
438 		}
439 	}
440 
441 	if (height < base_height && height > base_height / 2) {
442 		row_n = div_round_integer(height, base_height - height);
443 		if (row_n > 0 && row_n <= 255) {
444 			row_en = true;
445 			row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
446 			f->fmt.pix.height = (base_height * row_n) / (row_n + 1);
447 		}
448 
449 	} else if (height <= base_height / 2) {
450 		row_n = div_round_integer(base_height, height) - 1;
451 		if (row_n > 0 && row_n <= 255) {
452 			row_en = true;
453 			row_mode = STK1160_DECIMATE_MORE_THAN_HALF;
454 			f->fmt.pix.height = base_height / (row_n + 1);
455 		}
456 	}
457 
458 	f->fmt.pix.pixelformat = dev->fmt->fourcc;
459 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
460 	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
461 	f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
462 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
463 
464 	if (ctrl) {
465 		ctrl->col_en = col_en;
466 		ctrl->col_n = col_n;
467 		ctrl->col_mode = col_mode;
468 		ctrl->row_en = row_en;
469 		ctrl->row_n = row_n;
470 		ctrl->row_mode = row_mode;
471 	}
472 
473 	stk1160_dbg("width %d, height %d\n",
474 		    f->fmt.pix.width, f->fmt.pix.height);
475 	return 0;
476 }
477 
478 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
479 				  struct v4l2_format *f)
480 {
481 	struct stk1160 *dev = video_drvdata(file);
482 
483 	return stk1160_try_fmt(dev, f, NULL);
484 }
485 
486 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
487 					struct v4l2_format *f)
488 {
489 	struct stk1160 *dev = video_drvdata(file);
490 	struct vb2_queue *q = &dev->vb_vidq;
491 	struct stk1160_decimate_ctrl ctrl;
492 	int rc;
493 
494 	if (vb2_is_busy(q))
495 		return -EBUSY;
496 
497 	rc = stk1160_try_fmt(dev, f, &ctrl);
498 	if (rc < 0)
499 		return rc;
500 	dev->width = f->fmt.pix.width;
501 	dev->height = f->fmt.pix.height;
502 	stk1160_set_fmt(dev, &ctrl);
503 
504 	return 0;
505 }
506 
507 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
508 {
509 	struct stk1160 *dev = video_drvdata(file);
510 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, querystd, norm);
511 	return 0;
512 }
513 
514 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
515 {
516 	struct stk1160 *dev = video_drvdata(file);
517 
518 	*norm = dev->norm;
519 	return 0;
520 }
521 
522 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
523 {
524 	struct stk1160 *dev = video_drvdata(file);
525 	struct vb2_queue *q = &dev->vb_vidq;
526 
527 	if (dev->norm == norm)
528 		return 0;
529 
530 	if (vb2_is_busy(q))
531 		return -EBUSY;
532 
533 	/* Check device presence */
534 	if (!dev->udev)
535 		return -ENODEV;
536 
537 	/* We need to set this now, before we call stk1160_set_std */
538 	dev->width = 720;
539 	dev->height = (norm & V4L2_STD_525_60) ? 480 : 576;
540 	dev->norm = norm;
541 
542 	stk1160_set_std(dev);
543 
544 	/* Calling with NULL disables frame decimation */
545 	stk1160_set_fmt(dev, NULL);
546 
547 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
548 			dev->norm);
549 
550 	return 0;
551 }
552 
553 
554 static int vidioc_enum_input(struct file *file, void *priv,
555 				struct v4l2_input *i)
556 {
557 	struct stk1160 *dev = video_drvdata(file);
558 
559 	if (i->index > STK1160_MAX_INPUT)
560 		return -EINVAL;
561 
562 	/* S-Video special handling */
563 	if (i->index == STK1160_SVIDEO_INPUT)
564 		sprintf(i->name, "S-Video");
565 	else
566 		sprintf(i->name, "Composite%d", i->index);
567 
568 	i->type = V4L2_INPUT_TYPE_CAMERA;
569 	i->std = dev->vdev.tvnorms;
570 	return 0;
571 }
572 
573 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
574 {
575 	struct stk1160 *dev = video_drvdata(file);
576 	*i = dev->ctl_input;
577 	return 0;
578 }
579 
580 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
581 {
582 	struct stk1160 *dev = video_drvdata(file);
583 
584 	if (i > STK1160_MAX_INPUT)
585 		return -EINVAL;
586 
587 	dev->ctl_input = i;
588 
589 	stk1160_select_input(dev);
590 
591 	return 0;
592 }
593 
594 #ifdef CONFIG_VIDEO_ADV_DEBUG
595 static int vidioc_g_register(struct file *file, void *priv,
596 			     struct v4l2_dbg_register *reg)
597 {
598 	struct stk1160 *dev = video_drvdata(file);
599 	int rc;
600 	u8 val;
601 
602 	/* Match host */
603 	rc = stk1160_read_reg(dev, reg->reg, &val);
604 	reg->val = val;
605 	reg->size = 1;
606 
607 	return rc;
608 }
609 
610 static int vidioc_s_register(struct file *file, void *priv,
611 			     const struct v4l2_dbg_register *reg)
612 {
613 	struct stk1160 *dev = video_drvdata(file);
614 
615 	/* Match host */
616 	return stk1160_write_reg(dev, reg->reg, reg->val);
617 }
618 #endif
619 
620 static const struct v4l2_ioctl_ops stk1160_ioctl_ops = {
621 	.vidioc_querycap      = vidioc_querycap,
622 	.vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
623 	.vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
624 	.vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
625 	.vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
626 	.vidioc_querystd      = vidioc_querystd,
627 	.vidioc_g_std         = vidioc_g_std,
628 	.vidioc_s_std         = vidioc_s_std,
629 	.vidioc_enum_input    = vidioc_enum_input,
630 	.vidioc_g_input       = vidioc_g_input,
631 	.vidioc_s_input       = vidioc_s_input,
632 
633 	/* vb2 takes care of these */
634 	.vidioc_reqbufs       = vb2_ioctl_reqbufs,
635 	.vidioc_querybuf      = vb2_ioctl_querybuf,
636 	.vidioc_qbuf          = vb2_ioctl_qbuf,
637 	.vidioc_dqbuf         = vb2_ioctl_dqbuf,
638 	.vidioc_streamon      = vb2_ioctl_streamon,
639 	.vidioc_streamoff     = vb2_ioctl_streamoff,
640 	.vidioc_expbuf        = vb2_ioctl_expbuf,
641 
642 	.vidioc_log_status  = v4l2_ctrl_log_status,
643 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
644 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
645 
646 #ifdef CONFIG_VIDEO_ADV_DEBUG
647 	.vidioc_g_register = vidioc_g_register,
648 	.vidioc_s_register = vidioc_s_register,
649 #endif
650 };
651 
652 /********************************************************************/
653 
654 /*
655  * Videobuf2 operations
656  */
657 static int queue_setup(struct vb2_queue *vq,
658 				unsigned int *nbuffers, unsigned int *nplanes,
659 				unsigned int sizes[], struct device *alloc_devs[])
660 {
661 	struct stk1160 *dev = vb2_get_drv_priv(vq);
662 	unsigned long size;
663 
664 	size = dev->width * dev->height * 2;
665 
666 	/*
667 	 * Here we can change the number of buffers being requested.
668 	 * So, we set a minimum and a maximum like this:
669 	 */
670 	*nbuffers = clamp_t(unsigned int, *nbuffers,
671 			STK1160_MIN_VIDEO_BUFFERS, STK1160_MAX_VIDEO_BUFFERS);
672 
673 	if (*nplanes)
674 		return sizes[0] < size ? -EINVAL : 0;
675 
676 	/* This means a packed colorformat */
677 	*nplanes = 1;
678 
679 	sizes[0] = size;
680 
681 	stk1160_dbg("%s: buffer count %d, each %ld bytes\n",
682 		    __func__, *nbuffers, size);
683 
684 	return 0;
685 }
686 
687 static void buffer_queue(struct vb2_buffer *vb)
688 {
689 	unsigned long flags;
690 	struct stk1160 *dev = vb2_get_drv_priv(vb->vb2_queue);
691 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
692 	struct stk1160_buffer *buf =
693 		container_of(vbuf, struct stk1160_buffer, vb);
694 
695 	spin_lock_irqsave(&dev->buf_lock, flags);
696 	if (!dev->udev) {
697 		/*
698 		 * If the device is disconnected return the buffer to userspace
699 		 * directly. The next QBUF call will fail with -ENODEV.
700 		 */
701 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
702 	} else {
703 
704 		buf->mem = vb2_plane_vaddr(vb, 0);
705 		buf->length = vb2_plane_size(vb, 0);
706 		buf->bytesused = 0;
707 		buf->pos = 0;
708 
709 		/*
710 		 * If buffer length is less from expected then we return
711 		 * the buffer to userspace directly.
712 		 */
713 		if (buf->length < dev->width * dev->height * 2)
714 			vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
715 		else
716 			list_add_tail(&buf->list, &dev->avail_bufs);
717 
718 	}
719 	spin_unlock_irqrestore(&dev->buf_lock, flags);
720 }
721 
722 static int start_streaming(struct vb2_queue *vq, unsigned int count)
723 {
724 	struct stk1160 *dev = vb2_get_drv_priv(vq);
725 	return stk1160_start_streaming(dev);
726 }
727 
728 /* abort streaming and wait for last buffer */
729 static void stop_streaming(struct vb2_queue *vq)
730 {
731 	struct stk1160 *dev = vb2_get_drv_priv(vq);
732 	stk1160_stop_streaming(dev);
733 }
734 
735 static const struct vb2_ops stk1160_video_qops = {
736 	.queue_setup		= queue_setup,
737 	.buf_queue		= buffer_queue,
738 	.start_streaming	= start_streaming,
739 	.stop_streaming		= stop_streaming,
740 	.wait_prepare		= vb2_ops_wait_prepare,
741 	.wait_finish		= vb2_ops_wait_finish,
742 };
743 
744 static const struct video_device v4l_template = {
745 	.name = "stk1160",
746 	.tvnorms = V4L2_STD_525_60 | V4L2_STD_625_50,
747 	.fops = &stk1160_fops,
748 	.ioctl_ops = &stk1160_ioctl_ops,
749 	.release = video_device_release_empty,
750 };
751 
752 /********************************************************************/
753 
754 /* Must be called with both v4l_lock and vb_queue_lock hold */
755 void stk1160_clear_queue(struct stk1160 *dev)
756 {
757 	struct stk1160_buffer *buf;
758 	unsigned long flags;
759 
760 	/* Release all active buffers */
761 	spin_lock_irqsave(&dev->buf_lock, flags);
762 	while (!list_empty(&dev->avail_bufs)) {
763 		buf = list_first_entry(&dev->avail_bufs,
764 			struct stk1160_buffer, list);
765 		list_del(&buf->list);
766 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
767 		stk1160_dbg("buffer [%p/%d] aborted\n",
768 			    buf, buf->vb.vb2_buf.index);
769 	}
770 
771 	/* It's important to release the current buffer */
772 	if (dev->isoc_ctl.buf) {
773 		buf = dev->isoc_ctl.buf;
774 		dev->isoc_ctl.buf = NULL;
775 
776 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
777 		stk1160_dbg("buffer [%p/%d] aborted\n",
778 			    buf, buf->vb.vb2_buf.index);
779 	}
780 	spin_unlock_irqrestore(&dev->buf_lock, flags);
781 }
782 
783 int stk1160_vb2_setup(struct stk1160 *dev)
784 {
785 	int rc;
786 	struct vb2_queue *q;
787 
788 	q = &dev->vb_vidq;
789 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
790 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
791 	q->drv_priv = dev;
792 	q->buf_struct_size = sizeof(struct stk1160_buffer);
793 	q->ops = &stk1160_video_qops;
794 	q->mem_ops = &vb2_vmalloc_memops;
795 	q->lock = &dev->vb_queue_lock;
796 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
797 
798 	rc = vb2_queue_init(q);
799 	if (rc < 0)
800 		return rc;
801 
802 	/* initialize video dma queue */
803 	INIT_LIST_HEAD(&dev->avail_bufs);
804 
805 	return 0;
806 }
807 
808 int stk1160_video_register(struct stk1160 *dev)
809 {
810 	int rc;
811 
812 	/* Initialize video_device with a template structure */
813 	dev->vdev = v4l_template;
814 	dev->vdev.queue = &dev->vb_vidq;
815 
816 	/*
817 	 * Provide mutexes for v4l2 core and for videobuf2 queue.
818 	 * It will be used to protect *only* v4l2 ioctls.
819 	 */
820 	dev->vdev.lock = &dev->v4l_lock;
821 
822 	/* This will be used to set video_device parent */
823 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
824 
825 	/* NTSC is default */
826 	dev->norm = V4L2_STD_NTSC_M;
827 	dev->width = 720;
828 	dev->height = 480;
829 
830 	/* set default format */
831 	dev->fmt = &format[0];
832 	stk1160_set_std(dev);
833 
834 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
835 			dev->norm);
836 
837 	video_set_drvdata(&dev->vdev, dev);
838 	rc = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
839 	if (rc < 0) {
840 		stk1160_err("video_register_device failed (%d)\n", rc);
841 		return rc;
842 	}
843 
844 	v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
845 		  video_device_node_name(&dev->vdev));
846 
847 	return 0;
848 }
849