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