1 /*
2    em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB
3 		    video capture devices
4 
5    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
6 		      Markus Rechberger <mrechberger@gmail.com>
7 		      Mauro Carvalho Chehab <mchehab@infradead.org>
8 		      Sascha Sommer <saschasommer@freenet.de>
9    Copyright (C) 2012 Frank Schäfer <fschaefer.oss@googlemail.com>
10 
11 	Some parts based on SN9C10x PC Camera Controllers GPL driver made
12 		by Luca Risolia <luca.risolia@studio.unibo.it>
13 
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 2 of the License, or
17    (at your option) any later version.
18 
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23 
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  */
28 
29 #include "em28xx.h"
30 
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/bitmap.h>
36 #include <linux/usb.h>
37 #include <linux/i2c.h>
38 #include <linux/mm.h>
39 #include <linux/mutex.h>
40 #include <linux/slab.h>
41 
42 #include "em28xx-v4l.h"
43 #include <media/v4l2-common.h>
44 #include <media/v4l2-ioctl.h>
45 #include <media/v4l2-event.h>
46 #include <media/v4l2-clk.h>
47 #include <media/drv-intf/msp3400.h>
48 #include <media/tuner.h>
49 
50 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
51 		      "Markus Rechberger <mrechberger@gmail.com>, " \
52 		      "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
53 		      "Sascha Sommer <saschasommer@freenet.de>"
54 
55 static unsigned int isoc_debug;
56 module_param(isoc_debug, int, 0644);
57 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
58 
59 static unsigned int disable_vbi;
60 module_param(disable_vbi, int, 0644);
61 MODULE_PARM_DESC(disable_vbi, "disable vbi support");
62 
63 static int alt;
64 module_param(alt, int, 0644);
65 MODULE_PARM_DESC(alt, "alternate setting to use for video endpoint");
66 
67 #define em28xx_videodbg(fmt, arg...) do {\
68 	if (video_debug) \
69 		printk(KERN_DEBUG pr_fmt("video: %s: " fmt), \
70 			 __func__, ##arg); } while (0)
71 
72 #define em28xx_isocdbg(fmt, arg...) do {\
73 	if (isoc_debug) \
74 		printk(KERN_DEBUG pr_fmt("isoc: %s: " fmt), \
75 			 __func__, ##arg); } while (0)
76 
77 MODULE_AUTHOR(DRIVER_AUTHOR);
78 MODULE_DESCRIPTION(DRIVER_DESC " - v4l2 interface");
79 MODULE_LICENSE("GPL");
80 MODULE_VERSION(EM28XX_VERSION);
81 
82 #define EM25XX_FRMDATAHDR_BYTE1			0x02
83 #define EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE	0x20
84 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_END	0x02
85 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_ID	0x01
86 #define EM25XX_FRMDATAHDR_BYTE2_MASK	(EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE | \
87 					 EM25XX_FRMDATAHDR_BYTE2_FRAME_END |   \
88 					 EM25XX_FRMDATAHDR_BYTE2_FRAME_ID)
89 
90 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
91 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
92 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
93 
94 module_param_array(video_nr, int, NULL, 0444);
95 module_param_array(vbi_nr, int, NULL, 0444);
96 module_param_array(radio_nr, int, NULL, 0444);
97 MODULE_PARM_DESC(video_nr, "video device numbers");
98 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
99 MODULE_PARM_DESC(radio_nr, "radio device numbers");
100 
101 static unsigned int video_debug;
102 module_param(video_debug, int, 0644);
103 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
104 
105 /* supported video standards */
106 static struct em28xx_fmt format[] = {
107 	{
108 		.name     = "16 bpp YUY2, 4:2:2, packed",
109 		.fourcc   = V4L2_PIX_FMT_YUYV,
110 		.depth    = 16,
111 		.reg	  = EM28XX_OUTFMT_YUV422_Y0UY1V,
112 	}, {
113 		.name     = "16 bpp RGB 565, LE",
114 		.fourcc   = V4L2_PIX_FMT_RGB565,
115 		.depth    = 16,
116 		.reg      = EM28XX_OUTFMT_RGB_16_656,
117 	}, {
118 		.name     = "8 bpp Bayer BGBG..GRGR",
119 		.fourcc   = V4L2_PIX_FMT_SBGGR8,
120 		.depth    = 8,
121 		.reg      = EM28XX_OUTFMT_RGB_8_BGBG,
122 	}, {
123 		.name     = "8 bpp Bayer GRGR..BGBG",
124 		.fourcc   = V4L2_PIX_FMT_SGRBG8,
125 		.depth    = 8,
126 		.reg      = EM28XX_OUTFMT_RGB_8_GRGR,
127 	}, {
128 		.name     = "8 bpp Bayer GBGB..RGRG",
129 		.fourcc   = V4L2_PIX_FMT_SGBRG8,
130 		.depth    = 8,
131 		.reg      = EM28XX_OUTFMT_RGB_8_GBGB,
132 	}, {
133 		.name     = "12 bpp YUV411",
134 		.fourcc   = V4L2_PIX_FMT_YUV411P,
135 		.depth    = 12,
136 		.reg      = EM28XX_OUTFMT_YUV411,
137 	},
138 };
139 
140 /*FIXME: maxw should be dependent of alt mode */
141 static inline unsigned int norm_maxw(struct em28xx *dev)
142 {
143 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
144 
145 	if (dev->board.is_webcam)
146 		return v4l2->sensor_xres;
147 
148 	if (dev->board.max_range_640_480)
149 		return 640;
150 
151 	return 720;
152 }
153 
154 static inline unsigned int norm_maxh(struct em28xx *dev)
155 {
156 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
157 
158 	if (dev->board.is_webcam)
159 		return v4l2->sensor_yres;
160 
161 	if (dev->board.max_range_640_480)
162 		return 480;
163 
164 	return (v4l2->norm & V4L2_STD_625_50) ? 576 : 480;
165 }
166 
167 static int em28xx_vbi_supported(struct em28xx *dev)
168 {
169 	/* Modprobe option to manually disable */
170 	if (disable_vbi == 1)
171 		return 0;
172 
173 	if (dev->board.is_webcam)
174 		return 0;
175 
176 	/* FIXME: check subdevices for VBI support */
177 
178 	if (dev->chip_id == CHIP_ID_EM2860 ||
179 	    dev->chip_id == CHIP_ID_EM2883)
180 		return 1;
181 
182 	/* Version of em28xx that does not support VBI */
183 	return 0;
184 }
185 
186 /*
187  * em28xx_wake_i2c()
188  * configure i2c attached devices
189  */
190 static void em28xx_wake_i2c(struct em28xx *dev)
191 {
192 	struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
193 
194 	v4l2_device_call_all(v4l2_dev, 0, core,  reset, 0);
195 	v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
196 			     INPUT(dev->ctl_input)->vmux, 0, 0);
197 }
198 
199 static int em28xx_colorlevels_set_default(struct em28xx *dev)
200 {
201 	em28xx_write_reg(dev, EM28XX_R20_YGAIN, CONTRAST_DEFAULT);
202 	em28xx_write_reg(dev, EM28XX_R21_YOFFSET, BRIGHTNESS_DEFAULT);
203 	em28xx_write_reg(dev, EM28XX_R22_UVGAIN, SATURATION_DEFAULT);
204 	em28xx_write_reg(dev, EM28XX_R23_UOFFSET, BLUE_BALANCE_DEFAULT);
205 	em28xx_write_reg(dev, EM28XX_R24_VOFFSET, RED_BALANCE_DEFAULT);
206 	em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, SHARPNESS_DEFAULT);
207 
208 	em28xx_write_reg(dev, EM28XX_R14_GAMMA, 0x20);
209 	em28xx_write_reg(dev, EM28XX_R15_RGAIN, 0x20);
210 	em28xx_write_reg(dev, EM28XX_R16_GGAIN, 0x20);
211 	em28xx_write_reg(dev, EM28XX_R17_BGAIN, 0x20);
212 	em28xx_write_reg(dev, EM28XX_R18_ROFFSET, 0x00);
213 	em28xx_write_reg(dev, EM28XX_R19_GOFFSET, 0x00);
214 	return em28xx_write_reg(dev, EM28XX_R1A_BOFFSET, 0x00);
215 }
216 
217 static int em28xx_set_outfmt(struct em28xx *dev)
218 {
219 	int ret;
220 	u8 fmt, vinctrl;
221 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
222 
223 	fmt = v4l2->format->reg;
224 	if (!dev->is_em25xx)
225 		fmt |= 0x20;
226 	/*
227 	 * NOTE: it's not clear if this is really needed !
228 	 * The datasheets say bit 5 is a reserved bit and devices seem to work
229 	 * fine without it. But the Windows driver sets it for em2710/50+em28xx
230 	 * devices and we've always been setting it, too.
231 	 *
232 	 * em2765 (em25xx, em276x/7x/8x) devices do NOT work with this bit set,
233 	 * it's likely used for an additional (compressed ?) format there.
234 	 */
235 	ret = em28xx_write_reg(dev, EM28XX_R27_OUTFMT, fmt);
236 	if (ret < 0)
237 		return ret;
238 
239 	ret = em28xx_write_reg(dev, EM28XX_R10_VINMODE, v4l2->vinmode);
240 	if (ret < 0)
241 		return ret;
242 
243 	vinctrl = v4l2->vinctl;
244 	if (em28xx_vbi_supported(dev) == 1) {
245 		vinctrl |= EM28XX_VINCTRL_VBI_RAW;
246 		em28xx_write_reg(dev, EM28XX_R34_VBI_START_H, 0x00);
247 		em28xx_write_reg(dev, EM28XX_R36_VBI_WIDTH, v4l2->vbi_width/4);
248 		em28xx_write_reg(dev, EM28XX_R37_VBI_HEIGHT, v4l2->vbi_height);
249 		if (v4l2->norm & V4L2_STD_525_60) {
250 			/* NTSC */
251 			em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x09);
252 		} else if (v4l2->norm & V4L2_STD_625_50) {
253 			/* PAL */
254 			em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x07);
255 		}
256 	}
257 
258 	return em28xx_write_reg(dev, EM28XX_R11_VINCTRL, vinctrl);
259 }
260 
261 static int em28xx_accumulator_set(struct em28xx *dev, u8 xmin, u8 xmax,
262 				  u8 ymin, u8 ymax)
263 {
264 	em28xx_videodbg("em28xx Scale: (%d,%d)-(%d,%d)\n",
265 			xmin, ymin, xmax, ymax);
266 
267 	em28xx_write_regs(dev, EM28XX_R28_XMIN, &xmin, 1);
268 	em28xx_write_regs(dev, EM28XX_R29_XMAX, &xmax, 1);
269 	em28xx_write_regs(dev, EM28XX_R2A_YMIN, &ymin, 1);
270 	return em28xx_write_regs(dev, EM28XX_R2B_YMAX, &ymax, 1);
271 }
272 
273 static void em28xx_capture_area_set(struct em28xx *dev, u8 hstart, u8 vstart,
274 				    u16 width, u16 height)
275 {
276 	u8 cwidth = width >> 2;
277 	u8 cheight = height >> 2;
278 	u8 overflow = (height >> 9 & 0x02) | (width >> 10 & 0x01);
279 	/* NOTE: size limit: 2047x1023 = 2MPix */
280 
281 	em28xx_videodbg("capture area set to (%d,%d): %dx%d\n",
282 			hstart, vstart,
283 		       ((overflow & 2) << 9 | cwidth << 2),
284 		       ((overflow & 1) << 10 | cheight << 2));
285 
286 	em28xx_write_regs(dev, EM28XX_R1C_HSTART, &hstart, 1);
287 	em28xx_write_regs(dev, EM28XX_R1D_VSTART, &vstart, 1);
288 	em28xx_write_regs(dev, EM28XX_R1E_CWIDTH, &cwidth, 1);
289 	em28xx_write_regs(dev, EM28XX_R1F_CHEIGHT, &cheight, 1);
290 	em28xx_write_regs(dev, EM28XX_R1B_OFLOW, &overflow, 1);
291 
292 	/* FIXME: function/meaning of these registers ? */
293 	/* FIXME: align width+height to multiples of 4 ?! */
294 	if (dev->is_em25xx) {
295 		em28xx_write_reg(dev, 0x34, width >> 4);
296 		em28xx_write_reg(dev, 0x35, height >> 4);
297 	}
298 }
299 
300 static int em28xx_scaler_set(struct em28xx *dev, u16 h, u16 v)
301 {
302 	u8 mode = 0x00;
303 	/* the em2800 scaler only supports scaling down to 50% */
304 
305 	if (dev->board.is_em2800) {
306 		mode = (v ? 0x20 : 0x00) | (h ? 0x10 : 0x00);
307 	} else {
308 		u8 buf[2];
309 
310 		buf[0] = h;
311 		buf[1] = h >> 8;
312 		em28xx_write_regs(dev, EM28XX_R30_HSCALELOW, (char *)buf, 2);
313 
314 		buf[0] = v;
315 		buf[1] = v >> 8;
316 		em28xx_write_regs(dev, EM28XX_R32_VSCALELOW, (char *)buf, 2);
317 		/* it seems that both H and V scalers must be active
318 		   to work correctly */
319 		mode = (h || v) ? 0x30 : 0x00;
320 	}
321 	return em28xx_write_reg(dev, EM28XX_R26_COMPR, mode);
322 }
323 
324 /* FIXME: this only function read values from dev */
325 static int em28xx_resolution_set(struct em28xx *dev)
326 {
327 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
328 	int width = norm_maxw(dev);
329 	int height = norm_maxh(dev);
330 
331 	/* Properly setup VBI */
332 	v4l2->vbi_width = 720;
333 	if (v4l2->norm & V4L2_STD_525_60)
334 		v4l2->vbi_height = 12;
335 	else
336 		v4l2->vbi_height = 18;
337 
338 	em28xx_set_outfmt(dev);
339 
340 	em28xx_accumulator_set(dev, 1, (width - 4) >> 2, 1, (height - 4) >> 2);
341 
342 	/* If we don't set the start position to 2 in VBI mode, we end up
343 	   with line 20/21 being YUYV encoded instead of being in 8-bit
344 	   greyscale.  The core of the issue is that line 21 (and line 23 for
345 	   PAL WSS) are inside of active video region, and as a result they
346 	   get the pixelformatting associated with that area.  So by cropping
347 	   it out, we end up with the same format as the rest of the VBI
348 	   region */
349 	if (em28xx_vbi_supported(dev) == 1)
350 		em28xx_capture_area_set(dev, 0, 2, width, height);
351 	else
352 		em28xx_capture_area_set(dev, 0, 0, width, height);
353 
354 	return em28xx_scaler_set(dev, v4l2->hscale, v4l2->vscale);
355 }
356 
357 /* Set USB alternate setting for analog video */
358 static int em28xx_set_alternate(struct em28xx *dev)
359 {
360 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
361 	int errCode;
362 	int i;
363 	unsigned int min_pkt_size = v4l2->width * 2 + 4;
364 
365 	/* NOTE: for isoc transfers, only alt settings > 0 are allowed
366 		 bulk transfers seem to work only with alt=0 ! */
367 	dev->alt = 0;
368 	if ((alt > 0) && (alt < dev->num_alt)) {
369 		em28xx_videodbg("alternate forced to %d\n", dev->alt);
370 		dev->alt = alt;
371 		goto set_alt;
372 	}
373 	if (dev->analog_xfer_bulk)
374 		goto set_alt;
375 
376 	/* When image size is bigger than a certain value,
377 	   the frame size should be increased, otherwise, only
378 	   green screen will be received.
379 	 */
380 	if (v4l2->width * 2 * v4l2->height > 720 * 240 * 2)
381 		min_pkt_size *= 2;
382 
383 	for (i = 0; i < dev->num_alt; i++) {
384 		/* stop when the selected alt setting offers enough bandwidth */
385 		if (dev->alt_max_pkt_size_isoc[i] >= min_pkt_size) {
386 			dev->alt = i;
387 			break;
388 		/* otherwise make sure that we end up with the maximum bandwidth
389 		   because the min_pkt_size equation might be wrong...
390 		*/
391 		} else if (dev->alt_max_pkt_size_isoc[i] >
392 			   dev->alt_max_pkt_size_isoc[dev->alt])
393 			dev->alt = i;
394 	}
395 
396 set_alt:
397 	/* NOTE: for bulk transfers, we need to call usb_set_interface()
398 	 * even if the previous settings were the same. Otherwise streaming
399 	 * fails with all urbs having status = -EOVERFLOW ! */
400 	if (dev->analog_xfer_bulk) {
401 		dev->max_pkt_size = 512; /* USB 2.0 spec */
402 		dev->packet_multiplier = EM28XX_BULK_PACKET_MULTIPLIER;
403 	} else { /* isoc */
404 		em28xx_videodbg("minimum isoc packet size: %u (alt=%d)\n",
405 				min_pkt_size, dev->alt);
406 		dev->max_pkt_size =
407 				  dev->alt_max_pkt_size_isoc[dev->alt];
408 		dev->packet_multiplier = EM28XX_NUM_ISOC_PACKETS;
409 	}
410 	em28xx_videodbg("setting alternate %d with wMaxPacketSize=%u\n",
411 			dev->alt, dev->max_pkt_size);
412 	errCode = usb_set_interface(dev->udev, dev->ifnum, dev->alt);
413 	if (errCode < 0) {
414 		pr_err("cannot change alternate number to %d (error=%i)\n",
415 		       dev->alt, errCode);
416 		return errCode;
417 	}
418 	return 0;
419 }
420 
421 /* ------------------------------------------------------------------
422 	DMA and thread functions
423    ------------------------------------------------------------------*/
424 
425 /*
426  * Finish the current buffer
427  */
428 static inline void finish_buffer(struct em28xx *dev,
429 				 struct em28xx_buffer *buf)
430 {
431 	em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->top_field);
432 
433 	buf->vb.sequence = dev->v4l2->field_count++;
434 	if (dev->v4l2->progressive)
435 		buf->vb.field = V4L2_FIELD_NONE;
436 	else
437 		buf->vb.field = V4L2_FIELD_INTERLACED;
438 	buf->vb.vb2_buf.timestamp = ktime_get_ns();
439 
440 	vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
441 }
442 
443 /*
444  * Copy picture data from USB buffer to videobuf buffer
445  */
446 static void em28xx_copy_video(struct em28xx *dev,
447 			      struct em28xx_buffer *buf,
448 			      unsigned char *usb_buf,
449 			      unsigned long len)
450 {
451 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
452 	void *fieldstart, *startwrite, *startread;
453 	int  linesdone, currlinedone, offset, lencopy, remain;
454 	int bytesperline = v4l2->width << 1;
455 
456 	if (buf->pos + len > buf->length)
457 		len = buf->length - buf->pos;
458 
459 	startread = usb_buf;
460 	remain = len;
461 
462 	if (v4l2->progressive || buf->top_field)
463 		fieldstart = buf->vb_buf;
464 	else /* interlaced mode, even nr. of lines */
465 		fieldstart = buf->vb_buf + bytesperline;
466 
467 	linesdone = buf->pos / bytesperline;
468 	currlinedone = buf->pos % bytesperline;
469 
470 	if (v4l2->progressive)
471 		offset = linesdone * bytesperline + currlinedone;
472 	else
473 		offset = linesdone * bytesperline * 2 + currlinedone;
474 
475 	startwrite = fieldstart + offset;
476 	lencopy = bytesperline - currlinedone;
477 	lencopy = lencopy > remain ? remain : lencopy;
478 
479 	if ((char *)startwrite + lencopy > (char *)buf->vb_buf + buf->length) {
480 		em28xx_isocdbg("Overflow of %zu bytes past buffer end (1)\n",
481 			       ((char *)startwrite + lencopy) -
482 			      ((char *)buf->vb_buf + buf->length));
483 		remain = (char *)buf->vb_buf + buf->length -
484 			 (char *)startwrite;
485 		lencopy = remain;
486 	}
487 	if (lencopy <= 0)
488 		return;
489 	memcpy(startwrite, startread, lencopy);
490 
491 	remain -= lencopy;
492 
493 	while (remain > 0) {
494 		if (v4l2->progressive)
495 			startwrite += lencopy;
496 		else
497 			startwrite += lencopy + bytesperline;
498 		startread += lencopy;
499 		if (bytesperline > remain)
500 			lencopy = remain;
501 		else
502 			lencopy = bytesperline;
503 
504 		if ((char *)startwrite + lencopy > (char *)buf->vb_buf +
505 		    buf->length) {
506 			em28xx_isocdbg("Overflow of %zu bytes past buffer end(2)\n",
507 				       ((char *)startwrite + lencopy) -
508 				       ((char *)buf->vb_buf + buf->length));
509 			lencopy = remain = (char *)buf->vb_buf + buf->length -
510 				(char *)startwrite;
511 		}
512 		if (lencopy <= 0)
513 			break;
514 
515 		memcpy(startwrite, startread, lencopy);
516 
517 		remain -= lencopy;
518 	}
519 
520 	buf->pos += len;
521 }
522 
523 /*
524  * Copy VBI data from USB buffer to videobuf buffer
525  */
526 static void em28xx_copy_vbi(struct em28xx *dev,
527 			    struct em28xx_buffer *buf,
528 			    unsigned char *usb_buf,
529 			    unsigned long len)
530 {
531 	unsigned int offset;
532 
533 	if (buf->pos + len > buf->length)
534 		len = buf->length - buf->pos;
535 
536 	offset = buf->pos;
537 	/* Make sure the bottom field populates the second half of the frame */
538 	if (buf->top_field == 0)
539 		offset += dev->v4l2->vbi_width * dev->v4l2->vbi_height;
540 
541 	memcpy(buf->vb_buf + offset, usb_buf, len);
542 	buf->pos += len;
543 }
544 
545 static inline void print_err_status(struct em28xx *dev,
546 				    int packet, int status)
547 {
548 	char *errmsg = "Unknown";
549 
550 	switch (status) {
551 	case -ENOENT:
552 		errmsg = "unlinked synchronuously";
553 		break;
554 	case -ECONNRESET:
555 		errmsg = "unlinked asynchronuously";
556 		break;
557 	case -ENOSR:
558 		errmsg = "Buffer error (overrun)";
559 		break;
560 	case -EPIPE:
561 		errmsg = "Stalled (device not responding)";
562 		break;
563 	case -EOVERFLOW:
564 		errmsg = "Babble (bad cable?)";
565 		break;
566 	case -EPROTO:
567 		errmsg = "Bit-stuff error (bad cable?)";
568 		break;
569 	case -EILSEQ:
570 		errmsg = "CRC/Timeout (could be anything)";
571 		break;
572 	case -ETIME:
573 		errmsg = "Device does not respond";
574 		break;
575 	}
576 	if (packet < 0) {
577 		em28xx_isocdbg("URB status %d [%s].\n",	status, errmsg);
578 	} else {
579 		em28xx_isocdbg("URB packet %d, status %d [%s].\n",
580 			       packet, status, errmsg);
581 	}
582 }
583 
584 /*
585  * get the next available buffer from dma queue
586  */
587 static inline struct em28xx_buffer *get_next_buf(struct em28xx *dev,
588 						 struct em28xx_dmaqueue *dma_q)
589 {
590 	struct em28xx_buffer *buf;
591 
592 	if (list_empty(&dma_q->active)) {
593 		em28xx_isocdbg("No active queue to serve\n");
594 		return NULL;
595 	}
596 
597 	/* Get the next buffer */
598 	buf = list_entry(dma_q->active.next, struct em28xx_buffer, list);
599 	/* Cleans up buffer - Useful for testing for frame/URB loss */
600 	list_del(&buf->list);
601 	buf->pos = 0;
602 	buf->vb_buf = buf->mem;
603 
604 	return buf;
605 }
606 
607 /*
608  * Finish the current buffer if completed and prepare for the next field
609  */
610 static struct em28xx_buffer *
611 finish_field_prepare_next(struct em28xx *dev,
612 			  struct em28xx_buffer *buf,
613 			  struct em28xx_dmaqueue *dma_q)
614 {
615 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
616 
617 	if (v4l2->progressive || v4l2->top_field) { /* Brand new frame */
618 		if (buf != NULL)
619 			finish_buffer(dev, buf);
620 		buf = get_next_buf(dev, dma_q);
621 	}
622 	if (buf != NULL) {
623 		buf->top_field = v4l2->top_field;
624 		buf->pos = 0;
625 	}
626 
627 	return buf;
628 }
629 
630 /*
631  * Process data packet according to the em2710/em2750/em28xx frame data format
632  */
633 static inline void process_frame_data_em28xx(struct em28xx *dev,
634 					     unsigned char *data_pkt,
635 					     unsigned int  data_len)
636 {
637 	struct em28xx_v4l2      *v4l2 = dev->v4l2;
638 	struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
639 	struct em28xx_buffer    *vbi_buf = dev->usb_ctl.vbi_buf;
640 	struct em28xx_dmaqueue  *dma_q = &dev->vidq;
641 	struct em28xx_dmaqueue  *vbi_dma_q = &dev->vbiq;
642 
643 	/* capture type 0 = vbi start
644 	   capture type 1 = vbi in progress
645 	   capture type 2 = video start
646 	   capture type 3 = video in progress */
647 	if (data_len >= 4) {
648 		/* NOTE: Headers are always 4 bytes and
649 		 * never split across packets */
650 		if (data_pkt[0] == 0x88 && data_pkt[1] == 0x88 &&
651 		    data_pkt[2] == 0x88 && data_pkt[3] == 0x88) {
652 			/* Continuation */
653 			data_pkt += 4;
654 			data_len -= 4;
655 		} else if (data_pkt[0] == 0x33 && data_pkt[1] == 0x95) {
656 			/* Field start (VBI mode) */
657 			v4l2->capture_type = 0;
658 			v4l2->vbi_read = 0;
659 			em28xx_isocdbg("VBI START HEADER !!!\n");
660 			v4l2->top_field = !(data_pkt[2] & 1);
661 			data_pkt += 4;
662 			data_len -= 4;
663 		} else if (data_pkt[0] == 0x22 && data_pkt[1] == 0x5a) {
664 			/* Field start (VBI disabled) */
665 			v4l2->capture_type = 2;
666 			em28xx_isocdbg("VIDEO START HEADER !!!\n");
667 			v4l2->top_field = !(data_pkt[2] & 1);
668 			data_pkt += 4;
669 			data_len -= 4;
670 		}
671 	}
672 	/* NOTE: With bulk transfers, intermediate data packets
673 	 * have no continuation header */
674 
675 	if (v4l2->capture_type == 0) {
676 		vbi_buf = finish_field_prepare_next(dev, vbi_buf, vbi_dma_q);
677 		dev->usb_ctl.vbi_buf = vbi_buf;
678 		v4l2->capture_type = 1;
679 	}
680 
681 	if (v4l2->capture_type == 1) {
682 		int vbi_size = v4l2->vbi_width * v4l2->vbi_height;
683 		int vbi_data_len = ((v4l2->vbi_read + data_len) > vbi_size) ?
684 				   (vbi_size - v4l2->vbi_read) : data_len;
685 
686 		/* Copy VBI data */
687 		if (vbi_buf != NULL)
688 			em28xx_copy_vbi(dev, vbi_buf, data_pkt, vbi_data_len);
689 		v4l2->vbi_read += vbi_data_len;
690 
691 		if (vbi_data_len < data_len) {
692 			/* Continue with copying video data */
693 			v4l2->capture_type = 2;
694 			data_pkt += vbi_data_len;
695 			data_len -= vbi_data_len;
696 		}
697 	}
698 
699 	if (v4l2->capture_type == 2) {
700 		buf = finish_field_prepare_next(dev, buf, dma_q);
701 		dev->usb_ctl.vid_buf = buf;
702 		v4l2->capture_type = 3;
703 	}
704 
705 	if (v4l2->capture_type == 3 && buf != NULL && data_len > 0)
706 		em28xx_copy_video(dev, buf, data_pkt, data_len);
707 }
708 
709 /*
710  * Process data packet according to the em25xx/em276x/7x/8x frame data format
711  */
712 static inline void process_frame_data_em25xx(struct em28xx *dev,
713 					     unsigned char *data_pkt,
714 					     unsigned int  data_len)
715 {
716 	struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
717 	struct em28xx_dmaqueue  *dmaq = &dev->vidq;
718 	struct em28xx_v4l2      *v4l2 = dev->v4l2;
719 	bool frame_end = false;
720 
721 	/* Check for header */
722 	/* NOTE: at least with bulk transfers, only the first packet
723 	 * has a header and has always set the FRAME_END bit         */
724 	if (data_len >= 2) {	/* em25xx header is only 2 bytes long */
725 		if ((data_pkt[0] == EM25XX_FRMDATAHDR_BYTE1) &&
726 		    ((data_pkt[1] & ~EM25XX_FRMDATAHDR_BYTE2_MASK) == 0x00)) {
727 			v4l2->top_field = !(data_pkt[1] &
728 					   EM25XX_FRMDATAHDR_BYTE2_FRAME_ID);
729 			frame_end = data_pkt[1] &
730 				    EM25XX_FRMDATAHDR_BYTE2_FRAME_END;
731 			data_pkt += 2;
732 			data_len -= 2;
733 		}
734 
735 		/* Finish field and prepare next (BULK only) */
736 		if (dev->analog_xfer_bulk && frame_end) {
737 			buf = finish_field_prepare_next(dev, buf, dmaq);
738 			dev->usb_ctl.vid_buf = buf;
739 		}
740 		/* NOTE: in ISOC mode when a new frame starts and buf==NULL,
741 		 * we COULD already prepare a buffer here to avoid skipping the
742 		 * first frame.
743 		 */
744 	}
745 
746 	/* Copy data */
747 	if (buf != NULL && data_len > 0)
748 		em28xx_copy_video(dev, buf, data_pkt, data_len);
749 
750 	/* Finish frame (ISOC only) => avoids lag of 1 frame */
751 	if (!dev->analog_xfer_bulk && frame_end) {
752 		buf = finish_field_prepare_next(dev, buf, dmaq);
753 		dev->usb_ctl.vid_buf = buf;
754 	}
755 
756 	/* NOTE: Tested with USB bulk transfers only !
757 	 * The wording in the datasheet suggests that isoc might work different.
758 	 * The current code assumes that with isoc transfers each packet has a
759 	 * header like with the other em28xx devices.
760 	 */
761 	/* NOTE: Support for interlaced mode is pure theory. It has not been
762 	 * tested and it is unknown if these devices actually support it. */
763 	/* NOTE: No VBI support yet (these chips likely do not support VBI). */
764 }
765 
766 /* Processes and copies the URB data content (video and VBI data) */
767 static inline int em28xx_urb_data_copy(struct em28xx *dev, struct urb *urb)
768 {
769 	int xfer_bulk, num_packets, i;
770 	unsigned char *usb_data_pkt;
771 	unsigned int usb_data_len;
772 
773 	if (!dev)
774 		return 0;
775 
776 	if (dev->disconnected)
777 		return 0;
778 
779 	if (urb->status < 0)
780 		print_err_status(dev, -1, urb->status);
781 
782 	xfer_bulk = usb_pipebulk(urb->pipe);
783 
784 	if (xfer_bulk) /* bulk */
785 		num_packets = 1;
786 	else /* isoc */
787 		num_packets = urb->number_of_packets;
788 
789 	for (i = 0; i < num_packets; i++) {
790 		if (xfer_bulk) { /* bulk */
791 			usb_data_len = urb->actual_length;
792 
793 			usb_data_pkt = urb->transfer_buffer;
794 		} else { /* isoc */
795 			if (urb->iso_frame_desc[i].status < 0) {
796 				print_err_status(dev, i,
797 						 urb->iso_frame_desc[i].status);
798 				if (urb->iso_frame_desc[i].status != -EPROTO)
799 					continue;
800 			}
801 
802 			usb_data_len = urb->iso_frame_desc[i].actual_length;
803 			if (usb_data_len > dev->max_pkt_size) {
804 				em28xx_isocdbg("packet bigger than packet size");
805 				continue;
806 			}
807 
808 			usb_data_pkt = urb->transfer_buffer +
809 				       urb->iso_frame_desc[i].offset;
810 		}
811 
812 		if (usb_data_len == 0) {
813 			/* NOTE: happens very often with isoc transfers */
814 			/* em28xx_usbdbg("packet %d is empty",i); - spammy */
815 			continue;
816 		}
817 
818 		if (dev->is_em25xx)
819 			process_frame_data_em25xx(dev,
820 						  usb_data_pkt, usb_data_len);
821 		else
822 			process_frame_data_em28xx(dev,
823 						  usb_data_pkt, usb_data_len);
824 
825 	}
826 	return 1;
827 }
828 
829 static int get_ressource(enum v4l2_buf_type f_type)
830 {
831 	switch (f_type) {
832 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
833 		return EM28XX_RESOURCE_VIDEO;
834 	case V4L2_BUF_TYPE_VBI_CAPTURE:
835 		return EM28XX_RESOURCE_VBI;
836 	default:
837 		BUG();
838 	}
839 }
840 
841 /* Usage lock check functions */
842 static int res_get(struct em28xx *dev, enum v4l2_buf_type f_type)
843 {
844 	int res_type = get_ressource(f_type);
845 
846 	/* is it free? */
847 	if (dev->resources & res_type) {
848 		/* no, someone else uses it */
849 		return -EBUSY;
850 	}
851 
852 	/* it's free, grab it */
853 	dev->resources |= res_type;
854 	em28xx_videodbg("res: get %d\n", res_type);
855 	return 0;
856 }
857 
858 static void res_free(struct em28xx *dev, enum v4l2_buf_type f_type)
859 {
860 	int res_type = get_ressource(f_type);
861 
862 	dev->resources &= ~res_type;
863 	em28xx_videodbg("res: put %d\n", res_type);
864 }
865 
866 static void em28xx_v4l2_media_release(struct em28xx *dev)
867 {
868 #ifdef CONFIG_MEDIA_CONTROLLER
869 	int i;
870 
871 	for (i = 0; i < MAX_EM28XX_INPUT; i++) {
872 		if (!INPUT(i)->type)
873 			return;
874 		media_device_unregister_entity(&dev->input_ent[i]);
875 	}
876 #endif
877 }
878 
879 /*
880  * Media Controller helper functions
881  */
882 
883 static int em28xx_enable_analog_tuner(struct em28xx *dev)
884 {
885 #ifdef CONFIG_MEDIA_CONTROLLER
886 	struct media_device *mdev = dev->media_dev;
887 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
888 	struct media_entity *source;
889 	struct media_link *link, *found_link = NULL;
890 	int ret, active_links = 0;
891 
892 	if (!mdev || !v4l2->decoder)
893 		return 0;
894 
895 	/*
896 	 * This will find the tuner that is connected into the decoder.
897 	 * Technically, this is not 100% correct, as the device may be
898 	 * using an analog input instead of the tuner. However, as we can't
899 	 * do DVB streaming while the DMA engine is being used for V4L2,
900 	 * this should be enough for the actual needs.
901 	 */
902 	list_for_each_entry(link, &v4l2->decoder->links, list) {
903 		if (link->sink->entity == v4l2->decoder) {
904 			found_link = link;
905 			if (link->flags & MEDIA_LNK_FL_ENABLED)
906 				active_links++;
907 			break;
908 		}
909 	}
910 
911 	if (active_links == 1 || !found_link)
912 		return 0;
913 
914 	source = found_link->source->entity;
915 	list_for_each_entry(link, &source->links, list) {
916 		struct media_entity *sink;
917 		int flags = 0;
918 
919 		sink = link->sink->entity;
920 
921 		if (sink == v4l2->decoder)
922 			flags = MEDIA_LNK_FL_ENABLED;
923 
924 		ret = media_entity_setup_link(link, flags);
925 		if (ret) {
926 			pr_err("Couldn't change link %s->%s to %s. Error %d\n",
927 			       source->name, sink->name,
928 			       flags ? "enabled" : "disabled",
929 			       ret);
930 			return ret;
931 		} else
932 			em28xx_videodbg("link %s->%s was %s\n",
933 					source->name, sink->name,
934 					flags ? "ENABLED" : "disabled");
935 	}
936 #endif
937 	return 0;
938 }
939 
940 static const char * const iname[] = {
941 	[EM28XX_VMUX_COMPOSITE]  = "Composite",
942 	[EM28XX_VMUX_SVIDEO]     = "S-Video",
943 	[EM28XX_VMUX_TELEVISION] = "Television",
944 	[EM28XX_RADIO]           = "Radio",
945 };
946 
947 static void em28xx_v4l2_create_entities(struct em28xx *dev)
948 {
949 #if defined(CONFIG_MEDIA_CONTROLLER)
950 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
951 	int ret, i;
952 
953 	/* Initialize Video, VBI and Radio pads */
954 	v4l2->video_pad.flags = MEDIA_PAD_FL_SINK;
955 	ret = media_entity_pads_init(&v4l2->vdev.entity, 1, &v4l2->video_pad);
956 	if (ret < 0)
957 		pr_err("failed to initialize video media entity!\n");
958 
959 	if (em28xx_vbi_supported(dev)) {
960 		v4l2->vbi_pad.flags = MEDIA_PAD_FL_SINK;
961 		ret = media_entity_pads_init(&v4l2->vbi_dev.entity, 1,
962 					     &v4l2->vbi_pad);
963 		if (ret < 0)
964 			pr_err("failed to initialize vbi media entity!\n");
965 	}
966 
967 	/* Webcams don't have input connectors */
968 	if (dev->board.is_webcam)
969 		return;
970 
971 	/* Create entities for each input connector */
972 	for (i = 0; i < MAX_EM28XX_INPUT; i++) {
973 		struct media_entity *ent = &dev->input_ent[i];
974 
975 		if (!INPUT(i)->type)
976 			break;
977 
978 		ent->name = iname[INPUT(i)->type];
979 		ent->flags = MEDIA_ENT_FL_CONNECTOR;
980 		dev->input_pad[i].flags = MEDIA_PAD_FL_SOURCE;
981 
982 		switch (INPUT(i)->type) {
983 		case EM28XX_VMUX_COMPOSITE:
984 			ent->function = MEDIA_ENT_F_CONN_COMPOSITE;
985 			break;
986 		case EM28XX_VMUX_SVIDEO:
987 			ent->function = MEDIA_ENT_F_CONN_SVIDEO;
988 			break;
989 		default: /* EM28XX_VMUX_TELEVISION or EM28XX_RADIO */
990 			if (dev->tuner_type != TUNER_ABSENT)
991 				ent->function = MEDIA_ENT_F_CONN_RF;
992 			break;
993 		}
994 
995 		ret = media_entity_pads_init(ent, 1, &dev->input_pad[i]);
996 		if (ret < 0)
997 			pr_err("failed to initialize input pad[%d]!\n", i);
998 
999 		ret = media_device_register_entity(dev->media_dev, ent);
1000 		if (ret < 0)
1001 			pr_err("failed to register input entity %d!\n", i);
1002 	}
1003 #endif
1004 }
1005 
1006 
1007 /* ------------------------------------------------------------------
1008 	Videobuf2 operations
1009    ------------------------------------------------------------------*/
1010 
1011 static int queue_setup(struct vb2_queue *vq,
1012 		       unsigned int *nbuffers, unsigned int *nplanes,
1013 		       unsigned int sizes[], struct device *alloc_devs[])
1014 {
1015 	struct em28xx *dev = vb2_get_drv_priv(vq);
1016 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1017 	unsigned long size =
1018 		    (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1019 
1020 	if (*nplanes)
1021 		return sizes[0] < size ? -EINVAL : 0;
1022 	*nplanes = 1;
1023 	sizes[0] = size;
1024 
1025 	em28xx_enable_analog_tuner(dev);
1026 
1027 	return 0;
1028 }
1029 
1030 static int
1031 buffer_prepare(struct vb2_buffer *vb)
1032 {
1033 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1034 	struct em28xx        *dev = vb2_get_drv_priv(vb->vb2_queue);
1035 	struct em28xx_v4l2   *v4l2 = dev->v4l2;
1036 	unsigned long size;
1037 
1038 	em28xx_videodbg("%s, field=%d\n", __func__, vbuf->field);
1039 
1040 	size = (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1041 
1042 	if (vb2_plane_size(vb, 0) < size) {
1043 		em28xx_videodbg("%s data will not fit into plane (%lu < %lu)\n",
1044 				__func__, vb2_plane_size(vb, 0), size);
1045 		return -EINVAL;
1046 	}
1047 	vb2_set_plane_payload(vb, 0, size);
1048 
1049 	return 0;
1050 }
1051 
1052 int em28xx_start_analog_streaming(struct vb2_queue *vq, unsigned int count)
1053 {
1054 	struct em28xx *dev = vb2_get_drv_priv(vq);
1055 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1056 	struct v4l2_frequency f;
1057 	struct v4l2_fh *owner;
1058 	int rc = 0;
1059 
1060 	em28xx_videodbg("%s\n", __func__);
1061 
1062 	/* Make sure streaming is not already in progress for this type
1063 	   of filehandle (e.g. video, vbi) */
1064 	rc = res_get(dev, vq->type);
1065 	if (rc)
1066 		return rc;
1067 
1068 	if (v4l2->streaming_users == 0) {
1069 		/* First active streaming user, so allocate all the URBs */
1070 
1071 		/* Allocate the USB bandwidth */
1072 		em28xx_set_alternate(dev);
1073 
1074 		/* Needed, since GPIO might have disabled power of
1075 		   some i2c device
1076 		*/
1077 		em28xx_wake_i2c(dev);
1078 
1079 		v4l2->capture_type = -1;
1080 		rc = em28xx_init_usb_xfer(dev, EM28XX_ANALOG_MODE,
1081 					  dev->analog_xfer_bulk,
1082 					  EM28XX_NUM_BUFS,
1083 					  dev->max_pkt_size,
1084 					  dev->packet_multiplier,
1085 					  em28xx_urb_data_copy);
1086 		if (rc < 0)
1087 			return rc;
1088 
1089 		/*
1090 		 * djh: it's not clear whether this code is still needed.  I'm
1091 		 * leaving it in here for now entirely out of concern for
1092 		 * backward compatibility (the old code did it)
1093 		 */
1094 
1095 		/* Ask tuner to go to analog or radio mode */
1096 		memset(&f, 0, sizeof(f));
1097 		f.frequency = v4l2->frequency;
1098 		owner = (struct v4l2_fh *)vq->owner;
1099 		if (owner && owner->vdev->vfl_type == VFL_TYPE_RADIO)
1100 			f.type = V4L2_TUNER_RADIO;
1101 		else
1102 			f.type = V4L2_TUNER_ANALOG_TV;
1103 		v4l2_device_call_all(&v4l2->v4l2_dev,
1104 				     0, tuner, s_frequency, &f);
1105 
1106 		/* Enable video stream at TV decoder */
1107 		v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 1);
1108 	}
1109 
1110 	v4l2->streaming_users++;
1111 
1112 	return rc;
1113 }
1114 
1115 static void em28xx_stop_streaming(struct vb2_queue *vq)
1116 {
1117 	struct em28xx *dev = vb2_get_drv_priv(vq);
1118 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1119 	struct em28xx_dmaqueue *vidq = &dev->vidq;
1120 	unsigned long flags = 0;
1121 
1122 	em28xx_videodbg("%s\n", __func__);
1123 
1124 	res_free(dev, vq->type);
1125 
1126 	if (v4l2->streaming_users-- == 1) {
1127 		/* Disable video stream at TV decoder */
1128 		v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1129 
1130 		/* Last active user, so shutdown all the URBS */
1131 		em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1132 	}
1133 
1134 	spin_lock_irqsave(&dev->slock, flags);
1135 	if (dev->usb_ctl.vid_buf != NULL) {
1136 		vb2_buffer_done(&dev->usb_ctl.vid_buf->vb.vb2_buf,
1137 				VB2_BUF_STATE_ERROR);
1138 		dev->usb_ctl.vid_buf = NULL;
1139 	}
1140 	while (!list_empty(&vidq->active)) {
1141 		struct em28xx_buffer *buf;
1142 
1143 		buf = list_entry(vidq->active.next, struct em28xx_buffer, list);
1144 		list_del(&buf->list);
1145 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1146 	}
1147 	spin_unlock_irqrestore(&dev->slock, flags);
1148 }
1149 
1150 void em28xx_stop_vbi_streaming(struct vb2_queue *vq)
1151 {
1152 	struct em28xx *dev = vb2_get_drv_priv(vq);
1153 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1154 	struct em28xx_dmaqueue *vbiq = &dev->vbiq;
1155 	unsigned long flags = 0;
1156 
1157 	em28xx_videodbg("%s\n", __func__);
1158 
1159 	res_free(dev, vq->type);
1160 
1161 	if (v4l2->streaming_users-- == 1) {
1162 		/* Disable video stream at TV decoder */
1163 		v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1164 
1165 		/* Last active user, so shutdown all the URBS */
1166 		em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1167 	}
1168 
1169 	spin_lock_irqsave(&dev->slock, flags);
1170 	if (dev->usb_ctl.vbi_buf != NULL) {
1171 		vb2_buffer_done(&dev->usb_ctl.vbi_buf->vb.vb2_buf,
1172 				VB2_BUF_STATE_ERROR);
1173 		dev->usb_ctl.vbi_buf = NULL;
1174 	}
1175 	while (!list_empty(&vbiq->active)) {
1176 		struct em28xx_buffer *buf;
1177 
1178 		buf = list_entry(vbiq->active.next, struct em28xx_buffer, list);
1179 		list_del(&buf->list);
1180 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1181 	}
1182 	spin_unlock_irqrestore(&dev->slock, flags);
1183 }
1184 
1185 static void
1186 buffer_queue(struct vb2_buffer *vb)
1187 {
1188 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1189 	struct em28xx *dev = vb2_get_drv_priv(vb->vb2_queue);
1190 	struct em28xx_buffer *buf =
1191 		container_of(vbuf, struct em28xx_buffer, vb);
1192 	struct em28xx_dmaqueue *vidq = &dev->vidq;
1193 	unsigned long flags = 0;
1194 
1195 	em28xx_videodbg("%s\n", __func__);
1196 	buf->mem = vb2_plane_vaddr(vb, 0);
1197 	buf->length = vb2_plane_size(vb, 0);
1198 
1199 	spin_lock_irqsave(&dev->slock, flags);
1200 	list_add_tail(&buf->list, &vidq->active);
1201 	spin_unlock_irqrestore(&dev->slock, flags);
1202 }
1203 
1204 static const struct vb2_ops em28xx_video_qops = {
1205 	.queue_setup    = queue_setup,
1206 	.buf_prepare    = buffer_prepare,
1207 	.buf_queue      = buffer_queue,
1208 	.start_streaming = em28xx_start_analog_streaming,
1209 	.stop_streaming = em28xx_stop_streaming,
1210 	.wait_prepare   = vb2_ops_wait_prepare,
1211 	.wait_finish    = vb2_ops_wait_finish,
1212 };
1213 
1214 static int em28xx_vb2_setup(struct em28xx *dev)
1215 {
1216 	int rc;
1217 	struct vb2_queue *q;
1218 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1219 
1220 	/* Setup Videobuf2 for Video capture */
1221 	q = &v4l2->vb_vidq;
1222 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1223 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1224 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1225 	q->drv_priv = dev;
1226 	q->buf_struct_size = sizeof(struct em28xx_buffer);
1227 	q->ops = &em28xx_video_qops;
1228 	q->mem_ops = &vb2_vmalloc_memops;
1229 
1230 	rc = vb2_queue_init(q);
1231 	if (rc < 0)
1232 		return rc;
1233 
1234 	/* Setup Videobuf2 for VBI capture */
1235 	q = &v4l2->vb_vbiq;
1236 	q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1237 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR;
1238 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1239 	q->drv_priv = dev;
1240 	q->buf_struct_size = sizeof(struct em28xx_buffer);
1241 	q->ops = &em28xx_vbi_qops;
1242 	q->mem_ops = &vb2_vmalloc_memops;
1243 
1244 	rc = vb2_queue_init(q);
1245 	if (rc < 0)
1246 		return rc;
1247 
1248 	return 0;
1249 }
1250 
1251 /*********************  v4l2 interface  **************************************/
1252 
1253 static void video_mux(struct em28xx *dev, int index)
1254 {
1255 	struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
1256 
1257 	dev->ctl_input = index;
1258 	dev->ctl_ainput = INPUT(index)->amux;
1259 	dev->ctl_aoutput = INPUT(index)->aout;
1260 
1261 	if (!dev->ctl_aoutput)
1262 		dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1263 
1264 	v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
1265 			     INPUT(index)->vmux, 0, 0);
1266 
1267 	if (dev->board.has_msp34xx) {
1268 		if (dev->i2s_speed) {
1269 			v4l2_device_call_all(v4l2_dev, 0, audio,
1270 					     s_i2s_clock_freq, dev->i2s_speed);
1271 		}
1272 		/* Note: this is msp3400 specific */
1273 		v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1274 				     dev->ctl_ainput,
1275 				     MSP_OUTPUT(MSP_SC_IN_DSP_SCART1), 0);
1276 	}
1277 
1278 	if (dev->board.adecoder != EM28XX_NOADECODER) {
1279 		v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1280 				     dev->ctl_ainput, dev->ctl_aoutput, 0);
1281 	}
1282 
1283 	em28xx_audio_analog_set(dev);
1284 }
1285 
1286 static void em28xx_ctrl_notify(struct v4l2_ctrl *ctrl, void *priv)
1287 {
1288 	struct em28xx *dev = priv;
1289 
1290 	/*
1291 	 * In the case of non-AC97 volume controls, we still need
1292 	 * to do some setups at em28xx, in order to mute/unmute
1293 	 * and to adjust audio volume. However, the value ranges
1294 	 * should be checked by the corresponding V4L subdriver.
1295 	 */
1296 	switch (ctrl->id) {
1297 	case V4L2_CID_AUDIO_MUTE:
1298 		dev->mute = ctrl->val;
1299 		em28xx_audio_analog_set(dev);
1300 		break;
1301 	case V4L2_CID_AUDIO_VOLUME:
1302 		dev->volume = ctrl->val;
1303 		em28xx_audio_analog_set(dev);
1304 		break;
1305 	}
1306 }
1307 
1308 static int em28xx_s_ctrl(struct v4l2_ctrl *ctrl)
1309 {
1310 	struct em28xx_v4l2 *v4l2 =
1311 		  container_of(ctrl->handler, struct em28xx_v4l2, ctrl_handler);
1312 	struct em28xx *dev = v4l2->dev;
1313 	int ret = -EINVAL;
1314 
1315 	switch (ctrl->id) {
1316 	case V4L2_CID_AUDIO_MUTE:
1317 		dev->mute = ctrl->val;
1318 		ret = em28xx_audio_analog_set(dev);
1319 		break;
1320 	case V4L2_CID_AUDIO_VOLUME:
1321 		dev->volume = ctrl->val;
1322 		ret = em28xx_audio_analog_set(dev);
1323 		break;
1324 	case V4L2_CID_CONTRAST:
1325 		ret = em28xx_write_reg(dev, EM28XX_R20_YGAIN, ctrl->val);
1326 		break;
1327 	case V4L2_CID_BRIGHTNESS:
1328 		ret = em28xx_write_reg(dev, EM28XX_R21_YOFFSET, ctrl->val);
1329 		break;
1330 	case V4L2_CID_SATURATION:
1331 		ret = em28xx_write_reg(dev, EM28XX_R22_UVGAIN, ctrl->val);
1332 		break;
1333 	case V4L2_CID_BLUE_BALANCE:
1334 		ret = em28xx_write_reg(dev, EM28XX_R23_UOFFSET, ctrl->val);
1335 		break;
1336 	case V4L2_CID_RED_BALANCE:
1337 		ret = em28xx_write_reg(dev, EM28XX_R24_VOFFSET, ctrl->val);
1338 		break;
1339 	case V4L2_CID_SHARPNESS:
1340 		ret = em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, ctrl->val);
1341 		break;
1342 	}
1343 
1344 	return (ret < 0) ? ret : 0;
1345 }
1346 
1347 static const struct v4l2_ctrl_ops em28xx_ctrl_ops = {
1348 	.s_ctrl = em28xx_s_ctrl,
1349 };
1350 
1351 static void size_to_scale(struct em28xx *dev,
1352 			  unsigned int width, unsigned int height,
1353 			unsigned int *hscale, unsigned int *vscale)
1354 {
1355 	unsigned int          maxw = norm_maxw(dev);
1356 	unsigned int          maxh = norm_maxh(dev);
1357 
1358 	*hscale = (((unsigned long)maxw) << 12) / width - 4096L;
1359 	if (*hscale > EM28XX_HVSCALE_MAX)
1360 		*hscale = EM28XX_HVSCALE_MAX;
1361 
1362 	*vscale = (((unsigned long)maxh) << 12) / height - 4096L;
1363 	if (*vscale > EM28XX_HVSCALE_MAX)
1364 		*vscale = EM28XX_HVSCALE_MAX;
1365 }
1366 
1367 static void scale_to_size(struct em28xx *dev,
1368 			  unsigned int hscale, unsigned int vscale,
1369 			  unsigned int *width, unsigned int *height)
1370 {
1371 	unsigned int          maxw = norm_maxw(dev);
1372 	unsigned int          maxh = norm_maxh(dev);
1373 
1374 	*width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
1375 	*height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
1376 
1377 	/* Don't let width or height to be zero */
1378 	if (*width < 1)
1379 		*width = 1;
1380 	if (*height < 1)
1381 		*height = 1;
1382 }
1383 
1384 /* ------------------------------------------------------------------
1385 	IOCTL vidioc handling
1386    ------------------------------------------------------------------*/
1387 
1388 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1389 				struct v4l2_format *f)
1390 {
1391 	struct em28xx         *dev = video_drvdata(file);
1392 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
1393 
1394 	f->fmt.pix.width = v4l2->width;
1395 	f->fmt.pix.height = v4l2->height;
1396 	f->fmt.pix.pixelformat = v4l2->format->fourcc;
1397 	f->fmt.pix.bytesperline = (v4l2->width * v4l2->format->depth + 7) >> 3;
1398 	f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * v4l2->height;
1399 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1400 
1401 	/* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
1402 	if (v4l2->progressive)
1403 		f->fmt.pix.field = V4L2_FIELD_NONE;
1404 	else
1405 		f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1406 			   V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1407 	return 0;
1408 }
1409 
1410 static struct em28xx_fmt *format_by_fourcc(unsigned int fourcc)
1411 {
1412 	unsigned int i;
1413 
1414 	for (i = 0; i < ARRAY_SIZE(format); i++)
1415 		if (format[i].fourcc == fourcc)
1416 			return &format[i];
1417 
1418 	return NULL;
1419 }
1420 
1421 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1422 				  struct v4l2_format *f)
1423 {
1424 	struct em28xx         *dev   = video_drvdata(file);
1425 	struct em28xx_v4l2    *v4l2  = dev->v4l2;
1426 	unsigned int          width  = f->fmt.pix.width;
1427 	unsigned int          height = f->fmt.pix.height;
1428 	unsigned int          maxw   = norm_maxw(dev);
1429 	unsigned int          maxh   = norm_maxh(dev);
1430 	unsigned int          hscale, vscale;
1431 	struct em28xx_fmt     *fmt;
1432 
1433 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1434 	if (!fmt) {
1435 		em28xx_videodbg("Fourcc format (%08x) invalid.\n",
1436 				f->fmt.pix.pixelformat);
1437 		return -EINVAL;
1438 	}
1439 
1440 	if (dev->board.is_em2800) {
1441 		/* the em2800 can only scale down to 50% */
1442 		height = height > (3 * maxh / 4) ? maxh : maxh / 2;
1443 		width = width > (3 * maxw / 4) ? maxw : maxw / 2;
1444 		/*
1445 		 * MaxPacketSize for em2800 is too small to capture at full
1446 		 * resolution use half of maxw as the scaler can only scale
1447 		 * to 50%
1448 		 */
1449 		if (width == maxw && height == maxh)
1450 			width /= 2;
1451 	} else {
1452 		/* width must even because of the YUYV format
1453 		   height must be even because of interlacing */
1454 		v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh,
1455 				      1, 0);
1456 	}
1457 	/* Avoid division by zero at size_to_scale */
1458 	if (width < 1)
1459 		width = 1;
1460 	if (height < 1)
1461 		height = 1;
1462 
1463 	size_to_scale(dev, width, height, &hscale, &vscale);
1464 	scale_to_size(dev, hscale, vscale, &width, &height);
1465 
1466 	f->fmt.pix.width = width;
1467 	f->fmt.pix.height = height;
1468 	f->fmt.pix.pixelformat = fmt->fourcc;
1469 	f->fmt.pix.bytesperline = (width * fmt->depth + 7) >> 3;
1470 	f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
1471 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1472 	if (v4l2->progressive)
1473 		f->fmt.pix.field = V4L2_FIELD_NONE;
1474 	else
1475 		f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1476 			   V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1477 	f->fmt.pix.priv = 0;
1478 
1479 	return 0;
1480 }
1481 
1482 static int em28xx_set_video_format(struct em28xx *dev, unsigned int fourcc,
1483 				   unsigned width, unsigned height)
1484 {
1485 	struct em28xx_fmt     *fmt;
1486 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
1487 
1488 	fmt = format_by_fourcc(fourcc);
1489 	if (!fmt)
1490 		return -EINVAL;
1491 
1492 	v4l2->format = fmt;
1493 	v4l2->width  = width;
1494 	v4l2->height = height;
1495 
1496 	/* set new image size */
1497 	size_to_scale(dev, v4l2->width, v4l2->height,
1498 		      &v4l2->hscale, &v4l2->vscale);
1499 
1500 	em28xx_resolution_set(dev);
1501 
1502 	return 0;
1503 }
1504 
1505 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1506 				struct v4l2_format *f)
1507 {
1508 	struct em28xx *dev = video_drvdata(file);
1509 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1510 
1511 	if (vb2_is_busy(&v4l2->vb_vidq))
1512 		return -EBUSY;
1513 
1514 	vidioc_try_fmt_vid_cap(file, priv, f);
1515 
1516 	return em28xx_set_video_format(dev, f->fmt.pix.pixelformat,
1517 				f->fmt.pix.width, f->fmt.pix.height);
1518 }
1519 
1520 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
1521 {
1522 	struct em28xx *dev = video_drvdata(file);
1523 
1524 	*norm = dev->v4l2->norm;
1525 
1526 	return 0;
1527 }
1528 
1529 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
1530 {
1531 	struct em28xx *dev = video_drvdata(file);
1532 
1533 	v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, video, querystd, norm);
1534 
1535 	return 0;
1536 }
1537 
1538 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1539 {
1540 	struct em28xx      *dev  = video_drvdata(file);
1541 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1542 	struct v4l2_format f;
1543 
1544 	if (norm == v4l2->norm)
1545 		return 0;
1546 
1547 	if (v4l2->streaming_users > 0)
1548 		return -EBUSY;
1549 
1550 	v4l2->norm = norm;
1551 
1552 	/* Adjusts width/height, if needed */
1553 	f.fmt.pix.width = 720;
1554 	f.fmt.pix.height = (norm & V4L2_STD_525_60) ? 480 : 576;
1555 	vidioc_try_fmt_vid_cap(file, priv, &f);
1556 
1557 	/* set new image size */
1558 	v4l2->width = f.fmt.pix.width;
1559 	v4l2->height = f.fmt.pix.height;
1560 	size_to_scale(dev, v4l2->width, v4l2->height,
1561 		      &v4l2->hscale, &v4l2->vscale);
1562 
1563 	em28xx_resolution_set(dev);
1564 	v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
1565 
1566 	return 0;
1567 }
1568 
1569 static int vidioc_g_parm(struct file *file, void *priv,
1570 			 struct v4l2_streamparm *p)
1571 {
1572 	struct em28xx      *dev  = video_drvdata(file);
1573 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
1574 	int rc = 0;
1575 
1576 	p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1577 	if (dev->board.is_webcam)
1578 		rc = v4l2_device_call_until_err(&v4l2->v4l2_dev, 0,
1579 						video, g_parm, p);
1580 	else
1581 		v4l2_video_std_frame_period(v4l2->norm,
1582 					    &p->parm.capture.timeperframe);
1583 
1584 	return rc;
1585 }
1586 
1587 static int vidioc_s_parm(struct file *file, void *priv,
1588 			 struct v4l2_streamparm *p)
1589 {
1590 	struct em28xx *dev = video_drvdata(file);
1591 
1592 	p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1593 	return v4l2_device_call_until_err(&dev->v4l2->v4l2_dev,
1594 					  0, video, s_parm, p);
1595 }
1596 
1597 static int vidioc_enum_input(struct file *file, void *priv,
1598 			     struct v4l2_input *i)
1599 {
1600 	struct em28xx *dev = video_drvdata(file);
1601 	unsigned int       n;
1602 
1603 	n = i->index;
1604 	if (n >= MAX_EM28XX_INPUT)
1605 		return -EINVAL;
1606 	if (0 == INPUT(n)->type)
1607 		return -EINVAL;
1608 
1609 	i->index = n;
1610 	i->type = V4L2_INPUT_TYPE_CAMERA;
1611 
1612 	strcpy(i->name, iname[INPUT(n)->type]);
1613 
1614 	if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type))
1615 		i->type = V4L2_INPUT_TYPE_TUNER;
1616 
1617 	i->std = dev->v4l2->vdev.tvnorms;
1618 	/* webcams do not have the STD API */
1619 	if (dev->board.is_webcam)
1620 		i->capabilities = 0;
1621 
1622 	return 0;
1623 }
1624 
1625 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1626 {
1627 	struct em28xx *dev = video_drvdata(file);
1628 
1629 	*i = dev->ctl_input;
1630 
1631 	return 0;
1632 }
1633 
1634 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1635 {
1636 	struct em28xx *dev = video_drvdata(file);
1637 
1638 	if (i >= MAX_EM28XX_INPUT)
1639 		return -EINVAL;
1640 	if (0 == INPUT(i)->type)
1641 		return -EINVAL;
1642 
1643 	video_mux(dev, i);
1644 	return 0;
1645 }
1646 
1647 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1648 {
1649 	struct em28xx *dev = video_drvdata(file);
1650 
1651 	switch (a->index) {
1652 	case EM28XX_AMUX_VIDEO:
1653 		strcpy(a->name, "Television");
1654 		break;
1655 	case EM28XX_AMUX_LINE_IN:
1656 		strcpy(a->name, "Line In");
1657 		break;
1658 	case EM28XX_AMUX_VIDEO2:
1659 		strcpy(a->name, "Television alt");
1660 		break;
1661 	case EM28XX_AMUX_PHONE:
1662 		strcpy(a->name, "Phone");
1663 		break;
1664 	case EM28XX_AMUX_MIC:
1665 		strcpy(a->name, "Mic");
1666 		break;
1667 	case EM28XX_AMUX_CD:
1668 		strcpy(a->name, "CD");
1669 		break;
1670 	case EM28XX_AMUX_AUX:
1671 		strcpy(a->name, "Aux");
1672 		break;
1673 	case EM28XX_AMUX_PCM_OUT:
1674 		strcpy(a->name, "PCM");
1675 		break;
1676 	default:
1677 		return -EINVAL;
1678 	}
1679 
1680 	a->index = dev->ctl_ainput;
1681 	a->capability = V4L2_AUDCAP_STEREO;
1682 
1683 	return 0;
1684 }
1685 
1686 static int vidioc_s_audio(struct file *file, void *priv, const struct v4l2_audio *a)
1687 {
1688 	struct em28xx *dev = video_drvdata(file);
1689 
1690 	if (a->index >= MAX_EM28XX_INPUT)
1691 		return -EINVAL;
1692 	if (0 == INPUT(a->index)->type)
1693 		return -EINVAL;
1694 
1695 	dev->ctl_ainput = INPUT(a->index)->amux;
1696 	dev->ctl_aoutput = INPUT(a->index)->aout;
1697 
1698 	if (!dev->ctl_aoutput)
1699 		dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1700 
1701 	return 0;
1702 }
1703 
1704 static int vidioc_g_tuner(struct file *file, void *priv,
1705 			  struct v4l2_tuner *t)
1706 {
1707 	struct em28xx *dev = video_drvdata(file);
1708 
1709 	if (0 != t->index)
1710 		return -EINVAL;
1711 
1712 	strcpy(t->name, "Tuner");
1713 
1714 	v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
1715 	return 0;
1716 }
1717 
1718 static int vidioc_s_tuner(struct file *file, void *priv,
1719 			  const struct v4l2_tuner *t)
1720 {
1721 	struct em28xx *dev = video_drvdata(file);
1722 
1723 	if (0 != t->index)
1724 		return -EINVAL;
1725 
1726 	v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
1727 	return 0;
1728 }
1729 
1730 static int vidioc_g_frequency(struct file *file, void *priv,
1731 			      struct v4l2_frequency *f)
1732 {
1733 	struct em28xx         *dev = video_drvdata(file);
1734 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
1735 
1736 	if (0 != f->tuner)
1737 		return -EINVAL;
1738 
1739 	f->frequency = v4l2->frequency;
1740 	return 0;
1741 }
1742 
1743 static int vidioc_s_frequency(struct file *file, void *priv,
1744 			      const struct v4l2_frequency *f)
1745 {
1746 	struct v4l2_frequency  new_freq = *f;
1747 	struct em28xx             *dev  = video_drvdata(file);
1748 	struct em28xx_v4l2        *v4l2 = dev->v4l2;
1749 
1750 	if (0 != f->tuner)
1751 		return -EINVAL;
1752 
1753 	v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_frequency, f);
1754 	v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, g_frequency, &new_freq);
1755 	v4l2->frequency = new_freq.frequency;
1756 
1757 	return 0;
1758 }
1759 
1760 #ifdef CONFIG_VIDEO_ADV_DEBUG
1761 static int vidioc_g_chip_info(struct file *file, void *priv,
1762 			      struct v4l2_dbg_chip_info *chip)
1763 {
1764 	struct em28xx *dev = video_drvdata(file);
1765 
1766 	if (chip->match.addr > 1)
1767 		return -EINVAL;
1768 	if (chip->match.addr == 1)
1769 		strlcpy(chip->name, "ac97", sizeof(chip->name));
1770 	else
1771 		strlcpy(chip->name,
1772 			dev->v4l2->v4l2_dev.name, sizeof(chip->name));
1773 	return 0;
1774 }
1775 
1776 static int em28xx_reg_len(int reg)
1777 {
1778 	switch (reg) {
1779 	case EM28XX_R40_AC97LSB:
1780 	case EM28XX_R30_HSCALELOW:
1781 	case EM28XX_R32_VSCALELOW:
1782 		return 2;
1783 	default:
1784 		return 1;
1785 	}
1786 }
1787 
1788 static int vidioc_g_register(struct file *file, void *priv,
1789 			     struct v4l2_dbg_register *reg)
1790 {
1791 	struct em28xx *dev = video_drvdata(file);
1792 	int ret;
1793 
1794 	if (reg->match.addr > 1)
1795 		return -EINVAL;
1796 	if (reg->match.addr) {
1797 		ret = em28xx_read_ac97(dev, reg->reg);
1798 		if (ret < 0)
1799 			return ret;
1800 
1801 		reg->val = ret;
1802 		reg->size = 1;
1803 		return 0;
1804 	}
1805 
1806 	/* Match host */
1807 	reg->size = em28xx_reg_len(reg->reg);
1808 	if (reg->size == 1) {
1809 		ret = em28xx_read_reg(dev, reg->reg);
1810 
1811 		if (ret < 0)
1812 			return ret;
1813 
1814 		reg->val = ret;
1815 	} else {
1816 		__le16 val = 0;
1817 
1818 		ret = dev->em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1819 						   reg->reg, (char *)&val, 2);
1820 		if (ret < 0)
1821 			return ret;
1822 
1823 		reg->val = le16_to_cpu(val);
1824 	}
1825 
1826 	return 0;
1827 }
1828 
1829 static int vidioc_s_register(struct file *file, void *priv,
1830 			     const struct v4l2_dbg_register *reg)
1831 {
1832 	struct em28xx *dev = video_drvdata(file);
1833 	__le16 buf;
1834 
1835 	if (reg->match.addr > 1)
1836 		return -EINVAL;
1837 	if (reg->match.addr)
1838 		return em28xx_write_ac97(dev, reg->reg, reg->val);
1839 
1840 	/* Match host */
1841 	buf = cpu_to_le16(reg->val);
1842 
1843 	return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1844 			       em28xx_reg_len(reg->reg));
1845 }
1846 #endif
1847 
1848 static int vidioc_querycap(struct file *file, void  *priv,
1849 			   struct v4l2_capability *cap)
1850 {
1851 	struct video_device   *vdev = video_devdata(file);
1852 	struct em28xx         *dev  = video_drvdata(file);
1853 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
1854 
1855 	strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1856 	strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1857 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
1858 
1859 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1860 		cap->device_caps = V4L2_CAP_READWRITE |
1861 			V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1862 	else if (vdev->vfl_type == VFL_TYPE_RADIO)
1863 		cap->device_caps = V4L2_CAP_RADIO;
1864 	else
1865 		cap->device_caps = V4L2_CAP_READWRITE | V4L2_CAP_VBI_CAPTURE;
1866 
1867 	if (dev->int_audio_type != EM28XX_INT_AUDIO_NONE)
1868 		cap->device_caps |= V4L2_CAP_AUDIO;
1869 
1870 	if (dev->tuner_type != TUNER_ABSENT)
1871 		cap->device_caps |= V4L2_CAP_TUNER;
1872 
1873 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS |
1874 		V4L2_CAP_READWRITE | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1875 	if (video_is_registered(&v4l2->vbi_dev))
1876 		cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
1877 	if (video_is_registered(&v4l2->radio_dev))
1878 		cap->capabilities |= V4L2_CAP_RADIO;
1879 	return 0;
1880 }
1881 
1882 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1883 				   struct v4l2_fmtdesc *f)
1884 {
1885 	if (unlikely(f->index >= ARRAY_SIZE(format)))
1886 		return -EINVAL;
1887 
1888 	strlcpy(f->description, format[f->index].name, sizeof(f->description));
1889 	f->pixelformat = format[f->index].fourcc;
1890 
1891 	return 0;
1892 }
1893 
1894 static int vidioc_enum_framesizes(struct file *file, void *priv,
1895 				  struct v4l2_frmsizeenum *fsize)
1896 {
1897 	struct em28xx         *dev = video_drvdata(file);
1898 	struct em28xx_fmt     *fmt;
1899 	unsigned int	      maxw = norm_maxw(dev);
1900 	unsigned int	      maxh = norm_maxh(dev);
1901 
1902 	fmt = format_by_fourcc(fsize->pixel_format);
1903 	if (!fmt) {
1904 		em28xx_videodbg("Fourcc format (%08x) invalid.\n",
1905 				fsize->pixel_format);
1906 		return -EINVAL;
1907 	}
1908 
1909 	if (dev->board.is_em2800) {
1910 		if (fsize->index > 1)
1911 			return -EINVAL;
1912 		fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1913 		fsize->discrete.width = maxw / (1 + fsize->index);
1914 		fsize->discrete.height = maxh / (1 + fsize->index);
1915 		return 0;
1916 	}
1917 
1918 	if (fsize->index != 0)
1919 		return -EINVAL;
1920 
1921 	/* Report a continuous range */
1922 	fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1923 	scale_to_size(dev, EM28XX_HVSCALE_MAX, EM28XX_HVSCALE_MAX,
1924 		      &fsize->stepwise.min_width, &fsize->stepwise.min_height);
1925 	if (fsize->stepwise.min_width < 48)
1926 		fsize->stepwise.min_width = 48;
1927 	if (fsize->stepwise.min_height < 38)
1928 		fsize->stepwise.min_height = 38;
1929 	fsize->stepwise.max_width = maxw;
1930 	fsize->stepwise.max_height = maxh;
1931 	fsize->stepwise.step_width = 1;
1932 	fsize->stepwise.step_height = 1;
1933 	return 0;
1934 }
1935 
1936 /* RAW VBI ioctls */
1937 
1938 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1939 				struct v4l2_format *format)
1940 {
1941 	struct em28xx         *dev  = video_drvdata(file);
1942 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
1943 
1944 	format->fmt.vbi.samples_per_line = v4l2->vbi_width;
1945 	format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1946 	format->fmt.vbi.offset = 0;
1947 	format->fmt.vbi.flags = 0;
1948 	format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1949 	format->fmt.vbi.count[0] = v4l2->vbi_height;
1950 	format->fmt.vbi.count[1] = v4l2->vbi_height;
1951 	memset(format->fmt.vbi.reserved, 0, sizeof(format->fmt.vbi.reserved));
1952 
1953 	/* Varies by video standard (NTSC, PAL, etc.) */
1954 	if (v4l2->norm & V4L2_STD_525_60) {
1955 		/* NTSC */
1956 		format->fmt.vbi.start[0] = 10;
1957 		format->fmt.vbi.start[1] = 273;
1958 	} else if (v4l2->norm & V4L2_STD_625_50) {
1959 		/* PAL */
1960 		format->fmt.vbi.start[0] = 6;
1961 		format->fmt.vbi.start[1] = 318;
1962 	}
1963 
1964 	return 0;
1965 }
1966 
1967 /* ----------------------------------------------------------- */
1968 /* RADIO ESPECIFIC IOCTLS                                      */
1969 /* ----------------------------------------------------------- */
1970 
1971 static int radio_g_tuner(struct file *file, void *priv,
1972 			 struct v4l2_tuner *t)
1973 {
1974 	struct em28xx *dev = video_drvdata(file);
1975 
1976 	if (unlikely(t->index > 0))
1977 		return -EINVAL;
1978 
1979 	strcpy(t->name, "Radio");
1980 
1981 	v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
1982 
1983 	return 0;
1984 }
1985 
1986 static int radio_s_tuner(struct file *file, void *priv,
1987 			 const struct v4l2_tuner *t)
1988 {
1989 	struct em28xx *dev = video_drvdata(file);
1990 
1991 	if (0 != t->index)
1992 		return -EINVAL;
1993 
1994 	v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
1995 
1996 	return 0;
1997 }
1998 
1999 /*
2000  * em28xx_free_v4l2() - Free struct em28xx_v4l2
2001  *
2002  * @ref: struct kref for struct em28xx_v4l2
2003  *
2004  * Called when all users of struct em28xx_v4l2 are gone
2005  */
2006 static void em28xx_free_v4l2(struct kref *ref)
2007 {
2008 	struct em28xx_v4l2 *v4l2 = container_of(ref, struct em28xx_v4l2, ref);
2009 
2010 	v4l2->dev->v4l2 = NULL;
2011 	kfree(v4l2);
2012 }
2013 
2014 /*
2015  * em28xx_v4l2_open()
2016  * inits the device and starts isoc transfer
2017  */
2018 static int em28xx_v4l2_open(struct file *filp)
2019 {
2020 	struct video_device *vdev = video_devdata(filp);
2021 	struct em28xx *dev = video_drvdata(filp);
2022 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
2023 	enum v4l2_buf_type fh_type = 0;
2024 	int ret;
2025 
2026 	switch (vdev->vfl_type) {
2027 	case VFL_TYPE_GRABBER:
2028 		fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2029 		break;
2030 	case VFL_TYPE_VBI:
2031 		fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
2032 		break;
2033 	case VFL_TYPE_RADIO:
2034 		break;
2035 	default:
2036 		return -EINVAL;
2037 	}
2038 
2039 	em28xx_videodbg("open dev=%s type=%s users=%d\n",
2040 			video_device_node_name(vdev), v4l2_type_names[fh_type],
2041 			v4l2->users);
2042 
2043 	if (mutex_lock_interruptible(&dev->lock))
2044 		return -ERESTARTSYS;
2045 
2046 	ret = v4l2_fh_open(filp);
2047 	if (ret) {
2048 		pr_err("%s: v4l2_fh_open() returned error %d\n",
2049 		       __func__, ret);
2050 		mutex_unlock(&dev->lock);
2051 		return ret;
2052 	}
2053 
2054 	if (v4l2->users == 0) {
2055 		em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
2056 
2057 		if (vdev->vfl_type != VFL_TYPE_RADIO)
2058 			em28xx_resolution_set(dev);
2059 
2060 		/*
2061 		 * Needed, since GPIO might have disabled power
2062 		 * of some i2c devices
2063 		 */
2064 		em28xx_wake_i2c(dev);
2065 	}
2066 
2067 	if (vdev->vfl_type == VFL_TYPE_RADIO) {
2068 		em28xx_videodbg("video_open: setting radio device\n");
2069 		v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_radio);
2070 	}
2071 
2072 	kref_get(&dev->ref);
2073 	kref_get(&v4l2->ref);
2074 	v4l2->users++;
2075 
2076 	mutex_unlock(&dev->lock);
2077 
2078 	return 0;
2079 }
2080 
2081 /*
2082  * em28xx_v4l2_fini()
2083  * unregisters the v4l2,i2c and usb devices
2084  * called when the device gets disconected or at module unload
2085 */
2086 static int em28xx_v4l2_fini(struct em28xx *dev)
2087 {
2088 	struct em28xx_v4l2 *v4l2 = dev->v4l2;
2089 
2090 	if (dev->is_audio_only) {
2091 		/* Shouldn't initialize IR for this interface */
2092 		return 0;
2093 	}
2094 
2095 	if (!dev->has_video) {
2096 		/* This device does not support the v4l2 extension */
2097 		return 0;
2098 	}
2099 
2100 	if (v4l2 == NULL)
2101 		return 0;
2102 
2103 	pr_info("Closing video extension\n");
2104 
2105 	mutex_lock(&dev->lock);
2106 
2107 	v4l2_device_disconnect(&v4l2->v4l2_dev);
2108 
2109 	em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
2110 
2111 	em28xx_v4l2_media_release(dev);
2112 
2113 	if (video_is_registered(&v4l2->radio_dev)) {
2114 		pr_info("V4L2 device %s deregistered\n",
2115 			video_device_node_name(&v4l2->radio_dev));
2116 		video_unregister_device(&v4l2->radio_dev);
2117 	}
2118 	if (video_is_registered(&v4l2->vbi_dev)) {
2119 		pr_info("V4L2 device %s deregistered\n",
2120 			video_device_node_name(&v4l2->vbi_dev));
2121 		video_unregister_device(&v4l2->vbi_dev);
2122 	}
2123 	if (video_is_registered(&v4l2->vdev)) {
2124 		pr_info("V4L2 device %s deregistered\n",
2125 			video_device_node_name(&v4l2->vdev));
2126 		video_unregister_device(&v4l2->vdev);
2127 	}
2128 
2129 	v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2130 	v4l2_device_unregister(&v4l2->v4l2_dev);
2131 
2132 	if (v4l2->clk) {
2133 		v4l2_clk_unregister_fixed(v4l2->clk);
2134 		v4l2->clk = NULL;
2135 	}
2136 
2137 	kref_put(&v4l2->ref, em28xx_free_v4l2);
2138 
2139 	mutex_unlock(&dev->lock);
2140 
2141 	kref_put(&dev->ref, em28xx_free_device);
2142 
2143 	return 0;
2144 }
2145 
2146 static int em28xx_v4l2_suspend(struct em28xx *dev)
2147 {
2148 	if (dev->is_audio_only)
2149 		return 0;
2150 
2151 	if (!dev->has_video)
2152 		return 0;
2153 
2154 	pr_info("Suspending video extension\n");
2155 	em28xx_stop_urbs(dev);
2156 	return 0;
2157 }
2158 
2159 static int em28xx_v4l2_resume(struct em28xx *dev)
2160 {
2161 	if (dev->is_audio_only)
2162 		return 0;
2163 
2164 	if (!dev->has_video)
2165 		return 0;
2166 
2167 	pr_info("Resuming video extension\n");
2168 	/* what do we do here */
2169 	return 0;
2170 }
2171 
2172 /*
2173  * em28xx_v4l2_close()
2174  * stops streaming and deallocates all resources allocated by the v4l2
2175  * calls and ioctls
2176  */
2177 static int em28xx_v4l2_close(struct file *filp)
2178 {
2179 	struct em28xx         *dev  = video_drvdata(filp);
2180 	struct em28xx_v4l2    *v4l2 = dev->v4l2;
2181 	int              errCode;
2182 
2183 	em28xx_videodbg("users=%d\n", v4l2->users);
2184 
2185 	vb2_fop_release(filp);
2186 	mutex_lock(&dev->lock);
2187 
2188 	if (v4l2->users == 1) {
2189 		/* No sense to try to write to the device */
2190 		if (dev->disconnected)
2191 			goto exit;
2192 
2193 		/* Save some power by putting tuner to sleep */
2194 		v4l2_device_call_all(&v4l2->v4l2_dev, 0, core, s_power, 0);
2195 
2196 		/* do this before setting alternate! */
2197 		em28xx_set_mode(dev, EM28XX_SUSPEND);
2198 
2199 		/* set alternate 0 */
2200 		dev->alt = 0;
2201 		em28xx_videodbg("setting alternate 0\n");
2202 		errCode = usb_set_interface(dev->udev, 0, 0);
2203 		if (errCode < 0) {
2204 			pr_err("cannot change alternate number to 0 (error=%i)\n",
2205 			       errCode);
2206 		}
2207 	}
2208 
2209 exit:
2210 	v4l2->users--;
2211 	kref_put(&v4l2->ref, em28xx_free_v4l2);
2212 	mutex_unlock(&dev->lock);
2213 	kref_put(&dev->ref, em28xx_free_device);
2214 
2215 	return 0;
2216 }
2217 
2218 static const struct v4l2_file_operations em28xx_v4l_fops = {
2219 	.owner         = THIS_MODULE,
2220 	.open          = em28xx_v4l2_open,
2221 	.release       = em28xx_v4l2_close,
2222 	.read          = vb2_fop_read,
2223 	.poll          = vb2_fop_poll,
2224 	.mmap          = vb2_fop_mmap,
2225 	.unlocked_ioctl = video_ioctl2,
2226 };
2227 
2228 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2229 	.vidioc_querycap            = vidioc_querycap,
2230 	.vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
2231 	.vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
2232 	.vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
2233 	.vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
2234 	.vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2235 	.vidioc_try_fmt_vbi_cap     = vidioc_g_fmt_vbi_cap,
2236 	.vidioc_s_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2237 	.vidioc_enum_framesizes     = vidioc_enum_framesizes,
2238 	.vidioc_g_audio             = vidioc_g_audio,
2239 	.vidioc_s_audio             = vidioc_s_audio,
2240 
2241 	.vidioc_reqbufs             = vb2_ioctl_reqbufs,
2242 	.vidioc_create_bufs         = vb2_ioctl_create_bufs,
2243 	.vidioc_prepare_buf         = vb2_ioctl_prepare_buf,
2244 	.vidioc_querybuf            = vb2_ioctl_querybuf,
2245 	.vidioc_qbuf                = vb2_ioctl_qbuf,
2246 	.vidioc_dqbuf               = vb2_ioctl_dqbuf,
2247 
2248 	.vidioc_g_std               = vidioc_g_std,
2249 	.vidioc_querystd            = vidioc_querystd,
2250 	.vidioc_s_std               = vidioc_s_std,
2251 	.vidioc_g_parm		    = vidioc_g_parm,
2252 	.vidioc_s_parm		    = vidioc_s_parm,
2253 	.vidioc_enum_input          = vidioc_enum_input,
2254 	.vidioc_g_input             = vidioc_g_input,
2255 	.vidioc_s_input             = vidioc_s_input,
2256 	.vidioc_streamon            = vb2_ioctl_streamon,
2257 	.vidioc_streamoff           = vb2_ioctl_streamoff,
2258 	.vidioc_g_tuner             = vidioc_g_tuner,
2259 	.vidioc_s_tuner             = vidioc_s_tuner,
2260 	.vidioc_g_frequency         = vidioc_g_frequency,
2261 	.vidioc_s_frequency         = vidioc_s_frequency,
2262 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2263 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2264 #ifdef CONFIG_VIDEO_ADV_DEBUG
2265 	.vidioc_g_chip_info         = vidioc_g_chip_info,
2266 	.vidioc_g_register          = vidioc_g_register,
2267 	.vidioc_s_register          = vidioc_s_register,
2268 #endif
2269 };
2270 
2271 static const struct video_device em28xx_video_template = {
2272 	.fops		= &em28xx_v4l_fops,
2273 	.ioctl_ops	= &video_ioctl_ops,
2274 	.release	= video_device_release_empty,
2275 	.tvnorms	= V4L2_STD_ALL,
2276 };
2277 
2278 static const struct v4l2_file_operations radio_fops = {
2279 	.owner         = THIS_MODULE,
2280 	.open          = em28xx_v4l2_open,
2281 	.release       = em28xx_v4l2_close,
2282 	.unlocked_ioctl = video_ioctl2,
2283 };
2284 
2285 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2286 	.vidioc_querycap      = vidioc_querycap,
2287 	.vidioc_g_tuner       = radio_g_tuner,
2288 	.vidioc_s_tuner       = radio_s_tuner,
2289 	.vidioc_g_frequency   = vidioc_g_frequency,
2290 	.vidioc_s_frequency   = vidioc_s_frequency,
2291 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2292 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2293 #ifdef CONFIG_VIDEO_ADV_DEBUG
2294 	.vidioc_g_chip_info   = vidioc_g_chip_info,
2295 	.vidioc_g_register    = vidioc_g_register,
2296 	.vidioc_s_register    = vidioc_s_register,
2297 #endif
2298 };
2299 
2300 static struct video_device em28xx_radio_template = {
2301 	.fops		= &radio_fops,
2302 	.ioctl_ops	= &radio_ioctl_ops,
2303 	.release	= video_device_release_empty,
2304 };
2305 
2306 /* I2C possible address to saa7115, tvp5150, msp3400, tvaudio */
2307 static unsigned short saa711x_addrs[] = {
2308 	0x4a >> 1, 0x48 >> 1,   /* SAA7111, SAA7111A and SAA7113 */
2309 	0x42 >> 1, 0x40 >> 1,   /* SAA7114, SAA7115 and SAA7118 */
2310 	I2C_CLIENT_END };
2311 
2312 static unsigned short tvp5150_addrs[] = {
2313 	0xb8 >> 1,
2314 	0xba >> 1,
2315 	I2C_CLIENT_END
2316 };
2317 
2318 static unsigned short msp3400_addrs[] = {
2319 	0x80 >> 1,
2320 	0x88 >> 1,
2321 	I2C_CLIENT_END
2322 };
2323 
2324 /******************************** usb interface ******************************/
2325 
2326 static void em28xx_vdev_init(struct em28xx *dev,
2327 			     struct video_device *vfd,
2328 			     const struct video_device *template,
2329 			     const char *type_name)
2330 {
2331 	*vfd		= *template;
2332 	vfd->v4l2_dev	= &dev->v4l2->v4l2_dev;
2333 	vfd->lock	= &dev->lock;
2334 	if (dev->board.is_webcam)
2335 		vfd->tvnorms = 0;
2336 
2337 	snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2338 		 dev->name, type_name);
2339 
2340 	video_set_drvdata(vfd, dev);
2341 }
2342 
2343 static void em28xx_tuner_setup(struct em28xx *dev, unsigned short tuner_addr)
2344 {
2345 	struct em28xx_v4l2      *v4l2 = dev->v4l2;
2346 	struct v4l2_device      *v4l2_dev = &v4l2->v4l2_dev;
2347 	struct tuner_setup      tun_setup;
2348 	struct v4l2_frequency   f;
2349 
2350 	memset(&tun_setup, 0, sizeof(tun_setup));
2351 
2352 	tun_setup.mode_mask = T_ANALOG_TV | T_RADIO;
2353 	tun_setup.tuner_callback = em28xx_tuner_callback;
2354 
2355 	if (dev->board.radio.type) {
2356 		tun_setup.type = dev->board.radio.type;
2357 		tun_setup.addr = dev->board.radio_addr;
2358 
2359 		v4l2_device_call_all(v4l2_dev,
2360 				     0, tuner, s_type_addr, &tun_setup);
2361 	}
2362 
2363 	if ((dev->tuner_type != TUNER_ABSENT) && (dev->tuner_type)) {
2364 		tun_setup.type   = dev->tuner_type;
2365 		tun_setup.addr   = tuner_addr;
2366 
2367 		v4l2_device_call_all(v4l2_dev,
2368 				     0, tuner, s_type_addr, &tun_setup);
2369 	}
2370 
2371 	if (dev->board.tda9887_conf) {
2372 		struct v4l2_priv_tun_config tda9887_cfg;
2373 
2374 		tda9887_cfg.tuner = TUNER_TDA9887;
2375 		tda9887_cfg.priv = &dev->board.tda9887_conf;
2376 
2377 		v4l2_device_call_all(v4l2_dev,
2378 				     0, tuner, s_config, &tda9887_cfg);
2379 	}
2380 
2381 	if (dev->tuner_type == TUNER_XC2028) {
2382 		struct v4l2_priv_tun_config  xc2028_cfg;
2383 		struct xc2028_ctrl           ctl;
2384 
2385 		memset(&xc2028_cfg, 0, sizeof(xc2028_cfg));
2386 		memset(&ctl, 0, sizeof(ctl));
2387 
2388 		em28xx_setup_xc3028(dev, &ctl);
2389 
2390 		xc2028_cfg.tuner = TUNER_XC2028;
2391 		xc2028_cfg.priv  = &ctl;
2392 
2393 		v4l2_device_call_all(v4l2_dev, 0, tuner, s_config, &xc2028_cfg);
2394 	}
2395 
2396 	/* configure tuner */
2397 	f.tuner = 0;
2398 	f.type = V4L2_TUNER_ANALOG_TV;
2399 	f.frequency = 9076;     /* just a magic number */
2400 	v4l2->frequency = f.frequency;
2401 	v4l2_device_call_all(v4l2_dev, 0, tuner, s_frequency, &f);
2402 }
2403 
2404 static int em28xx_v4l2_init(struct em28xx *dev)
2405 {
2406 	u8 val;
2407 	int ret;
2408 	unsigned int maxw;
2409 	struct v4l2_ctrl_handler *hdl;
2410 	struct em28xx_v4l2 *v4l2;
2411 
2412 	if (dev->is_audio_only) {
2413 		/* Shouldn't initialize IR for this interface */
2414 		return 0;
2415 	}
2416 
2417 	if (!dev->has_video) {
2418 		/* This device does not support the v4l2 extension */
2419 		return 0;
2420 	}
2421 
2422 	pr_info("Registering V4L2 extension\n");
2423 
2424 	mutex_lock(&dev->lock);
2425 
2426 	v4l2 = kzalloc(sizeof(struct em28xx_v4l2), GFP_KERNEL);
2427 	if (!v4l2) {
2428 		mutex_unlock(&dev->lock);
2429 		return -ENOMEM;
2430 	}
2431 	kref_init(&v4l2->ref);
2432 	v4l2->dev = dev;
2433 	dev->v4l2 = v4l2;
2434 
2435 #ifdef CONFIG_MEDIA_CONTROLLER
2436 	v4l2->v4l2_dev.mdev = dev->media_dev;
2437 #endif
2438 	ret = v4l2_device_register(&dev->udev->dev, &v4l2->v4l2_dev);
2439 	if (ret < 0) {
2440 		pr_err("Call to v4l2_device_register() failed!\n");
2441 		goto err;
2442 	}
2443 
2444 	hdl = &v4l2->ctrl_handler;
2445 	v4l2_ctrl_handler_init(hdl, 8);
2446 	v4l2->v4l2_dev.ctrl_handler = hdl;
2447 
2448 	if (dev->board.is_webcam)
2449 		v4l2->progressive = true;
2450 
2451 	/*
2452 	 * Default format, used for tvp5150 or saa711x output formats
2453 	 */
2454 	v4l2->vinmode = 0x10;
2455 	v4l2->vinctl  = EM28XX_VINCTRL_INTERLACED |
2456 			EM28XX_VINCTRL_CCIR656_ENABLE;
2457 
2458 	/* request some modules */
2459 
2460 	if (dev->board.has_msp34xx)
2461 		v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2462 				    &dev->i2c_adap[dev->def_i2c_bus],
2463 				    "msp3400", 0, msp3400_addrs);
2464 
2465 	if (dev->board.decoder == EM28XX_SAA711X)
2466 		v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2467 				    &dev->i2c_adap[dev->def_i2c_bus],
2468 				    "saa7115_auto", 0, saa711x_addrs);
2469 
2470 	if (dev->board.decoder == EM28XX_TVP5150)
2471 		v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2472 				    &dev->i2c_adap[dev->def_i2c_bus],
2473 				    "tvp5150", 0, tvp5150_addrs);
2474 
2475 	if (dev->board.adecoder == EM28XX_TVAUDIO)
2476 		v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2477 				    &dev->i2c_adap[dev->def_i2c_bus],
2478 				    "tvaudio", dev->board.tvaudio_addr, NULL);
2479 
2480 	/* Initialize tuner and camera */
2481 
2482 	if (dev->board.tuner_type != TUNER_ABSENT) {
2483 		unsigned short tuner_addr = dev->board.tuner_addr;
2484 		int has_demod = (dev->board.tda9887_conf & TDA9887_PRESENT);
2485 
2486 		if (dev->board.radio.type)
2487 			v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2488 					    &dev->i2c_adap[dev->def_i2c_bus],
2489 					    "tuner", dev->board.radio_addr,
2490 					    NULL);
2491 
2492 		if (has_demod)
2493 			v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2494 					    &dev->i2c_adap[dev->def_i2c_bus],
2495 					    "tuner", 0,
2496 					    v4l2_i2c_tuner_addrs(ADDRS_DEMOD));
2497 		if (tuner_addr == 0) {
2498 			enum v4l2_i2c_tuner_type type =
2499 				has_demod ? ADDRS_TV_WITH_DEMOD : ADDRS_TV;
2500 			struct v4l2_subdev *sd;
2501 
2502 			sd = v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2503 						 &dev->i2c_adap[dev->def_i2c_bus],
2504 						 "tuner", 0,
2505 						 v4l2_i2c_tuner_addrs(type));
2506 
2507 			if (sd)
2508 				tuner_addr = v4l2_i2c_subdev_addr(sd);
2509 		} else {
2510 			v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2511 					    &dev->i2c_adap[dev->def_i2c_bus],
2512 					    "tuner", tuner_addr, NULL);
2513 		}
2514 
2515 		em28xx_tuner_setup(dev, tuner_addr);
2516 	}
2517 
2518 	if (dev->em28xx_sensor != EM28XX_NOSENSOR)
2519 		em28xx_init_camera(dev);
2520 
2521 	/* Configure audio */
2522 	ret = em28xx_audio_setup(dev);
2523 	if (ret < 0) {
2524 		pr_err("%s: Error while setting audio - error [%d]!\n",
2525 		       __func__, ret);
2526 		goto unregister_dev;
2527 	}
2528 	if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
2529 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2530 				  V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
2531 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2532 				  V4L2_CID_AUDIO_VOLUME, 0, 0x1f, 1, 0x1f);
2533 	} else {
2534 		/* install the em28xx notify callback */
2535 		v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_MUTE),
2536 				 em28xx_ctrl_notify, dev);
2537 		v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_VOLUME),
2538 				 em28xx_ctrl_notify, dev);
2539 	}
2540 
2541 	/* wake i2c devices */
2542 	em28xx_wake_i2c(dev);
2543 
2544 	/* init video dma queues */
2545 	INIT_LIST_HEAD(&dev->vidq.active);
2546 	INIT_LIST_HEAD(&dev->vbiq.active);
2547 
2548 	if (dev->board.has_msp34xx) {
2549 		/* Send a reset to other chips via gpio */
2550 		ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xf7);
2551 		if (ret < 0) {
2552 			pr_err("%s: em28xx_write_reg - msp34xx(1) failed! error [%d]\n",
2553 			       __func__, ret);
2554 			goto unregister_dev;
2555 		}
2556 		msleep(3);
2557 
2558 		ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xff);
2559 		if (ret < 0) {
2560 			pr_err("%s: em28xx_write_reg - msp34xx(2) failed! error [%d]\n",
2561 			       __func__, ret);
2562 			goto unregister_dev;
2563 		}
2564 		msleep(3);
2565 	}
2566 
2567 	/* set default norm */
2568 	v4l2->norm = V4L2_STD_PAL;
2569 	v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
2570 	v4l2->interlaced_fieldmode = EM28XX_INTERLACED_DEFAULT;
2571 
2572 	/* Analog specific initialization */
2573 	v4l2->format = &format[0];
2574 
2575 	maxw = norm_maxw(dev);
2576 	/* MaxPacketSize for em2800 is too small to capture at full resolution
2577 	 * use half of maxw as the scaler can only scale to 50% */
2578 	if (dev->board.is_em2800)
2579 		maxw /= 2;
2580 
2581 	em28xx_set_video_format(dev, format[0].fourcc,
2582 				maxw, norm_maxh(dev));
2583 
2584 	video_mux(dev, 0);
2585 
2586 	/* Audio defaults */
2587 	dev->mute = 1;
2588 	dev->volume = 0x1f;
2589 
2590 /*	em28xx_write_reg(dev, EM28XX_R0E_AUDIOSRC, 0xc0); audio register */
2591 	val = (u8)em28xx_read_reg(dev, EM28XX_R0F_XCLK);
2592 	em28xx_write_reg(dev, EM28XX_R0F_XCLK,
2593 			 (EM28XX_XCLK_AUDIO_UNMUTE | val));
2594 
2595 	em28xx_set_outfmt(dev);
2596 
2597 	/* Add image controls */
2598 	/* NOTE: at this point, the subdevices are already registered, so bridge
2599 	 * controls are only added/enabled when no subdevice provides them */
2600 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_CONTRAST))
2601 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2602 				  V4L2_CID_CONTRAST,
2603 				  0, 0x1f, 1, CONTRAST_DEFAULT);
2604 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_BRIGHTNESS))
2605 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2606 				  V4L2_CID_BRIGHTNESS,
2607 				  -0x80, 0x7f, 1, BRIGHTNESS_DEFAULT);
2608 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_SATURATION))
2609 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2610 				  V4L2_CID_SATURATION,
2611 				  0, 0x1f, 1, SATURATION_DEFAULT);
2612 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_BLUE_BALANCE))
2613 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2614 				  V4L2_CID_BLUE_BALANCE,
2615 				  -0x30, 0x30, 1, BLUE_BALANCE_DEFAULT);
2616 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_RED_BALANCE))
2617 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2618 				  V4L2_CID_RED_BALANCE,
2619 				  -0x30, 0x30, 1, RED_BALANCE_DEFAULT);
2620 	if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_SHARPNESS))
2621 		v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2622 				  V4L2_CID_SHARPNESS,
2623 				  0, 0x0f, 1, SHARPNESS_DEFAULT);
2624 
2625 	/* Reset image controls */
2626 	em28xx_colorlevels_set_default(dev);
2627 	v4l2_ctrl_handler_setup(hdl);
2628 	ret = hdl->error;
2629 	if (ret)
2630 		goto unregister_dev;
2631 
2632 	/* allocate and fill video video_device struct */
2633 	em28xx_vdev_init(dev, &v4l2->vdev, &em28xx_video_template, "video");
2634 	mutex_init(&v4l2->vb_queue_lock);
2635 	mutex_init(&v4l2->vb_vbi_queue_lock);
2636 	v4l2->vdev.queue = &v4l2->vb_vidq;
2637 	v4l2->vdev.queue->lock = &v4l2->vb_queue_lock;
2638 
2639 	/* disable inapplicable ioctls */
2640 	if (dev->board.is_webcam) {
2641 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_QUERYSTD);
2642 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_STD);
2643 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_STD);
2644 	} else {
2645 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_PARM);
2646 	}
2647 	if (dev->tuner_type == TUNER_ABSENT) {
2648 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_TUNER);
2649 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_TUNER);
2650 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_FREQUENCY);
2651 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_FREQUENCY);
2652 	}
2653 	if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2654 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_AUDIO);
2655 		v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_AUDIO);
2656 	}
2657 
2658 	/* register v4l2 video video_device */
2659 	ret = video_register_device(&v4l2->vdev, VFL_TYPE_GRABBER,
2660 				    video_nr[dev->devno]);
2661 	if (ret) {
2662 		pr_err("unable to register video device (error=%i).\n", ret);
2663 		goto unregister_dev;
2664 	}
2665 
2666 	/* Allocate and fill vbi video_device struct */
2667 	if (em28xx_vbi_supported(dev) == 1) {
2668 		em28xx_vdev_init(dev, &v4l2->vbi_dev, &em28xx_video_template,
2669 				"vbi");
2670 
2671 		v4l2->vbi_dev.queue = &v4l2->vb_vbiq;
2672 		v4l2->vbi_dev.queue->lock = &v4l2->vb_vbi_queue_lock;
2673 
2674 		/* disable inapplicable ioctls */
2675 		v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_PARM);
2676 		if (dev->tuner_type == TUNER_ABSENT) {
2677 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_TUNER);
2678 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_TUNER);
2679 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_FREQUENCY);
2680 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_FREQUENCY);
2681 		}
2682 		if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2683 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_AUDIO);
2684 			v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_AUDIO);
2685 		}
2686 
2687 		/* register v4l2 vbi video_device */
2688 		ret = video_register_device(&v4l2->vbi_dev, VFL_TYPE_VBI,
2689 					    vbi_nr[dev->devno]);
2690 		if (ret < 0) {
2691 			pr_err("unable to register vbi device\n");
2692 			goto unregister_dev;
2693 		}
2694 	}
2695 
2696 	if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2697 		em28xx_vdev_init(dev, &v4l2->radio_dev, &em28xx_radio_template,
2698 				   "radio");
2699 		ret = video_register_device(&v4l2->radio_dev, VFL_TYPE_RADIO,
2700 					    radio_nr[dev->devno]);
2701 		if (ret < 0) {
2702 			pr_err("can't register radio device\n");
2703 			goto unregister_dev;
2704 		}
2705 		pr_info("Registered radio device as %s\n",
2706 			video_device_node_name(&v4l2->radio_dev));
2707 	}
2708 
2709 	/* Init entities at the Media Controller */
2710 	em28xx_v4l2_create_entities(dev);
2711 
2712 #ifdef CONFIG_MEDIA_CONTROLLER
2713 	ret = v4l2_mc_create_media_graph(dev->media_dev);
2714 	if (ret) {
2715 		pr_err("failed to create media graph\n");
2716 		em28xx_v4l2_media_release(dev);
2717 		goto unregister_dev;
2718 	}
2719 #endif
2720 
2721 	pr_info("V4L2 video device registered as %s\n",
2722 		video_device_node_name(&v4l2->vdev));
2723 
2724 	if (video_is_registered(&v4l2->vbi_dev))
2725 		pr_info("V4L2 VBI device registered as %s\n",
2726 			video_device_node_name(&v4l2->vbi_dev));
2727 
2728 	/* Save some power by putting tuner to sleep */
2729 	v4l2_device_call_all(&v4l2->v4l2_dev, 0, core, s_power, 0);
2730 
2731 	/* initialize videobuf2 stuff */
2732 	em28xx_vb2_setup(dev);
2733 
2734 	pr_info("V4L2 extension successfully initialized\n");
2735 
2736 	kref_get(&dev->ref);
2737 
2738 	mutex_unlock(&dev->lock);
2739 	return 0;
2740 
2741 unregister_dev:
2742 	if (video_is_registered(&v4l2->radio_dev)) {
2743 		pr_info("V4L2 device %s deregistered\n",
2744 			video_device_node_name(&v4l2->radio_dev));
2745 		video_unregister_device(&v4l2->radio_dev);
2746 	}
2747 	if (video_is_registered(&v4l2->vbi_dev)) {
2748 		pr_info("V4L2 device %s deregistered\n",
2749 			video_device_node_name(&v4l2->vbi_dev));
2750 		video_unregister_device(&v4l2->vbi_dev);
2751 	}
2752 	if (video_is_registered(&v4l2->vdev)) {
2753 		pr_info("V4L2 device %s deregistered\n",
2754 			video_device_node_name(&v4l2->vdev));
2755 		video_unregister_device(&v4l2->vdev);
2756 	}
2757 
2758 	v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2759 	v4l2_device_unregister(&v4l2->v4l2_dev);
2760 err:
2761 	dev->v4l2 = NULL;
2762 	kref_put(&v4l2->ref, em28xx_free_v4l2);
2763 	mutex_unlock(&dev->lock);
2764 	return ret;
2765 }
2766 
2767 static struct em28xx_ops v4l2_ops = {
2768 	.id   = EM28XX_V4L2,
2769 	.name = "Em28xx v4l2 Extension",
2770 	.init = em28xx_v4l2_init,
2771 	.fini = em28xx_v4l2_fini,
2772 	.suspend = em28xx_v4l2_suspend,
2773 	.resume = em28xx_v4l2_resume,
2774 };
2775 
2776 static int __init em28xx_video_register(void)
2777 {
2778 	return em28xx_register_extension(&v4l2_ops);
2779 }
2780 
2781 static void __exit em28xx_video_unregister(void)
2782 {
2783 	em28xx_unregister_extension(&v4l2_ops);
2784 }
2785 
2786 module_init(em28xx_video_register);
2787 module_exit(em28xx_video_unregister);
2788