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