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