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