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