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