]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/video/em28xx/em28xx-video.c
V4L/DVB (7593): em28xx: add a module to handle dvb
[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 MODULE_AUTHOR(DRIVER_AUTHOR);
67 MODULE_DESCRIPTION(DRIVER_DESC);
68 MODULE_LICENSE("GPL");
69
70 static LIST_HEAD(em28xx_devlist);
71
72 static unsigned int card[]     = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
73 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
74 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
75 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
76
77 module_param_array(card,  int, NULL, 0444);
78 module_param_array(video_nr, int, NULL, 0444);
79 module_param_array(vbi_nr, int, NULL, 0444);
80 module_param_array(radio_nr, int, NULL, 0444);
81 MODULE_PARM_DESC(card,     "card type");
82 MODULE_PARM_DESC(video_nr, "video device numbers");
83 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
84 MODULE_PARM_DESC(radio_nr, "radio device numbers");
85
86 static unsigned int video_debug;
87 module_param(video_debug,int,0644);
88 MODULE_PARM_DESC(video_debug,"enable debug messages [video]");
89
90 /* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
91 static unsigned long em28xx_devused;
92
93 /* supported controls */
94 /* Common to all boards */
95 static 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
117 static 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  */
126 static 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  */
145 static 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
218 static 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  */
260 static 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  */
288 static 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  */
380 static 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  */
408 static 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  */
446 static 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
527 static 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
559 static int
560 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
561 {
562         struct em28xx_fh *fh = vq->priv_data;
563
564         *size = 16 * fh->dev->width * fh->dev->height >> 3;
565         if (0 == *count)
566                 *count = EM28XX_DEF_BUF;
567
568         if (*count < EM28XX_MIN_BUF)
569                 *count = EM28XX_MIN_BUF;
570
571         return 0;
572 }
573
574 /* This is called *without* dev->slock held; please keep it that way */
575 static void free_buffer(struct videobuf_queue *vq, struct em28xx_buffer *buf)
576 {
577         struct em28xx_fh     *fh  = vq->priv_data;
578         struct em28xx        *dev = fh->dev;
579         unsigned long flags = 0;
580         if (in_interrupt())
581                 BUG();
582
583         /* We used to wait for the buffer to finish here, but this didn't work
584            because, as we were keeping the state as VIDEOBUF_QUEUED,
585            videobuf_queue_cancel marked it as finished for us.
586            (Also, it could wedge forever if the hardware was misconfigured.)
587
588            This should be safe; by the time we get here, the buffer isn't
589            queued anymore. If we ever start marking the buffers as
590            VIDEOBUF_ACTIVE, it won't be, though.
591         */
592         spin_lock_irqsave(&dev->slock, flags);
593         if (dev->isoc_ctl.buf == buf)
594                 dev->isoc_ctl.buf = NULL;
595         spin_unlock_irqrestore(&dev->slock, flags);
596
597         videobuf_vmalloc_free(&buf->vb);
598         buf->vb.state = VIDEOBUF_NEEDS_INIT;
599 }
600
601 static int
602 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
603                                                 enum v4l2_field field)
604 {
605         struct em28xx_fh     *fh  = vq->priv_data;
606         struct em28xx_buffer *buf = container_of(vb, struct em28xx_buffer, vb);
607         struct em28xx        *dev = fh->dev;
608         struct em28xx_dmaqueue *vidq = &dev->vidq;
609         int                  rc = 0, urb_init = 0;
610
611         /* FIXME: It assumes depth = 16 */
612         /* The only currently supported format is 16 bits/pixel */
613         buf->vb.size = 16 * dev->width * dev->height >> 3;
614
615         if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
616                 return -EINVAL;
617
618         buf->vb.width  = dev->width;
619         buf->vb.height = dev->height;
620         buf->vb.field  = field;
621
622         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
623                 rc = videobuf_iolock(vq, &buf->vb, NULL);
624                 if (rc < 0)
625                         goto fail;
626         }
627
628         if (!dev->isoc_ctl.num_bufs)
629                 urb_init = 1;
630
631         if (urb_init) {
632                 rc = em28xx_prepare_isoc(dev, EM28XX_NUM_PACKETS,
633                                          EM28XX_NUM_BUFS);
634                 if (rc < 0)
635                         goto fail;
636
637                 rc = em28xx_start_thread(vidq);
638                 if (rc < 0)
639                         goto fail;
640         }
641
642         buf->vb.state = VIDEOBUF_PREPARED;
643         return 0;
644
645 fail:
646         free_buffer(vq, buf);
647         return rc;
648 }
649
650 static void
651 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
652 {
653         struct em28xx_buffer    *buf     = container_of(vb, struct em28xx_buffer, vb);
654         struct em28xx_fh        *fh      = vq->priv_data;
655         struct em28xx           *dev     = fh->dev;
656         struct em28xx_dmaqueue  *vidq    = &dev->vidq;
657
658         buf->vb.state = VIDEOBUF_QUEUED;
659         list_add_tail(&buf->vb.queue, &vidq->active);
660
661 }
662
663 static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
664 {
665         struct em28xx_buffer   *buf  = container_of(vb, struct em28xx_buffer, vb);
666         struct em28xx_fh       *fh   = vq->priv_data;
667         struct em28xx          *dev  = (struct em28xx *)fh->dev;
668
669         em28xx_isocdbg("em28xx: called buffer_release\n");
670
671         free_buffer(vq, buf);
672 }
673
674 static struct videobuf_queue_ops em28xx_video_qops = {
675         .buf_setup      = buffer_setup,
676         .buf_prepare    = buffer_prepare,
677         .buf_queue      = buffer_queue,
678         .buf_release    = buffer_release,
679 };
680
681 /*********************  v4l2 interface  ******************************************/
682
683 /*
684  * em28xx_config()
685  * inits registers with sane defaults
686  */
687 static int em28xx_config(struct em28xx *dev)
688 {
689
690         /* Sets I2C speed to 100 KHz */
691         if (!dev->is_em2800)
692                 em28xx_write_regs_req(dev, 0x00, 0x06, "\x40", 1);
693
694         /* enable vbi capturing */
695
696 /*      em28xx_write_regs_req(dev,0x00,0x0e,"\xC0",1); audio register */
697 /*      em28xx_write_regs_req(dev,0x00,0x0f,"\x80",1); clk register */
698         em28xx_write_regs_req(dev,0x00,0x11,"\x51",1);
699
700         dev->mute = 1;          /* maybe not the right place... */
701         dev->volume = 0x1f;
702
703         em28xx_outfmt_set_yuv422(dev);
704         em28xx_colorlevels_set_default(dev);
705         em28xx_compression_disable(dev);
706
707         return 0;
708 }
709
710 /*
711  * em28xx_config_i2c()
712  * configure i2c attached devices
713  */
714 static void em28xx_config_i2c(struct em28xx *dev)
715 {
716         struct v4l2_routing route;
717
718         route.input = INPUT(dev->ctl_input)->vmux;
719         route.output = 0;
720         em28xx_i2c_call_clients(dev, VIDIOC_INT_RESET, NULL);
721         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
722         em28xx_i2c_call_clients(dev, VIDIOC_STREAMON, NULL);
723 }
724
725 static void video_mux(struct em28xx *dev, int index)
726 {
727         struct v4l2_routing route;
728
729         route.input = INPUT(index)->vmux;
730         route.output = 0;
731         dev->ctl_input = index;
732         dev->ctl_ainput = INPUT(index)->amux;
733
734         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
735
736         if (dev->has_msp34xx) {
737                 if (dev->i2s_speed)
738                         em28xx_i2c_call_clients(dev, VIDIOC_INT_I2S_CLOCK_FREQ, &dev->i2s_speed);
739                 route.input = dev->ctl_ainput;
740                 route.output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
741                 /* Note: this is msp3400 specific */
742                 em28xx_i2c_call_clients(dev, VIDIOC_INT_S_AUDIO_ROUTING, &route);
743         }
744
745         em28xx_audio_analog_set(dev);
746 }
747
748 /* Usage lock check functions */
749 static int res_get(struct em28xx_fh *fh)
750 {
751         struct em28xx    *dev = fh->dev;
752         int              rc   = 0;
753
754         /* This instance already has stream_on */
755         if (fh->stream_on)
756                 return rc;
757
758         if (dev->stream_on)
759                 return -EINVAL;
760
761         mutex_lock(&dev->lock);
762         dev->stream_on = 1;
763         fh->stream_on  = 1;
764         mutex_unlock(&dev->lock);
765         return rc;
766 }
767
768 static int res_check(struct em28xx_fh *fh)
769 {
770         return (fh->stream_on);
771 }
772
773 static void res_free(struct em28xx_fh *fh)
774 {
775         struct em28xx    *dev = fh->dev;
776
777         mutex_lock(&dev->lock);
778         fh->stream_on = 0;
779         dev->stream_on = 0;
780         mutex_unlock(&dev->lock);
781 }
782
783 /*
784  * em28xx_get_ctrl()
785  * return the current saturation, brightness or contrast, mute state
786  */
787 static int em28xx_get_ctrl(struct em28xx *dev, struct v4l2_control *ctrl)
788 {
789         switch (ctrl->id) {
790         case V4L2_CID_AUDIO_MUTE:
791                 ctrl->value = dev->mute;
792                 return 0;
793         case V4L2_CID_AUDIO_VOLUME:
794                 ctrl->value = dev->volume;
795                 return 0;
796         default:
797                 return -EINVAL;
798         }
799 }
800
801 /*
802  * em28xx_set_ctrl()
803  * mute or set new saturation, brightness or contrast
804  */
805 static int em28xx_set_ctrl(struct em28xx *dev, const struct v4l2_control *ctrl)
806 {
807         switch (ctrl->id) {
808         case V4L2_CID_AUDIO_MUTE:
809                 if (ctrl->value != dev->mute) {
810                         dev->mute = ctrl->value;
811                         return em28xx_audio_analog_set(dev);
812                 }
813                 return 0;
814         case V4L2_CID_AUDIO_VOLUME:
815                 dev->volume = ctrl->value;
816                 return em28xx_audio_analog_set(dev);
817         default:
818                 return -EINVAL;
819         }
820 }
821
822 static int check_dev(struct em28xx *dev)
823 {
824         if (dev->state & DEV_DISCONNECTED) {
825                 em28xx_errdev("v4l2 ioctl: device not present\n");
826                 return -ENODEV;
827         }
828
829         if (dev->state & DEV_MISCONFIGURED) {
830                 em28xx_errdev("v4l2 ioctl: device is misconfigured; "
831                               "close and open it again\n");
832                 return -EIO;
833         }
834         return 0;
835 }
836
837 static void get_scale(struct em28xx *dev,
838                         unsigned int width, unsigned int height,
839                         unsigned int *hscale, unsigned int *vscale)
840 {
841         unsigned int          maxw   = norm_maxw(dev);
842         unsigned int          maxh   = norm_maxh(dev);
843
844         *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
845         if (*hscale >= 0x4000)
846                 *hscale = 0x3fff;
847
848         *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
849         if (*vscale >= 0x4000)
850                 *vscale = 0x3fff;
851 }
852
853 /* ------------------------------------------------------------------
854         IOCTL vidioc handling
855    ------------------------------------------------------------------*/
856
857 static int vidioc_g_fmt_cap(struct file *file, void *priv,
858                                         struct v4l2_format *f)
859 {
860         struct em28xx_fh      *fh  = priv;
861         struct em28xx         *dev = fh->dev;
862
863         mutex_lock(&dev->lock);
864
865         f->fmt.pix.width = dev->width;
866         f->fmt.pix.height = dev->height;
867         f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
868         f->fmt.pix.bytesperline = dev->width * 2;
869         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline  * dev->height;
870         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
871
872         /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
873         f->fmt.pix.field = dev->interlaced ?
874                            V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
875
876         mutex_unlock(&dev->lock);
877         return 0;
878 }
879
880 static int vidioc_try_fmt_cap(struct file *file, void *priv,
881                         struct v4l2_format *f)
882 {
883         struct em28xx_fh      *fh    = priv;
884         struct em28xx         *dev   = fh->dev;
885         int                   width  = f->fmt.pix.width;
886         int                   height = f->fmt.pix.height;
887         unsigned int          maxw   = norm_maxw(dev);
888         unsigned int          maxh   = norm_maxh(dev);
889         unsigned int          hscale, vscale;
890
891         /* width must even because of the YUYV format
892            height must be even because of interlacing */
893         height &= 0xfffe;
894         width &= 0xfffe;
895
896         if (height < 32)
897                 height = 32;
898         if (height > maxh)
899                 height = maxh;
900         if (width < 48)
901                 width = 48;
902         if (width > maxw)
903                 width = maxw;
904
905         mutex_lock(&dev->lock);
906
907         if (dev->is_em2800) {
908                 /* the em2800 can only scale down to 50% */
909                 if (height % (maxh / 2))
910                         height = maxh;
911                 if (width % (maxw / 2))
912                         width = maxw;
913                 /* according to empiatech support */
914                 /* the MaxPacketSize is to small to support */
915                 /* framesizes larger than 640x480 @ 30 fps */
916                 /* or 640x576 @ 25 fps. As this would cut */
917                 /* of a part of the image we prefer */
918                 /* 360x576 or 360x480 for now */
919                 if (width == maxw && height == maxh)
920                         width /= 2;
921         }
922
923         get_scale(dev, width, height, &hscale, &vscale);
924
925         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
926         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
927
928         f->fmt.pix.width = width;
929         f->fmt.pix.height = height;
930         f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
931         f->fmt.pix.bytesperline = width * 2;
932         f->fmt.pix.sizeimage = width * 2 * height;
933         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
934         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
935
936         mutex_unlock(&dev->lock);
937         return 0;
938 }
939
940 static int vidioc_s_fmt_cap(struct file *file, void *priv,
941                         struct v4l2_format *f)
942 {
943         struct em28xx_fh      *fh  = priv;
944         struct em28xx         *dev = fh->dev;
945         int                   rc;
946
947         rc = check_dev(dev);
948         if (rc < 0)
949                 return rc;
950
951         vidioc_try_fmt_cap(file, priv, f);
952
953         mutex_lock(&dev->lock);
954
955         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
956                 em28xx_errdev("%s queue busy\n", __func__);
957                 rc = -EBUSY;
958                 goto out;
959         }
960
961         if (dev->stream_on && !fh->stream_on) {
962                 em28xx_errdev("%s device in use by another fh\n", __func__);
963                 rc = -EBUSY;
964                 goto out;
965         }
966
967         /* set new image size */
968         dev->width = f->fmt.pix.width;
969         dev->height = f->fmt.pix.height;
970         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
971
972         em28xx_set_alternate(dev);
973         em28xx_resolution_set(dev);
974
975         rc = 0;
976
977 out:
978         mutex_unlock(&dev->lock);
979         return rc;
980 }
981
982 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm)
983 {
984         struct em28xx_fh   *fh  = priv;
985         struct em28xx      *dev = fh->dev;
986         struct v4l2_format f;
987         int                rc;
988
989         rc = check_dev(dev);
990         if (rc < 0)
991                 return rc;
992
993         mutex_lock(&dev->lock);
994         dev->norm = *norm;
995         mutex_unlock(&dev->lock);
996
997         /* Adjusts width/height, if needed */
998         f.fmt.pix.width = dev->width;
999         f.fmt.pix.height = dev->height;
1000         vidioc_try_fmt_cap(file, priv, &f);
1001
1002         mutex_lock(&dev->lock);
1003
1004         /* set new image size */
1005         dev->width = f.fmt.pix.width;
1006         dev->height = f.fmt.pix.height;
1007         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
1008
1009         em28xx_resolution_set(dev);
1010         em28xx_i2c_call_clients(dev, VIDIOC_S_STD, &dev->norm);
1011
1012         mutex_unlock(&dev->lock);
1013         return 0;
1014 }
1015
1016 static const char *iname[] = {
1017         [EM28XX_VMUX_COMPOSITE1] = "Composite1",
1018         [EM28XX_VMUX_COMPOSITE2] = "Composite2",
1019         [EM28XX_VMUX_COMPOSITE3] = "Composite3",
1020         [EM28XX_VMUX_COMPOSITE4] = "Composite4",
1021         [EM28XX_VMUX_SVIDEO]     = "S-Video",
1022         [EM28XX_VMUX_TELEVISION] = "Television",
1023         [EM28XX_VMUX_CABLE]      = "Cable TV",
1024         [EM28XX_VMUX_DVB]        = "DVB",
1025         [EM28XX_VMUX_DEBUG]      = "for debug only",
1026 };
1027
1028 static int vidioc_enum_input(struct file *file, void *priv,
1029                                 struct v4l2_input *i)
1030 {
1031         struct em28xx_fh   *fh  = priv;
1032         struct em28xx      *dev = fh->dev;
1033         unsigned int       n;
1034
1035         n = i->index;
1036         if (n >= MAX_EM28XX_INPUT)
1037                 return -EINVAL;
1038         if (0 == INPUT(n)->type)
1039                 return -EINVAL;
1040
1041         i->index = n;
1042         i->type = V4L2_INPUT_TYPE_CAMERA;
1043
1044         strcpy(i->name, iname[INPUT(n)->type]);
1045
1046         if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type) ||
1047                 (EM28XX_VMUX_CABLE == INPUT(n)->type))
1048                 i->type = V4L2_INPUT_TYPE_TUNER;
1049
1050         i->std = dev->vdev->tvnorms;
1051
1052         return 0;
1053 }
1054
1055 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1056 {
1057         struct em28xx_fh   *fh  = priv;
1058         struct em28xx      *dev = fh->dev;
1059
1060         *i = dev->ctl_input;
1061
1062         return 0;
1063 }
1064
1065 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1066 {
1067         struct em28xx_fh   *fh  = priv;
1068         struct em28xx      *dev = fh->dev;
1069         int                rc;
1070
1071         rc = check_dev(dev);
1072         if (rc < 0)
1073                 return rc;
1074
1075         if (i >= MAX_EM28XX_INPUT)
1076                 return -EINVAL;
1077         if (0 == INPUT(i)->type)
1078                 return -EINVAL;
1079
1080         mutex_lock(&dev->lock);
1081
1082         video_mux(dev, i);
1083
1084         mutex_unlock(&dev->lock);
1085         return 0;
1086 }
1087
1088 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1089 {
1090         struct em28xx_fh   *fh    = priv;
1091         struct em28xx      *dev   = fh->dev;
1092         unsigned int        index = a->index;
1093
1094         if (a->index > 1)
1095                 return -EINVAL;
1096
1097         index = dev->ctl_ainput;
1098
1099         if (index == 0) {
1100                 strcpy(a->name, "Television");
1101         } else {
1102                 strcpy(a->name, "Line In");
1103         }
1104         a->capability = V4L2_AUDCAP_STEREO;
1105         a->index = index;
1106
1107         return 0;
1108 }
1109
1110 static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
1111 {
1112         struct em28xx_fh   *fh  = priv;
1113         struct em28xx      *dev = fh->dev;
1114
1115         if (a->index != dev->ctl_ainput)
1116                 return -EINVAL;
1117
1118         return 0;
1119 }
1120
1121 static int vidioc_queryctrl(struct file *file, void *priv,
1122                                 struct v4l2_queryctrl *qc)
1123 {
1124         struct em28xx_fh      *fh  = priv;
1125         struct em28xx         *dev = fh->dev;
1126         int                   id  = qc->id;
1127         int                   i;
1128         int                   rc;
1129
1130         rc = check_dev(dev);
1131         if (rc < 0)
1132                 return rc;
1133
1134         memset(qc, 0, sizeof(*qc));
1135
1136         qc->id = id;
1137
1138         if (!dev->has_msp34xx) {
1139                 for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1140                         if (qc->id && qc->id == em28xx_qctrl[i].id) {
1141                                 memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1142                                 return 0;
1143                         }
1144                 }
1145         }
1146         mutex_lock(&dev->lock);
1147         em28xx_i2c_call_clients(dev, VIDIOC_QUERYCTRL, qc);
1148         mutex_unlock(&dev->lock);
1149
1150         if (qc->type)
1151                 return 0;
1152         else
1153                 return -EINVAL;
1154 }
1155
1156 static int vidioc_g_ctrl(struct file *file, void *priv,
1157                                 struct v4l2_control *ctrl)
1158 {
1159         struct em28xx_fh      *fh  = priv;
1160         struct em28xx         *dev = fh->dev;
1161         int                   rc;
1162
1163         rc = check_dev(dev);
1164         if (rc < 0)
1165                 return rc;
1166         mutex_lock(&dev->lock);
1167
1168         if (!dev->has_msp34xx)
1169                 rc = em28xx_get_ctrl(dev, ctrl);
1170         else
1171                 rc = -EINVAL;
1172
1173         if (rc == -EINVAL) {
1174                 em28xx_i2c_call_clients(dev, VIDIOC_G_CTRL, ctrl);
1175                 rc = 0;
1176         }
1177
1178         mutex_unlock(&dev->lock);
1179         return rc;
1180 }
1181
1182 static int vidioc_s_ctrl(struct file *file, void *priv,
1183                                 struct v4l2_control *ctrl)
1184 {
1185         struct em28xx_fh      *fh  = priv;
1186         struct em28xx         *dev = fh->dev;
1187         u8                    i;
1188         int                   rc;
1189
1190         rc = check_dev(dev);
1191         if (rc < 0)
1192                 return rc;
1193
1194         mutex_lock(&dev->lock);
1195
1196         if (dev->has_msp34xx)
1197                 em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1198         else {
1199                 rc = 1;
1200                 for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1201                         if (ctrl->id == em28xx_qctrl[i].id) {
1202                                 if (ctrl->value < em28xx_qctrl[i].minimum ||
1203                                     ctrl->value > em28xx_qctrl[i].maximum) {
1204                                         rc = -ERANGE;
1205                                         break;
1206                                 }
1207
1208                                 rc = em28xx_set_ctrl(dev, ctrl);
1209                                 break;
1210                         }
1211                 }
1212         }
1213
1214         /* Control not found - try to send it to the attached devices */
1215         if (rc == 1) {
1216                 em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1217                 rc = 0;
1218         }
1219
1220         mutex_unlock(&dev->lock);
1221         return rc;
1222 }
1223
1224 static int vidioc_g_tuner(struct file *file, void *priv,
1225                                 struct v4l2_tuner *t)
1226 {
1227         struct em28xx_fh      *fh  = priv;
1228         struct em28xx         *dev = fh->dev;
1229         int                   rc;
1230
1231         rc = check_dev(dev);
1232         if (rc < 0)
1233                 return rc;
1234
1235         if (0 != t->index)
1236                 return -EINVAL;
1237
1238         strcpy(t->name, "Tuner");
1239
1240         mutex_lock(&dev->lock);
1241
1242         em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1243
1244         mutex_unlock(&dev->lock);
1245         return 0;
1246 }
1247
1248 static int vidioc_s_tuner(struct file *file, void *priv,
1249                                 struct v4l2_tuner *t)
1250 {
1251         struct em28xx_fh      *fh  = priv;
1252         struct em28xx         *dev = fh->dev;
1253         int                   rc;
1254
1255         rc = check_dev(dev);
1256         if (rc < 0)
1257                 return rc;
1258
1259         if (0 != t->index)
1260                 return -EINVAL;
1261
1262         mutex_lock(&dev->lock);
1263
1264         em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1265
1266         mutex_unlock(&dev->lock);
1267         return 0;
1268 }
1269
1270 static int vidioc_g_frequency(struct file *file, void *priv,
1271                                 struct v4l2_frequency *f)
1272 {
1273         struct em28xx_fh      *fh  = priv;
1274         struct em28xx         *dev = fh->dev;
1275
1276         f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
1277         f->frequency = dev->ctl_freq;
1278
1279         return 0;
1280 }
1281
1282 static int vidioc_s_frequency(struct file *file, void *priv,
1283                                 struct v4l2_frequency *f)
1284 {
1285         struct em28xx_fh      *fh  = priv;
1286         struct em28xx         *dev = fh->dev;
1287         int                   rc;
1288
1289         rc = check_dev(dev);
1290         if (rc < 0)
1291                 return rc;
1292
1293         if (0 != f->tuner)
1294                 return -EINVAL;
1295
1296         if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
1297                 return -EINVAL;
1298         if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
1299                 return -EINVAL;
1300
1301         mutex_lock(&dev->lock);
1302
1303         dev->ctl_freq = f->frequency;
1304         em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, f);
1305
1306         mutex_unlock(&dev->lock);
1307         return 0;
1308 }
1309
1310 #ifdef CONFIG_VIDEO_ADV_DEBUG
1311 static int em28xx_reg_len(int reg)
1312 {
1313         switch (reg) {
1314         case AC97LSB_REG:
1315         case HSCALELOW_REG:
1316         case VSCALELOW_REG:
1317                 return 2;
1318         default:
1319                 return 1;
1320         }
1321 }
1322
1323 static int vidioc_g_register(struct file *file, void *priv,
1324                              struct v4l2_register *reg)
1325 {
1326         struct em28xx_fh      *fh  = priv;
1327         struct em28xx         *dev = fh->dev;
1328         int ret;
1329
1330         if (!v4l2_chip_match_host(reg->match_type, reg->match_chip))
1331                 return -EINVAL;
1332
1333         if (em28xx_reg_len(reg->reg) == 1) {
1334                 ret = em28xx_read_reg(dev, reg->reg);
1335                 if (ret < 0)
1336                         return ret;
1337
1338                 reg->val = ret;
1339         } else {
1340                 u64 val = 0;
1341                 ret = em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1342                                                    reg->reg, (char *)&val, 2);
1343                 if (ret < 0)
1344                         return ret;
1345
1346                 reg->val = cpu_to_le64((__u64)val);
1347         }
1348
1349         return 0;
1350 }
1351
1352 static int vidioc_s_register(struct file *file, void *priv,
1353                              struct v4l2_register *reg)
1354 {
1355         struct em28xx_fh      *fh  = priv;
1356         struct em28xx         *dev = fh->dev;
1357         u64 buf;
1358
1359         buf = le64_to_cpu((__u64)reg->val);
1360
1361         return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1362                                  em28xx_reg_len(reg->reg));
1363 }
1364 #endif
1365
1366
1367 static int vidioc_cropcap(struct file *file, void *priv,
1368                                         struct v4l2_cropcap *cc)
1369 {
1370         struct em28xx_fh      *fh  = priv;
1371         struct em28xx         *dev = fh->dev;
1372
1373         if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1374                 return -EINVAL;
1375
1376         cc->bounds.left = 0;
1377         cc->bounds.top = 0;
1378         cc->bounds.width = dev->width;
1379         cc->bounds.height = dev->height;
1380         cc->defrect = cc->bounds;
1381         cc->pixelaspect.numerator = 54; /* 4:3 FIXME: remove magic numbers */
1382         cc->pixelaspect.denominator = 59;
1383
1384         return 0;
1385 }
1386
1387 static int vidioc_streamon(struct file *file, void *priv,
1388                                         enum v4l2_buf_type type)
1389 {
1390         struct em28xx_fh      *fh  = priv;
1391         struct em28xx         *dev = fh->dev;
1392         int                   rc;
1393
1394         rc = check_dev(dev);
1395         if (rc < 0)
1396                 return rc;
1397
1398
1399         if (unlikely(res_get(fh) < 0))
1400                 return -EBUSY;
1401
1402         return (videobuf_streamon(&fh->vb_vidq));
1403 }
1404
1405 static int vidioc_streamoff(struct file *file, void *priv,
1406                                         enum v4l2_buf_type type)
1407 {
1408         struct em28xx_fh      *fh  = priv;
1409         struct em28xx         *dev = fh->dev;
1410         int                   rc;
1411
1412         rc = check_dev(dev);
1413         if (rc < 0)
1414                 return rc;
1415
1416         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1417                 return -EINVAL;
1418         if (type != fh->type)
1419                 return -EINVAL;
1420
1421         videobuf_streamoff(&fh->vb_vidq);
1422         res_free(fh);
1423
1424         return 0;
1425 }
1426
1427 static int vidioc_querycap(struct file *file, void  *priv,
1428                                         struct v4l2_capability *cap)
1429 {
1430         struct em28xx_fh      *fh  = priv;
1431         struct em28xx         *dev = fh->dev;
1432
1433         strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1434         strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1435         strlcpy(cap->bus_info, dev->udev->dev.bus_id, sizeof(cap->bus_info));
1436
1437         cap->version = EM28XX_VERSION_CODE;
1438
1439         cap->capabilities =
1440                         V4L2_CAP_SLICED_VBI_CAPTURE |
1441                         V4L2_CAP_VIDEO_CAPTURE |
1442                         V4L2_CAP_AUDIO |
1443                         V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1444
1445         if (dev->tuner_type != TUNER_ABSENT)
1446                 cap->capabilities |= V4L2_CAP_TUNER;
1447
1448         return 0;
1449 }
1450
1451 static int vidioc_enum_fmt_cap(struct file *file, void  *priv,
1452                                         struct v4l2_fmtdesc *fmtd)
1453 {
1454         if (fmtd->index != 0)
1455                 return -EINVAL;
1456
1457         fmtd->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1458         strcpy(fmtd->description, "Packed YUY2");
1459         fmtd->pixelformat = V4L2_PIX_FMT_YUYV;
1460         memset(fmtd->reserved, 0, sizeof(fmtd->reserved));
1461
1462         return 0;
1463 }
1464
1465 /* Sliced VBI ioctls */
1466 static int vidioc_g_fmt_vbi_capture(struct file *file, void *priv,
1467                                         struct v4l2_format *f)
1468 {
1469         struct em28xx_fh      *fh  = priv;
1470         struct em28xx         *dev = fh->dev;
1471         int                   rc;
1472
1473         rc = check_dev(dev);
1474         if (rc < 0)
1475                 return rc;
1476
1477         mutex_lock(&dev->lock);
1478
1479         f->fmt.sliced.service_set = 0;
1480
1481         em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1482
1483         if (f->fmt.sliced.service_set == 0)
1484                 rc = -EINVAL;
1485
1486         mutex_unlock(&dev->lock);
1487         return rc;
1488 }
1489
1490 static int vidioc_try_set_vbi_capture(struct file *file, void *priv,
1491                         struct v4l2_format *f)
1492 {
1493         struct em28xx_fh      *fh  = priv;
1494         struct em28xx         *dev = fh->dev;
1495         int                   rc;
1496
1497         rc = check_dev(dev);
1498         if (rc < 0)
1499                 return rc;
1500
1501         mutex_lock(&dev->lock);
1502         em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1503         mutex_unlock(&dev->lock);
1504
1505         if (f->fmt.sliced.service_set == 0)
1506                 return -EINVAL;
1507
1508         return 0;
1509 }
1510
1511
1512 static int vidioc_reqbufs(struct file *file, void *priv,
1513                           struct v4l2_requestbuffers *rb)
1514 {
1515         struct em28xx_fh      *fh  = priv;
1516         struct em28xx         *dev = fh->dev;
1517         int                   rc;
1518
1519         rc = check_dev(dev);
1520         if (rc < 0)
1521                 return rc;
1522
1523         return (videobuf_reqbufs(&fh->vb_vidq, rb));
1524 }
1525
1526 static int vidioc_querybuf(struct file *file, void *priv,
1527                            struct v4l2_buffer *b)
1528 {
1529         struct em28xx_fh      *fh  = priv;
1530         struct em28xx         *dev = fh->dev;
1531         int                   rc;
1532
1533         rc = check_dev(dev);
1534         if (rc < 0)
1535                 return rc;
1536
1537         return (videobuf_querybuf(&fh->vb_vidq, b));
1538 }
1539
1540 static int vidioc_qbuf(struct file *file, void *priv, 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_qbuf(&fh->vb_vidq, b));
1551 }
1552
1553 static int vidioc_dqbuf(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_dqbuf(&fh->vb_vidq, b,
1564                                 file->f_flags & O_NONBLOCK));
1565 }
1566
1567 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1568 static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
1569 {
1570         struct em28xx_fh  *fh = priv;
1571
1572         return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
1573 }
1574 #endif
1575
1576
1577 /* ----------------------------------------------------------- */
1578 /* RADIO ESPECIFIC IOCTLS                                      */
1579 /* ----------------------------------------------------------- */
1580
1581 static int radio_querycap(struct file *file, void  *priv,
1582                           struct v4l2_capability *cap)
1583 {
1584         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1585
1586         strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1587         strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1588         strlcpy(cap->bus_info, dev->udev->dev.bus_id, sizeof(cap->bus_info));
1589
1590         cap->version = EM28XX_VERSION_CODE;
1591         cap->capabilities = V4L2_CAP_TUNER;
1592         return 0;
1593 }
1594
1595 static int radio_g_tuner(struct file *file, void *priv,
1596                          struct v4l2_tuner *t)
1597 {
1598         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1599
1600         if (unlikely(t->index > 0))
1601                 return -EINVAL;
1602
1603         strcpy(t->name, "Radio");
1604         t->type = V4L2_TUNER_RADIO;
1605
1606         em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1607         return 0;
1608 }
1609
1610 static int radio_enum_input(struct file *file, void *priv,
1611                             struct v4l2_input *i)
1612 {
1613         if (i->index != 0)
1614                 return -EINVAL;
1615         strcpy(i->name, "Radio");
1616         i->type = V4L2_INPUT_TYPE_TUNER;
1617
1618         return 0;
1619 }
1620
1621 static int radio_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1622 {
1623         if (unlikely(a->index))
1624                 return -EINVAL;
1625
1626         strcpy(a->name, "Radio");
1627         return 0;
1628 }
1629
1630 static int radio_s_tuner(struct file *file, void *priv,
1631                          struct v4l2_tuner *t)
1632 {
1633         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1634
1635         if (0 != t->index)
1636                 return -EINVAL;
1637
1638         em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1639
1640         return 0;
1641 }
1642
1643 static int radio_s_audio(struct file *file, void *fh,
1644                          struct v4l2_audio *a)
1645 {
1646         return 0;
1647 }
1648
1649 static int radio_s_input(struct file *file, void *fh, unsigned int i)
1650 {
1651         return 0;
1652 }
1653
1654 static int radio_queryctrl(struct file *file, void *priv,
1655                            struct v4l2_queryctrl *qc)
1656 {
1657         int i;
1658
1659         if (qc->id <  V4L2_CID_BASE ||
1660                 qc->id >= V4L2_CID_LASTP1)
1661                 return -EINVAL;
1662
1663         for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1664                 if (qc->id && qc->id == em28xx_qctrl[i].id) {
1665                         memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1666                         return 0;
1667                 }
1668         }
1669
1670         return -EINVAL;
1671 }
1672
1673 /*
1674  * em28xx_v4l2_open()
1675  * inits the device and starts isoc transfer
1676  */
1677 static int em28xx_v4l2_open(struct inode *inode, struct file *filp)
1678 {
1679         int minor = iminor(inode);
1680         int errCode = 0, radio = 0;
1681         struct em28xx *h,*dev = NULL;
1682         struct em28xx_fh *fh;
1683         enum v4l2_buf_type fh_type = 0;
1684
1685         list_for_each_entry(h, &em28xx_devlist, devlist) {
1686                 if (h->vdev->minor == minor) {
1687                         dev  = h;
1688                         fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1689                 }
1690                 if (h->vbi_dev->minor == minor) {
1691                         dev  = h;
1692                         fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1693                 }
1694                 if (h->radio_dev &&
1695                     h->radio_dev->minor == minor) {
1696                         radio = 1;
1697                         dev   = h;
1698                 }
1699         }
1700         if (NULL == dev)
1701                 return -ENODEV;
1702
1703         em28xx_videodbg("open minor=%d type=%s users=%d\n",
1704                                 minor, v4l2_type_names[fh_type], dev->users);
1705
1706         fh = kzalloc(sizeof(struct em28xx_fh), GFP_KERNEL);
1707
1708         if (!fh) {
1709                 em28xx_errdev("em28xx-video.c: Out of memory?!\n");
1710                 return -ENOMEM;
1711         }
1712         mutex_lock(&dev->lock);
1713         fh->dev = dev;
1714         fh->radio = radio;
1715         fh->type = fh_type;
1716         filp->private_data = fh;
1717
1718         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1719                 dev->width = norm_maxw(dev);
1720                 dev->height = norm_maxh(dev);
1721                 dev->hscale = 0;
1722                 dev->vscale = 0;
1723
1724                 em28xx_set_alternate(dev);
1725                 em28xx_resolution_set(dev);
1726
1727         }
1728         if (fh->radio) {
1729                 em28xx_videodbg("video_open: setting radio device\n");
1730                 em28xx_i2c_call_clients(dev, AUDC_SET_RADIO, NULL);
1731         }
1732
1733         dev->users++;
1734
1735         videobuf_queue_vmalloc_init(&fh->vb_vidq, &em28xx_video_qops,
1736                         NULL, &dev->slock, fh->type, V4L2_FIELD_INTERLACED,
1737                         sizeof(struct em28xx_buffer), fh);
1738
1739         mutex_unlock(&dev->lock);
1740         return errCode;
1741 }
1742
1743 /*
1744  * em28xx_realease_resources()
1745  * unregisters the v4l2,i2c and usb devices
1746  * called when the device gets disconected or at module unload
1747 */
1748 static void em28xx_release_resources(struct em28xx *dev)
1749 {
1750
1751         /*FIXME: I2C IR should be disconnected */
1752
1753         em28xx_info("V4L2 devices /dev/video%d and /dev/vbi%d deregistered\n",
1754                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
1755                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
1756         list_del(&dev->devlist);
1757         if (dev->radio_dev) {
1758                 if (-1 != dev->radio_dev->minor)
1759                         video_unregister_device(dev->radio_dev);
1760                 else
1761                         video_device_release(dev->radio_dev);
1762                 dev->radio_dev = NULL;
1763         }
1764         if (dev->vbi_dev) {
1765                 if (-1 != dev->vbi_dev->minor)
1766                         video_unregister_device(dev->vbi_dev);
1767                 else
1768                         video_device_release(dev->vbi_dev);
1769                 dev->vbi_dev = NULL;
1770         }
1771         if (dev->vdev) {
1772                 if (-1 != dev->vdev->minor)
1773                         video_unregister_device(dev->vdev);
1774                 else
1775                         video_device_release(dev->vdev);
1776                 dev->vdev = NULL;
1777         }
1778         em28xx_i2c_unregister(dev);
1779         usb_put_dev(dev->udev);
1780
1781         /* Mark device as unused */
1782         em28xx_devused&=~(1<<dev->devno);
1783 }
1784
1785 /*
1786  * em28xx_v4l2_close()
1787  * stops streaming and deallocates all resources allocated by the v4l2 calls and ioctls
1788  */
1789 static int em28xx_v4l2_close(struct inode *inode, struct file *filp)
1790 {
1791         struct em28xx_fh *fh  = filp->private_data;
1792         struct em28xx    *dev = fh->dev;
1793         int              errCode;
1794
1795         em28xx_videodbg("users=%d\n", dev->users);
1796
1797
1798         if (res_check(fh))
1799                 res_free(fh);
1800
1801         mutex_lock(&dev->lock);
1802
1803         if (dev->users == 1) {
1804                 videobuf_stop(&fh->vb_vidq);
1805                 videobuf_mmap_free(&fh->vb_vidq);
1806
1807                 /* the device is already disconnect,
1808                    free the remaining resources */
1809                 if (dev->state & DEV_DISCONNECTED) {
1810                         em28xx_release_resources(dev);
1811                         mutex_unlock(&dev->lock);
1812                         kfree(dev);
1813                         return 0;
1814                 }
1815
1816                 /* do this before setting alternate! */
1817                 em28xx_uninit_isoc(dev);
1818
1819                 /* set alternate 0 */
1820                 dev->alt = 0;
1821                 em28xx_videodbg("setting alternate 0\n");
1822                 errCode = usb_set_interface(dev->udev, 0, 0);
1823                 if (errCode < 0) {
1824                         em28xx_errdev("cannot change alternate number to "
1825                                         "0 (error=%i)\n", errCode);
1826                 }
1827         }
1828         kfree(fh);
1829         dev->users--;
1830         wake_up_interruptible_nr(&dev->open, 1);
1831         mutex_unlock(&dev->lock);
1832         return 0;
1833 }
1834
1835 /*
1836  * em28xx_v4l2_read()
1837  * will allocate buffers when called for the first time
1838  */
1839 static ssize_t
1840 em28xx_v4l2_read(struct file *filp, char __user * buf, size_t count,
1841                  loff_t *pos)
1842 {
1843         struct em28xx_fh *fh = filp->private_data;
1844         struct em28xx *dev = fh->dev;
1845         int rc;
1846
1847         rc = check_dev(dev);
1848         if (rc < 0)
1849                 return rc;
1850
1851         /* FIXME: read() is not prepared to allow changing the video
1852            resolution while streaming. Seems a bug at em28xx_set_fmt
1853          */
1854
1855         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1856                 if (unlikely(res_get(fh)))
1857                         return -EBUSY;
1858
1859                 return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1860                                         filp->f_flags & O_NONBLOCK);
1861         }
1862         return 0;
1863 }
1864
1865 /*
1866  * em28xx_v4l2_poll()
1867  * will allocate buffers when called for the first time
1868  */
1869 static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table * wait)
1870 {
1871         struct em28xx_fh *fh = filp->private_data;
1872         struct em28xx *dev = fh->dev;
1873         int rc;
1874
1875         rc = check_dev(dev);
1876         if (rc < 0)
1877                 return rc;
1878
1879         if (unlikely(res_get(fh) < 0))
1880                 return POLLERR;
1881
1882         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1883                 return POLLERR;
1884
1885         return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
1886 }
1887
1888 /*
1889  * em28xx_v4l2_mmap()
1890  */
1891 static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
1892 {
1893         struct em28xx_fh *fh    = filp->private_data;
1894         struct em28xx    *dev   = fh->dev;
1895         int              rc;
1896
1897         if (unlikely(res_get(fh) < 0))
1898                 return -EBUSY;
1899
1900         rc = check_dev(dev);
1901         if (rc < 0)
1902                 return rc;
1903
1904         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1905
1906         em28xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
1907                 (unsigned long)vma->vm_start,
1908                 (unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1909                 rc);
1910
1911         return rc;
1912 }
1913
1914 static const struct file_operations em28xx_v4l_fops = {
1915         .owner         = THIS_MODULE,
1916         .open          = em28xx_v4l2_open,
1917         .release       = em28xx_v4l2_close,
1918         .read          = em28xx_v4l2_read,
1919         .poll          = em28xx_v4l2_poll,
1920         .mmap          = em28xx_v4l2_mmap,
1921         .ioctl         = video_ioctl2,
1922         .llseek        = no_llseek,
1923         .compat_ioctl  = v4l_compat_ioctl32,
1924 };
1925
1926 static const struct file_operations radio_fops = {
1927         .owner         = THIS_MODULE,
1928         .open          = em28xx_v4l2_open,
1929         .release       = em28xx_v4l2_close,
1930         .ioctl         = video_ioctl2,
1931         .compat_ioctl  = v4l_compat_ioctl32,
1932         .llseek        = no_llseek,
1933 };
1934
1935 static const struct video_device em28xx_video_template = {
1936         .fops                       = &em28xx_v4l_fops,
1937         .release                    = video_device_release,
1938
1939         .minor                      = -1,
1940         .vidioc_querycap            = vidioc_querycap,
1941         .vidioc_enum_fmt_cap        = vidioc_enum_fmt_cap,
1942         .vidioc_g_fmt_cap           = vidioc_g_fmt_cap,
1943         .vidioc_try_fmt_cap         = vidioc_try_fmt_cap,
1944         .vidioc_s_fmt_cap           = vidioc_s_fmt_cap,
1945         .vidioc_g_audio             = vidioc_g_audio,
1946         .vidioc_s_audio             = vidioc_s_audio,
1947         .vidioc_cropcap             = vidioc_cropcap,
1948
1949         .vidioc_g_fmt_vbi_capture   = vidioc_g_fmt_vbi_capture,
1950         .vidioc_try_fmt_vbi_capture = vidioc_try_set_vbi_capture,
1951         .vidioc_s_fmt_vbi_capture   = vidioc_try_set_vbi_capture,
1952
1953         .vidioc_reqbufs             = vidioc_reqbufs,
1954         .vidioc_querybuf            = vidioc_querybuf,
1955         .vidioc_qbuf                = vidioc_qbuf,
1956         .vidioc_dqbuf               = vidioc_dqbuf,
1957         .vidioc_s_std               = vidioc_s_std,
1958         .vidioc_enum_input          = vidioc_enum_input,
1959         .vidioc_g_input             = vidioc_g_input,
1960         .vidioc_s_input             = vidioc_s_input,
1961         .vidioc_queryctrl           = vidioc_queryctrl,
1962         .vidioc_g_ctrl              = vidioc_g_ctrl,
1963         .vidioc_s_ctrl              = vidioc_s_ctrl,
1964         .vidioc_streamon            = vidioc_streamon,
1965         .vidioc_streamoff           = vidioc_streamoff,
1966         .vidioc_g_tuner             = vidioc_g_tuner,
1967         .vidioc_s_tuner             = vidioc_s_tuner,
1968         .vidioc_g_frequency         = vidioc_g_frequency,
1969         .vidioc_s_frequency         = vidioc_s_frequency,
1970 #ifdef CONFIG_VIDEO_ADV_DEBUG
1971         .vidioc_g_register          = vidioc_g_register,
1972         .vidioc_s_register          = vidioc_s_register,
1973 #endif
1974 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1975         .vidiocgmbuf                = vidiocgmbuf,
1976 #endif
1977
1978         .tvnorms                    = V4L2_STD_ALL,
1979         .current_norm               = V4L2_STD_PAL,
1980 };
1981
1982 static struct video_device em28xx_radio_template = {
1983         .name                 = "em28xx-radio",
1984         .type                 = VID_TYPE_TUNER,
1985         .fops                 = &radio_fops,
1986         .minor                = -1,
1987         .vidioc_querycap      = radio_querycap,
1988         .vidioc_g_tuner       = radio_g_tuner,
1989         .vidioc_enum_input    = radio_enum_input,
1990         .vidioc_g_audio       = radio_g_audio,
1991         .vidioc_s_tuner       = radio_s_tuner,
1992         .vidioc_s_audio       = radio_s_audio,
1993         .vidioc_s_input       = radio_s_input,
1994         .vidioc_queryctrl     = radio_queryctrl,
1995         .vidioc_g_ctrl        = vidioc_g_ctrl,
1996         .vidioc_s_ctrl        = vidioc_s_ctrl,
1997         .vidioc_g_frequency   = vidioc_g_frequency,
1998         .vidioc_s_frequency   = vidioc_s_frequency,
1999 #ifdef CONFIG_VIDEO_ADV_DEBUG
2000         .vidioc_g_register    = vidioc_g_register,
2001         .vidioc_s_register    = vidioc_s_register,
2002 #endif
2003 };
2004
2005 /******************************** usb interface *****************************************/
2006
2007
2008 static LIST_HEAD(em28xx_extension_devlist);
2009 static DEFINE_MUTEX(em28xx_extension_devlist_lock);
2010
2011 int em28xx_register_extension(struct em28xx_ops *ops)
2012 {
2013         struct em28xx *h, *dev = NULL;
2014
2015         list_for_each_entry(h, &em28xx_devlist, devlist)
2016                 dev = h;
2017
2018         mutex_lock(&em28xx_extension_devlist_lock);
2019         list_add_tail(&ops->next, &em28xx_extension_devlist);
2020         if (dev)
2021                 ops->init(dev);
2022
2023         printk(KERN_INFO "Em28xx: Initialized (%s) extension\n", ops->name);
2024         mutex_unlock(&em28xx_extension_devlist_lock);
2025
2026         return 0;
2027 }
2028 EXPORT_SYMBOL(em28xx_register_extension);
2029
2030 void em28xx_unregister_extension(struct em28xx_ops *ops)
2031 {
2032         struct em28xx *h, *dev = NULL;
2033
2034         list_for_each_entry(h, &em28xx_devlist, devlist)
2035                 dev = h;
2036
2037         if (dev)
2038                 ops->fini(dev);
2039
2040         mutex_lock(&em28xx_extension_devlist_lock);
2041         printk(KERN_INFO "Em28xx: Removed (%s) extension\n", ops->name);
2042         list_del(&ops->next);
2043         mutex_unlock(&em28xx_extension_devlist_lock);
2044 }
2045 EXPORT_SYMBOL(em28xx_unregister_extension);
2046
2047 static struct video_device *em28xx_vdev_init(struct em28xx *dev,
2048                                              const struct video_device *template,
2049                                              const int type,
2050                                              const char *type_name)
2051 {
2052         struct video_device *vfd;
2053
2054         vfd = video_device_alloc();
2055         if (NULL == vfd)
2056                 return NULL;
2057         *vfd = *template;
2058         vfd->minor   = -1;
2059         vfd->dev = &dev->udev->dev;
2060         vfd->release = video_device_release;
2061         vfd->type = type;
2062         vfd->debug = video_debug;
2063
2064         snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2065                  dev->name, type_name);
2066
2067         return vfd;
2068 }
2069
2070
2071 /*
2072  * em28xx_init_dev()
2073  * allocates and inits the device structs, registers i2c bus and v4l device
2074  */
2075 static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
2076                            int minor)
2077 {
2078         struct em28xx_ops *ops = NULL;
2079         struct em28xx *dev = *devhandle;
2080         int retval = -ENOMEM;
2081         int errCode;
2082         unsigned int maxh, maxw;
2083
2084         dev->udev = udev;
2085         mutex_init(&dev->lock);
2086         spin_lock_init(&dev->slock);
2087         init_waitqueue_head(&dev->open);
2088         init_waitqueue_head(&dev->wait_frame);
2089         init_waitqueue_head(&dev->wait_stream);
2090
2091         dev->em28xx_write_regs = em28xx_write_regs;
2092         dev->em28xx_read_reg = em28xx_read_reg;
2093         dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
2094         dev->em28xx_write_regs_req = em28xx_write_regs_req;
2095         dev->em28xx_read_reg_req = em28xx_read_reg_req;
2096         dev->is_em2800 = em28xx_boards[dev->model].is_em2800;
2097
2098         errCode = em28xx_read_reg(dev, CHIPID_REG);
2099         if (errCode >= 0)
2100                 em28xx_info("em28xx chip ID = %d\n", errCode);
2101
2102         em28xx_pre_card_setup(dev);
2103
2104         errCode = em28xx_config(dev);
2105         if (errCode) {
2106                 em28xx_errdev("error configuring device\n");
2107                 em28xx_devused &= ~(1<<dev->devno);
2108                 kfree(dev);
2109                 return -ENOMEM;
2110         }
2111
2112         /* register i2c bus */
2113         em28xx_i2c_register(dev);
2114
2115         /* Do board specific init and eeprom reading */
2116         em28xx_card_setup(dev);
2117
2118         /* Configure audio */
2119         em28xx_audio_analog_set(dev);
2120
2121         /* configure the device */
2122         em28xx_config_i2c(dev);
2123
2124         /* set default norm */
2125         dev->norm = em28xx_video_template.current_norm;
2126
2127         maxw = norm_maxw(dev);
2128         maxh = norm_maxh(dev);
2129
2130         /* set default image size */
2131         dev->width = maxw;
2132         dev->height = maxh;
2133         dev->interlaced = EM28XX_INTERLACED_DEFAULT;
2134         dev->hscale = 0;
2135         dev->vscale = 0;
2136         dev->ctl_input = 2;
2137
2138         errCode = em28xx_config(dev);
2139
2140         list_add_tail(&dev->devlist, &em28xx_devlist);
2141
2142         /* allocate and fill video video_device struct */
2143         dev->vdev = em28xx_vdev_init(dev, &em28xx_video_template,
2144                                           VID_TYPE_CAPTURE, "video");
2145         if (NULL == dev->vdev) {
2146                 em28xx_errdev("cannot allocate video_device.\n");
2147                 goto fail_unreg;
2148         }
2149         if (dev->tuner_type != TUNER_ABSENT)
2150                 dev->vdev->type |= VID_TYPE_TUNER;
2151
2152         /* register v4l2 video video_device */
2153         retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2154                                        video_nr[dev->devno]);
2155         if (retval) {
2156                 em28xx_errdev("unable to register video device (error=%i).\n",
2157                               retval);
2158                 goto fail_unreg;
2159         }
2160
2161         /* Allocate and fill vbi video_device struct */
2162         dev->vbi_dev = em28xx_vdev_init(dev, &em28xx_video_template,
2163                                           VFL_TYPE_VBI, "vbi");
2164         /* register v4l2 vbi video_device */
2165         if (video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2166                                         vbi_nr[dev->devno]) < 0) {
2167                 em28xx_errdev("unable to register vbi device\n");
2168                 retval = -ENODEV;
2169                 goto fail_unreg;
2170         }
2171
2172         if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2173                 dev->radio_dev = em28xx_vdev_init(dev, &em28xx_radio_template,
2174                                         VFL_TYPE_RADIO, "radio");
2175                 if (NULL == dev->radio_dev) {
2176                         em28xx_errdev("cannot allocate video_device.\n");
2177                         goto fail_unreg;
2178                 }
2179                 retval = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2180                                             radio_nr[dev->devno]);
2181                 if (retval < 0) {
2182                         em28xx_errdev("can't register radio device\n");
2183                         goto fail_unreg;
2184                 }
2185                 em28xx_info("Registered radio device as /dev/radio%d\n",
2186                             dev->radio_dev->minor & 0x1f);
2187         }
2188
2189         /* init video dma queues */
2190         INIT_LIST_HEAD(&dev->vidq.active);
2191         INIT_LIST_HEAD(&dev->vidq.queued);
2192
2193
2194         if (dev->has_msp34xx) {
2195                 /* Send a reset to other chips via gpio */
2196                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xf7", 1);
2197                 msleep(3);
2198                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xff", 1);
2199                 msleep(3);
2200         }
2201
2202         video_mux(dev, 0);
2203
2204         em28xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
2205                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
2206                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
2207
2208         mutex_lock(&em28xx_extension_devlist_lock);
2209         if (!list_empty(&em28xx_extension_devlist)) {
2210                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2211                         if (ops->id)
2212                                 ops->init(dev);
2213                 }
2214         }
2215         mutex_unlock(&em28xx_extension_devlist_lock);
2216
2217         return 0;
2218
2219 fail_unreg:
2220         em28xx_release_resources(dev);
2221         mutex_unlock(&dev->lock);
2222         kfree(dev);
2223         return retval;
2224 }
2225
2226 #if defined(CONFIG_MODULES) && defined(MODULE)
2227 static void request_module_async(struct work_struct *work)
2228 {
2229         struct em28xx *dev = container_of(work,
2230                              struct em28xx, request_module_wk);
2231
2232         if (dev->has_audio_class)
2233                 request_module("snd-usb-audio");
2234         else
2235                 request_module("em28xx-alsa");
2236
2237         if (dev->has_dvb)
2238                 request_module("em28xx-dvb");
2239 }
2240
2241 static void request_modules(struct em28xx *dev)
2242 {
2243         INIT_WORK(&dev->request_module_wk, request_module_async);
2244         schedule_work(&dev->request_module_wk);
2245 }
2246 #else
2247 #define request_modules(dev)
2248 #endif /* CONFIG_MODULES */
2249
2250 /*
2251  * em28xx_usb_probe()
2252  * checks for supported devices
2253  */
2254 static int em28xx_usb_probe(struct usb_interface *interface,
2255                             const struct usb_device_id *id)
2256 {
2257         const struct usb_endpoint_descriptor *endpoint;
2258         struct usb_device *udev;
2259         struct usb_interface *uif;
2260         struct em28xx *dev = NULL;
2261         int retval = -ENODEV;
2262         int i, nr, ifnum;
2263
2264         udev = usb_get_dev(interface_to_usbdev(interface));
2265         ifnum = interface->altsetting[0].desc.bInterfaceNumber;
2266
2267         /* Check to see next free device and mark as used */
2268         nr=find_first_zero_bit(&em28xx_devused,EM28XX_MAXBOARDS);
2269         em28xx_devused|=1<<nr;
2270
2271         /* Don't register audio interfaces */
2272         if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2273                 em28xx_err(DRIVER_NAME " audio device (%04x:%04x): interface %i, class %i\n",
2274                                 udev->descriptor.idVendor,udev->descriptor.idProduct,
2275                                 ifnum,
2276                                 interface->altsetting[0].desc.bInterfaceClass);
2277
2278                 em28xx_devused&=~(1<<nr);
2279                 return -ENODEV;
2280         }
2281
2282         em28xx_err(DRIVER_NAME " new video device (%04x:%04x): interface %i, class %i\n",
2283                         udev->descriptor.idVendor,udev->descriptor.idProduct,
2284                         ifnum,
2285                         interface->altsetting[0].desc.bInterfaceClass);
2286
2287         endpoint = &interface->cur_altsetting->endpoint[1].desc;
2288
2289         /* check if the device has the iso in endpoint at the correct place */
2290         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2291             USB_ENDPOINT_XFER_ISOC) {
2292                 em28xx_err(DRIVER_NAME " probing error: endpoint is non-ISO endpoint!\n");
2293                 em28xx_devused&=~(1<<nr);
2294                 return -ENODEV;
2295         }
2296         if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
2297                 em28xx_err(DRIVER_NAME " probing error: endpoint is ISO OUT endpoint!\n");
2298                 em28xx_devused&=~(1<<nr);
2299                 return -ENODEV;
2300         }
2301
2302         if (nr >= EM28XX_MAXBOARDS) {
2303                 printk (DRIVER_NAME ": Supports only %i em28xx boards.\n",EM28XX_MAXBOARDS);
2304                 em28xx_devused&=~(1<<nr);
2305                 return -ENOMEM;
2306         }
2307
2308         /* allocate memory for our device state and initialize it */
2309         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2310         if (dev == NULL) {
2311                 em28xx_err(DRIVER_NAME ": out of memory!\n");
2312                 em28xx_devused&=~(1<<nr);
2313                 return -ENOMEM;
2314         }
2315
2316         snprintf(dev->name, 29, "em28xx #%d", nr);
2317         dev->devno = nr;
2318         dev->model = id->driver_info;
2319         dev->alt   = -1;
2320
2321         /* Checks if audio is provided by some interface */
2322         for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
2323                 uif = udev->config->interface[i];
2324                 if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2325                         dev->has_audio_class = 1;
2326                         break;
2327                 }
2328         }
2329
2330         printk(KERN_INFO DRIVER_NAME " %s usb audio class\n",
2331                    dev->has_audio_class ? "Has" : "Doesn't have");
2332
2333         /* compute alternate max packet sizes */
2334         uif = udev->actconfig->interface[0];
2335
2336         dev->num_alt=uif->num_altsetting;
2337         em28xx_info("Alternate settings: %i\n",dev->num_alt);
2338 //      dev->alt_max_pkt_size = kmalloc(sizeof(*dev->alt_max_pkt_size)*
2339         dev->alt_max_pkt_size = kmalloc(32*
2340                                                 dev->num_alt,GFP_KERNEL);
2341         if (dev->alt_max_pkt_size == NULL) {
2342                 em28xx_errdev("out of memory!\n");
2343                 em28xx_devused&=~(1<<nr);
2344                 kfree(dev);
2345                 return -ENOMEM;
2346         }
2347
2348         for (i = 0; i < dev->num_alt ; i++) {
2349                 u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.
2350                                                         wMaxPacketSize);
2351                 dev->alt_max_pkt_size[i] =
2352                     (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
2353                 em28xx_info("Alternate setting %i, max size= %i\n",i,
2354                                                         dev->alt_max_pkt_size[i]);
2355         }
2356
2357         if ((card[nr]>=0)&&(card[nr]<em28xx_bcount))
2358                 dev->model = card[nr];
2359
2360         /* allocate device struct */
2361         retval = em28xx_init_dev(&dev, udev, nr);
2362         if (retval)
2363                 return retval;
2364
2365         em28xx_info("Found %s\n", em28xx_boards[dev->model].name);
2366
2367         /* save our data pointer in this interface device */
2368         usb_set_intfdata(interface, dev);
2369
2370 #if defined(CONFIG_VIDEO_EM28XX_DVB) || defined(CONFIG_VIDEO_EM28XX_DVB_MODULE)
2371         dev->qops = kmalloc(sizeof(em28xx_video_qops), GFP_KERNEL);
2372         memcpy(dev->qops, &em28xx_video_qops, sizeof(em28xx_video_qops));
2373 #endif
2374
2375         request_modules(dev);
2376
2377         return 0;
2378 }
2379
2380 /*
2381  * em28xx_usb_disconnect()
2382  * called when the device gets diconencted
2383  * video device will be unregistered on v4l2_close in case it is still open
2384  */
2385 static void em28xx_usb_disconnect(struct usb_interface *interface)
2386 {
2387         struct em28xx *dev;
2388         struct em28xx_ops *ops = NULL;
2389
2390         dev = usb_get_intfdata(interface);
2391         usb_set_intfdata(interface, NULL);
2392
2393         if (!dev)
2394                 return;
2395
2396         em28xx_info("disconnecting %s\n", dev->vdev->name);
2397
2398         /* wait until all current v4l2 io is finished then deallocate resources */
2399         mutex_lock(&dev->lock);
2400
2401         wake_up_interruptible_all(&dev->open);
2402
2403         if (dev->users) {
2404                 em28xx_warn
2405                     ("device /dev/video%d is open! Deregistration and memory "
2406                      "deallocation are deferred on close.\n",
2407                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN);
2408
2409                 dev->state |= DEV_MISCONFIGURED;
2410                 em28xx_uninit_isoc(dev);
2411                 dev->state |= DEV_DISCONNECTED;
2412                 wake_up_interruptible(&dev->wait_frame);
2413                 wake_up_interruptible(&dev->wait_stream);
2414         } else {
2415                 dev->state |= DEV_DISCONNECTED;
2416                 em28xx_release_resources(dev);
2417         }
2418         mutex_unlock(&dev->lock);
2419
2420         mutex_lock(&em28xx_extension_devlist_lock);
2421         if (!list_empty(&em28xx_extension_devlist)) {
2422                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2423                         ops->fini(dev);
2424                 }
2425         }
2426         mutex_unlock(&em28xx_extension_devlist_lock);
2427
2428         if (!dev->users) {
2429                 kfree(dev->alt_max_pkt_size);
2430                 kfree(dev);
2431         }
2432 }
2433
2434 static struct usb_driver em28xx_usb_driver = {
2435         .name = "em28xx",
2436         .probe = em28xx_usb_probe,
2437         .disconnect = em28xx_usb_disconnect,
2438         .id_table = em28xx_id_table,
2439 };
2440
2441 static int __init em28xx_module_init(void)
2442 {
2443         int result;
2444
2445         printk(KERN_INFO DRIVER_NAME " v4l2 driver version %d.%d.%d loaded\n",
2446                (EM28XX_VERSION_CODE >> 16) & 0xff,
2447                (EM28XX_VERSION_CODE >> 8) & 0xff, EM28XX_VERSION_CODE & 0xff);
2448 #ifdef SNAPSHOT
2449         printk(KERN_INFO DRIVER_NAME " snapshot date %04d-%02d-%02d\n",
2450                SNAPSHOT / 10000, (SNAPSHOT / 100) % 100, SNAPSHOT % 100);
2451 #endif
2452
2453         /* register this driver with the USB subsystem */
2454         result = usb_register(&em28xx_usb_driver);
2455         if (result)
2456                 em28xx_err(DRIVER_NAME
2457                            " usb_register failed. Error number %d.\n", result);
2458
2459         return result;
2460 }
2461
2462 static void __exit em28xx_module_exit(void)
2463 {
2464         /* deregister this driver with the USB subsystem */
2465         usb_deregister(&em28xx_usb_driver);
2466 }
2467
2468 module_init(em28xx_module_init);
2469 module_exit(em28xx_module_exit);