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