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