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