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