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