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