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