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