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