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