et61x251_core.c 64.0 KB
Newer Older
1 2 3
/***************************************************************************
 * V4L2 driver for ET61X[12]51 PC Camera Controllers                       *
 *                                                                         *
4
 * Copyright (C) 2006-2007 by Luca Risolia <luca.risolia@studio.unibo.it>  *
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 *                                                                         *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.               *
 ***************************************************************************/

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/compiler.h>
#include <linux/ioctl.h>
#include <linux/poll.h>
#include <linux/stat.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/page-flags.h>
#include <linux/byteorder/generic.h>
#include <asm/page.h>
#include <asm/uaccess.h>

#include "et61x251.h"

/*****************************************************************************/

#define ET61X251_MODULE_NAME    "V4L2 driver for ET61X[12]51 "                \
46
				"PC Camera Controllers"
47
#define ET61X251_MODULE_AUTHOR  "(C) 2006-2007 Luca Risolia"
48 49
#define ET61X251_AUTHOR_EMAIL   "<luca.risolia@studio.unibo.it>"
#define ET61X251_MODULE_LICENSE "GPL"
50 51
#define ET61X251_MODULE_VERSION "1:1.09"
#define ET61X251_MODULE_VERSION_CODE  KERNEL_VERSION(1, 1, 9)
52 53 54 55 56 57 58 59 60 61 62 63 64

/*****************************************************************************/

MODULE_DEVICE_TABLE(usb, et61x251_id_table);

MODULE_AUTHOR(ET61X251_MODULE_AUTHOR " " ET61X251_AUTHOR_EMAIL);
MODULE_DESCRIPTION(ET61X251_MODULE_NAME);
MODULE_VERSION(ET61X251_MODULE_VERSION);
MODULE_LICENSE(ET61X251_MODULE_LICENSE);

static short video_nr[] = {[0 ... ET61X251_MAX_DEVICES-1] = -1};
module_param_array(video_nr, short, NULL, 0444);
MODULE_PARM_DESC(video_nr,
65 66 67 68 69 70 71 72 73 74
		 "\n<-1|n[,...]> Specify V4L2 minor mode number."
		 "\n -1 = use next available (default)"
		 "\n  n = use minor number n (integer >= 0)"
		 "\nYou can specify up to "
		 __MODULE_STRING(ET61X251_MAX_DEVICES) " cameras this way."
		 "\nFor example:"
		 "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
		 "\nthe second registered camera and use auto for the first"
		 "\none and for every other camera."
		 "\n");
75 76

static short force_munmap[] = {[0 ... ET61X251_MAX_DEVICES-1] =
77
			       ET61X251_FORCE_MUNMAP};
78 79
module_param_array(force_munmap, bool, NULL, 0444);
MODULE_PARM_DESC(force_munmap,
80 81 82 83 84 85 86
		 "\n<0|1[,...]> Force the application to unmap previously"
		 "\nmapped buffer memory before calling any VIDIOC_S_CROP or"
		 "\nVIDIOC_S_FMT ioctl's. Not all the applications support"
		 "\nthis feature. This parameter is specific for each"
		 "\ndetected camera."
		 "\n 0 = do not force memory unmapping"
		 "\n 1 = force memory unmapping (save memory)"
87
		 "\nDefault value is "__MODULE_STRING(ET61X251_FORCE_MUNMAP)"."
88
		 "\n");
89

90
static unsigned int frame_timeout[] = {[0 ... ET61X251_MAX_DEVICES-1] =
91
				       ET61X251_FRAME_TIMEOUT};
92 93
module_param_array(frame_timeout, uint, NULL, 0644);
MODULE_PARM_DESC(frame_timeout,
94 95 96 97 98
		 "\n<n[,...]> Timeout for a video frame in seconds."
		 "\nThis parameter is specific for each detected camera."
		 "\nDefault value is "
		 __MODULE_STRING(ET61X251_FRAME_TIMEOUT)"."
		 "\n");
99

100 101 102 103
#ifdef ET61X251_DEBUG
static unsigned short debug = ET61X251_DEBUG_LEVEL;
module_param(debug, ushort, 0644);
MODULE_PARM_DESC(debug,
104 105 106 107 108 109 110 111 112
		 "\n<n> Debugging information level, from 0 to 3:"
		 "\n0 = none (use carefully)"
		 "\n1 = critical errors"
		 "\n2 = significant informations"
		 "\n3 = more verbose messages"
		 "\nLevel 3 is useful for testing only, when only "
		 "one device is used."
		 "\nDefault value is "__MODULE_STRING(ET61X251_DEBUG_LEVEL)"."
		 "\n");
113 114 115 116 117 118
#endif

/*****************************************************************************/

static u32
et61x251_request_buffers(struct et61x251_device* cam, u32 count,
119
			 enum et61x251_io_method io)
120
{
121 122
	struct v4l2_pix_format* p = &(cam->sensor.pix_format);
	struct v4l2_rect* r = &(cam->sensor.cropcap.bounds);
123
	const size_t imagesize = cam->module_param.force_munmap ||
124 125 126
				 io == IO_READ ?
				 (p->width * p->height * p->priv) / 8 :
				 (r->width * r->height * p->priv) / 8;
127 128 129 130 131 132 133 134
	void* buff = NULL;
	u32 i;

	if (count > ET61X251_MAX_FRAMES)
		count = ET61X251_MAX_FRAMES;

	cam->nbuffers = count;
	while (cam->nbuffers > 0) {
135 136
		if ((buff = vmalloc_32_user(cam->nbuffers *
					    PAGE_ALIGN(imagesize))))
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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
			break;
		cam->nbuffers--;
	}

	for (i = 0; i < cam->nbuffers; i++) {
		cam->frame[i].bufmem = buff + i*PAGE_ALIGN(imagesize);
		cam->frame[i].buf.index = i;
		cam->frame[i].buf.m.offset = i*PAGE_ALIGN(imagesize);
		cam->frame[i].buf.length = imagesize;
		cam->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		cam->frame[i].buf.sequence = 0;
		cam->frame[i].buf.field = V4L2_FIELD_NONE;
		cam->frame[i].buf.memory = V4L2_MEMORY_MMAP;
		cam->frame[i].buf.flags = 0;
	}

	return cam->nbuffers;
}


static void et61x251_release_buffers(struct et61x251_device* cam)
{
	if (cam->nbuffers) {
		vfree(cam->frame[0].bufmem);
		cam->nbuffers = 0;
	}
	cam->frame_current = NULL;
}


static void et61x251_empty_framequeues(struct et61x251_device* cam)
{
	u32 i;

	INIT_LIST_HEAD(&cam->inqueue);
	INIT_LIST_HEAD(&cam->outqueue);

	for (i = 0; i < ET61X251_MAX_FRAMES; i++) {
		cam->frame[i].state = F_UNUSED;
		cam->frame[i].buf.bytesused = 0;
	}
}


static void et61x251_requeue_outqueue(struct et61x251_device* cam)
{
	struct et61x251_frame_t *i;

	list_for_each_entry(i, &cam->outqueue, frame) {
		i->state = F_QUEUED;
		list_add(&i->frame, &cam->inqueue);
	}

	INIT_LIST_HEAD(&cam->outqueue);
}


static void et61x251_queue_unusedframes(struct et61x251_device* cam)
{
	unsigned long lock_flags;
	u32 i;

	for (i = 0; i < cam->nbuffers; i++)
		if (cam->frame[i].state == F_UNUSED) {
			cam->frame[i].state = F_QUEUED;
			spin_lock_irqsave(&cam->queue_lock, lock_flags);
			list_add_tail(&cam->frame[i].frame, &cam->inqueue);
			spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
		}
}

/*****************************************************************************/

int et61x251_write_reg(struct et61x251_device* cam, u8 value, u16 index)
{
	struct usb_device* udev = cam->usbdev;
	u8* buff = cam->control_buffer;
	int res;

	*buff = value;

	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
219
			      0, index, buff, 1, ET61X251_CTRL_TIMEOUT);
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	if (res < 0) {
		DBG(3, "Failed to write a register (value 0x%02X, index "
		       "0x%02X, error %d)", value, index, res);
		return -1;
	}

	return 0;
}


int et61x251_read_reg(struct et61x251_device* cam, u16 index)
{
	struct usb_device* udev = cam->usbdev;
	u8* buff = cam->control_buffer;
	int res;

	res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
237
			      0, index, buff, 1, ET61X251_CTRL_TIMEOUT);
238 239 240 241 242 243 244 245 246
	if (res < 0)
		DBG(3, "Failed to read a register (index 0x%02X, error %d)",
		    index, res);

	return (res >= 0) ? (int)(*buff) : -1;
}


static int
247 248
et61x251_i2c_wait(struct et61x251_device* cam,
		  const struct et61x251_sensor* sensor)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
{
	int i, r;

	for (i = 1; i <= 8; i++) {
		if (sensor->interface == ET61X251_I2C_3WIRES) {
			r = et61x251_read_reg(cam, 0x8e);
			if (!(r & 0x02) && (r >= 0))
				return 0;
		} else {
			r = et61x251_read_reg(cam, 0x8b);
			if (!(r & 0x01) && (r >= 0))
				return 0;
		}
		if (r < 0)
			return -EIO;
		udelay(8*8); /* minimum for sensors at 400kHz */
	}

	return -EBUSY;
}


int
et61x251_i2c_try_read(struct et61x251_device* cam,
273
		      const struct et61x251_sensor* sensor, u8 address)
274 275 276 277 278 279
{
	struct usb_device* udev = cam->usbdev;
	u8* data = cam->control_buffer;
	int err = 0, res;

	data[0] = address;
280 281
	data[1] = cam->sensor.i2c_slave_id;
	data[2] = cam->sensor.rsta | 0x10;
282 283
	data[3] = !(et61x251_read_reg(cam, 0x8b) & 0x02);
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
284
			      0, 0x88, data, 4, ET61X251_CTRL_TIMEOUT);
285 286 287 288 289 290
	if (res < 0)
		err += res;

	err += et61x251_i2c_wait(cam, sensor);

	res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
291
			      0, 0x80, data, 8, ET61X251_CTRL_TIMEOUT);
292 293 294 295 296 297 298 299 300 301 302 303 304 305
	if (res < 0)
		err += res;

	if (err)
		DBG(3, "I2C read failed for %s image sensor", sensor->name);

	PDBGG("I2C read: address 0x%02X, value: 0x%02X", address, data[0]);

	return err ? -1 : (int)data[0];
}


int
et61x251_i2c_try_write(struct et61x251_device* cam,
306 307
		       const struct et61x251_sensor* sensor, u8 address,
		       u8 value)
308 309 310 311 312 313
{
	struct usb_device* udev = cam->usbdev;
	u8* data = cam->control_buffer;
	int err = 0, res;

	data[0] = address;
314 315
	data[1] = cam->sensor.i2c_slave_id;
	data[2] = cam->sensor.rsta | 0x12;
316
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
317
			      0, 0x88, data, 3, ET61X251_CTRL_TIMEOUT);
318 319 320 321 322
	if (res < 0)
		err += res;

	data[0] = value;
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
323
			      0, 0x80, data, 1, ET61X251_CTRL_TIMEOUT);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
	if (res < 0)
		err += res;

	err += et61x251_i2c_wait(cam, sensor);

	if (err)
		DBG(3, "I2C write failed for %s image sensor", sensor->name);

	PDBGG("I2C write: address 0x%02X, value: 0x%02X", address, value);

	return err ? -1 : 0;
}


int
et61x251_i2c_raw_write(struct et61x251_device* cam, u8 n, u8 data1, u8 data2,
340 341
		       u8 data3, u8 data4, u8 data5, u8 data6, u8 data7,
		       u8 data8, u8 address)
342 343 344 345 346 347 348 349 350 351 352 353 354
{
	struct usb_device* udev = cam->usbdev;
	u8* data = cam->control_buffer;
	int err = 0, res;

	data[0] = data2;
	data[1] = data3;
	data[2] = data4;
	data[3] = data5;
	data[4] = data6;
	data[5] = data7;
	data[6] = data8;
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
355
			      0, 0x81, data, n-1, ET61X251_CTRL_TIMEOUT);
356 357 358 359
	if (res < 0)
		err += res;

	data[0] = address;
360 361
	data[1] = cam->sensor.i2c_slave_id;
	data[2] = cam->sensor.rsta | 0x02 | (n << 4);
362
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
363
			      0, 0x88, data, 3, ET61X251_CTRL_TIMEOUT);
364 365 366 367 368 369
	if (res < 0)
		err += res;

	/* Start writing through the serial interface */
	data[0] = data1;
	res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00, 0x41,
370
			      0, 0x80, data, 1, ET61X251_CTRL_TIMEOUT);
371 372 373
	if (res < 0)
		err += res;

374
	err += et61x251_i2c_wait(cam, &cam->sensor);
375 376 377

	if (err)
		DBG(3, "I2C raw write failed for %s image sensor",
378
		    cam->sensor.name);
379 380 381 382 383 384 385 386 387 388 389 390 391

	PDBGG("I2C raw write: %u bytes, address = 0x%02X, data1 = 0x%02X, "
	      "data2 = 0x%02X, data3 = 0x%02X, data4 = 0x%02X, data5 = 0x%02X,"
	      " data6 = 0x%02X, data7 = 0x%02X, data8 = 0x%02X", n, address,
	      data1, data2, data3, data4, data5, data6, data7, data8);

	return err ? -1 : 0;

}


int et61x251_i2c_read(struct et61x251_device* cam, u8 address)
{
392
	return et61x251_i2c_try_read(cam, &cam->sensor, address);
393 394 395 396 397
}


int et61x251_i2c_write(struct et61x251_device* cam, u8 address, u8 value)
{
398
	return et61x251_i2c_try_write(cam, &cam->sensor, address, value);
399 400 401 402
}

/*****************************************************************************/

403
static void et61x251_urb_complete(struct urb *urb)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
{
	struct et61x251_device* cam = urb->context;
	struct et61x251_frame_t** f;
	size_t imagesize;
	u8 i;
	int err = 0;

	if (urb->status == -ENOENT)
		return;

	f = &cam->frame_current;

	if (cam->stream == STREAM_INTERRUPT) {
		cam->stream = STREAM_OFF;
		if ((*f))
			(*f)->state = F_QUEUED;
		DBG(3, "Stream interrupted");
421
		wake_up(&cam->wait_stream);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
	}

	if (cam->state & DEV_DISCONNECTED)
		return;

	if (cam->state & DEV_MISCONFIGURED) {
		wake_up_interruptible(&cam->wait_frame);
		return;
	}

	if (cam->stream == STREAM_OFF || list_empty(&cam->inqueue))
		goto resubmit_urb;

	if (!(*f))
		(*f) = list_entry(cam->inqueue.next, struct et61x251_frame_t,
437
				  frame);
438

439
	imagesize = (cam->sensor.pix_format.width *
440 441
		     cam->sensor.pix_format.height *
		     cam->sensor.pix_format.priv) / 8;
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

	for (i = 0; i < urb->number_of_packets; i++) {
		unsigned int len, status;
		void *pos;
		u8* b1, * b2, sof;
		const u8 VOID_BYTES = 6;
		size_t imglen;

		len = urb->iso_frame_desc[i].actual_length;
		status = urb->iso_frame_desc[i].status;
		pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;

		if (status) {
			DBG(3, "Error in isochronous frame");
			(*f)->state = F_ERROR;
			continue;
		}

		b1 = pos++;
		b2 = pos++;
		sof = ((*b1 & 0x3f) == 63);
		imglen = ((*b1 & 0xc0) << 2) | *b2;

		PDBGG("Isochrnous frame: length %u, #%u i, image length %zu",
		      len, i, imglen);

		if ((*f)->state == F_QUEUED || (*f)->state == F_ERROR)
start_of_frame:
			if (sof) {
				(*f)->state = F_GRABBING;
				(*f)->buf.bytesused = 0;
				do_gettimeofday(&(*f)->buf.timestamp);
				pos += 22;
				DBG(3, "SOF detected: new video frame");
			}

		if ((*f)->state == F_GRABBING) {
			if (sof && (*f)->buf.bytesused) {
480
				if (cam->sensor.pix_format.pixelformat ==
481
							 V4L2_PIX_FMT_ET61X251)
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
					goto end_of_frame;
				else {
					DBG(3, "Not expected SOF detected "
					       "after %lu bytes",
					   (unsigned long)(*f)->buf.bytesused);
					(*f)->state = F_ERROR;
					continue;
				}
			}

			if ((*f)->buf.bytesused + imglen > imagesize) {
				DBG(3, "Video frame size exceeded");
				(*f)->state = F_ERROR;
				continue;
			}

			pos += VOID_BYTES;

			memcpy((*f)->bufmem+(*f)->buf.bytesused, pos, imglen);
			(*f)->buf.bytesused += imglen;

			if ((*f)->buf.bytesused == imagesize) {
				u32 b;
end_of_frame:
				b = (*f)->buf.bytesused;
				(*f)->state = F_DONE;
				(*f)->buf.sequence= ++cam->frame_count;
				spin_lock(&cam->queue_lock);
				list_move_tail(&(*f)->frame, &cam->outqueue);
				if (!list_empty(&cam->inqueue))
					(*f) = list_entry(cam->inqueue.next,
513 514
						       struct et61x251_frame_t,
							  frame);
515 516 517 518 519 520 521 522 523 524
				else
					(*f) = NULL;
				spin_unlock(&cam->queue_lock);
				DBG(3, "Video frame captured: : %lu bytes",
				       (unsigned long)(b));

				if (!(*f))
					goto resubmit_urb;

				if (sof &&
525
				    cam->sensor.pix_format.pixelformat ==
526
							 V4L2_PIX_FMT_ET61X251)
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
					goto start_of_frame;
			}
		}
	}

resubmit_urb:
	urb->dev = cam->usbdev;
	err = usb_submit_urb(urb, GFP_ATOMIC);
	if (err < 0 && err != -EPERM) {
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "usb_submit_urb() failed");
	}

	wake_up_interruptible(&cam->wait_frame);
}


static int et61x251_start_transfer(struct et61x251_device* cam)
{
	struct usb_device *udev = cam->usbdev;
	struct urb* urb;
548 549 550 551 552
	struct usb_host_interface* altsetting = usb_altnum_to_altsetting(
						   usb_ifnum_to_if(udev, 0),
						   ET61X251_ALTERNATE_SETTING);
	const unsigned int psz = le16_to_cpu(altsetting->
					     endpoint[0].desc.wMaxPacketSize);
553 554 555 556 557
	s8 i, j;
	int err = 0;

	for (i = 0; i < ET61X251_URBS; i++) {
		cam->transfer_buffer[i] = kzalloc(ET61X251_ISO_PACKETS * psz,
558
						  GFP_KERNEL);
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
		if (!cam->transfer_buffer[i]) {
			err = -ENOMEM;
			DBG(1, "Not enough memory");
			goto free_buffers;
		}
	}

	for (i = 0; i < ET61X251_URBS; i++) {
		urb = usb_alloc_urb(ET61X251_ISO_PACKETS, GFP_KERNEL);
		cam->urb[i] = urb;
		if (!urb) {
			err = -ENOMEM;
			DBG(1, "usb_alloc_urb() failed");
			goto free_urbs;
		}
		urb->dev = udev;
		urb->context = cam;
		urb->pipe = usb_rcvisocpipe(udev, 1);
		urb->transfer_flags = URB_ISO_ASAP;
		urb->number_of_packets = ET61X251_ISO_PACKETS;
		urb->complete = et61x251_urb_complete;
		urb->transfer_buffer = cam->transfer_buffer[i];
		urb->transfer_buffer_length = psz * ET61X251_ISO_PACKETS;
		urb->interval = 1;
		for (j = 0; j < ET61X251_ISO_PACKETS; j++) {
			urb->iso_frame_desc[j].offset = psz * j;
			urb->iso_frame_desc[j].length = psz;
		}
	}

	err = et61x251_write_reg(cam, 0x01, 0x03);
	err = et61x251_write_reg(cam, 0x00, 0x03);
	err = et61x251_write_reg(cam, 0x08, 0x03);
	if (err) {
		err = -EIO;
		DBG(1, "I/O hardware error");
		goto free_urbs;
	}

	err = usb_set_interface(udev, 0, ET61X251_ALTERNATE_SETTING);
	if (err) {
		DBG(1, "usb_set_interface() failed");
		goto free_urbs;
	}

	cam->frame_current = NULL;

	for (i = 0; i < ET61X251_URBS; i++) {
		err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
		if (err) {
			for (j = i-1; j >= 0; j--)
				usb_kill_urb(cam->urb[j]);
			DBG(1, "usb_submit_urb() failed, error %d", err);
			goto free_urbs;
		}
	}

	return 0;

free_urbs:
619
	for (i = 0; (i < ET61X251_URBS) && cam->urb[i]; i++)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
		usb_free_urb(cam->urb[i]);

free_buffers:
	for (i = 0; (i < ET61X251_URBS) && cam->transfer_buffer[i]; i++)
		kfree(cam->transfer_buffer[i]);

	return err;
}


static int et61x251_stop_transfer(struct et61x251_device* cam)
{
	struct usb_device *udev = cam->usbdev;
	s8 i;
	int err = 0;

	if (cam->state & DEV_DISCONNECTED)
		return 0;

	for (i = ET61X251_URBS-1; i >= 0; i--) {
		usb_kill_urb(cam->urb[i]);
		usb_free_urb(cam->urb[i]);
		kfree(cam->transfer_buffer[i]);
	}

	err = usb_set_interface(udev, 0, 0); /* 0 Mb/s */
	if (err)
		DBG(3, "usb_set_interface() failed");

	return err;
}


static int et61x251_stream_interrupt(struct et61x251_device* cam)
{
655
	long timeout;
656 657

	cam->stream = STREAM_INTERRUPT;
658
	timeout = wait_event_timeout(cam->wait_stream,
659 660 661
				     (cam->stream == STREAM_OFF) ||
				     (cam->state & DEV_DISCONNECTED),
				     ET61X251_URB_TIMEOUT);
662 663
	if (cam->state & DEV_DISCONNECTED)
		return -ENODEV;
664
	else if (cam->stream != STREAM_OFF) {
665 666 667 668
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "URB timeout reached. The camera is misconfigured. To "
		       "use it, close and open /dev/video%d again.",
		    cam->v4ldev->minor);
669
		return -EIO;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
	}

	return 0;
}

/*****************************************************************************/

#ifdef CONFIG_VIDEO_ADV_DEBUG
static u8 et61x251_strtou8(const char* buff, size_t len, ssize_t* count)
{
	char str[5];
	char* endp;
	unsigned long val;

	if (len < 4) {
		strncpy(str, buff, len);
686
		str[len] = '\0';
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
	} else {
		strncpy(str, buff, 4);
		str[4] = '\0';
	}

	val = simple_strtoul(str, &endp, 0);

	*count = 0;
	if (val <= 0xff)
		*count = (ssize_t)(endp - str);
	if ((*count) && (len == *count+1) && (buff[*count] == '\n'))
		*count += 1;

	return (u8)val;
}

/*
   NOTE 1: being inside one of the following methods implies that the v4l
705
	   device exists for sure (see kobjects and reference counters)
706 707 708 709 710 711 712 713
   NOTE 2: buffers are PAGE_SIZE long
*/

static ssize_t et61x251_show_reg(struct class_device* cd, char* buf)
{
	struct et61x251_device* cam;
	ssize_t count;

714
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
715 716 717 718
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
719
		mutex_unlock(&et61x251_sysfs_lock);
720 721 722 723 724
		return -ENODEV;
	}

	count = sprintf(buf, "%u\n", cam->sysfs.reg);

725
	mutex_unlock(&et61x251_sysfs_lock);
726 727 728 729 730 731 732 733 734 735 736 737

	return count;
}


static ssize_t
et61x251_store_reg(struct class_device* cd, const char* buf, size_t len)
{
	struct et61x251_device* cam;
	u8 index;
	ssize_t count;

738
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
739 740 741 742
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
743
		mutex_unlock(&et61x251_sysfs_lock);
744 745 746 747 748
		return -ENODEV;
	}

	index = et61x251_strtou8(buf, len, &count);
	if (index > 0x8e || !count) {
749
		mutex_unlock(&et61x251_sysfs_lock);
750 751 752 753 754 755 756 757
		return -EINVAL;
	}

	cam->sysfs.reg = index;

	DBG(2, "Moved ET61X[12]51 register index to 0x%02X", cam->sysfs.reg);
	DBG(3, "Written bytes: %zd", count);

758
	mutex_unlock(&et61x251_sysfs_lock);
759 760 761 762 763 764 765 766 767 768 769

	return count;
}


static ssize_t et61x251_show_val(struct class_device* cd, char* buf)
{
	struct et61x251_device* cam;
	ssize_t count;
	int val;

770
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
771 772 773 774
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
775
		mutex_unlock(&et61x251_sysfs_lock);
776 777 778 779
		return -ENODEV;
	}

	if ((val = et61x251_read_reg(cam, cam->sysfs.reg)) < 0) {
780
		mutex_unlock(&et61x251_sysfs_lock);
781 782 783 784 785 786 787
		return -EIO;
	}

	count = sprintf(buf, "%d\n", val);

	DBG(3, "Read bytes: %zd", count);

788
	mutex_unlock(&et61x251_sysfs_lock);
789 790 791 792 793 794 795 796 797 798 799 800 801

	return count;
}


static ssize_t
et61x251_store_val(struct class_device* cd, const char* buf, size_t len)
{
	struct et61x251_device* cam;
	u8 value;
	ssize_t count;
	int err;

802
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
803 804 805 806
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
807
		mutex_unlock(&et61x251_sysfs_lock);
808 809 810 811 812
		return -ENODEV;
	}

	value = et61x251_strtou8(buf, len, &count);
	if (!count) {
813
		mutex_unlock(&et61x251_sysfs_lock);
814 815 816 817 818
		return -EINVAL;
	}

	err = et61x251_write_reg(cam, value, cam->sysfs.reg);
	if (err) {
819
		mutex_unlock(&et61x251_sysfs_lock);
820 821 822 823 824 825 826
		return -EIO;
	}

	DBG(2, "Written ET61X[12]51 reg. 0x%02X, val. 0x%02X",
	    cam->sysfs.reg, value);
	DBG(3, "Written bytes: %zd", count);

827
	mutex_unlock(&et61x251_sysfs_lock);
828 829 830 831 832 833 834 835 836 837

	return count;
}


static ssize_t et61x251_show_i2c_reg(struct class_device* cd, char* buf)
{
	struct et61x251_device* cam;
	ssize_t count;

838
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
839 840 841 842
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
843
		mutex_unlock(&et61x251_sysfs_lock);
844 845 846 847 848 849 850
		return -ENODEV;
	}

	count = sprintf(buf, "%u\n", cam->sysfs.i2c_reg);

	DBG(3, "Read bytes: %zd", count);

851
	mutex_unlock(&et61x251_sysfs_lock);
852 853 854 855 856 857 858 859 860 861 862 863

	return count;
}


static ssize_t
et61x251_store_i2c_reg(struct class_device* cd, const char* buf, size_t len)
{
	struct et61x251_device* cam;
	u8 index;
	ssize_t count;

864
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
865 866 867 868
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
869
		mutex_unlock(&et61x251_sysfs_lock);
870 871 872 873 874
		return -ENODEV;
	}

	index = et61x251_strtou8(buf, len, &count);
	if (!count) {
875
		mutex_unlock(&et61x251_sysfs_lock);
876 877 878 879 880 881 882 883
		return -EINVAL;
	}

	cam->sysfs.i2c_reg = index;

	DBG(2, "Moved sensor register index to 0x%02X", cam->sysfs.i2c_reg);
	DBG(3, "Written bytes: %zd", count);

884
	mutex_unlock(&et61x251_sysfs_lock);
885 886 887 888 889 890 891 892 893 894 895

	return count;
}


static ssize_t et61x251_show_i2c_val(struct class_device* cd, char* buf)
{
	struct et61x251_device* cam;
	ssize_t count;
	int val;

896
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
897 898 899 900
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
901
		mutex_unlock(&et61x251_sysfs_lock);
902 903 904
		return -ENODEV;
	}

905 906
	if (!(cam->sensor.sysfs_ops & ET61X251_I2C_READ)) {
		mutex_unlock(&et61x251_sysfs_lock);
907 908 909 910
		return -ENOSYS;
	}

	if ((val = et61x251_i2c_read(cam, cam->sysfs.i2c_reg)) < 0) {
911
		mutex_unlock(&et61x251_sysfs_lock);
912 913 914 915 916 917 918
		return -EIO;
	}

	count = sprintf(buf, "%d\n", val);

	DBG(3, "Read bytes: %zd", count);

919
	mutex_unlock(&et61x251_sysfs_lock);
920 921 922 923 924 925 926 927 928 929 930 931 932

	return count;
}


static ssize_t
et61x251_store_i2c_val(struct class_device* cd, const char* buf, size_t len)
{
	struct et61x251_device* cam;
	u8 value;
	ssize_t count;
	int err;

933
	if (mutex_lock_interruptible(&et61x251_sysfs_lock))
934 935 936 937
		return -ERESTARTSYS;

	cam = video_get_drvdata(to_video_device(cd));
	if (!cam) {
938
		mutex_unlock(&et61x251_sysfs_lock);
939 940 941
		return -ENODEV;
	}

942 943
	if (!(cam->sensor.sysfs_ops & ET61X251_I2C_READ)) {
		mutex_unlock(&et61x251_sysfs_lock);
944 945 946 947 948
		return -ENOSYS;
	}

	value = et61x251_strtou8(buf, len, &count);
	if (!count) {
949
		mutex_unlock(&et61x251_sysfs_lock);
950 951 952 953 954
		return -EINVAL;
	}

	err = et61x251_i2c_write(cam, cam->sysfs.i2c_reg, value);
	if (err) {
955
		mutex_unlock(&et61x251_sysfs_lock);
956 957 958 959 960 961 962
		return -EIO;
	}

	DBG(2, "Written sensor reg. 0x%02X, val. 0x%02X",
	    cam->sysfs.i2c_reg, value);
	DBG(3, "Written bytes: %zd", count);

963
	mutex_unlock(&et61x251_sysfs_lock);
964 965 966 967 968 969

	return count;
}


static CLASS_DEVICE_ATTR(reg, S_IRUGO | S_IWUSR,
970
			 et61x251_show_reg, et61x251_store_reg);
971
static CLASS_DEVICE_ATTR(val, S_IRUGO | S_IWUSR,
972
			 et61x251_show_val, et61x251_store_val);
973
static CLASS_DEVICE_ATTR(i2c_reg, S_IRUGO | S_IWUSR,
974
			 et61x251_show_i2c_reg, et61x251_store_i2c_reg);
975
static CLASS_DEVICE_ATTR(i2c_val, S_IRUGO | S_IWUSR,
976
			 et61x251_show_i2c_val, et61x251_store_i2c_val);
977 978


979
static int et61x251_create_sysfs(struct et61x251_device* cam)
980
{
981
	struct class_device *classdev = &(cam->v4ldev->class_dev);
982 983
	int err = 0;

984
	if ((err = class_device_create_file(classdev, &class_device_attr_reg)))
985
		goto err_out;
986
	if ((err = class_device_create_file(classdev, &class_device_attr_val)))
987
		goto err_reg;
988

989
	if (cam->sensor.sysfs_ops) {
990
		if ((err = class_device_create_file(classdev,
991 992
						  &class_device_attr_i2c_reg)))
			goto err_val;
993
		if ((err = class_device_create_file(classdev,
994 995
						  &class_device_attr_i2c_val)))
			goto err_i2c_reg;
996
	}
997 998

err_i2c_reg:
999
	if (cam->sensor.sysfs_ops)
1000
		class_device_remove_file(classdev, &class_device_attr_i2c_reg);
1001
err_val:
1002
	class_device_remove_file(classdev, &class_device_attr_val);
1003
err_reg:
1004
	class_device_remove_file(classdev, &class_device_attr_reg);
1005 1006
err_out:
	return err;
1007 1008 1009 1010 1011 1012 1013
}
#endif /* CONFIG_VIDEO_ADV_DEBUG */

/*****************************************************************************/

static int
et61x251_set_pix_format(struct et61x251_device* cam,
1014
			struct v4l2_pix_format* pix)
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
{
	int r, err = 0;

	if ((r = et61x251_read_reg(cam, 0x12)) < 0)
		err += r;
	if (pix->pixelformat == V4L2_PIX_FMT_ET61X251)
		err += et61x251_write_reg(cam, r & 0xfd, 0x12);
	else
		err += et61x251_write_reg(cam, r | 0x02, 0x12);

	return err ? -EIO : 0;
}


static int
et61x251_set_compression(struct et61x251_device* cam,
1031
			 struct v4l2_jpegcompression* compression)
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
{
	int r, err = 0;

	if ((r = et61x251_read_reg(cam, 0x12)) < 0)
		err += r;
	if (compression->quality == 0)
		err += et61x251_write_reg(cam, r & 0xfb, 0x12);
	else
		err += et61x251_write_reg(cam, r | 0x04, 0x12);

	return err ? -EIO : 0;
}


static int et61x251_set_scale(struct et61x251_device* cam, u8 scale)
{
	int r = 0, err = 0;

	r = et61x251_read_reg(cam, 0x12);
	if (r < 0)
		err += r;

	if (scale == 1)
		err += et61x251_write_reg(cam, r & ~0x01, 0x12);
	else if (scale == 2)
		err += et61x251_write_reg(cam, r | 0x01, 0x12);

	if (err)
		return -EIO;

	PDBGG("Scaling factor: %u", scale);

	return 0;
}


static int
et61x251_set_crop(struct et61x251_device* cam, struct v4l2_rect* rect)
{
1071
	struct et61x251_sensor* s = &cam->sensor;
1072
	u16 fmw_sx = (u16)(rect->left - s->cropcap.bounds.left +
1073
			   s->active_pixel.left),
1074
	    fmw_sy = (u16)(rect->top - s->cropcap.bounds.top +
1075
			   s->active_pixel.top),
1076 1077 1078 1079 1080 1081 1082 1083 1084
	    fmw_length = (u16)(rect->width),
	    fmw_height = (u16)(rect->height);
	int err = 0;

	err += et61x251_write_reg(cam, fmw_sx & 0xff, 0x69);
	err += et61x251_write_reg(cam, fmw_sy & 0xff, 0x6a);
	err += et61x251_write_reg(cam, fmw_length & 0xff, 0x6b);
	err += et61x251_write_reg(cam, fmw_height & 0xff, 0x6c);
	err += et61x251_write_reg(cam, (fmw_sx >> 8) | ((fmw_sy & 0x300) >> 6)
1085 1086
				       | ((fmw_length & 0x300) >> 4)
				       | ((fmw_height & 0x300) >> 2), 0x6d);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
	if (err)
		return -EIO;

	PDBGG("fmw_sx, fmw_sy, fmw_length, fmw_height: %u %u %u %u",
	      fmw_sx, fmw_sy, fmw_length, fmw_height);

	return 0;
}


static int et61x251_init(struct et61x251_device* cam)
{
1099
	struct et61x251_sensor* s = &cam->sensor;
1100 1101 1102 1103 1104 1105 1106
	struct v4l2_control ctrl;
	struct v4l2_queryctrl *qctrl;
	struct v4l2_rect* rect;
	u8 i = 0;
	int err = 0;

	if (!(cam->state & DEV_INITIALIZED)) {
1107 1108
		mutex_init(&cam->open_mutex);
		init_waitqueue_head(&cam->wait_open);
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
		qctrl = s->qctrl;
		rect = &(s->cropcap.defrect);
		cam->compression.quality = ET61X251_COMPRESSION_QUALITY;
	} else { /* use current values */
		qctrl = s->_qctrl;
		rect = &(s->_rect);
	}

	err += et61x251_set_scale(cam, rect->width / s->pix_format.width);
	err += et61x251_set_crop(cam, rect);
	if (err)
		return err;

	if (s->init) {
		err = s->init(cam);
		if (err) {
			DBG(3, "Sensor initialization failed");
			return err;
		}
	}

	err += et61x251_set_compression(cam, &cam->compression);
	err += et61x251_set_pix_format(cam, &s->pix_format);
	if (s->set_pix_format)
		err += s->set_pix_format(cam, &s->pix_format);
	if (err)
		return err;

	if (s->pix_format.pixelformat == V4L2_PIX_FMT_ET61X251)
		DBG(3, "Compressed video format is active, quality %d",
		    cam->compression.quality);
	else
		DBG(3, "Uncompressed video format is active");

	if (s->set_crop)
		if ((err = s->set_crop(cam, rect))) {
			DBG(3, "set_crop() failed");
			return err;
		}

	if (s->set_ctrl) {
		for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
			if (s->qctrl[i].id != 0 &&
			    !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
				ctrl.id = s->qctrl[i].id;
				ctrl.value = qctrl[i].default_value;
				err = s->set_ctrl(cam, &ctrl);
				if (err) {
					DBG(3, "Set %s control failed",
					    s->qctrl[i].name);
					return err;
				}
				DBG(3, "Image sensor supports '%s' control",
				    s->qctrl[i].name);
			}
	}

	if (!(cam->state & DEV_INITIALIZED)) {
1167
		mutex_init(&cam->fileop_mutex);
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
		spin_lock_init(&cam->queue_lock);
		init_waitqueue_head(&cam->wait_frame);
		init_waitqueue_head(&cam->wait_stream);
		cam->nreadbuffers = 2;
		memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
		memcpy(&(s->_rect), &(s->cropcap.defrect),
		       sizeof(struct v4l2_rect));
		cam->state |= DEV_INITIALIZED;
	}

	DBG(2, "Initialization succeeded");
	return 0;
}

1182
/*****************************************************************************/
1183

1184
static void et61x251_release_resources(struct kref *kref)
1185
{
1186 1187
	struct et61x251_device *cam;

1188
	mutex_lock(&et61x251_sysfs_lock);
1189

1190 1191
	cam = container_of(kref, struct et61x251_device, kref);

1192 1193 1194
	DBG(2, "V4L2 device /dev/video%d deregistered", cam->v4ldev->minor);
	video_set_drvdata(cam->v4ldev, NULL);
	video_unregister_device(cam->v4ldev);
1195 1196 1197
	usb_put_dev(cam->usbdev);
	kfree(cam->control_buffer);
	kfree(cam);
1198

1199
	mutex_unlock(&et61x251_sysfs_lock);
1200 1201 1202 1203 1204 1205 1206 1207
}


static int et61x251_open(struct inode* inode, struct file* filp)
{
	struct et61x251_device* cam;
	int err = 0;

1208
	if (!down_read_trylock(&et61x251_dev_lock))
1209 1210 1211 1212
		return -ERESTARTSYS;

	cam = video_get_drvdata(video_devdata(filp));

1213 1214
	if (wait_for_completion_interruptible(&cam->probe)) {
		up_read(&et61x251_dev_lock);
1215 1216 1217
		return -ERESTARTSYS;
	}

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
	kref_get(&cam->kref);

	if (mutex_lock_interruptible(&cam->open_mutex)) {
		kref_put(&cam->kref, et61x251_release_resources);
		up_read(&et61x251_dev_lock);
		return -ERESTARTSYS;
	}

	if (cam->state & DEV_DISCONNECTED) {
		DBG(1, "Device not present");
		err = -ENODEV;
		goto out;
	}

1232
	if (cam->users) {
1233 1234 1235
		DBG(2, "Device /dev/video%d is already in use",
		       cam->v4ldev->minor);
		DBG(3, "Simultaneous opens are not supported");
1236 1237 1238 1239 1240
		if ((filp->f_flags & O_NONBLOCK) ||
		    (filp->f_flags & O_NDELAY)) {
			err = -EWOULDBLOCK;
			goto out;
		}
1241 1242 1243 1244 1245
		DBG(2, "A blocking open() has been requested. Wait for the "
		       "device to be released...");
		up_read(&et61x251_dev_lock);
		err = wait_event_interruptible_exclusive(cam->wait_open,
						(cam->state & DEV_DISCONNECTED)
1246
							 || !cam->users);
1247 1248 1249
		down_read(&et61x251_dev_lock);
		if (err)
			goto out;
1250
		if (cam->state & DEV_DISCONNECTED) {
1251 1252
			err = -ENODEV;
			goto out;
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
		}
	}

	if (cam->state & DEV_MISCONFIGURED) {
		err = et61x251_init(cam);
		if (err) {
			DBG(1, "Initialization failed again. "
			       "I will retry on next open().");
			goto out;
		}
		cam->state &= ~DEV_MISCONFIGURED;
	}

	if ((err = et61x251_start_transfer(cam)))
		goto out;

	filp->private_data = cam;
	cam->users++;
	cam->io = IO_NONE;
	cam->stream = STREAM_OFF;
	cam->nbuffers = 0;
	cam->frame_count = 0;
	et61x251_empty_framequeues(cam);

	DBG(3, "Video device /dev/video%d is open", cam->v4ldev->minor);

out:
1280 1281 1282 1283
	mutex_unlock(&cam->open_mutex);
	if (err)
		kref_put(&cam->kref, et61x251_release_resources);
	up_read(&et61x251_dev_lock);
1284 1285 1286 1287 1288 1289
	return err;
}


static int et61x251_release(struct inode* inode, struct file* filp)
{
1290
	struct et61x251_device* cam;
1291

1292
	down_write(&et61x251_dev_lock);
1293

1294
	cam = video_get_drvdata(video_devdata(filp));
1295

1296
	et61x251_stop_transfer(cam);
1297 1298
	et61x251_release_buffers(cam);
	cam->users--;
1299
	wake_up_interruptible_nr(&cam->wait_open, 1);
1300 1301 1302

	DBG(3, "Video device /dev/video%d closed", cam->v4ldev->minor);

1303 1304 1305
	kref_put(&cam->kref, et61x251_release_resources);

	up_write(&et61x251_dev_lock);
1306 1307 1308 1309 1310 1311 1312

	return 0;
}


static ssize_t
et61x251_read(struct file* filp, char __user * buf,
1313
	      size_t count, loff_t* f_pos)
1314 1315 1316 1317
{
	struct et61x251_device* cam = video_get_drvdata(video_devdata(filp));
	struct et61x251_frame_t* f, * i;
	unsigned long lock_flags;
1318
	long timeout;
1319 1320
	int err = 0;

1321
	if (mutex_lock_interruptible(&cam->fileop_mutex))
1322 1323 1324 1325
		return -ERESTARTSYS;

	if (cam->state & DEV_DISCONNECTED) {
		DBG(1, "Device not present");
1326
		mutex_unlock(&cam->fileop_mutex);
1327 1328 1329 1330 1331 1332
		return -ENODEV;
	}

	if (cam->state & DEV_MISCONFIGURED) {
		DBG(1, "The camera is misconfigured. Close and open it "
		       "again.");
1333
		mutex_unlock(&cam->fileop_mutex);
1334 1335 1336 1337 1338 1339
		return -EIO;
	}

	if (cam->io == IO_MMAP) {
		DBG(3, "Close and open the device again to choose the read "
		       "method");
1340
		mutex_unlock(&cam->fileop_mutex);
1341
		return -EBUSY;
1342 1343 1344 1345
	}

	if (cam->io == IO_NONE) {
		if (!et61x251_request_buffers(cam, cam->nreadbuffers,
1346
					      IO_READ)) {
1347
			DBG(1, "read() failed, not enough memory");
1348
			mutex_unlock(&cam->fileop_mutex);
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
			return -ENOMEM;
		}
		cam->io = IO_READ;
		cam->stream = STREAM_ON;
	}

	if (list_empty(&cam->inqueue)) {
		if (!list_empty(&cam->outqueue))
			et61x251_empty_framequeues(cam);
		et61x251_queue_unusedframes(cam);
	}

	if (!count) {
1362
		mutex_unlock(&cam->fileop_mutex);
1363 1364 1365 1366 1367
		return 0;
	}

	if (list_empty(&cam->outqueue)) {
		if (filp->f_flags & O_NONBLOCK) {
1368
			mutex_unlock(&cam->fileop_mutex);
1369 1370
			return -EAGAIN;
		}
1371
		timeout = wait_event_interruptible_timeout
1372 1373 1374 1375 1376 1377
			  ( cam->wait_frame,
			    (!list_empty(&cam->outqueue)) ||
			    (cam->state & DEV_DISCONNECTED) ||
			    (cam->state & DEV_MISCONFIGURED),
			    cam->module_param.frame_timeout *
			    1000 * msecs_to_jiffies(1) );
1378 1379 1380
		if (timeout < 0) {
			mutex_unlock(&cam->fileop_mutex);
			return timeout;
1381 1382
		}
		if (cam->state & DEV_DISCONNECTED) {
1383
			mutex_unlock(&cam->fileop_mutex);
1384 1385
			return -ENODEV;
		}
1386 1387
		if (!timeout || (cam->state & DEV_MISCONFIGURED)) {
			mutex_unlock(&cam->fileop_mutex);
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
			return -EIO;
		}
	}

	f = list_entry(cam->outqueue.prev, struct et61x251_frame_t, frame);

	if (count > f->buf.bytesused)
		count = f->buf.bytesused;

	if (copy_to_user(buf, f->bufmem, count)) {
		err = -EFAULT;
		goto exit;
	}
	*f_pos += count;

exit:
	spin_lock_irqsave(&cam->queue_lock, lock_flags);
	list_for_each_entry(i, &cam->outqueue, frame)
		i->state = F_UNUSED;
	INIT_LIST_HEAD(&cam->outqueue);
	spin_unlock_irqrestore(&cam->queue_lock, lock_flags);

	et61x251_queue_unusedframes(cam);

	PDBGG("Frame #%lu, bytes read: %zu",
	      (unsigned long)f->buf.index, count);

1415
	mutex_unlock(&cam->fileop_mutex);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427

	return err ? err : count;
}


static unsigned int et61x251_poll(struct file *filp, poll_table *wait)
{
	struct et61x251_device* cam = video_get_drvdata(video_devdata(filp));
	struct et61x251_frame_t* f;
	unsigned long lock_flags;
	unsigned int mask = 0;

1428
	if (mutex_lock_interruptible(&cam->fileop_mutex))
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
		return POLLERR;

	if (cam->state & DEV_DISCONNECTED) {
		DBG(1, "Device not present");
		goto error;
	}

	if (cam->state & DEV_MISCONFIGURED) {
		DBG(1, "The camera is misconfigured. Close and open it "
		       "again.");
		goto error;
	}

	if (cam->io == IO_NONE) {
		if (!et61x251_request_buffers(cam, cam->nreadbuffers,
1444
					      IO_READ)) {
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
			DBG(1, "poll() failed, not enough memory");
			goto error;
		}
		cam->io = IO_READ;
		cam->stream = STREAM_ON;
	}

	if (cam->io == IO_READ) {
		spin_lock_irqsave(&cam->queue_lock, lock_flags);
		list_for_each_entry(f, &cam->outqueue, frame)
			f->state = F_UNUSED;
		INIT_LIST_HEAD(&cam->outqueue);
		spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
		et61x251_queue_unusedframes(cam);
	}

	poll_wait(filp, &cam->wait_frame, wait);

	if (!list_empty(&cam->outqueue))
		mask |= POLLIN | POLLRDNORM;

1466
	mutex_unlock(&cam->fileop_mutex);
1467 1468 1469 1470

	return mask;

error:
1471
	mutex_unlock(&cam->fileop_mutex);
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
	return POLLERR;
}


static void et61x251_vm_open(struct vm_area_struct* vma)
{
	struct et61x251_frame_t* f = vma->vm_private_data;
	f->vma_use_count++;
}


static void et61x251_vm_close(struct vm_area_struct* vma)
{
	/* NOTE: buffers are not freed here */
	struct et61x251_frame_t* f = vma->vm_private_data;
	f->vma_use_count--;
}


static struct vm_operations_struct et61x251_vm_ops = {
	.open = et61x251_vm_open,
	.close = et61x251_vm_close,
};


static int et61x251_mmap(struct file* filp, struct vm_area_struct *vma)
{
	struct et61x251_device* cam = video_get_drvdata(video_devdata(filp));
	unsigned long size = vma->vm_end - vma->vm_start,
1501
		      start = vma->vm_start;
1502 1503 1504
	void *pos;
	u32 i;

1505
	if (mutex_lock_interruptible(&cam->fileop_mutex))
1506 1507 1508 1509
		return -ERESTARTSYS;

	if (cam->state & DEV_DISCONNECTED) {
		DBG(1, "Device not present");
1510
		mutex_unlock(&cam->fileop_mutex);
1511 1512 1513 1514 1515 1516
		return -ENODEV;
	}

	if (cam->state & DEV_MISCONFIGURED) {
		DBG(1, "The camera is misconfigured. Close and open it "
		       "again.");
1517
		mutex_unlock(&cam->fileop_mutex);
1518 1519 1520
		return -EIO;
	}

1521 1522 1523 1524 1525 1526
	if (!(vma->vm_flags & (VM_WRITE | VM_READ))) {
		mutex_unlock(&cam->fileop_mutex);
		return -EACCES;
	}

	if (cam->io != IO_MMAP ||
1527
	    size != PAGE_ALIGN(cam->frame[0].buf.length)) {
1528
		mutex_unlock(&cam->fileop_mutex);
1529 1530 1531 1532 1533 1534 1535 1536
		return -EINVAL;
	}

	for (i = 0; i < cam->nbuffers; i++) {
		if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
			break;
	}
	if (i == cam->nbuffers) {
1537
		mutex_unlock(&cam->fileop_mutex);
1538 1539 1540 1541 1542 1543 1544 1545 1546
		return -EINVAL;
	}

	vma->vm_flags |= VM_IO;
	vma->vm_flags |= VM_RESERVED;

	pos = cam->frame[i].bufmem;
	while (size > 0) { /* size is page-aligned */
		if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
1547
			mutex_unlock(&cam->fileop_mutex);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
			return -EAGAIN;
		}
		start += PAGE_SIZE;
		pos += PAGE_SIZE;
		size -= PAGE_SIZE;
	}

	vma->vm_ops = &et61x251_vm_ops;
	vma->vm_private_data = &cam->frame[i];
	et61x251_vm_open(vma);

1559
	mutex_unlock(&cam->fileop_mutex);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572

	return 0;
}

/*****************************************************************************/

static int
et61x251_vidioc_querycap(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_capability cap = {
		.driver = "et61x251",
		.version = ET61X251_MODULE_VERSION_CODE,
		.capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
1573
				V4L2_CAP_STREAMING,
1574 1575 1576 1577 1578
	};

	strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
	if (usb_make_path(cam->usbdev, cap.bus_info, sizeof(cap.bus_info)) < 0)
		strlcpy(cap.bus_info, cam->usbdev->dev.bus_id,
1579
			sizeof(cap.bus_info));
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600

	if (copy_to_user(arg, &cap, sizeof(cap)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_enuminput(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_input i;

	if (copy_from_user(&i, arg, sizeof(i)))
		return -EFAULT;

	if (i.index)
		return -EINVAL;

	memset(&i, 0, sizeof(i));
	strcpy(i.name, "Camera");
1601
	i.type = V4L2_INPUT_TYPE_CAMERA;
1602 1603 1604 1605 1606 1607 1608 1609 1610

	if (copy_to_user(arg, &i, sizeof(i)))
		return -EFAULT;

	return 0;
}


static int
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
et61x251_vidioc_g_input(struct et61x251_device* cam, void __user * arg)
{
	int index = 0;

	if (copy_to_user(arg, &index, sizeof(index)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_s_input(struct et61x251_device* cam, void __user * arg)
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
{
	int index;

	if (copy_from_user(&index, arg, sizeof(index)))
		return -EFAULT;

	if (index != 0)
		return -EINVAL;

	return 0;
}


static int
et61x251_vidioc_query_ctrl(struct et61x251_device* cam, void __user * arg)
{
1640
	struct et61x251_sensor* s = &cam->sensor;
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
	struct v4l2_queryctrl qc;
	u8 i;

	if (copy_from_user(&qc, arg, sizeof(qc)))
		return -EFAULT;

	for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
		if (qc.id && qc.id == s->qctrl[i].id) {
			memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
			if (copy_to_user(arg, &qc, sizeof(qc)))
				return -EFAULT;
			return 0;
		}

	return -EINVAL;
}


static int
et61x251_vidioc_g_ctrl(struct et61x251_device* cam, void __user * arg)
{
1662
	struct et61x251_sensor* s = &cam->sensor;
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
	struct v4l2_control ctrl;
	int err = 0;
	u8 i;

	if (!s->get_ctrl && !s->set_ctrl)
		return -EINVAL;

	if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
		return -EFAULT;

	if (!s->get_ctrl) {
		for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
			if (ctrl.id == s->qctrl[i].id) {
				ctrl.value = s->_qctrl[i].default_value;
				goto exit;
			}
		return -EINVAL;
	} else
		err = s->get_ctrl(cam, &ctrl);

exit:
	if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
		return -EFAULT;

	return err;
}


static int
et61x251_vidioc_s_ctrl(struct et61x251_device* cam, void __user * arg)
{
1694
	struct et61x251_sensor* s = &cam->sensor;
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
	struct v4l2_control ctrl;
	u8 i;
	int err = 0;

	if (!s->set_ctrl)
		return -EINVAL;

	if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
		return -EFAULT;

	for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
		if (ctrl.id == s->qctrl[i].id) {
1707 1708
			if (s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)
				return -EINVAL;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
			if (ctrl.value < s->qctrl[i].minimum ||
			    ctrl.value > s->qctrl[i].maximum)
				return -ERANGE;
			ctrl.value -= ctrl.value % s->qctrl[i].step;
			break;
		}

	if ((err = s->set_ctrl(cam, &ctrl)))
		return err;

	s->_qctrl[i].default_value = ctrl.value;

	return 0;
}


static int
et61x251_vidioc_cropcap(struct et61x251_device* cam, void __user * arg)
{
1728
	struct v4l2_cropcap* cc = &(cam->sensor.cropcap);
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

	cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	cc->pixelaspect.numerator = 1;
	cc->pixelaspect.denominator = 1;

	if (copy_to_user(arg, cc, sizeof(*cc)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_g_crop(struct et61x251_device* cam, void __user * arg)
{
1744
	struct et61x251_sensor* s = &cam->sensor;
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
	struct v4l2_crop crop = {
		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
	};

	memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));

	if (copy_to_user(arg, &crop, sizeof(crop)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_s_crop(struct et61x251_device* cam, void __user * arg)
{
1761
	struct et61x251_sensor* s = &cam->sensor;
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
	struct v4l2_crop crop;
	struct v4l2_rect* rect;
	struct v4l2_rect* bounds = &(s->cropcap.bounds);
	struct v4l2_pix_format* pix_format = &(s->pix_format);
	u8 scale;
	const enum et61x251_stream_state stream = cam->stream;
	const u32 nbuffers = cam->nbuffers;
	u32 i;
	int err = 0;

	if (copy_from_user(&crop, arg, sizeof(crop)))
		return -EFAULT;

	rect = &(crop.c);

	if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

	if (cam->module_param.force_munmap)
		for (i = 0; i < cam->nbuffers; i++)
			if (cam->frame[i].vma_use_count) {
				DBG(3, "VIDIOC_S_CROP failed. "
				       "Unmap the buffers first.");
1785
				return -EBUSY;
1786 1787 1788 1789 1790 1791
			}

	/* Preserve R,G or B origin */
	rect->left = (s->_rect.left & 1L) ? rect->left | 1L : rect->left & ~1L;
	rect->top = (s->_rect.top & 1L) ? rect->top | 1L : rect->top & ~1L;

1792 1793 1794 1795
	if (rect->width < 16)
		rect->width = 16;
	if (rect->height < 16)
		rect->height = 16;
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
	if (rect->width > bounds->width)
		rect->width = bounds->width;
	if (rect->height > bounds->height)
		rect->height = bounds->height;
	if (rect->left < bounds->left)
		rect->left = bounds->left;
	if (rect->top < bounds->top)
		rect->top = bounds->top;
	if (rect->left + rect->width > bounds->left + bounds->width)
		rect->left = bounds->left+bounds->width - rect->width;
	if (rect->top + rect->height > bounds->top + bounds->height)
		rect->top = bounds->top+bounds->height - rect->height;

1809 1810
	rect->width &= ~15L;
	rect->height &= ~15L;
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

	if (ET61X251_PRESERVE_IMGSCALE) {
		/* Calculate the actual scaling factor */
		u32 a, b;
		a = rect->width * rect->height;
		b = pix_format->width * pix_format->height;
		scale = b ? (u8)((a / b) < 4 ? 1 : 2) : 1;
	} else
		scale = 1;

	if (cam->stream == STREAM_ON)
		if ((err = et61x251_stream_interrupt(cam)))
			return err;

	if (copy_to_user(arg, &crop, sizeof(crop))) {
		cam->stream = stream;
		return -EFAULT;
	}

	if (cam->module_param.force_munmap || cam->io == IO_READ)
		et61x251_release_buffers(cam);

	err = et61x251_set_crop(cam, rect);
	if (s->set_crop)
		err += s->set_crop(cam, rect);
	err += et61x251_set_scale(cam, scale);

	if (err) { /* atomic, no rollback in ioctl() */
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "VIDIOC_S_CROP failed because of hardware problems. To "
		       "use the camera, close and open /dev/video%d again.",
		    cam->v4ldev->minor);
		return -EIO;
	}

	s->pix_format.width = rect->width/scale;
	s->pix_format.height = rect->height/scale;
	memcpy(&(s->_rect), rect, sizeof(*rect));

	if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
	    nbuffers != et61x251_request_buffers(cam, nbuffers, cam->io)) {
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "VIDIOC_S_CROP failed because of not enough memory. To "
		       "use the camera, close and open /dev/video%d again.",
		    cam->v4ldev->minor);
		return -ENOMEM;
	}

	if (cam->io == IO_READ)
		et61x251_empty_framequeues(cam);
	else if (cam->module_param.force_munmap)
		et61x251_requeue_outqueue(cam);

	cam->stream = stream;

	return 0;
}


1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
static int
et61x251_vidioc_enum_framesizes(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_frmsizeenum frmsize;

	if (copy_from_user(&frmsize, arg, sizeof(frmsize)))
		return -EFAULT;

	if (frmsize.index != 0)
		return -EINVAL;

	if (frmsize.pixel_format != V4L2_PIX_FMT_ET61X251 &&
	    frmsize.pixel_format != V4L2_PIX_FMT_SBGGR8)
		return -EINVAL;

	frmsize.type = V4L2_FRMSIZE_TYPE_STEPWISE;
	frmsize.stepwise.min_width = frmsize.stepwise.step_width = 16;
	frmsize.stepwise.min_height = frmsize.stepwise.step_height = 16;
	frmsize.stepwise.max_width = cam->sensor.cropcap.bounds.width;
	frmsize.stepwise.max_height = cam->sensor.cropcap.bounds.height;
	memset(&frmsize.reserved, 0, sizeof(frmsize.reserved));

	if (copy_to_user(arg, &frmsize, sizeof(frmsize)))
		return -EFAULT;

	return 0;
}


1899 1900 1901 1902 1903 1904 1905 1906
static int
et61x251_vidioc_enum_fmt(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_fmtdesc fmtd;

	if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
		return -EFAULT;

1907 1908 1909
	if (fmtd.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
	if (fmtd.index == 0) {
		strcpy(fmtd.description, "bayer rgb");
		fmtd.pixelformat = V4L2_PIX_FMT_SBGGR8;
	} else if (fmtd.index == 1) {
		strcpy(fmtd.description, "compressed");
		fmtd.pixelformat = V4L2_PIX_FMT_ET61X251;
		fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
	} else
		return -EINVAL;

	fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));

	if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_g_fmt(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_format format;
1934
	struct v4l2_pix_format* pfmt = &(cam->sensor.pix_format);
1935 1936 1937 1938 1939 1940 1941

	if (copy_from_user(&format, arg, sizeof(format)))
		return -EFAULT;

	if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

1942 1943
	pfmt->colorspace = (pfmt->pixelformat == V4L2_PIX_FMT_ET61X251) ?
			   0 : V4L2_COLORSPACE_SRGB;
1944
	pfmt->bytesperline = (pfmt->pixelformat==V4L2_PIX_FMT_ET61X251)
1945
			     ? 0 : (pfmt->width * pfmt->priv) / 8;
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
	pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
	pfmt->field = V4L2_FIELD_NONE;
	memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));

	if (copy_to_user(arg, &format, sizeof(format)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_try_s_fmt(struct et61x251_device* cam, unsigned int cmd,
1959
			  void __user * arg)
1960
{
1961
	struct et61x251_sensor* s = &cam->sensor;
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
	struct v4l2_format format;
	struct v4l2_pix_format* pix;
	struct v4l2_pix_format* pfmt = &(s->pix_format);
	struct v4l2_rect* bounds = &(s->cropcap.bounds);
	struct v4l2_rect rect;
	u8 scale;
	const enum et61x251_stream_state stream = cam->stream;
	const u32 nbuffers = cam->nbuffers;
	u32 i;
	int err = 0;

	if (copy_from_user(&format, arg, sizeof(format)))
		return -EFAULT;

	pix = &(format.fmt.pix);

	if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

	memcpy(&rect, &(s->_rect), sizeof(rect));

	{ /* calculate the actual scaling factor */
		u32 a, b;
		a = rect.width * rect.height;
		b = pix->width * pix->height;
		scale = b ? (u8)((a / b) < 4 ? 1 : 2) : 1;
	}

	rect.width = scale * pix->width;
	rect.height = scale * pix->height;

1993 1994 1995 1996
	if (rect.width < 16)
		rect.width = 16;
	if (rect.height < 16)
		rect.height = 16;
1997 1998 1999 2000 2001
	if (rect.width > bounds->left + bounds->width - rect.left)
		rect.width = bounds->left + bounds->width - rect.left;
	if (rect.height > bounds->top + bounds->height - rect.top)
		rect.height = bounds->top + bounds->height - rect.top;

2002 2003
	rect.width &= ~15L;
	rect.height &= ~15L;
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

	{ /* adjust the scaling factor */
		u32 a, b;
		a = rect.width * rect.height;
		b = pix->width * pix->height;
		scale = b ? (u8)((a / b) < 4 ? 1 : 2) : 1;
	}

	pix->width = rect.width / scale;
	pix->height = rect.height / scale;

	if (pix->pixelformat != V4L2_PIX_FMT_ET61X251 &&
	    pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
		pix->pixelformat = pfmt->pixelformat;
	pix->priv = pfmt->priv; /* bpp */
2019 2020
	pix->colorspace = (pix->pixelformat == V4L2_PIX_FMT_ET61X251) ?
			  0 : V4L2_COLORSPACE_SRGB;
2021 2022
	pix->colorspace = pfmt->colorspace;
	pix->bytesperline = (pix->pixelformat == V4L2_PIX_FMT_ET61X251)
2023
			    ? 0 : (pix->width * pix->priv) / 8;
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
	pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
	pix->field = V4L2_FIELD_NONE;

	if (cmd == VIDIOC_TRY_FMT) {
		if (copy_to_user(arg, &format, sizeof(format)))
			return -EFAULT;
		return 0;
	}

	if (cam->module_param.force_munmap)
		for (i = 0; i < cam->nbuffers; i++)
			if (cam->frame[i].vma_use_count) {
				DBG(3, "VIDIOC_S_FMT failed. "
				       "Unmap the buffers first.");
2038
				return -EBUSY;
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
			}

	if (cam->stream == STREAM_ON)
		if ((err = et61x251_stream_interrupt(cam)))
			return err;

	if (copy_to_user(arg, &format, sizeof(format))) {
		cam->stream = stream;
		return -EFAULT;
	}

	if (cam->module_param.force_munmap || cam->io == IO_READ)
		et61x251_release_buffers(cam);

	err += et61x251_set_pix_format(cam, pix);
	err += et61x251_set_crop(cam, &rect);
	if (s->set_pix_format)
		err += s->set_pix_format(cam, pix);
	if (s->set_crop)
		err += s->set_crop(cam, &rect);
	err += et61x251_set_scale(cam, scale);

	if (err) { /* atomic, no rollback in ioctl() */
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "VIDIOC_S_FMT failed because of hardware problems. To "
		       "use the camera, close and open /dev/video%d again.",
		    cam->v4ldev->minor);
		return -EIO;
	}

	memcpy(pfmt, pix, sizeof(*pix));
	memcpy(&(s->_rect), &rect, sizeof(rect));

	if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
	    nbuffers != et61x251_request_buffers(cam, nbuffers, cam->io)) {
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "VIDIOC_S_FMT failed because of not enough memory. To "
		       "use the camera, close and open /dev/video%d again.",
		    cam->v4ldev->minor);
		return -ENOMEM;
	}

	if (cam->io == IO_READ)
		et61x251_empty_framequeues(cam);
	else if (cam->module_param.force_munmap)
		et61x251_requeue_outqueue(cam);

	cam->stream = stream;

	return 0;
}


static int
et61x251_vidioc_g_jpegcomp(struct et61x251_device* cam, void __user * arg)
{
	if (copy_to_user(arg, &cam->compression,
2096
			 sizeof(cam->compression)))
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_s_jpegcomp(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_jpegcompression jc;
	const enum et61x251_stream_state stream = cam->stream;
	int err = 0;

	if (copy_from_user(&jc, arg, sizeof(jc)))
		return -EFAULT;

	if (jc.quality != 0 && jc.quality != 1)
		return -EINVAL;

	if (cam->stream == STREAM_ON)
		if ((err = et61x251_stream_interrupt(cam)))
			return err;

	err += et61x251_set_compression(cam, &jc);
	if (err) { /* atomic, no rollback in ioctl() */
		cam->state |= DEV_MISCONFIGURED;
		DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware "
		       "problems. To use the camera, close and open "
		       "/dev/video%d again.", cam->v4ldev->minor);
		return -EIO;
	}

	cam->compression.quality = jc.quality;

	cam->stream = stream;

	return 0;
}


static int
et61x251_vidioc_reqbufs(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_requestbuffers rb;
	u32 i;
	int err;

	if (copy_from_user(&rb, arg, sizeof(rb)))
		return -EFAULT;

	if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
	    rb.memory != V4L2_MEMORY_MMAP)
		return -EINVAL;

	if (cam->io == IO_READ) {
		DBG(3, "Close and open the device again to choose the mmap "
		       "I/O method");
2154
		return -EBUSY;
2155 2156 2157 2158 2159 2160
	}

	for (i = 0; i < cam->nbuffers; i++)
		if (cam->frame[i].vma_use_count) {
			DBG(3, "VIDIOC_REQBUFS failed. "
			       "Previous buffers are still mapped.");
2161
			return -EBUSY;
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
		}

	if (cam->stream == STREAM_ON)
		if ((err = et61x251_stream_interrupt(cam)))
			return err;

	et61x251_empty_framequeues(cam);

	et61x251_release_buffers(cam);
	if (rb.count)
		rb.count = et61x251_request_buffers(cam, rb.count, IO_MMAP);

	if (copy_to_user(arg, &rb, sizeof(rb))) {
		et61x251_release_buffers(cam);
		cam->io = IO_NONE;
		return -EFAULT;
	}

	cam->io = rb.count ? IO_MMAP : IO_NONE;

	return 0;
}


static int
et61x251_vidioc_querybuf(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_buffer b;

	if (copy_from_user(&b, arg, sizeof(b)))
		return -EFAULT;

	if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
	    b.index >= cam->nbuffers || cam->io != IO_MMAP)
		return -EINVAL;

	memcpy(&b, &cam->frame[b.index].buf, sizeof(b));

	if (cam->frame[b.index].vma_use_count)
		b.flags |= V4L2_BUF_FLAG_MAPPED;

	if (cam->frame[b.index].state == F_DONE)
		b.flags |= V4L2_BUF_FLAG_DONE;
	else if (cam->frame[b.index].state != F_UNUSED)
		b.flags |= V4L2_BUF_FLAG_QUEUED;

	if (copy_to_user(arg, &b, sizeof(b)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_qbuf(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_buffer b;
	unsigned long lock_flags;

	if (copy_from_user(&b, arg, sizeof(b)))
		return -EFAULT;

	if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
	    b.index >= cam->nbuffers || cam->io != IO_MMAP)
		return -EINVAL;

	if (cam->frame[b.index].state != F_UNUSED)
		return -EINVAL;

	cam->frame[b.index].state = F_QUEUED;

	spin_lock_irqsave(&cam->queue_lock, lock_flags);
	list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
	spin_unlock_irqrestore(&cam->queue_lock, lock_flags);

	PDBGG("Frame #%lu queued", (unsigned long)b.index);

	return 0;
}


static int
et61x251_vidioc_dqbuf(struct et61x251_device* cam, struct file* filp,
2245
		      void __user * arg)
2246 2247 2248 2249
{
	struct v4l2_buffer b;
	struct et61x251_frame_t *f;
	unsigned long lock_flags;
2250
	long timeout;
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262

	if (copy_from_user(&b, arg, sizeof(b)))
		return -EFAULT;

	if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io!= IO_MMAP)
		return -EINVAL;

	if (list_empty(&cam->outqueue)) {
		if (cam->stream == STREAM_OFF)
			return -EINVAL;
		if (filp->f_flags & O_NONBLOCK)
			return -EAGAIN;
2263
		timeout = wait_event_interruptible_timeout
2264 2265 2266 2267 2268 2269
			  ( cam->wait_frame,
			    (!list_empty(&cam->outqueue)) ||
			    (cam->state & DEV_DISCONNECTED) ||
			    (cam->state & DEV_MISCONFIGURED),
			    cam->module_param.frame_timeout *
			    1000 * msecs_to_jiffies(1) );
2270 2271
		if (timeout < 0)
			return timeout;
2272 2273
		if (cam->state & DEV_DISCONNECTED)
			return -ENODEV;
2274
		if (!timeout || (cam->state & DEV_MISCONFIGURED))
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
			return -EIO;
	}

	spin_lock_irqsave(&cam->queue_lock, lock_flags);
	f = list_entry(cam->outqueue.next, struct et61x251_frame_t, frame);
	list_del(cam->outqueue.next);
	spin_unlock_irqrestore(&cam->queue_lock, lock_flags);

	f->state = F_UNUSED;

	memcpy(&b, &f->buf, sizeof(b));
	if (f->vma_use_count)
		b.flags |= V4L2_BUF_FLAG_MAPPED;

	if (copy_to_user(arg, &b, sizeof(b)))
		return -EFAULT;

	PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index);

	return 0;
}


static int
et61x251_vidioc_streamon(struct et61x251_device* cam, void __user * arg)
{
	int type;

	if (copy_from_user(&type, arg, sizeof(type)))
		return -EFAULT;

	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
		return -EINVAL;

	cam->stream = STREAM_ON;

	DBG(3, "Stream on");

	return 0;
}


static int
et61x251_vidioc_streamoff(struct et61x251_device* cam, void __user * arg)
{
	int type, err;

	if (copy_from_user(&type, arg, sizeof(type)))
		return -EFAULT;

	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
		return -EINVAL;

	if (cam->stream == STREAM_ON)
		if ((err = et61x251_stream_interrupt(cam)))
			return err;

	et61x251_empty_framequeues(cam);

	DBG(3, "Stream off");

	return 0;
}


static int
et61x251_vidioc_g_parm(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_streamparm sp;

	if (copy_from_user(&sp, arg, sizeof(sp)))
		return -EFAULT;

	if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

	sp.parm.capture.extendedmode = 0;
	sp.parm.capture.readbuffers = cam->nreadbuffers;

	if (copy_to_user(arg, &sp, sizeof(sp)))
		return -EFAULT;

	return 0;
}


static int
et61x251_vidioc_s_parm(struct et61x251_device* cam, void __user * arg)
{
	struct v4l2_streamparm sp;

	if (copy_from_user(&sp, arg, sizeof(sp)))
		return -EFAULT;

	if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
		return -EINVAL;

	sp.parm.capture.extendedmode = 0;

	if (sp.parm.capture.readbuffers == 0)
		sp.parm.capture.readbuffers = cam->nreadbuffers;

	if (sp.parm.capture.readbuffers > ET61X251_MAX_FRAMES)
		sp.parm.capture.readbuffers = ET61X251_MAX_FRAMES;

	if (copy_to_user(arg, &sp, sizeof(sp)))
		return -EFAULT;

	cam->nreadbuffers = sp.parm.capture.readbuffers;

	return 0;
}


static int et61x251_ioctl_v4l2(struct inode* inode, struct file* filp,
2390
			       unsigned int cmd, void __user * arg)
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
{
	struct et61x251_device* cam = video_get_drvdata(video_devdata(filp));

	switch (cmd) {

	case VIDIOC_QUERYCAP:
		return et61x251_vidioc_querycap(cam, arg);

	case VIDIOC_ENUMINPUT:
		return et61x251_vidioc_enuminput(cam, arg);

	case VIDIOC_G_INPUT:
2403 2404
		return et61x251_vidioc_g_input(cam, arg);

2405
	case VIDIOC_S_INPUT:
2406
		return et61x251_vidioc_s_input(cam, arg);
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435

	case VIDIOC_QUERYCTRL:
		return et61x251_vidioc_query_ctrl(cam, arg);

	case VIDIOC_G_CTRL:
		return et61x251_vidioc_g_ctrl(cam, arg);

	case VIDIOC_S_CTRL:
		return et61x251_vidioc_s_ctrl(cam, arg);

	case VIDIOC_CROPCAP:
		return et61x251_vidioc_cropcap(cam, arg);

	case VIDIOC_G_CROP:
		return et61x251_vidioc_g_crop(cam, arg);

	case VIDIOC_S_CROP:
		return et61x251_vidioc_s_crop(cam, arg);

	case VIDIOC_ENUM_FMT:
		return et61x251_vidioc_enum_fmt(cam, arg);

	case VIDIOC_G_FMT:
		return et61x251_vidioc_g_fmt(cam, arg);

	case VIDIOC_TRY_FMT:
	case VIDIOC_S_FMT:
		return et61x251_vidioc_try_s_fmt(cam, cmd, arg);

2436 2437 2438
	case VIDIOC_ENUM_FRAMESIZES:
		return et61x251_vidioc_enum_framesizes(cam, arg);

2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
	case VIDIOC_G_JPEGCOMP:
		return et61x251_vidioc_g_jpegcomp(cam, arg);

	case VIDIOC_S_JPEGCOMP:
		return et61x251_vidioc_s_jpegcomp(cam, arg);

	case VIDIOC_REQBUFS:
		return et61x251_vidioc_reqbufs(cam, arg);

	case VIDIOC_QUERYBUF:
		return et61x251_vidioc_querybuf(cam, arg);

	case VIDIOC_QBUF:
		return et61x251_vidioc_qbuf(cam, arg);

	case VIDIOC_DQBUF:
		return et61x251_vidioc_dqbuf(cam, filp, arg);

	case VIDIOC_STREAMON:
		return et61x251_vidioc_streamon(cam, arg);

	case VIDIOC_STREAMOFF:
		return et61x251_vidioc_streamoff(cam, arg);

	case VIDIOC_G_PARM:
		return et61x251_vidioc_g_parm(cam, arg);

	case VIDIOC_S_PARM:
		return et61x251_vidioc_s_parm(cam, arg);

	case VIDIOC_G_STD:
	case VIDIOC_S_STD:
	case VIDIOC_QUERYSTD:
	case VIDIOC_ENUMSTD:
	case VIDIOC_QUERYMENU:
2474
	case VIDIOC_ENUM_FRAMEINTERVALS:
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
		return -EINVAL;

	default:
		return -EINVAL;

	}
}


static int et61x251_ioctl(struct inode* inode, struct file* filp,
2485
			 unsigned int cmd, unsigned long arg)
2486 2487 2488 2489
{
	struct et61x251_device* cam = video_get_drvdata(video_devdata(filp));
	int err = 0;

2490
	if (mutex_lock_interruptible(&cam->fileop_mutex))
2491 2492 2493 2494
		return -ERESTARTSYS;

	if (cam->state & DEV_DISCONNECTED) {
		DBG(1, "Device not present");
2495
		mutex_unlock(&cam->fileop_mutex);
2496 2497 2498 2499 2500 2501
		return -ENODEV;
	}

	if (cam->state & DEV_MISCONFIGURED) {
		DBG(1, "The camera is misconfigured. Close and open it "
		       "again.");
2502
		mutex_unlock(&cam->fileop_mutex);
2503 2504 2505 2506 2507 2508 2509
		return -EIO;
	}

	V4LDBG(3, "et61x251", cmd);

	err = et61x251_ioctl_v4l2(inode, filp, cmd, (void __user *)arg);

2510
	mutex_unlock(&cam->fileop_mutex);
2511 2512 2513 2514 2515

	return err;
}


2516
static const struct file_operations et61x251_fops = {
2517 2518 2519 2520
	.owner = THIS_MODULE,
	.open =    et61x251_open,
	.release = et61x251_release,
	.ioctl =   et61x251_ioctl,
2521
	.compat_ioctl = v4l_compat_ioctl32,
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
	.read =    et61x251_read,
	.poll =    et61x251_poll,
	.mmap =    et61x251_mmap,
	.llseek =  no_llseek,
};

/*****************************************************************************/

/* It exists a single interface only. We do not need to validate anything. */
static int
et61x251_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct et61x251_device* cam;
	static unsigned int dev_nr = 0;
	unsigned int i;
	int err = 0;

	if (!(cam = kzalloc(sizeof(struct et61x251_device), GFP_KERNEL)))
		return -ENOMEM;

	cam->usbdev = udev;

	if (!(cam->control_buffer = kzalloc(8, GFP_KERNEL))) {
		DBG(1, "kmalloc() failed");
		err = -ENOMEM;
		goto fail;
	}

	if (!(cam->v4ldev = video_device_alloc())) {
		DBG(1, "video_device_alloc() failed");
		err = -ENOMEM;
		goto fail;
	}

	DBG(2, "ET61X[12]51 PC Camera Controller detected "
2558
	       "(vid/pid 0x%04X:0x%04X)",id->idVendor, id->idProduct);
2559 2560 2561 2562 2563 2564 2565

	for  (i = 0; et61x251_sensor_table[i]; i++) {
		err = et61x251_sensor_table[i](cam);
		if (!err)
			break;
	}

2566 2567
	if (!err)
		DBG(2, "%s image sensor detected", cam->sensor.name);
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
	else {
		DBG(1, "No supported image sensor detected");
		err = -ENODEV;
		goto fail;
	}

	if (et61x251_init(cam)) {
		DBG(1, "Initialization failed. I will retry on open().");
		cam->state |= DEV_MISCONFIGURED;
	}

	strcpy(cam->v4ldev->name, "ET61X[12]51 PC Camera");
	cam->v4ldev->owner = THIS_MODULE;
	cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
	cam->v4ldev->hardware = 0;
	cam->v4ldev->fops = &et61x251_fops;
	cam->v4ldev->minor = video_nr[dev_nr];
	cam->v4ldev->release = video_device_release;
	video_set_drvdata(cam->v4ldev, cam);

2588
	init_completion(&cam->probe);
2589 2590

	err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
2591
				    video_nr[dev_nr]);
2592 2593 2594 2595 2596 2597
	if (err) {
		DBG(1, "V4L2 device registration failed");
		if (err == -ENFILE && video_nr[dev_nr] == -1)
			DBG(1, "Free /dev/videoX node not found");
		video_nr[dev_nr] = -1;
		dev_nr = (dev_nr < ET61X251_MAX_DEVICES-1) ? dev_nr+1 : 0;
2598
		complete_all(&cam->probe);
2599 2600 2601 2602 2603 2604
		goto fail;
	}

	DBG(2, "V4L2 device registered as /dev/video%d", cam->v4ldev->minor);

	cam->module_param.force_munmap = force_munmap[dev_nr];
2605
	cam->module_param.frame_timeout = frame_timeout[dev_nr];
2606 2607 2608 2609

	dev_nr = (dev_nr < ET61X251_MAX_DEVICES-1) ? dev_nr+1 : 0;

#ifdef CONFIG_VIDEO_ADV_DEBUG
2610
	err = et61x251_create_sysfs(cam);
2611 2612 2613 2614 2615 2616 2617 2618
	if (!err)
		DBG(2, "Optional device control through 'sysfs' "
		       "interface ready");
	else
		DBG(2, "Failed to create 'sysfs' interface for optional "
		       "device controlling. Error #%d", err);
#else
	DBG(2, "Optional device control through 'sysfs' interface disabled");
2619 2620
	DBG(3, "Compile the kernel with the 'CONFIG_VIDEO_ADV_DEBUG' "
	       "configuration option to enable it.");
2621 2622 2623
#endif

	usb_set_intfdata(intf, cam);
2624 2625
	kref_init(&cam->kref);
	usb_get_dev(cam->usbdev);
2626

2627
	complete_all(&cam->probe);
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643

	return 0;

fail:
	if (cam) {
		kfree(cam->control_buffer);
		if (cam->v4ldev)
			video_device_release(cam->v4ldev);
		kfree(cam);
	}
	return err;
}


static void et61x251_usb_disconnect(struct usb_interface* intf)
{
2644
	struct et61x251_device* cam;
2645

2646
	down_write(&et61x251_dev_lock);
2647

2648
	cam = usb_get_intfdata(intf);
2649 2650 2651 2652 2653

	DBG(2, "Disconnecting %s...", cam->v4ldev->name);

	if (cam->users) {
		DBG(2, "Device /dev/video%d is open! Deregistration and "
2654
		       "memory deallocation are deferred.",
2655 2656 2657 2658 2659
		    cam->v4ldev->minor);
		cam->state |= DEV_MISCONFIGURED;
		et61x251_stop_transfer(cam);
		cam->state |= DEV_DISCONNECTED;
		wake_up_interruptible(&cam->wait_frame);
2660
		wake_up(&cam->wait_stream);
2661
	} else
2662 2663
		cam->state |= DEV_DISCONNECTED;

2664
	wake_up_interruptible_all(&cam->wait_open);
2665

2666
	kref_put(&cam->kref, et61x251_release_resources);
2667

2668
	up_write(&et61x251_dev_lock);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
}


static struct usb_driver et61x251_usb_driver = {
	.name =       "et61x251",
	.id_table =   et61x251_id_table,
	.probe =      et61x251_usb_probe,
	.disconnect = et61x251_usb_disconnect,
};

/*****************************************************************************/

static int __init et61x251_module_init(void)
{
	int err = 0;

	KDBG(2, ET61X251_MODULE_NAME " v" ET61X251_MODULE_VERSION);
	KDBG(3, ET61X251_MODULE_AUTHOR);

	if ((err = usb_register(&et61x251_usb_driver)))
		KDBG(1, "usb_register() failed");

	return err;
}


static void __exit et61x251_module_exit(void)
{
	usb_deregister(&et61x251_usb_driver);
}


module_init(et61x251_module_init);
module_exit(et61x251_module_exit);