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