em28xx-video.c revision d2d9fbfd732f49999a2a94f2479934488fe3ea9d
1/*
2   em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB video capture devices
3
4   Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
5		      Markus Rechberger <mrechberger@gmail.com>
6		      Mauro Carvalho Chehab <mchehab@infradead.org>
7		      Sascha Sommer <saschasommer@freenet.de>
8
9	Some parts based on SN9C10x PC Camera Controllers GPL driver made
10		by Luca Risolia <luca.risolia@studio.unibo.it>
11
12   This program is free software; you can redistribute it and/or modify
13   it under the terms of the GNU General Public License as published by
14   the Free Software Foundation; either version 2 of the License, or
15   (at your option) any later version.
16
17   This program is distributed in the hope that it will be useful,
18   but WITHOUT ANY WARRANTY; without even the implied warranty of
19   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20   GNU General Public License for more details.
21
22   You should have received a copy of the GNU General Public License
23   along with this program; if not, write to the Free Software
24   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */
26
27#include <linux/init.h>
28#include <linux/list.h>
29#include <linux/module.h>
30#include <linux/kernel.h>
31#include <linux/bitmap.h>
32#include <linux/usb.h>
33#include <linux/i2c.h>
34#include <linux/version.h>
35#include <linux/mm.h>
36#include <linux/mutex.h>
37
38#include "em28xx.h"
39#include <media/v4l2-common.h>
40#include <media/msp3400.h>
41#include <media/tuner.h>
42
43#define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
44		      "Markus Rechberger <mrechberger@gmail.com>, " \
45		      "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
46		      "Sascha Sommer <saschasommer@freenet.de>"
47
48#define DRIVER_NAME         "em28xx"
49#define DRIVER_DESC         "Empia em28xx based USB video device driver"
50#define EM28XX_VERSION_CODE  KERNEL_VERSION(0, 1, 0)
51
52#define em28xx_videodbg(fmt, arg...) do {\
53	if (video_debug) \
54		printk(KERN_INFO "%s %s :"fmt, \
55			 dev->name, __func__ , ##arg); } while (0)
56
57static unsigned int isoc_debug;
58module_param(isoc_debug, int, 0644);
59MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
60
61#define em28xx_isocdbg(fmt, arg...) do {\
62	if (isoc_debug) \
63		printk(KERN_INFO "%s %s :"fmt, \
64			 dev->name, __func__ , ##arg); } while (0)
65
66MODULE_AUTHOR(DRIVER_AUTHOR);
67MODULE_DESCRIPTION(DRIVER_DESC);
68MODULE_LICENSE("GPL");
69
70static LIST_HEAD(em28xx_devlist);
71
72static unsigned int card[]     = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
73static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
74static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
75static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
76
77module_param_array(card,  int, NULL, 0444);
78module_param_array(video_nr, int, NULL, 0444);
79module_param_array(vbi_nr, int, NULL, 0444);
80module_param_array(radio_nr, int, NULL, 0444);
81MODULE_PARM_DESC(card,     "card type");
82MODULE_PARM_DESC(video_nr, "video device numbers");
83MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
84MODULE_PARM_DESC(radio_nr, "radio device numbers");
85
86static unsigned int video_debug;
87module_param(video_debug,int,0644);
88MODULE_PARM_DESC(video_debug,"enable debug messages [video]");
89
90/* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
91static unsigned long em28xx_devused;
92
93/* supported controls */
94/* Common to all boards */
95static struct v4l2_queryctrl em28xx_qctrl[] = {
96	{
97		.id = V4L2_CID_AUDIO_VOLUME,
98		.type = V4L2_CTRL_TYPE_INTEGER,
99		.name = "Volume",
100		.minimum = 0x0,
101		.maximum = 0x1f,
102		.step = 0x1,
103		.default_value = 0x1f,
104		.flags = 0,
105	},{
106		.id = V4L2_CID_AUDIO_MUTE,
107		.type = V4L2_CTRL_TYPE_BOOLEAN,
108		.name = "Mute",
109		.minimum = 0,
110		.maximum = 1,
111		.step = 1,
112		.default_value = 1,
113		.flags = 0,
114	}
115};
116
117static struct usb_driver em28xx_usb_driver;
118
119/* ------------------------------------------------------------------
120	DMA and thread functions
121   ------------------------------------------------------------------*/
122
123/*
124 * Announces that a buffer were filled and request the next
125 */
126static inline void buffer_filled(struct em28xx *dev,
127				  struct em28xx_dmaqueue *dma_q,
128				  struct em28xx_buffer *buf)
129{
130	/* Advice that buffer was filled */
131	em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
132	buf->vb.state = VIDEOBUF_DONE;
133	buf->vb.field_count++;
134	do_gettimeofday(&buf->vb.ts);
135
136	dev->isoc_ctl.buf = NULL;
137
138	list_del(&buf->vb.queue);
139	wake_up(&buf->vb.done);
140}
141
142/*
143 * Identify the buffer header type and properly handles
144 */
145static void em28xx_copy_video(struct em28xx *dev,
146			      struct em28xx_dmaqueue  *dma_q,
147			      struct em28xx_buffer *buf,
148			      unsigned char *p,
149			      unsigned char *outp, unsigned long len)
150{
151	void *fieldstart, *startwrite, *startread;
152	int  linesdone, currlinedone, offset, lencopy, remain;
153	int bytesperline = dev->width << 1;
154
155	if (dma_q->pos + len > buf->vb.size)
156		len = buf->vb.size - dma_q->pos;
157
158	if (p[0] != 0x88 && p[0] != 0x22) {
159		em28xx_isocdbg("frame is not complete\n");
160		len += 4;
161	} else
162		p += 4;
163
164	startread = p;
165	remain = len;
166
167	/* Interlaces frame */
168	if (buf->top_field)
169		fieldstart = outp;
170	else
171		fieldstart = outp + bytesperline;
172
173	linesdone = dma_q->pos / bytesperline;
174	currlinedone = dma_q->pos % bytesperline;
175	offset = linesdone * bytesperline * 2 + currlinedone;
176	startwrite = fieldstart + offset;
177	lencopy = bytesperline - currlinedone;
178	lencopy = lencopy > remain ? remain : lencopy;
179
180	if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
181		em28xx_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
182			       ((char *)startwrite + lencopy) -
183			       ((char *)outp + buf->vb.size));
184		lencopy = remain = (char *)outp + buf->vb.size - (char *)startwrite;
185	}
186	if (lencopy <= 0)
187		return;
188	memcpy(startwrite, startread, lencopy);
189
190	remain -= lencopy;
191
192	while (remain > 0) {
193		startwrite += lencopy + bytesperline;
194		startread += lencopy;
195		if (bytesperline > remain)
196			lencopy = remain;
197		else
198			lencopy = bytesperline;
199
200		if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
201			em28xx_isocdbg("Overflow of %zi bytes past buffer end (2)\n",
202				       ((char *)startwrite + lencopy) -
203				       ((char *)outp + buf->vb.size));
204			lencopy = remain = (char *)outp + buf->vb.size -
205					   (char *)startwrite;
206		}
207		if (lencopy <= 0)
208			break;
209
210		memcpy(startwrite, startread, lencopy);
211
212		remain -= lencopy;
213	}
214
215	dma_q->pos += len;
216}
217
218static inline void print_err_status(struct em28xx *dev,
219				     int packet, int status)
220{
221	char *errmsg = "Unknown";
222
223	switch (status) {
224	case -ENOENT:
225		errmsg = "unlinked synchronuously";
226		break;
227	case -ECONNRESET:
228		errmsg = "unlinked asynchronuously";
229		break;
230	case -ENOSR:
231		errmsg = "Buffer error (overrun)";
232		break;
233	case -EPIPE:
234		errmsg = "Stalled (device not responding)";
235		break;
236	case -EOVERFLOW:
237		errmsg = "Babble (bad cable?)";
238		break;
239	case -EPROTO:
240		errmsg = "Bit-stuff error (bad cable?)";
241		break;
242	case -EILSEQ:
243		errmsg = "CRC/Timeout (could be anything)";
244		break;
245	case -ETIME:
246		errmsg = "Device does not respond";
247		break;
248	}
249	if (packet < 0) {
250		em28xx_isocdbg("URB status %d [%s].\n",	status, errmsg);
251	} else {
252		em28xx_isocdbg("URB packet %d, status %d [%s].\n",
253			       packet, status, errmsg);
254	}
255}
256
257/*
258 * video-buf generic routine to get the next available buffer
259 */
260static inline void get_next_buf(struct em28xx_dmaqueue *dma_q,
261					  struct em28xx_buffer **buf)
262{
263	struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
264	char *outp;
265
266	if (list_empty(&dma_q->active)) {
267		em28xx_isocdbg("No active queue to serve\n");
268		dev->isoc_ctl.buf = NULL;
269		*buf = NULL;
270		return;
271	}
272
273	/* Get the next buffer */
274	*buf = list_entry(dma_q->active.next, struct em28xx_buffer, vb.queue);
275
276	/* Cleans up buffer - Usefull for testing for frame/URB loss */
277	outp = videobuf_to_vmalloc(&(*buf)->vb);
278	memset(outp, 0, (*buf)->vb.size);
279
280	dev->isoc_ctl.buf = *buf;
281
282	return;
283}
284
285/*
286 * Controls the isoc copy of each urb packet
287 */
288static inline int em28xx_isoc_copy(struct urb *urb)
289{
290	struct em28xx_buffer    *buf;
291	struct em28xx_dmaqueue  *dma_q = urb->context;
292	struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
293	unsigned char *outp = NULL;
294	int i, len = 0, rc = 1;
295	unsigned char *p;
296
297	if (!dev)
298		return 0;
299
300	if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
301		return 0;
302
303	if (urb->status < 0) {
304		print_err_status(dev, -1, urb->status);
305		if (urb->status == -ENOENT)
306			return 0;
307	}
308
309	buf = dev->isoc_ctl.buf;
310	if (buf != NULL)
311		outp = videobuf_to_vmalloc(&buf->vb);
312
313	for (i = 0; i < urb->number_of_packets; i++) {
314		int status = urb->iso_frame_desc[i].status;
315
316		if (status < 0) {
317			print_err_status(dev, i, status);
318			if (urb->iso_frame_desc[i].status != -EPROTO)
319				continue;
320		}
321
322		len = urb->iso_frame_desc[i].actual_length - 4;
323
324		if (urb->iso_frame_desc[i].actual_length <= 0) {
325			/* em28xx_isocdbg("packet %d is empty",i); - spammy */
326			continue;
327		}
328		if (urb->iso_frame_desc[i].actual_length >
329						dev->max_pkt_size) {
330			em28xx_isocdbg("packet bigger than packet size");
331			continue;
332		}
333
334		p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
335
336		/* FIXME: incomplete buffer checks where removed to make
337		   logic simpler. Impacts of those changes should be evaluated
338		 */
339		if (p[0] == 0x33 && p[1] == 0x95 && p[2] == 0x00) {
340			em28xx_isocdbg("VBI HEADER!!!\n");
341			/* FIXME: Should add vbi copy */
342			continue;
343		}
344		if (p[0] == 0x22 && p[1] == 0x5a) {
345			em28xx_isocdbg("Video frame %d, length=%i, %s\n", p[2],
346				       len, (p[2] & 1)? "odd" : "even");
347
348			if (!(p[2] & 1)) {
349				if (buf != NULL)
350					buffer_filled(dev, dma_q, buf);
351				get_next_buf(dma_q, &buf);
352				if (buf == NULL)
353					outp = NULL;
354				else
355					outp = videobuf_to_vmalloc(&buf->vb);
356			}
357
358			if (buf != NULL) {
359				if (p[2] & 1)
360					buf->top_field = 0;
361				else
362					buf->top_field = 1;
363			}
364
365			dma_q->pos = 0;
366		}
367		if (buf != NULL)
368			em28xx_copy_video(dev, dma_q, buf, p, outp, len);
369	}
370	return rc;
371}
372
373/* ------------------------------------------------------------------
374	URB control
375   ------------------------------------------------------------------*/
376
377/*
378 * IRQ callback, called by URB callback
379 */
380static void em28xx_irq_callback(struct urb *urb)
381{
382	struct em28xx_dmaqueue  *dma_q = urb->context;
383	struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
384	int rc, i;
385
386	/* Copy data from URB */
387	spin_lock(&dev->slock);
388	rc = em28xx_isoc_copy(urb);
389	spin_unlock(&dev->slock);
390
391	/* Reset urb buffers */
392	for (i = 0; i < urb->number_of_packets; i++) {
393		urb->iso_frame_desc[i].status = 0;
394		urb->iso_frame_desc[i].actual_length = 0;
395	}
396	urb->status = 0;
397
398	urb->status = usb_submit_urb(urb, GFP_ATOMIC);
399	if (urb->status) {
400		em28xx_err("urb resubmit failed (error=%i)\n",
401			urb->status);
402	}
403}
404
405/*
406 * Stop and Deallocate URBs
407 */
408static void em28xx_uninit_isoc(struct em28xx *dev)
409{
410	struct urb *urb;
411	int i;
412
413	em28xx_isocdbg("em28xx: called em28xx_uninit_isoc\n");
414
415	dev->isoc_ctl.nfields = -1;
416	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
417		urb = dev->isoc_ctl.urb[i];
418		if (urb) {
419			usb_kill_urb(urb);
420			usb_unlink_urb(urb);
421			if (dev->isoc_ctl.transfer_buffer[i]) {
422				usb_buffer_free(dev->udev,
423						urb->transfer_buffer_length,
424						dev->isoc_ctl.transfer_buffer[i],
425						urb->transfer_dma);
426			}
427			usb_free_urb(urb);
428			dev->isoc_ctl.urb[i] = NULL;
429		}
430		dev->isoc_ctl.transfer_buffer[i] = NULL;
431	}
432
433	kfree(dev->isoc_ctl.urb);
434	kfree(dev->isoc_ctl.transfer_buffer);
435	dev->isoc_ctl.urb = NULL;
436	dev->isoc_ctl.transfer_buffer = NULL;
437
438	dev->isoc_ctl.num_bufs = 0;
439
440	em28xx_capture_start(dev, 0);
441}
442
443/*
444 * Allocate URBs and start IRQ
445 */
446static int em28xx_prepare_isoc(struct em28xx *dev, int max_packets,
447			       int num_bufs)
448{
449	struct em28xx_dmaqueue *dma_q = &dev->vidq;
450	int i;
451	int sb_size, pipe;
452	struct urb *urb;
453	int j, k;
454
455	em28xx_isocdbg("em28xx: called em28xx_prepare_isoc\n");
456
457	/* De-allocates all pending stuff */
458	em28xx_uninit_isoc(dev);
459
460	dev->isoc_ctl.num_bufs = num_bufs;
461
462	dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs,  GFP_KERNEL);
463	if (!dev->isoc_ctl.urb) {
464		em28xx_errdev("cannot alloc memory for usb buffers\n");
465		return -ENOMEM;
466	}
467
468	dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
469					      GFP_KERNEL);
470	if (!dev->isoc_ctl.urb) {
471		em28xx_errdev("cannot allocate memory for usbtransfer\n");
472		kfree(dev->isoc_ctl.urb);
473		return -ENOMEM;
474	}
475
476	dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
477	dev->isoc_ctl.buf = NULL;
478
479	sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
480
481	/* allocate urbs and transfer buffers */
482	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
483		urb = usb_alloc_urb(max_packets, GFP_KERNEL);
484		if (!urb) {
485			em28xx_err("cannot alloc isoc_ctl.urb %i\n", i);
486			em28xx_uninit_isoc(dev);
487			return -ENOMEM;
488		}
489		dev->isoc_ctl.urb[i] = urb;
490
491		dev->isoc_ctl.transfer_buffer[i] = usb_buffer_alloc(dev->udev,
492			sb_size, GFP_KERNEL, &urb->transfer_dma);
493		if (!dev->isoc_ctl.transfer_buffer[i]) {
494			em28xx_err("unable to allocate %i bytes for transfer"
495					" buffer %i%s\n",
496					sb_size, i,
497					in_interrupt()?" while in int":"");
498			em28xx_uninit_isoc(dev);
499			return -ENOMEM;
500		}
501		memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
502
503		/* FIXME: this is a hack - should be
504			'desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK'
505			should also be using 'desc.bInterval'
506		 */
507		pipe = usb_rcvisocpipe(dev->udev, 0x82);
508		usb_fill_int_urb(urb, dev->udev, pipe,
509				 dev->isoc_ctl.transfer_buffer[i], sb_size,
510				 em28xx_irq_callback, dma_q, 1);
511
512		urb->number_of_packets = max_packets;
513		urb->transfer_flags = URB_ISO_ASAP;
514
515		k = 0;
516		for (j = 0; j < max_packets; j++) {
517			urb->iso_frame_desc[j].offset = k;
518			urb->iso_frame_desc[j].length =
519						dev->isoc_ctl.max_pkt_size;
520			k += dev->isoc_ctl.max_pkt_size;
521		}
522	}
523
524	return 0;
525}
526
527static int em28xx_start_thread(struct em28xx_dmaqueue  *dma_q)
528{
529	struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
530	int i, rc = 0;
531
532	em28xx_videodbg("Called em28xx_start_thread\n");
533
534	init_waitqueue_head(&dma_q->wq);
535
536	em28xx_capture_start(dev, 1);
537
538	/* submit urbs and enables IRQ */
539	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
540		rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
541		if (rc) {
542			em28xx_err("submit of urb %i failed (error=%i)\n", i,
543				   rc);
544			em28xx_uninit_isoc(dev);
545			return rc;
546		}
547	}
548
549	if (rc < 0)
550		return rc;
551
552	return 0;
553}
554
555/* ------------------------------------------------------------------
556	Videobuf operations
557   ------------------------------------------------------------------*/
558
559static int
560buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
561{
562	struct em28xx_fh *fh = vq->priv_data;
563	struct em28xx        *dev = fh->dev;
564	struct v4l2_frequency f;
565
566	*size = 16 * fh->dev->width * fh->dev->height >> 3;
567	if (0 == *count)
568		*count = EM28XX_DEF_BUF;
569
570	if (*count < EM28XX_MIN_BUF)
571		*count = EM28XX_MIN_BUF;
572
573	dev->mode = EM28XX_ANALOG_MODE;
574
575	/* Ask tuner to go to analog mode */
576	memset (&f, 0, sizeof(f));
577	f.frequency = dev->ctl_freq;
578
579	em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, &f);
580
581	return 0;
582}
583
584/* This is called *without* dev->slock held; please keep it that way */
585static void free_buffer(struct videobuf_queue *vq, struct em28xx_buffer *buf)
586{
587	struct em28xx_fh     *fh  = vq->priv_data;
588	struct em28xx        *dev = fh->dev;
589	unsigned long flags = 0;
590	if (in_interrupt())
591		BUG();
592
593	/* We used to wait for the buffer to finish here, but this didn't work
594	   because, as we were keeping the state as VIDEOBUF_QUEUED,
595	   videobuf_queue_cancel marked it as finished for us.
596	   (Also, it could wedge forever if the hardware was misconfigured.)
597
598	   This should be safe; by the time we get here, the buffer isn't
599	   queued anymore. If we ever start marking the buffers as
600	   VIDEOBUF_ACTIVE, it won't be, though.
601	*/
602	spin_lock_irqsave(&dev->slock, flags);
603	if (dev->isoc_ctl.buf == buf)
604		dev->isoc_ctl.buf = NULL;
605	spin_unlock_irqrestore(&dev->slock, flags);
606
607	videobuf_vmalloc_free(&buf->vb);
608	buf->vb.state = VIDEOBUF_NEEDS_INIT;
609}
610
611static int
612buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
613						enum v4l2_field field)
614{
615	struct em28xx_fh     *fh  = vq->priv_data;
616	struct em28xx_buffer *buf = container_of(vb, struct em28xx_buffer, vb);
617	struct em28xx        *dev = fh->dev;
618	struct em28xx_dmaqueue *vidq = &dev->vidq;
619	int                  rc = 0, urb_init = 0;
620
621	/* FIXME: It assumes depth = 16 */
622	/* The only currently supported format is 16 bits/pixel */
623	buf->vb.size = 16 * dev->width * dev->height >> 3;
624
625	if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
626		return -EINVAL;
627
628	buf->vb.width  = dev->width;
629	buf->vb.height = dev->height;
630	buf->vb.field  = field;
631
632	if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
633		rc = videobuf_iolock(vq, &buf->vb, NULL);
634		if (rc < 0)
635			goto fail;
636	}
637
638	if (!dev->isoc_ctl.num_bufs)
639		urb_init = 1;
640
641	if (urb_init) {
642		rc = em28xx_prepare_isoc(dev, EM28XX_NUM_PACKETS,
643					 EM28XX_NUM_BUFS);
644		if (rc < 0)
645			goto fail;
646
647		rc = em28xx_start_thread(vidq);
648		if (rc < 0)
649			goto fail;
650	}
651
652	buf->vb.state = VIDEOBUF_PREPARED;
653	return 0;
654
655fail:
656	free_buffer(vq, buf);
657	return rc;
658}
659
660static void
661buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
662{
663	struct em28xx_buffer    *buf     = container_of(vb, struct em28xx_buffer, vb);
664	struct em28xx_fh        *fh      = vq->priv_data;
665	struct em28xx           *dev     = fh->dev;
666	struct em28xx_dmaqueue  *vidq    = &dev->vidq;
667
668	buf->vb.state = VIDEOBUF_QUEUED;
669	list_add_tail(&buf->vb.queue, &vidq->active);
670
671}
672
673static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
674{
675	struct em28xx_buffer   *buf  = container_of(vb, struct em28xx_buffer, vb);
676	struct em28xx_fh       *fh   = vq->priv_data;
677	struct em28xx          *dev  = (struct em28xx *)fh->dev;
678
679	em28xx_isocdbg("em28xx: called buffer_release\n");
680
681	free_buffer(vq, buf);
682}
683
684static struct videobuf_queue_ops em28xx_video_qops = {
685	.buf_setup      = buffer_setup,
686	.buf_prepare    = buffer_prepare,
687	.buf_queue      = buffer_queue,
688	.buf_release    = buffer_release,
689};
690
691/*********************  v4l2 interface  ******************************************/
692
693/*
694 * em28xx_config()
695 * inits registers with sane defaults
696 */
697static int em28xx_config(struct em28xx *dev)
698{
699
700	/* Sets I2C speed to 100 KHz */
701	if (!dev->is_em2800)
702		em28xx_write_regs_req(dev, 0x00, 0x06, "\x40", 1);
703
704	/* enable vbi capturing */
705
706/*	em28xx_write_regs_req(dev,0x00,0x0e,"\xC0",1); audio register */
707/*	em28xx_write_regs_req(dev,0x00,0x0f,"\x80",1); clk register */
708	em28xx_write_regs_req(dev,0x00,0x11,"\x51",1);
709
710	dev->mute = 1;		/* maybe not the right place... */
711	dev->volume = 0x1f;
712
713	em28xx_outfmt_set_yuv422(dev);
714	em28xx_colorlevels_set_default(dev);
715	em28xx_compression_disable(dev);
716
717	return 0;
718}
719
720/*
721 * em28xx_config_i2c()
722 * configure i2c attached devices
723 */
724static void em28xx_config_i2c(struct em28xx *dev)
725{
726	struct v4l2_routing route;
727
728	route.input = INPUT(dev->ctl_input)->vmux;
729	route.output = 0;
730	em28xx_i2c_call_clients(dev, VIDIOC_INT_RESET, NULL);
731	em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
732	em28xx_i2c_call_clients(dev, VIDIOC_STREAMON, NULL);
733}
734
735static void video_mux(struct em28xx *dev, int index)
736{
737	struct v4l2_routing route;
738
739	route.input = INPUT(index)->vmux;
740	route.output = 0;
741	dev->ctl_input = index;
742	dev->ctl_ainput = INPUT(index)->amux;
743
744	em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
745
746	if (dev->has_msp34xx) {
747		if (dev->i2s_speed)
748			em28xx_i2c_call_clients(dev, VIDIOC_INT_I2S_CLOCK_FREQ, &dev->i2s_speed);
749		route.input = dev->ctl_ainput;
750		route.output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
751		/* Note: this is msp3400 specific */
752		em28xx_i2c_call_clients(dev, VIDIOC_INT_S_AUDIO_ROUTING, &route);
753	}
754
755	em28xx_audio_analog_set(dev);
756}
757
758/* Usage lock check functions */
759static int res_get(struct em28xx_fh *fh)
760{
761	struct em28xx    *dev = fh->dev;
762	int		 rc   = 0;
763
764	/* This instance already has stream_on */
765	if (fh->stream_on)
766		return rc;
767
768	if (dev->stream_on)
769		return -EINVAL;
770
771	mutex_lock(&dev->lock);
772	dev->stream_on = 1;
773	fh->stream_on  = 1;
774	mutex_unlock(&dev->lock);
775	return rc;
776}
777
778static int res_check(struct em28xx_fh *fh)
779{
780	return (fh->stream_on);
781}
782
783static void res_free(struct em28xx_fh *fh)
784{
785	struct em28xx    *dev = fh->dev;
786
787	mutex_lock(&dev->lock);
788	fh->stream_on = 0;
789	dev->stream_on = 0;
790	mutex_unlock(&dev->lock);
791}
792
793/*
794 * em28xx_get_ctrl()
795 * return the current saturation, brightness or contrast, mute state
796 */
797static int em28xx_get_ctrl(struct em28xx *dev, struct v4l2_control *ctrl)
798{
799	switch (ctrl->id) {
800	case V4L2_CID_AUDIO_MUTE:
801		ctrl->value = dev->mute;
802		return 0;
803	case V4L2_CID_AUDIO_VOLUME:
804		ctrl->value = dev->volume;
805		return 0;
806	default:
807		return -EINVAL;
808	}
809}
810
811/*
812 * em28xx_set_ctrl()
813 * mute or set new saturation, brightness or contrast
814 */
815static int em28xx_set_ctrl(struct em28xx *dev, const struct v4l2_control *ctrl)
816{
817	switch (ctrl->id) {
818	case V4L2_CID_AUDIO_MUTE:
819		if (ctrl->value != dev->mute) {
820			dev->mute = ctrl->value;
821			return em28xx_audio_analog_set(dev);
822		}
823		return 0;
824	case V4L2_CID_AUDIO_VOLUME:
825		dev->volume = ctrl->value;
826		return em28xx_audio_analog_set(dev);
827	default:
828		return -EINVAL;
829	}
830}
831
832static int check_dev(struct em28xx *dev)
833{
834	if (dev->state & DEV_DISCONNECTED) {
835		em28xx_errdev("v4l2 ioctl: device not present\n");
836		return -ENODEV;
837	}
838
839	if (dev->state & DEV_MISCONFIGURED) {
840		em28xx_errdev("v4l2 ioctl: device is misconfigured; "
841			      "close and open it again\n");
842		return -EIO;
843	}
844	return 0;
845}
846
847static void get_scale(struct em28xx *dev,
848			unsigned int width, unsigned int height,
849			unsigned int *hscale, unsigned int *vscale)
850{
851	unsigned int          maxw   = norm_maxw(dev);
852	unsigned int          maxh   = norm_maxh(dev);
853
854	*hscale = (((unsigned long)maxw) << 12) / width - 4096L;
855	if (*hscale >= 0x4000)
856		*hscale = 0x3fff;
857
858	*vscale = (((unsigned long)maxh) << 12) / height - 4096L;
859	if (*vscale >= 0x4000)
860		*vscale = 0x3fff;
861}
862
863/* ------------------------------------------------------------------
864	IOCTL vidioc handling
865   ------------------------------------------------------------------*/
866
867static int vidioc_g_fmt_cap(struct file *file, void *priv,
868					struct v4l2_format *f)
869{
870	struct em28xx_fh      *fh  = priv;
871	struct em28xx         *dev = fh->dev;
872
873	mutex_lock(&dev->lock);
874
875	f->fmt.pix.width = dev->width;
876	f->fmt.pix.height = dev->height;
877	f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
878	f->fmt.pix.bytesperline = dev->width * 2;
879	f->fmt.pix.sizeimage = f->fmt.pix.bytesperline  * dev->height;
880	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
881
882	/* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
883	f->fmt.pix.field = dev->interlaced ?
884			   V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
885
886	mutex_unlock(&dev->lock);
887	return 0;
888}
889
890static int vidioc_try_fmt_cap(struct file *file, void *priv,
891			struct v4l2_format *f)
892{
893	struct em28xx_fh      *fh    = priv;
894	struct em28xx         *dev   = fh->dev;
895	int                   width  = f->fmt.pix.width;
896	int                   height = f->fmt.pix.height;
897	unsigned int          maxw   = norm_maxw(dev);
898	unsigned int          maxh   = norm_maxh(dev);
899	unsigned int          hscale, vscale;
900
901	/* width must even because of the YUYV format
902	   height must be even because of interlacing */
903	height &= 0xfffe;
904	width &= 0xfffe;
905
906	if (height < 32)
907		height = 32;
908	if (height > maxh)
909		height = maxh;
910	if (width < 48)
911		width = 48;
912	if (width > maxw)
913		width = maxw;
914
915	mutex_lock(&dev->lock);
916
917	if (dev->is_em2800) {
918		/* the em2800 can only scale down to 50% */
919		if (height % (maxh / 2))
920			height = maxh;
921		if (width % (maxw / 2))
922			width = maxw;
923		/* according to empiatech support */
924		/* the MaxPacketSize is to small to support */
925		/* framesizes larger than 640x480 @ 30 fps */
926		/* or 640x576 @ 25 fps. As this would cut */
927		/* of a part of the image we prefer */
928		/* 360x576 or 360x480 for now */
929		if (width == maxw && height == maxh)
930			width /= 2;
931	}
932
933	get_scale(dev, width, height, &hscale, &vscale);
934
935	width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
936	height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
937
938	f->fmt.pix.width = width;
939	f->fmt.pix.height = height;
940	f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
941	f->fmt.pix.bytesperline = width * 2;
942	f->fmt.pix.sizeimage = width * 2 * height;
943	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
944	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
945
946	mutex_unlock(&dev->lock);
947	return 0;
948}
949
950static int vidioc_s_fmt_cap(struct file *file, void *priv,
951			struct v4l2_format *f)
952{
953	struct em28xx_fh      *fh  = priv;
954	struct em28xx         *dev = fh->dev;
955	int                   rc;
956
957	rc = check_dev(dev);
958	if (rc < 0)
959		return rc;
960
961	vidioc_try_fmt_cap(file, priv, f);
962
963	mutex_lock(&dev->lock);
964
965	if (videobuf_queue_is_busy(&fh->vb_vidq)) {
966		em28xx_errdev("%s queue busy\n", __func__);
967		rc = -EBUSY;
968		goto out;
969	}
970
971	if (dev->stream_on && !fh->stream_on) {
972		em28xx_errdev("%s device in use by another fh\n", __func__);
973		rc = -EBUSY;
974		goto out;
975	}
976
977	/* set new image size */
978	dev->width = f->fmt.pix.width;
979	dev->height = f->fmt.pix.height;
980	get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
981
982	em28xx_set_alternate(dev);
983	em28xx_resolution_set(dev);
984
985	rc = 0;
986
987out:
988	mutex_unlock(&dev->lock);
989	return rc;
990}
991
992static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm)
993{
994	struct em28xx_fh   *fh  = priv;
995	struct em28xx      *dev = fh->dev;
996	struct v4l2_format f;
997	int                rc;
998
999	rc = check_dev(dev);
1000	if (rc < 0)
1001		return rc;
1002
1003	mutex_lock(&dev->lock);
1004	dev->norm = *norm;
1005	mutex_unlock(&dev->lock);
1006
1007	/* Adjusts width/height, if needed */
1008	f.fmt.pix.width = dev->width;
1009	f.fmt.pix.height = dev->height;
1010	vidioc_try_fmt_cap(file, priv, &f);
1011
1012	mutex_lock(&dev->lock);
1013
1014	/* set new image size */
1015	dev->width = f.fmt.pix.width;
1016	dev->height = f.fmt.pix.height;
1017	get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
1018
1019	em28xx_resolution_set(dev);
1020	em28xx_i2c_call_clients(dev, VIDIOC_S_STD, &dev->norm);
1021
1022	mutex_unlock(&dev->lock);
1023	return 0;
1024}
1025
1026static const char *iname[] = {
1027	[EM28XX_VMUX_COMPOSITE1] = "Composite1",
1028	[EM28XX_VMUX_COMPOSITE2] = "Composite2",
1029	[EM28XX_VMUX_COMPOSITE3] = "Composite3",
1030	[EM28XX_VMUX_COMPOSITE4] = "Composite4",
1031	[EM28XX_VMUX_SVIDEO]     = "S-Video",
1032	[EM28XX_VMUX_TELEVISION] = "Television",
1033	[EM28XX_VMUX_CABLE]      = "Cable TV",
1034	[EM28XX_VMUX_DVB]        = "DVB",
1035	[EM28XX_VMUX_DEBUG]      = "for debug only",
1036};
1037
1038static int vidioc_enum_input(struct file *file, void *priv,
1039				struct v4l2_input *i)
1040{
1041	struct em28xx_fh   *fh  = priv;
1042	struct em28xx      *dev = fh->dev;
1043	unsigned int       n;
1044
1045	n = i->index;
1046	if (n >= MAX_EM28XX_INPUT)
1047		return -EINVAL;
1048	if (0 == INPUT(n)->type)
1049		return -EINVAL;
1050
1051	i->index = n;
1052	i->type = V4L2_INPUT_TYPE_CAMERA;
1053
1054	strcpy(i->name, iname[INPUT(n)->type]);
1055
1056	if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type) ||
1057		(EM28XX_VMUX_CABLE == INPUT(n)->type))
1058		i->type = V4L2_INPUT_TYPE_TUNER;
1059
1060	i->std = dev->vdev->tvnorms;
1061
1062	return 0;
1063}
1064
1065static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1066{
1067	struct em28xx_fh   *fh  = priv;
1068	struct em28xx      *dev = fh->dev;
1069
1070	*i = dev->ctl_input;
1071
1072	return 0;
1073}
1074
1075static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1076{
1077	struct em28xx_fh   *fh  = priv;
1078	struct em28xx      *dev = fh->dev;
1079	int                rc;
1080
1081	rc = check_dev(dev);
1082	if (rc < 0)
1083		return rc;
1084
1085	if (i >= MAX_EM28XX_INPUT)
1086		return -EINVAL;
1087	if (0 == INPUT(i)->type)
1088		return -EINVAL;
1089
1090	mutex_lock(&dev->lock);
1091
1092	video_mux(dev, i);
1093
1094	mutex_unlock(&dev->lock);
1095	return 0;
1096}
1097
1098static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1099{
1100	struct em28xx_fh   *fh    = priv;
1101	struct em28xx      *dev   = fh->dev;
1102	unsigned int        index = a->index;
1103
1104	if (a->index > 1)
1105		return -EINVAL;
1106
1107	index = dev->ctl_ainput;
1108
1109	if (index == 0) {
1110		strcpy(a->name, "Television");
1111	} else {
1112		strcpy(a->name, "Line In");
1113	}
1114	a->capability = V4L2_AUDCAP_STEREO;
1115	a->index = index;
1116
1117	return 0;
1118}
1119
1120static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
1121{
1122	struct em28xx_fh   *fh  = priv;
1123	struct em28xx      *dev = fh->dev;
1124
1125	if (a->index != dev->ctl_ainput)
1126		return -EINVAL;
1127
1128	return 0;
1129}
1130
1131static int vidioc_queryctrl(struct file *file, void *priv,
1132				struct v4l2_queryctrl *qc)
1133{
1134	struct em28xx_fh      *fh  = priv;
1135	struct em28xx         *dev = fh->dev;
1136	int                   id  = qc->id;
1137	int                   i;
1138	int                   rc;
1139
1140	rc = check_dev(dev);
1141	if (rc < 0)
1142		return rc;
1143
1144	memset(qc, 0, sizeof(*qc));
1145
1146	qc->id = id;
1147
1148	if (!dev->has_msp34xx) {
1149		for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1150			if (qc->id && qc->id == em28xx_qctrl[i].id) {
1151				memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1152				return 0;
1153			}
1154		}
1155	}
1156	mutex_lock(&dev->lock);
1157	em28xx_i2c_call_clients(dev, VIDIOC_QUERYCTRL, qc);
1158	mutex_unlock(&dev->lock);
1159
1160	if (qc->type)
1161		return 0;
1162	else
1163		return -EINVAL;
1164}
1165
1166static int vidioc_g_ctrl(struct file *file, void *priv,
1167				struct v4l2_control *ctrl)
1168{
1169	struct em28xx_fh      *fh  = priv;
1170	struct em28xx         *dev = fh->dev;
1171	int                   rc;
1172
1173	rc = check_dev(dev);
1174	if (rc < 0)
1175		return rc;
1176	mutex_lock(&dev->lock);
1177
1178	if (!dev->has_msp34xx)
1179		rc = em28xx_get_ctrl(dev, ctrl);
1180	else
1181		rc = -EINVAL;
1182
1183	if (rc == -EINVAL) {
1184		em28xx_i2c_call_clients(dev, VIDIOC_G_CTRL, ctrl);
1185		rc = 0;
1186	}
1187
1188	mutex_unlock(&dev->lock);
1189	return rc;
1190}
1191
1192static int vidioc_s_ctrl(struct file *file, void *priv,
1193				struct v4l2_control *ctrl)
1194{
1195	struct em28xx_fh      *fh  = priv;
1196	struct em28xx         *dev = fh->dev;
1197	u8                    i;
1198	int                   rc;
1199
1200	rc = check_dev(dev);
1201	if (rc < 0)
1202		return rc;
1203
1204	mutex_lock(&dev->lock);
1205
1206	if (dev->has_msp34xx)
1207		em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1208	else {
1209		rc = 1;
1210		for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1211			if (ctrl->id == em28xx_qctrl[i].id) {
1212				if (ctrl->value < em28xx_qctrl[i].minimum ||
1213				    ctrl->value > em28xx_qctrl[i].maximum) {
1214					rc = -ERANGE;
1215					break;
1216				}
1217
1218				rc = em28xx_set_ctrl(dev, ctrl);
1219				break;
1220			}
1221		}
1222	}
1223
1224	/* Control not found - try to send it to the attached devices */
1225	if (rc == 1) {
1226		em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1227		rc = 0;
1228	}
1229
1230	mutex_unlock(&dev->lock);
1231	return rc;
1232}
1233
1234static int vidioc_g_tuner(struct file *file, void *priv,
1235				struct v4l2_tuner *t)
1236{
1237	struct em28xx_fh      *fh  = priv;
1238	struct em28xx         *dev = fh->dev;
1239	int                   rc;
1240
1241	rc = check_dev(dev);
1242	if (rc < 0)
1243		return rc;
1244
1245	if (0 != t->index)
1246		return -EINVAL;
1247
1248	strcpy(t->name, "Tuner");
1249
1250	mutex_lock(&dev->lock);
1251
1252	em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1253
1254	mutex_unlock(&dev->lock);
1255	return 0;
1256}
1257
1258static int vidioc_s_tuner(struct file *file, void *priv,
1259				struct v4l2_tuner *t)
1260{
1261	struct em28xx_fh      *fh  = priv;
1262	struct em28xx         *dev = fh->dev;
1263	int                   rc;
1264
1265	rc = check_dev(dev);
1266	if (rc < 0)
1267		return rc;
1268
1269	if (0 != t->index)
1270		return -EINVAL;
1271
1272	mutex_lock(&dev->lock);
1273
1274	em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1275
1276	mutex_unlock(&dev->lock);
1277	return 0;
1278}
1279
1280static int vidioc_g_frequency(struct file *file, void *priv,
1281				struct v4l2_frequency *f)
1282{
1283	struct em28xx_fh      *fh  = priv;
1284	struct em28xx         *dev = fh->dev;
1285
1286	f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
1287	f->frequency = dev->ctl_freq;
1288
1289	return 0;
1290}
1291
1292static int vidioc_s_frequency(struct file *file, void *priv,
1293				struct v4l2_frequency *f)
1294{
1295	struct em28xx_fh      *fh  = priv;
1296	struct em28xx         *dev = fh->dev;
1297	int                   rc;
1298
1299	rc = check_dev(dev);
1300	if (rc < 0)
1301		return rc;
1302
1303	if (0 != f->tuner)
1304		return -EINVAL;
1305
1306	if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
1307		return -EINVAL;
1308	if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
1309		return -EINVAL;
1310
1311	mutex_lock(&dev->lock);
1312
1313	dev->ctl_freq = f->frequency;
1314	em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, f);
1315
1316	mutex_unlock(&dev->lock);
1317	return 0;
1318}
1319
1320#ifdef CONFIG_VIDEO_ADV_DEBUG
1321static int em28xx_reg_len(int reg)
1322{
1323	switch (reg) {
1324	case AC97LSB_REG:
1325	case HSCALELOW_REG:
1326	case VSCALELOW_REG:
1327		return 2;
1328	default:
1329		return 1;
1330	}
1331}
1332
1333static int vidioc_g_register(struct file *file, void *priv,
1334			     struct v4l2_register *reg)
1335{
1336	struct em28xx_fh      *fh  = priv;
1337	struct em28xx         *dev = fh->dev;
1338	int ret;
1339
1340	if (!v4l2_chip_match_host(reg->match_type, reg->match_chip))
1341		return -EINVAL;
1342
1343	if (em28xx_reg_len(reg->reg) == 1) {
1344		ret = em28xx_read_reg(dev, reg->reg);
1345		if (ret < 0)
1346			return ret;
1347
1348		reg->val = ret;
1349	} else {
1350		u64 val = 0;
1351		ret = em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1352						   reg->reg, (char *)&val, 2);
1353		if (ret < 0)
1354			return ret;
1355
1356		reg->val = cpu_to_le64((__u64)val);
1357	}
1358
1359	return 0;
1360}
1361
1362static int vidioc_s_register(struct file *file, void *priv,
1363			     struct v4l2_register *reg)
1364{
1365	struct em28xx_fh      *fh  = priv;
1366	struct em28xx         *dev = fh->dev;
1367	u64 buf;
1368
1369	buf = le64_to_cpu((__u64)reg->val);
1370
1371	return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1372				 em28xx_reg_len(reg->reg));
1373}
1374#endif
1375
1376
1377static int vidioc_cropcap(struct file *file, void *priv,
1378					struct v4l2_cropcap *cc)
1379{
1380	struct em28xx_fh      *fh  = priv;
1381	struct em28xx         *dev = fh->dev;
1382
1383	if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1384		return -EINVAL;
1385
1386	cc->bounds.left = 0;
1387	cc->bounds.top = 0;
1388	cc->bounds.width = dev->width;
1389	cc->bounds.height = dev->height;
1390	cc->defrect = cc->bounds;
1391	cc->pixelaspect.numerator = 54;	/* 4:3 FIXME: remove magic numbers */
1392	cc->pixelaspect.denominator = 59;
1393
1394	return 0;
1395}
1396
1397static int vidioc_streamon(struct file *file, void *priv,
1398					enum v4l2_buf_type type)
1399{
1400	struct em28xx_fh      *fh  = priv;
1401	struct em28xx         *dev = fh->dev;
1402	int                   rc;
1403
1404	rc = check_dev(dev);
1405	if (rc < 0)
1406		return rc;
1407
1408
1409	if (unlikely(res_get(fh) < 0))
1410		return -EBUSY;
1411
1412	return (videobuf_streamon(&fh->vb_vidq));
1413}
1414
1415static int vidioc_streamoff(struct file *file, void *priv,
1416					enum v4l2_buf_type type)
1417{
1418	struct em28xx_fh      *fh  = priv;
1419	struct em28xx         *dev = fh->dev;
1420	int                   rc;
1421
1422	rc = check_dev(dev);
1423	if (rc < 0)
1424		return rc;
1425
1426	if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1427		return -EINVAL;
1428	if (type != fh->type)
1429		return -EINVAL;
1430
1431	videobuf_streamoff(&fh->vb_vidq);
1432	res_free(fh);
1433
1434	return 0;
1435}
1436
1437static int vidioc_querycap(struct file *file, void  *priv,
1438					struct v4l2_capability *cap)
1439{
1440	struct em28xx_fh      *fh  = priv;
1441	struct em28xx         *dev = fh->dev;
1442
1443	strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1444	strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1445	strlcpy(cap->bus_info, dev->udev->dev.bus_id, sizeof(cap->bus_info));
1446
1447	cap->version = EM28XX_VERSION_CODE;
1448
1449	cap->capabilities =
1450			V4L2_CAP_SLICED_VBI_CAPTURE |
1451			V4L2_CAP_VIDEO_CAPTURE |
1452			V4L2_CAP_AUDIO |
1453			V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1454
1455	if (dev->tuner_type != TUNER_ABSENT)
1456		cap->capabilities |= V4L2_CAP_TUNER;
1457
1458	return 0;
1459}
1460
1461static int vidioc_enum_fmt_cap(struct file *file, void  *priv,
1462					struct v4l2_fmtdesc *fmtd)
1463{
1464	if (fmtd->index != 0)
1465		return -EINVAL;
1466
1467	fmtd->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1468	strcpy(fmtd->description, "Packed YUY2");
1469	fmtd->pixelformat = V4L2_PIX_FMT_YUYV;
1470	memset(fmtd->reserved, 0, sizeof(fmtd->reserved));
1471
1472	return 0;
1473}
1474
1475/* Sliced VBI ioctls */
1476static int vidioc_g_fmt_vbi_capture(struct file *file, void *priv,
1477					struct v4l2_format *f)
1478{
1479	struct em28xx_fh      *fh  = priv;
1480	struct em28xx         *dev = fh->dev;
1481	int                   rc;
1482
1483	rc = check_dev(dev);
1484	if (rc < 0)
1485		return rc;
1486
1487	mutex_lock(&dev->lock);
1488
1489	f->fmt.sliced.service_set = 0;
1490
1491	em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1492
1493	if (f->fmt.sliced.service_set == 0)
1494		rc = -EINVAL;
1495
1496	mutex_unlock(&dev->lock);
1497	return rc;
1498}
1499
1500static int vidioc_try_set_vbi_capture(struct file *file, void *priv,
1501			struct v4l2_format *f)
1502{
1503	struct em28xx_fh      *fh  = priv;
1504	struct em28xx         *dev = fh->dev;
1505	int                   rc;
1506
1507	rc = check_dev(dev);
1508	if (rc < 0)
1509		return rc;
1510
1511	mutex_lock(&dev->lock);
1512	em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1513	mutex_unlock(&dev->lock);
1514
1515	if (f->fmt.sliced.service_set == 0)
1516		return -EINVAL;
1517
1518	return 0;
1519}
1520
1521
1522static int vidioc_reqbufs(struct file *file, void *priv,
1523			  struct v4l2_requestbuffers *rb)
1524{
1525	struct em28xx_fh      *fh  = priv;
1526	struct em28xx         *dev = fh->dev;
1527	int                   rc;
1528
1529	rc = check_dev(dev);
1530	if (rc < 0)
1531		return rc;
1532
1533	return (videobuf_reqbufs(&fh->vb_vidq, rb));
1534}
1535
1536static int vidioc_querybuf(struct file *file, void *priv,
1537			   struct v4l2_buffer *b)
1538{
1539	struct em28xx_fh      *fh  = priv;
1540	struct em28xx         *dev = fh->dev;
1541	int                   rc;
1542
1543	rc = check_dev(dev);
1544	if (rc < 0)
1545		return rc;
1546
1547	return (videobuf_querybuf(&fh->vb_vidq, b));
1548}
1549
1550static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1551{
1552	struct em28xx_fh      *fh  = priv;
1553	struct em28xx         *dev = fh->dev;
1554	int                   rc;
1555
1556	rc = check_dev(dev);
1557	if (rc < 0)
1558		return rc;
1559
1560	return (videobuf_qbuf(&fh->vb_vidq, b));
1561}
1562
1563static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1564{
1565	struct em28xx_fh      *fh  = priv;
1566	struct em28xx         *dev = fh->dev;
1567	int                   rc;
1568
1569	rc = check_dev(dev);
1570	if (rc < 0)
1571		return rc;
1572
1573	return (videobuf_dqbuf(&fh->vb_vidq, b,
1574				file->f_flags & O_NONBLOCK));
1575}
1576
1577#ifdef CONFIG_VIDEO_V4L1_COMPAT
1578static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
1579{
1580	struct em28xx_fh  *fh = priv;
1581
1582	return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
1583}
1584#endif
1585
1586
1587/* ----------------------------------------------------------- */
1588/* RADIO ESPECIFIC IOCTLS                                      */
1589/* ----------------------------------------------------------- */
1590
1591static int radio_querycap(struct file *file, void  *priv,
1592			  struct v4l2_capability *cap)
1593{
1594	struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1595
1596	strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1597	strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1598	strlcpy(cap->bus_info, dev->udev->dev.bus_id, sizeof(cap->bus_info));
1599
1600	cap->version = EM28XX_VERSION_CODE;
1601	cap->capabilities = V4L2_CAP_TUNER;
1602	return 0;
1603}
1604
1605static int radio_g_tuner(struct file *file, void *priv,
1606			 struct v4l2_tuner *t)
1607{
1608	struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1609
1610	if (unlikely(t->index > 0))
1611		return -EINVAL;
1612
1613	strcpy(t->name, "Radio");
1614	t->type = V4L2_TUNER_RADIO;
1615
1616	em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1617	return 0;
1618}
1619
1620static int radio_enum_input(struct file *file, void *priv,
1621			    struct v4l2_input *i)
1622{
1623	if (i->index != 0)
1624		return -EINVAL;
1625	strcpy(i->name, "Radio");
1626	i->type = V4L2_INPUT_TYPE_TUNER;
1627
1628	return 0;
1629}
1630
1631static int radio_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1632{
1633	if (unlikely(a->index))
1634		return -EINVAL;
1635
1636	strcpy(a->name, "Radio");
1637	return 0;
1638}
1639
1640static int radio_s_tuner(struct file *file, void *priv,
1641			 struct v4l2_tuner *t)
1642{
1643	struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1644
1645	if (0 != t->index)
1646		return -EINVAL;
1647
1648	em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1649
1650	return 0;
1651}
1652
1653static int radio_s_audio(struct file *file, void *fh,
1654			 struct v4l2_audio *a)
1655{
1656	return 0;
1657}
1658
1659static int radio_s_input(struct file *file, void *fh, unsigned int i)
1660{
1661	return 0;
1662}
1663
1664static int radio_queryctrl(struct file *file, void *priv,
1665			   struct v4l2_queryctrl *qc)
1666{
1667	int i;
1668
1669	if (qc->id <  V4L2_CID_BASE ||
1670		qc->id >= V4L2_CID_LASTP1)
1671		return -EINVAL;
1672
1673	for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1674		if (qc->id && qc->id == em28xx_qctrl[i].id) {
1675			memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1676			return 0;
1677		}
1678	}
1679
1680	return -EINVAL;
1681}
1682
1683/*
1684 * em28xx_v4l2_open()
1685 * inits the device and starts isoc transfer
1686 */
1687static int em28xx_v4l2_open(struct inode *inode, struct file *filp)
1688{
1689	int minor = iminor(inode);
1690	int errCode = 0, radio = 0;
1691	struct em28xx *h,*dev = NULL;
1692	struct em28xx_fh *fh;
1693	enum v4l2_buf_type fh_type = 0;
1694
1695	list_for_each_entry(h, &em28xx_devlist, devlist) {
1696		if (h->vdev->minor == minor) {
1697			dev  = h;
1698			fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1699		}
1700		if (h->vbi_dev->minor == minor) {
1701			dev  = h;
1702			fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1703		}
1704		if (h->radio_dev &&
1705		    h->radio_dev->minor == minor) {
1706			radio = 1;
1707			dev   = h;
1708		}
1709	}
1710	if (NULL == dev)
1711		return -ENODEV;
1712
1713	em28xx_videodbg("open minor=%d type=%s users=%d\n",
1714				minor, v4l2_type_names[fh_type], dev->users);
1715
1716	fh = kzalloc(sizeof(struct em28xx_fh), GFP_KERNEL);
1717
1718	if (!fh) {
1719		em28xx_errdev("em28xx-video.c: Out of memory?!\n");
1720		return -ENOMEM;
1721	}
1722	mutex_lock(&dev->lock);
1723	fh->dev = dev;
1724	fh->radio = radio;
1725	fh->type = fh_type;
1726	filp->private_data = fh;
1727
1728	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1729		dev->width = norm_maxw(dev);
1730		dev->height = norm_maxh(dev);
1731		dev->hscale = 0;
1732		dev->vscale = 0;
1733
1734		em28xx_set_alternate(dev);
1735		em28xx_resolution_set(dev);
1736
1737	}
1738	if (fh->radio) {
1739		em28xx_videodbg("video_open: setting radio device\n");
1740		em28xx_i2c_call_clients(dev, AUDC_SET_RADIO, NULL);
1741	}
1742
1743	dev->users++;
1744
1745	videobuf_queue_vmalloc_init(&fh->vb_vidq, &em28xx_video_qops,
1746			NULL, &dev->slock, fh->type, V4L2_FIELD_INTERLACED,
1747			sizeof(struct em28xx_buffer), fh);
1748
1749	mutex_unlock(&dev->lock);
1750	return errCode;
1751}
1752
1753/*
1754 * em28xx_realease_resources()
1755 * unregisters the v4l2,i2c and usb devices
1756 * called when the device gets disconected or at module unload
1757*/
1758static void em28xx_release_resources(struct em28xx *dev)
1759{
1760
1761	/*FIXME: I2C IR should be disconnected */
1762
1763	em28xx_info("V4L2 devices /dev/video%d and /dev/vbi%d deregistered\n",
1764				dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
1765				dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
1766	list_del(&dev->devlist);
1767	if (dev->radio_dev) {
1768		if (-1 != dev->radio_dev->minor)
1769			video_unregister_device(dev->radio_dev);
1770		else
1771			video_device_release(dev->radio_dev);
1772		dev->radio_dev = NULL;
1773	}
1774	if (dev->vbi_dev) {
1775		if (-1 != dev->vbi_dev->minor)
1776			video_unregister_device(dev->vbi_dev);
1777		else
1778			video_device_release(dev->vbi_dev);
1779		dev->vbi_dev = NULL;
1780	}
1781	if (dev->vdev) {
1782		if (-1 != dev->vdev->minor)
1783			video_unregister_device(dev->vdev);
1784		else
1785			video_device_release(dev->vdev);
1786		dev->vdev = NULL;
1787	}
1788	em28xx_i2c_unregister(dev);
1789	usb_put_dev(dev->udev);
1790
1791	/* Mark device as unused */
1792	em28xx_devused&=~(1<<dev->devno);
1793}
1794
1795/*
1796 * em28xx_v4l2_close()
1797 * stops streaming and deallocates all resources allocated by the v4l2 calls and ioctls
1798 */
1799static int em28xx_v4l2_close(struct inode *inode, struct file *filp)
1800{
1801	struct em28xx_fh *fh  = filp->private_data;
1802	struct em28xx    *dev = fh->dev;
1803	int              errCode;
1804
1805	em28xx_videodbg("users=%d\n", dev->users);
1806
1807
1808	if (res_check(fh))
1809		res_free(fh);
1810
1811	mutex_lock(&dev->lock);
1812
1813	if (dev->users == 1) {
1814		videobuf_stop(&fh->vb_vidq);
1815		videobuf_mmap_free(&fh->vb_vidq);
1816
1817		/* the device is already disconnect,
1818		   free the remaining resources */
1819		if (dev->state & DEV_DISCONNECTED) {
1820			em28xx_release_resources(dev);
1821			mutex_unlock(&dev->lock);
1822			kfree(dev);
1823			return 0;
1824		}
1825
1826		/* do this before setting alternate! */
1827		em28xx_uninit_isoc(dev);
1828
1829		/* set alternate 0 */
1830		dev->alt = 0;
1831		em28xx_videodbg("setting alternate 0\n");
1832		errCode = usb_set_interface(dev->udev, 0, 0);
1833		if (errCode < 0) {
1834			em28xx_errdev("cannot change alternate number to "
1835					"0 (error=%i)\n", errCode);
1836		}
1837	}
1838	kfree(fh);
1839	dev->users--;
1840	wake_up_interruptible_nr(&dev->open, 1);
1841	mutex_unlock(&dev->lock);
1842	return 0;
1843}
1844
1845/*
1846 * em28xx_v4l2_read()
1847 * will allocate buffers when called for the first time
1848 */
1849static ssize_t
1850em28xx_v4l2_read(struct file *filp, char __user * buf, size_t count,
1851		 loff_t *pos)
1852{
1853	struct em28xx_fh *fh = filp->private_data;
1854	struct em28xx *dev = fh->dev;
1855	int rc;
1856
1857	rc = check_dev(dev);
1858	if (rc < 0)
1859		return rc;
1860
1861	/* FIXME: read() is not prepared to allow changing the video
1862	   resolution while streaming. Seems a bug at em28xx_set_fmt
1863	 */
1864
1865	if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1866		if (unlikely(res_get(fh)))
1867			return -EBUSY;
1868
1869		return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1870					filp->f_flags & O_NONBLOCK);
1871	}
1872	return 0;
1873}
1874
1875/*
1876 * em28xx_v4l2_poll()
1877 * will allocate buffers when called for the first time
1878 */
1879static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table * wait)
1880{
1881	struct em28xx_fh *fh = filp->private_data;
1882	struct em28xx *dev = fh->dev;
1883	int rc;
1884
1885	rc = check_dev(dev);
1886	if (rc < 0)
1887		return rc;
1888
1889	if (unlikely(res_get(fh) < 0))
1890		return POLLERR;
1891
1892	if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1893		return POLLERR;
1894
1895	return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
1896}
1897
1898/*
1899 * em28xx_v4l2_mmap()
1900 */
1901static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
1902{
1903	struct em28xx_fh *fh    = filp->private_data;
1904	struct em28xx	 *dev   = fh->dev;
1905	int		 rc;
1906
1907	if (unlikely(res_get(fh) < 0))
1908		return -EBUSY;
1909
1910	rc = check_dev(dev);
1911	if (rc < 0)
1912		return rc;
1913
1914	rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1915
1916	em28xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
1917		(unsigned long)vma->vm_start,
1918		(unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1919		rc);
1920
1921	return rc;
1922}
1923
1924static const struct file_operations em28xx_v4l_fops = {
1925	.owner         = THIS_MODULE,
1926	.open          = em28xx_v4l2_open,
1927	.release       = em28xx_v4l2_close,
1928	.read          = em28xx_v4l2_read,
1929	.poll          = em28xx_v4l2_poll,
1930	.mmap          = em28xx_v4l2_mmap,
1931	.ioctl	       = video_ioctl2,
1932	.llseek        = no_llseek,
1933	.compat_ioctl  = v4l_compat_ioctl32,
1934};
1935
1936static const struct file_operations radio_fops = {
1937	.owner         = THIS_MODULE,
1938	.open          = em28xx_v4l2_open,
1939	.release       = em28xx_v4l2_close,
1940	.ioctl	       = video_ioctl2,
1941	.compat_ioctl  = v4l_compat_ioctl32,
1942	.llseek        = no_llseek,
1943};
1944
1945static const struct video_device em28xx_video_template = {
1946	.fops                       = &em28xx_v4l_fops,
1947	.release                    = video_device_release,
1948
1949	.minor                      = -1,
1950	.vidioc_querycap            = vidioc_querycap,
1951	.vidioc_enum_fmt_cap        = vidioc_enum_fmt_cap,
1952	.vidioc_g_fmt_cap           = vidioc_g_fmt_cap,
1953	.vidioc_try_fmt_cap         = vidioc_try_fmt_cap,
1954	.vidioc_s_fmt_cap           = vidioc_s_fmt_cap,
1955	.vidioc_g_audio             = vidioc_g_audio,
1956	.vidioc_s_audio             = vidioc_s_audio,
1957	.vidioc_cropcap             = vidioc_cropcap,
1958
1959	.vidioc_g_fmt_vbi_capture   = vidioc_g_fmt_vbi_capture,
1960	.vidioc_try_fmt_vbi_capture = vidioc_try_set_vbi_capture,
1961	.vidioc_s_fmt_vbi_capture   = vidioc_try_set_vbi_capture,
1962
1963	.vidioc_reqbufs             = vidioc_reqbufs,
1964	.vidioc_querybuf            = vidioc_querybuf,
1965	.vidioc_qbuf                = vidioc_qbuf,
1966	.vidioc_dqbuf               = vidioc_dqbuf,
1967	.vidioc_s_std               = vidioc_s_std,
1968	.vidioc_enum_input          = vidioc_enum_input,
1969	.vidioc_g_input             = vidioc_g_input,
1970	.vidioc_s_input             = vidioc_s_input,
1971	.vidioc_queryctrl           = vidioc_queryctrl,
1972	.vidioc_g_ctrl              = vidioc_g_ctrl,
1973	.vidioc_s_ctrl              = vidioc_s_ctrl,
1974	.vidioc_streamon            = vidioc_streamon,
1975	.vidioc_streamoff           = vidioc_streamoff,
1976	.vidioc_g_tuner             = vidioc_g_tuner,
1977	.vidioc_s_tuner             = vidioc_s_tuner,
1978	.vidioc_g_frequency         = vidioc_g_frequency,
1979	.vidioc_s_frequency         = vidioc_s_frequency,
1980#ifdef CONFIG_VIDEO_ADV_DEBUG
1981	.vidioc_g_register          = vidioc_g_register,
1982	.vidioc_s_register          = vidioc_s_register,
1983#endif
1984#ifdef CONFIG_VIDEO_V4L1_COMPAT
1985	.vidiocgmbuf                = vidiocgmbuf,
1986#endif
1987
1988	.tvnorms                    = V4L2_STD_ALL,
1989	.current_norm               = V4L2_STD_PAL,
1990};
1991
1992static struct video_device em28xx_radio_template = {
1993	.name                 = "em28xx-radio",
1994	.type                 = VID_TYPE_TUNER,
1995	.fops                 = &radio_fops,
1996	.minor                = -1,
1997	.vidioc_querycap      = radio_querycap,
1998	.vidioc_g_tuner       = radio_g_tuner,
1999	.vidioc_enum_input    = radio_enum_input,
2000	.vidioc_g_audio       = radio_g_audio,
2001	.vidioc_s_tuner       = radio_s_tuner,
2002	.vidioc_s_audio       = radio_s_audio,
2003	.vidioc_s_input       = radio_s_input,
2004	.vidioc_queryctrl     = radio_queryctrl,
2005	.vidioc_g_ctrl        = vidioc_g_ctrl,
2006	.vidioc_s_ctrl        = vidioc_s_ctrl,
2007	.vidioc_g_frequency   = vidioc_g_frequency,
2008	.vidioc_s_frequency   = vidioc_s_frequency,
2009#ifdef CONFIG_VIDEO_ADV_DEBUG
2010	.vidioc_g_register    = vidioc_g_register,
2011	.vidioc_s_register    = vidioc_s_register,
2012#endif
2013};
2014
2015/******************************** usb interface *****************************************/
2016
2017
2018static LIST_HEAD(em28xx_extension_devlist);
2019static DEFINE_MUTEX(em28xx_extension_devlist_lock);
2020
2021int em28xx_register_extension(struct em28xx_ops *ops)
2022{
2023	struct em28xx *h, *dev = NULL;
2024
2025	list_for_each_entry(h, &em28xx_devlist, devlist)
2026		dev = h;
2027
2028	mutex_lock(&em28xx_extension_devlist_lock);
2029	list_add_tail(&ops->next, &em28xx_extension_devlist);
2030	if (dev)
2031		ops->init(dev);
2032
2033	printk(KERN_INFO "Em28xx: Initialized (%s) extension\n", ops->name);
2034	mutex_unlock(&em28xx_extension_devlist_lock);
2035
2036	return 0;
2037}
2038EXPORT_SYMBOL(em28xx_register_extension);
2039
2040void em28xx_unregister_extension(struct em28xx_ops *ops)
2041{
2042	struct em28xx *h, *dev = NULL;
2043
2044	list_for_each_entry(h, &em28xx_devlist, devlist)
2045		dev = h;
2046
2047	if (dev)
2048		ops->fini(dev);
2049
2050	mutex_lock(&em28xx_extension_devlist_lock);
2051	printk(KERN_INFO "Em28xx: Removed (%s) extension\n", ops->name);
2052	list_del(&ops->next);
2053	mutex_unlock(&em28xx_extension_devlist_lock);
2054}
2055EXPORT_SYMBOL(em28xx_unregister_extension);
2056
2057static struct video_device *em28xx_vdev_init(struct em28xx *dev,
2058					     const struct video_device *template,
2059					     const int type,
2060					     const char *type_name)
2061{
2062	struct video_device *vfd;
2063
2064	vfd = video_device_alloc();
2065	if (NULL == vfd)
2066		return NULL;
2067	*vfd = *template;
2068	vfd->minor   = -1;
2069	vfd->dev = &dev->udev->dev;
2070	vfd->release = video_device_release;
2071	vfd->type = type;
2072	vfd->debug = video_debug;
2073
2074	snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2075		 dev->name, type_name);
2076
2077	return vfd;
2078}
2079
2080
2081/*
2082 * em28xx_init_dev()
2083 * allocates and inits the device structs, registers i2c bus and v4l device
2084 */
2085static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
2086			   int minor)
2087{
2088	struct em28xx_ops *ops = NULL;
2089	struct em28xx *dev = *devhandle;
2090	int retval = -ENOMEM;
2091	int errCode;
2092	unsigned int maxh, maxw;
2093
2094	dev->udev = udev;
2095	mutex_init(&dev->lock);
2096	spin_lock_init(&dev->slock);
2097	init_waitqueue_head(&dev->open);
2098	init_waitqueue_head(&dev->wait_frame);
2099	init_waitqueue_head(&dev->wait_stream);
2100
2101	dev->em28xx_write_regs = em28xx_write_regs;
2102	dev->em28xx_read_reg = em28xx_read_reg;
2103	dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
2104	dev->em28xx_write_regs_req = em28xx_write_regs_req;
2105	dev->em28xx_read_reg_req = em28xx_read_reg_req;
2106	dev->is_em2800 = em28xx_boards[dev->model].is_em2800;
2107
2108	errCode = em28xx_read_reg(dev, CHIPID_REG);
2109	if (errCode >= 0)
2110		em28xx_info("em28xx chip ID = %d\n", errCode);
2111
2112	em28xx_pre_card_setup(dev);
2113
2114	errCode = em28xx_config(dev);
2115	if (errCode) {
2116		em28xx_errdev("error configuring device\n");
2117		em28xx_devused &= ~(1<<dev->devno);
2118		kfree(dev);
2119		return -ENOMEM;
2120	}
2121
2122	/* register i2c bus */
2123	em28xx_i2c_register(dev);
2124
2125	/* Do board specific init and eeprom reading */
2126	em28xx_card_setup(dev);
2127
2128	/* Configure audio */
2129	em28xx_audio_analog_set(dev);
2130
2131	/* configure the device */
2132	em28xx_config_i2c(dev);
2133
2134	/* set default norm */
2135	dev->norm = em28xx_video_template.current_norm;
2136
2137	maxw = norm_maxw(dev);
2138	maxh = norm_maxh(dev);
2139
2140	/* set default image size */
2141	dev->width = maxw;
2142	dev->height = maxh;
2143	dev->interlaced = EM28XX_INTERLACED_DEFAULT;
2144	dev->hscale = 0;
2145	dev->vscale = 0;
2146	dev->ctl_input = 2;
2147
2148	errCode = em28xx_config(dev);
2149
2150	list_add_tail(&dev->devlist, &em28xx_devlist);
2151
2152	/* allocate and fill video video_device struct */
2153	dev->vdev = em28xx_vdev_init(dev, &em28xx_video_template,
2154					  VID_TYPE_CAPTURE, "video");
2155	if (NULL == dev->vdev) {
2156		em28xx_errdev("cannot allocate video_device.\n");
2157		goto fail_unreg;
2158	}
2159	if (dev->tuner_type != TUNER_ABSENT)
2160		dev->vdev->type |= VID_TYPE_TUNER;
2161
2162	/* register v4l2 video video_device */
2163	retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2164				       video_nr[dev->devno]);
2165	if (retval) {
2166		em28xx_errdev("unable to register video device (error=%i).\n",
2167			      retval);
2168		goto fail_unreg;
2169	}
2170
2171	/* Allocate and fill vbi video_device struct */
2172	dev->vbi_dev = em28xx_vdev_init(dev, &em28xx_video_template,
2173					  VFL_TYPE_VBI, "vbi");
2174	/* register v4l2 vbi video_device */
2175	if (video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2176					vbi_nr[dev->devno]) < 0) {
2177		em28xx_errdev("unable to register vbi device\n");
2178		retval = -ENODEV;
2179		goto fail_unreg;
2180	}
2181
2182	if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2183		dev->radio_dev = em28xx_vdev_init(dev, &em28xx_radio_template,
2184					VFL_TYPE_RADIO, "radio");
2185		if (NULL == dev->radio_dev) {
2186			em28xx_errdev("cannot allocate video_device.\n");
2187			goto fail_unreg;
2188		}
2189		retval = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2190					    radio_nr[dev->devno]);
2191		if (retval < 0) {
2192			em28xx_errdev("can't register radio device\n");
2193			goto fail_unreg;
2194		}
2195		em28xx_info("Registered radio device as /dev/radio%d\n",
2196			    dev->radio_dev->minor & 0x1f);
2197	}
2198
2199	/* init video dma queues */
2200	INIT_LIST_HEAD(&dev->vidq.active);
2201	INIT_LIST_HEAD(&dev->vidq.queued);
2202
2203
2204	if (dev->has_msp34xx) {
2205		/* Send a reset to other chips via gpio */
2206		em28xx_write_regs_req(dev, 0x00, 0x08, "\xf7", 1);
2207		msleep(3);
2208		em28xx_write_regs_req(dev, 0x00, 0x08, "\xff", 1);
2209		msleep(3);
2210	}
2211
2212	video_mux(dev, 0);
2213
2214	em28xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
2215				dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
2216				dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
2217
2218	mutex_lock(&em28xx_extension_devlist_lock);
2219	if (!list_empty(&em28xx_extension_devlist)) {
2220		list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2221			if (ops->id)
2222				ops->init(dev);
2223		}
2224	}
2225	mutex_unlock(&em28xx_extension_devlist_lock);
2226
2227	return 0;
2228
2229fail_unreg:
2230	em28xx_release_resources(dev);
2231	mutex_unlock(&dev->lock);
2232	kfree(dev);
2233	return retval;
2234}
2235
2236#if defined(CONFIG_MODULES) && defined(MODULE)
2237static void request_module_async(struct work_struct *work)
2238{
2239	struct em28xx *dev = container_of(work,
2240			     struct em28xx, request_module_wk);
2241
2242	if (dev->has_audio_class)
2243		request_module("snd-usb-audio");
2244	else
2245		request_module("em28xx-alsa");
2246
2247	if (dev->has_dvb)
2248		request_module("em28xx-dvb");
2249}
2250
2251static void request_modules(struct em28xx *dev)
2252{
2253	INIT_WORK(&dev->request_module_wk, request_module_async);
2254	schedule_work(&dev->request_module_wk);
2255}
2256#else
2257#define request_modules(dev)
2258#endif /* CONFIG_MODULES */
2259
2260/*
2261 * em28xx_usb_probe()
2262 * checks for supported devices
2263 */
2264static int em28xx_usb_probe(struct usb_interface *interface,
2265			    const struct usb_device_id *id)
2266{
2267	const struct usb_endpoint_descriptor *endpoint;
2268	struct usb_device *udev;
2269	struct usb_interface *uif;
2270	struct em28xx *dev = NULL;
2271	int retval = -ENODEV;
2272	int i, nr, ifnum;
2273
2274	udev = usb_get_dev(interface_to_usbdev(interface));
2275	ifnum = interface->altsetting[0].desc.bInterfaceNumber;
2276
2277	/* Check to see next free device and mark as used */
2278	nr=find_first_zero_bit(&em28xx_devused,EM28XX_MAXBOARDS);
2279	em28xx_devused|=1<<nr;
2280
2281	/* Don't register audio interfaces */
2282	if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2283		em28xx_err(DRIVER_NAME " audio device (%04x:%04x): interface %i, class %i\n",
2284				udev->descriptor.idVendor,udev->descriptor.idProduct,
2285				ifnum,
2286				interface->altsetting[0].desc.bInterfaceClass);
2287
2288		em28xx_devused&=~(1<<nr);
2289		return -ENODEV;
2290	}
2291
2292	em28xx_err(DRIVER_NAME " new video device (%04x:%04x): interface %i, class %i\n",
2293			udev->descriptor.idVendor,udev->descriptor.idProduct,
2294			ifnum,
2295			interface->altsetting[0].desc.bInterfaceClass);
2296
2297	endpoint = &interface->cur_altsetting->endpoint[1].desc;
2298
2299	/* check if the device has the iso in endpoint at the correct place */
2300	if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2301	    USB_ENDPOINT_XFER_ISOC) {
2302		em28xx_err(DRIVER_NAME " probing error: endpoint is non-ISO endpoint!\n");
2303		em28xx_devused&=~(1<<nr);
2304		return -ENODEV;
2305	}
2306	if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
2307		em28xx_err(DRIVER_NAME " probing error: endpoint is ISO OUT endpoint!\n");
2308		em28xx_devused&=~(1<<nr);
2309		return -ENODEV;
2310	}
2311
2312	if (nr >= EM28XX_MAXBOARDS) {
2313		printk (DRIVER_NAME ": Supports only %i em28xx boards.\n",EM28XX_MAXBOARDS);
2314		em28xx_devused&=~(1<<nr);
2315		return -ENOMEM;
2316	}
2317
2318	/* allocate memory for our device state and initialize it */
2319	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2320	if (dev == NULL) {
2321		em28xx_err(DRIVER_NAME ": out of memory!\n");
2322		em28xx_devused&=~(1<<nr);
2323		return -ENOMEM;
2324	}
2325
2326	snprintf(dev->name, 29, "em28xx #%d", nr);
2327	dev->devno = nr;
2328	dev->model = id->driver_info;
2329	dev->alt   = -1;
2330
2331	/* Checks if audio is provided by some interface */
2332	for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
2333		uif = udev->config->interface[i];
2334		if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2335			dev->has_audio_class = 1;
2336			break;
2337		}
2338	}
2339
2340	printk(KERN_INFO DRIVER_NAME " %s usb audio class\n",
2341		   dev->has_audio_class ? "Has" : "Doesn't have");
2342
2343	/* compute alternate max packet sizes */
2344	uif = udev->actconfig->interface[0];
2345
2346	dev->num_alt=uif->num_altsetting;
2347	em28xx_info("Alternate settings: %i\n",dev->num_alt);
2348//	dev->alt_max_pkt_size = kmalloc(sizeof(*dev->alt_max_pkt_size)*
2349	dev->alt_max_pkt_size = kmalloc(32*
2350						dev->num_alt,GFP_KERNEL);
2351	if (dev->alt_max_pkt_size == NULL) {
2352		em28xx_errdev("out of memory!\n");
2353		em28xx_devused&=~(1<<nr);
2354		kfree(dev);
2355		return -ENOMEM;
2356	}
2357
2358	for (i = 0; i < dev->num_alt ; i++) {
2359		u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.
2360							wMaxPacketSize);
2361		dev->alt_max_pkt_size[i] =
2362		    (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
2363		em28xx_info("Alternate setting %i, max size= %i\n",i,
2364							dev->alt_max_pkt_size[i]);
2365	}
2366
2367	if ((card[nr]>=0)&&(card[nr]<em28xx_bcount))
2368		dev->model = card[nr];
2369
2370	/* allocate device struct */
2371	retval = em28xx_init_dev(&dev, udev, nr);
2372	if (retval)
2373		return retval;
2374
2375	em28xx_info("Found %s\n", em28xx_boards[dev->model].name);
2376
2377	/* save our data pointer in this interface device */
2378	usb_set_intfdata(interface, dev);
2379
2380#if defined(CONFIG_VIDEO_EM28XX_DVB) || defined(CONFIG_VIDEO_EM28XX_DVB_MODULE)
2381	dev->qops = kmalloc(sizeof(em28xx_video_qops), GFP_KERNEL);
2382	memcpy(dev->qops, &em28xx_video_qops, sizeof(em28xx_video_qops));
2383#endif
2384
2385	request_modules(dev);
2386
2387	return 0;
2388}
2389
2390/*
2391 * em28xx_usb_disconnect()
2392 * called when the device gets diconencted
2393 * video device will be unregistered on v4l2_close in case it is still open
2394 */
2395static void em28xx_usb_disconnect(struct usb_interface *interface)
2396{
2397	struct em28xx *dev;
2398	struct em28xx_ops *ops = NULL;
2399
2400	dev = usb_get_intfdata(interface);
2401	usb_set_intfdata(interface, NULL);
2402
2403	if (!dev)
2404		return;
2405
2406	em28xx_info("disconnecting %s\n", dev->vdev->name);
2407
2408	/* wait until all current v4l2 io is finished then deallocate resources */
2409	mutex_lock(&dev->lock);
2410
2411	wake_up_interruptible_all(&dev->open);
2412
2413	if (dev->users) {
2414		em28xx_warn
2415		    ("device /dev/video%d is open! Deregistration and memory "
2416		     "deallocation are deferred on close.\n",
2417				dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN);
2418
2419		dev->state |= DEV_MISCONFIGURED;
2420		em28xx_uninit_isoc(dev);
2421		dev->state |= DEV_DISCONNECTED;
2422		wake_up_interruptible(&dev->wait_frame);
2423		wake_up_interruptible(&dev->wait_stream);
2424	} else {
2425		dev->state |= DEV_DISCONNECTED;
2426		em28xx_release_resources(dev);
2427	}
2428	mutex_unlock(&dev->lock);
2429
2430	mutex_lock(&em28xx_extension_devlist_lock);
2431	if (!list_empty(&em28xx_extension_devlist)) {
2432		list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2433			ops->fini(dev);
2434		}
2435	}
2436	mutex_unlock(&em28xx_extension_devlist_lock);
2437
2438	if (!dev->users) {
2439		kfree(dev->alt_max_pkt_size);
2440		kfree(dev);
2441	}
2442}
2443
2444static struct usb_driver em28xx_usb_driver = {
2445	.name = "em28xx",
2446	.probe = em28xx_usb_probe,
2447	.disconnect = em28xx_usb_disconnect,
2448	.id_table = em28xx_id_table,
2449};
2450
2451static int __init em28xx_module_init(void)
2452{
2453	int result;
2454
2455	printk(KERN_INFO DRIVER_NAME " v4l2 driver version %d.%d.%d loaded\n",
2456	       (EM28XX_VERSION_CODE >> 16) & 0xff,
2457	       (EM28XX_VERSION_CODE >> 8) & 0xff, EM28XX_VERSION_CODE & 0xff);
2458#ifdef SNAPSHOT
2459	printk(KERN_INFO DRIVER_NAME " snapshot date %04d-%02d-%02d\n",
2460	       SNAPSHOT / 10000, (SNAPSHOT / 100) % 100, SNAPSHOT % 100);
2461#endif
2462
2463	/* register this driver with the USB subsystem */
2464	result = usb_register(&em28xx_usb_driver);
2465	if (result)
2466		em28xx_err(DRIVER_NAME
2467			   " usb_register failed. Error number %d.\n", result);
2468
2469	return result;
2470}
2471
2472static void __exit em28xx_module_exit(void)
2473{
2474	/* deregister this driver with the USB subsystem */
2475	usb_deregister(&em28xx_usb_driver);
2476}
2477
2478module_init(em28xx_module_init);
2479module_exit(em28xx_module_exit);
2480