1 /*
2    em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB
3 		    video capture devices
4 
5    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
6 		      Markus Rechberger <mrechberger@gmail.com>
7 		      Mauro Carvalho Chehab <mchehab@infradead.org>
8 		      Sascha Sommer <saschasommer@freenet.de>
9    Copyright (C) 2012 Frank Schäfer <fschaefer.oss@googlemail.com>
10 
11 	Some parts based on SN9C10x PC Camera Controllers GPL driver made
12 		by Luca Risolia <luca.risolia@studio.unibo.it>
13 
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 2 of the License, or
17    (at your option) any later version.
18 
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23 
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  */
28 
29 #include <linux/init.h>
30 #include <linux/list.h>
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/bitmap.h>
34 #include <linux/usb.h>
35 #include <linux/i2c.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/slab.h>
39 
40 #include "em28xx.h"
41 #include <media/v4l2-common.h>
42 #include <media/v4l2-ioctl.h>
43 #include <media/v4l2-chip-ident.h>
44 #include <media/msp3400.h>
45 #include <media/tuner.h>
46 
47 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
48 		      "Markus Rechberger <mrechberger@gmail.com>, " \
49 		      "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
50 		      "Sascha Sommer <saschasommer@freenet.de>"
51 
52 #define DRIVER_DESC         "Empia em28xx based USB video device driver"
53 
54 #define EM28XX_VERSION "0.1.3"
55 
56 #define em28xx_videodbg(fmt, arg...) do {\
57 	if (video_debug) \
58 		printk(KERN_INFO "%s %s :"fmt, \
59 			 dev->name, __func__ , ##arg); } while (0)
60 
61 static unsigned int isoc_debug;
62 module_param(isoc_debug, int, 0644);
63 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
64 
65 #define em28xx_isocdbg(fmt, arg...) \
66 do {\
67 	if (isoc_debug) { \
68 		printk(KERN_INFO "%s %s :"fmt, \
69 			 dev->name, __func__ , ##arg); \
70 	} \
71   } while (0)
72 
73 MODULE_AUTHOR(DRIVER_AUTHOR);
74 MODULE_DESCRIPTION(DRIVER_DESC);
75 MODULE_LICENSE("GPL");
76 MODULE_VERSION(EM28XX_VERSION);
77 
78 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
79 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
80 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
81 
82 module_param_array(video_nr, int, NULL, 0444);
83 module_param_array(vbi_nr, int, NULL, 0444);
84 module_param_array(radio_nr, int, NULL, 0444);
85 MODULE_PARM_DESC(video_nr, "video device numbers");
86 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
87 MODULE_PARM_DESC(radio_nr, "radio device numbers");
88 
89 static unsigned int video_debug;
90 module_param(video_debug, int, 0644);
91 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
92 
93 /* supported video standards */
94 static struct em28xx_fmt format[] = {
95 	{
96 		.name     = "16 bpp YUY2, 4:2:2, packed",
97 		.fourcc   = V4L2_PIX_FMT_YUYV,
98 		.depth    = 16,
99 		.reg	  = EM28XX_OUTFMT_YUV422_Y0UY1V,
100 	}, {
101 		.name     = "16 bpp RGB 565, LE",
102 		.fourcc   = V4L2_PIX_FMT_RGB565,
103 		.depth    = 16,
104 		.reg      = EM28XX_OUTFMT_RGB_16_656,
105 	}, {
106 		.name     = "8 bpp Bayer BGBG..GRGR",
107 		.fourcc   = V4L2_PIX_FMT_SBGGR8,
108 		.depth    = 8,
109 		.reg      = EM28XX_OUTFMT_RGB_8_BGBG,
110 	}, {
111 		.name     = "8 bpp Bayer GRGR..BGBG",
112 		.fourcc   = V4L2_PIX_FMT_SGRBG8,
113 		.depth    = 8,
114 		.reg      = EM28XX_OUTFMT_RGB_8_GRGR,
115 	}, {
116 		.name     = "8 bpp Bayer GBGB..RGRG",
117 		.fourcc   = V4L2_PIX_FMT_SGBRG8,
118 		.depth    = 8,
119 		.reg      = EM28XX_OUTFMT_RGB_8_GBGB,
120 	}, {
121 		.name     = "12 bpp YUV411",
122 		.fourcc   = V4L2_PIX_FMT_YUV411P,
123 		.depth    = 12,
124 		.reg      = EM28XX_OUTFMT_YUV411,
125 	},
126 };
127 
128 /* ------------------------------------------------------------------
129 	DMA and thread functions
130    ------------------------------------------------------------------*/
131 
132 /*
133  * Finish the current buffer
134  */
135 static inline void finish_buffer(struct em28xx *dev,
136 				 struct em28xx_buffer *buf)
137 {
138 	em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
139 	buf->vb.state = VIDEOBUF_DONE;
140 	buf->vb.field_count++;
141 	v4l2_get_timestamp(&buf->vb.ts);
142 	list_del(&buf->vb.queue);
143 	wake_up(&buf->vb.done);
144 }
145 
146 /*
147  * Copy picture data from USB buffer to videobuf buffer
148  */
149 static void em28xx_copy_video(struct em28xx *dev,
150 			      struct em28xx_buffer *buf,
151 			      unsigned char *usb_buf,
152 			      unsigned long len)
153 {
154 	void *fieldstart, *startwrite, *startread;
155 	int  linesdone, currlinedone, offset, lencopy, remain;
156 	int bytesperline = dev->width << 1;
157 
158 	if (buf->pos + len > buf->vb.size)
159 		len = buf->vb.size - buf->pos;
160 
161 	startread = usb_buf;
162 	remain = len;
163 
164 	if (dev->progressive || buf->top_field)
165 		fieldstart = buf->vb_buf;
166 	else /* interlaced mode, even nr. of lines */
167 		fieldstart = buf->vb_buf + bytesperline;
168 
169 	linesdone = buf->pos / bytesperline;
170 	currlinedone = buf->pos % bytesperline;
171 
172 	if (dev->progressive)
173 		offset = linesdone * bytesperline + currlinedone;
174 	else
175 		offset = linesdone * bytesperline * 2 + currlinedone;
176 
177 	startwrite = fieldstart + offset;
178 	lencopy = bytesperline - currlinedone;
179 	lencopy = lencopy > remain ? remain : lencopy;
180 
181 	if ((char *)startwrite + lencopy > (char *)buf->vb_buf + buf->vb.size) {
182 		em28xx_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
183 			      ((char *)startwrite + lencopy) -
184 			      ((char *)buf->vb_buf + buf->vb.size));
185 		remain = (char *)buf->vb_buf + buf->vb.size -
186 			 (char *)startwrite;
187 		lencopy = remain;
188 	}
189 	if (lencopy <= 0)
190 		return;
191 	memcpy(startwrite, startread, lencopy);
192 
193 	remain -= lencopy;
194 
195 	while (remain > 0) {
196 		if (dev->progressive)
197 			startwrite += lencopy;
198 		else
199 			startwrite += lencopy + bytesperline;
200 		startread += lencopy;
201 		if (bytesperline > remain)
202 			lencopy = remain;
203 		else
204 			lencopy = bytesperline;
205 
206 		if ((char *)startwrite + lencopy > (char *)buf->vb_buf +
207 		    buf->vb.size) {
208 			em28xx_isocdbg("Overflow of %zi bytes past buffer end"
209 				       "(2)\n",
210 				       ((char *)startwrite + lencopy) -
211 				       ((char *)buf->vb_buf + buf->vb.size));
212 			lencopy = remain = (char *)buf->vb_buf + buf->vb.size -
213 					   (char *)startwrite;
214 		}
215 		if (lencopy <= 0)
216 			break;
217 
218 		memcpy(startwrite, startread, lencopy);
219 
220 		remain -= lencopy;
221 	}
222 
223 	buf->pos += len;
224 }
225 
226 /*
227  * Copy VBI data from USB buffer to videobuf buffer
228  */
229 static void em28xx_copy_vbi(struct em28xx *dev,
230 			    struct em28xx_buffer *buf,
231 			    unsigned char *usb_buf,
232 			    unsigned long len)
233 {
234 	unsigned int offset;
235 
236 	if (buf->pos + len > buf->vb.size)
237 		len = buf->vb.size - buf->pos;
238 
239 	offset = buf->pos;
240 	/* Make sure the bottom field populates the second half of the frame */
241 	if (buf->top_field == 0)
242 		offset += dev->vbi_width * dev->vbi_height;
243 
244 	memcpy(buf->vb_buf + offset, usb_buf, len);
245 	buf->pos += len;
246 }
247 
248 static inline void print_err_status(struct em28xx *dev,
249 				     int packet, int status)
250 {
251 	char *errmsg = "Unknown";
252 
253 	switch (status) {
254 	case -ENOENT:
255 		errmsg = "unlinked synchronuously";
256 		break;
257 	case -ECONNRESET:
258 		errmsg = "unlinked asynchronuously";
259 		break;
260 	case -ENOSR:
261 		errmsg = "Buffer error (overrun)";
262 		break;
263 	case -EPIPE:
264 		errmsg = "Stalled (device not responding)";
265 		break;
266 	case -EOVERFLOW:
267 		errmsg = "Babble (bad cable?)";
268 		break;
269 	case -EPROTO:
270 		errmsg = "Bit-stuff error (bad cable?)";
271 		break;
272 	case -EILSEQ:
273 		errmsg = "CRC/Timeout (could be anything)";
274 		break;
275 	case -ETIME:
276 		errmsg = "Device does not respond";
277 		break;
278 	}
279 	if (packet < 0) {
280 		em28xx_isocdbg("URB status %d [%s].\n",	status, errmsg);
281 	} else {
282 		em28xx_isocdbg("URB packet %d, status %d [%s].\n",
283 			       packet, status, errmsg);
284 	}
285 }
286 
287 /*
288  * get the next available buffer from dma queue
289  */
290 static inline struct em28xx_buffer *get_next_buf(struct em28xx *dev,
291 						 struct em28xx_dmaqueue *dma_q)
292 {
293 	struct em28xx_buffer *buf;
294 	char *outp;
295 
296 	if (list_empty(&dma_q->active)) {
297 		em28xx_isocdbg("No active queue to serve\n");
298 		return NULL;
299 	}
300 
301 	/* Get the next buffer */
302 	buf = list_entry(dma_q->active.next, struct em28xx_buffer, vb.queue);
303 	/* Cleans up buffer - Useful for testing for frame/URB loss */
304 	outp = videobuf_to_vmalloc(&buf->vb);
305 	memset(outp, 0, buf->vb.size);
306 	buf->pos = 0;
307 	buf->vb_buf = outp;
308 
309 	return buf;
310 }
311 
312 /*
313  * Finish the current buffer if completed and prepare for the next field
314  */
315 static struct em28xx_buffer *
316 finish_field_prepare_next(struct em28xx *dev,
317 			  struct em28xx_buffer *buf,
318 			  struct em28xx_dmaqueue *dma_q)
319 {
320 	if (dev->progressive || dev->top_field) { /* Brand new frame */
321 		if (buf != NULL)
322 			finish_buffer(dev, buf);
323 		buf = get_next_buf(dev, dma_q);
324 	}
325 	if (buf != NULL) {
326 		buf->top_field = dev->top_field;
327 		buf->pos = 0;
328 	}
329 
330 	return buf;
331 }
332 
333 /*
334  * Process data packet according to the em2710/em2750/em28xx frame data format
335  */
336 static inline void process_frame_data_em28xx(struct em28xx *dev,
337 					     unsigned char *data_pkt,
338 					     unsigned int  data_len)
339 {
340 	struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
341 	struct em28xx_buffer    *vbi_buf = dev->usb_ctl.vbi_buf;
342 	struct em28xx_dmaqueue  *dma_q = &dev->vidq;
343 	struct em28xx_dmaqueue  *vbi_dma_q = &dev->vbiq;
344 
345 	/* capture type 0 = vbi start
346 	   capture type 1 = vbi in progress
347 	   capture type 2 = video start
348 	   capture type 3 = video in progress */
349 	if (data_len >= 4) {
350 		/* NOTE: Headers are always 4 bytes and
351 		 * never split across packets */
352 		if (data_pkt[0] == 0x88 && data_pkt[1] == 0x88 &&
353 		    data_pkt[2] == 0x88 && data_pkt[3] == 0x88) {
354 			/* Continuation */
355 			data_pkt += 4;
356 			data_len -= 4;
357 		} else if (data_pkt[0] == 0x33 && data_pkt[1] == 0x95) {
358 			/* Field start (VBI mode) */
359 			dev->capture_type = 0;
360 			dev->vbi_read = 0;
361 			em28xx_isocdbg("VBI START HEADER !!!\n");
362 			dev->top_field = !(data_pkt[2] & 1);
363 			data_pkt += 4;
364 			data_len -= 4;
365 		} else if (data_pkt[0] == 0x22 && data_pkt[1] == 0x5a) {
366 			/* Field start (VBI disabled) */
367 			dev->capture_type = 2;
368 			em28xx_isocdbg("VIDEO START HEADER !!!\n");
369 			dev->top_field = !(data_pkt[2] & 1);
370 			data_pkt += 4;
371 			data_len -= 4;
372 		}
373 	}
374 	/* NOTE: With bulk transfers, intermediate data packets
375 	 * have no continuation header */
376 
377 	if (dev->capture_type == 0) {
378 		vbi_buf = finish_field_prepare_next(dev, vbi_buf, vbi_dma_q);
379 		dev->usb_ctl.vbi_buf = vbi_buf;
380 		dev->capture_type = 1;
381 	}
382 
383 	if (dev->capture_type == 1) {
384 		int vbi_size = dev->vbi_width * dev->vbi_height;
385 		int vbi_data_len = ((dev->vbi_read + data_len) > vbi_size) ?
386 				   (vbi_size - dev->vbi_read) : data_len;
387 
388 		/* Copy VBI data */
389 		if (vbi_buf != NULL)
390 			em28xx_copy_vbi(dev, vbi_buf, data_pkt, vbi_data_len);
391 		dev->vbi_read += vbi_data_len;
392 
393 		if (vbi_data_len < data_len) {
394 			/* Continue with copying video data */
395 			dev->capture_type = 2;
396 			data_pkt += vbi_data_len;
397 			data_len -= vbi_data_len;
398 		}
399 	}
400 
401 	if (dev->capture_type == 2) {
402 		buf = finish_field_prepare_next(dev, buf, dma_q);
403 		dev->usb_ctl.vid_buf = buf;
404 		dev->capture_type = 3;
405 	}
406 
407 	if (dev->capture_type == 3 && buf != NULL && data_len > 0)
408 		em28xx_copy_video(dev, buf, data_pkt, data_len);
409 }
410 
411 /* Processes and copies the URB data content (video and VBI data) */
412 static inline int em28xx_urb_data_copy(struct em28xx *dev, struct urb *urb)
413 {
414 	int xfer_bulk, num_packets, i;
415 	unsigned char *usb_data_pkt;
416 	unsigned int usb_data_len;
417 
418 	if (!dev)
419 		return 0;
420 
421 	if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
422 		return 0;
423 
424 	if (urb->status < 0)
425 		print_err_status(dev, -1, urb->status);
426 
427 	xfer_bulk = usb_pipebulk(urb->pipe);
428 
429 	if (xfer_bulk) /* bulk */
430 		num_packets = 1;
431 	else /* isoc */
432 		num_packets = urb->number_of_packets;
433 
434 	for (i = 0; i < num_packets; i++) {
435 		if (xfer_bulk) { /* bulk */
436 			usb_data_len = urb->actual_length;
437 
438 			usb_data_pkt = urb->transfer_buffer;
439 		} else { /* isoc */
440 			if (urb->iso_frame_desc[i].status < 0) {
441 				print_err_status(dev, i,
442 						 urb->iso_frame_desc[i].status);
443 				if (urb->iso_frame_desc[i].status != -EPROTO)
444 					continue;
445 			}
446 
447 			usb_data_len = urb->iso_frame_desc[i].actual_length;
448 			if (usb_data_len > dev->max_pkt_size) {
449 				em28xx_isocdbg("packet bigger than packet size");
450 				continue;
451 			}
452 
453 			usb_data_pkt = urb->transfer_buffer +
454 				       urb->iso_frame_desc[i].offset;
455 		}
456 
457 		if (usb_data_len == 0) {
458 			/* NOTE: happens very often with isoc transfers */
459 			/* em28xx_usbdbg("packet %d is empty",i); - spammy */
460 			continue;
461 		}
462 
463 		process_frame_data_em28xx(dev, usb_data_pkt, usb_data_len);
464 	}
465 	return 1;
466 }
467 
468 
469 /* ------------------------------------------------------------------
470 	Videobuf operations
471    ------------------------------------------------------------------*/
472 
473 static int
474 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
475 {
476 	struct em28xx_fh *fh = vq->priv_data;
477 	struct em28xx        *dev = fh->dev;
478 	struct v4l2_frequency f;
479 
480 	*size = (fh->dev->width * fh->dev->height * dev->format->depth + 7)
481 		>> 3;
482 
483 	if (0 == *count)
484 		*count = EM28XX_DEF_BUF;
485 
486 	if (*count < EM28XX_MIN_BUF)
487 		*count = EM28XX_MIN_BUF;
488 
489 	/* Ask tuner to go to analog or radio mode */
490 	memset(&f, 0, sizeof(f));
491 	f.frequency = dev->ctl_freq;
492 	f.type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
493 
494 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, &f);
495 
496 	return 0;
497 }
498 
499 /* This is called *without* dev->slock held; please keep it that way */
500 static void free_buffer(struct videobuf_queue *vq, struct em28xx_buffer *buf)
501 {
502 	struct em28xx_fh     *fh  = vq->priv_data;
503 	struct em28xx        *dev = fh->dev;
504 	unsigned long flags = 0;
505 	if (in_interrupt())
506 		BUG();
507 
508 	/* We used to wait for the buffer to finish here, but this didn't work
509 	   because, as we were keeping the state as VIDEOBUF_QUEUED,
510 	   videobuf_queue_cancel marked it as finished for us.
511 	   (Also, it could wedge forever if the hardware was misconfigured.)
512 
513 	   This should be safe; by the time we get here, the buffer isn't
514 	   queued anymore. If we ever start marking the buffers as
515 	   VIDEOBUF_ACTIVE, it won't be, though.
516 	*/
517 	spin_lock_irqsave(&dev->slock, flags);
518 	if (dev->usb_ctl.vid_buf == buf)
519 		dev->usb_ctl.vid_buf = NULL;
520 	spin_unlock_irqrestore(&dev->slock, flags);
521 
522 	videobuf_vmalloc_free(&buf->vb);
523 	buf->vb.state = VIDEOBUF_NEEDS_INIT;
524 }
525 
526 static int
527 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
528 						enum v4l2_field field)
529 {
530 	struct em28xx_fh     *fh  = vq->priv_data;
531 	struct em28xx_buffer *buf = container_of(vb, struct em28xx_buffer, vb);
532 	struct em28xx        *dev = fh->dev;
533 	int                  rc = 0, urb_init = 0;
534 
535 	buf->vb.size = (fh->dev->width * fh->dev->height * dev->format->depth
536 			+ 7) >> 3;
537 
538 	if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
539 		return -EINVAL;
540 
541 	buf->vb.width  = dev->width;
542 	buf->vb.height = dev->height;
543 	buf->vb.field  = field;
544 
545 	if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
546 		rc = videobuf_iolock(vq, &buf->vb, NULL);
547 		if (rc < 0)
548 			goto fail;
549 	}
550 
551 	if (!dev->usb_ctl.analog_bufs.num_bufs)
552 		urb_init = 1;
553 
554 	if (urb_init) {
555 		dev->capture_type = -1;
556 		rc = em28xx_init_usb_xfer(dev, EM28XX_ANALOG_MODE,
557 					  dev->analog_xfer_bulk,
558 					  EM28XX_NUM_BUFS,
559 					  dev->max_pkt_size,
560 					  dev->packet_multiplier,
561 					  em28xx_urb_data_copy);
562 		if (rc < 0)
563 			goto fail;
564 	}
565 
566 	buf->vb.state = VIDEOBUF_PREPARED;
567 	return 0;
568 
569 fail:
570 	free_buffer(vq, buf);
571 	return rc;
572 }
573 
574 static void
575 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
576 {
577 	struct em28xx_buffer    *buf     = container_of(vb,
578 							struct em28xx_buffer,
579 							vb);
580 	struct em28xx_fh        *fh      = vq->priv_data;
581 	struct em28xx           *dev     = fh->dev;
582 	struct em28xx_dmaqueue  *vidq    = &dev->vidq;
583 
584 	buf->vb.state = VIDEOBUF_QUEUED;
585 	list_add_tail(&buf->vb.queue, &vidq->active);
586 
587 }
588 
589 static void buffer_release(struct videobuf_queue *vq,
590 				struct videobuf_buffer *vb)
591 {
592 	struct em28xx_buffer   *buf  = container_of(vb,
593 						    struct em28xx_buffer,
594 						    vb);
595 	struct em28xx_fh       *fh   = vq->priv_data;
596 	struct em28xx          *dev  = (struct em28xx *)fh->dev;
597 
598 	em28xx_isocdbg("em28xx: called buffer_release\n");
599 
600 	free_buffer(vq, buf);
601 }
602 
603 static struct videobuf_queue_ops em28xx_video_qops = {
604 	.buf_setup      = buffer_setup,
605 	.buf_prepare    = buffer_prepare,
606 	.buf_queue      = buffer_queue,
607 	.buf_release    = buffer_release,
608 };
609 
610 /*********************  v4l2 interface  **************************************/
611 
612 static void video_mux(struct em28xx *dev, int index)
613 {
614 	dev->ctl_input = index;
615 	dev->ctl_ainput = INPUT(index)->amux;
616 	dev->ctl_aoutput = INPUT(index)->aout;
617 
618 	if (!dev->ctl_aoutput)
619 		dev->ctl_aoutput = EM28XX_AOUT_MASTER;
620 
621 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_routing,
622 			INPUT(index)->vmux, 0, 0);
623 
624 	if (dev->board.has_msp34xx) {
625 		if (dev->i2s_speed) {
626 			v4l2_device_call_all(&dev->v4l2_dev, 0, audio,
627 				s_i2s_clock_freq, dev->i2s_speed);
628 		}
629 		/* Note: this is msp3400 specific */
630 		v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
631 			 dev->ctl_ainput, MSP_OUTPUT(MSP_SC_IN_DSP_SCART1), 0);
632 	}
633 
634 	if (dev->board.adecoder != EM28XX_NOADECODER) {
635 		v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
636 			dev->ctl_ainput, dev->ctl_aoutput, 0);
637 	}
638 
639 	em28xx_audio_analog_set(dev);
640 }
641 
642 /* Usage lock check functions */
643 static int res_get(struct em28xx_fh *fh, unsigned int bit)
644 {
645 	struct em28xx    *dev = fh->dev;
646 
647 	if (fh->resources & bit)
648 		/* have it already allocated */
649 		return 1;
650 
651 	/* is it free? */
652 	if (dev->resources & bit) {
653 		/* no, someone else uses it */
654 		return 0;
655 	}
656 	/* it's free, grab it */
657 	fh->resources  |= bit;
658 	dev->resources |= bit;
659 	em28xx_videodbg("res: get %d\n", bit);
660 	return 1;
661 }
662 
663 static int res_check(struct em28xx_fh *fh, unsigned int bit)
664 {
665 	return fh->resources & bit;
666 }
667 
668 static int res_locked(struct em28xx *dev, unsigned int bit)
669 {
670 	return dev->resources & bit;
671 }
672 
673 static void res_free(struct em28xx_fh *fh, unsigned int bits)
674 {
675 	struct em28xx    *dev = fh->dev;
676 
677 	BUG_ON((fh->resources & bits) != bits);
678 
679 	fh->resources  &= ~bits;
680 	dev->resources &= ~bits;
681 	em28xx_videodbg("res: put %d\n", bits);
682 }
683 
684 static int get_ressource(struct em28xx_fh *fh)
685 {
686 	switch (fh->type) {
687 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
688 		return EM28XX_RESOURCE_VIDEO;
689 	case V4L2_BUF_TYPE_VBI_CAPTURE:
690 		return EM28XX_RESOURCE_VBI;
691 	default:
692 		BUG();
693 		return 0;
694 	}
695 }
696 
697 void em28xx_ctrl_notify(struct v4l2_ctrl *ctrl, void *priv)
698 {
699 	struct em28xx *dev = priv;
700 
701 	/*
702 	 * In the case of non-AC97 volume controls, we still need
703 	 * to do some setups at em28xx, in order to mute/unmute
704 	 * and to adjust audio volume. However, the value ranges
705 	 * should be checked by the corresponding V4L subdriver.
706 	 */
707 	switch (ctrl->id) {
708 	case V4L2_CID_AUDIO_MUTE:
709 		dev->mute = ctrl->val;
710 		em28xx_audio_analog_set(dev);
711 		break;
712 	case V4L2_CID_AUDIO_VOLUME:
713 		dev->volume = ctrl->val;
714 		em28xx_audio_analog_set(dev);
715 		break;
716 	}
717 }
718 
719 static int em28xx_s_ctrl(struct v4l2_ctrl *ctrl)
720 {
721 	struct em28xx *dev = container_of(ctrl->handler, struct em28xx, ctrl_handler);
722 
723 	switch (ctrl->id) {
724 	case V4L2_CID_AUDIO_MUTE:
725 		dev->mute = ctrl->val;
726 		break;
727 	case V4L2_CID_AUDIO_VOLUME:
728 		dev->volume = ctrl->val;
729 		break;
730 	}
731 
732 	return em28xx_audio_analog_set(dev);
733 }
734 
735 const struct v4l2_ctrl_ops em28xx_ctrl_ops = {
736 	.s_ctrl = em28xx_s_ctrl,
737 };
738 
739 static int check_dev(struct em28xx *dev)
740 {
741 	if (dev->state & DEV_DISCONNECTED) {
742 		em28xx_errdev("v4l2 ioctl: device not present\n");
743 		return -ENODEV;
744 	}
745 
746 	if (dev->state & DEV_MISCONFIGURED) {
747 		em28xx_errdev("v4l2 ioctl: device is misconfigured; "
748 			      "close and open it again\n");
749 		return -EIO;
750 	}
751 	return 0;
752 }
753 
754 static void get_scale(struct em28xx *dev,
755 			unsigned int width, unsigned int height,
756 			unsigned int *hscale, unsigned int *vscale)
757 {
758 	unsigned int          maxw = norm_maxw(dev);
759 	unsigned int          maxh = norm_maxh(dev);
760 
761 	*hscale = (((unsigned long)maxw) << 12) / width - 4096L;
762 	if (*hscale >= 0x4000)
763 		*hscale = 0x3fff;
764 
765 	*vscale = (((unsigned long)maxh) << 12) / height - 4096L;
766 	if (*vscale >= 0x4000)
767 		*vscale = 0x3fff;
768 }
769 
770 /* ------------------------------------------------------------------
771 	IOCTL vidioc handling
772    ------------------------------------------------------------------*/
773 
774 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
775 					struct v4l2_format *f)
776 {
777 	struct em28xx_fh      *fh  = priv;
778 	struct em28xx         *dev = fh->dev;
779 
780 	f->fmt.pix.width = dev->width;
781 	f->fmt.pix.height = dev->height;
782 	f->fmt.pix.pixelformat = dev->format->fourcc;
783 	f->fmt.pix.bytesperline = (dev->width * dev->format->depth + 7) >> 3;
784 	f->fmt.pix.sizeimage = f->fmt.pix.bytesperline  * dev->height;
785 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
786 
787 	/* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
788 	if (dev->progressive)
789 		f->fmt.pix.field = V4L2_FIELD_NONE;
790 	else
791 		f->fmt.pix.field = dev->interlaced ?
792 			   V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
793 	return 0;
794 }
795 
796 static struct em28xx_fmt *format_by_fourcc(unsigned int fourcc)
797 {
798 	unsigned int i;
799 
800 	for (i = 0; i < ARRAY_SIZE(format); i++)
801 		if (format[i].fourcc == fourcc)
802 			return &format[i];
803 
804 	return NULL;
805 }
806 
807 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
808 			struct v4l2_format *f)
809 {
810 	struct em28xx_fh      *fh    = priv;
811 	struct em28xx         *dev   = fh->dev;
812 	unsigned int          width  = f->fmt.pix.width;
813 	unsigned int          height = f->fmt.pix.height;
814 	unsigned int          maxw   = norm_maxw(dev);
815 	unsigned int          maxh   = norm_maxh(dev);
816 	unsigned int          hscale, vscale;
817 	struct em28xx_fmt     *fmt;
818 
819 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
820 	if (!fmt) {
821 		em28xx_videodbg("Fourcc format (%08x) invalid.\n",
822 				f->fmt.pix.pixelformat);
823 		return -EINVAL;
824 	}
825 
826 	if (dev->board.is_em2800) {
827 		/* the em2800 can only scale down to 50% */
828 		height = height > (3 * maxh / 4) ? maxh : maxh / 2;
829 		width = width > (3 * maxw / 4) ? maxw : maxw / 2;
830                 /* MaxPacketSize for em2800 is too small to capture at full resolution
831                  * use half of maxw as the scaler can only scale to 50% */
832 		if (width == maxw && height == maxh)
833 			width /= 2;
834 	} else {
835 		/* width must even because of the YUYV format
836 		   height must be even because of interlacing */
837 		v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh,
838 				      1, 0);
839 	}
840 
841 	get_scale(dev, width, height, &hscale, &vscale);
842 
843 	width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
844 	height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
845 
846 	f->fmt.pix.width = width;
847 	f->fmt.pix.height = height;
848 	f->fmt.pix.pixelformat = fmt->fourcc;
849 	f->fmt.pix.bytesperline = (dev->width * fmt->depth + 7) >> 3;
850 	f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
851 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
852 	if (dev->progressive)
853 		f->fmt.pix.field = V4L2_FIELD_NONE;
854 	else
855 		f->fmt.pix.field = dev->interlaced ?
856 			   V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
857 
858 	return 0;
859 }
860 
861 static int em28xx_set_video_format(struct em28xx *dev, unsigned int fourcc,
862 				   unsigned width, unsigned height)
863 {
864 	struct em28xx_fmt     *fmt;
865 
866 	fmt = format_by_fourcc(fourcc);
867 	if (!fmt)
868 		return -EINVAL;
869 
870 	dev->format = fmt;
871 	dev->width  = width;
872 	dev->height = height;
873 
874 	/* set new image size */
875 	get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
876 
877 	em28xx_set_alternate(dev);
878 	em28xx_resolution_set(dev);
879 
880 	return 0;
881 }
882 
883 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
884 			struct v4l2_format *f)
885 {
886 	struct em28xx_fh      *fh  = priv;
887 	struct em28xx         *dev = fh->dev;
888 	int                   rc;
889 
890 	rc = check_dev(dev);
891 	if (rc < 0)
892 		return rc;
893 
894 	vidioc_try_fmt_vid_cap(file, priv, f);
895 
896 	if (videobuf_queue_is_busy(&fh->vb_vidq)) {
897 		em28xx_errdev("%s queue busy\n", __func__);
898 		return -EBUSY;
899 	}
900 
901 	return em28xx_set_video_format(dev, f->fmt.pix.pixelformat,
902 				f->fmt.pix.width, f->fmt.pix.height);
903 }
904 
905 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
906 {
907 	struct em28xx_fh   *fh  = priv;
908 	struct em28xx      *dev = fh->dev;
909 	int                rc;
910 
911 	rc = check_dev(dev);
912 	if (rc < 0)
913 		return rc;
914 
915 	*norm = dev->norm;
916 
917 	return 0;
918 }
919 
920 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
921 {
922 	struct em28xx_fh   *fh  = priv;
923 	struct em28xx      *dev = fh->dev;
924 	int                rc;
925 
926 	rc = check_dev(dev);
927 	if (rc < 0)
928 		return rc;
929 
930 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, querystd, norm);
931 
932 	return 0;
933 }
934 
935 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm)
936 {
937 	struct em28xx_fh   *fh  = priv;
938 	struct em28xx      *dev = fh->dev;
939 	struct v4l2_format f;
940 	int                rc;
941 
942 	rc = check_dev(dev);
943 	if (rc < 0)
944 		return rc;
945 
946 	dev->norm = *norm;
947 
948 	/* Adjusts width/height, if needed */
949 	f.fmt.pix.width = dev->width;
950 	f.fmt.pix.height = dev->height;
951 	vidioc_try_fmt_vid_cap(file, priv, &f);
952 
953 	/* set new image size */
954 	dev->width = f.fmt.pix.width;
955 	dev->height = f.fmt.pix.height;
956 	get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
957 
958 	em28xx_resolution_set(dev);
959 	v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std, dev->norm);
960 
961 	return 0;
962 }
963 
964 static int vidioc_g_parm(struct file *file, void *priv,
965 			 struct v4l2_streamparm *p)
966 {
967 	struct em28xx_fh   *fh  = priv;
968 	struct em28xx      *dev = fh->dev;
969 	int rc = 0;
970 
971 	if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
972 		return -EINVAL;
973 
974 	if (dev->board.is_webcam)
975 		rc = v4l2_device_call_until_err(&dev->v4l2_dev, 0,
976 						video, g_parm, p);
977 	else
978 		v4l2_video_std_frame_period(dev->norm,
979 						 &p->parm.capture.timeperframe);
980 
981 	return rc;
982 }
983 
984 static int vidioc_s_parm(struct file *file, void *priv,
985 			 struct v4l2_streamparm *p)
986 {
987 	struct em28xx_fh   *fh  = priv;
988 	struct em28xx      *dev = fh->dev;
989 
990 	if (!dev->board.is_webcam)
991 		return -EINVAL;
992 
993 	if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
994 		return -EINVAL;
995 
996 	return v4l2_device_call_until_err(&dev->v4l2_dev, 0, video, s_parm, p);
997 }
998 
999 static const char *iname[] = {
1000 	[EM28XX_VMUX_COMPOSITE1] = "Composite1",
1001 	[EM28XX_VMUX_COMPOSITE2] = "Composite2",
1002 	[EM28XX_VMUX_COMPOSITE3] = "Composite3",
1003 	[EM28XX_VMUX_COMPOSITE4] = "Composite4",
1004 	[EM28XX_VMUX_SVIDEO]     = "S-Video",
1005 	[EM28XX_VMUX_TELEVISION] = "Television",
1006 	[EM28XX_VMUX_CABLE]      = "Cable TV",
1007 	[EM28XX_VMUX_DVB]        = "DVB",
1008 	[EM28XX_VMUX_DEBUG]      = "for debug only",
1009 };
1010 
1011 static int vidioc_enum_input(struct file *file, void *priv,
1012 				struct v4l2_input *i)
1013 {
1014 	struct em28xx_fh   *fh  = priv;
1015 	struct em28xx      *dev = fh->dev;
1016 	unsigned int       n;
1017 
1018 	n = i->index;
1019 	if (n >= MAX_EM28XX_INPUT)
1020 		return -EINVAL;
1021 	if (0 == INPUT(n)->type)
1022 		return -EINVAL;
1023 
1024 	i->index = n;
1025 	i->type = V4L2_INPUT_TYPE_CAMERA;
1026 
1027 	strcpy(i->name, iname[INPUT(n)->type]);
1028 
1029 	if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type) ||
1030 		(EM28XX_VMUX_CABLE == INPUT(n)->type))
1031 		i->type = V4L2_INPUT_TYPE_TUNER;
1032 
1033 	i->std = dev->vdev->tvnorms;
1034 
1035 	return 0;
1036 }
1037 
1038 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1039 {
1040 	struct em28xx_fh   *fh  = priv;
1041 	struct em28xx      *dev = fh->dev;
1042 
1043 	*i = dev->ctl_input;
1044 
1045 	return 0;
1046 }
1047 
1048 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1049 {
1050 	struct em28xx_fh   *fh  = priv;
1051 	struct em28xx      *dev = fh->dev;
1052 	int                rc;
1053 
1054 	rc = check_dev(dev);
1055 	if (rc < 0)
1056 		return rc;
1057 
1058 	if (i >= MAX_EM28XX_INPUT)
1059 		return -EINVAL;
1060 	if (0 == INPUT(i)->type)
1061 		return -EINVAL;
1062 
1063 	video_mux(dev, i);
1064 	return 0;
1065 }
1066 
1067 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1068 {
1069 	struct em28xx_fh   *fh    = priv;
1070 	struct em28xx      *dev   = fh->dev;
1071 
1072 	if (!dev->audio_mode.has_audio)
1073 		return -EINVAL;
1074 
1075 	switch (a->index) {
1076 	case EM28XX_AMUX_VIDEO:
1077 		strcpy(a->name, "Television");
1078 		break;
1079 	case EM28XX_AMUX_LINE_IN:
1080 		strcpy(a->name, "Line In");
1081 		break;
1082 	case EM28XX_AMUX_VIDEO2:
1083 		strcpy(a->name, "Television alt");
1084 		break;
1085 	case EM28XX_AMUX_PHONE:
1086 		strcpy(a->name, "Phone");
1087 		break;
1088 	case EM28XX_AMUX_MIC:
1089 		strcpy(a->name, "Mic");
1090 		break;
1091 	case EM28XX_AMUX_CD:
1092 		strcpy(a->name, "CD");
1093 		break;
1094 	case EM28XX_AMUX_AUX:
1095 		strcpy(a->name, "Aux");
1096 		break;
1097 	case EM28XX_AMUX_PCM_OUT:
1098 		strcpy(a->name, "PCM");
1099 		break;
1100 	default:
1101 		return -EINVAL;
1102 	}
1103 
1104 	a->index = dev->ctl_ainput;
1105 	a->capability = V4L2_AUDCAP_STEREO;
1106 
1107 	return 0;
1108 }
1109 
1110 static int vidioc_s_audio(struct file *file, void *priv, const struct v4l2_audio *a)
1111 {
1112 	struct em28xx_fh   *fh  = priv;
1113 	struct em28xx      *dev = fh->dev;
1114 
1115 
1116 	if (!dev->audio_mode.has_audio)
1117 		return -EINVAL;
1118 
1119 	if (a->index >= MAX_EM28XX_INPUT)
1120 		return -EINVAL;
1121 	if (0 == INPUT(a->index)->type)
1122 		return -EINVAL;
1123 
1124 	dev->ctl_ainput = INPUT(a->index)->amux;
1125 	dev->ctl_aoutput = INPUT(a->index)->aout;
1126 
1127 	if (!dev->ctl_aoutput)
1128 		dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1129 
1130 	return 0;
1131 }
1132 
1133 static int vidioc_g_tuner(struct file *file, void *priv,
1134 				struct v4l2_tuner *t)
1135 {
1136 	struct em28xx_fh      *fh  = priv;
1137 	struct em28xx         *dev = fh->dev;
1138 	int                   rc;
1139 
1140 	rc = check_dev(dev);
1141 	if (rc < 0)
1142 		return rc;
1143 
1144 	if (0 != t->index)
1145 		return -EINVAL;
1146 
1147 	strcpy(t->name, "Tuner");
1148 
1149 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
1150 	return 0;
1151 }
1152 
1153 static int vidioc_s_tuner(struct file *file, void *priv,
1154 				struct v4l2_tuner *t)
1155 {
1156 	struct em28xx_fh      *fh  = priv;
1157 	struct em28xx         *dev = fh->dev;
1158 	int                   rc;
1159 
1160 	rc = check_dev(dev);
1161 	if (rc < 0)
1162 		return rc;
1163 
1164 	if (0 != t->index)
1165 		return -EINVAL;
1166 
1167 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
1168 	return 0;
1169 }
1170 
1171 static int vidioc_g_frequency(struct file *file, void *priv,
1172 				struct v4l2_frequency *f)
1173 {
1174 	struct em28xx_fh      *fh  = priv;
1175 	struct em28xx         *dev = fh->dev;
1176 
1177 	if (0 != f->tuner)
1178 		return -EINVAL;
1179 
1180 	f->frequency = dev->ctl_freq;
1181 	return 0;
1182 }
1183 
1184 static int vidioc_s_frequency(struct file *file, void *priv,
1185 				struct v4l2_frequency *f)
1186 {
1187 	struct em28xx_fh      *fh  = priv;
1188 	struct em28xx         *dev = fh->dev;
1189 	int                   rc;
1190 
1191 	rc = check_dev(dev);
1192 	if (rc < 0)
1193 		return rc;
1194 
1195 	if (0 != f->tuner)
1196 		return -EINVAL;
1197 
1198 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, f);
1199 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_frequency, f);
1200 	dev->ctl_freq = f->frequency;
1201 
1202 	return 0;
1203 }
1204 
1205 #ifdef CONFIG_VIDEO_ADV_DEBUG
1206 static int em28xx_reg_len(int reg)
1207 {
1208 	switch (reg) {
1209 	case EM28XX_R40_AC97LSB:
1210 	case EM28XX_R30_HSCALELOW:
1211 	case EM28XX_R32_VSCALELOW:
1212 		return 2;
1213 	default:
1214 		return 1;
1215 	}
1216 }
1217 
1218 static int vidioc_g_chip_ident(struct file *file, void *priv,
1219 	       struct v4l2_dbg_chip_ident *chip)
1220 {
1221 	struct em28xx_fh      *fh  = priv;
1222 	struct em28xx         *dev = fh->dev;
1223 
1224 	chip->ident = V4L2_IDENT_NONE;
1225 	chip->revision = 0;
1226 	if (chip->match.type == V4L2_CHIP_MATCH_HOST) {
1227 		if (v4l2_chip_match_host(&chip->match))
1228 			chip->ident = V4L2_IDENT_NONE;
1229 		return 0;
1230 	}
1231 	if (chip->match.type != V4L2_CHIP_MATCH_I2C_DRIVER &&
1232 	    chip->match.type != V4L2_CHIP_MATCH_I2C_ADDR)
1233 		return -EINVAL;
1234 
1235 	v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_chip_ident, chip);
1236 
1237 	return 0;
1238 }
1239 
1240 
1241 static int vidioc_g_register(struct file *file, void *priv,
1242 			     struct v4l2_dbg_register *reg)
1243 {
1244 	struct em28xx_fh      *fh  = priv;
1245 	struct em28xx         *dev = fh->dev;
1246 	int ret;
1247 
1248 	switch (reg->match.type) {
1249 	case V4L2_CHIP_MATCH_AC97:
1250 		ret = em28xx_read_ac97(dev, reg->reg);
1251 		if (ret < 0)
1252 			return ret;
1253 
1254 		reg->val = ret;
1255 		reg->size = 1;
1256 		return 0;
1257 	case V4L2_CHIP_MATCH_I2C_DRIVER:
1258 		v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
1259 		return 0;
1260 	case V4L2_CHIP_MATCH_I2C_ADDR:
1261 		/* TODO: is this correct? */
1262 		v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
1263 		return 0;
1264 	default:
1265 		if (!v4l2_chip_match_host(&reg->match))
1266 			return -EINVAL;
1267 	}
1268 
1269 	/* Match host */
1270 	reg->size = em28xx_reg_len(reg->reg);
1271 	if (reg->size == 1) {
1272 		ret = em28xx_read_reg(dev, reg->reg);
1273 
1274 		if (ret < 0)
1275 			return ret;
1276 
1277 		reg->val = ret;
1278 	} else {
1279 		__le16 val = 0;
1280 		ret = em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1281 						   reg->reg, (char *)&val, 2);
1282 		if (ret < 0)
1283 			return ret;
1284 
1285 		reg->val = le16_to_cpu(val);
1286 	}
1287 
1288 	return 0;
1289 }
1290 
1291 static int vidioc_s_register(struct file *file, void *priv,
1292 			     struct v4l2_dbg_register *reg)
1293 {
1294 	struct em28xx_fh      *fh  = priv;
1295 	struct em28xx         *dev = fh->dev;
1296 	__le16 buf;
1297 
1298 	switch (reg->match.type) {
1299 	case V4L2_CHIP_MATCH_AC97:
1300 		return em28xx_write_ac97(dev, reg->reg, reg->val);
1301 	case V4L2_CHIP_MATCH_I2C_DRIVER:
1302 		v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
1303 		return 0;
1304 	case V4L2_CHIP_MATCH_I2C_ADDR:
1305 		/* TODO: is this correct? */
1306 		v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
1307 		return 0;
1308 	default:
1309 		if (!v4l2_chip_match_host(&reg->match))
1310 			return -EINVAL;
1311 	}
1312 
1313 	/* Match host */
1314 	buf = cpu_to_le16(reg->val);
1315 
1316 	return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1317 			       em28xx_reg_len(reg->reg));
1318 }
1319 #endif
1320 
1321 
1322 static int vidioc_cropcap(struct file *file, void *priv,
1323 					struct v4l2_cropcap *cc)
1324 {
1325 	struct em28xx_fh      *fh  = priv;
1326 	struct em28xx         *dev = fh->dev;
1327 
1328 	if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1329 		return -EINVAL;
1330 
1331 	cc->bounds.left = 0;
1332 	cc->bounds.top = 0;
1333 	cc->bounds.width = dev->width;
1334 	cc->bounds.height = dev->height;
1335 	cc->defrect = cc->bounds;
1336 	cc->pixelaspect.numerator = 54;	/* 4:3 FIXME: remove magic numbers */
1337 	cc->pixelaspect.denominator = 59;
1338 
1339 	return 0;
1340 }
1341 
1342 static int vidioc_streamon(struct file *file, void *priv,
1343 					enum v4l2_buf_type type)
1344 {
1345 	struct em28xx_fh      *fh  = priv;
1346 	struct em28xx         *dev = fh->dev;
1347 	int                   rc = -EINVAL;
1348 
1349 	rc = check_dev(dev);
1350 	if (rc < 0)
1351 		return rc;
1352 
1353 	if (unlikely(type != fh->type))
1354 		return -EINVAL;
1355 
1356 	em28xx_videodbg("vidioc_streamon fh=%p t=%d fh->res=%d dev->res=%d\n",
1357 			fh, type, fh->resources, dev->resources);
1358 
1359 	if (unlikely(!res_get(fh, get_ressource(fh))))
1360 		return -EBUSY;
1361 
1362 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1363 		rc = videobuf_streamon(&fh->vb_vidq);
1364 	else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
1365 		rc = videobuf_streamon(&fh->vb_vbiq);
1366 
1367 	return rc;
1368 }
1369 
1370 static int vidioc_streamoff(struct file *file, void *priv,
1371 					enum v4l2_buf_type type)
1372 {
1373 	struct em28xx_fh      *fh  = priv;
1374 	struct em28xx         *dev = fh->dev;
1375 	int                   rc;
1376 
1377 	rc = check_dev(dev);
1378 	if (rc < 0)
1379 		return rc;
1380 
1381 	if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1382 	    fh->type != V4L2_BUF_TYPE_VBI_CAPTURE)
1383 		return -EINVAL;
1384 	if (type != fh->type)
1385 		return -EINVAL;
1386 
1387 	em28xx_videodbg("vidioc_streamoff fh=%p t=%d fh->res=%d dev->res=%d\n",
1388 			fh, type, fh->resources, dev->resources);
1389 
1390 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1391 		if (res_check(fh, EM28XX_RESOURCE_VIDEO)) {
1392 			videobuf_streamoff(&fh->vb_vidq);
1393 			res_free(fh, EM28XX_RESOURCE_VIDEO);
1394 		}
1395 	} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1396 		if (res_check(fh, EM28XX_RESOURCE_VBI)) {
1397 			videobuf_streamoff(&fh->vb_vbiq);
1398 			res_free(fh, EM28XX_RESOURCE_VBI);
1399 		}
1400 	}
1401 
1402 	return 0;
1403 }
1404 
1405 static int vidioc_querycap(struct file *file, void  *priv,
1406 					struct v4l2_capability *cap)
1407 {
1408 	struct video_device *vdev = video_devdata(file);
1409 	struct em28xx_fh      *fh  = priv;
1410 	struct em28xx         *dev = fh->dev;
1411 
1412 	strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1413 	strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1414 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
1415 
1416 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1417 		cap->device_caps = V4L2_CAP_READWRITE |
1418 			V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1419 	else if (vdev->vfl_type == VFL_TYPE_RADIO)
1420 		cap->device_caps = V4L2_CAP_RADIO;
1421 	else
1422 		cap->device_caps = V4L2_CAP_READWRITE |
1423 			V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE;
1424 
1425 	if (dev->audio_mode.has_audio)
1426 		cap->device_caps |= V4L2_CAP_AUDIO;
1427 
1428 	if (dev->tuner_type != TUNER_ABSENT)
1429 		cap->device_caps |= V4L2_CAP_TUNER;
1430 
1431 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS |
1432 		V4L2_CAP_READWRITE | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1433 	if (dev->vbi_dev)
1434 		cap->capabilities |=
1435 			V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE;
1436 	if (dev->radio_dev)
1437 		cap->capabilities |= V4L2_CAP_RADIO;
1438 	return 0;
1439 }
1440 
1441 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1442 					struct v4l2_fmtdesc *f)
1443 {
1444 	if (unlikely(f->index >= ARRAY_SIZE(format)))
1445 		return -EINVAL;
1446 
1447 	strlcpy(f->description, format[f->index].name, sizeof(f->description));
1448 	f->pixelformat = format[f->index].fourcc;
1449 
1450 	return 0;
1451 }
1452 
1453 static int vidioc_enum_framesizes(struct file *file, void *priv,
1454 				  struct v4l2_frmsizeenum *fsize)
1455 {
1456 	struct em28xx_fh      *fh  = priv;
1457 	struct em28xx         *dev = fh->dev;
1458 	struct em28xx_fmt     *fmt;
1459 	unsigned int	      maxw = norm_maxw(dev);
1460 	unsigned int	      maxh = norm_maxh(dev);
1461 
1462 	fmt = format_by_fourcc(fsize->pixel_format);
1463 	if (!fmt) {
1464 		em28xx_videodbg("Fourcc format (%08x) invalid.\n",
1465 				fsize->pixel_format);
1466 		return -EINVAL;
1467 	}
1468 
1469 	if (dev->board.is_em2800) {
1470 		if (fsize->index > 1)
1471 			return -EINVAL;
1472 		fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1473 		fsize->discrete.width = maxw / (1 + fsize->index);
1474 		fsize->discrete.height = maxh / (1 + fsize->index);
1475 		return 0;
1476 	}
1477 
1478 	if (fsize->index != 0)
1479 		return -EINVAL;
1480 
1481 	/* Report a continuous range */
1482 	fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1483 	fsize->stepwise.min_width = 48;
1484 	fsize->stepwise.min_height = 32;
1485 	fsize->stepwise.max_width = maxw;
1486 	fsize->stepwise.max_height = maxh;
1487 	fsize->stepwise.step_width = 1;
1488 	fsize->stepwise.step_height = 1;
1489 	return 0;
1490 }
1491 
1492 /* Sliced VBI ioctls */
1493 static int vidioc_g_fmt_sliced_vbi_cap(struct file *file, void *priv,
1494 					struct v4l2_format *f)
1495 {
1496 	struct em28xx_fh      *fh  = priv;
1497 	struct em28xx         *dev = fh->dev;
1498 	int                   rc;
1499 
1500 	rc = check_dev(dev);
1501 	if (rc < 0)
1502 		return rc;
1503 
1504 	f->fmt.sliced.service_set = 0;
1505 	v4l2_device_call_all(&dev->v4l2_dev, 0, vbi, g_sliced_fmt, &f->fmt.sliced);
1506 
1507 	if (f->fmt.sliced.service_set == 0)
1508 		rc = -EINVAL;
1509 
1510 	return rc;
1511 }
1512 
1513 static int vidioc_try_set_sliced_vbi_cap(struct file *file, void *priv,
1514 			struct v4l2_format *f)
1515 {
1516 	struct em28xx_fh      *fh  = priv;
1517 	struct em28xx         *dev = fh->dev;
1518 	int                   rc;
1519 
1520 	rc = check_dev(dev);
1521 	if (rc < 0)
1522 		return rc;
1523 
1524 	v4l2_device_call_all(&dev->v4l2_dev, 0, vbi, g_sliced_fmt, &f->fmt.sliced);
1525 
1526 	if (f->fmt.sliced.service_set == 0)
1527 		return -EINVAL;
1528 
1529 	return 0;
1530 }
1531 
1532 /* RAW VBI ioctls */
1533 
1534 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1535 				struct v4l2_format *format)
1536 {
1537 	struct em28xx_fh      *fh  = priv;
1538 	struct em28xx         *dev = fh->dev;
1539 
1540 	format->fmt.vbi.samples_per_line = dev->vbi_width;
1541 	format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1542 	format->fmt.vbi.offset = 0;
1543 	format->fmt.vbi.flags = 0;
1544 	format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1545 	format->fmt.vbi.count[0] = dev->vbi_height;
1546 	format->fmt.vbi.count[1] = dev->vbi_height;
1547 
1548 	/* Varies by video standard (NTSC, PAL, etc.) */
1549 	if (dev->norm & V4L2_STD_525_60) {
1550 		/* NTSC */
1551 		format->fmt.vbi.start[0] = 10;
1552 		format->fmt.vbi.start[1] = 273;
1553 	} else if (dev->norm & V4L2_STD_625_50) {
1554 		/* PAL */
1555 		format->fmt.vbi.start[0] = 6;
1556 		format->fmt.vbi.start[1] = 318;
1557 	}
1558 
1559 	return 0;
1560 }
1561 
1562 static int vidioc_s_fmt_vbi_cap(struct file *file, void *priv,
1563 				struct v4l2_format *format)
1564 {
1565 	struct em28xx_fh      *fh  = priv;
1566 	struct em28xx         *dev = fh->dev;
1567 
1568 	format->fmt.vbi.samples_per_line = dev->vbi_width;
1569 	format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1570 	format->fmt.vbi.offset = 0;
1571 	format->fmt.vbi.flags = 0;
1572 	format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1573 	format->fmt.vbi.count[0] = dev->vbi_height;
1574 	format->fmt.vbi.count[1] = dev->vbi_height;
1575 
1576 	/* Varies by video standard (NTSC, PAL, etc.) */
1577 	if (dev->norm & V4L2_STD_525_60) {
1578 		/* NTSC */
1579 		format->fmt.vbi.start[0] = 10;
1580 		format->fmt.vbi.start[1] = 273;
1581 	} else if (dev->norm & V4L2_STD_625_50) {
1582 		/* PAL */
1583 		format->fmt.vbi.start[0] = 6;
1584 		format->fmt.vbi.start[1] = 318;
1585 	}
1586 
1587 	return 0;
1588 }
1589 
1590 static int vidioc_reqbufs(struct file *file, void *priv,
1591 			  struct v4l2_requestbuffers *rb)
1592 {
1593 	struct em28xx_fh      *fh  = priv;
1594 	struct em28xx         *dev = fh->dev;
1595 	int                   rc;
1596 
1597 	rc = check_dev(dev);
1598 	if (rc < 0)
1599 		return rc;
1600 
1601 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1602 		return videobuf_reqbufs(&fh->vb_vidq, rb);
1603 	else
1604 		return videobuf_reqbufs(&fh->vb_vbiq, rb);
1605 }
1606 
1607 static int vidioc_querybuf(struct file *file, void *priv,
1608 			   struct v4l2_buffer *b)
1609 {
1610 	struct em28xx_fh      *fh  = priv;
1611 	struct em28xx         *dev = fh->dev;
1612 	int                   rc;
1613 
1614 	rc = check_dev(dev);
1615 	if (rc < 0)
1616 		return rc;
1617 
1618 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1619 		return videobuf_querybuf(&fh->vb_vidq, b);
1620 	else {
1621 		/* FIXME: I'm not sure yet whether this is a bug in zvbi or
1622 		   the videobuf framework, but we probably shouldn't be
1623 		   returning a buffer larger than that which was asked for.
1624 		   At a minimum, it causes a crash in zvbi since it does
1625 		   a memcpy based on the source buffer length */
1626 		int result = videobuf_querybuf(&fh->vb_vbiq, b);
1627 		b->length = dev->vbi_width * dev->vbi_height * 2;
1628 
1629 		return result;
1630 	}
1631 }
1632 
1633 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1634 {
1635 	struct em28xx_fh      *fh  = priv;
1636 	struct em28xx         *dev = fh->dev;
1637 	int                   rc;
1638 
1639 	rc = check_dev(dev);
1640 	if (rc < 0)
1641 		return rc;
1642 
1643 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1644 		return videobuf_qbuf(&fh->vb_vidq, b);
1645 	else
1646 		return videobuf_qbuf(&fh->vb_vbiq, b);
1647 }
1648 
1649 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1650 {
1651 	struct em28xx_fh      *fh  = priv;
1652 	struct em28xx         *dev = fh->dev;
1653 	int                   rc;
1654 
1655 	rc = check_dev(dev);
1656 	if (rc < 0)
1657 		return rc;
1658 
1659 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1660 		return videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags &
1661 				      O_NONBLOCK);
1662 	else
1663 		return videobuf_dqbuf(&fh->vb_vbiq, b, file->f_flags &
1664 				      O_NONBLOCK);
1665 }
1666 
1667 /* ----------------------------------------------------------- */
1668 /* RADIO ESPECIFIC IOCTLS                                      */
1669 /* ----------------------------------------------------------- */
1670 
1671 static int radio_g_tuner(struct file *file, void *priv,
1672 			 struct v4l2_tuner *t)
1673 {
1674 	struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1675 
1676 	if (unlikely(t->index > 0))
1677 		return -EINVAL;
1678 
1679 	strcpy(t->name, "Radio");
1680 	t->type = V4L2_TUNER_RADIO;
1681 
1682 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
1683 
1684 	return 0;
1685 }
1686 
1687 static int radio_s_tuner(struct file *file, void *priv,
1688 			 struct v4l2_tuner *t)
1689 {
1690 	struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1691 
1692 	if (0 != t->index)
1693 		return -EINVAL;
1694 
1695 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
1696 
1697 	return 0;
1698 }
1699 
1700 /*
1701  * em28xx_v4l2_open()
1702  * inits the device and starts isoc transfer
1703  */
1704 static int em28xx_v4l2_open(struct file *filp)
1705 {
1706 	int errCode = 0, radio = 0;
1707 	struct video_device *vdev = video_devdata(filp);
1708 	struct em28xx *dev = video_drvdata(filp);
1709 	enum v4l2_buf_type fh_type = 0;
1710 	struct em28xx_fh *fh;
1711 	enum v4l2_field field;
1712 
1713 	switch (vdev->vfl_type) {
1714 	case VFL_TYPE_GRABBER:
1715 		fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1716 		break;
1717 	case VFL_TYPE_VBI:
1718 		fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1719 		break;
1720 	case VFL_TYPE_RADIO:
1721 		radio = 1;
1722 		break;
1723 	}
1724 
1725 	em28xx_videodbg("open dev=%s type=%s users=%d\n",
1726 			video_device_node_name(vdev), v4l2_type_names[fh_type],
1727 			dev->users);
1728 
1729 
1730 	if (mutex_lock_interruptible(&dev->lock))
1731 		return -ERESTARTSYS;
1732 	fh = kzalloc(sizeof(struct em28xx_fh), GFP_KERNEL);
1733 	if (!fh) {
1734 		em28xx_errdev("em28xx-video.c: Out of memory?!\n");
1735 		mutex_unlock(&dev->lock);
1736 		return -ENOMEM;
1737 	}
1738 	fh->dev = dev;
1739 	fh->radio = radio;
1740 	fh->type = fh_type;
1741 	filp->private_data = fh;
1742 
1743 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1744 		em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
1745 		em28xx_set_alternate(dev);
1746 		em28xx_resolution_set(dev);
1747 
1748 		/* Needed, since GPIO might have disabled power of
1749 		   some i2c device
1750 		 */
1751 		em28xx_wake_i2c(dev);
1752 
1753 	}
1754 	if (fh->radio) {
1755 		em28xx_videodbg("video_open: setting radio device\n");
1756 		v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_radio);
1757 	}
1758 
1759 	dev->users++;
1760 
1761 	if (dev->progressive)
1762 		field = V4L2_FIELD_NONE;
1763 	else
1764 		field = V4L2_FIELD_INTERLACED;
1765 
1766 	videobuf_queue_vmalloc_init(&fh->vb_vidq, &em28xx_video_qops,
1767 				    NULL, &dev->slock,
1768 				    V4L2_BUF_TYPE_VIDEO_CAPTURE, field,
1769 				    sizeof(struct em28xx_buffer), fh, &dev->lock);
1770 
1771 	videobuf_queue_vmalloc_init(&fh->vb_vbiq, &em28xx_vbi_qops,
1772 				    NULL, &dev->slock,
1773 				    V4L2_BUF_TYPE_VBI_CAPTURE,
1774 				    V4L2_FIELD_SEQ_TB,
1775 				    sizeof(struct em28xx_buffer), fh, &dev->lock);
1776 	mutex_unlock(&dev->lock);
1777 
1778 	return errCode;
1779 }
1780 
1781 /*
1782  * em28xx_realease_resources()
1783  * unregisters the v4l2,i2c and usb devices
1784  * called when the device gets disconected or at module unload
1785 */
1786 void em28xx_release_analog_resources(struct em28xx *dev)
1787 {
1788 
1789 	/*FIXME: I2C IR should be disconnected */
1790 
1791 	if (dev->radio_dev) {
1792 		if (video_is_registered(dev->radio_dev))
1793 			video_unregister_device(dev->radio_dev);
1794 		else
1795 			video_device_release(dev->radio_dev);
1796 		dev->radio_dev = NULL;
1797 	}
1798 	if (dev->vbi_dev) {
1799 		em28xx_info("V4L2 device %s deregistered\n",
1800 			    video_device_node_name(dev->vbi_dev));
1801 		if (video_is_registered(dev->vbi_dev))
1802 			video_unregister_device(dev->vbi_dev);
1803 		else
1804 			video_device_release(dev->vbi_dev);
1805 		dev->vbi_dev = NULL;
1806 	}
1807 	if (dev->vdev) {
1808 		em28xx_info("V4L2 device %s deregistered\n",
1809 			    video_device_node_name(dev->vdev));
1810 		if (video_is_registered(dev->vdev))
1811 			video_unregister_device(dev->vdev);
1812 		else
1813 			video_device_release(dev->vdev);
1814 		dev->vdev = NULL;
1815 	}
1816 }
1817 
1818 /*
1819  * em28xx_v4l2_close()
1820  * stops streaming and deallocates all resources allocated by the v4l2
1821  * calls and ioctls
1822  */
1823 static int em28xx_v4l2_close(struct file *filp)
1824 {
1825 	struct em28xx_fh *fh  = filp->private_data;
1826 	struct em28xx    *dev = fh->dev;
1827 	int              errCode;
1828 
1829 	em28xx_videodbg("users=%d\n", dev->users);
1830 
1831 	mutex_lock(&dev->lock);
1832 	if (res_check(fh, EM28XX_RESOURCE_VIDEO)) {
1833 		videobuf_stop(&fh->vb_vidq);
1834 		res_free(fh, EM28XX_RESOURCE_VIDEO);
1835 	}
1836 
1837 	if (res_check(fh, EM28XX_RESOURCE_VBI)) {
1838 		videobuf_stop(&fh->vb_vbiq);
1839 		res_free(fh, EM28XX_RESOURCE_VBI);
1840 	}
1841 
1842 	if (dev->users == 1) {
1843 		/* the device is already disconnect,
1844 		   free the remaining resources */
1845 		if (dev->state & DEV_DISCONNECTED) {
1846 			em28xx_release_resources(dev);
1847 			kfree(dev->alt_max_pkt_size_isoc);
1848 			mutex_unlock(&dev->lock);
1849 			kfree(dev);
1850 			kfree(fh);
1851 			return 0;
1852 		}
1853 
1854 		/* Save some power by putting tuner to sleep */
1855 		v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_power, 0);
1856 
1857 		/* do this before setting alternate! */
1858 		em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1859 		em28xx_set_mode(dev, EM28XX_SUSPEND);
1860 
1861 		/* set alternate 0 */
1862 		dev->alt = 0;
1863 		em28xx_videodbg("setting alternate 0\n");
1864 		errCode = usb_set_interface(dev->udev, 0, 0);
1865 		if (errCode < 0) {
1866 			em28xx_errdev("cannot change alternate number to "
1867 					"0 (error=%i)\n", errCode);
1868 		}
1869 	}
1870 
1871 	videobuf_mmap_free(&fh->vb_vidq);
1872 	videobuf_mmap_free(&fh->vb_vbiq);
1873 	kfree(fh);
1874 	dev->users--;
1875 	mutex_unlock(&dev->lock);
1876 	return 0;
1877 }
1878 
1879 /*
1880  * em28xx_v4l2_read()
1881  * will allocate buffers when called for the first time
1882  */
1883 static ssize_t
1884 em28xx_v4l2_read(struct file *filp, char __user *buf, size_t count,
1885 		 loff_t *pos)
1886 {
1887 	struct em28xx_fh *fh = filp->private_data;
1888 	struct em28xx *dev = fh->dev;
1889 	int rc;
1890 
1891 	rc = check_dev(dev);
1892 	if (rc < 0)
1893 		return rc;
1894 
1895 	if (mutex_lock_interruptible(&dev->lock))
1896 		return -ERESTARTSYS;
1897 	/* FIXME: read() is not prepared to allow changing the video
1898 	   resolution while streaming. Seems a bug at em28xx_set_fmt
1899 	 */
1900 
1901 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1902 		if (res_locked(dev, EM28XX_RESOURCE_VIDEO))
1903 			rc = -EBUSY;
1904 		else
1905 			rc = videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1906 					filp->f_flags & O_NONBLOCK);
1907 	} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1908 		if (!res_get(fh, EM28XX_RESOURCE_VBI))
1909 			rc = -EBUSY;
1910 		else
1911 			rc = videobuf_read_stream(&fh->vb_vbiq, buf, count, pos, 0,
1912 					filp->f_flags & O_NONBLOCK);
1913 	}
1914 	mutex_unlock(&dev->lock);
1915 
1916 	return rc;
1917 }
1918 
1919 /*
1920  * em28xx_poll()
1921  * will allocate buffers when called for the first time
1922  */
1923 static unsigned int em28xx_poll(struct file *filp, poll_table *wait)
1924 {
1925 	struct em28xx_fh *fh = filp->private_data;
1926 	struct em28xx *dev = fh->dev;
1927 	int rc;
1928 
1929 	rc = check_dev(dev);
1930 	if (rc < 0)
1931 		return rc;
1932 
1933 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1934 		if (!res_get(fh, EM28XX_RESOURCE_VIDEO))
1935 			return POLLERR;
1936 		return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
1937 	} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1938 		if (!res_get(fh, EM28XX_RESOURCE_VBI))
1939 			return POLLERR;
1940 		return videobuf_poll_stream(filp, &fh->vb_vbiq, wait);
1941 	} else {
1942 		return POLLERR;
1943 	}
1944 }
1945 
1946 static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table *wait)
1947 {
1948 	struct em28xx_fh *fh = filp->private_data;
1949 	struct em28xx *dev = fh->dev;
1950 	unsigned int res;
1951 
1952 	mutex_lock(&dev->lock);
1953 	res = em28xx_poll(filp, wait);
1954 	mutex_unlock(&dev->lock);
1955 	return res;
1956 }
1957 
1958 /*
1959  * em28xx_v4l2_mmap()
1960  */
1961 static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
1962 {
1963 	struct em28xx_fh *fh    = filp->private_data;
1964 	struct em28xx	 *dev   = fh->dev;
1965 	int		 rc;
1966 
1967 	rc = check_dev(dev);
1968 	if (rc < 0)
1969 		return rc;
1970 
1971 	if (mutex_lock_interruptible(&dev->lock))
1972 		return -ERESTARTSYS;
1973 	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1974 		rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1975 	else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
1976 		rc = videobuf_mmap_mapper(&fh->vb_vbiq, vma);
1977 	mutex_unlock(&dev->lock);
1978 
1979 	em28xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
1980 		(unsigned long)vma->vm_start,
1981 		(unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1982 		rc);
1983 
1984 	return rc;
1985 }
1986 
1987 static const struct v4l2_file_operations em28xx_v4l_fops = {
1988 	.owner         = THIS_MODULE,
1989 	.open          = em28xx_v4l2_open,
1990 	.release       = em28xx_v4l2_close,
1991 	.read          = em28xx_v4l2_read,
1992 	.poll          = em28xx_v4l2_poll,
1993 	.mmap          = em28xx_v4l2_mmap,
1994 	.unlocked_ioctl = video_ioctl2,
1995 };
1996 
1997 static const struct v4l2_ioctl_ops video_ioctl_ops = {
1998 	.vidioc_querycap            = vidioc_querycap,
1999 	.vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
2000 	.vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
2001 	.vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
2002 	.vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
2003 	.vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2004 	.vidioc_s_fmt_vbi_cap       = vidioc_s_fmt_vbi_cap,
2005 	.vidioc_enum_framesizes     = vidioc_enum_framesizes,
2006 	.vidioc_g_audio             = vidioc_g_audio,
2007 	.vidioc_s_audio             = vidioc_s_audio,
2008 	.vidioc_cropcap             = vidioc_cropcap,
2009 	.vidioc_g_fmt_sliced_vbi_cap   = vidioc_g_fmt_sliced_vbi_cap,
2010 	.vidioc_try_fmt_sliced_vbi_cap = vidioc_try_set_sliced_vbi_cap,
2011 	.vidioc_s_fmt_sliced_vbi_cap   = vidioc_try_set_sliced_vbi_cap,
2012 
2013 	.vidioc_reqbufs             = vidioc_reqbufs,
2014 	.vidioc_querybuf            = vidioc_querybuf,
2015 	.vidioc_qbuf                = vidioc_qbuf,
2016 	.vidioc_dqbuf               = vidioc_dqbuf,
2017 	.vidioc_g_std               = vidioc_g_std,
2018 	.vidioc_querystd            = vidioc_querystd,
2019 	.vidioc_s_std               = vidioc_s_std,
2020 	.vidioc_g_parm		    = vidioc_g_parm,
2021 	.vidioc_s_parm		    = vidioc_s_parm,
2022 	.vidioc_enum_input          = vidioc_enum_input,
2023 	.vidioc_g_input             = vidioc_g_input,
2024 	.vidioc_s_input             = vidioc_s_input,
2025 	.vidioc_streamon            = vidioc_streamon,
2026 	.vidioc_streamoff           = vidioc_streamoff,
2027 	.vidioc_g_tuner             = vidioc_g_tuner,
2028 	.vidioc_s_tuner             = vidioc_s_tuner,
2029 	.vidioc_g_frequency         = vidioc_g_frequency,
2030 	.vidioc_s_frequency         = vidioc_s_frequency,
2031 #ifdef CONFIG_VIDEO_ADV_DEBUG
2032 	.vidioc_g_register          = vidioc_g_register,
2033 	.vidioc_s_register          = vidioc_s_register,
2034 	.vidioc_g_chip_ident        = vidioc_g_chip_ident,
2035 #endif
2036 };
2037 
2038 static const struct video_device em28xx_video_template = {
2039 	.fops                       = &em28xx_v4l_fops,
2040 	.release                    = video_device_release,
2041 	.ioctl_ops 		    = &video_ioctl_ops,
2042 
2043 	.tvnorms                    = V4L2_STD_ALL,
2044 	.current_norm               = V4L2_STD_PAL,
2045 };
2046 
2047 static const struct v4l2_file_operations radio_fops = {
2048 	.owner         = THIS_MODULE,
2049 	.open          = em28xx_v4l2_open,
2050 	.release       = em28xx_v4l2_close,
2051 	.unlocked_ioctl = video_ioctl2,
2052 };
2053 
2054 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2055 	.vidioc_querycap      = vidioc_querycap,
2056 	.vidioc_g_tuner       = radio_g_tuner,
2057 	.vidioc_s_tuner       = radio_s_tuner,
2058 	.vidioc_g_frequency   = vidioc_g_frequency,
2059 	.vidioc_s_frequency   = vidioc_s_frequency,
2060 #ifdef CONFIG_VIDEO_ADV_DEBUG
2061 	.vidioc_g_register    = vidioc_g_register,
2062 	.vidioc_s_register    = vidioc_s_register,
2063 #endif
2064 };
2065 
2066 static struct video_device em28xx_radio_template = {
2067 	.name                 = "em28xx-radio",
2068 	.fops                 = &radio_fops,
2069 	.ioctl_ops 	      = &radio_ioctl_ops,
2070 };
2071 
2072 /******************************** usb interface ******************************/
2073 
2074 
2075 
2076 static struct video_device *em28xx_vdev_init(struct em28xx *dev,
2077 					const struct video_device *template,
2078 					const char *type_name)
2079 {
2080 	struct video_device *vfd;
2081 
2082 	vfd = video_device_alloc();
2083 	if (NULL == vfd)
2084 		return NULL;
2085 
2086 	*vfd		= *template;
2087 	vfd->v4l2_dev	= &dev->v4l2_dev;
2088 	vfd->release	= video_device_release;
2089 	vfd->debug	= video_debug;
2090 	vfd->lock	= &dev->lock;
2091 
2092 	snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2093 		 dev->name, type_name);
2094 
2095 	video_set_drvdata(vfd, dev);
2096 	return vfd;
2097 }
2098 
2099 int em28xx_register_analog_devices(struct em28xx *dev)
2100 {
2101 	u8 val;
2102 	int ret;
2103 	unsigned int maxw;
2104 
2105 	printk(KERN_INFO "%s: v4l2 driver version %s\n",
2106 		dev->name, EM28XX_VERSION);
2107 
2108 	/* set default norm */
2109 	dev->norm = em28xx_video_template.current_norm;
2110 	v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std, dev->norm);
2111 	dev->interlaced = EM28XX_INTERLACED_DEFAULT;
2112 
2113 	/* Analog specific initialization */
2114 	dev->format = &format[0];
2115 
2116 	maxw = norm_maxw(dev);
2117         /* MaxPacketSize for em2800 is too small to capture at full resolution
2118          * use half of maxw as the scaler can only scale to 50% */
2119         if (dev->board.is_em2800)
2120             maxw /= 2;
2121 
2122 	em28xx_set_video_format(dev, format[0].fourcc,
2123 				maxw, norm_maxh(dev));
2124 
2125 	video_mux(dev, 0);
2126 
2127 	/* Audio defaults */
2128 	dev->mute = 1;
2129 	dev->volume = 0x1f;
2130 
2131 /*	em28xx_write_reg(dev, EM28XX_R0E_AUDIOSRC, 0xc0); audio register */
2132 	val = (u8)em28xx_read_reg(dev, EM28XX_R0F_XCLK);
2133 	em28xx_write_reg(dev, EM28XX_R0F_XCLK,
2134 			 (EM28XX_XCLK_AUDIO_UNMUTE | val));
2135 
2136 	em28xx_set_outfmt(dev);
2137 	em28xx_colorlevels_set_default(dev);
2138 	em28xx_compression_disable(dev);
2139 
2140 	/* allocate and fill video video_device struct */
2141 	dev->vdev = em28xx_vdev_init(dev, &em28xx_video_template, "video");
2142 	if (!dev->vdev) {
2143 		em28xx_errdev("cannot allocate video_device.\n");
2144 		return -ENODEV;
2145 	}
2146 
2147 	/* register v4l2 video video_device */
2148 	ret = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2149 				       video_nr[dev->devno]);
2150 	if (ret) {
2151 		em28xx_errdev("unable to register video device (error=%i).\n",
2152 			      ret);
2153 		return ret;
2154 	}
2155 
2156 	/* Allocate and fill vbi video_device struct */
2157 	if (em28xx_vbi_supported(dev) == 1) {
2158 		dev->vbi_dev = em28xx_vdev_init(dev, &em28xx_video_template,
2159 						"vbi");
2160 
2161 		/* register v4l2 vbi video_device */
2162 		ret = video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2163 					    vbi_nr[dev->devno]);
2164 		if (ret < 0) {
2165 			em28xx_errdev("unable to register vbi device\n");
2166 			return ret;
2167 		}
2168 	}
2169 
2170 	if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2171 		dev->radio_dev = em28xx_vdev_init(dev, &em28xx_radio_template,
2172 						  "radio");
2173 		if (!dev->radio_dev) {
2174 			em28xx_errdev("cannot allocate video_device.\n");
2175 			return -ENODEV;
2176 		}
2177 		ret = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2178 					    radio_nr[dev->devno]);
2179 		if (ret < 0) {
2180 			em28xx_errdev("can't register radio device\n");
2181 			return ret;
2182 		}
2183 		em28xx_info("Registered radio device as %s\n",
2184 			    video_device_node_name(dev->radio_dev));
2185 	}
2186 
2187 	em28xx_info("V4L2 video device registered as %s\n",
2188 		    video_device_node_name(dev->vdev));
2189 
2190 	if (dev->vbi_dev)
2191 		em28xx_info("V4L2 VBI device registered as %s\n",
2192 			    video_device_node_name(dev->vbi_dev));
2193 
2194 	return 0;
2195 }
2196