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