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