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