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