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