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