]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/video/em28xx/em28xx-video.c
V4L/DVB (6536): Add a hint for boards without unique USB ID
[karo-tx-linux.git] / drivers / media / video / em28xx / em28xx-video.c
1 /*
2    em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB video capture devices
3
4    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
5                       Markus Rechberger <mrechberger@gmail.com>
6                       Mauro Carvalho Chehab <mchehab@infradead.org>
7                       Sascha Sommer <saschasommer@freenet.de>
8
9         Some parts based on SN9C10x PC Camera Controllers GPL driver made
10                 by Luca Risolia <luca.risolia@studio.unibo.it>
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 2 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include <linux/init.h>
28 #include <linux/list.h>
29 #include <linux/module.h>
30 #include <linux/kernel.h>
31 #include <linux/bitmap.h>
32 #include <linux/usb.h>
33 #include <linux/i2c.h>
34 #include <linux/version.h>
35 #include <linux/mm.h>
36 #include <linux/video_decoder.h>
37 #include <linux/mutex.h>
38
39 #include "em28xx.h"
40 #include <media/v4l2-common.h>
41 #include <media/msp3400.h>
42
43 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
44                       "Markus Rechberger <mrechberger@gmail.com>, " \
45                       "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
46                       "Sascha Sommer <saschasommer@freenet.de>"
47
48 #define DRIVER_NAME         "em28xx"
49 #define DRIVER_DESC         "Empia em28xx based USB video device driver"
50 #define EM28XX_VERSION_CODE  KERNEL_VERSION(0, 0, 1)
51
52 #define em28xx_videodbg(fmt, arg...) do {\
53         if (video_debug) \
54                 printk(KERN_INFO "%s %s :"fmt, \
55                          dev->name, __FUNCTION__ , ##arg); } while (0)
56
57 MODULE_AUTHOR(DRIVER_AUTHOR);
58 MODULE_DESCRIPTION(DRIVER_DESC);
59 MODULE_LICENSE("GPL");
60
61 static LIST_HEAD(em28xx_devlist);
62
63 static unsigned int card[]     = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
64 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
65 static unsigned int vbi_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
66 module_param_array(card,  int, NULL, 0444);
67 module_param_array(video_nr, int, NULL, 0444);
68 module_param_array(vbi_nr, int, NULL, 0444);
69 MODULE_PARM_DESC(card,"card type");
70 MODULE_PARM_DESC(video_nr,"video device numbers");
71 MODULE_PARM_DESC(vbi_nr,"vbi device numbers");
72
73 static unsigned int video_debug = 0;
74 module_param(video_debug,int,0644);
75 MODULE_PARM_DESC(video_debug,"enable debug messages [video]");
76
77 /* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
78 static unsigned long em28xx_devused;
79
80 /* supported tv norms */
81 static struct em28xx_tvnorm tvnorms[] = {
82         {
83                 .name = "PAL",
84                 .id = V4L2_STD_PAL,
85                 .mode = VIDEO_MODE_PAL,
86          }, {
87                 .name = "NTSC",
88                 .id = V4L2_STD_NTSC,
89                 .mode = VIDEO_MODE_NTSC,
90         }, {
91                  .name = "SECAM",
92                  .id = V4L2_STD_SECAM,
93                  .mode = VIDEO_MODE_SECAM,
94         }, {
95                 .name = "PAL-M",
96                 .id = V4L2_STD_PAL_M,
97                 .mode = VIDEO_MODE_PAL,
98         }
99 };
100
101 #define TVNORMS ARRAY_SIZE(tvnorms)
102
103 /* supported controls */
104 /* Common to all boards */
105 static struct v4l2_queryctrl em28xx_qctrl[] = {
106         {
107                 .id = V4L2_CID_AUDIO_VOLUME,
108                 .type = V4L2_CTRL_TYPE_INTEGER,
109                 .name = "Volume",
110                 .minimum = 0x0,
111                 .maximum = 0x1f,
112                 .step = 0x1,
113                 .default_value = 0x1f,
114                 .flags = 0,
115         },{
116                 .id = V4L2_CID_AUDIO_MUTE,
117                 .type = V4L2_CTRL_TYPE_BOOLEAN,
118                 .name = "Mute",
119                 .minimum = 0,
120                 .maximum = 1,
121                 .step = 1,
122                 .default_value = 1,
123                 .flags = 0,
124         }
125 };
126
127 static struct usb_driver em28xx_usb_driver;
128
129 static DEFINE_MUTEX(em28xx_sysfs_lock);
130 static DECLARE_RWSEM(em28xx_disconnect);
131
132 /*********************  v4l2 interface  ******************************************/
133
134 /*
135  * em28xx_config()
136  * inits registers with sane defaults
137  */
138 static int em28xx_config(struct em28xx *dev)
139 {
140
141         /* Sets I2C speed to 100 KHz */
142         if (!dev->is_em2800)
143                 em28xx_write_regs_req(dev, 0x00, 0x06, "\x40", 1);
144
145         /* enable vbi capturing */
146
147 /*      em28xx_write_regs_req(dev,0x00,0x0e,"\xC0",1); audio register */
148 /*      em28xx_write_regs_req(dev,0x00,0x0f,"\x80",1); clk register */
149         em28xx_write_regs_req(dev,0x00,0x11,"\x51",1);
150
151         em28xx_audio_usb_mute(dev, 1);
152         dev->mute = 1;          /* maybe not the right place... */
153         dev->volume = 0x1f;
154         em28xx_audio_analog_set(dev);
155         em28xx_audio_analog_setup(dev);
156         em28xx_outfmt_set_yuv422(dev);
157         em28xx_colorlevels_set_default(dev);
158         em28xx_compression_disable(dev);
159
160         return 0;
161 }
162
163 /*
164  * em28xx_config_i2c()
165  * configure i2c attached devices
166  */
167 static void em28xx_config_i2c(struct em28xx *dev)
168 {
169         struct v4l2_routing route;
170
171         route.input = INPUT(dev->ctl_input)->vmux;
172         route.output = 0;
173         em28xx_i2c_call_clients(dev, VIDIOC_INT_RESET, NULL);
174         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
175         em28xx_i2c_call_clients(dev, VIDIOC_STREAMON, NULL);
176 }
177
178 /*
179  * em28xx_empty_framequeues()
180  * prepare queues for incoming and outgoing frames
181  */
182 static void em28xx_empty_framequeues(struct em28xx *dev)
183 {
184         u32 i;
185
186         INIT_LIST_HEAD(&dev->inqueue);
187         INIT_LIST_HEAD(&dev->outqueue);
188
189         for (i = 0; i < EM28XX_NUM_FRAMES; i++) {
190                 dev->frame[i].state = F_UNUSED;
191                 dev->frame[i].buf.bytesused = 0;
192         }
193 }
194
195 static void video_mux(struct em28xx *dev, int index)
196 {
197         int ainput;
198         struct v4l2_routing route;
199
200         route.input = INPUT(index)->vmux;
201         route.output = 0;
202         dev->ctl_input = index;
203         dev->ctl_ainput = INPUT(index)->amux;
204
205         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
206
207         em28xx_videodbg("Setting input index=%d, vmux=%d, amux=%d\n",index,route.input,dev->ctl_ainput);
208
209         if (dev->has_msp34xx) {
210                 if (dev->i2s_speed)
211                         em28xx_i2c_call_clients(dev, VIDIOC_INT_I2S_CLOCK_FREQ, &dev->i2s_speed);
212                 route.input = dev->ctl_ainput;
213                 route.output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
214                 /* Note: this is msp3400 specific */
215                 em28xx_i2c_call_clients(dev, VIDIOC_INT_S_AUDIO_ROUTING, &route);
216                 ainput = EM28XX_AUDIO_SRC_TUNER;
217                 em28xx_audio_source(dev, ainput);
218         } else {
219                 switch (dev->ctl_ainput) {
220                         case 0:
221                                 ainput = EM28XX_AUDIO_SRC_TUNER;
222                                 break;
223                         default:
224                                 ainput = EM28XX_AUDIO_SRC_LINE;
225                 }
226                 em28xx_audio_source(dev, ainput);
227         }
228 }
229
230 /*
231  * em28xx_v4l2_open()
232  * inits the device and starts isoc transfer
233  */
234 static int em28xx_v4l2_open(struct inode *inode, struct file *filp)
235 {
236         int minor = iminor(inode);
237         int errCode = 0;
238         struct em28xx *h,*dev = NULL;
239
240         list_for_each_entry(h, &em28xx_devlist, devlist) {
241                 if (h->vdev->minor == minor) {
242                         dev  = h;
243                         dev->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
244                 }
245                 if (h->vbi_dev->minor == minor) {
246                         dev  = h;
247                         dev->type = V4L2_BUF_TYPE_VBI_CAPTURE;
248                 }
249         }
250         if (NULL == dev)
251                 return -ENODEV;
252
253         em28xx_videodbg("open minor=%d type=%s users=%d\n",
254                                 minor,v4l2_type_names[dev->type],dev->users);
255
256         if (!down_read_trylock(&em28xx_disconnect))
257                 return -ERESTARTSYS;
258
259         if (dev->users) {
260                 em28xx_warn("this driver can be opened only once\n");
261                 up_read(&em28xx_disconnect);
262                 return -EBUSY;
263         }
264
265         mutex_init(&dev->fileop_lock);  /* to 1 == available */
266         spin_lock_init(&dev->queue_lock);
267         init_waitqueue_head(&dev->wait_frame);
268         init_waitqueue_head(&dev->wait_stream);
269
270         mutex_lock(&dev->lock);
271
272         if (dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
273                 em28xx_set_alternate(dev);
274
275                 dev->width = norm_maxw(dev);
276                 dev->height = norm_maxh(dev);
277                 dev->frame_size = dev->width * dev->height * 2;
278                 dev->field_size = dev->frame_size >> 1; /*both_fileds ? dev->frame_size>>1 : dev->frame_size; */
279                 dev->bytesperline = dev->width * 2;
280                 dev->hscale = 0;
281                 dev->vscale = 0;
282
283                 em28xx_capture_start(dev, 1);
284                 em28xx_resolution_set(dev);
285
286                 /* device needs to be initialized before isoc transfer */
287                 video_mux(dev, 0);
288
289                 /* start the transfer */
290                 errCode = em28xx_init_isoc(dev);
291                 if (errCode)
292                         goto err;
293
294         }
295
296         dev->users++;
297         filp->private_data = dev;
298         dev->io = IO_NONE;
299         dev->stream = STREAM_OFF;
300         dev->num_frames = 0;
301
302         /* prepare queues */
303         em28xx_empty_framequeues(dev);
304
305         dev->state |= DEV_INITIALIZED;
306
307 err:
308         mutex_unlock(&dev->lock);
309         up_read(&em28xx_disconnect);
310         return errCode;
311 }
312
313 /*
314  * em28xx_realease_resources()
315  * unregisters the v4l2,i2c and usb devices
316  * called when the device gets disconected or at module unload
317 */
318 static void em28xx_release_resources(struct em28xx *dev)
319 {
320         mutex_lock(&em28xx_sysfs_lock);
321
322         /*FIXME: I2C IR should be disconnected */
323
324         em28xx_info("V4L2 devices /dev/video%d and /dev/vbi%d deregistered\n",
325                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
326                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
327         list_del(&dev->devlist);
328         video_unregister_device(dev->vdev);
329         video_unregister_device(dev->vbi_dev);
330         em28xx_i2c_unregister(dev);
331         usb_put_dev(dev->udev);
332         mutex_unlock(&em28xx_sysfs_lock);
333
334
335         /* Mark device as unused */
336         em28xx_devused&=~(1<<dev->devno);
337 }
338
339 /*
340  * em28xx_v4l2_close()
341  * stops streaming and deallocates all resources allocated by the v4l2 calls and ioctls
342  */
343 static int em28xx_v4l2_close(struct inode *inode, struct file *filp)
344 {
345         int errCode;
346         struct em28xx *dev=filp->private_data;
347
348         em28xx_videodbg("users=%d\n", dev->users);
349
350         mutex_lock(&dev->lock);
351
352         em28xx_uninit_isoc(dev);
353
354         em28xx_release_buffers(dev);
355
356         /* the device is already disconnect, free the remaining resources */
357         if (dev->state & DEV_DISCONNECTED) {
358                 em28xx_release_resources(dev);
359                 mutex_unlock(&dev->lock);
360                 kfree(dev);
361                 return 0;
362         }
363
364         /* set alternate 0 */
365         dev->alt = 0;
366         em28xx_videodbg("setting alternate 0\n");
367         errCode = usb_set_interface(dev->udev, 0, 0);
368         if (errCode < 0) {
369                 em28xx_errdev ("cannot change alternate number to 0 (error=%i)\n",
370                      errCode);
371         }
372
373         dev->users--;
374         wake_up_interruptible_nr(&dev->open, 1);
375         mutex_unlock(&dev->lock);
376         return 0;
377 }
378
379 /*
380  * em28xx_v4l2_read()
381  * will allocate buffers when called for the first time
382  */
383 static ssize_t
384 em28xx_v4l2_read(struct file *filp, char __user * buf, size_t count,
385                  loff_t * f_pos)
386 {
387         struct em28xx_frame_t *f, *i;
388         unsigned long lock_flags;
389         int ret = 0;
390         struct em28xx *dev = filp->private_data;
391
392         if (dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
393                 em28xx_videodbg("V4l2_Buf_type_videocapture is set\n");
394         }
395         if (dev->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
396                 em28xx_videodbg("V4L2_BUF_TYPE_VBI_CAPTURE is set\n");
397                 em28xx_videodbg("not supported yet! ...\n");
398                 if (copy_to_user(buf, "", 1)) {
399                         mutex_unlock(&dev->fileop_lock);
400                         return -EFAULT;
401                 }
402                 return (1);
403         }
404         if (dev->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE) {
405                 em28xx_videodbg("V4L2_BUF_TYPE_SLICED_VBI_CAPTURE is set\n");
406                 em28xx_videodbg("not supported yet! ...\n");
407                 if (copy_to_user(buf, "", 1)) {
408                         mutex_unlock(&dev->fileop_lock);
409                         return -EFAULT;
410                 }
411                 return (1);
412         }
413
414         if (mutex_lock_interruptible(&dev->fileop_lock))
415                 return -ERESTARTSYS;
416
417         if (dev->state & DEV_DISCONNECTED) {
418                 em28xx_videodbg("device not present\n");
419                 mutex_unlock(&dev->fileop_lock);
420                 return -ENODEV;
421         }
422
423         if (dev->state & DEV_MISCONFIGURED) {
424                 em28xx_videodbg("device misconfigured; close and open it again\n");
425                 mutex_unlock(&dev->fileop_lock);
426                 return -EIO;
427         }
428
429         if (dev->io == IO_MMAP) {
430                 em28xx_videodbg ("IO method is set to mmap; close and open"
431                                 " the device again to choose the read method\n");
432                 mutex_unlock(&dev->fileop_lock);
433                 return -EINVAL;
434         }
435
436         if (dev->io == IO_NONE) {
437                 if (!em28xx_request_buffers(dev, EM28XX_NUM_READ_FRAMES)) {
438                         em28xx_errdev("read failed, not enough memory\n");
439                         mutex_unlock(&dev->fileop_lock);
440                         return -ENOMEM;
441                 }
442                 dev->io = IO_READ;
443                 dev->stream = STREAM_ON;
444                 em28xx_queue_unusedframes(dev);
445         }
446
447         if (!count) {
448                 mutex_unlock(&dev->fileop_lock);
449                 return 0;
450         }
451
452         if (list_empty(&dev->outqueue)) {
453                 if (filp->f_flags & O_NONBLOCK) {
454                         mutex_unlock(&dev->fileop_lock);
455                         return -EAGAIN;
456                 }
457                 ret = wait_event_interruptible
458                     (dev->wait_frame,
459                      (!list_empty(&dev->outqueue)) ||
460                      (dev->state & DEV_DISCONNECTED));
461                 if (ret) {
462                         mutex_unlock(&dev->fileop_lock);
463                         return ret;
464                 }
465                 if (dev->state & DEV_DISCONNECTED) {
466                         mutex_unlock(&dev->fileop_lock);
467                         return -ENODEV;
468                 }
469         }
470
471         f = list_entry(dev->outqueue.prev, struct em28xx_frame_t, frame);
472
473         spin_lock_irqsave(&dev->queue_lock, lock_flags);
474         list_for_each_entry(i, &dev->outqueue, frame)
475             i->state = F_UNUSED;
476         INIT_LIST_HEAD(&dev->outqueue);
477         spin_unlock_irqrestore(&dev->queue_lock, lock_flags);
478
479         em28xx_queue_unusedframes(dev);
480
481         if (count > f->buf.length)
482                 count = f->buf.length;
483
484         if (copy_to_user(buf, f->bufmem, count)) {
485                 mutex_unlock(&dev->fileop_lock);
486                 return -EFAULT;
487         }
488         *f_pos += count;
489
490         mutex_unlock(&dev->fileop_lock);
491
492         return count;
493 }
494
495 /*
496  * em28xx_v4l2_poll()
497  * will allocate buffers when called for the first time
498  */
499 static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table * wait)
500 {
501         unsigned int mask = 0;
502         struct em28xx *dev = filp->private_data;
503
504         if (mutex_lock_interruptible(&dev->fileop_lock))
505                 return POLLERR;
506
507         if (dev->state & DEV_DISCONNECTED) {
508                 em28xx_videodbg("device not present\n");
509         } else if (dev->state & DEV_MISCONFIGURED) {
510                 em28xx_videodbg("device is misconfigured; close and open it again\n");
511         } else {
512                 if (dev->io == IO_NONE) {
513                         if (!em28xx_request_buffers
514                             (dev, EM28XX_NUM_READ_FRAMES)) {
515                                 em28xx_warn
516                                     ("poll() failed, not enough memory\n");
517                         } else {
518                                 dev->io = IO_READ;
519                                 dev->stream = STREAM_ON;
520                         }
521                 }
522
523                 if (dev->io == IO_READ) {
524                         em28xx_queue_unusedframes(dev);
525                         poll_wait(filp, &dev->wait_frame, wait);
526
527                         if (!list_empty(&dev->outqueue))
528                                 mask |= POLLIN | POLLRDNORM;
529
530                         mutex_unlock(&dev->fileop_lock);
531
532                         return mask;
533                 }
534         }
535
536         mutex_unlock(&dev->fileop_lock);
537         return POLLERR;
538 }
539
540 /*
541  * em28xx_vm_open()
542  */
543 static void em28xx_vm_open(struct vm_area_struct *vma)
544 {
545         struct em28xx_frame_t *f = vma->vm_private_data;
546         f->vma_use_count++;
547 }
548
549 /*
550  * em28xx_vm_close()
551  */
552 static void em28xx_vm_close(struct vm_area_struct *vma)
553 {
554         /* NOTE: buffers are not freed here */
555         struct em28xx_frame_t *f = vma->vm_private_data;
556
557         if (f->vma_use_count)
558                 f->vma_use_count--;
559 }
560
561 static struct vm_operations_struct em28xx_vm_ops = {
562         .open = em28xx_vm_open,
563         .close = em28xx_vm_close,
564 };
565
566 /*
567  * em28xx_v4l2_mmap()
568  */
569 static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
570 {
571         unsigned long size = vma->vm_end - vma->vm_start,
572             start = vma->vm_start;
573         void *pos;
574         u32 i;
575
576         struct em28xx *dev = filp->private_data;
577
578         if (mutex_lock_interruptible(&dev->fileop_lock))
579                 return -ERESTARTSYS;
580
581         if (dev->state & DEV_DISCONNECTED) {
582                 em28xx_videodbg("mmap: device not present\n");
583                 mutex_unlock(&dev->fileop_lock);
584                 return -ENODEV;
585         }
586
587         if (dev->state & DEV_MISCONFIGURED) {
588                 em28xx_videodbg ("mmap: Device is misconfigured; close and "
589                                                 "open it again\n");
590                 mutex_unlock(&dev->fileop_lock);
591                 return -EIO;
592         }
593
594         if (dev->io != IO_MMAP || !(vma->vm_flags & VM_WRITE) ||
595             size != PAGE_ALIGN(dev->frame[0].buf.length)) {
596                 mutex_unlock(&dev->fileop_lock);
597                 return -EINVAL;
598         }
599
600         for (i = 0; i < dev->num_frames; i++) {
601                 if ((dev->frame[i].buf.m.offset >> PAGE_SHIFT) == vma->vm_pgoff)
602                         break;
603         }
604         if (i == dev->num_frames) {
605                 em28xx_videodbg("mmap: user supplied mapping address is out of range\n");
606                 mutex_unlock(&dev->fileop_lock);
607                 return -EINVAL;
608         }
609
610         /* VM_IO is eventually going to replace PageReserved altogether */
611         vma->vm_flags |= VM_IO;
612         vma->vm_flags |= VM_RESERVED;   /* avoid to swap out this VMA */
613
614         pos = dev->frame[i].bufmem;
615         while (size > 0) {      /* size is page-aligned */
616                 if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
617                         em28xx_videodbg("mmap: vm_insert_page failed\n");
618                         mutex_unlock(&dev->fileop_lock);
619                         return -EAGAIN;
620                 }
621                 start += PAGE_SIZE;
622                 pos += PAGE_SIZE;
623                 size -= PAGE_SIZE;
624         }
625
626         vma->vm_ops = &em28xx_vm_ops;
627         vma->vm_private_data = &dev->frame[i];
628
629         em28xx_vm_open(vma);
630         mutex_unlock(&dev->fileop_lock);
631         return 0;
632 }
633
634 /*
635  * em28xx_get_ctrl()
636  * return the current saturation, brightness or contrast, mute state
637  */
638 static int em28xx_get_ctrl(struct em28xx *dev, struct v4l2_control *ctrl)
639 {
640         switch (ctrl->id) {
641         case V4L2_CID_AUDIO_MUTE:
642                 ctrl->value = dev->mute;
643                 return 0;
644         case V4L2_CID_AUDIO_VOLUME:
645                 ctrl->value = dev->volume;
646                 return 0;
647         default:
648                 return -EINVAL;
649         }
650 }
651
652 /*
653  * em28xx_set_ctrl()
654  * mute or set new saturation, brightness or contrast
655  */
656 static int em28xx_set_ctrl(struct em28xx *dev, const struct v4l2_control *ctrl)
657 {
658         switch (ctrl->id) {
659         case V4L2_CID_AUDIO_MUTE:
660                 if (ctrl->value != dev->mute) {
661                         dev->mute = ctrl->value;
662                         em28xx_audio_usb_mute(dev, ctrl->value);
663                         return em28xx_audio_analog_set(dev);
664                 }
665                 return 0;
666         case V4L2_CID_AUDIO_VOLUME:
667                 dev->volume = ctrl->value;
668                 return em28xx_audio_analog_set(dev);
669         default:
670                 return -EINVAL;
671         }
672 }
673
674 /*
675  * em28xx_stream_interrupt()
676  * stops streaming
677  */
678 static int em28xx_stream_interrupt(struct em28xx *dev)
679 {
680         int ret = 0;
681
682         /* stop reading from the device */
683
684         dev->stream = STREAM_INTERRUPT;
685         ret = wait_event_timeout(dev->wait_stream,
686                                  (dev->stream == STREAM_OFF) ||
687                                  (dev->state & DEV_DISCONNECTED),
688                                  EM28XX_URB_TIMEOUT);
689         if (dev->state & DEV_DISCONNECTED)
690                 return -ENODEV;
691         else if (ret) {
692                 dev->state |= DEV_MISCONFIGURED;
693                 em28xx_videodbg("device is misconfigured; close and "
694                         "open /dev/video%d again\n",
695                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN);
696                 return ret;
697         }
698
699         return 0;
700 }
701
702 static int em28xx_set_norm(struct em28xx *dev, int width, int height)
703 {
704         unsigned int hscale, vscale;
705         unsigned int maxh, maxw;
706
707         maxw = norm_maxw(dev);
708         maxh = norm_maxh(dev);
709
710         /* width must even because of the YUYV format */
711         /* height must be even because of interlacing */
712         height &= 0xfffe;
713         width &= 0xfffe;
714
715         if (height < 32)
716                 height = 32;
717         if (height > maxh)
718                 height = maxh;
719         if (width < 48)
720                 width = 48;
721         if (width > maxw)
722                 width = maxw;
723
724         if ((hscale = (((unsigned long)maxw) << 12) / width - 4096L) >= 0x4000)
725                 hscale = 0x3fff;
726         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
727
728         if ((vscale = (((unsigned long)maxh) << 12) / height - 4096L) >= 0x4000)
729                 vscale = 0x3fff;
730         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
731
732         /* set new image size */
733         dev->width = width;
734         dev->height = height;
735         dev->frame_size = dev->width * dev->height * 2;
736         dev->field_size = dev->frame_size >> 1; /*both_fileds ? dev->frame_size>>1 : dev->frame_size; */
737         dev->bytesperline = dev->width * 2;
738         dev->hscale = hscale;
739         dev->vscale = vscale;
740
741         em28xx_resolution_set(dev);
742
743         return 0;
744 }
745
746 static int em28xx_get_fmt(struct em28xx *dev, struct v4l2_format *format)
747 {
748         em28xx_videodbg("VIDIOC_G_FMT: type=%s\n",
749                 (format->type ==V4L2_BUF_TYPE_VIDEO_CAPTURE) ?
750                 "V4L2_BUF_TYPE_VIDEO_CAPTURE" :
751                 (format->type ==V4L2_BUF_TYPE_VBI_CAPTURE) ?
752                 "V4L2_BUF_TYPE_VBI_CAPTURE" :
753                 (format->type ==V4L2_CAP_SLICED_VBI_CAPTURE) ?
754                 "V4L2_BUF_TYPE_SLICED_VBI_CAPTURE " :
755                 "not supported");
756
757         switch (format->type) {
758         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
759         {
760                 format->fmt.pix.width = dev->width;
761                 format->fmt.pix.height = dev->height;
762                 format->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
763                 format->fmt.pix.bytesperline = dev->bytesperline;
764                 format->fmt.pix.sizeimage = dev->frame_size;
765                 format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
766                 format->fmt.pix.field = dev->interlaced ? V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;       /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
767
768                 em28xx_videodbg("VIDIOC_G_FMT: %dx%d\n", dev->width,
769                         dev->height);
770                 break;
771         }
772
773         case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
774         {
775                 format->fmt.sliced.service_set=0;
776
777                 em28xx_i2c_call_clients(dev,VIDIOC_G_FMT,format);
778
779                 if (format->fmt.sliced.service_set==0)
780                         return -EINVAL;
781
782                 break;
783         }
784
785         default:
786                 return -EINVAL;
787         }
788         return (0);
789 }
790
791 static int em28xx_set_fmt(struct em28xx *dev, unsigned int cmd, struct v4l2_format *format)
792 {
793         u32 i;
794         int ret = 0;
795         int width = format->fmt.pix.width;
796         int height = format->fmt.pix.height;
797         unsigned int hscale, vscale;
798         unsigned int maxh, maxw;
799
800         maxw = norm_maxw(dev);
801         maxh = norm_maxh(dev);
802
803         em28xx_videodbg("%s: type=%s\n",
804                         cmd == VIDIOC_TRY_FMT ?
805                         "VIDIOC_TRY_FMT" : "VIDIOC_S_FMT",
806                         format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ?
807                         "V4L2_BUF_TYPE_VIDEO_CAPTURE" :
808                         format->type == V4L2_BUF_TYPE_VBI_CAPTURE ?
809                         "V4L2_BUF_TYPE_VBI_CAPTURE " :
810                         "not supported");
811
812         if (format->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE) {
813                 em28xx_i2c_call_clients(dev,VIDIOC_G_FMT,format);
814
815                 if (format->fmt.sliced.service_set==0)
816                         return -EINVAL;
817
818                 return 0;
819         }
820
821
822         if (format->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
823                 return -EINVAL;
824
825         em28xx_videodbg("%s: requested %dx%d\n",
826                 cmd == VIDIOC_TRY_FMT ?
827                 "VIDIOC_TRY_FMT" : "VIDIOC_S_FMT",
828                 format->fmt.pix.width, format->fmt.pix.height);
829
830         /* FIXME: Move some code away from here */
831         /* width must even because of the YUYV format */
832         /* height must be even because of interlacing */
833         height &= 0xfffe;
834         width &= 0xfffe;
835
836         if (height < 32)
837                 height = 32;
838         if (height > maxh)
839                 height = maxh;
840         if (width < 48)
841                 width = 48;
842         if (width > maxw)
843                 width = maxw;
844
845         if(dev->is_em2800){
846                 /* the em2800 can only scale down to 50% */
847                 if(height % (maxh / 2))
848                         height=maxh;
849                 if(width % (maxw / 2))
850                         width=maxw;
851                 /* according to empiatech support */
852                 /* the MaxPacketSize is to small to support */
853                 /* framesizes larger than 640x480 @ 30 fps */
854                 /* or 640x576 @ 25 fps. As this would cut */
855                 /* of a part of the image we prefer */
856                 /* 360x576 or 360x480 for now */
857                 if(width == maxw && height == maxh)
858                         width /= 2;
859         }
860
861         if ((hscale = (((unsigned long)maxw) << 12) / width - 4096L) >= 0x4000)
862                 hscale = 0x3fff;
863
864         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
865
866         if ((vscale = (((unsigned long)maxh) << 12) / height - 4096L) >= 0x4000)
867                 vscale = 0x3fff;
868
869         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
870
871         format->fmt.pix.width = width;
872         format->fmt.pix.height = height;
873         format->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
874         format->fmt.pix.bytesperline = width * 2;
875         format->fmt.pix.sizeimage = width * 2 * height;
876         format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
877         format->fmt.pix.field = V4L2_FIELD_INTERLACED;
878
879         em28xx_videodbg("%s: returned %dx%d (%d, %d)\n",
880                 cmd == VIDIOC_TRY_FMT ?
881                 "VIDIOC_TRY_FMT" :"VIDIOC_S_FMT",
882                 format->fmt.pix.width, format->fmt.pix.height, hscale, vscale);
883
884         if (cmd == VIDIOC_TRY_FMT)
885                 return 0;
886
887         for (i = 0; i < dev->num_frames; i++)
888                 if (dev->frame[i].vma_use_count) {
889                         em28xx_videodbg("VIDIOC_S_FMT failed. "
890                                 "Unmap the buffers first.\n");
891                         return -EINVAL;
892                 }
893
894         /* stop io in case it is already in progress */
895         if (dev->stream == STREAM_ON) {
896                 em28xx_videodbg("VIDIOC_SET_FMT: interrupting stream\n");
897                 if ((ret = em28xx_stream_interrupt(dev)))
898                         return ret;
899         }
900
901         em28xx_release_buffers(dev);
902         dev->io = IO_NONE;
903
904         /* set new image size */
905         dev->width = width;
906         dev->height = height;
907         dev->frame_size = dev->width * dev->height * 2;
908         dev->field_size = dev->frame_size >> 1;
909         dev->bytesperline = dev->width * 2;
910         dev->hscale = hscale;
911         dev->vscale = vscale;
912         em28xx_uninit_isoc(dev);
913         em28xx_set_alternate(dev);
914         em28xx_capture_start(dev, 1);
915         em28xx_resolution_set(dev);
916         em28xx_init_isoc(dev);
917
918         return 0;
919 }
920
921 /*
922  * em28xx_v4l2_do_ioctl()
923  * This function is _not_ called directly, but from
924  * em28xx_v4l2_ioctl. Userspace
925  * copying is done already, arg is a kernel pointer.
926  */
927 static int em28xx_do_ioctl(struct inode *inode, struct file *filp,
928                            struct em28xx *dev, unsigned int cmd, void *arg,
929                            v4l2_kioctl driver_ioctl)
930 {
931         int ret;
932
933         switch (cmd) {
934                 /* ---------- tv norms ---------- */
935         case VIDIOC_ENUMSTD:
936         {
937                 struct v4l2_standard *e = arg;
938                 unsigned int i;
939
940                 i = e->index;
941                 if (i >= TVNORMS)
942                         return -EINVAL;
943                 ret = v4l2_video_std_construct(e, tvnorms[e->index].id,
944                                                 tvnorms[e->index].name);
945                 e->index = i;
946                 if (ret < 0)
947                         return ret;
948                 return 0;
949         }
950         case VIDIOC_G_STD:
951         {
952                 v4l2_std_id *id = arg;
953
954                 *id = dev->tvnorm->id;
955                 return 0;
956         }
957         case VIDIOC_S_STD:
958         {
959                 v4l2_std_id *id = arg;
960                 unsigned int i;
961
962                 for (i = 0; i < TVNORMS; i++)
963                         if (*id == tvnorms[i].id)
964                                 break;
965                 if (i == TVNORMS)
966                         for (i = 0; i < TVNORMS; i++)
967                                 if (*id & tvnorms[i].id)
968                                         break;
969                 if (i == TVNORMS)
970                         return -EINVAL;
971
972                 mutex_lock(&dev->lock);
973                 dev->tvnorm = &tvnorms[i];
974
975                 em28xx_set_norm(dev, dev->width, dev->height);
976
977                 em28xx_i2c_call_clients(dev, VIDIOC_S_STD,
978                                         &dev->tvnorm->id);
979
980                 mutex_unlock(&dev->lock);
981
982                 return 0;
983         }
984
985         /* ------ input switching ---------- */
986         case VIDIOC_ENUMINPUT:
987         {
988                 struct v4l2_input *i = arg;
989                 unsigned int n;
990                 static const char *iname[] = {
991                         [EM28XX_VMUX_COMPOSITE1] = "Composite1",
992                         [EM28XX_VMUX_COMPOSITE2] = "Composite2",
993                         [EM28XX_VMUX_COMPOSITE3] = "Composite3",
994                         [EM28XX_VMUX_COMPOSITE4] = "Composite4",
995                         [EM28XX_VMUX_SVIDEO] = "S-Video",
996                         [EM28XX_VMUX_TELEVISION] = "Television",
997                         [EM28XX_VMUX_CABLE] = "Cable TV",
998                         [EM28XX_VMUX_DVB] = "DVB",
999                         [EM28XX_VMUX_DEBUG] = "for debug only",
1000                 };
1001
1002                 n = i->index;
1003                 if (n >= MAX_EM28XX_INPUT)
1004                         return -EINVAL;
1005                 if (0 == INPUT(n)->type)
1006                         return -EINVAL;
1007                 memset(i, 0, sizeof(*i));
1008                 i->index = n;
1009                 i->type = V4L2_INPUT_TYPE_CAMERA;
1010                 strcpy(i->name, iname[INPUT(n)->type]);
1011                 if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type) ||
1012                         (EM28XX_VMUX_CABLE == INPUT(n)->type))
1013                         i->type = V4L2_INPUT_TYPE_TUNER;
1014                 for (n = 0; n < ARRAY_SIZE(tvnorms); n++)
1015                         i->std |= tvnorms[n].id;
1016                 return 0;
1017         }
1018         case VIDIOC_G_INPUT:
1019         {
1020                 int *i = arg;
1021                 *i = dev->ctl_input;
1022
1023                 return 0;
1024         }
1025         case VIDIOC_S_INPUT:
1026         {
1027                 int *index = arg;
1028
1029                 if (*index >= MAX_EM28XX_INPUT)
1030                         return -EINVAL;
1031                 if (0 == INPUT(*index)->type)
1032                         return -EINVAL;
1033
1034                 mutex_lock(&dev->lock);
1035                 video_mux(dev, *index);
1036                 mutex_unlock(&dev->lock);
1037
1038                 return 0;
1039         }
1040         case VIDIOC_G_AUDIO:
1041         {
1042                 struct v4l2_audio *a = arg;
1043                 unsigned int index = a->index;
1044
1045                 if (a->index > 1)
1046                         return -EINVAL;
1047                 memset(a, 0, sizeof(*a));
1048                 index = dev->ctl_ainput;
1049
1050                 if (index == 0) {
1051                         strcpy(a->name, "Television");
1052                 } else {
1053                         strcpy(a->name, "Line In");
1054                 }
1055                 a->capability = V4L2_AUDCAP_STEREO;
1056                 a->index = index;
1057                 return 0;
1058         }
1059         case VIDIOC_S_AUDIO:
1060         {
1061                 struct v4l2_audio *a = arg;
1062
1063                 if (a->index != dev->ctl_ainput)
1064                         return -EINVAL;
1065
1066                 return 0;
1067         }
1068
1069         /* --- controls ---------------------------------------------- */
1070         case VIDIOC_QUERYCTRL:
1071         {
1072                 struct v4l2_queryctrl *qc = arg;
1073                 int i, id=qc->id;
1074
1075                 memset(qc,0,sizeof(*qc));
1076                 qc->id=id;
1077
1078                 if (!dev->has_msp34xx) {
1079                         for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1080                                 if (qc->id && qc->id == em28xx_qctrl[i].id) {
1081                                         memcpy(qc, &(em28xx_qctrl[i]),
1082                                         sizeof(*qc));
1083                                         return 0;
1084                                 }
1085                         }
1086                 }
1087                 em28xx_i2c_call_clients(dev,cmd,qc);
1088                 if (qc->type)
1089                         return 0;
1090                 else
1091                         return -EINVAL;
1092         }
1093         case VIDIOC_G_CTRL:
1094         {
1095                 struct v4l2_control *ctrl = arg;
1096                 int retval=-EINVAL;
1097
1098                 if (!dev->has_msp34xx)
1099                         retval=em28xx_get_ctrl(dev, ctrl);
1100                 if (retval==-EINVAL) {
1101                         em28xx_i2c_call_clients(dev,cmd,arg);
1102                         return 0;
1103                 } else return retval;
1104         }
1105         case VIDIOC_S_CTRL:
1106         {
1107                 struct v4l2_control *ctrl = arg;
1108                 u8 i;
1109
1110                 if (!dev->has_msp34xx){
1111                         for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1112                                 if (ctrl->id == em28xx_qctrl[i].id) {
1113                                         if (ctrl->value <
1114                                         em28xx_qctrl[i].minimum
1115                                         || ctrl->value >
1116                                         em28xx_qctrl[i].maximum)
1117                                                 return -ERANGE;
1118                                         return em28xx_set_ctrl(dev, ctrl);
1119                                 }
1120                         }
1121                 }
1122
1123                 em28xx_i2c_call_clients(dev,cmd,arg);
1124                 return 0;
1125         }
1126         /* --- tuner ioctls ------------------------------------------ */
1127         case VIDIOC_G_TUNER:
1128         {
1129                 struct v4l2_tuner *t = arg;
1130
1131                 if (0 != t->index)
1132                         return -EINVAL;
1133
1134                 memset(t, 0, sizeof(*t));
1135                 strcpy(t->name, "Tuner");
1136                 mutex_lock(&dev->lock);
1137                 /* let clients fill in the remainder of this struct */
1138                 em28xx_i2c_call_clients(dev, cmd, t);
1139                 mutex_unlock(&dev->lock);
1140                 em28xx_videodbg("VIDIO_G_TUNER: signal=%x, afc=%x\n", t->signal,
1141                                 t->afc);
1142                 return 0;
1143         }
1144         case VIDIOC_S_TUNER:
1145         {
1146                 struct v4l2_tuner *t = arg;
1147
1148                 if (0 != t->index)
1149                         return -EINVAL;
1150                 mutex_lock(&dev->lock);
1151                 /* let clients handle this */
1152                 em28xx_i2c_call_clients(dev, cmd, t);
1153                 mutex_unlock(&dev->lock);
1154                 return 0;
1155         }
1156         case VIDIOC_G_FREQUENCY:
1157         {
1158                 struct v4l2_frequency *f = arg;
1159
1160                 memset(f, 0, sizeof(*f));
1161                 f->type = V4L2_TUNER_ANALOG_TV;
1162                 f->frequency = dev->ctl_freq;
1163
1164                 return 0;
1165         }
1166         case VIDIOC_S_FREQUENCY:
1167         {
1168                 struct v4l2_frequency *f = arg;
1169
1170                 if (0 != f->tuner)
1171                         return -EINVAL;
1172
1173                 if (V4L2_TUNER_ANALOG_TV != f->type)
1174                         return -EINVAL;
1175
1176                 mutex_lock(&dev->lock);
1177                 dev->ctl_freq = f->frequency;
1178                 em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, f);
1179                 mutex_unlock(&dev->lock);
1180                 return 0;
1181         }
1182         case VIDIOC_CROPCAP:
1183         {
1184                 struct v4l2_cropcap *cc = arg;
1185
1186                 if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1187                         return -EINVAL;
1188                 cc->bounds.left = 0;
1189                 cc->bounds.top = 0;
1190                 cc->bounds.width = dev->width;
1191                 cc->bounds.height = dev->height;
1192                 cc->defrect = cc->bounds;
1193                 cc->pixelaspect.numerator = 54; /* 4:3 FIXME: remove magic numbers */
1194                 cc->pixelaspect.denominator = 59;
1195                 return 0;
1196         }
1197         case VIDIOC_STREAMON:
1198         {
1199                 int *type = arg;
1200
1201                 if (*type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1202                         || dev->io != IO_MMAP)
1203                         return -EINVAL;
1204
1205                 if (list_empty(&dev->inqueue))
1206                         return -EINVAL;
1207
1208                 dev->stream = STREAM_ON;        /* FIXME: Start video capture here? */
1209
1210                 em28xx_videodbg("VIDIOC_STREAMON: starting stream\n");
1211
1212                 return 0;
1213         }
1214         case VIDIOC_STREAMOFF:
1215         {
1216                 int *type = arg;
1217                 int ret;
1218
1219                 if (*type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1220                         || dev->io != IO_MMAP)
1221                         return -EINVAL;
1222
1223                 if (dev->stream == STREAM_ON) {
1224                         em28xx_videodbg ("VIDIOC_STREAMOFF: interrupting stream\n");
1225                         if ((ret = em28xx_stream_interrupt(dev)))
1226                                 return ret;
1227                 }
1228                 em28xx_empty_framequeues(dev);
1229
1230                 return 0;
1231         }
1232         default:
1233                 return v4l_compat_translate_ioctl(inode, filp, cmd, arg,
1234                                                   driver_ioctl);
1235         }
1236         return 0;
1237 }
1238
1239 /*
1240  * em28xx_v4l2_do_ioctl()
1241  * This function is _not_ called directly, but from
1242  * em28xx_v4l2_ioctl. Userspace
1243  * copying is done already, arg is a kernel pointer.
1244  */
1245 static int em28xx_video_do_ioctl(struct inode *inode, struct file *filp,
1246                                  unsigned int cmd, void *arg)
1247 {
1248         struct em28xx *dev = filp->private_data;
1249
1250         if (!dev)
1251                 return -ENODEV;
1252
1253         if (video_debug > 1)
1254                 v4l_print_ioctl(dev->name,cmd);
1255
1256         switch (cmd) {
1257
1258                 /* --- capabilities ------------------------------------------ */
1259         case VIDIOC_QUERYCAP:
1260                 {
1261                 struct v4l2_capability *cap = arg;
1262
1263                 memset(cap, 0, sizeof(*cap));
1264                 strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1265                 strlcpy(cap->card, em28xx_boards[dev->model].name,
1266                         sizeof(cap->card));
1267                 strlcpy(cap->bus_info, dev->udev->dev.bus_id,
1268                         sizeof(cap->bus_info));
1269                 cap->version = EM28XX_VERSION_CODE;
1270                 cap->capabilities =
1271                                 V4L2_CAP_SLICED_VBI_CAPTURE |
1272                                 V4L2_CAP_VIDEO_CAPTURE |
1273                                 V4L2_CAP_AUDIO |
1274                                 V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1275                 if (dev->has_tuner)
1276                         cap->capabilities |= V4L2_CAP_TUNER;
1277                 return 0;
1278         }
1279         /* --- capture ioctls ---------------------------------------- */
1280         case VIDIOC_ENUM_FMT:
1281         {
1282                 struct v4l2_fmtdesc *fmtd = arg;
1283
1284                 if (fmtd->index != 0)
1285                         return -EINVAL;
1286                 memset(fmtd, 0, sizeof(*fmtd));
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                 return 0;
1292         }
1293         case VIDIOC_G_FMT:
1294                 return em28xx_get_fmt(dev, (struct v4l2_format *) arg);
1295
1296         case VIDIOC_TRY_FMT:
1297         case VIDIOC_S_FMT:
1298                 return em28xx_set_fmt(dev, cmd, (struct v4l2_format *)arg);
1299
1300         case VIDIOC_REQBUFS:
1301         {
1302                 struct v4l2_requestbuffers *rb = arg;
1303                 u32 i;
1304                 int ret;
1305
1306                 if (rb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1307                         rb->memory != V4L2_MEMORY_MMAP)
1308                         return -EINVAL;
1309
1310                 if (dev->io == IO_READ) {
1311                         em28xx_videodbg ("method is set to read;"
1312                                 " close and open the device again to"
1313                                 " choose the mmap I/O method\n");
1314                         return -EINVAL;
1315                 }
1316
1317                 for (i = 0; i < dev->num_frames; i++)
1318                         if (dev->frame[i].vma_use_count) {
1319                                 em28xx_videodbg ("VIDIOC_REQBUFS failed; previous buffers are still mapped\n");
1320                                 return -EINVAL;
1321                         }
1322
1323                 if (dev->stream == STREAM_ON) {
1324                         em28xx_videodbg("VIDIOC_REQBUFS: interrupting stream\n");
1325                         if ((ret = em28xx_stream_interrupt(dev)))
1326                                 return ret;
1327                 }
1328
1329                 em28xx_empty_framequeues(dev);
1330
1331                 em28xx_release_buffers(dev);
1332                 if (rb->count)
1333                         rb->count =
1334                                 em28xx_request_buffers(dev, rb->count);
1335
1336                 dev->frame_current = NULL;
1337
1338                 em28xx_videodbg ("VIDIOC_REQBUFS: setting io method to mmap: num bufs %i\n",
1339                                                 rb->count);
1340                 dev->io = rb->count ? IO_MMAP : IO_NONE;
1341                 return 0;
1342         }
1343         case VIDIOC_QUERYBUF:
1344         {
1345                 struct v4l2_buffer *b = arg;
1346
1347                 if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1348                         b->index >= dev->num_frames || dev->io != IO_MMAP)
1349                         return -EINVAL;
1350
1351                 memcpy(b, &dev->frame[b->index].buf, sizeof(*b));
1352
1353                 if (dev->frame[b->index].vma_use_count) {
1354                         b->flags |= V4L2_BUF_FLAG_MAPPED;
1355                 }
1356                 if (dev->frame[b->index].state == F_DONE)
1357                         b->flags |= V4L2_BUF_FLAG_DONE;
1358                 else if (dev->frame[b->index].state != F_UNUSED)
1359                         b->flags |= V4L2_BUF_FLAG_QUEUED;
1360                 return 0;
1361         }
1362         case VIDIOC_QBUF:
1363         {
1364                 struct v4l2_buffer *b = arg;
1365                 unsigned long lock_flags;
1366
1367                 if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1368                         b->index >= dev->num_frames || dev->io != IO_MMAP) {
1369                         return -EINVAL;
1370                 }
1371
1372                 if (dev->frame[b->index].state != F_UNUSED) {
1373                         return -EAGAIN;
1374                 }
1375                 dev->frame[b->index].state = F_QUEUED;
1376
1377                 /* add frame to fifo */
1378                 spin_lock_irqsave(&dev->queue_lock, lock_flags);
1379                 list_add_tail(&dev->frame[b->index].frame,
1380                                 &dev->inqueue);
1381                 spin_unlock_irqrestore(&dev->queue_lock, lock_flags);
1382
1383                 return 0;
1384         }
1385         case VIDIOC_DQBUF:
1386         {
1387                 struct v4l2_buffer *b = arg;
1388                 struct em28xx_frame_t *f;
1389                 unsigned long lock_flags;
1390                 int ret = 0;
1391
1392                 if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1393                         || dev->io != IO_MMAP)
1394                         return -EINVAL;
1395
1396                 if (list_empty(&dev->outqueue)) {
1397                         if (dev->stream == STREAM_OFF)
1398                                 return -EINVAL;
1399                         if (filp->f_flags & O_NONBLOCK)
1400                                 return -EAGAIN;
1401                         ret = wait_event_interruptible
1402                                 (dev->wait_frame,
1403                                 (!list_empty(&dev->outqueue)) ||
1404                                 (dev->state & DEV_DISCONNECTED));
1405                         if (ret)
1406                                 return ret;
1407                         if (dev->state & DEV_DISCONNECTED)
1408                                 return -ENODEV;
1409                 }
1410
1411                 spin_lock_irqsave(&dev->queue_lock, lock_flags);
1412                 f = list_entry(dev->outqueue.next,
1413                                 struct em28xx_frame_t, frame);
1414                 list_del(dev->outqueue.next);
1415                 spin_unlock_irqrestore(&dev->queue_lock, lock_flags);
1416
1417                 f->state = F_UNUSED;
1418                 memcpy(b, &f->buf, sizeof(*b));
1419
1420                 if (f->vma_use_count)
1421                         b->flags |= V4L2_BUF_FLAG_MAPPED;
1422
1423                 return 0;
1424         }
1425         default:
1426                 return em28xx_do_ioctl(inode, filp, dev, cmd, arg,
1427                                        em28xx_video_do_ioctl);
1428         }
1429         return 0;
1430 }
1431
1432 /*
1433  * em28xx_v4l2_ioctl()
1434  * handle v4l2 ioctl the main action happens in em28xx_v4l2_do_ioctl()
1435  */
1436 static int em28xx_v4l2_ioctl(struct inode *inode, struct file *filp,
1437                              unsigned int cmd, unsigned long arg)
1438 {
1439         int ret = 0;
1440         struct em28xx *dev = filp->private_data;
1441
1442         if (mutex_lock_interruptible(&dev->fileop_lock))
1443                 return -ERESTARTSYS;
1444
1445         if (dev->state & DEV_DISCONNECTED) {
1446                 em28xx_errdev("v4l2 ioctl: device not present\n");
1447                 mutex_unlock(&dev->fileop_lock);
1448                 return -ENODEV;
1449         }
1450
1451         if (dev->state & DEV_MISCONFIGURED) {
1452                 em28xx_errdev
1453                     ("v4l2 ioctl: device is misconfigured; close and open it again\n");
1454                 mutex_unlock(&dev->fileop_lock);
1455                 return -EIO;
1456         }
1457
1458         ret = video_usercopy(inode, filp, cmd, arg, em28xx_video_do_ioctl);
1459
1460         mutex_unlock(&dev->fileop_lock);
1461
1462         return ret;
1463 }
1464
1465 static const struct file_operations em28xx_v4l_fops = {
1466         .owner = THIS_MODULE,
1467         .open = em28xx_v4l2_open,
1468         .release = em28xx_v4l2_close,
1469         .ioctl = em28xx_v4l2_ioctl,
1470         .read = em28xx_v4l2_read,
1471         .poll = em28xx_v4l2_poll,
1472         .mmap = em28xx_v4l2_mmap,
1473         .llseek = no_llseek,
1474         .compat_ioctl   = v4l_compat_ioctl32,
1475
1476 };
1477
1478 /******************************** usb interface *****************************************/
1479
1480 /*
1481  * em28xx_init_dev()
1482  * allocates and inits the device structs, registers i2c bus and v4l device
1483  */
1484 static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
1485                            int minor)
1486 {
1487         struct em28xx *dev = *devhandle;
1488         int retval = -ENOMEM;
1489         int errCode, i;
1490         unsigned int maxh, maxw;
1491
1492         dev->udev = udev;
1493         mutex_init(&dev->lock);
1494         init_waitqueue_head(&dev->open);
1495
1496         dev->em28xx_write_regs = em28xx_write_regs;
1497         dev->em28xx_read_reg = em28xx_read_reg;
1498         dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
1499         dev->em28xx_write_regs_req = em28xx_write_regs_req;
1500         dev->em28xx_read_reg_req = em28xx_read_reg_req;
1501
1502         /* setup video picture settings for saa7113h */
1503         memset(&dev->vpic, 0, sizeof(dev->vpic));
1504         dev->vpic.colour = 128 << 8;
1505         dev->vpic.hue = 128 << 8;
1506         dev->vpic.brightness = 128 << 8;
1507         dev->vpic.contrast = 192 << 8;
1508         dev->vpic.whiteness = 128 << 8; /* This one isn't used */
1509         dev->vpic.depth = 16;
1510         dev->vpic.palette = VIDEO_PALETTE_YUV422;
1511
1512         em28xx_pre_card_setup(dev);
1513
1514         errCode = em28xx_config(dev);
1515         if (errCode) {
1516                 em28xx_errdev("error configuring device\n");
1517                 em28xx_devused &= ~(1<<dev->devno);
1518                 kfree(dev);
1519                 return -ENOMEM;
1520         }
1521
1522         mutex_lock(&dev->lock);
1523
1524         /* register i2c bus */
1525         em28xx_i2c_register(dev);
1526
1527         /* Do board specific init and eeprom reading */
1528         em28xx_card_setup(dev);
1529
1530         /* configure the device */
1531         em28xx_config_i2c(dev);
1532
1533         mutex_unlock(&dev->lock);
1534
1535         for (i = 0; i < TVNORMS; i++)
1536                 if (em28xx_boards[dev->model].norm == tvnorms[i].mode)
1537                         break;
1538         if (i == TVNORMS)
1539                 i = 0;
1540
1541         dev->tvnorm = &tvnorms[i];      /* set default norm */
1542
1543         em28xx_videodbg("tvnorm=%s\n", dev->tvnorm->name);
1544
1545         maxw = norm_maxw(dev);
1546         maxh = norm_maxh(dev);
1547
1548         /* set default image size */
1549         dev->width = maxw;
1550         dev->height = maxh;
1551         dev->interlaced = EM28XX_INTERLACED_DEFAULT;
1552         dev->field_size = dev->width * dev->height;
1553         dev->frame_size =
1554             dev->interlaced ? dev->field_size << 1 : dev->field_size;
1555         dev->bytesperline = dev->width * 2;
1556         dev->hscale = 0;
1557         dev->vscale = 0;
1558         dev->ctl_input = 2;
1559
1560         errCode = em28xx_config(dev);
1561
1562         /* allocate and fill v4l2 device struct */
1563         dev->vdev = video_device_alloc();
1564         if (NULL == dev->vdev) {
1565                 em28xx_errdev("cannot allocate video_device.\n");
1566                 em28xx_devused&=~(1<<dev->devno);
1567                 kfree(dev);
1568                 return -ENOMEM;
1569         }
1570
1571         dev->vbi_dev = video_device_alloc();
1572         if (NULL == dev->vbi_dev) {
1573                 em28xx_errdev("cannot allocate video_device.\n");
1574                 kfree(dev->vdev);
1575                 em28xx_devused&=~(1<<dev->devno);
1576                 kfree(dev);
1577                 return -ENOMEM;
1578         }
1579
1580         /* Fills VBI device info */
1581         dev->vbi_dev->type = VFL_TYPE_VBI;
1582         dev->vbi_dev->fops = &em28xx_v4l_fops;
1583         dev->vbi_dev->minor = -1;
1584         dev->vbi_dev->dev = &dev->udev->dev;
1585         dev->vbi_dev->release = video_device_release;
1586         snprintf(dev->vbi_dev->name, sizeof(dev->vbi_dev->name), "%s#%d %s",
1587                                                          "em28xx",dev->devno,"vbi");
1588
1589         /* Fills CAPTURE device info */
1590         dev->vdev->type = VID_TYPE_CAPTURE;
1591         if (dev->has_tuner)
1592                 dev->vdev->type |= VID_TYPE_TUNER;
1593         dev->vdev->fops = &em28xx_v4l_fops;
1594         dev->vdev->minor = -1;
1595         dev->vdev->dev = &dev->udev->dev;
1596         dev->vdev->release = video_device_release;
1597         snprintf(dev->vdev->name, sizeof(dev->vbi_dev->name), "%s#%d %s",
1598                                                          "em28xx",dev->devno,"video");
1599
1600         list_add_tail(&dev->devlist,&em28xx_devlist);
1601
1602         /* register v4l2 device */
1603         mutex_lock(&dev->lock);
1604         if ((retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
1605                                          video_nr[dev->devno]))) {
1606                 em28xx_errdev("unable to register video device (error=%i).\n",
1607                               retval);
1608                 mutex_unlock(&dev->lock);
1609                 list_del(&dev->devlist);
1610                 video_device_release(dev->vdev);
1611                 em28xx_devused&=~(1<<dev->devno);
1612                 kfree(dev);
1613                 return -ENODEV;
1614         }
1615
1616         if (video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
1617                                         vbi_nr[dev->devno]) < 0) {
1618                 printk("unable to register vbi device\n");
1619                 mutex_unlock(&dev->lock);
1620                 list_del(&dev->devlist);
1621                 video_device_release(dev->vbi_dev);
1622                 video_device_release(dev->vdev);
1623                 em28xx_devused&=~(1<<dev->devno);
1624                 kfree(dev);
1625                 return -ENODEV;
1626         } else {
1627                 printk("registered VBI\n");
1628         }
1629
1630         if (dev->has_msp34xx) {
1631                 /* Send a reset to other chips via gpio */
1632                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xf7", 1);
1633                 msleep(3);
1634                 em28xx_write_regs_req(dev, 0x00, 0x08, "\xff", 1);
1635                 msleep(3);
1636
1637         }
1638         video_mux(dev, 0);
1639
1640         mutex_unlock(&dev->lock);
1641
1642         em28xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
1643                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN,
1644                                 dev->vbi_dev->minor-MINOR_VFL_TYPE_VBI_MIN);
1645
1646         return 0;
1647 }
1648
1649 /*
1650  * em28xx_usb_probe()
1651  * checks for supported devices
1652  */
1653 static int em28xx_usb_probe(struct usb_interface *interface,
1654                             const struct usb_device_id *id)
1655 {
1656         const struct usb_endpoint_descriptor *endpoint;
1657         struct usb_device *udev;
1658         struct usb_interface *uif;
1659         struct em28xx *dev = NULL;
1660         int retval = -ENODEV;
1661         int i, nr, ifnum;
1662
1663         udev = usb_get_dev(interface_to_usbdev(interface));
1664         ifnum = interface->altsetting[0].desc.bInterfaceNumber;
1665
1666         /* Check to see next free device and mark as used */
1667         nr=find_first_zero_bit(&em28xx_devused,EM28XX_MAXBOARDS);
1668         em28xx_devused|=1<<nr;
1669
1670         /* Don't register audio interfaces */
1671         if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
1672                 em28xx_err(DRIVER_NAME " audio device (%04x:%04x): interface %i, class %i\n",
1673                                 udev->descriptor.idVendor,udev->descriptor.idProduct,
1674                                 ifnum,
1675                                 interface->altsetting[0].desc.bInterfaceClass);
1676
1677                 em28xx_devused&=~(1<<nr);
1678                 return -ENODEV;
1679         }
1680
1681         em28xx_err(DRIVER_NAME " new video device (%04x:%04x): interface %i, class %i\n",
1682                         udev->descriptor.idVendor,udev->descriptor.idProduct,
1683                         ifnum,
1684                         interface->altsetting[0].desc.bInterfaceClass);
1685
1686         endpoint = &interface->cur_altsetting->endpoint[1].desc;
1687
1688         /* check if the device has the iso in endpoint at the correct place */
1689         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
1690             USB_ENDPOINT_XFER_ISOC) {
1691                 em28xx_err(DRIVER_NAME " probing error: endpoint is non-ISO endpoint!\n");
1692                 em28xx_devused&=~(1<<nr);
1693                 return -ENODEV;
1694         }
1695         if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
1696                 em28xx_err(DRIVER_NAME " probing error: endpoint is ISO OUT endpoint!\n");
1697                 em28xx_devused&=~(1<<nr);
1698                 return -ENODEV;
1699         }
1700
1701         if (nr >= EM28XX_MAXBOARDS) {
1702                 printk (DRIVER_NAME ": Supports only %i em28xx boards.\n",EM28XX_MAXBOARDS);
1703                 em28xx_devused&=~(1<<nr);
1704                 return -ENOMEM;
1705         }
1706
1707         /* allocate memory for our device state and initialize it */
1708         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1709         if (dev == NULL) {
1710                 em28xx_err(DRIVER_NAME ": out of memory!\n");
1711                 em28xx_devused&=~(1<<nr);
1712                 return -ENOMEM;
1713         }
1714
1715         snprintf(dev->name, 29, "em28xx #%d", nr);
1716         dev->devno = nr;
1717         dev->model = id->driver_info;
1718
1719         /* compute alternate max packet sizes */
1720         uif = udev->actconfig->interface[0];
1721
1722         dev->num_alt=uif->num_altsetting;
1723         em28xx_info("Alternate settings: %i\n",dev->num_alt);
1724 //      dev->alt_max_pkt_size = kmalloc(sizeof(*dev->alt_max_pkt_size)*
1725         dev->alt_max_pkt_size = kmalloc(32*
1726                                                 dev->num_alt,GFP_KERNEL);
1727         if (dev->alt_max_pkt_size == NULL) {
1728                 em28xx_errdev("out of memory!\n");
1729                 em28xx_devused&=~(1<<nr);
1730                 kfree(dev);
1731                 return -ENOMEM;
1732         }
1733
1734         for (i = 0; i < dev->num_alt ; i++) {
1735                 u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.
1736                                                         wMaxPacketSize);
1737                 dev->alt_max_pkt_size[i] =
1738                     (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
1739                 em28xx_info("Alternate setting %i, max size= %i\n",i,
1740                                                         dev->alt_max_pkt_size[i]);
1741         }
1742
1743         if ((card[nr]>=0)&&(card[nr]<em28xx_bcount))
1744                 dev->model = card[nr];
1745
1746         /* allocate device struct */
1747         retval = em28xx_init_dev(&dev, udev, nr);
1748         if (retval)
1749                 return retval;
1750
1751         em28xx_info("Found %s\n", em28xx_boards[dev->model].name);
1752
1753         /* save our data pointer in this interface device */
1754         usb_set_intfdata(interface, dev);
1755         return 0;
1756 }
1757
1758 /*
1759  * em28xx_usb_disconnect()
1760  * called when the device gets diconencted
1761  * video device will be unregistered on v4l2_close in case it is still open
1762  */
1763 static void em28xx_usb_disconnect(struct usb_interface *interface)
1764 {
1765         struct em28xx *dev = usb_get_intfdata(interface);
1766         usb_set_intfdata(interface, NULL);
1767
1768         if (!dev)
1769                 return;
1770
1771         down_write(&em28xx_disconnect);
1772
1773         mutex_lock(&dev->lock);
1774
1775         em28xx_info("disconnecting %s\n", dev->vdev->name);
1776
1777         wake_up_interruptible_all(&dev->open);
1778
1779         if (dev->users) {
1780                 em28xx_warn
1781                     ("device /dev/video%d is open! Deregistration and memory "
1782                      "deallocation are deferred on close.\n",
1783                                 dev->vdev->minor-MINOR_VFL_TYPE_GRABBER_MIN);
1784
1785                 dev->state |= DEV_MISCONFIGURED;
1786                 em28xx_uninit_isoc(dev);
1787                 dev->state |= DEV_DISCONNECTED;
1788                 wake_up_interruptible(&dev->wait_frame);
1789                 wake_up_interruptible(&dev->wait_stream);
1790         } else {
1791                 dev->state |= DEV_DISCONNECTED;
1792                 em28xx_release_resources(dev);
1793         }
1794
1795         mutex_unlock(&dev->lock);
1796
1797         if (!dev->users) {
1798                 kfree(dev->alt_max_pkt_size);
1799                 kfree(dev);
1800         }
1801
1802         up_write(&em28xx_disconnect);
1803 }
1804
1805 static struct usb_driver em28xx_usb_driver = {
1806         .name = "em28xx",
1807         .probe = em28xx_usb_probe,
1808         .disconnect = em28xx_usb_disconnect,
1809         .id_table = em28xx_id_table,
1810 };
1811
1812 static int __init em28xx_module_init(void)
1813 {
1814         int result;
1815
1816         printk(KERN_INFO DRIVER_NAME " v4l2 driver version %d.%d.%d loaded\n",
1817                (EM28XX_VERSION_CODE >> 16) & 0xff,
1818                (EM28XX_VERSION_CODE >> 8) & 0xff, EM28XX_VERSION_CODE & 0xff);
1819 #ifdef SNAPSHOT
1820         printk(KERN_INFO DRIVER_NAME " snapshot date %04d-%02d-%02d\n",
1821                SNAPSHOT / 10000, (SNAPSHOT / 100) % 100, SNAPSHOT % 100);
1822 #endif
1823
1824         /* register this driver with the USB subsystem */
1825         result = usb_register(&em28xx_usb_driver);
1826         if (result)
1827                 em28xx_err(DRIVER_NAME
1828                            " usb_register failed. Error number %d.\n", result);
1829
1830         return result;
1831 }
1832
1833 static void __exit em28xx_module_exit(void)
1834 {
1835         /* deregister this driver with the USB subsystem */
1836         usb_deregister(&em28xx_usb_driver);
1837 }
1838
1839 module_init(em28xx_module_init);
1840 module_exit(em28xx_module_exit);