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