Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/rric/oprofile
[linux-2.6] / drivers / media / video / usbvision / usbvision-video.c
1 /*
2  * USB USBVISION Video device driver 0.9.9
3  *
4  *
5  *
6  * Copyright (c) 1999-2005 Joerg Heckenbach <joerg@heckenbach-aw.de>
7  *
8  * This module is part of usbvision driver project.
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  * Let's call the version 0.... until compression decoding is completely
25  * implemented.
26  *
27  * This driver is written by Jose Ignacio Gijon and Joerg Heckenbach.
28  * It was based on USB CPiA driver written by Peter Pregler,
29  * Scott J. Bertin and Johannes Erdfelt
30  * Ideas are taken from bttv driver by Ralph Metzler, Marcus Metzler &
31  * Gerd Knorr and zoran 36120/36125 driver by Pauline Middelink
32  * Updates to driver completed by Dwaine P. Garden
33  *
34  *
35  * TODO:
36  *     - use submit_urb for all setup packets
37  *     - Fix memory settings for nt1004. It is 4 times as big as the
38  *       nt1003 memory.
39  *     - Add audio on endpoint 3 for nt1004 chip.
40  *         Seems impossible, needs a codec interface.  Which one?
41  *     - Clean up the driver.
42  *     - optimization for performance.
43  *     - Add Videotext capability (VBI).  Working on it.....
44  *     - Check audio for other devices
45  *
46  */
47
48 #include <linux/version.h>
49 #include <linux/kernel.h>
50 #include <linux/list.h>
51 #include <linux/timer.h>
52 #include <linux/slab.h>
53 #include <linux/mm.h>
54 #include <linux/utsname.h>
55 #include <linux/highmem.h>
56 #include <linux/vmalloc.h>
57 #include <linux/module.h>
58 #include <linux/init.h>
59 #include <linux/spinlock.h>
60 #include <asm/io.h>
61 #include <linux/videodev2.h>
62 #include <linux/video_decoder.h>
63 #include <linux/i2c.h>
64
65 #include <media/saa7115.h>
66 #include <media/v4l2-common.h>
67 #include <media/v4l2-ioctl.h>
68 #include <media/tuner.h>
69
70 #include <linux/workqueue.h>
71
72 #include "usbvision.h"
73 #include "usbvision-cards.h"
74
75 #define DRIVER_AUTHOR "Joerg Heckenbach <joerg@heckenbach-aw.de>,\
76  Dwaine Garden <DwaineGarden@rogers.com>"
77 #define DRIVER_NAME "usbvision"
78 #define DRIVER_ALIAS "USBVision"
79 #define DRIVER_DESC "USBVision USB Video Device Driver for Linux"
80 #define DRIVER_LICENSE "GPL"
81 #define USBVISION_DRIVER_VERSION_MAJOR 0
82 #define USBVISION_DRIVER_VERSION_MINOR 9
83 #define USBVISION_DRIVER_VERSION_PATCHLEVEL 9
84 #define USBVISION_DRIVER_VERSION KERNEL_VERSION(USBVISION_DRIVER_VERSION_MAJOR,\
85 USBVISION_DRIVER_VERSION_MINOR,\
86 USBVISION_DRIVER_VERSION_PATCHLEVEL)
87 #define USBVISION_VERSION_STRING __stringify(USBVISION_DRIVER_VERSION_MAJOR)\
88  "." __stringify(USBVISION_DRIVER_VERSION_MINOR)\
89  "." __stringify(USBVISION_DRIVER_VERSION_PATCHLEVEL)
90
91 #define ENABLE_HEXDUMP  0       /* Enable if you need it */
92
93
94 #ifdef USBVISION_DEBUG
95         #define PDEBUG(level, fmt, args...) { \
96                 if (video_debug & (level)) \
97                         printk(KERN_INFO KBUILD_MODNAME ":[%s:%d] " fmt, \
98                                 __func__, __LINE__ , ## args); \
99         }
100 #else
101         #define PDEBUG(level, fmt, args...) do {} while(0)
102 #endif
103
104 #define DBG_IO          1<<1
105 #define DBG_PROBE       1<<2
106 #define DBG_MMAP        1<<3
107
108 //String operations
109 #define rmspace(str)    while(*str==' ') str++;
110 #define goto2next(str)  while(*str!=' ') str++; while(*str==' ') str++;
111
112
113 /* sequential number of usbvision device */
114 static int usbvision_nr;
115
116 static struct usbvision_v4l2_format_st usbvision_v4l2_format[] = {
117         { 1, 1,  8, V4L2_PIX_FMT_GREY    , "GREY" },
118         { 1, 2, 16, V4L2_PIX_FMT_RGB565  , "RGB565" },
119         { 1, 3, 24, V4L2_PIX_FMT_RGB24   , "RGB24" },
120         { 1, 4, 32, V4L2_PIX_FMT_RGB32   , "RGB32" },
121         { 1, 2, 16, V4L2_PIX_FMT_RGB555  , "RGB555" },
122         { 1, 2, 16, V4L2_PIX_FMT_YUYV    , "YUV422" },
123         { 1, 2, 12, V4L2_PIX_FMT_YVU420  , "YUV420P" }, // 1.5 !
124         { 1, 2, 16, V4L2_PIX_FMT_YUV422P , "YUV422P" }
125 };
126
127 /* Function prototypes */
128 static void usbvision_release(struct usb_usbvision *usbvision);
129
130 /* Default initialization of device driver parameters */
131 /* Set the default format for ISOC endpoint */
132 static int isocMode = ISOC_MODE_COMPRESS;
133 /* Set the default Debug Mode of the device driver */
134 static int video_debug;
135 /* Set the default device to power on at startup */
136 static int PowerOnAtOpen = 1;
137 /* Sequential Number of Video Device */
138 static int video_nr = -1;
139 /* Sequential Number of Radio Device */
140 static int radio_nr = -1;
141 /* Sequential Number of VBI Device */
142 static int vbi_nr = -1;
143
144 /* Grab parameters for the device driver */
145
146 /* Showing parameters under SYSFS */
147 module_param(isocMode, int, 0444);
148 module_param(video_debug, int, 0444);
149 module_param(PowerOnAtOpen, int, 0444);
150 module_param(video_nr, int, 0444);
151 module_param(radio_nr, int, 0444);
152 module_param(vbi_nr, int, 0444);
153
154 MODULE_PARM_DESC(isocMode, " Set the default format for ISOC endpoint.  Default: 0x60 (Compression On)");
155 MODULE_PARM_DESC(video_debug, " Set the default Debug Mode of the device driver.  Default: 0 (Off)");
156 MODULE_PARM_DESC(PowerOnAtOpen, " Set the default device to power on when device is opened.  Default: 1 (On)");
157 MODULE_PARM_DESC(video_nr, "Set video device number (/dev/videoX).  Default: -1 (autodetect)");
158 MODULE_PARM_DESC(radio_nr, "Set radio device number (/dev/radioX).  Default: -1 (autodetect)");
159 MODULE_PARM_DESC(vbi_nr, "Set vbi device number (/dev/vbiX).  Default: -1 (autodetect)");
160
161
162 // Misc stuff
163 MODULE_AUTHOR(DRIVER_AUTHOR);
164 MODULE_DESCRIPTION(DRIVER_DESC);
165 MODULE_LICENSE(DRIVER_LICENSE);
166 MODULE_VERSION(USBVISION_VERSION_STRING);
167 MODULE_ALIAS(DRIVER_ALIAS);
168
169
170 /*****************************************************************************/
171 /* SYSFS Code - Copied from the stv680.c usb module.                         */
172 /* Device information is located at /sys/class/video4linux/video0            */
173 /* Device parameters information is located at /sys/module/usbvision         */
174 /* Device USB Information is located at                                      */
175 /*   /sys/bus/usb/drivers/USBVision Video Grabber                            */
176 /*****************************************************************************/
177
178 #define YES_NO(x) ((x) ? "Yes" : "No")
179
180 static inline struct usb_usbvision *cd_to_usbvision(struct device *cd)
181 {
182         struct video_device *vdev =
183                 container_of(cd, struct video_device, dev);
184         return video_get_drvdata(vdev);
185 }
186
187 static ssize_t show_version(struct device *cd,
188                             struct device_attribute *attr, char *buf)
189 {
190         return sprintf(buf, "%s\n", USBVISION_VERSION_STRING);
191 }
192 static DEVICE_ATTR(version, S_IRUGO, show_version, NULL);
193
194 static ssize_t show_model(struct device *cd,
195                           struct device_attribute *attr, char *buf)
196 {
197         struct video_device *vdev =
198                 container_of(cd, struct video_device, dev);
199         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
200         return sprintf(buf, "%s\n",
201                        usbvision_device_data[usbvision->DevModel].ModelString);
202 }
203 static DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
204
205 static ssize_t show_hue(struct device *cd,
206                         struct device_attribute *attr, char *buf)
207 {
208         struct video_device *vdev =
209                 container_of(cd, struct video_device, dev);
210         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
211         struct v4l2_control ctrl;
212         ctrl.id = V4L2_CID_HUE;
213         ctrl.value = 0;
214         if(usbvision->user)
215                 call_i2c_clients(usbvision, VIDIOC_G_CTRL, &ctrl);
216         return sprintf(buf, "%d\n", ctrl.value);
217 }
218 static DEVICE_ATTR(hue, S_IRUGO, show_hue, NULL);
219
220 static ssize_t show_contrast(struct device *cd,
221                              struct device_attribute *attr, char *buf)
222 {
223         struct video_device *vdev =
224                 container_of(cd, struct video_device, dev);
225         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
226         struct v4l2_control ctrl;
227         ctrl.id = V4L2_CID_CONTRAST;
228         ctrl.value = 0;
229         if(usbvision->user)
230                 call_i2c_clients(usbvision, VIDIOC_G_CTRL, &ctrl);
231         return sprintf(buf, "%d\n", ctrl.value);
232 }
233 static DEVICE_ATTR(contrast, S_IRUGO, show_contrast, NULL);
234
235 static ssize_t show_brightness(struct device *cd,
236                                struct device_attribute *attr, char *buf)
237 {
238         struct video_device *vdev =
239                 container_of(cd, struct video_device, dev);
240         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
241         struct v4l2_control ctrl;
242         ctrl.id = V4L2_CID_BRIGHTNESS;
243         ctrl.value = 0;
244         if(usbvision->user)
245                 call_i2c_clients(usbvision, VIDIOC_G_CTRL, &ctrl);
246         return sprintf(buf, "%d\n", ctrl.value);
247 }
248 static DEVICE_ATTR(brightness, S_IRUGO, show_brightness, NULL);
249
250 static ssize_t show_saturation(struct device *cd,
251                                struct device_attribute *attr, char *buf)
252 {
253         struct video_device *vdev =
254                 container_of(cd, struct video_device, dev);
255         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
256         struct v4l2_control ctrl;
257         ctrl.id = V4L2_CID_SATURATION;
258         ctrl.value = 0;
259         if(usbvision->user)
260                 call_i2c_clients(usbvision, VIDIOC_G_CTRL, &ctrl);
261         return sprintf(buf, "%d\n", ctrl.value);
262 }
263 static DEVICE_ATTR(saturation, S_IRUGO, show_saturation, NULL);
264
265 static ssize_t show_streaming(struct device *cd,
266                               struct device_attribute *attr, char *buf)
267 {
268         struct video_device *vdev =
269                 container_of(cd, struct video_device, dev);
270         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
271         return sprintf(buf, "%s\n",
272                        YES_NO(usbvision->streaming==Stream_On?1:0));
273 }
274 static DEVICE_ATTR(streaming, S_IRUGO, show_streaming, NULL);
275
276 static ssize_t show_compression(struct device *cd,
277                                 struct device_attribute *attr, char *buf)
278 {
279         struct video_device *vdev =
280                 container_of(cd, struct video_device, dev);
281         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
282         return sprintf(buf, "%s\n",
283                        YES_NO(usbvision->isocMode==ISOC_MODE_COMPRESS));
284 }
285 static DEVICE_ATTR(compression, S_IRUGO, show_compression, NULL);
286
287 static ssize_t show_device_bridge(struct device *cd,
288                                   struct device_attribute *attr, char *buf)
289 {
290         struct video_device *vdev =
291                 container_of(cd, struct video_device, dev);
292         struct usb_usbvision *usbvision = video_get_drvdata(vdev);
293         return sprintf(buf, "%d\n", usbvision->bridgeType);
294 }
295 static DEVICE_ATTR(bridge, S_IRUGO, show_device_bridge, NULL);
296
297 static void usbvision_create_sysfs(struct video_device *vdev)
298 {
299         int res;
300         if (!vdev)
301                 return;
302         do {
303                 res = device_create_file(&vdev->dev, &dev_attr_version);
304                 if (res<0)
305                         break;
306                 res = device_create_file(&vdev->dev, &dev_attr_model);
307                 if (res<0)
308                         break;
309                 res = device_create_file(&vdev->dev, &dev_attr_hue);
310                 if (res<0)
311                         break;
312                 res = device_create_file(&vdev->dev, &dev_attr_contrast);
313                 if (res<0)
314                         break;
315                 res = device_create_file(&vdev->dev, &dev_attr_brightness);
316                 if (res<0)
317                         break;
318                 res = device_create_file(&vdev->dev, &dev_attr_saturation);
319                 if (res<0)
320                         break;
321                 res = device_create_file(&vdev->dev, &dev_attr_streaming);
322                 if (res<0)
323                         break;
324                 res = device_create_file(&vdev->dev, &dev_attr_compression);
325                 if (res<0)
326                         break;
327                 res = device_create_file(&vdev->dev, &dev_attr_bridge);
328                 if (res>=0)
329                         return;
330         } while (0);
331
332         err("%s error: %d\n", __func__, res);
333 }
334
335 static void usbvision_remove_sysfs(struct video_device *vdev)
336 {
337         if (vdev) {
338                 device_remove_file(&vdev->dev, &dev_attr_version);
339                 device_remove_file(&vdev->dev, &dev_attr_model);
340                 device_remove_file(&vdev->dev, &dev_attr_hue);
341                 device_remove_file(&vdev->dev, &dev_attr_contrast);
342                 device_remove_file(&vdev->dev, &dev_attr_brightness);
343                 device_remove_file(&vdev->dev, &dev_attr_saturation);
344                 device_remove_file(&vdev->dev, &dev_attr_streaming);
345                 device_remove_file(&vdev->dev, &dev_attr_compression);
346                 device_remove_file(&vdev->dev, &dev_attr_bridge);
347         }
348 }
349
350 /*
351  * usbvision_open()
352  *
353  * This is part of Video 4 Linux API. The driver can be opened by one
354  * client only (checks internal counter 'usbvision->user'). The procedure
355  * then allocates buffers needed for video processing.
356  *
357  */
358 static int usbvision_v4l2_open(struct file *file)
359 {
360         struct usb_usbvision *usbvision = video_drvdata(file);
361         int errCode = 0;
362
363         PDEBUG(DBG_IO, "open");
364
365         lock_kernel();
366         usbvision_reset_powerOffTimer(usbvision);
367
368         if (usbvision->user)
369                 errCode = -EBUSY;
370         else {
371                 /* Allocate memory for the scratch ring buffer */
372                 errCode = usbvision_scratch_alloc(usbvision);
373                 if (isocMode==ISOC_MODE_COMPRESS) {
374                         /* Allocate intermediate decompression buffers
375                            only if needed */
376                         errCode = usbvision_decompress_alloc(usbvision);
377                 }
378                 if (errCode) {
379                         /* Deallocate all buffers if trouble */
380                         usbvision_scratch_free(usbvision);
381                         usbvision_decompress_free(usbvision);
382                 }
383         }
384
385         /* If so far no errors then we shall start the camera */
386         if (!errCode) {
387                 mutex_lock(&usbvision->lock);
388                 if (usbvision->power == 0) {
389                         usbvision_power_on(usbvision);
390                         usbvision_i2c_register(usbvision);
391                 }
392
393                 /* Send init sequence only once, it's large! */
394                 if (!usbvision->initialized) {
395                         int setup_ok = 0;
396                         setup_ok = usbvision_setup(usbvision,isocMode);
397                         if (setup_ok)
398                                 usbvision->initialized = 1;
399                         else
400                                 errCode = -EBUSY;
401                 }
402
403                 if (!errCode) {
404                         usbvision_begin_streaming(usbvision);
405                         errCode = usbvision_init_isoc(usbvision);
406                         /* device must be initialized before isoc transfer */
407                         usbvision_muxsel(usbvision,0);
408                         usbvision->user++;
409                 } else {
410                         if (PowerOnAtOpen) {
411                                 usbvision_i2c_unregister(usbvision);
412                                 usbvision_power_off(usbvision);
413                                 usbvision->initialized = 0;
414                         }
415                 }
416                 mutex_unlock(&usbvision->lock);
417         }
418
419         /* prepare queues */
420         usbvision_empty_framequeues(usbvision);
421
422         PDEBUG(DBG_IO, "success");
423         unlock_kernel();
424         return errCode;
425 }
426
427 /*
428  * usbvision_v4l2_close()
429  *
430  * This is part of Video 4 Linux API. The procedure
431  * stops streaming and deallocates all buffers that were earlier
432  * allocated in usbvision_v4l2_open().
433  *
434  */
435 static int usbvision_v4l2_close(struct file *file)
436 {
437         struct usb_usbvision *usbvision = video_drvdata(file);
438
439         PDEBUG(DBG_IO, "close");
440         mutex_lock(&usbvision->lock);
441
442         usbvision_audio_off(usbvision);
443         usbvision_restart_isoc(usbvision);
444         usbvision_stop_isoc(usbvision);
445
446         usbvision_decompress_free(usbvision);
447         usbvision_frames_free(usbvision);
448         usbvision_empty_framequeues(usbvision);
449         usbvision_scratch_free(usbvision);
450
451         usbvision->user--;
452
453         if (PowerOnAtOpen) {
454                 /* power off in a little while
455                    to avoid off/on every close/open short sequences */
456                 usbvision_set_powerOffTimer(usbvision);
457                 usbvision->initialized = 0;
458         }
459
460         mutex_unlock(&usbvision->lock);
461
462         if (usbvision->remove_pending) {
463                 printk(KERN_INFO "%s: Final disconnect\n", __func__);
464                 usbvision_release(usbvision);
465         }
466
467         PDEBUG(DBG_IO, "success");
468         return 0;
469 }
470
471
472 /*
473  * usbvision_ioctl()
474  *
475  * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
476  *
477  */
478 #ifdef CONFIG_VIDEO_ADV_DEBUG
479 static int vidioc_g_register (struct file *file, void *priv,
480                                 struct v4l2_dbg_register *reg)
481 {
482         struct usb_usbvision *usbvision = video_drvdata(file);
483         int errCode;
484
485         if (!v4l2_chip_match_host(&reg->match))
486                 return -EINVAL;
487         /* NT100x has a 8-bit register space */
488         errCode = usbvision_read_reg(usbvision, reg->reg&0xff);
489         if (errCode < 0) {
490                 err("%s: VIDIOC_DBG_G_REGISTER failed: error %d",
491                     __func__, errCode);
492                 return errCode;
493         }
494         reg->val = errCode;
495         reg->size = 1;
496         return 0;
497 }
498
499 static int vidioc_s_register (struct file *file, void *priv,
500                                 struct v4l2_dbg_register *reg)
501 {
502         struct usb_usbvision *usbvision = video_drvdata(file);
503         int errCode;
504
505         if (!v4l2_chip_match_host(&reg->match))
506                 return -EINVAL;
507         /* NT100x has a 8-bit register space */
508         errCode = usbvision_write_reg(usbvision, reg->reg&0xff, reg->val);
509         if (errCode < 0) {
510                 err("%s: VIDIOC_DBG_S_REGISTER failed: error %d",
511                     __func__, errCode);
512                 return errCode;
513         }
514         return 0;
515 }
516 #endif
517
518 static int vidioc_querycap (struct file *file, void  *priv,
519                                         struct v4l2_capability *vc)
520 {
521         struct usb_usbvision *usbvision = video_drvdata(file);
522
523         strlcpy(vc->driver, "USBVision", sizeof(vc->driver));
524         strlcpy(vc->card,
525                 usbvision_device_data[usbvision->DevModel].ModelString,
526                 sizeof(vc->card));
527         strlcpy(vc->bus_info, dev_name(&usbvision->dev->dev),
528                 sizeof(vc->bus_info));
529         vc->version = USBVISION_DRIVER_VERSION;
530         vc->capabilities = V4L2_CAP_VIDEO_CAPTURE |
531                 V4L2_CAP_AUDIO |
532                 V4L2_CAP_READWRITE |
533                 V4L2_CAP_STREAMING |
534                 (usbvision->have_tuner ? V4L2_CAP_TUNER : 0);
535         return 0;
536 }
537
538 static int vidioc_enum_input (struct file *file, void *priv,
539                                 struct v4l2_input *vi)
540 {
541         struct usb_usbvision *usbvision = video_drvdata(file);
542         int chan;
543
544         if ((vi->index >= usbvision->video_inputs) || (vi->index < 0) )
545                 return -EINVAL;
546         if (usbvision->have_tuner) {
547                 chan = vi->index;
548         } else {
549                 chan = vi->index + 1; /*skip Television string*/
550         }
551         /* Determine the requested input characteristics
552            specific for each usbvision card model */
553         switch(chan) {
554         case 0:
555                 if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
556                         strcpy(vi->name, "White Video Input");
557                 } else {
558                         strcpy(vi->name, "Television");
559                         vi->type = V4L2_INPUT_TYPE_TUNER;
560                         vi->audioset = 1;
561                         vi->tuner = chan;
562                         vi->std = USBVISION_NORMS;
563                 }
564                 break;
565         case 1:
566                 vi->type = V4L2_INPUT_TYPE_CAMERA;
567                 if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
568                         strcpy(vi->name, "Green Video Input");
569                 } else {
570                         strcpy(vi->name, "Composite Video Input");
571                 }
572                 vi->std = V4L2_STD_PAL;
573                 break;
574         case 2:
575                 vi->type = V4L2_INPUT_TYPE_CAMERA;
576                 if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
577                         strcpy(vi->name, "Yellow Video Input");
578                 } else {
579                         strcpy(vi->name, "S-Video Input");
580                 }
581                 vi->std = V4L2_STD_PAL;
582                 break;
583         case 3:
584                 vi->type = V4L2_INPUT_TYPE_CAMERA;
585                 strcpy(vi->name, "Red Video Input");
586                 vi->std = V4L2_STD_PAL;
587                 break;
588         }
589         return 0;
590 }
591
592 static int vidioc_g_input (struct file *file, void *priv, unsigned int *input)
593 {
594         struct usb_usbvision *usbvision = video_drvdata(file);
595
596         *input = usbvision->ctl_input;
597         return 0;
598 }
599
600 static int vidioc_s_input (struct file *file, void *priv, unsigned int input)
601 {
602         struct usb_usbvision *usbvision = video_drvdata(file);
603
604         if ((input >= usbvision->video_inputs) || (input < 0) )
605                 return -EINVAL;
606
607         mutex_lock(&usbvision->lock);
608         usbvision_muxsel(usbvision, input);
609         usbvision_set_input(usbvision);
610         usbvision_set_output(usbvision,
611                              usbvision->curwidth,
612                              usbvision->curheight);
613         mutex_unlock(&usbvision->lock);
614         return 0;
615 }
616
617 static int vidioc_s_std (struct file *file, void *priv, v4l2_std_id *id)
618 {
619         struct usb_usbvision *usbvision = video_drvdata(file);
620
621         usbvision->tvnormId=*id;
622
623         mutex_lock(&usbvision->lock);
624         call_i2c_clients(usbvision, VIDIOC_S_STD,
625                          &usbvision->tvnormId);
626         mutex_unlock(&usbvision->lock);
627         /* propagate the change to the decoder */
628         usbvision_muxsel(usbvision, usbvision->ctl_input);
629
630         return 0;
631 }
632
633 static int vidioc_g_tuner (struct file *file, void *priv,
634                                 struct v4l2_tuner *vt)
635 {
636         struct usb_usbvision *usbvision = video_drvdata(file);
637
638         if (!usbvision->have_tuner || vt->index)        // Only tuner 0
639                 return -EINVAL;
640         if(usbvision->radio) {
641                 strcpy(vt->name, "Radio");
642                 vt->type = V4L2_TUNER_RADIO;
643         } else {
644                 strcpy(vt->name, "Television");
645         }
646         /* Let clients fill in the remainder of this struct */
647         call_i2c_clients(usbvision,VIDIOC_G_TUNER,vt);
648
649         return 0;
650 }
651
652 static int vidioc_s_tuner (struct file *file, void *priv,
653                                 struct v4l2_tuner *vt)
654 {
655         struct usb_usbvision *usbvision = video_drvdata(file);
656
657         // Only no or one tuner for now
658         if (!usbvision->have_tuner || vt->index)
659                 return -EINVAL;
660         /* let clients handle this */
661         call_i2c_clients(usbvision,VIDIOC_S_TUNER,vt);
662
663         return 0;
664 }
665
666 static int vidioc_g_frequency (struct file *file, void *priv,
667                                 struct v4l2_frequency *freq)
668 {
669         struct usb_usbvision *usbvision = video_drvdata(file);
670
671         freq->tuner = 0; // Only one tuner
672         if(usbvision->radio) {
673                 freq->type = V4L2_TUNER_RADIO;
674         } else {
675                 freq->type = V4L2_TUNER_ANALOG_TV;
676         }
677         freq->frequency = usbvision->freq;
678
679         return 0;
680 }
681
682 static int vidioc_s_frequency (struct file *file, void *priv,
683                                 struct v4l2_frequency *freq)
684 {
685         struct usb_usbvision *usbvision = video_drvdata(file);
686
687         // Only no or one tuner for now
688         if (!usbvision->have_tuner || freq->tuner)
689                 return -EINVAL;
690
691         usbvision->freq = freq->frequency;
692         call_i2c_clients(usbvision, VIDIOC_S_FREQUENCY, freq);
693
694         return 0;
695 }
696
697 static int vidioc_g_audio (struct file *file, void *priv, struct v4l2_audio *a)
698 {
699         struct usb_usbvision *usbvision = video_drvdata(file);
700
701         memset(a,0,sizeof(*a));
702         if(usbvision->radio) {
703                 strcpy(a->name,"Radio");
704         } else {
705                 strcpy(a->name, "TV");
706         }
707
708         return 0;
709 }
710
711 static int vidioc_s_audio (struct file *file, void *fh,
712                           struct v4l2_audio *a)
713 {
714         if(a->index) {
715                 return -EINVAL;
716         }
717
718         return 0;
719 }
720
721 static int vidioc_queryctrl (struct file *file, void *priv,
722                             struct v4l2_queryctrl *ctrl)
723 {
724         struct usb_usbvision *usbvision = video_drvdata(file);
725         int id=ctrl->id;
726
727         memset(ctrl,0,sizeof(*ctrl));
728         ctrl->id=id;
729
730         call_i2c_clients(usbvision, VIDIOC_QUERYCTRL, ctrl);
731
732         if (!ctrl->type)
733                 return -EINVAL;
734
735         return 0;
736 }
737
738 static int vidioc_g_ctrl (struct file *file, void *priv,
739                                 struct v4l2_control *ctrl)
740 {
741         struct usb_usbvision *usbvision = video_drvdata(file);
742         call_i2c_clients(usbvision, VIDIOC_G_CTRL, ctrl);
743
744         return 0;
745 }
746
747 static int vidioc_s_ctrl (struct file *file, void *priv,
748                                 struct v4l2_control *ctrl)
749 {
750         struct usb_usbvision *usbvision = video_drvdata(file);
751         call_i2c_clients(usbvision, VIDIOC_S_CTRL, ctrl);
752
753         return 0;
754 }
755
756 static int vidioc_reqbufs (struct file *file,
757                            void *priv, struct v4l2_requestbuffers *vr)
758 {
759         struct usb_usbvision *usbvision = video_drvdata(file);
760         int ret;
761
762         RESTRICT_TO_RANGE(vr->count,1,USBVISION_NUMFRAMES);
763
764         /* Check input validity:
765            the user must do a VIDEO CAPTURE and MMAP method. */
766         if((vr->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
767            (vr->memory != V4L2_MEMORY_MMAP))
768                 return -EINVAL;
769
770         if(usbvision->streaming == Stream_On) {
771                 if ((ret = usbvision_stream_interrupt(usbvision)))
772                         return ret;
773         }
774
775         usbvision_frames_free(usbvision);
776         usbvision_empty_framequeues(usbvision);
777         vr->count = usbvision_frames_alloc(usbvision,vr->count);
778
779         usbvision->curFrame = NULL;
780
781         return 0;
782 }
783
784 static int vidioc_querybuf (struct file *file,
785                             void *priv, struct v4l2_buffer *vb)
786 {
787         struct usb_usbvision *usbvision = video_drvdata(file);
788         struct usbvision_frame *frame;
789
790         /* FIXME : must control
791            that buffers are mapped (VIDIOC_REQBUFS has been called) */
792         if(vb->type != V4L2_CAP_VIDEO_CAPTURE) {
793                 return -EINVAL;
794         }
795         if(vb->index>=usbvision->num_frames)  {
796                 return -EINVAL;
797         }
798         /* Updating the corresponding frame state */
799         vb->flags = 0;
800         frame = &usbvision->frame[vb->index];
801         if(frame->grabstate >= FrameState_Ready)
802                 vb->flags |= V4L2_BUF_FLAG_QUEUED;
803         if(frame->grabstate >= FrameState_Done)
804                 vb->flags |= V4L2_BUF_FLAG_DONE;
805         if(frame->grabstate == FrameState_Unused)
806                 vb->flags |= V4L2_BUF_FLAG_MAPPED;
807         vb->memory = V4L2_MEMORY_MMAP;
808
809         vb->m.offset = vb->index*PAGE_ALIGN(usbvision->max_frame_size);
810
811         vb->memory = V4L2_MEMORY_MMAP;
812         vb->field = V4L2_FIELD_NONE;
813         vb->length = usbvision->curwidth*
814                 usbvision->curheight*
815                 usbvision->palette.bytes_per_pixel;
816         vb->timestamp = usbvision->frame[vb->index].timestamp;
817         vb->sequence = usbvision->frame[vb->index].sequence;
818         return 0;
819 }
820
821 static int vidioc_qbuf (struct file *file, void *priv, struct v4l2_buffer *vb)
822 {
823         struct usb_usbvision *usbvision = video_drvdata(file);
824         struct usbvision_frame *frame;
825         unsigned long lock_flags;
826
827         /* FIXME : works only on VIDEO_CAPTURE MODE, MMAP. */
828         if(vb->type != V4L2_CAP_VIDEO_CAPTURE) {
829                 return -EINVAL;
830         }
831         if(vb->index>=usbvision->num_frames)  {
832                 return -EINVAL;
833         }
834
835         frame = &usbvision->frame[vb->index];
836
837         if (frame->grabstate != FrameState_Unused) {
838                 return -EAGAIN;
839         }
840
841         /* Mark it as ready and enqueue frame */
842         frame->grabstate = FrameState_Ready;
843         frame->scanstate = ScanState_Scanning;
844         frame->scanlength = 0;  /* Accumulated in usbvision_parse_data() */
845
846         vb->flags &= ~V4L2_BUF_FLAG_DONE;
847
848         /* set v4l2_format index */
849         frame->v4l2_format = usbvision->palette;
850
851         spin_lock_irqsave(&usbvision->queue_lock, lock_flags);
852         list_add_tail(&usbvision->frame[vb->index].frame, &usbvision->inqueue);
853         spin_unlock_irqrestore(&usbvision->queue_lock, lock_flags);
854
855         return 0;
856 }
857
858 static int vidioc_dqbuf (struct file *file, void *priv, struct v4l2_buffer *vb)
859 {
860         struct usb_usbvision *usbvision = video_drvdata(file);
861         int ret;
862         struct usbvision_frame *f;
863         unsigned long lock_flags;
864
865         if (vb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
866                 return -EINVAL;
867
868         if (list_empty(&(usbvision->outqueue))) {
869                 if (usbvision->streaming == Stream_Idle)
870                         return -EINVAL;
871                 ret = wait_event_interruptible
872                         (usbvision->wait_frame,
873                          !list_empty(&(usbvision->outqueue)));
874                 if (ret)
875                         return ret;
876         }
877
878         spin_lock_irqsave(&usbvision->queue_lock, lock_flags);
879         f = list_entry(usbvision->outqueue.next,
880                        struct usbvision_frame, frame);
881         list_del(usbvision->outqueue.next);
882         spin_unlock_irqrestore(&usbvision->queue_lock, lock_flags);
883
884         f->grabstate = FrameState_Unused;
885
886         vb->memory = V4L2_MEMORY_MMAP;
887         vb->flags = V4L2_BUF_FLAG_MAPPED |
888                 V4L2_BUF_FLAG_QUEUED |
889                 V4L2_BUF_FLAG_DONE;
890         vb->index = f->index;
891         vb->sequence = f->sequence;
892         vb->timestamp = f->timestamp;
893         vb->field = V4L2_FIELD_NONE;
894         vb->bytesused = f->scanlength;
895
896         return 0;
897 }
898
899 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
900 {
901         struct usb_usbvision *usbvision = video_drvdata(file);
902         int b=V4L2_BUF_TYPE_VIDEO_CAPTURE;
903
904         usbvision->streaming = Stream_On;
905         call_i2c_clients(usbvision,VIDIOC_STREAMON , &b);
906
907         return 0;
908 }
909
910 static int vidioc_streamoff(struct file *file,
911                             void *priv, enum v4l2_buf_type type)
912 {
913         struct usb_usbvision *usbvision = video_drvdata(file);
914         int b=V4L2_BUF_TYPE_VIDEO_CAPTURE;
915
916         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
917                 return -EINVAL;
918
919         if(usbvision->streaming == Stream_On) {
920                 usbvision_stream_interrupt(usbvision);
921                 /* Stop all video streamings */
922                 call_i2c_clients(usbvision,VIDIOC_STREAMOFF , &b);
923         }
924         usbvision_empty_framequeues(usbvision);
925
926         return 0;
927 }
928
929 static int vidioc_enum_fmt_vid_cap (struct file *file, void  *priv,
930                                         struct v4l2_fmtdesc *vfd)
931 {
932         if(vfd->index>=USBVISION_SUPPORTED_PALETTES-1) {
933                 return -EINVAL;
934         }
935         vfd->flags = 0;
936         vfd->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
937         strcpy(vfd->description,usbvision_v4l2_format[vfd->index].desc);
938         vfd->pixelformat = usbvision_v4l2_format[vfd->index].format;
939         memset(vfd->reserved, 0, sizeof(vfd->reserved));
940         return 0;
941 }
942
943 static int vidioc_g_fmt_vid_cap (struct file *file, void *priv,
944                                         struct v4l2_format *vf)
945 {
946         struct usb_usbvision *usbvision = video_drvdata(file);
947         vf->fmt.pix.width = usbvision->curwidth;
948         vf->fmt.pix.height = usbvision->curheight;
949         vf->fmt.pix.pixelformat = usbvision->palette.format;
950         vf->fmt.pix.bytesperline =
951                 usbvision->curwidth*usbvision->palette.bytes_per_pixel;
952         vf->fmt.pix.sizeimage = vf->fmt.pix.bytesperline*usbvision->curheight;
953         vf->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
954         vf->fmt.pix.field = V4L2_FIELD_NONE; /* Always progressive image */
955
956         return 0;
957 }
958
959 static int vidioc_try_fmt_vid_cap (struct file *file, void *priv,
960                                struct v4l2_format *vf)
961 {
962         struct usb_usbvision *usbvision = video_drvdata(file);
963         int formatIdx;
964
965         /* Find requested format in available ones */
966         for(formatIdx=0;formatIdx<USBVISION_SUPPORTED_PALETTES;formatIdx++) {
967                 if(vf->fmt.pix.pixelformat ==
968                    usbvision_v4l2_format[formatIdx].format) {
969                         usbvision->palette = usbvision_v4l2_format[formatIdx];
970                         break;
971                 }
972         }
973         /* robustness */
974         if(formatIdx == USBVISION_SUPPORTED_PALETTES) {
975                 return -EINVAL;
976         }
977         RESTRICT_TO_RANGE(vf->fmt.pix.width, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
978         RESTRICT_TO_RANGE(vf->fmt.pix.height, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);
979
980         vf->fmt.pix.bytesperline = vf->fmt.pix.width*
981                 usbvision->palette.bytes_per_pixel;
982         vf->fmt.pix.sizeimage = vf->fmt.pix.bytesperline*vf->fmt.pix.height;
983
984         return 0;
985 }
986
987 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
988                                struct v4l2_format *vf)
989 {
990         struct usb_usbvision *usbvision = video_drvdata(file);
991         int ret;
992
993         if( 0 != (ret=vidioc_try_fmt_vid_cap (file, priv, vf)) ) {
994                 return ret;
995         }
996
997         /* stop io in case it is already in progress */
998         if(usbvision->streaming == Stream_On) {
999                 if ((ret = usbvision_stream_interrupt(usbvision)))
1000                         return ret;
1001         }
1002         usbvision_frames_free(usbvision);
1003         usbvision_empty_framequeues(usbvision);
1004
1005         usbvision->curFrame = NULL;
1006
1007         /* by now we are committed to the new data... */
1008         mutex_lock(&usbvision->lock);
1009         usbvision_set_output(usbvision, vf->fmt.pix.width, vf->fmt.pix.height);
1010         mutex_unlock(&usbvision->lock);
1011
1012         return 0;
1013 }
1014
1015 static ssize_t usbvision_v4l2_read(struct file *file, char __user *buf,
1016                       size_t count, loff_t *ppos)
1017 {
1018         struct usb_usbvision *usbvision = video_drvdata(file);
1019         int noblock = file->f_flags & O_NONBLOCK;
1020         unsigned long lock_flags;
1021
1022         int ret,i;
1023         struct usbvision_frame *frame;
1024
1025         PDEBUG(DBG_IO, "%s: %ld bytes, noblock=%d", __func__,
1026                (unsigned long)count, noblock);
1027
1028         if (!USBVISION_IS_OPERATIONAL(usbvision) || (buf == NULL))
1029                 return -EFAULT;
1030
1031         /* This entry point is compatible with the mmap routines
1032            so that a user can do either VIDIOC_QBUF/VIDIOC_DQBUF
1033            to get frames or call read on the device. */
1034         if(!usbvision->num_frames) {
1035                 /* First, allocate some frames to work with
1036                    if this has not been done with VIDIOC_REQBUF */
1037                 usbvision_frames_free(usbvision);
1038                 usbvision_empty_framequeues(usbvision);
1039                 usbvision_frames_alloc(usbvision,USBVISION_NUMFRAMES);
1040         }
1041
1042         if(usbvision->streaming != Stream_On) {
1043                 /* no stream is running, make it running ! */
1044                 usbvision->streaming = Stream_On;
1045                 call_i2c_clients(usbvision,VIDIOC_STREAMON , NULL);
1046         }
1047
1048         /* Then, enqueue as many frames as possible
1049            (like a user of VIDIOC_QBUF would do) */
1050         for(i=0;i<usbvision->num_frames;i++) {
1051                 frame = &usbvision->frame[i];
1052                 if(frame->grabstate == FrameState_Unused) {
1053                         /* Mark it as ready and enqueue frame */
1054                         frame->grabstate = FrameState_Ready;
1055                         frame->scanstate = ScanState_Scanning;
1056                         /* Accumulated in usbvision_parse_data() */
1057                         frame->scanlength = 0;
1058
1059                         /* set v4l2_format index */
1060                         frame->v4l2_format = usbvision->palette;
1061
1062                         spin_lock_irqsave(&usbvision->queue_lock, lock_flags);
1063                         list_add_tail(&frame->frame, &usbvision->inqueue);
1064                         spin_unlock_irqrestore(&usbvision->queue_lock,
1065                                                lock_flags);
1066                 }
1067         }
1068
1069         /* Then try to steal a frame (like a VIDIOC_DQBUF would do) */
1070         if (list_empty(&(usbvision->outqueue))) {
1071                 if(noblock)
1072                         return -EAGAIN;
1073
1074                 ret = wait_event_interruptible
1075                         (usbvision->wait_frame,
1076                          !list_empty(&(usbvision->outqueue)));
1077                 if (ret)
1078                         return ret;
1079         }
1080
1081         spin_lock_irqsave(&usbvision->queue_lock, lock_flags);
1082         frame = list_entry(usbvision->outqueue.next,
1083                            struct usbvision_frame, frame);
1084         list_del(usbvision->outqueue.next);
1085         spin_unlock_irqrestore(&usbvision->queue_lock, lock_flags);
1086
1087         /* An error returns an empty frame */
1088         if (frame->grabstate == FrameState_Error) {
1089                 frame->bytes_read = 0;
1090                 return 0;
1091         }
1092
1093         PDEBUG(DBG_IO, "%s: frmx=%d, bytes_read=%ld, scanlength=%ld",
1094                __func__,
1095                frame->index, frame->bytes_read, frame->scanlength);
1096
1097         /* copy bytes to user space; we allow for partials reads */
1098         if ((count + frame->bytes_read) > (unsigned long)frame->scanlength)
1099                 count = frame->scanlength - frame->bytes_read;
1100
1101         if (copy_to_user(buf, frame->data + frame->bytes_read, count)) {
1102                 return -EFAULT;
1103         }
1104
1105         frame->bytes_read += count;
1106         PDEBUG(DBG_IO, "%s: {copy} count used=%ld, new bytes_read=%ld",
1107                __func__,
1108                (unsigned long)count, frame->bytes_read);
1109
1110         /* For now, forget the frame if it has not been read in one shot. */
1111 /*      if (frame->bytes_read >= frame->scanlength) {// All data has been read */
1112                 frame->bytes_read = 0;
1113
1114                 /* Mark it as available to be used again. */
1115                 frame->grabstate = FrameState_Unused;
1116 /*      } */
1117
1118         return count;
1119 }
1120
1121 static int usbvision_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
1122 {
1123         unsigned long size = vma->vm_end - vma->vm_start,
1124                 start = vma->vm_start;
1125         void *pos;
1126         u32 i;
1127         struct usb_usbvision *usbvision = video_drvdata(file);
1128
1129         PDEBUG(DBG_MMAP, "mmap");
1130
1131         mutex_lock(&usbvision->lock);
1132
1133         if (!USBVISION_IS_OPERATIONAL(usbvision)) {
1134                 mutex_unlock(&usbvision->lock);
1135                 return -EFAULT;
1136         }
1137
1138         if (!(vma->vm_flags & VM_WRITE) ||
1139             size != PAGE_ALIGN(usbvision->max_frame_size)) {
1140                 mutex_unlock(&usbvision->lock);
1141                 return -EINVAL;
1142         }
1143
1144         for (i = 0; i < usbvision->num_frames; i++) {
1145                 if (((PAGE_ALIGN(usbvision->max_frame_size)*i) >> PAGE_SHIFT) ==
1146                     vma->vm_pgoff)
1147                         break;
1148         }
1149         if (i == usbvision->num_frames) {
1150                 PDEBUG(DBG_MMAP,
1151                        "mmap: user supplied mapping address is out of range");
1152                 mutex_unlock(&usbvision->lock);
1153                 return -EINVAL;
1154         }
1155
1156         /* VM_IO is eventually going to replace PageReserved altogether */
1157         vma->vm_flags |= VM_IO;
1158         vma->vm_flags |= VM_RESERVED;   /* avoid to swap out this VMA */
1159
1160         pos = usbvision->frame[i].data;
1161         while (size > 0) {
1162
1163                 if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
1164                         PDEBUG(DBG_MMAP, "mmap: vm_insert_page failed");
1165                         mutex_unlock(&usbvision->lock);
1166                         return -EAGAIN;
1167                 }
1168                 start += PAGE_SIZE;
1169                 pos += PAGE_SIZE;
1170                 size -= PAGE_SIZE;
1171         }
1172
1173         mutex_unlock(&usbvision->lock);
1174         return 0;
1175 }
1176
1177
1178 /*
1179  * Here comes the stuff for radio on usbvision based devices
1180  *
1181  */
1182 static int usbvision_radio_open(struct file *file)
1183 {
1184         struct usb_usbvision *usbvision = video_drvdata(file);
1185         int errCode = 0;
1186
1187         PDEBUG(DBG_IO, "%s:", __func__);
1188
1189         mutex_lock(&usbvision->lock);
1190
1191         if (usbvision->user) {
1192                 err("%s: Someone tried to open an already opened USBVision Radio!", __func__);
1193                 errCode = -EBUSY;
1194         }
1195         else {
1196                 if(PowerOnAtOpen) {
1197                         usbvision_reset_powerOffTimer(usbvision);
1198                         if (usbvision->power == 0) {
1199                                 usbvision_power_on(usbvision);
1200                                 usbvision_i2c_register(usbvision);
1201                         }
1202                 }
1203
1204                 /* Alternate interface 1 is is the biggest frame size */
1205                 errCode = usbvision_set_alternate(usbvision);
1206                 if (errCode < 0) {
1207                         usbvision->last_error = errCode;
1208                         errCode = -EBUSY;
1209                         goto out;
1210                 }
1211
1212                 // If so far no errors then we shall start the radio
1213                 usbvision->radio = 1;
1214                 call_i2c_clients(usbvision,AUDC_SET_RADIO,&usbvision->tuner_type);
1215                 usbvision_set_audio(usbvision, USBVISION_AUDIO_RADIO);
1216                 usbvision->user++;
1217         }
1218
1219         if (errCode) {
1220                 if (PowerOnAtOpen) {
1221                         usbvision_i2c_unregister(usbvision);
1222                         usbvision_power_off(usbvision);
1223                         usbvision->initialized = 0;
1224                 }
1225         }
1226 out:
1227         mutex_unlock(&usbvision->lock);
1228         return errCode;
1229 }
1230
1231
1232 static int usbvision_radio_close(struct file *file)
1233 {
1234         struct usb_usbvision *usbvision = video_drvdata(file);
1235         int errCode = 0;
1236
1237         PDEBUG(DBG_IO, "");
1238
1239         mutex_lock(&usbvision->lock);
1240
1241         /* Set packet size to 0 */
1242         usbvision->ifaceAlt=0;
1243         errCode = usb_set_interface(usbvision->dev, usbvision->iface,
1244                                     usbvision->ifaceAlt);
1245
1246         usbvision_audio_off(usbvision);
1247         usbvision->radio=0;
1248         usbvision->user--;
1249
1250         if (PowerOnAtOpen) {
1251                 usbvision_set_powerOffTimer(usbvision);
1252                 usbvision->initialized = 0;
1253         }
1254
1255         mutex_unlock(&usbvision->lock);
1256
1257         if (usbvision->remove_pending) {
1258                 printk(KERN_INFO "%s: Final disconnect\n", __func__);
1259                 usbvision_release(usbvision);
1260         }
1261
1262         PDEBUG(DBG_IO, "success");
1263         return errCode;
1264 }
1265
1266 /*
1267  * Here comes the stuff for vbi on usbvision based devices
1268  *
1269  */
1270 static int usbvision_vbi_open(struct file *file)
1271 {
1272         /* TODO */
1273         return -ENODEV;
1274 }
1275
1276 static int usbvision_vbi_close(struct file *file)
1277 {
1278         /* TODO */
1279         return -ENODEV;
1280 }
1281
1282 static long usbvision_do_vbi_ioctl(struct file *file,
1283                                  unsigned int cmd, void *arg)
1284 {
1285         /* TODO */
1286         return -ENOIOCTLCMD;
1287 }
1288
1289 static long usbvision_vbi_ioctl(struct file *file,
1290                        unsigned int cmd, unsigned long arg)
1291 {
1292         return video_usercopy(file, cmd, arg, usbvision_do_vbi_ioctl);
1293 }
1294
1295
1296 //
1297 // Video registration stuff
1298 //
1299
1300 // Video template
1301 static const struct v4l2_file_operations usbvision_fops = {
1302         .owner             = THIS_MODULE,
1303         .open           = usbvision_v4l2_open,
1304         .release        = usbvision_v4l2_close,
1305         .read           = usbvision_v4l2_read,
1306         .mmap           = usbvision_v4l2_mmap,
1307         .ioctl          = video_ioctl2,
1308 /*      .poll          = video_poll, */
1309 };
1310
1311 static const struct v4l2_ioctl_ops usbvision_ioctl_ops = {
1312         .vidioc_querycap      = vidioc_querycap,
1313         .vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
1314         .vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
1315         .vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
1316         .vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
1317         .vidioc_reqbufs       = vidioc_reqbufs,
1318         .vidioc_querybuf      = vidioc_querybuf,
1319         .vidioc_qbuf          = vidioc_qbuf,
1320         .vidioc_dqbuf         = vidioc_dqbuf,
1321         .vidioc_s_std         = vidioc_s_std,
1322         .vidioc_enum_input    = vidioc_enum_input,
1323         .vidioc_g_input       = vidioc_g_input,
1324         .vidioc_s_input       = vidioc_s_input,
1325         .vidioc_queryctrl     = vidioc_queryctrl,
1326         .vidioc_g_audio       = vidioc_g_audio,
1327         .vidioc_s_audio       = vidioc_s_audio,
1328         .vidioc_g_ctrl        = vidioc_g_ctrl,
1329         .vidioc_s_ctrl        = vidioc_s_ctrl,
1330         .vidioc_streamon      = vidioc_streamon,
1331         .vidioc_streamoff     = vidioc_streamoff,
1332 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1333 /*      .vidiocgmbuf          = vidiocgmbuf, */
1334 #endif
1335         .vidioc_g_tuner       = vidioc_g_tuner,
1336         .vidioc_s_tuner       = vidioc_s_tuner,
1337         .vidioc_g_frequency   = vidioc_g_frequency,
1338         .vidioc_s_frequency   = vidioc_s_frequency,
1339 #ifdef CONFIG_VIDEO_ADV_DEBUG
1340         .vidioc_g_register    = vidioc_g_register,
1341         .vidioc_s_register    = vidioc_s_register,
1342 #endif
1343 };
1344
1345 static struct video_device usbvision_video_template = {
1346         .fops           = &usbvision_fops,
1347         .ioctl_ops      = &usbvision_ioctl_ops,
1348         .name           = "usbvision-video",
1349         .release        = video_device_release,
1350         .minor          = -1,
1351         .tvnorms              = USBVISION_NORMS,
1352         .current_norm         = V4L2_STD_PAL
1353 };
1354
1355
1356 // Radio template
1357 static const struct v4l2_file_operations usbvision_radio_fops = {
1358         .owner             = THIS_MODULE,
1359         .open           = usbvision_radio_open,
1360         .release        = usbvision_radio_close,
1361         .ioctl          = video_ioctl2,
1362 };
1363
1364 static const struct v4l2_ioctl_ops usbvision_radio_ioctl_ops = {
1365         .vidioc_querycap      = vidioc_querycap,
1366         .vidioc_enum_input    = vidioc_enum_input,
1367         .vidioc_g_input       = vidioc_g_input,
1368         .vidioc_s_input       = vidioc_s_input,
1369         .vidioc_queryctrl     = vidioc_queryctrl,
1370         .vidioc_g_audio       = vidioc_g_audio,
1371         .vidioc_s_audio       = vidioc_s_audio,
1372         .vidioc_g_ctrl        = vidioc_g_ctrl,
1373         .vidioc_s_ctrl        = vidioc_s_ctrl,
1374         .vidioc_g_tuner       = vidioc_g_tuner,
1375         .vidioc_s_tuner       = vidioc_s_tuner,
1376         .vidioc_g_frequency   = vidioc_g_frequency,
1377         .vidioc_s_frequency   = vidioc_s_frequency,
1378 };
1379
1380 static struct video_device usbvision_radio_template = {
1381         .fops           = &usbvision_radio_fops,
1382         .name           = "usbvision-radio",
1383         .release        = video_device_release,
1384         .minor          = -1,
1385         .ioctl_ops      = &usbvision_radio_ioctl_ops,
1386
1387         .tvnorms              = USBVISION_NORMS,
1388         .current_norm         = V4L2_STD_PAL
1389 };
1390
1391 // vbi template
1392 static const struct v4l2_file_operations usbvision_vbi_fops = {
1393         .owner             = THIS_MODULE,
1394         .open           = usbvision_vbi_open,
1395         .release        = usbvision_vbi_close,
1396         .ioctl          = usbvision_vbi_ioctl,
1397 };
1398
1399 static struct video_device usbvision_vbi_template=
1400 {
1401         .fops           = &usbvision_vbi_fops,
1402         .release        = video_device_release,
1403         .name           = "usbvision-vbi",
1404         .minor          = -1,
1405 };
1406
1407
1408 static struct video_device *usbvision_vdev_init(struct usb_usbvision *usbvision,
1409                                         struct video_device *vdev_template,
1410                                         char *name)
1411 {
1412         struct usb_device *usb_dev = usbvision->dev;
1413         struct video_device *vdev;
1414
1415         if (usb_dev == NULL) {
1416                 err("%s: usbvision->dev is not set", __func__);
1417                 return NULL;
1418         }
1419
1420         vdev = video_device_alloc();
1421         if (NULL == vdev) {
1422                 return NULL;
1423         }
1424         *vdev = *vdev_template;
1425 //      vdev->minor   = -1;
1426         vdev->parent  = &usb_dev->dev;
1427         snprintf(vdev->name, sizeof(vdev->name), "%s", name);
1428         video_set_drvdata(vdev, usbvision);
1429         return vdev;
1430 }
1431
1432 // unregister video4linux devices
1433 static void usbvision_unregister_video(struct usb_usbvision *usbvision)
1434 {
1435         // vbi Device:
1436         if (usbvision->vbi) {
1437                 PDEBUG(DBG_PROBE, "unregister /dev/vbi%d [v4l2]",
1438                        usbvision->vbi->num);
1439                 if (usbvision->vbi->minor != -1) {
1440                         video_unregister_device(usbvision->vbi);
1441                 } else {
1442                         video_device_release(usbvision->vbi);
1443                 }
1444                 usbvision->vbi = NULL;
1445         }
1446
1447         // Radio Device:
1448         if (usbvision->rdev) {
1449                 PDEBUG(DBG_PROBE, "unregister /dev/radio%d [v4l2]",
1450                        usbvision->rdev->num);
1451                 if (usbvision->rdev->minor != -1) {
1452                         video_unregister_device(usbvision->rdev);
1453                 } else {
1454                         video_device_release(usbvision->rdev);
1455                 }
1456                 usbvision->rdev = NULL;
1457         }
1458
1459         // Video Device:
1460         if (usbvision->vdev) {
1461                 PDEBUG(DBG_PROBE, "unregister /dev/video%d [v4l2]",
1462                        usbvision->vdev->num);
1463                 if (usbvision->vdev->minor != -1) {
1464                         video_unregister_device(usbvision->vdev);
1465                 } else {
1466                         video_device_release(usbvision->vdev);
1467                 }
1468                 usbvision->vdev = NULL;
1469         }
1470 }
1471
1472 // register video4linux devices
1473 static int __devinit usbvision_register_video(struct usb_usbvision *usbvision)
1474 {
1475         // Video Device:
1476         usbvision->vdev = usbvision_vdev_init(usbvision,
1477                                               &usbvision_video_template,
1478                                               "USBVision Video");
1479         if (usbvision->vdev == NULL) {
1480                 goto err_exit;
1481         }
1482         if (video_register_device(usbvision->vdev,
1483                                   VFL_TYPE_GRABBER,
1484                                   video_nr)<0) {
1485                 goto err_exit;
1486         }
1487         printk(KERN_INFO "USBVision[%d]: registered USBVision Video device /dev/video%d [v4l2]\n",
1488                usbvision->nr, usbvision->vdev->num);
1489
1490         // Radio Device:
1491         if (usbvision_device_data[usbvision->DevModel].Radio) {
1492                 // usbvision has radio
1493                 usbvision->rdev = usbvision_vdev_init(usbvision,
1494                                                       &usbvision_radio_template,
1495                                                       "USBVision Radio");
1496                 if (usbvision->rdev == NULL) {
1497                         goto err_exit;
1498                 }
1499                 if (video_register_device(usbvision->rdev,
1500                                           VFL_TYPE_RADIO,
1501                                           radio_nr)<0) {
1502                         goto err_exit;
1503                 }
1504                 printk(KERN_INFO "USBVision[%d]: registered USBVision Radio device /dev/radio%d [v4l2]\n",
1505                        usbvision->nr, usbvision->rdev->num);
1506         }
1507         // vbi Device:
1508         if (usbvision_device_data[usbvision->DevModel].vbi) {
1509                 usbvision->vbi = usbvision_vdev_init(usbvision,
1510                                                      &usbvision_vbi_template,
1511                                                      "USBVision VBI");
1512                 if (usbvision->vdev == NULL) {
1513                         goto err_exit;
1514                 }
1515                 if (video_register_device(usbvision->vbi,
1516                                           VFL_TYPE_VBI,
1517                                           vbi_nr)<0) {
1518                         goto err_exit;
1519                 }
1520                 printk(KERN_INFO "USBVision[%d]: registered USBVision VBI device /dev/vbi%d [v4l2] (Not Working Yet!)\n",
1521                        usbvision->nr, usbvision->vbi->num);
1522         }
1523         // all done
1524         return 0;
1525
1526  err_exit:
1527         err("USBVision[%d]: video_register_device() failed", usbvision->nr);
1528         usbvision_unregister_video(usbvision);
1529         return -1;
1530 }
1531
1532 /*
1533  * usbvision_alloc()
1534  *
1535  * This code allocates the struct usb_usbvision.
1536  * It is filled with default values.
1537  *
1538  * Returns NULL on error, a pointer to usb_usbvision else.
1539  *
1540  */
1541 static struct usb_usbvision *usbvision_alloc(struct usb_device *dev)
1542 {
1543         struct usb_usbvision *usbvision;
1544
1545         if ((usbvision = kzalloc(sizeof(struct usb_usbvision), GFP_KERNEL)) ==
1546             NULL) {
1547                 goto err_exit;
1548         }
1549
1550         usbvision->dev = dev;
1551
1552         mutex_init(&usbvision->lock);   /* available */
1553
1554         // prepare control urb for control messages during interrupts
1555         usbvision->ctrlUrb = usb_alloc_urb(USBVISION_URB_FRAMES, GFP_KERNEL);
1556         if (usbvision->ctrlUrb == NULL) {
1557                 goto err_exit;
1558         }
1559         init_waitqueue_head(&usbvision->ctrlUrb_wq);
1560
1561         usbvision_init_powerOffTimer(usbvision);
1562
1563         return usbvision;
1564
1565 err_exit:
1566         if (usbvision && usbvision->ctrlUrb) {
1567                 usb_free_urb(usbvision->ctrlUrb);
1568         }
1569         if (usbvision) {
1570                 kfree(usbvision);
1571         }
1572         return NULL;
1573 }
1574
1575 /*
1576  * usbvision_release()
1577  *
1578  * This code does final release of struct usb_usbvision. This happens
1579  * after the device is disconnected -and- all clients closed their files.
1580  *
1581  */
1582 static void usbvision_release(struct usb_usbvision *usbvision)
1583 {
1584         PDEBUG(DBG_PROBE, "");
1585
1586         mutex_lock(&usbvision->lock);
1587
1588         usbvision_reset_powerOffTimer(usbvision);
1589
1590         usbvision->initialized = 0;
1591
1592         mutex_unlock(&usbvision->lock);
1593
1594         usbvision_remove_sysfs(usbvision->vdev);
1595         usbvision_unregister_video(usbvision);
1596
1597         if (usbvision->ctrlUrb) {
1598                 usb_free_urb(usbvision->ctrlUrb);
1599         }
1600
1601         kfree(usbvision);
1602
1603         PDEBUG(DBG_PROBE, "success");
1604 }
1605
1606
1607 /*********************** usb interface **********************************/
1608
1609 static void usbvision_configure_video(struct usb_usbvision *usbvision)
1610 {
1611         int model;
1612
1613         if (usbvision == NULL)
1614                 return;
1615
1616         model = usbvision->DevModel;
1617         usbvision->palette = usbvision_v4l2_format[2]; // V4L2_PIX_FMT_RGB24;
1618
1619         if (usbvision_device_data[usbvision->DevModel].Vin_Reg2_override) {
1620                 usbvision->Vin_Reg2_Preset =
1621                         usbvision_device_data[usbvision->DevModel].Vin_Reg2;
1622         } else {
1623                 usbvision->Vin_Reg2_Preset = 0;
1624         }
1625
1626         usbvision->tvnormId = usbvision_device_data[model].VideoNorm;
1627
1628         usbvision->video_inputs = usbvision_device_data[model].VideoChannels;
1629         usbvision->ctl_input = 0;
1630
1631         /* This should be here to make i2c clients to be able to register */
1632         /* first switch off audio */
1633         usbvision_audio_off(usbvision);
1634         if (!PowerOnAtOpen) {
1635                 /* and then power up the noisy tuner */
1636                 usbvision_power_on(usbvision);
1637                 usbvision_i2c_register(usbvision);
1638         }
1639 }
1640
1641 /*
1642  * usbvision_probe()
1643  *
1644  * This procedure queries device descriptor and accepts the interface
1645  * if it looks like USBVISION video device
1646  *
1647  */
1648 static int __devinit usbvision_probe(struct usb_interface *intf,
1649                                      const struct usb_device_id *devid)
1650 {
1651         struct usb_device *dev = usb_get_dev(interface_to_usbdev(intf));
1652         struct usb_interface *uif;
1653         __u8 ifnum = intf->altsetting->desc.bInterfaceNumber;
1654         const struct usb_host_interface *interface;
1655         struct usb_usbvision *usbvision = NULL;
1656         const struct usb_endpoint_descriptor *endpoint;
1657         int model,i;
1658
1659         PDEBUG(DBG_PROBE, "VID=%#04x, PID=%#04x, ifnum=%u",
1660                                 dev->descriptor.idVendor,
1661                                 dev->descriptor.idProduct, ifnum);
1662
1663         model = devid->driver_info;
1664         if ( (model<0) || (model>=usbvision_device_data_size) ) {
1665                 PDEBUG(DBG_PROBE, "model out of bounds %d",model);
1666                 return -ENODEV;
1667         }
1668         printk(KERN_INFO "%s: %s found\n", __func__,
1669                                 usbvision_device_data[model].ModelString);
1670
1671         if (usbvision_device_data[model].Interface >= 0) {
1672                 interface = &dev->actconfig->interface[usbvision_device_data[model].Interface]->altsetting[0];
1673         } else {
1674                 interface = &dev->actconfig->interface[ifnum]->altsetting[0];
1675         }
1676         endpoint = &interface->endpoint[1].desc;
1677         if (!usb_endpoint_xfer_isoc(endpoint)) {
1678                 err("%s: interface %d. has non-ISO endpoint!",
1679                     __func__, ifnum);
1680                 err("%s: Endpoint attributes %d",
1681                     __func__, endpoint->bmAttributes);
1682                 return -ENODEV;
1683         }
1684         if (usb_endpoint_dir_out(endpoint)) {
1685                 err("%s: interface %d. has ISO OUT endpoint!",
1686                     __func__, ifnum);
1687                 return -ENODEV;
1688         }
1689
1690         if ((usbvision = usbvision_alloc(dev)) == NULL) {
1691                 err("%s: couldn't allocate USBVision struct", __func__);
1692                 return -ENOMEM;
1693         }
1694
1695         if (dev->descriptor.bNumConfigurations > 1) {
1696                 usbvision->bridgeType = BRIDGE_NT1004;
1697         } else if (model == DAZZLE_DVC_90_REV_1_SECAM) {
1698                 usbvision->bridgeType = BRIDGE_NT1005;
1699         } else {
1700                 usbvision->bridgeType = BRIDGE_NT1003;
1701         }
1702         PDEBUG(DBG_PROBE, "bridgeType %d", usbvision->bridgeType);
1703
1704         mutex_lock(&usbvision->lock);
1705
1706         /* compute alternate max packet sizes */
1707         uif = dev->actconfig->interface[0];
1708
1709         usbvision->num_alt=uif->num_altsetting;
1710         PDEBUG(DBG_PROBE, "Alternate settings: %i",usbvision->num_alt);
1711         usbvision->alt_max_pkt_size = kmalloc(32*
1712                                               usbvision->num_alt,GFP_KERNEL);
1713         if (usbvision->alt_max_pkt_size == NULL) {
1714                 err("usbvision: out of memory!\n");
1715                 mutex_unlock(&usbvision->lock);
1716                 return -ENOMEM;
1717         }
1718
1719         for (i = 0; i < usbvision->num_alt ; i++) {
1720                 u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.
1721                                       wMaxPacketSize);
1722                 usbvision->alt_max_pkt_size[i] =
1723                         (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
1724                 PDEBUG(DBG_PROBE, "Alternate setting %i, max size= %i",i,
1725                        usbvision->alt_max_pkt_size[i]);
1726         }
1727
1728
1729         usbvision->nr = usbvision_nr++;
1730
1731         usbvision->have_tuner = usbvision_device_data[model].Tuner;
1732         if (usbvision->have_tuner) {
1733                 usbvision->tuner_type = usbvision_device_data[model].TunerType;
1734         }
1735
1736         usbvision->tuner_addr = ADDR_UNSET;
1737
1738         usbvision->DevModel = model;
1739         usbvision->remove_pending = 0;
1740         usbvision->iface = ifnum;
1741         usbvision->ifaceAlt = 0;
1742         usbvision->video_endp = endpoint->bEndpointAddress;
1743         usbvision->isocPacketSize = 0;
1744         usbvision->usb_bandwidth = 0;
1745         usbvision->user = 0;
1746         usbvision->streaming = Stream_Off;
1747         usbvision_register_video(usbvision);
1748         usbvision_configure_video(usbvision);
1749         mutex_unlock(&usbvision->lock);
1750
1751
1752         usb_set_intfdata (intf, usbvision);
1753         usbvision_create_sysfs(usbvision->vdev);
1754
1755         PDEBUG(DBG_PROBE, "success");
1756         return 0;
1757 }
1758
1759
1760 /*
1761  * usbvision_disconnect()
1762  *
1763  * This procedure stops all driver activity, deallocates interface-private
1764  * structure (pointed by 'ptr') and after that driver should be removable
1765  * with no ill consequences.
1766  *
1767  */
1768 static void __devexit usbvision_disconnect(struct usb_interface *intf)
1769 {
1770         struct usb_usbvision *usbvision = usb_get_intfdata(intf);
1771
1772         PDEBUG(DBG_PROBE, "");
1773
1774         if (usbvision == NULL) {
1775                 err("%s: usb_get_intfdata() failed", __func__);
1776                 return;
1777         }
1778         usb_set_intfdata (intf, NULL);
1779
1780         mutex_lock(&usbvision->lock);
1781
1782         // At this time we ask to cancel outstanding URBs
1783         usbvision_stop_isoc(usbvision);
1784
1785         if (usbvision->power) {
1786                 usbvision_i2c_unregister(usbvision);
1787                 usbvision_power_off(usbvision);
1788         }
1789         usbvision->remove_pending = 1;  // Now all ISO data will be ignored
1790
1791         usb_put_dev(usbvision->dev);
1792         usbvision->dev = NULL;  // USB device is no more
1793
1794         mutex_unlock(&usbvision->lock);
1795
1796         if (usbvision->user) {
1797                 printk(KERN_INFO "%s: In use, disconnect pending\n",
1798                        __func__);
1799                 wake_up_interruptible(&usbvision->wait_frame);
1800                 wake_up_interruptible(&usbvision->wait_stream);
1801         } else {
1802                 usbvision_release(usbvision);
1803         }
1804
1805         PDEBUG(DBG_PROBE, "success");
1806 }
1807
1808 static struct usb_driver usbvision_driver = {
1809         .name           = "usbvision",
1810         .id_table       = usbvision_table,
1811         .probe          = usbvision_probe,
1812         .disconnect     = usbvision_disconnect
1813 };
1814
1815 /*
1816  * usbvision_init()
1817  *
1818  * This code is run to initialize the driver.
1819  *
1820  */
1821 static int __init usbvision_init(void)
1822 {
1823         int errCode;
1824
1825         PDEBUG(DBG_PROBE, "");
1826
1827         PDEBUG(DBG_IO,  "IO      debugging is enabled [video]");
1828         PDEBUG(DBG_PROBE, "PROBE   debugging is enabled [video]");
1829         PDEBUG(DBG_MMAP, "MMAP    debugging is enabled [video]");
1830
1831         /* disable planar mode support unless compression enabled */
1832         if (isocMode != ISOC_MODE_COMPRESS ) {
1833                 // FIXME : not the right way to set supported flag
1834                 usbvision_v4l2_format[6].supported = 0; // V4L2_PIX_FMT_YVU420
1835                 usbvision_v4l2_format[7].supported = 0; // V4L2_PIX_FMT_YUV422P
1836         }
1837
1838         errCode = usb_register(&usbvision_driver);
1839
1840         if (errCode == 0) {
1841                 printk(KERN_INFO DRIVER_DESC " : " USBVISION_VERSION_STRING "\n");
1842                 PDEBUG(DBG_PROBE, "success");
1843         }
1844         return errCode;
1845 }
1846
1847 static void __exit usbvision_exit(void)
1848 {
1849  PDEBUG(DBG_PROBE, "");
1850
1851  usb_deregister(&usbvision_driver);
1852  PDEBUG(DBG_PROBE, "success");
1853 }
1854
1855 module_init(usbvision_init);
1856 module_exit(usbvision_exit);
1857
1858 /*
1859  * Overrides for Emacs so that we follow Linus's tabbing style.
1860  * ---------------------------------------------------------------------------
1861  * Local variables:
1862  * c-basic-offset: 8
1863  * End:
1864  */