zr364xx.c 42.7 KB
Newer Older
1
/*
2
 * Zoran 364xx based USB webcam module version 0.73
3 4 5 6 7 8 9 10 11 12
 *
 * Allows you to use your USB webcam with V4L2 applications
 * This is still in heavy developpement !
 *
 * Copyright (C) 2004  Antoine Jacquet <royale@zerezo.com>
 * http://royale.zerezo.com/zr364xx/
 *
 * Heavily inspired by usb-skeleton.c, vicam.c, cpia.c and spca50x.c drivers
 * V4L2 version inspired by meye.c driver
 *
13 14
 * Some video buffer code by Lamarque based on s2255drv.c and vivi.c drivers.
 *
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


#include <linux/module.h>
32
#include <linux/version.h>
33 34 35 36 37
#include <linux/init.h>
#include <linux/usb.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
38
#include <linux/highmem.h>
39
#include <media/v4l2-common.h>
40
#include <media/v4l2-ioctl.h>
41
#include <media/videobuf-vmalloc.h>
42 43 44


/* Version Information */
45
#define DRIVER_VERSION "v0.73"
46
#define ZR364XX_VERSION_CODE KERNEL_VERSION(0, 7, 3)
47 48 49 50 51
#define DRIVER_AUTHOR "Antoine Jacquet, http://royale.zerezo.com/"
#define DRIVER_DESC "Zoran 364xx"


/* Camera */
52
#define FRAMES 1
53
#define MAX_FRAME_SIZE 200000
54 55 56
#define BUFFER_SIZE 0x1000
#define CTRL_TIMEOUT 500

57 58 59
#define ZR364XX_DEF_BUFS	4
#define ZR364XX_READ_IDLE	0
#define ZR364XX_READ_FRAME	1
60 61

/* Debug macro */
62 63 64 65 66 67
#define DBG(fmt, args...) \
	do { \
		if (debug) { \
			printk(KERN_INFO KBUILD_MODNAME " " fmt, ##args); \
		} \
	} while (0)
68

69 70 71 72 73 74 75
/*#define FULL_DEBUG 1*/
#ifdef FULL_DEBUG
#define _DBG DBG
#else
#define _DBG(fmt, args...)
#endif

76 77 78 79 80
/* Init methods, need to find nicer names for these
 * the exact names of the chipsets would be the best if someone finds it */
#define METHOD0 0
#define METHOD1 1
#define METHOD2 2
81
#define METHOD3 3
82 83 84


/* Module parameters */
85 86
static int debug;
static int mode;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114


/* Module parameters interface */
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level");
module_param(mode, int, 0644);
MODULE_PARM_DESC(mode, "0 = 320x240, 1 = 160x120, 2 = 640x480");


/* Devices supported by this driver
 * .driver_info contains the init method used by the camera */
static struct usb_device_id device_table[] = {
	{USB_DEVICE(0x08ca, 0x0109), .driver_info = METHOD0 },
	{USB_DEVICE(0x041e, 0x4024), .driver_info = METHOD0 },
	{USB_DEVICE(0x0d64, 0x0108), .driver_info = METHOD0 },
	{USB_DEVICE(0x0546, 0x3187), .driver_info = METHOD0 },
	{USB_DEVICE(0x0d64, 0x3108), .driver_info = METHOD0 },
	{USB_DEVICE(0x0595, 0x4343), .driver_info = METHOD0 },
	{USB_DEVICE(0x0bb0, 0x500d), .driver_info = METHOD0 },
	{USB_DEVICE(0x0feb, 0x2004), .driver_info = METHOD0 },
	{USB_DEVICE(0x055f, 0xb500), .driver_info = METHOD0 },
	{USB_DEVICE(0x08ca, 0x2062), .driver_info = METHOD2 },
	{USB_DEVICE(0x052b, 0x1a18), .driver_info = METHOD1 },
	{USB_DEVICE(0x04c8, 0x0729), .driver_info = METHOD0 },
	{USB_DEVICE(0x04f2, 0xa208), .driver_info = METHOD0 },
	{USB_DEVICE(0x0784, 0x0040), .driver_info = METHOD1 },
	{USB_DEVICE(0x06d6, 0x0034), .driver_info = METHOD0 },
	{USB_DEVICE(0x0a17, 0x0062), .driver_info = METHOD2 },
115
	{USB_DEVICE(0x06d6, 0x003b), .driver_info = METHOD0 },
116
	{USB_DEVICE(0x0a17, 0x004e), .driver_info = METHOD2 },
117
	{USB_DEVICE(0x041e, 0x405d), .driver_info = METHOD2 },
118
	{USB_DEVICE(0x08ca, 0x2102), .driver_info = METHOD3 },
119
	{USB_DEVICE(0x06d6, 0x003d), .driver_info = METHOD0 },
120 121 122 123 124
	{}			/* Terminating entry */
};

MODULE_DEVICE_TABLE(usb, device_table);

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
struct zr364xx_mode {
	u32 color;	/* output video color format */
	u32 brightness;	/* brightness */
};

/* frame structure */
struct zr364xx_framei {
	unsigned long ulState;	/* ulState:ZR364XX_READ_IDLE,
					   ZR364XX_READ_FRAME */
	void *lpvbits;		/* image data */
	unsigned long cur_size;	/* current data copied to it */
};

/* image buffer structure */
struct zr364xx_bufferi {
	unsigned long dwFrames;			/* number of frames in buffer */
	struct zr364xx_framei frame[FRAMES];	/* array of FRAME structures */
};

struct zr364xx_dmaqueue {
	struct list_head	active;
	struct zr364xx_camera	*cam;
};

struct zr364xx_pipeinfo {
	u32 transfer_size;
	u8 *transfer_buffer;
	u32 state;
	void *stream_urb;
	void *cam;	/* back pointer to zr364xx_camera struct */
	u32 err_count;
	u32 idx;
};

struct zr364xx_fmt {
	char *name;
	u32 fourcc;
	int depth;
};

/* image formats.  */
static const struct zr364xx_fmt formats[] = {
	{
		.name = "JPG",
		.fourcc = V4L2_PIX_FMT_JPEG,
		.depth = 24
	}
};
173 174 175 176 177 178 179

/* Camera stuff */
struct zr364xx_camera {
	struct usb_device *udev;	/* save off the usb device pointer */
	struct usb_interface *interface;/* the interface for this device */
	struct video_device *vdev;	/* v4l video device */
	int nb;
180
	struct zr364xx_bufferi		buffer;
181 182 183 184 185
	int skip;
	int width;
	int height;
	int method;
	struct mutex lock;
186
	struct mutex open_lock;
187
	int users;
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

	spinlock_t		slock;
	struct zr364xx_dmaqueue	vidq;
	int			resources;
	int			last_frame;
	int			cur_frame;
	unsigned long		frame_count;
	int			b_acquire;
	struct zr364xx_pipeinfo	pipe[1];

	u8			read_endpoint;

	const struct zr364xx_fmt *fmt;
	struct videobuf_queue	vb_vidq;
	enum v4l2_buf_type	type;
	struct zr364xx_mode	mode;
204 205
};

206 207 208 209 210 211
/* buffer for one video frame */
struct zr364xx_buffer {
	/* common v4l buffer stuff -- must be first */
	struct videobuf_buffer vb;
	const struct zr364xx_fmt *fmt;
};
212 213 214 215 216 217 218 219 220

/* function used to send initialisation commands to the camera */
static int send_control_msg(struct usb_device *udev, u8 request, u16 value,
			    u16 index, unsigned char *cp, u16 size)
{
	int status;

	unsigned char *transfer_buffer = kmalloc(size, GFP_KERNEL);
	if (!transfer_buffer) {
221
		dev_err(&udev->dev, "kmalloc(%d) failed\n", size);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
		return -ENOMEM;
	}

	memcpy(transfer_buffer, cp, size);

	status = usb_control_msg(udev,
				 usb_sndctrlpipe(udev, 0),
				 request,
				 USB_DIR_OUT | USB_TYPE_VENDOR |
				 USB_RECIP_DEVICE, value, index,
				 transfer_buffer, size, CTRL_TIMEOUT);

	kfree(transfer_buffer);

	if (status < 0)
237 238
		dev_err(&udev->dev,
			"Failed sending control message, error %d.\n", status);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

	return status;
}


/* Control messages sent to the camera to initialize it
 * and launch the capture */
typedef struct {
	unsigned int value;
	unsigned int size;
	unsigned char *bytes;
} message;

/* method 0 */
static unsigned char m0d1[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static unsigned char m0d2[] = { 0, 0, 0, 0, 0, 0 };
static unsigned char m0d3[] = { 0, 0 };
static message m0[] = {
	{0x1f30, 0, NULL},
	{0xd000, 0, NULL},
	{0x3370, sizeof(m0d1), m0d1},
	{0x2000, 0, NULL},
	{0x2f0f, 0, NULL},
	{0x2610, sizeof(m0d2), m0d2},
	{0xe107, 0, NULL},
	{0x2502, 0, NULL},
	{0x1f70, 0, NULL},
	{0xd000, 0, NULL},
	{0x9a01, sizeof(m0d3), m0d3},
	{-1, -1, NULL}
};

/* method 1 */
static unsigned char m1d1[] = { 0xff, 0xff };
static unsigned char m1d2[] = { 0x00, 0x00 };
static message m1[] = {
	{0x1f30, 0, NULL},
	{0xd000, 0, NULL},
	{0xf000, 0, NULL},
	{0x2000, 0, NULL},
	{0x2f0f, 0, NULL},
	{0x2650, 0, NULL},
	{0xe107, 0, NULL},
	{0x2502, sizeof(m1d1), m1d1},
	{0x1f70, 0, NULL},
	{0xd000, 0, NULL},
	{0xd000, 0, NULL},
	{0xd000, 0, NULL},
	{0x9a01, sizeof(m1d2), m1d2},
	{-1, -1, NULL}
};

/* method 2 */
static unsigned char m2d1[] = { 0xff, 0xff };
static message m2[] = {
	{0x1f30, 0, NULL},
	{0xf000, 0, NULL},
	{0x2000, 0, NULL},
	{0x2f0f, 0, NULL},
	{0x2650, 0, NULL},
	{0xe107, 0, NULL},
	{0x2502, sizeof(m2d1), m2d1},
	{0x1f70, 0, NULL},
	{-1, -1, NULL}
};

/* init table */
306
static message *init[4] = { m0, m1, m2, m2 };
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364


/* JPEG static data in header (Huffman table, etc) */
static unsigned char header1[] = {
	0xFF, 0xD8,
	/*
	0xFF, 0xE0, 0x00, 0x10, 'J', 'F', 'I', 'F',
	0x00, 0x01, 0x01, 0x00, 0x33, 0x8A, 0x00, 0x00, 0x33, 0x88,
	*/
	0xFF, 0xDB, 0x00, 0x84
};
static unsigned char header2[] = {
	0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01,
	0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
	0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02,
	0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01,
	0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
	0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1,
	0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33,
	0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25,
	0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
	0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54,
	0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67,
	0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,
	0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94,
	0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6,
	0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8,
	0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA,
	0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
	0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3,
	0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xC4, 0x00, 0x1F,
	0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
	0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
	0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5,
	0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05,
	0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11,
	0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
	0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1,
	0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16,
	0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27,
	0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44,
	0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57,
	0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
	0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84,
	0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96,
	0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8,
	0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA,
	0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3,
	0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5,
	0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
	0xF8, 0xF9, 0xFA, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0xF0, 0x01,
	0x40, 0x03, 0x01, 0x21, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
	0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11,
	0x00, 0x3F, 0x00
};
static unsigned char header3;

365 366 367
/* ------------------------------------------------------------------
   Videobuf operations
   ------------------------------------------------------------------*/
368

369 370 371 372
static int buffer_setup(struct videobuf_queue *vq, unsigned int *count,
			unsigned int *size)
{
	struct zr364xx_camera *cam = vq->priv_data;
373

374
	*size = cam->width * cam->height * (cam->fmt->depth >> 3);
375

376 377
	if (*count == 0)
		*count = ZR364XX_DEF_BUFS;
378

379 380
	if (*size * *count > ZR364XX_DEF_BUFS * 1024 * 1024)
		*count = (ZR364XX_DEF_BUFS * 1024 * 1024) / *size;
381

382 383
	return 0;
}
384

385 386
static void free_buffer(struct videobuf_queue *vq, struct zr364xx_buffer *buf)
{
387
	_DBG("%s\n", __func__);
388

389 390
	if (in_interrupt())
		BUG();
391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	videobuf_vmalloc_free(&buf->vb);
	buf->vb.state = VIDEOBUF_NEEDS_INIT;
}

static int buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
			  enum v4l2_field field)
{
	struct zr364xx_camera *cam = vq->priv_data;
	struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
						  vb);
	int rc;

	DBG("%s, field=%d, fmt name = %s\n", __func__, field, cam->fmt != NULL ?
	    cam->fmt->name : "");
	if (cam->fmt == NULL)
		return -EINVAL;

	buf->vb.size = cam->width * cam->height * (cam->fmt->depth >> 3);

	if (buf->vb.baddr != 0 && buf->vb.bsize < buf->vb.size) {
		DBG("invalid buffer prepare\n");
		return -EINVAL;
414
	}
415 416 417 418 419 420 421 422 423 424

	buf->fmt = cam->fmt;
	buf->vb.width = cam->width;
	buf->vb.height = cam->height;
	buf->vb.field = field;

	if (buf->vb.state == VIDEOBUF_NEEDS_INIT) {
		rc = videobuf_iolock(vq, &buf->vb, NULL);
		if (rc < 0)
			goto fail;
425 426
	}

427 428 429 430 431 432 433 434 435 436 437 438 439
	buf->vb.state = VIDEOBUF_PREPARED;
	return 0;
fail:
	free_buffer(vq, buf);
	return rc;
}

static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
	struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
						  vb);
	struct zr364xx_camera *cam = vq->priv_data;

440
	_DBG("%s\n", __func__);
441

442 443
	buf->vb.state = VIDEOBUF_QUEUED;
	list_add_tail(&buf->vb.queue, &cam->vidq.active);
444 445
}

446 447 448 449 450 451
static void buffer_release(struct videobuf_queue *vq,
			   struct videobuf_buffer *vb)
{
	struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
						  vb);

452
	_DBG("%s\n", __func__);
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	free_buffer(vq, buf);
}

static struct videobuf_queue_ops zr364xx_video_qops = {
	.buf_setup = buffer_setup,
	.buf_prepare = buffer_prepare,
	.buf_queue = buffer_queue,
	.buf_release = buffer_release,
};

/********************/
/* V4L2 integration */
/********************/
static int zr364xx_vidioc_streamon(struct file *file, void *priv,
				   enum v4l2_buf_type type);
468

469
static ssize_t zr364xx_read(struct file *file, char __user *buf, size_t count,
470 471
			    loff_t * ppos)
{
472
	struct zr364xx_camera *cam = video_drvdata(file);
473

474
	_DBG("%s\n", __func__);
475 476 477 478 479 480 481

	if (!buf)
		return -EINVAL;

	if (!count)
		return -EINVAL;

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	if (cam->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
	    zr364xx_vidioc_streamon(file, cam, cam->type) == 0) {
		DBG("%s: reading %d bytes at pos %d.\n", __func__, (int) count,
		    (int) *ppos);

		/* NoMan Sux ! */
		return videobuf_read_one(&cam->vb_vidq, buf, count, ppos,
					file->f_flags & O_NONBLOCK);
	}

	return 0;
}

/* video buffer vmalloc implementation based partly on VIVI driver which is
 *          Copyright (c) 2006 by
 *                  Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
 *                  Ted Walther <ted--a.t--enumera.com>
 *                  John Sokol <sokol--a.t--videotechnology.com>
 *                  http://v4l.videotechnology.com/
 *
 */
static void zr364xx_fillbuff(struct zr364xx_camera *cam,
			     struct zr364xx_buffer *buf,
			     int jpgsize)
{
	int pos = 0;
	struct timeval ts;
	const char *tmpbuf;
	char *vbuf = videobuf_to_vmalloc(&buf->vb);
	unsigned long last_frame;
	struct zr364xx_framei *frm;

	if (!vbuf)
		return;

	last_frame = cam->last_frame;
	if (last_frame != -1) {
		frm = &cam->buffer.frame[last_frame];
		tmpbuf = (const char *)cam->buffer.frame[last_frame].lpvbits;
		switch (buf->fmt->fourcc) {
		case V4L2_PIX_FMT_JPEG:
			buf->vb.size = jpgsize;
			memcpy(vbuf, tmpbuf, buf->vb.size);
			break;
		default:
			printk(KERN_DEBUG KBUILD_MODNAME ": unknown format?\n");
		}
		cam->last_frame = -1;
	} else {
		printk(KERN_ERR KBUILD_MODNAME ": =======no frame\n");
		return;
	}
	DBG("%s: Buffer 0x%08lx size= %d\n", __func__,
		(unsigned long)vbuf, pos);
	/* tell v4l buffer was filled */

	buf->vb.field_count = cam->frame_count * 2;
	do_gettimeofday(&ts);
	buf->vb.ts = ts;
	buf->vb.state = VIDEOBUF_DONE;
}

static int zr364xx_got_frame(struct zr364xx_camera *cam, int jpgsize)
{
	struct zr364xx_dmaqueue *dma_q = &cam->vidq;
	struct zr364xx_buffer *buf;
	unsigned long flags = 0;
	int rc = 0;

	DBG("wakeup: %p\n", &dma_q);
	spin_lock_irqsave(&cam->slock, flags);

	if (list_empty(&dma_q->active)) {
		DBG("No active queue to serve\n");
		rc = -1;
		goto unlock;
	}
	buf = list_entry(dma_q->active.next,
			 struct zr364xx_buffer, vb.queue);

	if (!waitqueue_active(&buf->vb.done)) {
		/* no one active */
		rc = -1;
		goto unlock;
	}
	list_del(&buf->vb.queue);
	do_gettimeofday(&buf->vb.ts);
	DBG("[%p/%d] wakeup\n", buf, buf->vb.i);
	zr364xx_fillbuff(cam, buf, jpgsize);
	wake_up(&buf->vb.done);
	DBG("wakeup [buf/i] [%p/%d]\n", buf, buf->vb.i);
unlock:
	spin_unlock_irqrestore(&cam->slock, flags);
575
	return rc;
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
}

/* this function moves the usb stream read pipe data
 * into the system buffers.
 * returns 0 on success, EAGAIN if more data to process (call this
 * function again).
 */
static int zr364xx_read_video_callback(struct zr364xx_camera *cam,
					struct zr364xx_pipeinfo *pipe_info,
					struct urb *purb)
{
	unsigned char *pdest;
	unsigned char *psrc;
	s32 idx = -1;
	struct zr364xx_framei *frm;
	int i = 0;
	unsigned char *ptr = NULL;

594
	_DBG("buffer to user\n");
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	idx = cam->cur_frame;
	frm = &cam->buffer.frame[idx];

	/* swap bytes if camera needs it */
	if (cam->method == METHOD0) {
		u16 *buf = (u16 *)pipe_info->transfer_buffer;
		for (i = 0; i < purb->actual_length/2; i++)
			swab16s(buf + i);
	}

	/* search done.  now find out if should be acquiring */
	if (!cam->b_acquire) {
		/* we found a frame, but this channel is turned off */
		frm->ulState = ZR364XX_READ_IDLE;
		return -EINVAL;
	}

	psrc = (u8 *)pipe_info->transfer_buffer;
	ptr = pdest = frm->lpvbits;

	if (frm->ulState == ZR364XX_READ_IDLE) {
		frm->ulState = ZR364XX_READ_FRAME;
		frm->cur_size = 0;

619
		_DBG("jpeg header, ");
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
		memcpy(ptr, header1, sizeof(header1));
		ptr += sizeof(header1);
		header3 = 0;
		memcpy(ptr, &header3, 1);
		ptr++;
		memcpy(ptr, psrc, 64);
		ptr += 64;
		header3 = 1;
		memcpy(ptr, &header3, 1);
		ptr++;
		memcpy(ptr, psrc + 64, 64);
		ptr += 64;
		memcpy(ptr, header2, sizeof(header2));
		ptr += sizeof(header2);
		memcpy(ptr, psrc + 128,
		       purb->actual_length - 128);
		ptr += purb->actual_length - 128;
637
		_DBG("header : %d %d %d %d %d %d %d %d %d\n",
638 639 640 641 642
		    psrc[0], psrc[1], psrc[2],
		    psrc[3], psrc[4], psrc[5],
		    psrc[6], psrc[7], psrc[8]);
		frm->cur_size = ptr - pdest;
	} else {
643 644 645 646 647 648 649 650 651 652
		if (frm->cur_size + purb->actual_length > MAX_FRAME_SIZE) {
			dev_info(&cam->udev->dev,
				 "%s: buffer (%d bytes) too small to hold "
				 "frame data. Discarding frame data.\n",
				 __func__, MAX_FRAME_SIZE);
		} else {
			pdest += frm->cur_size;
			memcpy(pdest, psrc, purb->actual_length);
			frm->cur_size += purb->actual_length;
		}
653
	}
654
	/*_DBG("cur_size %lu urb size %d\n", frm->cur_size,
655 656 657
		purb->actual_length);*/

	if (purb->actual_length < pipe_info->transfer_size) {
658
		_DBG("****************Buffer[%d]full*************\n", idx);
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
		cam->last_frame = cam->cur_frame;
		cam->cur_frame++;
		/* end of system frame ring buffer, start at zero */
		if (cam->cur_frame == cam->buffer.dwFrames)
			cam->cur_frame = 0;

		/* frame ready */
		/* go back to find the JPEG EOI marker */
		ptr = pdest = frm->lpvbits;
		ptr += frm->cur_size - 2;
		while (ptr > pdest) {
			if (*ptr == 0xFF && *(ptr + 1) == 0xD9
			    && *(ptr + 2) == 0xFF)
				break;
			ptr--;
		}
		if (ptr == pdest)
			DBG("No EOI marker\n");

		/* Sometimes there is junk data in the middle of the picture,
		 * we want to skip this bogus frames */
		while (ptr > pdest) {
			if (*ptr == 0xFF && *(ptr + 1) == 0xFF
			    && *(ptr + 2) == 0xFF)
				break;
			ptr--;
		}
		if (ptr != pdest) {
			DBG("Bogus frame ? %d\n", ++(cam->nb));
		} else if (cam->b_acquire) {
			/* we skip the 2 first frames which are usually buggy */
			if (cam->skip)
				cam->skip--;
			else {
693
				_DBG("jpeg(%lu): %d %d %d %d %d %d %d %d\n",
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
				    frm->cur_size,
				    pdest[0], pdest[1], pdest[2], pdest[3],
				    pdest[4], pdest[5], pdest[6], pdest[7]);

				zr364xx_got_frame(cam, frm->cur_size);
			}
		}
		cam->frame_count++;
		frm->ulState = ZR364XX_READ_IDLE;
		frm->cur_size = 0;
	}
	/* done successfully */
	return 0;
}

static int res_get(struct zr364xx_camera *cam)
{
	/* is it free? */
	mutex_lock(&cam->lock);
	if (cam->resources) {
		/* no, someone else uses it */
		mutex_unlock(&cam->lock);
		return 0;
	}
	/* it's free, grab it */
	cam->resources = 1;
720
	_DBG("res: get\n");
721 722 723
	mutex_unlock(&cam->lock);
	return 1;
}
724

725 726 727
static inline int res_check(struct zr364xx_camera *cam)
{
	return cam->resources;
728 729
}

730 731 732 733 734
static void res_free(struct zr364xx_camera *cam)
{
	mutex_lock(&cam->lock);
	cam->resources = 0;
	mutex_unlock(&cam->lock);
735
	_DBG("res: put\n");
736
}
737 738 739 740

static int zr364xx_vidioc_querycap(struct file *file, void *priv,
				   struct v4l2_capability *cap)
{
741 742 743 744 745 746
	struct zr364xx_camera *cam = video_drvdata(file);

	strlcpy(cap->driver, DRIVER_DESC, sizeof(cap->driver));
	strlcpy(cap->card, cam->udev->product, sizeof(cap->card));
	strlcpy(cap->bus_info, dev_name(&cam->udev->dev),
		sizeof(cap->bus_info));
747
	cap->version = ZR364XX_VERSION_CODE;
748 749 750 751
	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
			    V4L2_CAP_READWRITE |
			    V4L2_CAP_STREAMING;

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
	return 0;
}

static int zr364xx_vidioc_enum_input(struct file *file, void *priv,
				     struct v4l2_input *i)
{
	if (i->index != 0)
		return -EINVAL;
	strcpy(i->name, DRIVER_DESC " Camera");
	i->type = V4L2_INPUT_TYPE_CAMERA;
	return 0;
}

static int zr364xx_vidioc_g_input(struct file *file, void *priv,
				  unsigned int *i)
{
	*i = 0;
	return 0;
}

static int zr364xx_vidioc_s_input(struct file *file, void *priv,
				  unsigned int i)
{
	if (i != 0)
		return -EINVAL;
	return 0;
}

static int zr364xx_vidioc_queryctrl(struct file *file, void *priv,
				    struct v4l2_queryctrl *c)
{
	struct zr364xx_camera *cam;

785
	if (file == NULL)
786
		return -ENODEV;
787
	cam = video_drvdata(file);
788 789 790 791 792 793 794 795

	switch (c->id) {
	case V4L2_CID_BRIGHTNESS:
		c->type = V4L2_CTRL_TYPE_INTEGER;
		strcpy(c->name, "Brightness");
		c->minimum = 0;
		c->maximum = 127;
		c->step = 1;
796
		c->default_value = cam->mode.brightness;
797 798 799 800 801 802 803 804 805 806 807 808
		c->flags = 0;
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

static int zr364xx_vidioc_s_ctrl(struct file *file, void *priv,
				 struct v4l2_control *c)
{
	struct zr364xx_camera *cam;
809
	int temp;
810

811
	if (file == NULL)
812
		return -ENODEV;
813
	cam = video_drvdata(file);
814 815 816

	switch (c->id) {
	case V4L2_CID_BRIGHTNESS:
817 818 819 820 821 822 823
		cam->mode.brightness = c->value;
		/* hardware brightness */
		mutex_lock(&cam->lock);
		send_control_msg(cam->udev, 1, 0x2001, 0, NULL, 0);
		temp = (0x60 << 8) + 127 - cam->mode.brightness;
		send_control_msg(cam->udev, 1, temp, 0, NULL, 0);
		mutex_unlock(&cam->lock);
824 825 826 827
		break;
	default:
		return -EINVAL;
	}
828

829 830 831 832 833 834 835 836
	return 0;
}

static int zr364xx_vidioc_g_ctrl(struct file *file, void *priv,
				 struct v4l2_control *c)
{
	struct zr364xx_camera *cam;

837
	if (file == NULL)
838
		return -ENODEV;
839
	cam = video_drvdata(file);
840 841 842

	switch (c->id) {
	case V4L2_CID_BRIGHTNESS:
843
		c->value = cam->mode.brightness;
844 845 846 847 848 849 850
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

851
static int zr364xx_vidioc_enum_fmt_vid_cap(struct file *file,
852 853 854 855 856
				       void *priv, struct v4l2_fmtdesc *f)
{
	if (f->index > 0)
		return -EINVAL;
	f->flags = V4L2_FMT_FLAG_COMPRESSED;
857 858
	strcpy(f->description, formats[0].name);
	f->pixelformat = formats[0].fourcc;
859 860 861
	return 0;
}

862 863 864 865 866 867 868 869 870 871
static char *decode_fourcc(__u32 pixelformat, char *buf)
{
	buf[0] = pixelformat & 0xff;
	buf[1] = (pixelformat >> 8) & 0xff;
	buf[2] = (pixelformat >> 16) & 0xff;
	buf[3] = (pixelformat >> 24) & 0xff;
	buf[4] = '\0';
	return buf;
}

872
static int zr364xx_vidioc_try_fmt_vid_cap(struct file *file, void *priv,
873 874
				      struct v4l2_format *f)
{
875 876
	struct zr364xx_camera *cam = video_drvdata(file);
	char pixelformat_name[5];
877

878
	if (cam == NULL)
879 880
		return -ENODEV;

881 882 883
	if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG) {
		DBG("%s: unsupported pixelformat V4L2_PIX_FMT_%s\n", __func__,
		    decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name));
884
		return -EINVAL;
885 886
	}

887 888 889 890 891 892
	if (!(f->fmt.pix.width == 160 && f->fmt.pix.height == 120) &&
	    !(f->fmt.pix.width == 640 && f->fmt.pix.height == 480)) {
		f->fmt.pix.width = 320;
		f->fmt.pix.height = 240;
	}

893 894 895 896 897
	f->fmt.pix.field = V4L2_FIELD_NONE;
	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
	f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
	f->fmt.pix.colorspace = 0;
	f->fmt.pix.priv = 0;
898 899 900
	DBG("%s: V4L2_PIX_FMT_%s (%d) ok!\n", __func__,
	    decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name),
	    f->fmt.pix.field);
901 902 903
	return 0;
}

904
static int zr364xx_vidioc_g_fmt_vid_cap(struct file *file, void *priv,
905 906 907 908
				    struct v4l2_format *f)
{
	struct zr364xx_camera *cam;

909
	if (file == NULL)
910
		return -ENODEV;
911
	cam = video_drvdata(file);
912

913
	f->fmt.pix.pixelformat = formats[0].fourcc;
914 915 916 917 918 919 920 921 922 923
	f->fmt.pix.field = V4L2_FIELD_NONE;
	f->fmt.pix.width = cam->width;
	f->fmt.pix.height = cam->height;
	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
	f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
	f->fmt.pix.colorspace = 0;
	f->fmt.pix.priv = 0;
	return 0;
}

924
static int zr364xx_vidioc_s_fmt_vid_cap(struct file *file, void *priv,
925 926
				    struct v4l2_format *f)
{
927 928 929 930
	struct zr364xx_camera *cam = video_drvdata(file);
	struct videobuf_queue *q = &cam->vb_vidq;
	char pixelformat_name[5];
	int ret = zr364xx_vidioc_try_fmt_vid_cap(file, cam, f);
931
	int i;
932

933 934 935 936 937 938 939 940 941 942
	if (ret < 0)
		return ret;

	mutex_lock(&q->vb_lock);

	if (videobuf_queue_is_busy(&cam->vb_vidq)) {
		DBG("%s queue busy\n", __func__);
		ret = -EBUSY;
		goto out;
	}
943

944 945 946 947 948 949 950 951 952 953
	if (res_check(cam)) {
		DBG("%s can't change format after started\n", __func__);
		ret = -EBUSY;
		goto out;
	}

	cam->width = f->fmt.pix.width;
	cam->height = f->fmt.pix.height;
	dev_info(&cam->udev->dev, "%s: %dx%d mode selected\n", __func__,
		 cam->width, cam->height);
954 955 956 957
	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
	f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
	f->fmt.pix.colorspace = 0;
	f->fmt.pix.priv = 0;
958 959
	cam->vb_vidq.field = f->fmt.pix.field;
	cam->mode.color = V4L2_PIX_FMT_JPEG;
960 961 962 963 964 965 966 967 968 969 970

	if (f->fmt.pix.width == 160 && f->fmt.pix.height == 120)
		mode = 1;
	else if (f->fmt.pix.width == 640 && f->fmt.pix.height == 480)
		mode = 2;
	else
		mode = 0;

	m0d1[0] = mode;
	m1[2].value = 0xf000 + mode;
	m2[1].value = 0xf000 + mode;
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

	/* special case for METHOD3, the modes are different */
	if (cam->method == METHOD3) {
		switch (mode) {
		case 1:
			m2[1].value = 0xf000 + 4;
			break;
		case 2:
			m2[1].value = 0xf000 + 0;
			break;
		default:
			m2[1].value = 0xf000 + 1;
			break;
		}
	}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	header2[437] = cam->height / 256;
	header2[438] = cam->height % 256;
	header2[439] = cam->width / 256;
	header2[440] = cam->width % 256;

	for (i = 0; init[cam->method][i].size != -1; i++) {
		ret =
		    send_control_msg(cam->udev, 1, init[cam->method][i].value,
				     0, init[cam->method][i].bytes,
				     init[cam->method][i].size);
		if (ret < 0) {
			dev_err(&cam->udev->dev,
			   "error during resolution change sequence: %d\n", i);
			goto out;
		}
	}

	/* Added some delay here, since opening/closing the camera quickly,
	 * like Ekiga does during its startup, can crash the webcam
	 */
	mdelay(100);
	cam->skip = 2;
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	ret = 0;

out:
	mutex_unlock(&q->vb_lock);

	DBG("%s: V4L2_PIX_FMT_%s (%d) ok!\n", __func__,
	    decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name),
	    f->fmt.pix.field);
	return ret;
}

static int zr364xx_vidioc_reqbufs(struct file *file, void *priv,
			  struct v4l2_requestbuffers *p)
{
	int rc;
	struct zr364xx_camera *cam = video_drvdata(file);
	rc = videobuf_reqbufs(&cam->vb_vidq, p);
	return rc;
}

static int zr364xx_vidioc_querybuf(struct file *file,
				void *priv,
				struct v4l2_buffer *p)
{
	int rc;
	struct zr364xx_camera *cam = video_drvdata(file);
	rc = videobuf_querybuf(&cam->vb_vidq, p);
	return rc;
}

static int zr364xx_vidioc_qbuf(struct file *file,
				void *priv,
				struct v4l2_buffer *p)
{
	int rc;
	struct zr364xx_camera *cam = video_drvdata(file);
1045
	_DBG("%s\n", __func__);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
	rc = videobuf_qbuf(&cam->vb_vidq, p);
	return rc;
}

static int zr364xx_vidioc_dqbuf(struct file *file,
				void *priv,
				struct v4l2_buffer *p)
{
	int rc;
	struct zr364xx_camera *cam = video_drvdata(file);
1056
	_DBG("%s\n", __func__);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
	rc = videobuf_dqbuf(&cam->vb_vidq, p, file->f_flags & O_NONBLOCK);
	return rc;
}

static void read_pipe_completion(struct urb *purb)
{
	struct zr364xx_pipeinfo *pipe_info;
	struct zr364xx_camera *cam;
	int pipe;

	pipe_info = purb->context;
1068
	_DBG("%s %p, status %d\n", __func__, purb, purb->status);
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	if (pipe_info == NULL) {
		printk(KERN_ERR KBUILD_MODNAME ": no context!\n");
		return;
	}

	cam = pipe_info->cam;
	if (cam == NULL) {
		printk(KERN_ERR KBUILD_MODNAME ": no context!\n");
		return;
	}

	/* if shutting down, do not resubmit, exit immediately */
	if (purb->status == -ESHUTDOWN) {
		DBG("%s, err shutdown\n", __func__);
		pipe_info->err_count++;
		return;
	}

	if (pipe_info->state == 0) {
		DBG("exiting USB pipe\n");
		return;
	}

	if (purb->actual_length < 0 ||
	    purb->actual_length > pipe_info->transfer_size) {
		dev_err(&cam->udev->dev, "wrong number of bytes\n");
		return;
	}

	if (purb->status == 0)
		zr364xx_read_video_callback(cam, pipe_info, purb);
	else {
		pipe_info->err_count++;
		DBG("%s: failed URB %d\n", __func__, purb->status);
	}

	pipe = usb_rcvbulkpipe(cam->udev, cam->read_endpoint);

	/* reuse urb */
	usb_fill_bulk_urb(pipe_info->stream_urb, cam->udev,
			  pipe,
			  pipe_info->transfer_buffer,
			  pipe_info->transfer_size,
			  read_pipe_completion, pipe_info);

	if (pipe_info->state != 0) {
		purb->status = usb_submit_urb(pipe_info->stream_urb,
					      GFP_ATOMIC);

		if (purb->status)
			dev_err(&cam->udev->dev,
				"error submitting urb (error=%i)\n",
				purb->status);
	} else
		DBG("read pipe complete state 0\n");
}

static int zr364xx_start_readpipe(struct zr364xx_camera *cam)
{
	int pipe;
	int retval;
	struct zr364xx_pipeinfo *pipe_info = cam->pipe;
	pipe = usb_rcvbulkpipe(cam->udev, cam->read_endpoint);
	DBG("%s: start pipe IN x%x\n", __func__, cam->read_endpoint);

	pipe_info->state = 1;
	pipe_info->err_count = 0;
	pipe_info->stream_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!pipe_info->stream_urb) {
		dev_err(&cam->udev->dev, "ReadStream: Unable to alloc URB\n");
		return -ENOMEM;
	}
	/* transfer buffer allocated in board_init */
	usb_fill_bulk_urb(pipe_info->stream_urb, cam->udev,
			  pipe,
			  pipe_info->transfer_buffer,
			  pipe_info->transfer_size,
			  read_pipe_completion, pipe_info);

	DBG("submitting URB %p\n", pipe_info->stream_urb);
	retval = usb_submit_urb(pipe_info->stream_urb, GFP_KERNEL);
	if (retval) {
		printk(KERN_ERR KBUILD_MODNAME ": start read pipe failed\n");
		return retval;
	}

	return 0;
}

static void zr364xx_stop_readpipe(struct zr364xx_camera *cam)
{
	struct zr364xx_pipeinfo *pipe_info;

	if (cam == NULL) {
		printk(KERN_ERR KBUILD_MODNAME ": invalid device\n");
		return;
	}
	DBG("stop read pipe\n");
	pipe_info = cam->pipe;
	if (pipe_info) {
		if (pipe_info->state != 0)
			pipe_info->state = 0;

		if (pipe_info->stream_urb) {
			/* cancel urb */
			usb_kill_urb(pipe_info->stream_urb);
			usb_free_urb(pipe_info->stream_urb);
			pipe_info->stream_urb = NULL;
		}
	}
	return;
}

/* starts acquisition process */
static int zr364xx_start_acquire(struct zr364xx_camera *cam)
{
	int j;

	DBG("start acquire\n");

	cam->last_frame = -1;
	cam->cur_frame = 0;
	for (j = 0; j < FRAMES; j++) {
		cam->buffer.frame[j].ulState = ZR364XX_READ_IDLE;
		cam->buffer.frame[j].cur_size = 0;
	}
1195
	cam->b_acquire = 1;
1196 1197 1198 1199 1200 1201
	return 0;
}

static inline int zr364xx_stop_acquire(struct zr364xx_camera *cam)
{
	cam->b_acquire = 0;
1202 1203 1204 1205 1206 1207
	return 0;
}

static int zr364xx_vidioc_streamon(struct file *file, void *priv,
				   enum v4l2_buf_type type)
{
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
	struct zr364xx_camera *cam = video_drvdata(file);
	int j;
	int res;

	DBG("%s\n", __func__);

	if (cam->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
		dev_err(&cam->udev->dev, "invalid fh type0\n");
		return -EINVAL;
	}
	if (cam->type != type) {
		dev_err(&cam->udev->dev, "invalid fh type1\n");
		return -EINVAL;
	}

	if (!res_get(cam)) {
		dev_err(&cam->udev->dev, "stream busy\n");
		return -EBUSY;
	}

	cam->last_frame = -1;
	cam->cur_frame = 0;
	cam->frame_count = 0;
	for (j = 0; j < FRAMES; j++) {
		cam->buffer.frame[j].ulState = ZR364XX_READ_IDLE;
		cam->buffer.frame[j].cur_size = 0;
	}
	res = videobuf_streamon(&cam->vb_vidq);
	if (res == 0) {
		zr364xx_start_acquire(cam);
	} else {
		res_free(cam);
	}
	return res;
1242 1243 1244 1245 1246
}

static int zr364xx_vidioc_streamoff(struct file *file, void *priv,
				    enum v4l2_buf_type type)
{
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	int res;
	struct zr364xx_camera *cam = video_drvdata(file);

	DBG("%s\n", __func__);
	if (cam->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
		dev_err(&cam->udev->dev, "invalid fh type0\n");
		return -EINVAL;
	}
	if (cam->type != type) {
		dev_err(&cam->udev->dev, "invalid fh type1\n");
		return -EINVAL;
	}
	zr364xx_stop_acquire(cam);
	res = videobuf_streamoff(&cam->vb_vidq);
	if (res < 0)
		return res;
	res_free(cam);
1264 1265 1266 1267 1268
	return 0;
}


/* open the camera */
1269
static int zr364xx_open(struct file *file)
1270 1271
{
	struct video_device *vdev = video_devdata(file);
1272
	struct zr364xx_camera *cam = video_drvdata(file);
1273 1274 1275
	struct usb_device *udev = cam->udev;
	int i, err;

1276
	DBG("%s\n", __func__);
1277

1278
	mutex_lock(&cam->open_lock);
1279

1280 1281
	if (cam->users) {
		err = -EBUSY;
1282
		goto out;
1283
	}
1284 1285 1286 1287 1288 1289 1290

	for (i = 0; init[cam->method][i].size != -1; i++) {
		err =
		    send_control_msg(udev, 1, init[cam->method][i].value,
				     0, init[cam->method][i].bytes,
				     init[cam->method][i].size);
		if (err < 0) {
1291 1292
			dev_err(&cam->udev->dev,
				"error during open sequence: %d\n", i);
1293
			goto out;
1294 1295 1296
		}
	}

1297 1298
	cam->skip = 2;
	cam->users++;
1299
	file->private_data = vdev;
1300 1301 1302 1303 1304 1305 1306
	cam->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	cam->fmt = formats;

	videobuf_queue_vmalloc_init(&cam->vb_vidq, &zr364xx_video_qops,
				    NULL, &cam->slock,
				    cam->type,
				    V4L2_FIELD_NONE,
1307
				    sizeof(struct zr364xx_buffer), cam, NULL);
1308 1309 1310 1311 1312

	/* Added some delay here, since opening/closing the camera quickly,
	 * like Ekiga does during its startup, can crash the webcam
	 */
	mdelay(100);
1313
	err = 0;
1314

1315
out:
1316 1317
	mutex_unlock(&cam->open_lock);
	DBG("%s: %d\n", __func__, err);
1318
	return err;
1319 1320
}

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
static void zr364xx_destroy(struct zr364xx_camera *cam)
{
	unsigned long i;

	if (!cam) {
		printk(KERN_ERR KBUILD_MODNAME ", %s: no device\n", __func__);
		return;
	}
	mutex_lock(&cam->open_lock);
	if (cam->vdev)
		video_unregister_device(cam->vdev);
	cam->vdev = NULL;

	/* stops the read pipe if it is running */
	if (cam->b_acquire)
		zr364xx_stop_acquire(cam);

	zr364xx_stop_readpipe(cam);

	/* release sys buffers */
	for (i = 0; i < FRAMES; i++) {
		if (cam->buffer.frame[i].lpvbits) {
			DBG("vfree %p\n", cam->buffer.frame[i].lpvbits);
			vfree(cam->buffer.frame[i].lpvbits);
		}
		cam->buffer.frame[i].lpvbits = NULL;
	}

	/* release transfer buffer */
	kfree(cam->pipe->transfer_buffer);
	cam->pipe->transfer_buffer = NULL;
	mutex_unlock(&cam->open_lock);
	kfree(cam);
	cam = NULL;
}
1356 1357

/* release the camera */
1358
static int zr364xx_release(struct file *file)
1359 1360 1361 1362 1363
{
	struct zr364xx_camera *cam;
	struct usb_device *udev;
	int i, err;

1364 1365
	DBG("%s\n", __func__);
	cam = video_drvdata(file);
1366

1367
	if (!cam)
1368 1369
		return -ENODEV;

1370
	mutex_lock(&cam->open_lock);
1371 1372
	udev = cam->udev;

1373 1374 1375 1376 1377 1378 1379
	/* turn off stream */
	if (res_check(cam)) {
		if (cam->b_acquire)
			zr364xx_stop_acquire(cam);
		videobuf_streamoff(&cam->vb_vidq);
		res_free(cam);
	}
1380 1381 1382 1383

	cam->users--;
	file->private_data = NULL;

1384 1385 1386
	for (i = 0; i < 2; i++) {
		err =
		    send_control_msg(udev, 1, init[cam->method][i].value,
1387
				     0, init[cam->method][i].bytes,
1388 1389
				     init[cam->method][i].size);
		if (err < 0) {
1390
			dev_err(&udev->dev, "error during release sequence\n");
1391
			goto out;
1392 1393 1394 1395 1396 1397 1398
		}
	}

	/* Added some delay here, since opening/closing the camera quickly,
	 * like Ekiga does during its startup, can crash the webcam
	 */
	mdelay(100);
1399
	err = 0;
1400

1401
out:
1402 1403
	mutex_unlock(&cam->open_lock);

1404
	return err;
1405 1406 1407 1408 1409
}


static int zr364xx_mmap(struct file *file, struct vm_area_struct *vma)
{
1410 1411
	struct zr364xx_camera *cam = video_drvdata(file);
	int ret;
1412

1413 1414
	if (cam == NULL) {
		DBG("%s: cam == NULL\n", __func__);
1415 1416
		return -ENODEV;
	}
1417
	DBG("mmap called, vma=0x%08lx\n", (unsigned long)vma);
1418

1419 1420 1421 1422 1423 1424
	ret = videobuf_mmap_mapper(&cam->vb_vidq, vma);

	DBG("vma start=0x%08lx, size=%ld, ret=%d\n",
		(unsigned long)vma->vm_start,
		(unsigned long)vma->vm_end - (unsigned long)vma->vm_start, ret);
	return ret;
1425 1426
}

1427 1428 1429 1430 1431
static unsigned int zr364xx_poll(struct file *file,
			       struct poll_table_struct *wait)
{
	struct zr364xx_camera *cam = video_drvdata(file);
	struct videobuf_queue *q = &cam->vb_vidq;
1432
	_DBG("%s\n", __func__);
1433 1434 1435 1436 1437 1438

	if (cam->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return POLLERR;

	return videobuf_poll_stream(file, q, wait);
}
1439

1440
static const struct v4l2_file_operations zr364xx_fops = {
1441 1442 1443 1444 1445 1446
	.owner = THIS_MODULE,
	.open = zr364xx_open,
	.release = zr364xx_release,
	.read = zr364xx_read,
	.mmap = zr364xx_mmap,
	.ioctl = video_ioctl2,
1447
	.poll = zr364xx_poll,
1448 1449
};

1450
static const struct v4l2_ioctl_ops zr364xx_ioctl_ops = {
1451
	.vidioc_querycap	= zr364xx_vidioc_querycap,
1452 1453 1454 1455
	.vidioc_enum_fmt_vid_cap = zr364xx_vidioc_enum_fmt_vid_cap,
	.vidioc_try_fmt_vid_cap	= zr364xx_vidioc_try_fmt_vid_cap,
	.vidioc_s_fmt_vid_cap	= zr364xx_vidioc_s_fmt_vid_cap,
	.vidioc_g_fmt_vid_cap	= zr364xx_vidioc_g_fmt_vid_cap,
1456 1457 1458 1459 1460 1461 1462 1463
	.vidioc_enum_input	= zr364xx_vidioc_enum_input,
	.vidioc_g_input		= zr364xx_vidioc_g_input,
	.vidioc_s_input		= zr364xx_vidioc_s_input,
	.vidioc_streamon	= zr364xx_vidioc_streamon,
	.vidioc_streamoff	= zr364xx_vidioc_streamoff,
	.vidioc_queryctrl	= zr364xx_vidioc_queryctrl,
	.vidioc_g_ctrl		= zr364xx_vidioc_g_ctrl,
	.vidioc_s_ctrl		= zr364xx_vidioc_s_ctrl,
1464 1465 1466 1467
	.vidioc_reqbufs         = zr364xx_vidioc_reqbufs,
	.vidioc_querybuf        = zr364xx_vidioc_querybuf,
	.vidioc_qbuf            = zr364xx_vidioc_qbuf,
	.vidioc_dqbuf           = zr364xx_vidioc_dqbuf,
1468 1469
};

1470 1471 1472 1473 1474 1475 1476
static struct video_device zr364xx_template = {
	.name = DRIVER_DESC,
	.fops = &zr364xx_fops,
	.ioctl_ops = &zr364xx_ioctl_ops,
	.release = video_device_release,
};

1477 1478 1479 1480 1481


/*******************/
/* USB integration */
/*******************/
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
static int zr364xx_board_init(struct zr364xx_camera *cam)
{
	struct zr364xx_pipeinfo *pipe = cam->pipe;
	unsigned long i;

	DBG("board init: %p\n", cam);
	memset(pipe, 0, sizeof(*pipe));
	pipe->cam = cam;
	pipe->transfer_size = BUFFER_SIZE;

	pipe->transfer_buffer = kzalloc(pipe->transfer_size,
					GFP_KERNEL);
	if (pipe->transfer_buffer == NULL) {
		DBG("out of memory!\n");
		return -ENOMEM;
	}

	cam->b_acquire = 0;
	cam->frame_count = 0;

	/*** start create system buffers ***/
	for (i = 0; i < FRAMES; i++) {
		/* always allocate maximum size for system buffers */
		cam->buffer.frame[i].lpvbits = vmalloc(MAX_FRAME_SIZE);

		DBG("valloc %p, idx %lu, pdata %p\n",
			&cam->buffer.frame[i], i,
			cam->buffer.frame[i].lpvbits);
		if (cam->buffer.frame[i].lpvbits == NULL) {
			printk(KERN_INFO KBUILD_MODNAME ": out of memory. "
			       "Using less frames\n");
			break;
		}
	}

	if (i == 0) {
		printk(KERN_INFO KBUILD_MODNAME ": out of memory. Aborting\n");
		kfree(cam->pipe->transfer_buffer);
		cam->pipe->transfer_buffer = NULL;
		return -ENOMEM;
	} else
		cam->buffer.dwFrames = i;

	/* make sure internal states are set */
	for (i = 0; i < FRAMES; i++) {
		cam->buffer.frame[i].ulState = ZR364XX_READ_IDLE;
		cam->buffer.frame[i].cur_size = 0;
	}

	cam->cur_frame = 0;
	cam->last_frame = -1;
	/*** end create system buffers ***/

	/* start read pipe */
	zr364xx_start_readpipe(cam);
	DBG(": board initialized\n");
	return 0;
}
1540 1541 1542 1543 1544 1545

static int zr364xx_probe(struct usb_interface *intf,
			 const struct usb_device_id *id)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct zr364xx_camera *cam = NULL;
1546 1547
	struct usb_host_interface *iface_desc;
	struct usb_endpoint_descriptor *endpoint;
1548
	int err;
1549
	int i;
1550

1551
	DBG("probing...\n");
1552

1553 1554 1555 1556
	dev_info(&intf->dev, DRIVER_DESC " compatible webcam plugged\n");
	dev_info(&intf->dev, "model %04x:%04x detected\n",
		 le16_to_cpu(udev->descriptor.idVendor),
		 le16_to_cpu(udev->descriptor.idProduct));
1557

1558 1559
	cam = kzalloc(sizeof(struct zr364xx_camera), GFP_KERNEL);
	if (cam == NULL) {
1560
		dev_err(&udev->dev, "cam: out of memory !\n");
1561
		return -ENOMEM;
1562 1563 1564 1565 1566 1567
	}
	/* save the init method used by this camera */
	cam->method = id->driver_info;

	cam->vdev = video_device_alloc();
	if (cam->vdev == NULL) {
1568
		dev_err(&udev->dev, "cam->vdev: out of memory !\n");
1569
		kfree(cam);
1570
		cam = NULL;
1571
		return -ENOMEM;
1572 1573
	}
	memcpy(cam->vdev, &zr364xx_template, sizeof(zr364xx_template));
1574
	cam->vdev->parent = &intf->dev;
1575 1576 1577 1578 1579 1580 1581 1582
	video_set_drvdata(cam->vdev, cam);
	if (debug)
		cam->vdev->debug = V4L2_DEBUG_IOCTL | V4L2_DEBUG_IOCTL_ARG;

	cam->udev = udev;

	switch (mode) {
	case 1:
1583
		dev_info(&udev->dev, "160x120 mode selected\n");
1584 1585 1586 1587
		cam->width = 160;
		cam->height = 120;
		break;
	case 2:
1588
		dev_info(&udev->dev, "640x480 mode selected\n");
1589 1590 1591 1592
		cam->width = 640;
		cam->height = 480;
		break;
	default:
1593
		dev_info(&udev->dev, "320x240 mode selected\n");
1594 1595 1596 1597 1598 1599 1600 1601
		cam->width = 320;
		cam->height = 240;
		break;
	}

	m0d1[0] = mode;
	m1[2].value = 0xf000 + mode;
	m2[1].value = 0xf000 + mode;
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

	/* special case for METHOD3, the modes are different */
	if (cam->method == METHOD3) {
		switch (mode) {
		case 1:
			m2[1].value = 0xf000 + 4;
			break;
		case 2:
			m2[1].value = 0xf000 + 0;
			break;
		default:
			m2[1].value = 0xf000 + 1;
			break;
		}
	}

1618 1619 1620 1621 1622
	header2[437] = cam->height / 256;
	header2[438] = cam->height % 256;
	header2[439] = cam->width / 256;
	header2[440] = cam->width % 256;

1623
	cam->users = 0;
1624
	cam->nb = 0;
1625
	cam->mode.brightness = 64;
1626
	mutex_init(&cam->lock);
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
	mutex_init(&cam->open_lock);

	DBG("dev: %p, udev %p interface %p\n", cam, cam->udev, intf);

	/* set up the endpoint information  */
	iface_desc = intf->cur_altsetting;
	DBG("num endpoints %d\n", iface_desc->desc.bNumEndpoints);
	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
		endpoint = &iface_desc->endpoint[i].desc;
		if (!cam->read_endpoint && usb_endpoint_is_bulk_in(endpoint)) {
			/* we found the bulk in endpoint */
			cam->read_endpoint = endpoint->bEndpointAddress;
		}
	}
1641

1642 1643 1644 1645 1646 1647 1648 1649
	if (!cam->read_endpoint) {
		dev_err(&intf->dev, "Could not find bulk-in endpoint\n");
		return -ENOMEM;
	}

	/* v4l */
	INIT_LIST_HEAD(&cam->vidq.active);
	cam->vidq.cam = cam;
1650 1651
	err = video_register_device(cam->vdev, VFL_TYPE_GRABBER, -1);
	if (err) {
1652
		dev_err(&udev->dev, "video_register_device failed\n");
1653 1654
		video_device_release(cam->vdev);
		kfree(cam);
1655
		cam = NULL;
1656
		return err;
1657 1658 1659 1660
	}

	usb_set_intfdata(intf, cam);

1661 1662 1663 1664 1665 1666 1667 1668 1669
	/* load zr364xx board specific */
	err = zr364xx_board_init(cam);
	if (err) {
		spin_lock_init(&cam->slock);
		return err;
	}

	spin_lock_init(&cam->slock);

1670 1671
	dev_info(&udev->dev, DRIVER_DESC " controlling device %s\n",
		 video_device_node_name(cam->vdev));
1672 1673 1674 1675 1676 1677 1678
	return 0;
}


static void zr364xx_disconnect(struct usb_interface *intf)
{
	struct zr364xx_camera *cam = usb_get_intfdata(intf);
1679
	videobuf_mmap_free(&cam->vb_vidq);
1680
	usb_set_intfdata(intf, NULL);
1681
	dev_info(&intf->dev, DRIVER_DESC " webcam unplugged\n");
1682
	zr364xx_destroy(cam);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
}



/**********************/
/* Module integration */
/**********************/

static struct usb_driver zr364xx_driver = {
	.name = "zr364xx",
	.probe = zr364xx_probe,
	.disconnect = zr364xx_disconnect,
	.id_table = device_table
};


static int __init zr364xx_init(void)
{
	int retval;
1702
	retval = usb_register(&zr364xx_driver);
1703
	if (retval)
1704
		printk(KERN_ERR KBUILD_MODNAME ": usb_register failed!\n");
1705
	else
1706
		printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC "\n");
1707 1708 1709 1710 1711 1712
	return retval;
}


static void __exit zr364xx_exit(void)
{
1713
	printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC " module unloaded\n");
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
	usb_deregister(&zr364xx_driver);
}


module_init(zr364xx_init);
module_exit(zr364xx_exit);

MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");