]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/video/em28xx/em28xx-video.c
V4L/DVB (7559): em28xx: Fills the entire buffer, before getting another one
[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 /* Limits minimum and default number of buffers */
67 #define EM28XX_MIN_BUF 4
68 #define EM28XX_DEF_BUF 8
69
70 MODULE_AUTHOR(DRIVER_AUTHOR);
71 MODULE_DESCRIPTION(DRIVER_DESC);
72 MODULE_LICENSE("GPL");
73
74 static LIST_HEAD(em28xx_devlist);
75
76 static unsigned int card[]     = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
77 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
78 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
79 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
80
81 module_param_array(card,  int, NULL, 0444);
82 module_param_array(video_nr, int, NULL, 0444);
83 module_param_array(vbi_nr, int, NULL, 0444);
84 module_param_array(radio_nr, int, NULL, 0444);
85 MODULE_PARM_DESC(card,     "card type");
86 MODULE_PARM_DESC(video_nr, "video device numbers");
87 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
88 MODULE_PARM_DESC(radio_nr, "radio device numbers");
89
90 static unsigned int video_debug;
91 module_param(video_debug,int,0644);
92 MODULE_PARM_DESC(video_debug,"enable debug messages [video]");
93
94 /* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
95 static unsigned long em28xx_devused;
96
97 /* supported controls */
98 /* Common to all boards */
99 static struct v4l2_queryctrl em28xx_qctrl[] = {
100         {
101                 .id = V4L2_CID_AUDIO_VOLUME,
102                 .type = V4L2_CTRL_TYPE_INTEGER,
103                 .name = "Volume",
104                 .minimum = 0x0,
105                 .maximum = 0x1f,
106                 .step = 0x1,
107                 .default_value = 0x1f,
108                 .flags = 0,
109         },{
110                 .id = V4L2_CID_AUDIO_MUTE,
111                 .type = V4L2_CTRL_TYPE_BOOLEAN,
112                 .name = "Mute",
113                 .minimum = 0,
114                 .maximum = 1,
115                 .step = 1,
116                 .default_value = 1,
117                 .flags = 0,
118         }
119 };
120
121 static struct usb_driver em28xx_usb_driver;
122
123 /* ------------------------------------------------------------------
124         DMA and thread functions
125    ------------------------------------------------------------------*/
126
127 /*
128  * Announces that a buffer were filled and request the next
129  */
130 static inline void buffer_filled(struct em28xx *dev,
131                                   struct em28xx_dmaqueue *dma_q,
132                                   struct em28xx_buffer *buf)
133 {
134         /* Advice that buffer was filled */
135         em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
136         buf->vb.state = VIDEOBUF_DONE;
137         buf->vb.field_count++;
138         do_gettimeofday(&buf->vb.ts);
139
140         dev->isoc_ctl.buf = NULL;
141
142         list_del(&buf->vb.queue);
143         wake_up(&buf->vb.done);
144 }
145
146 /*
147  * Identify the buffer header type and properly handles
148  */
149 static void em28xx_copy_video(struct em28xx *dev,
150                               struct em28xx_dmaqueue  *dma_q,
151                               struct em28xx_buffer *buf,
152                               unsigned char *p,
153                               unsigned char *outp, unsigned long len)
154 {
155         void *fieldstart, *startwrite, *startread;
156         int  linesdone, currlinedone, offset, lencopy, remain;
157
158         if (dev->frame_size != buf->vb.size) {
159                 em28xx_errdev("size %i and buf.length %lu are different!\n",
160                               dev->frame_size, buf->vb.size);
161                 return;
162         }
163
164         if (dma_q->pos + len > buf->vb.size)
165                 len = buf->vb.size - dma_q->pos;
166
167         if (p[0] != 0x88 && p[0] != 0x22) {
168                 em28xx_isocdbg("frame is not complete\n");
169                 len += 4;
170         } else
171                 p += 4;
172
173         startread = p;
174         remain = len;
175
176         /* Interlaces frame */
177         if (buf->top_field)
178                 fieldstart = outp;
179         else
180                 fieldstart = outp + dev->bytesperline;
181
182         linesdone = dma_q->pos / dev->bytesperline;
183         currlinedone = dma_q->pos % dev->bytesperline;
184         offset = linesdone * dev->bytesperline * 2 + currlinedone;
185         startwrite = fieldstart + offset;
186         lencopy = dev->bytesperline - currlinedone;
187         lencopy = lencopy > remain ? remain : lencopy;
188
189         if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
190                 em28xx_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
191                                ((char *)startwrite + lencopy) -
192                                ((char *)outp + buf->vb.size));
193                 lencopy = remain = (char *)outp + buf->vb.size - (char *)startwrite;
194         }
195         if (lencopy <= 0)
196                 return;
197         memcpy(startwrite, startread, lencopy);
198
199         remain -= lencopy;
200
201         while (remain > 0) {
202                 startwrite += lencopy + dev->bytesperline;
203                 startread += lencopy;
204                 if (dev->bytesperline > remain)
205                         lencopy = remain;
206                 else
207                         lencopy = dev->bytesperline;
208
209                 if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
210                         em28xx_isocdbg("Overflow of %zi bytes past buffer end (2)\n",
211                                        ((char *)startwrite + lencopy) -
212                                        ((char *)outp + buf->vb.size));
213                         lencopy = remain = (char *)outp + buf->vb.size -
214                                            (char *)startwrite;
215                 }
216                 if (lencopy <= 0)
217                         break;
218
219                 memcpy(startwrite, startread, lencopy);
220
221                 remain -= lencopy;
222         }
223
224         dma_q->pos += len;
225 }
226
227 static inline void print_err_status(struct em28xx *dev,
228                                      int packet, int status)
229 {
230         char *errmsg = "Unknown";
231
232         switch (status) {
233         case -ENOENT:
234                 errmsg = "unlinked synchronuously";
235                 break;
236         case -ECONNRESET:
237                 errmsg = "unlinked asynchronuously";
238                 break;
239         case -ENOSR:
240                 errmsg = "Buffer error (overrun)";
241                 break;
242         case -EPIPE:
243                 errmsg = "Stalled (device not responding)";
244                 break;
245         case -EOVERFLOW:
246                 errmsg = "Babble (bad cable?)";
247                 break;
248         case -EPROTO:
249                 errmsg = "Bit-stuff error (bad cable?)";
250                 break;
251         case -EILSEQ:
252                 errmsg = "CRC/Timeout (could be anything)";
253                 break;
254         case -ETIME:
255                 errmsg = "Device does not respond";
256                 break;
257         }
258         if (packet < 0) {
259                 em28xx_isocdbg("URB status %d [%s].\n", status, errmsg);
260         } else {
261                 em28xx_isocdbg("URB packet %d, status %d [%s].\n",
262                                packet, status, errmsg);
263         }
264 }
265
266 /*
267  * video-buf generic routine to get the next available buffer
268  */
269 static inline int get_next_buf(struct em28xx_dmaqueue *dma_q,
270                                           struct em28xx_buffer **buf)
271 {
272         struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
273
274         /* If the previous buffer were not filled yet, continue */
275         *buf = dev->isoc_ctl.buf;
276         if (*buf)
277                 return 1;
278
279         if (list_empty(&dma_q->active)) {
280                 em28xx_isocdbg("No active queue to serve\n");
281                 return 0;
282         }
283
284         *buf = list_entry(dma_q->active.next, struct em28xx_buffer, vb.queue);
285
286
287         dev->isoc_ctl.buf = *buf;
288
289         return 1;
290 }
291
292 /*
293  * Controls the isoc copy of each urb packet
294  */
295 static inline int em28xx_isoc_copy(struct urb *urb)
296 {
297         struct em28xx_buffer    *buf;
298         struct em28xx_dmaqueue  *dma_q = urb->context;
299         struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
300         unsigned char *outp;
301         int i, len = 0, rc = 1;
302         unsigned char *p;
303
304         if (!dev)
305                 return 0;
306
307         if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
308                 return 0;
309
310         if (urb->status < 0) {
311                 print_err_status(dev, -1, urb->status);
312                 if (urb->status == -ENOENT)
313                         return 0;
314         }
315
316         rc = get_next_buf(dma_q, &buf);
317         if (rc <= 0)
318                 return rc;
319
320         outp = videobuf_to_vmalloc(&buf->vb);
321
322         for (i = 0; i < urb->number_of_packets; i++) {
323                 int status = urb->iso_frame_desc[i].status;
324
325                 if (status < 0) {
326                         print_err_status(dev, i, status);
327                         if (urb->iso_frame_desc[i].status != -EPROTO)
328                                 continue;
329                 }
330
331                 len = urb->iso_frame_desc[i].actual_length - 4;
332
333                 if (urb->iso_frame_desc[i].actual_length <= 0) {
334                         /* em28xx_isocdbg("packet %d is empty",i); - spammy */
335                         continue;
336                 }
337                 if (urb->iso_frame_desc[i].actual_length >
338                                                 dev->max_pkt_size) {
339                         em28xx_isocdbg("packet bigger than packet size");
340                         continue;
341                 }
342
343                 p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
344
345                 /* FIXME: incomplete buffer checks where removed to make
346                    logic simpler. Impacts of those changes should be evaluated
347                  */
348                 if (p[0] == 0x22 && p[1] == 0x5a) {
349                         em28xx_isocdbg("Video frame %d, length=%i, %s\n", p[2],
350                                        len, (p[2] & 1)? "odd" : "even");
351
352                         if (p[2] & 1)
353                                 buf->top_field = 0;
354                         else {
355                                 if (buf->receiving) {
356                                         buffer_filled(dev, dma_q, buf);
357                                         rc = get_next_buf(dma_q, &buf);
358                                         if (rc <= 0)
359                                                 return rc;
360                                         outp = videobuf_to_vmalloc(&buf->vb);
361                                 }
362
363                                 buf->top_field = 1;
364                         }
365                         buf->receiving = 1;
366                         dma_q->pos = 0;
367                 } else if (p[0] == 0x33 && p[1] == 0x95 && p[2] == 0x00) {
368                         em28xx_isocdbg("VBI HEADER!!!\n");
369                 }
370
371                 em28xx_copy_video(dev, dma_q, buf, p, outp, len);
372
373                 /* FIXME: Should add vbi copy */
374         }
375         return rc;
376 }
377
378 /* ------------------------------------------------------------------
379         URB control
380    ------------------------------------------------------------------*/
381
382 /*
383  * IRQ callback, called by URB callback
384  */
385 static void em28xx_irq_callback(struct urb *urb)
386 {
387         struct em28xx_dmaqueue  *dma_q = urb->context;
388         struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
389         int rc, i;
390         unsigned long flags;
391
392         spin_lock_irqsave(&dev->slock, flags);
393
394         /* Copy data from URB */
395         rc = em28xx_isoc_copy(urb);
396
397         /* Reset urb buffers */
398         for (i = 0; i < urb->number_of_packets; i++) {
399                 urb->iso_frame_desc[i].status = 0;
400                 urb->iso_frame_desc[i].actual_length = 0;
401         }
402         urb->status = 0;
403
404         urb->status = usb_submit_urb(urb, GFP_ATOMIC);
405         if (urb->status) {
406                 em28xx_err("urb resubmit failed (error=%i)\n",
407                         urb->status);
408         }
409
410         spin_unlock_irqrestore(&dev->slock, flags);
411 }
412
413 /*
414  * Stop and Deallocate URBs
415  */
416 static void em28xx_uninit_isoc(struct em28xx *dev)
417 {
418         struct urb *urb;
419         int i;
420
421         em28xx_isocdbg("em28xx: called em28xx_uninit_isoc\n");
422
423         dev->isoc_ctl.nfields = -1;
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         em28xx_capture_start(dev, 0);
449 }
450
451 /*
452  * Allocate URBs and start IRQ
453  */
454 static int em28xx_prepare_isoc(struct em28xx *dev, int max_packets,
455                                int num_bufs)
456 {
457         struct em28xx_dmaqueue *dma_q = &dev->vidq;
458         int i;
459         int sb_size, pipe;
460         struct urb *urb;
461         int j, k;
462
463         em28xx_isocdbg("em28xx: called em28xx_prepare_isoc\n");
464
465         /* De-allocates all pending stuff */
466         em28xx_uninit_isoc(dev);
467
468         dev->isoc_ctl.num_bufs = num_bufs;
469
470         dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs,  GFP_KERNEL);
471         if (!dev->isoc_ctl.urb) {
472                 em28xx_errdev("cannot alloc memory for usb buffers\n");
473                 return -ENOMEM;
474         }
475
476         dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
477                                               GFP_KERNEL);
478         if (!dev->isoc_ctl.urb) {
479                 em28xx_errdev("cannot allocate memory for usbtransfer\n");
480                 kfree(dev->isoc_ctl.urb);
481                 return -ENOMEM;
482         }
483
484         dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
485         dev->isoc_ctl.buf = NULL;
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 /* ------------------------------------------------------------------
564         Videobuf operations
565    ------------------------------------------------------------------*/
566
567 static int
568 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
569 {
570         struct em28xx_fh *fh = vq->priv_data;
571
572         *size = 16 * fh->dev->width * fh->dev->height >> 3;
573         if (0 == *count)
574                 *count = EM28XX_DEF_BUF;
575
576         if (*count < EM28XX_MIN_BUF)
577                 *count = EM28XX_MIN_BUF;
578
579         return 0;
580 }
581
582 static void free_buffer(struct videobuf_queue *vq, struct em28xx_buffer *buf)
583 {
584         if (in_interrupt())
585                 BUG();
586
587         videobuf_waiton(&buf->vb, 0, 0);
588         videobuf_vmalloc_free(&buf->vb);
589         buf->vb.state = VIDEOBUF_NEEDS_INIT;
590 }
591
592 static int
593 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
594                                                 enum v4l2_field field)
595 {
596         struct em28xx_fh     *fh  = vq->priv_data;
597         struct em28xx_buffer *buf = container_of(vb, struct em28xx_buffer, vb);
598         struct em28xx        *dev = fh->dev;
599         struct em28xx_dmaqueue *vidq = &dev->vidq;
600         int                  rc = 0, urb_init = 0;
601
602         /* BUG_ON(NULL == fh->fmt); */
603
604         /* FIXME: It assumes depth = 16 */
605         /* The only currently supported format is 16 bits/pixel */
606         buf->vb.size = 16 * dev->width * dev->height >> 3;
607
608         if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
609                 return -EINVAL;
610
611         buf->fmt       = fh->fmt;
612         buf->vb.width  = dev->width;
613         buf->vb.height = dev->height;
614         buf->vb.field  = field;
615
616         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
617                 rc = videobuf_iolock(vq, &buf->vb, NULL);
618                 if (rc < 0)
619                         goto fail;
620         }
621
622         if (!dev->isoc_ctl.num_bufs)
623                 urb_init = 1;
624
625         if (urb_init) {
626                 rc = em28xx_prepare_isoc(dev, EM28XX_NUM_PACKETS,
627                                          EM28XX_NUM_BUFS);
628                 if (rc < 0)
629                         goto fail;
630
631                 rc = em28xx_start_thread(vidq);
632                 if (rc < 0)
633                         goto fail;
634         }
635
636         buf->vb.state = VIDEOBUF_PREPARED;
637         return 0;
638
639 fail:
640         free_buffer(vq, buf);
641         return rc;
642 }
643
644 static void
645 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
646 {
647         struct em28xx_buffer    *buf     = container_of(vb, struct em28xx_buffer, vb);
648         struct em28xx_fh        *fh      = vq->priv_data;
649         struct em28xx           *dev     = fh->dev;
650         struct em28xx_dmaqueue  *vidq    = &dev->vidq;
651
652         buf->vb.state = VIDEOBUF_QUEUED;
653         list_add_tail(&buf->vb.queue, &vidq->active);
654
655 }
656
657 static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
658 {
659         struct em28xx_buffer   *buf  = container_of(vb, struct em28xx_buffer, vb);
660         struct em28xx_fh       *fh   = vq->priv_data;
661         struct em28xx          *dev  = (struct em28xx *)fh->dev;
662
663         em28xx_isocdbg("em28xx: called buffer_release\n");
664
665         free_buffer(vq, buf);
666 }
667
668 static struct videobuf_queue_ops em28xx_video_qops = {
669         .buf_setup      = buffer_setup,
670         .buf_prepare    = buffer_prepare,
671         .buf_queue      = buffer_queue,
672         .buf_release    = buffer_release,
673 };
674
675 /*********************  v4l2 interface  ******************************************/
676
677 /*
678  * em28xx_config()
679  * inits registers with sane defaults
680  */
681 static int em28xx_config(struct em28xx *dev)
682 {
683
684         /* Sets I2C speed to 100 KHz */
685         if (!dev->is_em2800)
686                 em28xx_write_regs_req(dev, 0x00, 0x06, "\x40", 1);
687
688         /* enable vbi capturing */
689
690 /*      em28xx_write_regs_req(dev,0x00,0x0e,"\xC0",1); audio register */
691 /*      em28xx_write_regs_req(dev,0x00,0x0f,"\x80",1); clk register */
692         em28xx_write_regs_req(dev,0x00,0x11,"\x51",1);
693
694         dev->mute = 1;          /* maybe not the right place... */
695         dev->volume = 0x1f;
696
697         em28xx_outfmt_set_yuv422(dev);
698         em28xx_colorlevels_set_default(dev);
699         em28xx_compression_disable(dev);
700
701         return 0;
702 }
703
704 /*
705  * em28xx_config_i2c()
706  * configure i2c attached devices
707  */
708 static void em28xx_config_i2c(struct em28xx *dev)
709 {
710         struct v4l2_routing route;
711
712         route.input = INPUT(dev->ctl_input)->vmux;
713         route.output = 0;
714         em28xx_i2c_call_clients(dev, VIDIOC_INT_RESET, NULL);
715         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
716         em28xx_i2c_call_clients(dev, VIDIOC_STREAMON, NULL);
717 }
718
719 static void video_mux(struct em28xx *dev, int index)
720 {
721         struct v4l2_routing route;
722
723         route.input = INPUT(index)->vmux;
724         route.output = 0;
725         dev->ctl_input = index;
726         dev->ctl_ainput = INPUT(index)->amux;
727
728         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
729
730         if (dev->has_msp34xx) {
731                 if (dev->i2s_speed)
732                         em28xx_i2c_call_clients(dev, VIDIOC_INT_I2S_CLOCK_FREQ, &dev->i2s_speed);
733                 route.input = dev->ctl_ainput;
734                 route.output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
735                 /* Note: this is msp3400 specific */
736                 em28xx_i2c_call_clients(dev, VIDIOC_INT_S_AUDIO_ROUTING, &route);
737         }
738
739         em28xx_audio_analog_set(dev);
740 }
741
742 /* Usage lock check functions */
743 static int res_get(struct em28xx_fh *fh)
744 {
745         struct em28xx    *dev = fh->dev;
746         int              rc   = 0;
747
748         /* This instance already has stream_on */
749         if (fh->stream_on)
750                 return rc;
751
752         if (dev->stream_on)
753                 return -EINVAL;
754
755         mutex_lock(&dev->lock);
756         dev->stream_on = 1;
757         fh->stream_on  = 1;
758         mutex_unlock(&dev->lock);
759         return rc;
760 }
761
762 static int res_check(struct em28xx_fh *fh)
763 {
764         return (fh->stream_on);
765 }
766
767 static void res_free(struct em28xx_fh *fh)
768 {
769         struct em28xx    *dev = fh->dev;
770
771         mutex_lock(&dev->lock);
772         fh->stream_on = 0;
773         dev->stream_on = 0;
774         mutex_unlock(&dev->lock);
775 }
776
777 /*
778  * em28xx_get_ctrl()
779  * return the current saturation, brightness or contrast, mute state
780  */
781 static int em28xx_get_ctrl(struct em28xx *dev, struct v4l2_control *ctrl)
782 {
783         switch (ctrl->id) {
784         case V4L2_CID_AUDIO_MUTE:
785                 ctrl->value = dev->mute;
786                 return 0;
787         case V4L2_CID_AUDIO_VOLUME:
788                 ctrl->value = dev->volume;
789                 return 0;
790         default:
791                 return -EINVAL;
792         }
793 }
794
795 /*
796  * em28xx_set_ctrl()
797  * mute or set new saturation, brightness or contrast
798  */
799 static int em28xx_set_ctrl(struct em28xx *dev, const struct v4l2_control *ctrl)
800 {
801         switch (ctrl->id) {
802         case V4L2_CID_AUDIO_MUTE:
803                 if (ctrl->value != dev->mute) {
804                         dev->mute = ctrl->value;
805                         return em28xx_audio_analog_set(dev);
806                 }
807                 return 0;
808         case V4L2_CID_AUDIO_VOLUME:
809                 dev->volume = ctrl->value;
810                 return em28xx_audio_analog_set(dev);
811         default:
812                 return -EINVAL;
813         }
814 }
815
816 static int check_dev(struct em28xx *dev)
817 {
818         if (dev->state & DEV_DISCONNECTED) {
819                 em28xx_errdev("v4l2 ioctl: device not present\n");
820                 return -ENODEV;
821         }
822
823         if (dev->state & DEV_MISCONFIGURED) {
824                 em28xx_errdev("v4l2 ioctl: device is misconfigured; "
825                               "close and open it again\n");
826                 return -EIO;
827         }
828         return 0;
829 }
830
831 static void get_scale(struct em28xx *dev,
832                         unsigned int width, unsigned int height,
833                         unsigned int *hscale, unsigned int *vscale)
834 {
835         unsigned int          maxw   = norm_maxw(dev);
836         unsigned int          maxh   = norm_maxh(dev);
837
838         *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
839         if (*hscale >= 0x4000)
840                 *hscale = 0x3fff;
841
842         *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
843         if (*vscale >= 0x4000)
844                 *vscale = 0x3fff;
845 }
846
847 /* ------------------------------------------------------------------
848         IOCTL vidioc handling
849    ------------------------------------------------------------------*/
850
851 static int vidioc_g_fmt_cap(struct file *file, void *priv,
852                                         struct v4l2_format *f)
853 {
854         struct em28xx_fh      *fh  = priv;
855         struct em28xx         *dev = fh->dev;
856
857         mutex_lock(&dev->lock);
858
859         f->fmt.pix.width = dev->width;
860         f->fmt.pix.height = dev->height;
861         f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
862         f->fmt.pix.bytesperline = dev->bytesperline;
863         f->fmt.pix.sizeimage = dev->frame_size;
864         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
865
866         /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
867         f->fmt.pix.field = dev->interlaced ?
868                            V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
869
870         mutex_unlock(&dev->lock);
871         return 0;
872 }
873
874 static int vidioc_try_fmt_cap(struct file *file, void *priv,
875                         struct v4l2_format *f)
876 {
877         struct em28xx_fh      *fh    = priv;
878         struct em28xx         *dev   = fh->dev;
879         int                   width  = f->fmt.pix.width;
880         int                   height = f->fmt.pix.height;
881         unsigned int          maxw   = norm_maxw(dev);
882         unsigned int          maxh   = norm_maxh(dev);
883         unsigned int          hscale, vscale;
884
885         /* width must even because of the YUYV format
886            height must be even because of interlacing */
887         height &= 0xfffe;
888         width &= 0xfffe;
889
890         if (height < 32)
891                 height = 32;
892         if (height > maxh)
893                 height = maxh;
894         if (width < 48)
895                 width = 48;
896         if (width > maxw)
897                 width = maxw;
898
899         mutex_lock(&dev->lock);
900
901         if (dev->is_em2800) {
902                 /* the em2800 can only scale down to 50% */
903                 if (height % (maxh / 2))
904                         height = maxh;
905                 if (width % (maxw / 2))
906                         width = maxw;
907                 /* according to empiatech support */
908                 /* the MaxPacketSize is to small to support */
909                 /* framesizes larger than 640x480 @ 30 fps */
910                 /* or 640x576 @ 25 fps. As this would cut */
911                 /* of a part of the image we prefer */
912                 /* 360x576 or 360x480 for now */
913                 if (width == maxw && height == maxh)
914                         width /= 2;
915         }
916
917         get_scale(dev, width, height, &hscale, &vscale);
918
919         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
920         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
921
922         f->fmt.pix.width = width;
923         f->fmt.pix.height = height;
924         f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
925         f->fmt.pix.bytesperline = width * 2;
926         f->fmt.pix.sizeimage = width * 2 * height;
927         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
928         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
929
930         mutex_unlock(&dev->lock);
931         return 0;
932 }
933
934 static int vidioc_s_fmt_cap(struct file *file, void *priv,
935                         struct v4l2_format *f)
936 {
937         struct em28xx_fh      *fh  = priv;
938         struct em28xx         *dev = fh->dev;
939         int                   rc;
940
941         rc = check_dev(dev);
942         if (rc < 0)
943                 return rc;
944
945         vidioc_try_fmt_cap(file, priv, f);
946
947         mutex_lock(&dev->lock);
948
949         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
950                 em28xx_errdev("%s queue busy\n", __func__);
951                 rc = -EBUSY;
952                 goto out;
953         }
954
955         if (dev->stream_on && !fh->stream_on) {
956                 em28xx_errdev("%s device in use by another fh\n", __func__);
957                 rc = -EBUSY;
958                 goto out;
959         }
960
961         /* set new image size */
962         dev->width = f->fmt.pix.width;
963         dev->height = f->fmt.pix.height;
964         dev->frame_size = dev->width * dev->height * 2;
965         dev->field_size = dev->frame_size >> 1;
966         dev->bytesperline = dev->width * 2;
967         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
968
969         em28xx_set_alternate(dev);
970         em28xx_resolution_set(dev);
971
972         rc = 0;
973
974 out:
975         mutex_unlock(&dev->lock);
976         return rc;
977 }
978
979 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm)
980 {
981         struct em28xx_fh   *fh  = priv;
982         struct em28xx      *dev = fh->dev;
983         struct v4l2_format f;
984         int                rc;
985
986         rc = check_dev(dev);
987         if (rc < 0)
988                 return rc;
989
990         mutex_lock(&dev->lock);
991         dev->norm = *norm;
992         mutex_unlock(&dev->lock);
993
994         /* Adjusts width/height, if needed */
995         f.fmt.pix.width = dev->width;
996         f.fmt.pix.height = dev->height;
997         vidioc_try_fmt_cap(file, priv, &f);
998
999         mutex_lock(&dev->lock);
1000
1001         /* set new image size */
1002         dev->width = f.fmt.pix.width;
1003         dev->height = f.fmt.pix.height;
1004         dev->frame_size = dev->width * dev->height * 2;
1005         dev->field_size = dev->frame_size >> 1;
1006         dev->bytesperline = dev->width * 2;
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->frame_size = dev->width * dev->height * 2;
1722                 dev->field_size = dev->frame_size >> 1; /*both_fileds ? dev->frame_size>>1 : dev->frame_size; */
1723                 dev->bytesperline = dev->width * 2;
1724                 dev->hscale = 0;
1725                 dev->vscale = 0;
1726
1727                 em28xx_set_alternate(dev);
1728                 em28xx_resolution_set(dev);
1729
1730         }
1731         if (fh->radio) {
1732                 em28xx_videodbg("video_open: setting radio device\n");
1733                 em28xx_i2c_call_clients(dev, AUDC_SET_RADIO, NULL);
1734         }
1735
1736         dev->users++;
1737
1738         videobuf_queue_vmalloc_init(&fh->vb_vidq, &em28xx_video_qops,
1739                         NULL, &dev->slock, fh->type, V4L2_FIELD_INTERLACED,
1740                         sizeof(struct em28xx_buffer), fh);
1741
1742         mutex_unlock(&dev->lock);
1743         return errCode;
1744 }
1745
1746 /*
1747  * em28xx_realease_resources()
1748  * unregisters the v4l2,i2c and usb devices
1749  * called when the device gets disconected or at module unload
1750 */
1751 static void em28xx_release_resources(struct em28xx *dev)
1752 {
1753
1754         /*FIXME: I2C IR should be disconnected */
1755
1756         em28xx_info("V4L2 devices /dev/video%d and /dev/vbi%d deregistered\n",
1757                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
1758                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
1759         list_del(&dev->devlist);
1760         if (dev->radio_dev) {
1761                 if (-1 != dev->radio_dev->minor)
1762                         video_unregister_device(dev->radio_dev);
1763                 else
1764                         video_device_release(dev->radio_dev);
1765                 dev->radio_dev = NULL;
1766         }
1767         if (dev->vbi_dev) {
1768                 if (-1 != dev->vbi_dev->minor)
1769                         video_unregister_device(dev->vbi_dev);
1770                 else
1771                         video_device_release(dev->vbi_dev);
1772                 dev->vbi_dev = NULL;
1773         }
1774         if (dev->vdev) {
1775                 if (-1 != dev->vdev->minor)
1776                         video_unregister_device(dev->vdev);
1777                 else
1778                         video_device_release(dev->vdev);
1779                 dev->vdev = NULL;
1780         }
1781         em28xx_i2c_unregister(dev);
1782         usb_put_dev(dev->udev);
1783
1784         /* Mark device as unused */
1785         em28xx_devused&=~(1<<dev->devno);
1786 }
1787
1788 /*
1789  * em28xx_v4l2_close()
1790  * stops streaming and deallocates all resources allocated by the v4l2 calls and ioctls
1791  */
1792 static int em28xx_v4l2_close(struct inode *inode, struct file *filp)
1793 {
1794         struct em28xx_fh *fh  = filp->private_data;
1795         struct em28xx    *dev = fh->dev;
1796         int              errCode;
1797
1798         em28xx_videodbg("users=%d\n", dev->users);
1799
1800
1801         if (res_check(fh))
1802                 res_free(fh);
1803
1804         mutex_lock(&dev->lock);
1805
1806         if (dev->users == 1) {
1807                 videobuf_stop(&fh->vb_vidq);
1808                 videobuf_mmap_free(&fh->vb_vidq);
1809
1810                 /* the device is already disconnect,
1811                    free the remaining resources */
1812                 if (dev->state & DEV_DISCONNECTED) {
1813                         em28xx_release_resources(dev);
1814                         mutex_unlock(&dev->lock);
1815                         kfree(dev);
1816                         return 0;
1817                 }
1818
1819                 /* do this before setting alternate! */
1820                 em28xx_uninit_isoc(dev);
1821
1822                 /* set alternate 0 */
1823                 dev->alt = 0;
1824                 em28xx_videodbg("setting alternate 0\n");
1825                 errCode = usb_set_interface(dev->udev, 0, 0);
1826                 if (errCode < 0) {
1827                         em28xx_errdev("cannot change alternate number to "
1828                                         "0 (error=%i)\n", errCode);
1829                 }
1830         }
1831         kfree(fh);
1832         dev->users--;
1833         wake_up_interruptible_nr(&dev->open, 1);
1834         mutex_unlock(&dev->lock);
1835         return 0;
1836 }
1837
1838 /*
1839  * em28xx_v4l2_read()
1840  * will allocate buffers when called for the first time
1841  */
1842 static ssize_t
1843 em28xx_v4l2_read(struct file *filp, char __user * buf, size_t count,
1844                  loff_t *pos)
1845 {
1846         struct em28xx_fh *fh = filp->private_data;
1847         struct em28xx *dev = fh->dev;
1848         int rc;
1849
1850         rc = check_dev(dev);
1851         if (rc < 0)
1852                 return rc;
1853
1854         /* FIXME: read() is not prepared to allow changing the video
1855            resolution while streaming. Seems a bug at em28xx_set_fmt
1856          */
1857
1858         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1859                 if (unlikely(res_get(fh)))
1860                         return -EBUSY;
1861
1862                 return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1863                                         filp->f_flags & O_NONBLOCK);
1864         }
1865         return 0;
1866 }
1867
1868 /*
1869  * em28xx_v4l2_poll()
1870  * will allocate buffers when called for the first time
1871  */
1872 static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table * wait)
1873 {
1874         struct em28xx_fh *fh = filp->private_data;
1875         struct em28xx *dev = fh->dev;
1876         int rc;
1877
1878         rc = check_dev(dev);
1879         if (rc < 0)
1880                 return rc;
1881
1882         if (unlikely(res_get(fh) < 0))
1883                 return POLLERR;
1884
1885         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1886                 return POLLERR;
1887
1888         return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
1889 }
1890
1891 /*
1892  * em28xx_v4l2_mmap()
1893  */
1894 static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
1895 {
1896         struct em28xx_fh *fh    = filp->private_data;
1897         struct em28xx    *dev   = fh->dev;
1898         int              rc;
1899
1900         if (unlikely(res_get(fh) < 0))
1901                 return -EBUSY;
1902
1903         rc = check_dev(dev);
1904         if (rc < 0)
1905                 return rc;
1906
1907         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1908
1909         em28xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
1910                 (unsigned long)vma->vm_start,
1911                 (unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1912                 rc);
1913
1914         return rc;
1915 }
1916
1917 static const struct file_operations em28xx_v4l_fops = {
1918         .owner         = THIS_MODULE,
1919         .open          = em28xx_v4l2_open,
1920         .release       = em28xx_v4l2_close,
1921         .read          = em28xx_v4l2_read,
1922         .poll          = em28xx_v4l2_poll,
1923         .mmap          = em28xx_v4l2_mmap,
1924         .ioctl         = video_ioctl2,
1925         .llseek        = no_llseek,
1926         .compat_ioctl  = v4l_compat_ioctl32,
1927 };
1928
1929 static const struct file_operations radio_fops = {
1930         .owner         = THIS_MODULE,
1931         .open          = em28xx_v4l2_open,
1932         .release       = em28xx_v4l2_close,
1933         .ioctl         = video_ioctl2,
1934         .compat_ioctl  = v4l_compat_ioctl32,
1935         .llseek        = no_llseek,
1936 };
1937
1938 static const struct video_device em28xx_video_template = {
1939         .fops                       = &em28xx_v4l_fops,
1940         .release                    = video_device_release,
1941
1942         .minor                      = -1,
1943         .vidioc_querycap            = vidioc_querycap,
1944         .vidioc_enum_fmt_cap        = vidioc_enum_fmt_cap,
1945         .vidioc_g_fmt_cap           = vidioc_g_fmt_cap,
1946         .vidioc_try_fmt_cap         = vidioc_try_fmt_cap,
1947         .vidioc_s_fmt_cap           = vidioc_s_fmt_cap,
1948         .vidioc_g_audio             = vidioc_g_audio,
1949         .vidioc_s_audio             = vidioc_s_audio,
1950         .vidioc_cropcap             = vidioc_cropcap,
1951
1952         .vidioc_g_fmt_vbi_capture   = vidioc_g_fmt_vbi_capture,
1953         .vidioc_try_fmt_vbi_capture = vidioc_try_set_vbi_capture,
1954         .vidioc_s_fmt_vbi_capture   = vidioc_try_set_vbi_capture,
1955
1956         .vidioc_reqbufs             = vidioc_reqbufs,
1957         .vidioc_querybuf            = vidioc_querybuf,
1958         .vidioc_qbuf                = vidioc_qbuf,
1959         .vidioc_dqbuf               = vidioc_dqbuf,
1960         .vidioc_s_std               = vidioc_s_std,
1961         .vidioc_enum_input          = vidioc_enum_input,
1962         .vidioc_g_input             = vidioc_g_input,
1963         .vidioc_s_input             = vidioc_s_input,
1964         .vidioc_queryctrl           = vidioc_queryctrl,
1965         .vidioc_g_ctrl              = vidioc_g_ctrl,
1966         .vidioc_s_ctrl              = vidioc_s_ctrl,
1967         .vidioc_streamon            = vidioc_streamon,
1968         .vidioc_streamoff           = vidioc_streamoff,
1969         .vidioc_g_tuner             = vidioc_g_tuner,
1970         .vidioc_s_tuner             = vidioc_s_tuner,
1971         .vidioc_g_frequency         = vidioc_g_frequency,
1972         .vidioc_s_frequency         = vidioc_s_frequency,
1973 #ifdef CONFIG_VIDEO_ADV_DEBUG
1974         .vidioc_g_register          = vidioc_g_register,
1975         .vidioc_s_register          = vidioc_s_register,
1976 #endif
1977 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1978         .vidiocgmbuf                = vidiocgmbuf,
1979 #endif
1980
1981         .tvnorms                    = V4L2_STD_ALL,
1982         .current_norm               = V4L2_STD_PAL,
1983 };
1984
1985 static struct video_device em28xx_radio_template = {
1986         .name                 = "em28xx-radio",
1987         .type                 = VID_TYPE_TUNER,
1988         .fops                 = &radio_fops,
1989         .minor                = -1,
1990         .vidioc_querycap      = radio_querycap,
1991         .vidioc_g_tuner       = radio_g_tuner,
1992         .vidioc_enum_input    = radio_enum_input,
1993         .vidioc_g_audio       = radio_g_audio,
1994         .vidioc_s_tuner       = radio_s_tuner,
1995         .vidioc_s_audio       = radio_s_audio,
1996         .vidioc_s_input       = radio_s_input,
1997         .vidioc_queryctrl     = radio_queryctrl,
1998         .vidioc_g_ctrl        = vidioc_g_ctrl,
1999         .vidioc_s_ctrl        = vidioc_s_ctrl,
2000         .vidioc_g_frequency   = vidioc_g_frequency,
2001         .vidioc_s_frequency   = vidioc_s_frequency,
2002 #ifdef CONFIG_VIDEO_ADV_DEBUG
2003         .vidioc_g_register    = vidioc_g_register,
2004         .vidioc_s_register    = vidioc_s_register,
2005 #endif
2006 };
2007
2008 /******************************** usb interface *****************************************/
2009
2010
2011 static LIST_HEAD(em28xx_extension_devlist);
2012 static DEFINE_MUTEX(em28xx_extension_devlist_lock);
2013
2014 int em28xx_register_extension(struct em28xx_ops *ops)
2015 {
2016         struct em28xx *h, *dev = NULL;
2017
2018         list_for_each_entry(h, &em28xx_devlist, devlist)
2019                 dev = h;
2020
2021         mutex_lock(&em28xx_extension_devlist_lock);
2022         list_add_tail(&ops->next, &em28xx_extension_devlist);
2023         if (dev)
2024                 ops->init(dev);
2025
2026         printk(KERN_INFO "Em28xx: Initialized (%s) extension\n", ops->name);
2027         mutex_unlock(&em28xx_extension_devlist_lock);
2028
2029         return 0;
2030 }
2031 EXPORT_SYMBOL(em28xx_register_extension);
2032
2033 void em28xx_unregister_extension(struct em28xx_ops *ops)
2034 {
2035         struct em28xx *h, *dev = NULL;
2036
2037         list_for_each_entry(h, &em28xx_devlist, devlist)
2038                 dev = h;
2039
2040         if (dev)
2041                 ops->fini(dev);
2042
2043         mutex_lock(&em28xx_extension_devlist_lock);
2044         printk(KERN_INFO "Em28xx: Removed (%s) extension\n", ops->name);
2045         list_del(&ops->next);
2046         mutex_unlock(&em28xx_extension_devlist_lock);
2047 }
2048 EXPORT_SYMBOL(em28xx_unregister_extension);
2049
2050 static struct video_device *em28xx_vdev_init(struct em28xx *dev,
2051                                              const struct video_device *template,
2052                                              const int type,
2053                                              const char *type_name)
2054 {
2055         struct video_device *vfd;
2056
2057         vfd = video_device_alloc();
2058         if (NULL == vfd)
2059                 return NULL;
2060         *vfd = *template;
2061         vfd->minor   = -1;
2062         vfd->dev = &dev->udev->dev;
2063         vfd->release = video_device_release;
2064         vfd->type = type;
2065         vfd->debug = video_debug;
2066
2067         snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2068                  dev->name, type_name);
2069
2070         return vfd;
2071 }
2072
2073
2074 /*
2075  * em28xx_init_dev()
2076  * allocates and inits the device structs, registers i2c bus and v4l device
2077  */
2078 static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
2079                            int minor)
2080 {
2081         struct em28xx_ops *ops = NULL;
2082         struct em28xx *dev = *devhandle;
2083         int retval = -ENOMEM;
2084         int errCode;
2085         unsigned int maxh, maxw;
2086
2087         dev->udev = udev;
2088         mutex_init(&dev->lock);
2089         spin_lock_init(&dev->slock);
2090         init_waitqueue_head(&dev->open);
2091         init_waitqueue_head(&dev->wait_frame);
2092         init_waitqueue_head(&dev->wait_stream);
2093
2094         dev->em28xx_write_regs = em28xx_write_regs;
2095         dev->em28xx_read_reg = em28xx_read_reg;
2096         dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
2097         dev->em28xx_write_regs_req = em28xx_write_regs_req;
2098         dev->em28xx_read_reg_req = em28xx_read_reg_req;
2099         dev->is_em2800 = em28xx_boards[dev->model].is_em2800;
2100
2101         errCode = em28xx_read_reg(dev, CHIPID_REG);
2102         if (errCode >= 0)
2103                 em28xx_info("em28xx chip ID = %d\n", errCode);
2104
2105         em28xx_pre_card_setup(dev);
2106
2107         errCode = em28xx_config(dev);
2108         if (errCode) {
2109                 em28xx_errdev("error configuring device\n");
2110                 em28xx_devused &= ~(1<<dev->devno);
2111                 kfree(dev);
2112                 return -ENOMEM;
2113         }
2114
2115         /* register i2c bus */
2116         em28xx_i2c_register(dev);
2117
2118         /* Do board specific init and eeprom reading */
2119         em28xx_card_setup(dev);
2120
2121         /* Configure audio */
2122         em28xx_audio_analog_set(dev);
2123
2124         /* configure the device */
2125         em28xx_config_i2c(dev);
2126
2127         /* set default norm */
2128         dev->norm = em28xx_video_template.current_norm;
2129
2130         maxw = norm_maxw(dev);
2131         maxh = norm_maxh(dev);
2132
2133         /* set default image size */
2134         dev->width = maxw;
2135         dev->height = maxh;
2136         dev->interlaced = EM28XX_INTERLACED_DEFAULT;
2137         dev->field_size = dev->width * dev->height;
2138         dev->frame_size =
2139             dev->interlaced ? dev->field_size << 1 : dev->field_size;
2140         dev->bytesperline = dev->width * 2;
2141         dev->hscale = 0;
2142         dev->vscale = 0;
2143         dev->ctl_input = 2;
2144
2145         errCode = em28xx_config(dev);
2146
2147         list_add_tail(&dev->devlist, &em28xx_devlist);
2148
2149         /* allocate and fill video video_device struct */
2150         dev->vdev = em28xx_vdev_init(dev, &em28xx_video_template,
2151                                           VID_TYPE_CAPTURE, "video");
2152         if (NULL == dev->vdev) {
2153                 em28xx_errdev("cannot allocate video_device.\n");
2154                 goto fail_unreg;
2155         }
2156         if (dev->tuner_type != TUNER_ABSENT)
2157                 dev->vdev->type |= VID_TYPE_TUNER;
2158
2159         /* register v4l2 video video_device */
2160         retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2161                                        video_nr[dev->devno]);
2162         if (retval) {
2163                 em28xx_errdev("unable to register video device (error=%i).\n",
2164                               retval);
2165                 goto fail_unreg;
2166         }
2167
2168         /* Allocate and fill vbi video_device struct */
2169         dev->vbi_dev = em28xx_vdev_init(dev, &em28xx_video_template,
2170                                           VFL_TYPE_VBI, "vbi");
2171         /* register v4l2 vbi video_device */
2172         if (video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2173                                         vbi_nr[dev->devno]) < 0) {
2174                 em28xx_errdev("unable to register vbi device\n");
2175                 retval = -ENODEV;
2176                 goto fail_unreg;
2177         }
2178
2179         if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2180                 dev->radio_dev = em28xx_vdev_init(dev, &em28xx_radio_template,
2181                                         VFL_TYPE_RADIO, "radio");
2182                 if (NULL == dev->radio_dev) {
2183                         em28xx_errdev("cannot allocate video_device.\n");
2184                         goto fail_unreg;
2185                 }
2186                 retval = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2187                                             radio_nr[dev->devno]);
2188                 if (retval < 0) {
2189                         em28xx_errdev("can't register radio device\n");
2190                         goto fail_unreg;
2191                 }
2192                 em28xx_info("Registered radio device as /dev/radio%d\n",
2193                             dev->radio_dev->minor & 0x1f);
2194         }
2195
2196         /* init video dma queues */
2197         INIT_LIST_HEAD(&dev->vidq.active);
2198         INIT_LIST_HEAD(&dev->vidq.queued);
2199
2200
2201         if (dev->has_msp34xx) {
2202                 /* Send a reset to other chips via gpio */
2203                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xf7", 1);
2204                 msleep(3);
2205                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xff", 1);
2206                 msleep(3);
2207         }
2208
2209         video_mux(dev, 0);
2210
2211         em28xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
2212                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
2213                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
2214
2215         mutex_lock(&em28xx_extension_devlist_lock);
2216         if (!list_empty(&em28xx_extension_devlist)) {
2217                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2218                         if (ops->id)
2219                                 ops->init(dev);
2220                 }
2221         }
2222         mutex_unlock(&em28xx_extension_devlist_lock);
2223
2224         return 0;
2225
2226 fail_unreg:
2227         em28xx_release_resources(dev);
2228         mutex_unlock(&dev->lock);
2229         kfree(dev);
2230         return retval;
2231 }
2232
2233 #if defined(CONFIG_MODULES) && defined(MODULE)
2234 static void request_module_async(struct work_struct *work)
2235 {
2236         struct em28xx *dev = container_of(work,
2237                              struct em28xx, request_module_wk);
2238
2239         if (dev->has_audio_class)
2240                 request_module("snd-usb-audio");
2241         else
2242                 request_module("em28xx-alsa");
2243 }
2244
2245 static void request_modules(struct em28xx *dev)
2246 {
2247         INIT_WORK(&dev->request_module_wk, request_module_async);
2248         schedule_work(&dev->request_module_wk);
2249 }
2250 #else
2251 #define request_modules(dev)
2252 #endif /* CONFIG_MODULES */
2253
2254 /*
2255  * em28xx_usb_probe()
2256  * checks for supported devices
2257  */
2258 static int em28xx_usb_probe(struct usb_interface *interface,
2259                             const struct usb_device_id *id)
2260 {
2261         const struct usb_endpoint_descriptor *endpoint;
2262         struct usb_device *udev;
2263         struct usb_interface *uif;
2264         struct em28xx *dev = NULL;
2265         int retval = -ENODEV;
2266         int i, nr, ifnum;
2267
2268         udev = usb_get_dev(interface_to_usbdev(interface));
2269         ifnum = interface->altsetting[0].desc.bInterfaceNumber;
2270
2271         /* Check to see next free device and mark as used */
2272         nr=find_first_zero_bit(&em28xx_devused,EM28XX_MAXBOARDS);
2273         em28xx_devused|=1<<nr;
2274
2275         /* Don't register audio interfaces */
2276         if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2277                 em28xx_err(DRIVER_NAME " audio device (%04x:%04x): interface %i, class %i\n",
2278                                 udev->descriptor.idVendor,udev->descriptor.idProduct,
2279                                 ifnum,
2280                                 interface->altsetting[0].desc.bInterfaceClass);
2281
2282                 em28xx_devused&=~(1<<nr);
2283                 return -ENODEV;
2284         }
2285
2286         em28xx_err(DRIVER_NAME " new video device (%04x:%04x): interface %i, class %i\n",
2287                         udev->descriptor.idVendor,udev->descriptor.idProduct,
2288                         ifnum,
2289                         interface->altsetting[0].desc.bInterfaceClass);
2290
2291         endpoint = &interface->cur_altsetting->endpoint[1].desc;
2292
2293         /* check if the device has the iso in endpoint at the correct place */
2294         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2295             USB_ENDPOINT_XFER_ISOC) {
2296                 em28xx_err(DRIVER_NAME " probing error: endpoint is non-ISO endpoint!\n");
2297                 em28xx_devused&=~(1<<nr);
2298                 return -ENODEV;
2299         }
2300         if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
2301                 em28xx_err(DRIVER_NAME " probing error: endpoint is ISO OUT endpoint!\n");
2302                 em28xx_devused&=~(1<<nr);
2303                 return -ENODEV;
2304         }
2305
2306         if (nr >= EM28XX_MAXBOARDS) {
2307                 printk (DRIVER_NAME ": Supports only %i em28xx boards.\n",EM28XX_MAXBOARDS);
2308                 em28xx_devused&=~(1<<nr);
2309                 return -ENOMEM;
2310         }
2311
2312         /* allocate memory for our device state and initialize it */
2313         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2314         if (dev == NULL) {
2315                 em28xx_err(DRIVER_NAME ": out of memory!\n");
2316                 em28xx_devused&=~(1<<nr);
2317                 return -ENOMEM;
2318         }
2319
2320         snprintf(dev->name, 29, "em28xx #%d", nr);
2321         dev->devno = nr;
2322         dev->model = id->driver_info;
2323         dev->alt   = -1;
2324
2325         /* Checks if audio is provided by some interface */
2326         for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
2327                 uif = udev->config->interface[i];
2328                 if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2329                         dev->has_audio_class = 1;
2330                         break;
2331                 }
2332         }
2333
2334         printk(KERN_INFO DRIVER_NAME " %s usb audio class\n",
2335                    dev->has_audio_class ? "Has" : "Doesn't have");
2336
2337         /* compute alternate max packet sizes */
2338         uif = udev->actconfig->interface[0];
2339
2340         dev->num_alt=uif->num_altsetting;
2341         em28xx_info("Alternate settings: %i\n",dev->num_alt);
2342 //      dev->alt_max_pkt_size = kmalloc(sizeof(*dev->alt_max_pkt_size)*
2343         dev->alt_max_pkt_size = kmalloc(32*
2344                                                 dev->num_alt,GFP_KERNEL);
2345         if (dev->alt_max_pkt_size == NULL) {
2346                 em28xx_errdev("out of memory!\n");
2347                 em28xx_devused&=~(1<<nr);
2348                 kfree(dev);
2349                 return -ENOMEM;
2350         }
2351
2352         for (i = 0; i < dev->num_alt ; i++) {
2353                 u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.
2354                                                         wMaxPacketSize);
2355                 dev->alt_max_pkt_size[i] =
2356                     (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
2357                 em28xx_info("Alternate setting %i, max size= %i\n",i,
2358                                                         dev->alt_max_pkt_size[i]);
2359         }
2360
2361         if ((card[nr]>=0)&&(card[nr]<em28xx_bcount))
2362                 dev->model = card[nr];
2363
2364         /* allocate device struct */
2365         retval = em28xx_init_dev(&dev, udev, nr);
2366         if (retval)
2367                 return retval;
2368
2369         em28xx_info("Found %s\n", em28xx_boards[dev->model].name);
2370
2371         /* save our data pointer in this interface device */
2372         usb_set_intfdata(interface, dev);
2373
2374         request_modules(dev);
2375
2376         return 0;
2377 }
2378
2379 /*
2380  * em28xx_usb_disconnect()
2381  * called when the device gets diconencted
2382  * video device will be unregistered on v4l2_close in case it is still open
2383  */
2384 static void em28xx_usb_disconnect(struct usb_interface *interface)
2385 {
2386         struct em28xx *dev;
2387         struct em28xx_ops *ops = NULL;
2388
2389         dev = usb_get_intfdata(interface);
2390         usb_set_intfdata(interface, NULL);
2391
2392         if (!dev)
2393                 return;
2394
2395         em28xx_info("disconnecting %s\n", dev->vdev->name);
2396
2397         /* wait until all current v4l2 io is finished then deallocate resources */
2398         mutex_lock(&dev->lock);
2399
2400         wake_up_interruptible_all(&dev->open);
2401
2402         if (dev->users) {
2403                 em28xx_warn
2404                     ("device /dev/video%d is open! Deregistration and memory "
2405                      "deallocation are deferred on close.\n",
2406                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN);
2407
2408                 dev->state |= DEV_MISCONFIGURED;
2409                 em28xx_uninit_isoc(dev);
2410                 dev->state |= DEV_DISCONNECTED;
2411                 wake_up_interruptible(&dev->wait_frame);
2412                 wake_up_interruptible(&dev->wait_stream);
2413         } else {
2414                 dev->state |= DEV_DISCONNECTED;
2415                 em28xx_release_resources(dev);
2416         }
2417         mutex_unlock(&dev->lock);
2418
2419         mutex_lock(&em28xx_extension_devlist_lock);
2420         if (!list_empty(&em28xx_extension_devlist)) {
2421                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2422                         ops->fini(dev);
2423                 }
2424         }
2425         mutex_unlock(&em28xx_extension_devlist_lock);
2426
2427         if (!dev->users) {
2428                 kfree(dev->alt_max_pkt_size);
2429                 kfree(dev);
2430         }
2431 }
2432
2433 static struct usb_driver em28xx_usb_driver = {
2434         .name = "em28xx",
2435         .probe = em28xx_usb_probe,
2436         .disconnect = em28xx_usb_disconnect,
2437         .id_table = em28xx_id_table,
2438 };
2439
2440 static int __init em28xx_module_init(void)
2441 {
2442         int result;
2443
2444         printk(KERN_INFO DRIVER_NAME " v4l2 driver version %d.%d.%d loaded\n",
2445                (EM28XX_VERSION_CODE >> 16) & 0xff,
2446                (EM28XX_VERSION_CODE >> 8) & 0xff, EM28XX_VERSION_CODE & 0xff);
2447 #ifdef SNAPSHOT
2448         printk(KERN_INFO DRIVER_NAME " snapshot date %04d-%02d-%02d\n",
2449                SNAPSHOT / 10000, (SNAPSHOT / 100) % 100, SNAPSHOT % 100);
2450 #endif
2451
2452         /* register this driver with the USB subsystem */
2453         result = usb_register(&em28xx_usb_driver);
2454         if (result)
2455                 em28xx_err(DRIVER_NAME
2456                            " usb_register failed. Error number %d.\n", result);
2457
2458         return result;
2459 }
2460
2461 static void __exit em28xx_module_exit(void)
2462 {
2463         /* deregister this driver with the USB subsystem */
2464         usb_deregister(&em28xx_usb_driver);
2465 }
2466
2467 module_init(em28xx_module_init);
2468 module_exit(em28xx_module_exit);