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