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