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