1/* Video-to-USB Bridge Driver for OmniVision OV511/OV511+/OV518/OV518+/OV519
2 *
3 * Copyright (c) 1999-2003 Mark W. McClelland
4 * Support for OV519, OV8610 Copyright (c) 2003 Joerg Heckenbach
5 *
6 * Original decompression code Copyright 1998-2000 OmniVision Technologies
7 * Many improvements by Bret Wallach <bwallac1@san.rr.com>
8 * Color fixes by by Orion Sky Lawlor <olawlor@acm.org> (2/26/2000)
9 * Snapshot code by Kevin Moore
10 * OV7620 fixes by Charl P. Botha <cpbotha@ieee.org>
11 * Changes by Claudio Matsuoka <claudio@conectiva.com>
12 * Original SAA7111A code by Dave Perks <dperks@ibm.net>
13 * URB error messages from pwc driver by Nemosoft
14 * generic_ioctl() code from videodev.c by Gerd Knorr and Alan Cox
15 * Memory management (rvmalloc) code from bttv driver, by Gerd Knorr and others
16 * OV7x3x/7x4x detection by Franz Reinhardt
17 * 2004/01/25: Added OV7640 and EyeToy support (Mark McClelland)
18 *
19 * Based on the Linux CPiA driver written by Peter Pregler,
20 * Scott J. Bertin and Johannes Erdfelt.
21 *
22 * Please see the file: doc/ov51x.txt
23 * and the website at:  http://alpha.dyndns.org/ov511
24 * for more info.
25 * For Questions on OV519 or OV8610 please contact <joerg@heckenbach-aw.de>
26 *
27 * This program is free software; you can redistribute it and/or modify it
28 * under the terms of the GNU General Public License as published by the
29 * Free Software Foundation; either version 2 of the License, or (at your
30 * option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful, but
33 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
34 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
35 * for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program; if not, write to the Free Software Foundation,
39 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
40 */
41
42#include <linux/config.h>
43
44#if defined(OUTSIDE_KERNEL)
45	#if defined(CONFIG_MODVERSIONS) && !defined(MODVERSIONS)
46		#define MODVERSIONS
47	#endif
48
49	#include <linux/version.h>
50
51	#ifdef MODVERSIONS
52		#include <linux/modversions.h>
53	#endif
54#else
55	#include <linux/version.h>
56#endif
57
58#include <linux/module.h>
59#include <linux/init.h>
60#include <linux/fs.h>
61#include <linux/vmalloc.h>
62#include <linux/slab.h>
63#include <linux/proc_fs.h>
64#include <linux/ctype.h>
65#include <linux/pagemap.h>
66#include <asm/io.h>
67#include <asm/semaphore.h>
68#include <asm/processor.h>
69#include <linux/wrapper.h>
70
71/* 2.4.18+/2.5.5+ forward-compatibility; for page_address() */
72#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 18)
73	#include <linux/mm.h>
74#endif
75
76#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 0)
77	#if defined (__i386__)
78		#include <asm/cpufeature.h>
79	#endif
80#endif
81
82/* 2.2.x compatibility */
83#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 3, 0)
84	#ifdef CONFIG_KMOD
85		#include <linux/kmod.h>
86	#endif
87
88	/* For rvmalloc() and friends */
89	#define virt_to_page(va) MAP_NR(va)
90#endif
91
92/************** Special compatibility options **************/
93
94/* A new implementation of the V4L 1 API exists that gives drivers direct
95 * access to file_operations. The old API is compatible with all 2.2 and 2.4
96 * kernels, and all 2.5 kernels through 2.5.5 (at least).
97 *
98 * Remove this #define to enable the new API
99 *
100 * Note: This has nothing to do with the V4L 2 API.
101 */
102#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 19)
103	#define OV511_OLD_V4L
104#endif
105
106/* Conversion between standard V4L formats should only be done by apps. This
107 * #define performs conversion in this driver, to maintain backward
108 * compatibility with apps that can't convert YUV420 to their native format
109 *
110 * This should remain defined for 2.2 and 2.4 kernels. It should be removed
111 * for 2.5 kernels, including the code that it enables.
112 */
113#define OV511_ALLOW_CONVERSION
114
115/***********************************************************/
116
117#include "ov51x.h"
118
119/*
120 * Version Information
121 */
122#define DRIVER_VERSION "v1.65-1.10-mark"
123#define EMAIL "mark@alpha.dyndns.org, joerg@heckenbach-aw.de"
124#define DRIVER_AUTHOR "Mark McClelland <mark@alpha.dyndns.org> & Bret Wallach \
125	& Orion Sky Lawlor <olawlor@acm.org> & Kevin Moore & Charl P. Botha \
126	<cpbotha@ieee.org> & Claudio Matsuoka <claudio@conectiva.com> &\
127	Joerg Heckenbach <joerg@heckenbach-aw.de>"
128#define DRIVER_DESC "ov51x USB Camera Driver"
129
130#define OV511_I2C_RETRIES 6
131#define ENABLE_Y_QUANTABLE 1
132#define ENABLE_UV_QUANTABLE 1
133
134#define OV511_MAX_UNIT_VIDEO 16
135
136#ifdef OV511_ALLOW_CONVERSION
137	/* Pixel count * 3 bytes for RGB */
138	#define MAX_FRAME_SIZE(w, h) ((w) * (h) * 3)
139#else
140	/* Pixel count * bytes per YUV420 pixel (1.5) */
141	#define MAX_FRAME_SIZE(w, h) ((w) * (h) * 3 / 2)
142#endif
143
144#define MAX_DATA_SIZE(w, h) (MAX_FRAME_SIZE(w, h) + sizeof(struct timeval))
145
146/* Max size * bytes per YUV420 pixel (1.5) + one extra isoc frame for safety */
147#define MAX_RAW_DATA_SIZE(w, h) ((w) * (h) * 3 / 2 + 1024)
148
149#define FATAL_ERROR(rc) ((rc) < 0 && (rc) != -EPERM)
150
151/**********************************************************************
152 * Module Parameters
153 * (See ov51x.txt for detailed descriptions of these)
154 **********************************************************************/
155
156/* These variables (and all static globals) default to zero */
157static int autobright		= 1;
158static int autogain		= 1;
159static int autoexp		= 1;
160static int debug;
161static int snapshot;
162#ifdef OV511_ALLOW_CONVERSION
163	static int fix_rgb_offset;
164	static int force_rgb;
165#endif
166static int cams			= 1;
167static int compress;
168static int testpat;
169static int dumppix;
170static int led 			= 1;
171static int led2			= 0;
172static int dump_bridge;
173static int dump_sensor;
174static int printph;
175static int phy			= 0x1f;
176static int phuv			= 0x05;
177static int pvy			= 0x06;
178static int pvuv			= 0x06;
179static int qhy			= 0x14;
180static int qhuv			= 0x03;
181static int qvy			= 0x04;
182static int qvuv			= 0x04;
183static int lightfreq;
184static int bandingfilter;
185static int clockdiv		= -1;
186static int packetsize	= -1;
187static int framedrop	= -1;
188static int framerate	= -1;
189static int jpeginfo		=  1;
190static int fastset;
191static int force_palette;
192static int backlight;
193static int unit_video[OV511_MAX_UNIT_VIDEO];
194static int remove_zeros;
195static int mirror;
196static int ov518_color = 1;
197
198MODULE_PARM(autobright, "i");
199MODULE_PARM_DESC(autobright, "Sensor automatically changes brightness");
200MODULE_PARM(autogain, "i");
201MODULE_PARM_DESC(autogain, "Sensor automatically changes gain");
202MODULE_PARM(autoexp, "i");
203MODULE_PARM_DESC(autoexp, "Sensor automatically changes exposure");
204MODULE_PARM(debug, "i");
205MODULE_PARM_DESC(debug,
206  "Debug level: 0=none, 1=inits, 2=warning, 3=config, 4=functions, 5=max");
207MODULE_PARM(snapshot, "i");
208MODULE_PARM_DESC(snapshot, "Enable snapshot mode");
209
210#ifdef OV511_ALLOW_CONVERSION
211	MODULE_PARM(fix_rgb_offset, "i");
212	MODULE_PARM_DESC(fix_rgb_offset,
213	  "Fix vertical misalignment of red and blue at 640x480");
214	MODULE_PARM(force_rgb, "i");
215	MODULE_PARM_DESC(force_rgb, "Read RGB instead of BGR");
216#endif
217
218MODULE_PARM(cams, "i");
219MODULE_PARM_DESC(cams, "Number of simultaneous cameras");
220MODULE_PARM(compress, "i");
221MODULE_PARM_DESC(compress, "Turn on compression");
222MODULE_PARM(testpat, "i");
223MODULE_PARM_DESC(testpat,
224  "Replace image with vertical bar testpattern (only partially working)");
225MODULE_PARM(dumppix, "i");
226MODULE_PARM_DESC(dumppix, "Dump raw pixel data");
227MODULE_PARM(led, "i");
228MODULE_PARM_DESC(led,
229  "LED policy (OV511+ or later). 0=off, 1=on (default), 2=auto (on when open)");
230MODULE_PARM(led2, "i");
231MODULE_PARM_DESC(led2,
232  "LED 2 policy (EyeToy only). 0=off, 1=on (default), 2=auto (on when open)");
233MODULE_PARM(dump_bridge, "i");
234MODULE_PARM_DESC(dump_bridge, "Dump the bridge registers");
235MODULE_PARM(dump_sensor, "i");
236MODULE_PARM_DESC(dump_sensor, "Dump the sensor registers");
237MODULE_PARM(printph, "i");
238MODULE_PARM_DESC(printph, "Print frame start/end headers");
239MODULE_PARM(phy, "i");
240MODULE_PARM_DESC(phy, "Prediction range (horiz. Y)");
241MODULE_PARM(phuv, "i");
242MODULE_PARM_DESC(phuv, "Prediction range (horiz. UV)");
243MODULE_PARM(pvy, "i");
244MODULE_PARM_DESC(pvy, "Prediction range (vert. Y)");
245MODULE_PARM(pvuv, "i");
246MODULE_PARM_DESC(pvuv, "Prediction range (vert. UV)");
247MODULE_PARM(qhy, "i");
248MODULE_PARM_DESC(qhy, "Quantization threshold (horiz. Y)");
249MODULE_PARM(qhuv, "i");
250MODULE_PARM_DESC(qhuv, "Quantization threshold (horiz. UV)");
251MODULE_PARM(qvy, "i");
252MODULE_PARM_DESC(qvy, "Quantization threshold (vert. Y)");
253MODULE_PARM(qvuv, "i");
254MODULE_PARM_DESC(qvuv, "Quantization threshold (vert. UV)");
255MODULE_PARM(lightfreq, "i");
256MODULE_PARM_DESC(lightfreq,
257  "Light frequency. Set to 50 or 60 Hz, or zero for default settings");
258MODULE_PARM(bandingfilter, "i");
259MODULE_PARM_DESC(bandingfilter,
260  "Enable banding filter (to reduce effects of fluorescent lighting)");
261MODULE_PARM(clockdiv, "i");
262MODULE_PARM_DESC(clockdiv, "Force pixel clock divisor to a specific value");
263MODULE_PARM(packetsize, "i");
264MODULE_PARM_DESC(packetsize, "Force a specific isoc packet size");
265MODULE_PARM(framedrop, "i");
266MODULE_PARM_DESC(framedrop, "Force a specific frame drop register setting");
267MODULE_PARM(fastset, "i");
268MODULE_PARM_DESC(fastset, "Allows picture settings to take effect immediately");
269MODULE_PARM(force_palette, "i");
270MODULE_PARM_DESC(force_palette, "Force the palette to a specific value");
271MODULE_PARM(backlight, "i");
272MODULE_PARM_DESC(backlight, "For objects that are lit from behind");
273MODULE_PARM(unit_video, "1-" __MODULE_STRING(OV511_MAX_UNIT_VIDEO) "i");
274MODULE_PARM_DESC(unit_video,
275  "Force use of specific minor number(s). 0 is not allowed.");
276MODULE_PARM(remove_zeros, "i");
277MODULE_PARM_DESC(remove_zeros,
278  "Remove zero-padding from uncompressed incoming data");
279MODULE_PARM(mirror, "i");
280MODULE_PARM_DESC(mirror, "Reverse image horizontally");
281MODULE_PARM(ov518_color, "i");
282MODULE_PARM_DESC(ov518_color, "Enable OV518 color (experimental)");
283MODULE_PARM(framerate, "i");
284MODULE_PARM_DESC(framerate, "Force a specific framerate for OV519 (values: 5,10,15)");
285MODULE_PARM(jpeginfo, "i");
286MODULE_PARM_DESC(jpeginfo, "Force information on JPEG size in first two bytes of frame buffer for OV519");
287
288MODULE_AUTHOR(DRIVER_AUTHOR);
289MODULE_DESCRIPTION(DRIVER_DESC);
290#if defined(MODULE_LICENSE)	/* Introduced in ~2.4.10 */
291MODULE_LICENSE("GPL");
292#endif
293
294/**********************************************************************
295 * Miscellaneous Globals
296 **********************************************************************/
297
298/* 2.2.x compatibility */
299#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 3, 0)
300static char kernel_version[] = UTS_RELEASE;
301#endif
302
303static struct usb_driver ov511_driver;
304
305static struct ov51x_decomp_ops *ov511_decomp_ops;
306static struct ov51x_decomp_ops *ov511_mmx_decomp_ops;
307static struct ov51x_decomp_ops *ov518_decomp_ops;
308static struct ov51x_decomp_ops *ov518_mmx_decomp_ops;
309
310/* Number of times to retry a failed I2C transaction. Increase this if you
311 * are getting "Failed to read sensor ID..." */
312static int i2c_detect_tries = 10;
313
314/* MMX support is present in kernel and CPU. Checked upon decomp module load. */
315#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 0)
316	#if defined(__i386__) || defined(__x86_64__)
317	#define ov51x_mmx_available (cpu_has_mmx)
318	#else
319	#define ov51x_mmx_available (0)
320	#endif
321#else
322	static int ov51x_mmx_available;
323#endif
324
325#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 0)
326static struct usb_device_id device_table [] = {
327	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV511) },
328	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV511PLUS) },
329	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV518) },
330	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV518PLUS) },
331	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV519) },
332	{ USB_DEVICE(VEND_OMNIVISION, PROD_OV519A) },
333	{ USB_DEVICE(VEND_SONY, PROD_EYETOY) },
334	{ USB_DEVICE(VEND_MATTEL, PROD_ME2CAM) },
335	{ }  /* Terminating entry */
336};
337
338MODULE_DEVICE_TABLE (usb, device_table);
339#endif
340
341static unsigned char yQuanTable511[] = OV511_YQUANTABLE;
342static unsigned char uvQuanTable511[] = OV511_UVQUANTABLE;
343static unsigned char yQuanTable518[] = OV518_YQUANTABLE;
344static unsigned char uvQuanTable518[] = OV518_UVQUANTABLE;
345
346/**********************************************************************
347 * Symbolic Names
348 **********************************************************************/
349
350/* Known OV511-based cameras */
351static struct symbolic_list camlist[] = {
352	{   0, "Generic Camera (no ID)" },
353	{   1, "Mustek WCam 3X" },
354	{   3, "D-Link DSB-C300" },
355	{   4, "Generic OV511/OV7610" },
356	{   5, "Puretek PT-6007" },
357	{   6, "Lifeview USB Life TV (NTSC)" },
358	{  21, "Creative Labs WebCam 3" },
359	{  22, "Lifeview USB Life TV (PAL D/K+B/G)" },
360	{  36, "Koala-Cam" },
361	{  38, "Lifeview USB Life TV (PAL)" },
362	{  41, "Samsung Anycam MPC-M10" },
363	{  43, "Mtekvision Zeca MV402" },
364	{  46, "Suma eON" },
365	{  70, "Lifeview USB Life TV (PAL/SECAM)" },
366	{ 100, "Lifeview RoboCam" },
367	{ 102, "AverMedia InterCam Elite" },
368	{ 112, "MediaForte MV300" },	/* or OV7110 evaluation kit */
369	{ 134, "Ezonics EZCam II" },
370	{ 192, "Webeye 2000B" },
371	{ 253, "Alpha Vision Tech. AlphaCam SE" },
372	{  -1, NULL }
373};
374
375/* Video4Linux1 Palettes */
376static struct symbolic_list v4l1_plist[] = {
377	{ VIDEO_PALETTE_GREY,	"GREY" },
378	{ VIDEO_PALETTE_HI240,	"HI240" },
379	{ VIDEO_PALETTE_RGB565,	"RGB565" },
380	{ VIDEO_PALETTE_RGB24,	"RGB24" },
381	{ VIDEO_PALETTE_RGB32,	"RGB32" },
382	{ VIDEO_PALETTE_RGB555,	"RGB555" },
383	{ VIDEO_PALETTE_YUV422,	"YUV422" },
384	{ VIDEO_PALETTE_YUYV,	"YUYV" },
385	{ VIDEO_PALETTE_UYVY,	"UYVY" },
386	{ VIDEO_PALETTE_YUV420,	"YUV420" },
387	{ VIDEO_PALETTE_YUV411,	"YUV411" },
388	{ VIDEO_PALETTE_RAW,	"RAW" },
389	{ VIDEO_PALETTE_YUV422P,"YUV422P" },
390	{ VIDEO_PALETTE_YUV411P,"YUV411P" },
391	{ VIDEO_PALETTE_YUV420P,"YUV420P" },
392	{ VIDEO_PALETTE_YUV410P,"YUV410P" },
393	{ -1, NULL }
394};
395
396static struct symbolic_list brglist[] = {
397	{ BRG_OV511,		"OV511" },
398	{ BRG_OV511PLUS,	"OV511+" },
399	{ BRG_OV518,		"OV518" },
400	{ BRG_OV518PLUS,	"OV518+" },
401	{ BRG_OV519,		"OV519" },
402	{ -1, NULL }
403};
404
405#if defined(CONFIG_VIDEO_PROC_FS)
406static struct symbolic_list senlist[] = {
407	{ SEN_OV76BE,	"OV76BE" },
408	{ SEN_OV7610,	"OV7610" },
409	{ SEN_OV7620,	"OV7620" },
410	{ SEN_OV7620AE,	"OV7620AE" },
411	{ SEN_OV7630,	"OV7630" },
412	{ SEN_OV7640,	"OV7640" },
413	{ SEN_OV6620,	"OV6620" },
414	{ SEN_OV6630,	"OV6630" },
415	{ SEN_OV6630AE,	"OV6630AE" },
416	{ SEN_OV6630AF,	"OV6630AF" },
417	{ SEN_OV8600,	"OV8600" },
418	{ SEN_OV8610,	"OV8610" },
419	{ SEN_KS0127,	"KS0127" },
420	{ SEN_KS0127B,	"KS0127B" },
421	{ SEN_SAA7111A,	"SAA7111A" },
422	{ -1, NULL }
423};
424#endif
425
426/* URB error codes: */
427static struct symbolic_list urb_errlist[] = {
428	{ -ENOSR,		"Buffer error (overrun)" },
429	{ -EPIPE,		"Stalled (device not responding)" },
430	{ -EOVERFLOW,	"Babble (bad cable?)" },
431	{ -EPROTO,		"Bit-stuff error (bad cable?)" },
432	{ -EILSEQ,		"CRC/Timeout" },
433	{ -ETIMEDOUT,	"NAK (device does not respond)" },
434	{ -1, NULL }
435};
436
437/**********************************************************************
438 * Memory management
439 **********************************************************************/
440
441#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 4, 18)
442
443/* Here we want the physical address of the memory.
444 * This is used when initializing the contents of the area.
445 */
446static inline unsigned long
447kvirt_to_pa(unsigned long adr)
448{
449	unsigned long kva, ret;
450
451	kva = (unsigned long) page_address(vmalloc_to_page((void *)adr));
452	kva |= adr & (PAGE_SIZE-1); /* restore the offset */
453	ret = __pa(kva);
454	return ret;
455}
456
457static void *
458rvmalloc(unsigned long size)
459{
460	void *mem;
461	unsigned long adr;
462
463	size = PAGE_ALIGN(size);
464	mem = vmalloc_32(size);
465	if (!mem)
466		return NULL;
467
468	memset(mem, 0, size); /* Clear the ram out, no junk to the user */
469	adr = (unsigned long) mem;
470	while (size > 0) {
471		mem_map_reserve(vmalloc_to_page((void *)adr));
472		adr += PAGE_SIZE;
473		size -= PAGE_SIZE;
474	}
475
476	return mem;
477}
478
479static void
480rvfree(void *mem, unsigned long size)
481{
482	unsigned long adr;
483
484	if (!mem)
485		return;
486
487	adr = (unsigned long) mem;
488	while ((long) size > 0) {
489		mem_map_unreserve(vmalloc_to_page((void *)adr));
490		adr += PAGE_SIZE;
491		size -= PAGE_SIZE;
492	}
493	vfree(mem);
494}
495
496#else	/* if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 4, 18) */
497
498/* Given PGD from the address space's page table, return the kernel
499 * virtual mapping of the physical memory mapped at ADR.
500 */
501static inline unsigned long
502uvirt_to_kva(pgd_t *pgd, unsigned long adr)
503{
504	unsigned long ret = 0UL;
505	pmd_t *pmd;
506	pte_t *ptep, pte;
507
508	if (!pgd_none(*pgd)) {
509		pmd = pmd_offset(pgd, adr);
510		if (!pmd_none(*pmd)) {
511			ptep = pte_offset(pmd, adr);
512			pte = *ptep;
513			if (pte_present(pte)) {
514				ret = (unsigned long)
515				      page_address(pte_page(pte));
516				ret |= (adr & (PAGE_SIZE - 1));
517			}
518		}
519	}
520
521	return ret;
522}
523
524/* Here we want the physical address of the memory.
525 * This is used when initializing the contents of the
526 * area and marking the pages as reserved.
527 */
528static inline unsigned long
529kvirt_to_pa(unsigned long adr)
530{
531	unsigned long va, kva, ret;
532
533	va = VMALLOC_VMADDR(adr);
534	kva = uvirt_to_kva(pgd_offset_k(va), va);
535	ret = __pa(kva);
536	return ret;
537}
538
539/* Allocate logically contiguous mmap-compatible reserved pages */
540static void *
541rvmalloc(unsigned long size)
542{
543	void *mem;
544	unsigned long adr, page;
545
546	/* Round it off to PAGE_SIZE */
547	size += (PAGE_SIZE - 1);
548	size &= ~(PAGE_SIZE - 1);
549
550	mem = vmalloc_32(size);
551	if (!mem)
552		return NULL;
553
554	memset(mem, 0, size); /* Clear the ram out, no junk to the user */
555	adr = (unsigned long) mem;
556	while (size > 0) {
557		page = kvirt_to_pa(adr);
558		mem_map_reserve(virt_to_page(__va(page)));
559		adr += PAGE_SIZE;
560		if (size > PAGE_SIZE)
561			size -= PAGE_SIZE;
562		else
563			size = 0;
564	}
565
566	return mem;
567}
568
569static void
570rvfree(void *mem, unsigned long size)
571{
572	unsigned long adr, page;
573
574	if (!mem)
575		return;
576
577	size += (PAGE_SIZE - 1);
578	size &= ~(PAGE_SIZE - 1);
579
580	adr=(unsigned long) mem;
581	while (size > 0) {
582		page = kvirt_to_pa(adr);
583		mem_map_unreserve(virt_to_page(__va(page)));
584		adr += PAGE_SIZE;
585		if (size > PAGE_SIZE)
586			size -= PAGE_SIZE;
587		else
588			size = 0;
589	}
590	vfree(mem);
591}
592
593#endif	/* LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 5) */
594
595/**********************************************************************
596 * /proc interface
597 * Based on the CPiA driver version 0.7.4 -claudio
598 **********************************************************************/
599
600#if defined(CONFIG_VIDEO_PROC_FS)
601
602static struct proc_dir_entry *ov511_proc_entry = NULL;
603extern struct proc_dir_entry *video_proc_entry;
604
605/* Prototypes */
606static void ov51x_clear_snapshot(struct usb_ov511 *);
607static int sensor_get_picture(struct usb_ov511 *, struct video_picture *);
608static int sensor_get_exposure(struct usb_ov511 *, unsigned char *);
609static int ov51x_check_snapshot(struct usb_ov511 *);
610static int ov51x_control_ioctl(struct inode *, struct file *, unsigned int,
611			       unsigned long);
612
613static struct file_operations ov511_control_fops = {
614	.ioctl =	ov51x_control_ioctl,
615};
616
617#define YES_NO(x) ((x) ? "yes" : "no")
618
619/* /proc/video/ov511/<minor#>/info */
620static int
621ov511_read_proc_info(char *page, char **start, off_t off, int count, int *eof,
622		     void *data)
623{
624	char *out = page;
625	int i, len;
626	struct usb_ov511 *ov = data;
627	struct video_picture p;
628	unsigned char exp;
629
630	if (!ov || !ov->dev)
631		return -ENODEV;
632
633	sensor_get_picture(ov, &p);
634	sensor_get_exposure(ov, &exp);
635
636	/* IMPORTANT: This output MUST be kept under PAGE_SIZE
637	 *            or we need to get more sophisticated. */
638
639	out += sprintf(out, "driver_version  : %s\n", DRIVER_VERSION);
640	out += sprintf(out, "custom_id       : %d\n", ov->customid);
641	out += sprintf(out, "model           : %s\n", ov->desc);
642	out += sprintf(out, "streaming       : %s\n", YES_NO(ov->streaming));
643	out += sprintf(out, "grabbing        : %s\n", YES_NO(ov->grabbing));
644	out += sprintf(out, "can_decompress  : %s\n", YES_NO(ov->decomp_ops));
645	out += sprintf(out, "compress        : %s\n", YES_NO(ov->compress));
646	out += sprintf(out, "subcapture      : %s\n", YES_NO(ov->sub_flag));
647	out += sprintf(out, "sub_size        : %d %d %d %d\n",
648		       ov->subx, ov->suby, ov->subw, ov->subh);
649#ifdef OV511_ALLOW_CONVERSION
650	out += sprintf(out, "data_format     : %s\n",
651		       force_rgb ? "RGB" : "BGR");
652#endif
653	out += sprintf(out, "brightness      : %d\n", p.brightness >> 8);
654	out += sprintf(out, "colour          : %d\n", p.colour >> 8);
655	out += sprintf(out, "contrast        : %d\n", p.contrast >> 8);
656	out += sprintf(out, "hue             : %d\n", p.hue >> 8);
657	out += sprintf(out, "exposure        : %d\n", exp);
658	out += sprintf(out, "num_frames      : %d\n", OV511_NUMFRAMES);
659	for (i = 0; i < OV511_NUMFRAMES; i++) {
660		out += sprintf(out, "frame           : %d\n", i);
661		out += sprintf(out, "  depth         : %d\n",
662			       ov->frame[i].depth);
663		out += sprintf(out, "  size          : %d %d\n",
664			       ov->frame[i].width, ov->frame[i].height);
665		out += sprintf(out, "  format        : %s\n",
666			       symbolic(v4l1_plist, ov->frame[i].format));
667		out += sprintf(out, "  data_buffer   : 0x%p\n",
668			       ov->frame[i].data);
669	}
670	out += sprintf(out, "snap_enabled    : %s\n", YES_NO(ov->snap_enabled));
671	out += sprintf(out, "bridge          : %s\n",
672		       symbolic(brglist, ov->bridge));
673	out += sprintf(out, "sensor          : %s\n",
674		       symbolic(senlist, ov->sensor));
675	out += sprintf(out, "packet_size     : %d\n", ov->packet_size);
676	out += sprintf(out, "framebuffer     : 0x%p\n", ov->fbuf);
677	out += sprintf(out, "packet_numbering: %d\n", ov->packet_numbering);
678#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 20)
679	out += sprintf(out, "topology        : %s\n", ov->usb_path);
680#else
681	out += sprintf(out, "usb_bus         : %d\n", ov->dev->bus->busnum);
682	out += sprintf(out, "usb_device      : %d\n", ov->dev->devnum);
683#endif
684
685	len = out - page;
686	len -= off;
687	if (len < count) {
688		*eof = 1;
689		if (len <= 0)
690			return 0;
691	} else
692		len = count;
693
694	*start = page + off;
695
696	return len;
697}
698
699/* /proc/video/ov511/<minor#>/button
700 *
701 * When the camera's button is pressed, the output of this will change from a
702 * 0 to a 1 (ASCII). It will retain this value until it is read, after which
703 * it will reset to zero.
704 *
705 * SECURITY NOTE: Since reading this file can change the state of the snapshot
706 * status, it is important for applications that open it to keep it locked
707 * against access by other processes, using flock() or a similar mechanism. No
708 * locking is provided by this driver.
709 */
710static int
711ov511_read_proc_button(char *page, char **start, off_t off, int count, int *eof,
712		       void *data)
713{
714	char *out = page;
715	int len, status;
716	struct usb_ov511 *ov = data;
717
718	if (!ov || !ov->dev)
719		return -ENODEV;
720
721	status = ov51x_check_snapshot(ov);
722	out += sprintf(out, "%d", status);
723
724	if (status)
725		ov51x_clear_snapshot(ov);
726
727	len = out - page;
728	len -= off;
729	if (len < count) {
730		*eof = 1;
731		if (len <= 0)
732			return 0;
733	} else {
734		len = count;
735	}
736
737	*start = page + off;
738
739	return len;
740}
741
742static void
743create_proc_ov511_cam(struct usb_ov511 *ov)
744{
745	char dirname[10];
746
747	if (!ov511_proc_entry || !ov)
748		return;
749
750	/* Create per-device directory */
751#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 10)
752	snprintf(dirname, 10, "%d", ov->vdev.minor);
753#else
754	sprintf(dirname, "%d", ov->vdev.minor);
755#endif
756	PDEBUG(4, "creating /proc/video/ov51x/%s/", dirname);
757	ov->proc_devdir = create_proc_entry(dirname, S_IFDIR, ov511_proc_entry);
758	if (!ov->proc_devdir)
759		return;
760	ov->proc_devdir->owner = THIS_MODULE;
761
762	/* Create "info" entry (human readable device information) */
763	PDEBUG(4, "creating /proc/video/ov51x/%s/info", dirname);
764	ov->proc_info = create_proc_read_entry("info", S_IFREG|S_IRUGO|S_IWUSR,
765		ov->proc_devdir, ov511_read_proc_info, ov);
766	if (!ov->proc_info)
767		return;
768	ov->proc_info->owner = THIS_MODULE;
769
770	/* Don't create it if old snapshot mode on (would cause race cond.) */
771	if (!snapshot) {
772		/* Create "button" entry (snapshot button status) */
773		PDEBUG(4, "creating /proc/video/ov51x/%s/button", dirname);
774		ov->proc_button = create_proc_read_entry("button",
775			S_IFREG|S_IRUGO|S_IWUSR, ov->proc_devdir,
776			ov511_read_proc_button, ov);
777		if (!ov->proc_button)
778			return;
779		ov->proc_button->owner = THIS_MODULE;
780	}
781
782	/* Create "control" entry (ioctl() interface) */
783	PDEBUG(4, "creating /proc/video/ov51x/%s/control", dirname);
784	lock_kernel();
785	ov->proc_control = create_proc_entry("control",	S_IFREG|S_IRUGO|S_IWUSR,
786		ov->proc_devdir);
787	if (!ov->proc_control) {
788		unlock_kernel();
789		return;
790	}
791	ov->proc_control->owner = THIS_MODULE;
792	ov->proc_control->data = ov;
793	ov->proc_control->proc_fops = &ov511_control_fops;
794	unlock_kernel();
795}
796
797static void
798destroy_proc_ov511_cam(struct usb_ov511 *ov)
799{
800	char dirname[10];
801
802	if (!ov || !ov->proc_devdir)
803		return;
804
805#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 10)
806	snprintf(dirname, 10, "%d", ov->vdev.minor);
807#else
808	sprintf(dirname, "%d", ov->vdev.minor);
809#endif
810
811	/* Destroy "control" entry */
812	if (ov->proc_control) {
813		PDEBUG(4, "destroying /proc/video/ov51x/%s/control", dirname);
814		remove_proc_entry("control", ov->proc_devdir);
815		ov->proc_control = NULL;
816	}
817
818	/* Destroy "button" entry */
819	if (ov->proc_button) {
820		PDEBUG(4, "destroying /proc/video/ov51x/%s/button", dirname);
821		remove_proc_entry("button", ov->proc_devdir);
822		ov->proc_button = NULL;
823	}
824
825	/* Destroy "info" entry */
826	if (ov->proc_info) {
827		PDEBUG(4, "destroying /proc/video/ov51x/%s/info", dirname);
828		remove_proc_entry("info", ov->proc_devdir);
829		ov->proc_info = NULL;
830	}
831
832	/* Destroy per-device directory */
833	PDEBUG(4, "destroying /proc/video/ov51x/%s/", dirname);
834	remove_proc_entry(dirname, ov511_proc_entry);
835	ov->proc_devdir = NULL;
836}
837
838static void
839proc_ov511_create(void)
840{
841	/* No current standard here. Alan prefers /proc/video/ as it keeps
842	 * /proc "less cluttered than /proc/randomcardifoundintheshed/"
843	 * -claudio
844	 */
845	if (video_proc_entry == NULL) {
846		err("Error: /proc/video/ does not exist");
847		return;
848	}
849
850	ov511_proc_entry = create_proc_entry("ov51x", S_IFDIR,
851					     video_proc_entry);
852
853	if (ov511_proc_entry)
854		ov511_proc_entry->owner = THIS_MODULE;
855	else
856		err("Unable to create /proc/video/ov51x");
857}
858
859static void
860proc_ov511_destroy(void)
861{
862	PDEBUG(3, "removing /proc/video/ov51x");
863
864	if (ov511_proc_entry == NULL)
865		return;
866
867	remove_proc_entry("ov51x", video_proc_entry);
868}
869#else
870static inline void create_proc_ov511_cam(struct usb_ov511 *ov) { }
871static inline void destroy_proc_ov511_cam(struct usb_ov511 *ov) { }
872static inline void proc_ov511_create(void) { }
873static inline void proc_ov511_destroy(void) { }
874#endif /* #ifdef CONFIG_VIDEO_PROC_FS */
875
876/**********************************************************************
877 *
878 * Register I/O
879 *
880 **********************************************************************/
881
882/* Write an OV51x register */
883static int
884reg_w(struct usb_ov511 *ov, unsigned char reg, unsigned char value)
885{
886	int rc;
887	unsigned char request = 0;
888
889	PDEBUG(5, "0x%02X:0x%02X", reg, value);
890
891	down(&ov->cbuf_lock);
892	ov->cbuf[0] = value;
893
894	switch (ov->bclass) {
895		case BCL_OV511:
896			request = 2;
897			break;
898		case BCL_OV518:
899			request = 1;
900			break;
901		case BCL_OV519:
902			request = 1;
903			break;
904	}
905
906	rc = usb_control_msg(ov->dev,
907			     usb_sndctrlpipe(ov->dev, 0),
908			     request /* REG_IO */,
909			     USB_TYPE_VENDOR | USB_RECIP_DEVICE,
910			     0, (__u16)reg, &ov->cbuf[0], 1, HZ);
911	up(&ov->cbuf_lock);
912
913	if (rc < 0)
914		err("reg write: error %d: %s", rc, symbolic(urb_errlist, rc));
915
916	return rc;
917}
918
919/* Read from an OV51x register */
920/* returns: negative is error, pos or zero is data */
921static int
922reg_r(struct usb_ov511 *ov, unsigned char reg)
923{
924	int rc;
925	unsigned char request = 0;
926
927	down(&ov->cbuf_lock);
928
929	switch (ov->bclass) {
930		case BCL_OV511:
931			request = 3;
932			break;
933		case BCL_OV518:
934			request = 1;
935			break;
936		case BCL_OV519:
937			request = 1;
938			break;
939	}
940
941	rc = usb_control_msg(ov->dev,
942			     usb_rcvctrlpipe(ov->dev, 0),
943			     request /* REG_IO */,
944			     USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
945			     0, (__u16)reg, &ov->cbuf[0], 1, HZ);
946
947	if (rc < 0) {
948		err("reg read: error %d: %s", rc, symbolic(urb_errlist, rc));
949	} else {
950		rc = ov->cbuf[0];
951		PDEBUG(5, "0x%02X:0x%02X", reg, ov->cbuf[0]);
952	}
953
954	up(&ov->cbuf_lock);
955
956	return rc;
957}
958
959/*
960 * Writes bits at positions specified by mask to an OV51x reg. Bits that are in
961 * the same position as 1's in "mask" are cleared and set to "value". Bits
962 * that are in the same position as 0's in "mask" are preserved, regardless
963 * of their respective state in "value".
964 */
965static int
966reg_w_mask(struct usb_ov511 *ov,
967	   unsigned char reg,
968	   unsigned char value,
969	   unsigned char mask)
970{
971	int ret;
972	unsigned char oldval, newval;
973
974	if (mask == 0xff) {
975		newval = value;
976	} else {
977		ret = reg_r(ov, reg);
978		if (ret < 0)
979			return ret;
980
981		oldval = (unsigned char) ret;
982		oldval &= (~mask);		/* Clear the masked bits */
983		value &= mask;			/* Enforce mask on value */
984		newval = oldval | value;	/* Set the desired bits */
985	}
986
987	return (reg_w(ov, reg, newval));
988}
989
990/*
991 * Writes bits at positions specified by bitaddr to an OV51x reg. The addressed
992 * bit is set if value = 1 and clear if value = 0.
993 */
994static int
995reg_setbit(struct usb_ov511 *ov,
996	   unsigned char reg,
997	   unsigned char value,
998	   unsigned char bitaddr)
999{
1000	int ret;
1001
1002	ret = reg_r(ov, reg);
1003
1004	if (ret < 0)
1005		return ret;
1006
1007	return (reg_w(ov, reg, ((unsigned char)ret & ~(1 << bitaddr)) | (value ? (1 << bitaddr) : 0)));
1008}
1009
1010/*
1011 * Writes multiple (n) byte value to a single register. Only valid with certain
1012 * registers (0x30 and 0xc4 - 0xce).
1013 */
1014static int
1015ov518_reg_w32(struct usb_ov511 *ov, unsigned char reg, u32 val, int n)
1016{
1017	int rc;
1018
1019	PDEBUG(5, "0x%02X:%7d, n=%d", reg, val, n);
1020
1021	down(&ov->cbuf_lock);
1022
1023	*((u32 *)ov->cbuf) = __cpu_to_le32(val);
1024
1025	rc = usb_control_msg(ov->dev,
1026			     usb_sndctrlpipe(ov->dev, 0),
1027			     1 /* REG_IO */,
1028			     USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1029			     0, (__u16)reg, ov->cbuf, n, HZ);
1030	up(&ov->cbuf_lock);
1031
1032	if (rc < 0)
1033		err("reg write multiple: error %d: %s", rc,
1034		    symbolic(urb_errlist, rc));
1035
1036	return rc;
1037}
1038
1039static int
1040ov511_upload_quan_tables(struct usb_ov511 *ov)
1041{
1042	unsigned char *pYTable = yQuanTable511;
1043	unsigned char *pUVTable = uvQuanTable511;
1044	unsigned char val0, val1;
1045	int i, rc, reg = R511_COMP_LUT_BEGIN;
1046
1047	PDEBUG(4, "Uploading quantization tables");
1048
1049	for (i = 0; i < OV511_QUANTABLESIZE / 2; i++) {
1050		if (ENABLE_Y_QUANTABLE)	{
1051			val0 = *pYTable++;
1052			val1 = *pYTable++;
1053			val0 &= 0x0f;
1054			val1 &= 0x0f;
1055			val0 |= val1 << 4;
1056			rc = reg_w(ov, reg, val0);
1057			if (rc < 0)
1058				return rc;
1059		}
1060
1061		if (ENABLE_UV_QUANTABLE) {
1062			val0 = *pUVTable++;
1063			val1 = *pUVTable++;
1064			val0 &= 0x0f;
1065			val1 &= 0x0f;
1066			val0 |= val1 << 4;
1067			rc = reg_w(ov, reg + OV511_QUANTABLESIZE/2, val0);
1068			if (rc < 0)
1069				return rc;
1070		}
1071
1072		reg++;
1073	}
1074
1075	return 0;
1076}
1077
1078/* OV518 quantization tables are 8x4 (instead of 8x8) */
1079static int
1080ov518_upload_quan_tables(struct usb_ov511 *ov)
1081{
1082	unsigned char *pYTable = yQuanTable518;
1083	unsigned char *pUVTable = uvQuanTable518;
1084	unsigned char val0, val1;
1085	int i, rc, reg = R511_COMP_LUT_BEGIN;
1086
1087	PDEBUG(4, "Uploading quantization tables");
1088
1089	for (i = 0; i < OV518_QUANTABLESIZE / 2; i++) {
1090		if (ENABLE_Y_QUANTABLE) {
1091			val0 = *pYTable++;
1092			val1 = *pYTable++;
1093			val0 &= 0x0f;
1094			val1 &= 0x0f;
1095			val0 |= val1 << 4;
1096			rc = reg_w(ov, reg, val0);
1097			if (rc < 0)
1098				return rc;
1099		}
1100
1101		if (ENABLE_UV_QUANTABLE) {
1102			val0 = *pUVTable++;
1103			val1 = *pUVTable++;
1104			val0 &= 0x0f;
1105			val1 &= 0x0f;
1106			val0 |= val1 << 4;
1107			rc = reg_w(ov, reg + OV518_QUANTABLESIZE/2, val0);
1108			if (rc < 0)
1109				return rc;
1110		}
1111
1112		reg++;
1113	}
1114
1115	return 0;
1116}
1117
1118static int
1119ov51x_reset(struct usb_ov511 *ov, unsigned char reset_type)
1120{
1121	int rc = -1;
1122
1123	if (ov->bclass == BCL_OV519) {
1124		//~~~
1125		PDEBUG(1, "Reset: type=0x0f");
1126		switch (reset_type) {
1127		case OV511_RESET_NOREGS:
1128			rc = reg_w(ov, OV519_SYS_RESET1, 0x0f);
1129//			rc = reg_w(ov, OV519_SYS_RESET0, 0xdc);
1130//			rc = reg_w(ov, OV519_SYS_RESET0, 0);
1131			rc = reg_w(ov, OV519_SYS_RESET1, 0);
1132			break;
1133		}
1134	} else {
1135		/* Setting bit 0 not allowed on 518/518Plus */
1136		if (ov->bclass == BCL_OV518)
1137			reset_type &= 0xfe;
1138
1139		PDEBUG(4, "Reset: type=0x%02X", reset_type);
1140
1141		rc = reg_w(ov, R51x_SYS_RESET, reset_type);
1142		rc = reg_w(ov, R51x_SYS_RESET, 0);
1143	}
1144	if (rc < 0)
1145		err("reset: command failed");
1146
1147	return rc;
1148}
1149
1150/**********************************************************************
1151 *
1152 * Low-level I2C I/O functions
1153 *
1154 **********************************************************************/
1155
1156/* NOTE: Do not call this function directly!
1157 * The OV518 I2C I/O procedure is different, hence, this function.
1158 * This is normally only called from i2c_w(). Note that this function
1159 * always succeeds regardless of whether the sensor is present and working.
1160 */
1161static int
1162ov518_i2c_write_internal(struct usb_ov511 *ov,
1163			 unsigned char reg,
1164			 unsigned char value)
1165{
1166	int rc;
1167
1168	PDEBUG(5, "0x%02X:0x%02X", reg, value);
1169
1170	/* Select camera register */
1171	rc = reg_w(ov, R51x_I2C_SADDR_3, reg);
1172	if (rc < 0) return rc;
1173
1174	/* Write "value" to I2C data port of OV511 */
1175	rc = reg_w(ov, R51x_I2C_DATA, value);
1176	if (rc < 0) return rc;
1177
1178	/* Initiate 3-byte write cycle */
1179	rc = reg_w(ov, R518_I2C_CTL, 0x01);
1180	if (rc < 0) return rc;
1181
1182	return 0;
1183}
1184
1185/* NOTE: Do not call this function directly! */
1186static int
1187ov511_i2c_write_internal(struct usb_ov511 *ov,
1188			 unsigned char reg,
1189			 unsigned char value)
1190{
1191	int rc, retries;
1192
1193	PDEBUG(5, "0x%02X:0x%02X", reg, value);
1194
1195	/* Three byte write cycle */
1196	for (retries = OV511_I2C_RETRIES; ; ) {
1197		/* Select camera register */
1198		rc = reg_w(ov, R51x_I2C_SADDR_3, reg);
1199		if (rc < 0) return rc;
1200
1201		/* Write "value" to I2C data port of OV511 */
1202		rc = reg_w(ov, R51x_I2C_DATA, value);
1203		if (rc < 0) return rc;
1204
1205		/* Initiate 3-byte write cycle */
1206		rc = reg_w(ov, R511_I2C_CTL, 0x01);
1207		if (rc < 0) return rc;
1208
1209		do rc = reg_r(ov, R511_I2C_CTL);
1210		while (rc > 0 && ((rc&1) == 0)); /* Retry until idle */
1211		if (rc < 0) return rc;
1212
1213		if ((rc&2) == 0) /* Ack? */
1214			break;
1215#if 0
1216		/* I2C abort */
1217		reg_w(ov, R511_I2C_CTL, 0x10);
1218#endif
1219		if (--retries < 0) {
1220			PDEBUG(5, "i2c write retries exhausted");
1221			return -1;
1222		}
1223	}
1224
1225	return 0;
1226}
1227
1228/* NOTE: Do not call this function directly!
1229 * The OV518 I2C I/O procedure is different, hence, this function.
1230 * This is normally only called from i2c_r(). Note that this function
1231 * always succeeds regardless of whether the sensor is present and working.
1232 */
1233static int
1234ov518_i2c_read_internal(struct usb_ov511 *ov, unsigned char reg)
1235{
1236	int rc, value;
1237
1238	/* Select camera register */
1239	rc = reg_w(ov, R51x_I2C_SADDR_2, reg);
1240	if (rc < 0) return rc;
1241
1242	/* Initiate 2-byte write cycle */
1243	rc = reg_w(ov, R518_I2C_CTL, 0x03);
1244	if (rc < 0) return rc;
1245
1246	/* Initiate 2-byte read cycle */
1247	rc = reg_w(ov, R518_I2C_CTL, 0x05);
1248	if (rc < 0) return rc;
1249
1250	value = reg_r(ov, R51x_I2C_DATA);
1251
1252	PDEBUG(5, "0x%02X:0x%02X", reg, value);
1253
1254	return value;
1255}
1256
1257/* NOTE: Do not call this function directly!
1258 * returns: negative is error, pos or zero is data */
1259static int
1260ov511_i2c_read_internal(struct usb_ov511 *ov, unsigned char reg)
1261{
1262	int rc, value, retries;
1263
1264	/* Two byte write cycle */
1265	for (retries = OV511_I2C_RETRIES; ; ) {
1266		/* Select camera register */
1267		rc = reg_w(ov, R51x_I2C_SADDR_2, reg);
1268		if (rc < 0) return rc;
1269
1270		/* Initiate 2-byte write cycle */
1271		rc = reg_w(ov, R511_I2C_CTL, 0x03);
1272		if (rc < 0) return rc;
1273
1274		do rc = reg_r(ov, R511_I2C_CTL);
1275		while (rc > 0 && ((rc&1) == 0)); /* Retry until idle */
1276		if (rc < 0) return rc;
1277
1278		if ((rc&2) == 0) /* Ack? */
1279			break;
1280
1281		/* I2C abort */
1282		reg_w(ov, R511_I2C_CTL, 0x10);
1283
1284		if (--retries < 0) {
1285			PDEBUG(5, "i2c write retries exhausted");
1286			return -1;
1287		}
1288	}
1289
1290	/* Two byte read cycle */
1291	for (retries = OV511_I2C_RETRIES; ; ) {
1292		/* Initiate 2-byte read cycle */
1293		rc = reg_w(ov, R511_I2C_CTL, 0x05);
1294		if (rc < 0) return rc;
1295
1296		do rc = reg_r(ov, R511_I2C_CTL);
1297		while (rc > 0 && ((rc&1) == 0)); /* Retry until idle */
1298		if (rc < 0) return rc;
1299
1300		if ((rc&2) == 0) /* Ack? */
1301			break;
1302
1303		/* I2C abort */
1304		rc = reg_w(ov, R511_I2C_CTL, 0x10);
1305		if (rc < 0) return rc;
1306
1307		if (--retries < 0) {
1308			PDEBUG(5, "i2c read retries exhausted");
1309			return -1;
1310		}
1311	}
1312
1313	value = reg_r(ov, R51x_I2C_DATA);
1314
1315	PDEBUG(5, "0x%02X:0x%02X", reg, value);
1316
1317	/* This is needed to make i2c_w() work */
1318	rc = reg_w(ov, R511_I2C_CTL, 0x05);
1319	if (rc < 0)
1320		return rc;
1321
1322	return value;
1323}
1324
1325/* returns: negative is error, pos or zero is data */
1326static int
1327i2c_r(struct usb_ov511 *ov, unsigned char reg)
1328{
1329	int rc;
1330
1331	down(&ov->i2c_lock);
1332
1333	switch (ov->bclass) {
1334		case BCL_OV511:
1335			rc = ov511_i2c_read_internal(ov, reg);
1336			break;
1337		case BCL_OV518:
1338		case BCL_OV519:
1339			rc = ov518_i2c_read_internal(ov, reg);
1340			break;
1341		default:
1342			err("i2c_r: Invalid bridge class");
1343			rc = -EINVAL;
1344	}
1345	up(&ov->i2c_lock);
1346
1347	return rc;
1348}
1349
1350static int
1351i2c_w(struct usb_ov511 *ov, unsigned char reg, unsigned char value)
1352{
1353	int rc;
1354
1355	down(&ov->i2c_lock);
1356
1357	switch (ov->bclass) {
1358		case BCL_OV511:
1359			rc = ov511_i2c_write_internal(ov, reg, value);
1360			break;
1361		case BCL_OV518:
1362		case BCL_OV519:
1363			rc = ov518_i2c_write_internal(ov, reg, value);
1364			break;
1365		default:
1366			err("ic2_w: Invalid bridge class");
1367			rc = -EINVAL;
1368	}
1369
1370	up(&ov->i2c_lock);
1371
1372	return rc;
1373}
1374
1375/* Do not call this function directly! */
1376static int
1377ov51x_i2c_write_mask_internal(struct usb_ov511 *ov,
1378			      unsigned char reg,
1379			      unsigned char value,
1380			      unsigned char mask)
1381{
1382	int rc;
1383	unsigned char oldval, newval;
1384
1385	if (mask == 0xff) {
1386		newval = value;
1387	} else {
1388		switch (ov->bclass) {
1389			case BCL_OV511:
1390					rc = ov511_i2c_read_internal(ov, reg);
1391				break;
1392			case BCL_OV518:
1393			case BCL_OV519:
1394				rc = ov518_i2c_read_internal(ov, reg);
1395				break;
1396			default:
1397				err("ov51x_i2c_write_mask_internal: Invalid bridge class");
1398				rc = -EINVAL;
1399		}
1400		if (rc < 0)
1401			return rc;
1402
1403		oldval = (unsigned char) rc;
1404		oldval &= (~mask);		/* Clear the masked bits */
1405		value &= mask;			/* Enforce mask on value */
1406		newval = oldval | value;	/* Set the desired bits */
1407	}
1408
1409	switch (ov->bclass) {
1410		case BCL_OV511:
1411			return (ov511_i2c_write_internal(ov, reg, newval));
1412			break;
1413		case BCL_OV518:
1414		case BCL_OV519:
1415			return (ov518_i2c_write_internal(ov, reg, newval));
1416			break;
1417		default:
1418			return -EINVAL;
1419	}
1420}
1421
1422/* Writes bits at positions specified by mask to an I2C reg. Bits that are in
1423 * the same position as 1's in "mask" are cleared and set to "value". Bits
1424 * that are in the same position as 0's in "mask" are preserved, regardless
1425 * of their respective state in "value".
1426 */
1427static int
1428i2c_w_mask(struct usb_ov511 *ov,
1429	   unsigned char reg,
1430	   unsigned char value,
1431	   unsigned char mask)
1432{
1433	int rc;
1434
1435	down(&ov->i2c_lock);
1436	rc = ov51x_i2c_write_mask_internal(ov, reg, value, mask);
1437	up(&ov->i2c_lock);
1438
1439	return rc;
1440}
1441
1442/* Do not call this function directly! */
1443static int
1444ov51x_i2c_setbit_internal(struct usb_ov511 *ov,
1445			      unsigned char reg,
1446			      unsigned char value,
1447			      unsigned char bitaddr)
1448{
1449	int rc;
1450	unsigned char newval;
1451
1452	switch (ov->bclass) {
1453		case BCL_OV511:
1454			rc = ov511_i2c_read_internal(ov, reg);
1455			break;
1456		case BCL_OV518:
1457		case BCL_OV519:
1458			rc = ov518_i2c_read_internal(ov, reg);
1459			break;
1460		default:
1461			err("ov51x_i2c_setbit_internal: Invalid bridge class");
1462			rc = -EINVAL;
1463	}
1464	if (rc < 0)
1465		return rc;
1466
1467	newval = ((unsigned char)rc & ~(1 << bitaddr)) | (value ? (1 << bitaddr) : 0);	/* Set the desired bit */
1468
1469	switch (ov->bclass) {
1470		case BCL_OV511:
1471			return (ov511_i2c_write_internal(ov, reg, newval));
1472			break;
1473		case BCL_OV518:
1474		case BCL_OV519:
1475			return (ov518_i2c_write_internal(ov, reg, newval));
1476			break;
1477		default:
1478			return -EINVAL;
1479	}
1480}
1481
1482/* Writes bits at positions specified by bitaddr to an I2C reg. Bits are cleared
1483 * if value = 0 and set if value = 1.
1484 */
1485static int
1486i2c_setbit(struct usb_ov511 *ov,
1487	   unsigned char reg,
1488	   unsigned char value,
1489	   unsigned char bitaddr)
1490{
1491	int rc;
1492
1493	down(&ov->i2c_lock);
1494	rc = ov51x_i2c_setbit_internal(ov, reg, value, bitaddr);
1495	up(&ov->i2c_lock);
1496
1497	return rc;
1498}
1499
1500/* Set the read and write slave IDs. The "slave" argument is the write slave,
1501 * and the read slave will be set to (slave + 1). ov->i2c_lock should be held
1502 * when calling this. This should not be called from outside the i2c I/O
1503 * functions.
1504 */
1505static int
1506i2c_set_slave_internal(struct usb_ov511 *ov, unsigned char slave)
1507{
1508	int rc;
1509
1510	rc = reg_w(ov, R51x_I2C_W_SID, slave);
1511	if (rc < 0) return rc;
1512
1513	rc = reg_w(ov, R51x_I2C_R_SID, slave + 1);
1514	if (rc < 0) return rc;
1515
1516	return 0;
1517}
1518
1519/* Write to a specific I2C slave ID and register, using the specified mask */
1520static int
1521i2c_w_slave(struct usb_ov511 *ov,
1522	    unsigned char slave,
1523	    unsigned char reg,
1524	    unsigned char value,
1525	    unsigned char mask)
1526{
1527	int rc = 0;
1528
1529	down(&ov->i2c_lock);
1530
1531	/* Set new slave IDs */
1532	rc = i2c_set_slave_internal(ov, slave);
1533	if (rc < 0) goto out;
1534
1535	rc = ov51x_i2c_write_mask_internal(ov, reg, value, mask);
1536
1537out:
1538	/* Restore primary IDs */
1539	if (i2c_set_slave_internal(ov, ov->primary_i2c_slave) < 0)
1540		err("Couldn't restore primary I2C slave");
1541
1542	up(&ov->i2c_lock);
1543	return rc;
1544}
1545
1546/* Read from a specific I2C slave ID and register */
1547static int
1548i2c_r_slave(struct usb_ov511 *ov,
1549	    unsigned char slave,
1550	    unsigned char reg)
1551{
1552	int rc;
1553
1554	down(&ov->i2c_lock);
1555
1556	/* Set new slave IDs */
1557	rc = i2c_set_slave_internal(ov, slave);
1558	if (rc < 0) goto out;
1559
1560	switch (ov->bclass) {
1561		case BCL_OV511:
1562			rc = ov511_i2c_read_internal(ov, reg);
1563			break;
1564		case BCL_OV518:
1565		case BCL_OV519:
1566			rc = ov518_i2c_read_internal(ov, reg);
1567			break;
1568		default:
1569			err("i2c_r_slave: Invalid bridge class");
1570			rc = -EINVAL;
1571	}
1572out:
1573	/* Restore primary IDs */
1574	if (i2c_set_slave_internal(ov, ov->primary_i2c_slave) < 0)
1575		err("Couldn't restore primary I2C slave");
1576
1577	up(&ov->i2c_lock);
1578	return rc;
1579}
1580
1581/* Sets I2C read and write slave IDs. Returns <0 for error */
1582static int
1583ov51x_set_slave_ids(struct usb_ov511 *ov, unsigned char sid)
1584{
1585	int rc;
1586
1587	down(&ov->i2c_lock);
1588
1589	rc = i2c_set_slave_internal(ov, sid);
1590	if (rc < 0) goto out;
1591
1592	// FIXME: Is this actually necessary?
1593	if (ov->bclass != BCL_OV519)
1594		rc = ov51x_reset(ov, OV511_RESET_NOREGS);
1595	if (rc < 0) goto out;
1596
1597out:
1598	up(&ov->i2c_lock);
1599	return rc;
1600}
1601
1602static int
1603write_regvals(struct usb_ov511 *ov, struct ov511_regvals * pRegvals)
1604{
1605	int rc;
1606
1607	while (pRegvals->bus != OV511_DONE_BUS) {
1608		if (pRegvals->bus == OV511_REG_BUS) {
1609			if ((rc = reg_w(ov, pRegvals->reg, pRegvals->val)) < 0)
1610				return rc;
1611		} else if (pRegvals->bus == OV511_I2C_BUS) {
1612			if ((rc = i2c_w(ov, pRegvals->reg, pRegvals->val)) < 0)
1613				return rc;
1614		} else {
1615			err("Bad regval array");
1616			return -1;
1617		}
1618		pRegvals++;
1619	}
1620	return 0;
1621}
1622
1623#ifdef OV511_DEBUG
1624static void
1625dump_i2c_range(struct usb_ov511 *ov, int reg1, int regn)
1626{
1627	int i, rc;
1628
1629	for (i = reg1; i <= regn; i++) {
1630		rc = i2c_r(ov, i);
1631		info("Sensor[0x%02X] = 0x%02X", i, rc);
1632	}
1633}
1634
1635static void
1636dump_i2c_regs(struct usb_ov511 *ov)
1637{
1638	info("I2C REGS");
1639	dump_i2c_range(ov, 0x00, 0x7C);
1640}
1641
1642static void
1643dump_reg_range(struct usb_ov511 *ov, int reg1, int regn)
1644{
1645	int i, rc;
1646
1647	for (i = reg1; i <= regn; i++) {
1648		rc = reg_r(ov, i);
1649		info("OV511[0x%02X] = 0x%02X", i, rc);
1650	}
1651}
1652
1653static void
1654ov511_dump_regs(struct usb_ov511 *ov)
1655{
1656	info("CAMERA INTERFACE REGS");
1657	dump_reg_range(ov, 0x10, 0x1f);
1658	info("DRAM INTERFACE REGS");
1659	dump_reg_range(ov, 0x20, 0x23);
1660	info("ISO FIFO REGS");
1661	dump_reg_range(ov, 0x30, 0x31);
1662	info("PIO REGS");
1663	dump_reg_range(ov, 0x38, 0x39);
1664	dump_reg_range(ov, 0x3e, 0x3e);
1665	info("I2C REGS");
1666	dump_reg_range(ov, 0x40, 0x49);
1667	info("SYSTEM CONTROL REGS");
1668	dump_reg_range(ov, 0x50, 0x55);
1669	dump_reg_range(ov, 0x5e, 0x5f);
1670	info("OmniCE REGS");
1671	dump_reg_range(ov, 0x70, 0x79);
1672	/* NOTE: Quantization tables are not readable. You will get the value
1673	 * in reg. 0x79 for every table register */
1674	dump_reg_range(ov, 0x80, 0x9f);
1675	dump_reg_range(ov, 0xa0, 0xbf);
1676
1677}
1678
1679static void
1680ov518_dump_regs(struct usb_ov511 *ov)
1681{
1682	info("VIDEO MODE REGS");
1683	dump_reg_range(ov, 0x20, 0x2f);
1684	info("DATA PUMP AND SNAPSHOT REGS");
1685	dump_reg_range(ov, 0x30, 0x3f);
1686	info("I2C REGS");
1687	dump_reg_range(ov, 0x40, 0x4f);
1688	info("SYSTEM CONTROL AND VENDOR REGS");
1689	dump_reg_range(ov, 0x50, 0x5f);
1690	info("60 - 6F");
1691	dump_reg_range(ov, 0x60, 0x6f);
1692	info("70 - 7F");
1693	dump_reg_range(ov, 0x70, 0x7f);
1694	info("Y QUANTIZATION TABLE");
1695	dump_reg_range(ov, 0x80, 0x8f);
1696	info("UV QUANTIZATION TABLE");
1697	dump_reg_range(ov, 0x90, 0x9f);
1698	info("A0 - BF");
1699	dump_reg_range(ov, 0xa0, 0xbf);
1700	info("CBR");
1701	dump_reg_range(ov, 0xc0, 0xcf);
1702}
1703#endif
1704
1705/*****************************************************************************/
1706
1707/* Temporarily stops OV511 from functioning. Must do this before changing
1708 * registers while the camera is streaming */
1709static inline int
1710ov51x_stop(struct usb_ov511 *ov)
1711{
1712	PDEBUG(4, "stopping");
1713	ov->stopped = 1;
1714	switch (ov->bclass) {
1715		case BCL_OV511:
1716			return (reg_w(ov, R51x_SYS_RESET, 0x3d));
1717			break;
1718		case BCL_OV518:
1719			return (reg_w_mask(ov, R51x_SYS_RESET, 0x3a, 0x3a));
1720			break;
1721		case BCL_OV519:
1722			return (reg_w(ov, OV519_SYS_RESET1, 0x0f));
1723			break;
1724		default:
1725			err("ov51x_stop: invalid bridge type");
1726	}
1727	return -1;
1728}
1729
1730/* Restarts OV511 after ov511_stop() is called. Has no effect if it is not
1731 * actually stopped (for performance). */
1732static inline int
1733ov51x_restart(struct usb_ov511 *ov)
1734{
1735	int rc = 0;
1736
1737	if (ov->stopped) {
1738		PDEBUG(4, "restarting");
1739		ov->stopped = 0;
1740
1741		/* Reinitialize the stream */
1742		switch (ov->bclass) {
1743			case BCL_OV511:
1744				rc = reg_w(ov, R51x_SYS_RESET, 0x00);
1745				break;
1746			case BCL_OV518:
1747				rc = reg_w(ov, 0x2f, 0x80);
1748				rc = reg_w(ov, R51x_SYS_RESET, 0x00);
1749				break;
1750			case BCL_OV519:
1751				rc = reg_w(ov, OV519_SYS_RESET1, 0x00);
1752				break;
1753			default:
1754				err("ov51x_restart: invalid bridge type");
1755				rc = -EINVAL;
1756		}
1757	}
1758
1759	return rc;
1760}
1761
1762/* Sleeps until no frames are active. Returns !0 if got signal */
1763static int
1764ov51x_wait_frames_inactive(struct usb_ov511 *ov)
1765{
1766	return wait_event_interruptible(ov->wq, ov->curframe < 0);
1767}
1768
1769/* Resets the hardware snapshot button */
1770static void
1771ov51x_clear_snapshot(struct usb_ov511 *ov)
1772{
1773	if (ov->bclass == BCL_OV511) {
1774		reg_w(ov, R51x_SYS_SNAP, 0x00);
1775		reg_w(ov, R51x_SYS_SNAP, 0x02);
1776		reg_w(ov, R51x_SYS_SNAP, 0x00);
1777	} else if (ov->bclass == BCL_OV518) {
1778		warn("snapshot reset not supported yet on OV518(+)");
1779	} else {
1780		err("clear snap: invalid bridge type");
1781	}
1782}
1783
1784#if defined(CONFIG_VIDEO_PROC_FS)
1785/* Checks the status of the snapshot button. Returns 1 if it was pressed since
1786 * it was last cleared, and zero in all other cases (including errors) */
1787static int
1788ov51x_check_snapshot(struct usb_ov511 *ov)
1789{
1790	int ret, status = 0;
1791
1792	if (ov->bclass == BCL_OV511) {
1793		ret = reg_r(ov, R51x_SYS_SNAP);
1794		if (ret < 0) {
1795			err("Error checking snspshot status (%d)", ret);
1796		} else if (ret & 0x08) {
1797			status = 1;
1798		}
1799	} else if (ov->bclass == BCL_OV518) {
1800		warn("snapshot check not supported yet on OV518(+)");
1801	} else {
1802		err("check snap: invalid bridge type");
1803	}
1804
1805	return status;
1806}
1807#endif
1808
1809/* This does an initial reset of an OmniVision sensor and ensures that I2C
1810 * is synchronized. Returns <0 for failure.
1811 */
1812static int
1813init_ov_sensor(struct usb_ov511 *ov)
1814{
1815	int i, success;
1816
1817	/* Reset the sensor */
1818	if (i2c_w(ov, 0x12, 0x80) < 0) return -EIO;
1819
1820	/* Wait for it to initialize */
1821	schedule_timeout(1 + 150 * HZ / 1000);
1822
1823	for (i = 0, success = 0; i < i2c_detect_tries && !success; i++) {
1824		if ((i2c_r(ov, OV7610_REG_ID_HIGH) == 0x7F) &&
1825		    (i2c_r(ov, OV7610_REG_ID_LOW) == 0xA2)) {
1826			success = 1;
1827			continue;
1828		}
1829
1830		/* Reset the sensor */
1831		if (i2c_w(ov, 0x12, 0x80) < 0) return -EIO;
1832		/* Wait for it to initialize */
1833		schedule_timeout(1 + 150 * HZ / 1000);
1834		/* Dummy read to sync I2C */
1835		if (i2c_r(ov, 0x00) < 0) return -EIO;
1836	}
1837
1838	if (!success)
1839		return -EIO;
1840
1841	PDEBUG(1, "I2C synced in %d attempt(s)", i);
1842
1843	return 0;
1844}
1845
1846static int
1847ov511_set_packet_size(struct usb_ov511 *ov, int size)
1848{
1849	int alt, mult;
1850
1851	if (ov51x_stop(ov) < 0)
1852		return -EIO;
1853
1854	mult = size >> 5;
1855
1856	if (ov->bridge == BRG_OV511) {
1857		if (size == 0) alt = OV511_ALT_SIZE_0;
1858		else if (size == 257) alt = OV511_ALT_SIZE_257;
1859		else if (size == 513) alt = OV511_ALT_SIZE_513;
1860		else if (size == 769) alt = OV511_ALT_SIZE_769;
1861		else if (size == 993) alt = OV511_ALT_SIZE_993;
1862		else {
1863			err("Set packet size: invalid size (%d)", size);
1864			return -EINVAL;
1865		}
1866	} else if (ov->bridge == BRG_OV511PLUS) {
1867		if (size == 0) alt = OV511PLUS_ALT_SIZE_0;
1868		else if (size == 33) alt = OV511PLUS_ALT_SIZE_33;
1869		else if (size == 129) alt = OV511PLUS_ALT_SIZE_129;
1870		else if (size == 257) alt = OV511PLUS_ALT_SIZE_257;
1871		else if (size == 385) alt = OV511PLUS_ALT_SIZE_385;
1872		else if (size == 513) alt = OV511PLUS_ALT_SIZE_513;
1873		else if (size == 769) alt = OV511PLUS_ALT_SIZE_769;
1874		else if (size == 961) alt = OV511PLUS_ALT_SIZE_961;
1875		else {
1876			err("Set packet size: invalid size (%d)", size);
1877			return -EINVAL;
1878		}
1879	} else {
1880		err("Set packet size: Invalid bridge type");
1881		return -EINVAL;
1882	}
1883
1884	PDEBUG(3, "%d, mult=%d, alt=%d", size, mult, alt);
1885
1886	if (reg_w(ov, R51x_FIFO_PSIZE, mult) < 0)
1887		return -EIO;
1888
1889	if (usb_set_interface(ov->dev, ov->iface, alt) < 0) {
1890		err("Set packet size: set interface error");
1891		return -EBUSY;
1892	}
1893
1894	if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
1895		return -EIO;
1896
1897	ov->packet_size = size;
1898
1899	if (ov51x_restart(ov) < 0)
1900		return -EIO;
1901
1902	return 0;
1903}
1904
1905/* Note: Unlike the OV511/OV511+, the size argument does NOT include the
1906 * optional packet number byte. The actual size *is* stored in ov->packet_size,
1907 * though. */
1908static int
1909ov518_set_packet_size(struct usb_ov511 *ov, int size)
1910{
1911	int alt;
1912
1913	if (ov51x_stop(ov) < 0)
1914		return -EIO;
1915
1916	if (ov->bclass == BCL_OV518) {
1917		if (size == 0) alt = OV518_ALT_SIZE_0;
1918		else if (size == 128) alt = OV518_ALT_SIZE_128;
1919		else if (size == 256) alt = OV518_ALT_SIZE_256;
1920		else if (size == 384) alt = OV518_ALT_SIZE_384;
1921		else if (size == 512) alt = OV518_ALT_SIZE_512;
1922		else if (size == 640) alt = OV518_ALT_SIZE_640;
1923		else if (size == 768) alt = OV518_ALT_SIZE_768;
1924		else if (size == 896) alt = OV518_ALT_SIZE_896;
1925		else {
1926			err("Set packet size: invalid size (%d)", size);
1927			return -EINVAL;
1928		}
1929	} else {
1930		err("Set packet size: Invalid bridge type");
1931		return -EINVAL;
1932	}
1933
1934	PDEBUG(3, "%d, alt=%d", size, alt);
1935
1936	ov->packet_size = size;
1937	if (size > 0) {
1938		/* Program ISO FIFO size reg (packet number isn't included) */
1939		ov518_reg_w32(ov, 0x30, size, 2);
1940
1941		if (ov->packet_numbering)
1942			++ov->packet_size;
1943	}
1944
1945	if (usb_set_interface(ov->dev, ov->iface, alt) < 0) {
1946		err("Set packet size: set interface error");
1947		return -EBUSY;
1948	}
1949
1950	/* Initialize the stream */
1951	if (reg_w(ov, 0x2f, 0x80) < 0)
1952		return -EIO;
1953
1954	if (ov51x_restart(ov) < 0)
1955		return -EIO;
1956
1957	if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
1958		return -EIO;
1959
1960	return 0;
1961}
1962
1963/* Note: Unlike the OV511/OV511+, the size argument does NOT include the
1964 * optional packet number byte. The actual size *is* stored in ov->packet_size,
1965 * though. */
1966static int
1967ov519_set_packet_size(struct usb_ov511 *ov, int size)
1968{
1969	int alt;
1970
1971	if (ov51x_stop(ov) < 0)
1972		return -EIO;
1973
1974	if (ov->bclass == BCL_OV519) {
1975		if      (size ==   0) alt = OV519_ALT_SIZE_0;
1976		else if (size == 384) alt = OV519_ALT_SIZE_384;
1977		else if (size == 512) alt = OV519_ALT_SIZE_512;
1978		else if (size == 768) alt = OV519_ALT_SIZE_768;
1979		else if (size == 896) alt = OV519_ALT_SIZE_896;
1980		else {
1981			err("Set packet size: invalid size (%d)", size);
1982			return -EINVAL;
1983		}
1984	} else {
1985		err("Set packet size: Invalid bridge class");
1986		return -EINVAL;
1987	}
1988
1989	PDEBUG(3, "%d, alt=%d", size, alt);
1990
1991	ov->packet_size = size;
1992	if (size > 0) {
1993		/* Program ISO FIFO size reg (packet number isn't included) */
1994	//~~~ is this nessecary?	ov518_reg_w32(ov, 0x30, size, 2);
1995
1996		if (ov->packet_numbering)
1997			++ov->packet_size;
1998	}
1999
2000	if (usb_set_interface(ov->dev, ov->iface, alt) < 0) {
2001		err("Set packet size: set interface error");
2002		return -EBUSY;
2003	}
2004
2005	/* Initialize the stream */
2006
2007	if (size > 0) {
2008		if (ov51x_restart(ov) < 0)
2009			return -EIO;
2010	}
2011
2012//	if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
2013//		return -EIO;
2014
2015	return 0;
2016}
2017
2018/* Upload compression params and quantization tables. Returns 0 for success. */
2019static int
2020ov511_init_compression(struct usb_ov511 *ov)
2021{
2022	int rc = 0;
2023
2024	if (!ov->compress_inited) {
2025		reg_w(ov, 0x70, phy);
2026		reg_w(ov, 0x71, phuv);
2027		reg_w(ov, 0x72, pvy);
2028		reg_w(ov, 0x73, pvuv);
2029		reg_w(ov, 0x74, qhy);
2030		reg_w(ov, 0x75, qhuv);
2031		reg_w(ov, 0x76, qvy);
2032		reg_w(ov, 0x77, qvuv);
2033
2034		if (ov511_upload_quan_tables(ov) < 0) {
2035			err("Error uploading quantization tables");
2036			rc = -EIO;
2037			goto out;
2038		}
2039	}
2040
2041	ov->compress_inited = 1;
2042out:
2043	return rc;
2044}
2045
2046/* Upload compression params and quantization tables. Returns 0 for success. */
2047static int
2048ov518_init_compression(struct usb_ov511 *ov)
2049{
2050	int rc = 0;
2051
2052	if (!ov->compress_inited) {
2053		if (ov518_upload_quan_tables(ov) < 0) {
2054			err("Error uploading quantization tables");
2055			rc = -EIO;
2056			goto out;
2057		}
2058	}
2059
2060	ov->compress_inited = 1;
2061out:
2062	return rc;
2063}
2064
2065/* Switch on standard JPEG compression. Returns 0 for success. */
2066static int
2067ov519_init_compression(struct usb_ov511 *ov)
2068{
2069	int rc = 0;
2070
2071	if (!ov->compress_inited) {
2072		if (reg_setbit(ov, OV519_SYS_EN_CLK1, 1, 2 ) < 0) {
2073			err("Error switching to compressed mode");
2074			rc = -EIO;
2075			goto out;
2076		}
2077	}
2078
2079	ov->compress_inited = 1;
2080out:
2081	return rc;
2082}
2083
2084/* -------------------------------------------------------------------------- */
2085
2086/* Sets sensor's contrast setting to "val" */
2087static int
2088sensor_set_contrast(struct usb_ov511 *ov, unsigned short val)
2089{
2090	int rc;
2091
2092	PDEBUG(3, "%d", val);
2093
2094	if (ov->stop_during_set)
2095		if (ov51x_stop(ov) < 0)
2096			return -EIO;
2097
2098	switch (ov->sensor) {
2099	case SEN_OV7610:
2100	case SEN_OV6620:
2101	{
2102		rc = i2c_w(ov, OV7610_REG_CNT, val >> 8);
2103		if (rc < 0)
2104			goto out;
2105		break;
2106	}
2107	case SEN_OV6630:
2108	{
2109		rc = i2c_w_mask(ov, OV7610_REG_CNT, val >> 12, 0x0f);
2110		if (rc < 0)
2111			goto out;
2112		break;
2113	}
2114	case SEN_OV8610:
2115	{
2116		static unsigned char ctab[] = {
2117			0x03, 0x09, 0x0b, 0x0f, 0x53, 0x6f, 0x35, 0x7f
2118		};
2119
2120		/* Use Y gamma control instead. Bit 0 enables it. */
2121		rc = i2c_w(ov, 0x64, ctab[val>>13]);
2122		if (rc < 0)
2123			goto out;
2124		break;
2125	}
2126	case SEN_OV7620:
2127	{
2128		static unsigned char ctab[] = {
2129			0x01, 0x05, 0x09, 0x11, 0x15, 0x35, 0x37, 0x57,
2130			0x5b, 0xa5, 0xa7, 0xc7, 0xc9, 0xcf, 0xef, 0xff
2131		};
2132
2133		/* Use Y gamma control instead. Bit 0 enables it. */
2134		rc = i2c_w(ov, 0x64, ctab[val>>12]);
2135		if (rc < 0)
2136			goto out;
2137		break;
2138	}
2139	case SEN_OV7640:
2140	{
2141		/* Use gain control instead. */
2142		rc = i2c_w(ov, OV7610_REG_GAIN, val>>10);
2143		if (rc < 0)
2144			goto out;
2145		break;
2146	}
2147	case SEN_SAA7111A:
2148	{
2149		rc = i2c_w(ov, 0x0b, val >> 9);
2150		if (rc < 0)
2151			goto out;
2152		break;
2153	}
2154	default:
2155	{
2156		PDEBUG(3, "Unsupported with this sensor");
2157		rc = -EPERM;
2158		goto out;
2159	}
2160	}
2161
2162	rc = 0;		/* Success */
2163	ov->contrast = val;
2164out:
2165	if (ov51x_restart(ov) < 0)
2166		return -EIO;
2167
2168	return rc;
2169}
2170
2171/* Gets sensor's contrast setting */
2172static int
2173sensor_get_contrast(struct usb_ov511 *ov, unsigned short *val)
2174{
2175	int rc;
2176
2177	switch (ov->sensor) {
2178	case SEN_OV7610:
2179	case SEN_OV6620:
2180		rc = i2c_r(ov, OV7610_REG_CNT);
2181		if (rc < 0)
2182			return rc;
2183		else
2184			*val = rc << 8;
2185		break;
2186	case SEN_OV6630:
2187		rc = i2c_r(ov, OV7610_REG_CNT);
2188		if (rc < 0)
2189			return rc;
2190		else
2191			*val = rc << 12;
2192		break;
2193	case SEN_OV8610:
2194	{
2195		static unsigned char ctab[] = {
2196			0x03, 0x09, 0x0b, 0x0f, 0x53, 0x6f, 0x35, 0x7f
2197		};
2198		static int cidx = 0;
2199
2200		/* Use Y gamma control instead. Bit 0 enables it. */
2201		rc = i2c_r(ov, 0x64);
2202		if (rc < 0) {
2203			return rc;
2204		} else {
2205			for (cidx = 0; cidx < 8; cidx++) {
2206				if (ctab[cidx] == rc) {
2207					*val = cidx << 13;
2208					break;
2209				}
2210			}
2211			if (cidx == 8) // could not find value in table
2212				return -EINVAL;
2213		}
2214		break;
2215	}
2216	case SEN_OV7620:
2217		/* Use Y gamma reg instead. Bit 0 is the enable bit. */
2218		rc = i2c_r(ov, 0x64);
2219		if (rc < 0)
2220			return rc;
2221		else
2222			*val = (rc & 0xfe) << 8;
2223		break;
2224	case SEN_OV7640:
2225		/* Use gain control instead. */
2226		rc = i2c_r(ov, OV7610_REG_GAIN);
2227		if (rc < 0)
2228			return rc;
2229		else
2230			*val = rc << 10;
2231		break;
2232
2233	case SEN_SAA7111A:
2234		*val = ov->contrast;
2235		break;
2236	default:
2237		PDEBUG(3, "Unsupported with this sensor");
2238		return -EPERM;
2239	}
2240
2241	PDEBUG(3, "%d", *val);
2242	ov->contrast = *val;
2243
2244	return 0;
2245}
2246
2247/* -------------------------------------------------------------------------- */
2248
2249/* Sets sensor's brightness setting to "val" */
2250static int
2251sensor_set_brightness(struct usb_ov511 *ov, unsigned short val)
2252{
2253	int rc;
2254
2255	PDEBUG(4, "%d", val);
2256
2257	if (ov->stop_during_set)
2258		if (ov51x_stop(ov) < 0)
2259			return -EIO;
2260
2261	switch (ov->sensor) {
2262	case SEN_OV8610:
2263	case SEN_OV7610:
2264	case SEN_OV76BE:
2265	case SEN_OV6620:
2266	case SEN_OV6630:
2267	case SEN_OV7640:
2268		rc = i2c_w(ov, OV7610_REG_BRT, val >> 8);
2269		if (rc < 0)
2270			goto out;
2271		break;
2272	case SEN_OV7620:
2273		/* 7620 doesn't like manual changes when in auto mode */
2274		if (!ov->auto_brt) {
2275			rc = i2c_w(ov, OV7610_REG_BRT, val >> 8);
2276			if (rc < 0)
2277				goto out;
2278		}
2279		break;
2280	case SEN_SAA7111A:
2281		rc = i2c_w(ov, 0x0a, val >> 8);
2282		if (rc < 0)
2283			goto out;
2284		break;
2285	default:
2286		PDEBUG(3, "Unsupported with this sensor");
2287		rc = -EPERM;
2288		goto out;
2289	}
2290
2291	rc = 0;		/* Success */
2292	ov->brightness = val;
2293out:
2294	if (ov51x_restart(ov) < 0)
2295		return -EIO;
2296
2297	return rc;
2298}
2299
2300/* Gets sensor's brightness setting */
2301static int
2302sensor_get_brightness(struct usb_ov511 *ov, unsigned short *val)
2303{
2304	int rc;
2305
2306	switch (ov->sensor) {
2307	case SEN_OV8610:
2308	case SEN_OV7610:
2309	case SEN_OV76BE:
2310	case SEN_OV7620:
2311	case SEN_OV6620:
2312	case SEN_OV6630:
2313	case SEN_OV7640:
2314		rc = i2c_r(ov, OV7610_REG_BRT);
2315		if (rc < 0)
2316			return rc;
2317		else
2318			*val = rc << 8;
2319		break;
2320	case SEN_SAA7111A:
2321		*val = ov->brightness;
2322		break;
2323	default:
2324		PDEBUG(3, "Unsupported with this sensor");
2325		return -EPERM;
2326	}
2327
2328	PDEBUG(3, "%d", *val);
2329	ov->brightness = *val;
2330
2331	return 0;
2332}
2333
2334/* -------------------------------------------------------------------------- */
2335
2336/* Sets sensor's saturation (color intensity) setting to "val" */
2337static int
2338sensor_set_saturation(struct usb_ov511 *ov, unsigned short val)
2339{
2340	int rc;
2341
2342	PDEBUG(3, "%d", val);
2343
2344	if (ov->stop_during_set)
2345		if (ov51x_stop(ov) < 0)
2346			return -EIO;
2347
2348	switch (ov->sensor) {
2349	case SEN_OV8610:
2350	case SEN_OV7610:
2351	case SEN_OV76BE:
2352	case SEN_OV6620:
2353	case SEN_OV6630:
2354		rc = i2c_w(ov, OV7610_REG_SAT, val >> 8);
2355		if (rc < 0)
2356			goto out;
2357		break;
2358	case SEN_OV7620:
2359//		/* Use UV gamma control instead. Bits 0 & 7 are reserved. */
2360//		rc = ov_i2c_write(ov->dev, 0x62, (val >> 9) & 0x7e);
2361//		if (rc < 0)
2362//			goto out;
2363		rc = i2c_w(ov, OV7610_REG_SAT, val >> 8);
2364		if (rc < 0)
2365			goto out;
2366		break;
2367	case SEN_OV7640:
2368		rc = i2c_w(ov, OV7610_REG_SAT, (val >> 8) & 0xf0);
2369		if (rc < 0)
2370			goto out;
2371	case SEN_SAA7111A:
2372		rc = i2c_w(ov, 0x0c, val >> 9);
2373		if (rc < 0)
2374			goto out;
2375		break;
2376	default:
2377		PDEBUG(3, "Unsupported with this sensor");
2378		rc = -EPERM;
2379		goto out;
2380	}
2381
2382	rc = 0;		/* Success */
2383	ov->colour = val;
2384out:
2385	if (ov51x_restart(ov) < 0)
2386		return -EIO;
2387
2388	return rc;
2389}
2390
2391/* Gets sensor's saturation (color intensity) setting */
2392static int
2393sensor_get_saturation(struct usb_ov511 *ov, unsigned short *val)
2394{
2395	int rc;
2396
2397	switch (ov->sensor) {
2398	case SEN_OV8610:
2399	case SEN_OV7610:
2400	case SEN_OV76BE:
2401	case SEN_OV6620:
2402	case SEN_OV6630:
2403	case SEN_OV7640:
2404		rc = i2c_r(ov, OV7610_REG_SAT);
2405		if (rc < 0)
2406			return rc;
2407		else
2408			*val = rc << 8;
2409		break;
2410	case SEN_OV7620:
2411//		/* Use UV gamma reg instead. Bits 0 & 7 are reserved. */
2412//		rc = i2c_r(ov, 0x62);
2413//		if (rc < 0)
2414//			return rc;
2415//		else
2416//			*val = (rc & 0x7e) << 9;
2417		rc = i2c_r(ov, OV7610_REG_SAT);
2418		if (rc < 0)
2419			return rc;
2420		else
2421			*val = rc << 8;
2422		break;
2423	case SEN_SAA7111A:
2424		*val = ov->colour;
2425		break;
2426	default:
2427		PDEBUG(3, "Unsupported with this sensor");
2428		return -EPERM;
2429	}
2430
2431	PDEBUG(3, "%d", *val);
2432	ov->colour = *val;
2433
2434	return 0;
2435}
2436
2437/* -------------------------------------------------------------------------- */
2438
2439/* Sets sensor's hue (red/blue balance) setting to "val" */
2440static int
2441sensor_set_hue(struct usb_ov511 *ov, unsigned short val)
2442{
2443	int rc;
2444
2445	PDEBUG(3, "%d", val);
2446
2447	if (ov->stop_during_set)
2448		if (ov51x_stop(ov) < 0)
2449			return -EIO;
2450
2451	switch (ov->sensor) {
2452	case SEN_OV7610:
2453	case SEN_OV6620:
2454	case SEN_OV6630:
2455		rc = i2c_w(ov, OV7610_REG_RED, 0xFF - (val >> 8));
2456		if (rc < 0)
2457			goto out;
2458
2459		rc = i2c_w(ov, OV7610_REG_BLUE, val >> 8);
2460		if (rc < 0)
2461			goto out;
2462		break;
2463	case SEN_OV8610:
2464	case SEN_OV7640:
2465		rc = i2c_w(ov, OV8610_REG_HUE, (val >> 11) | 0x20);
2466		if (rc < 0)
2467			goto out;
2468		break;
2469	case SEN_OV7620:
2470// Hue control is causing problems. I will enable it once it's fixed.
2471#if 0
2472		rc = i2c_w(ov, 0x7a, (unsigned char)(val >> 8) + 0xb);
2473		if (rc < 0)
2474			goto out;
2475
2476		rc = i2c_w(ov, 0x79, (unsigned char)(val >> 8) + 0xb);
2477		if (rc < 0)
2478			goto out;
2479#endif
2480		break;
2481	case SEN_SAA7111A:
2482		rc = i2c_w(ov, 0x0d, (val + 32768) >> 8);
2483		if (rc < 0)
2484			goto out;
2485		break;
2486	default:
2487		PDEBUG(3, "Unsupported with this sensor");
2488		rc = -EPERM;
2489		goto out;
2490	}
2491
2492	rc = 0;		/* Success */
2493	ov->hue = val;
2494out:
2495	if (ov51x_restart(ov) < 0)
2496		return -EIO;
2497
2498	return rc;
2499}
2500
2501/* Gets sensor's hue (red/blue balance) setting */
2502static int
2503sensor_get_hue(struct usb_ov511 *ov, unsigned short *val)
2504{
2505	int rc;
2506
2507	switch (ov->sensor) {
2508	case SEN_OV7610:
2509	case SEN_OV6620:
2510	case SEN_OV6630:
2511		rc = i2c_r(ov, OV7610_REG_BLUE);
2512		if (rc < 0)
2513			return rc;
2514		else
2515			*val = rc << 8;
2516		break;
2517	case SEN_OV8610:
2518	case SEN_OV7640:
2519		rc = i2c_r(ov, OV8610_REG_HUE);
2520		if (rc < 0)
2521			return rc;
2522		else
2523			*val = (rc & 0x1f) << 11;
2524		break;
2525	case SEN_OV7620:
2526		rc = i2c_r(ov, 0x7a);
2527		if (rc < 0)
2528			return rc;
2529		else
2530			*val = rc << 8;
2531		break;
2532	case SEN_SAA7111A:
2533		*val = ov->hue;
2534		break;
2535	default:
2536		PDEBUG(3, "Unsupported with this sensor");
2537		return -EPERM;
2538	}
2539
2540	PDEBUG(3, "%d", *val);
2541	ov->hue = *val;
2542
2543	return 0;
2544}
2545
2546/* -------------------------------------------------------------------------- */
2547
2548static int
2549sensor_set_picture(struct usb_ov511 *ov, struct video_picture *p)
2550{
2551	int rc;
2552
2553	PDEBUG(4, "sensor_set_picture");
2554
2555	ov->whiteness = p->whiteness;
2556
2557	/* Don't return error if a setting is unsupported, or rest of settings
2558         * will not be performed */
2559
2560	rc = sensor_set_contrast(ov, p->contrast);
2561	if (FATAL_ERROR(rc))
2562		return rc;
2563
2564	rc = sensor_set_brightness(ov, p->brightness);
2565	if (FATAL_ERROR(rc))
2566		return rc;
2567
2568	rc = sensor_set_saturation(ov, p->colour);
2569	if (FATAL_ERROR(rc))
2570		return rc;
2571
2572	rc = sensor_set_hue(ov, p->hue);
2573	if (FATAL_ERROR(rc))
2574		return rc;
2575
2576	return 0;
2577}
2578
2579static int
2580sensor_get_picture(struct usb_ov511 *ov, struct video_picture *p)
2581{
2582	int rc;
2583
2584	PDEBUG(4, "sensor_get_picture");
2585
2586	/* Don't return error if a setting is unsupported, or rest of settings
2587         * will not be performed */
2588
2589	rc = sensor_get_contrast(ov, &(p->contrast));
2590	if (FATAL_ERROR(rc))
2591		return rc;
2592
2593	rc = sensor_get_brightness(ov, &(p->brightness));
2594	if (FATAL_ERROR(rc))
2595		return rc;
2596
2597	rc = sensor_get_saturation(ov, &(p->colour));
2598	if (FATAL_ERROR(rc))
2599		return rc;
2600
2601	rc = sensor_get_hue(ov, &(p->hue));
2602	if (FATAL_ERROR(rc))
2603		return rc;
2604
2605	p->whiteness = 105 << 8;
2606
2607	return 0;
2608}
2609
2610#if defined(CONFIG_VIDEO_PROC_FS)
2611// FIXME: Exposure range is only 0x00-0x7f in interlace mode
2612/* Sets current exposure for sensor. This only has an effect if auto-exposure
2613 * is off */
2614static inline int
2615sensor_set_exposure(struct usb_ov511 *ov, unsigned char val)
2616{
2617	int rc;
2618
2619	PDEBUG(3, "%d", val);
2620
2621	if (ov->stop_during_set)
2622		if (ov51x_stop(ov) < 0)
2623			return -EIO;
2624
2625	switch (ov->sensor) {
2626	case SEN_OV6620:
2627	case SEN_OV6630:
2628	case SEN_OV7610:
2629	case SEN_OV7620:
2630	case SEN_OV7640:
2631	case SEN_OV76BE:
2632	case SEN_OV8600:
2633	case SEN_OV8610:
2634		rc = i2c_w(ov, 0x10, val);
2635		if (rc < 0)
2636			goto out;
2637
2638		break;
2639	case SEN_SAA7111A:
2640		PDEBUG(3, "Unsupported with this sensor");
2641		return -EPERM;
2642	default:
2643		err("Sensor not supported for set_exposure");
2644		return -EINVAL;
2645	}
2646
2647	rc = 0;		/* Success */
2648	ov->exposure = val;
2649out:
2650	if (ov51x_restart(ov) < 0)
2651		return -EIO;
2652
2653	return rc;
2654}
2655
2656/* Gets current exposure level from sensor, regardless of whether it is under
2657 * manual control. */
2658static int
2659sensor_get_exposure(struct usb_ov511 *ov, unsigned char *val)
2660{
2661	int rc;
2662
2663	switch (ov->sensor) {
2664	case SEN_OV7610:
2665	case SEN_OV6620:
2666	case SEN_OV6630:
2667	case SEN_OV7620:
2668	case SEN_OV7640:
2669	case SEN_OV76BE:
2670	case SEN_OV8600:
2671	case SEN_OV8610:
2672		rc = i2c_r(ov, 0x10);
2673		if (rc < 0)
2674			return rc;
2675		else
2676			*val = rc;
2677		break;
2678	case SEN_SAA7111A:
2679		val = 0;
2680		PDEBUG(3, "Unsupported with this sensor");
2681		return -EPERM;
2682	default:
2683		err("Sensor not supported for get_exposure");
2684		return -EINVAL;
2685	}
2686
2687	PDEBUG(3, "%d", *val);
2688	ov->exposure = *val;
2689
2690	return 0;
2691}
2692#endif /* CONFIG_VIDEO_PROC_FS */
2693
2694/* Turns on or off the LED. Only has an effect with OV511+/OV518(+)/OV519 */
2695static void
2696ov51x_led_control(struct usb_ov511 *ov, int on)
2697{
2698	PDEBUG(4, " (%s)", on ? "turn on" : "turn off");
2699
2700	if (ov->bridge == BRG_OV511PLUS)
2701		reg_w(ov, R511_SYS_LED_CTL, on ? 1 : 0);
2702	else if (ov->bridge == BRG_OV519)
2703		reg_w_mask(ov, OV519_GPIO_DATA_OUT0, on ? 0x01 : 0x00, 0x01);
2704	else if (ov->bclass == BCL_OV518)
2705		reg_w_mask(ov, R518_GPIO_OUT, on ? 0x02 : 0x00, 0x02);
2706
2707	return;
2708}
2709
2710/* Matches the sensor's internal frame rate to the lighting frequency.
2711 * Valid frequencies are:
2712 *	50 - 50Hz, for European and Asian lighting
2713 *	60 - 60Hz, for American lighting
2714 *
2715 * Tested with: OV7610, OV7620, OV76BE, OV6620
2716 * Unsupported: KS0127, KS0127B, SAA7111A
2717 * Returns: 0 for success
2718 */
2719static int
2720sensor_set_light_freq(struct usb_ov511 *ov, int freq)
2721{
2722	int sixty;
2723
2724	PDEBUG(4, "%d Hz", freq);
2725
2726	if (freq == 60)
2727		sixty = 1;
2728	else if (freq == 50)
2729		sixty = 0;
2730	else {
2731		err("Invalid light freq (%d Hz)", freq);
2732		return -EINVAL;
2733	}
2734
2735	switch (ov->sensor) {
2736	case SEN_OV8610:
2737		i2c_w(ov, 0x2b, sixty?0xcc:0xc0);
2738		i2c_w(ov, 0x2a, sixty?0x80:0xa0);
2739		break;
2740	case SEN_OV7610:
2741		i2c_w_mask(ov, 0x2a, sixty?0x00:0x80, 0x80);
2742		i2c_w(ov, 0x2b, sixty?0x00:0xac);
2743		i2c_w_mask(ov, 0x13, 0x10, 0x10);
2744		i2c_w_mask(ov, 0x13, 0x00, 0x10);
2745		break;
2746	case SEN_OV7620:
2747	case SEN_OV76BE:
2748	case SEN_OV8600:
2749		i2c_w_mask(ov, 0x2a, sixty?0x00:0x80, 0x80);
2750		i2c_w(ov, 0x2b, sixty?0x00:0xac);
2751		i2c_w_mask(ov, 0x76, 0x01, 0x01);
2752		break;
2753	case SEN_OV7640:
2754		i2c_w_mask(ov, 0x2a, sixty?0x00:0x80, 0x80);
2755		i2c_w(ov, 0x2b, sixty?0x00:0xac);
2756	case SEN_OV6620:
2757	case SEN_OV6630:
2758		i2c_w(ov, 0x2b, sixty?0xa8:0x28);
2759		i2c_w(ov, 0x2a, sixty?0x84:0xa4);
2760		break;
2761	case SEN_SAA7111A:
2762		PDEBUG(5, "Unsupported with this sensor");
2763		return -EPERM;
2764	default:
2765		err("Sensor not supported for set_light_freq");
2766		return -EINVAL;
2767	}
2768
2769	ov->lightfreq = freq;
2770
2771	return 0;
2772}
2773
2774/* If enable is true, turn on the sensor's banding filter, otherwise turn it
2775 * off. This filter tries to reduce the pattern of horizontal light/dark bands
2776 * caused by some (usually fluorescent) lighting. The light frequency must be
2777 * set either before or after enabling it with ov51x_set_light_freq().
2778 *
2779 * Tested with: OV7610, OV7620, OV76BE, OV6620.
2780 * Unsupported: KS0127, KS0127B, SAA7111A
2781 * Returns: 0 for success
2782 */
2783static int
2784sensor_set_banding_filter(struct usb_ov511 *ov, int enable)
2785{
2786	int rc;
2787
2788	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2789
2790	if (ov->sensor == SEN_KS0127 || ov->sensor == SEN_KS0127B
2791		|| ov->sensor == SEN_SAA7111A) {
2792		PDEBUG(5, "Unsupported with this sensor");
2793		return -EPERM;
2794	}
2795
2796	rc = i2c_w_mask(ov, 0x2d, enable?0x04:0x00, 0x04);
2797	if (rc < 0)
2798		return rc;
2799
2800	ov->bandfilt = enable;
2801
2802	return 0;
2803}
2804
2805/* If enable is true, turn on the sensor's auto brightness control, otherwise
2806 * turn it off.
2807 *
2808 * Unsupported: KS0127, KS0127B, SAA7111A, OV7640
2809 * Returns: 0 for success
2810 */
2811static int
2812sensor_set_auto_brightness(struct usb_ov511 *ov, int enable)
2813{
2814	int rc;
2815
2816	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2817
2818	if (ov->sensor == SEN_KS0127 || ov->sensor == SEN_KS0127B
2819		|| ov->sensor == SEN_SAA7111A || ov->sensor == SEN_OV7640) {
2820		PDEBUG(5, "Unsupported with this sensor");
2821		return -EPERM;
2822	}
2823
2824	rc = i2c_w_mask(ov, 0x2d, enable?0x10:0x00, 0x10);
2825	if (rc < 0)
2826		return rc;
2827
2828	ov->auto_brt = enable;
2829
2830	return 0;
2831}
2832
2833/* If enable is true, turn on the sensor's auto exposure control, otherwise
2834 * turn it off.
2835 *
2836 * Unsupported: KS0127, KS0127B, SAA7111A
2837 * Returns: 0 for success
2838 */
2839static int
2840sensor_set_auto_exposure(struct usb_ov511 *ov, int enable)
2841{
2842	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2843
2844	switch (ov->sensor) {
2845	case SEN_OV7610:
2846		i2c_w_mask(ov, 0x29, enable?0x00:0x80, 0x80);
2847		break;
2848	case SEN_OV6620:
2849	case SEN_OV7620:
2850	case SEN_OV7640:
2851	case SEN_OV76BE:
2852	case SEN_OV8600:
2853		i2c_w_mask(ov, 0x13, enable?0x01:0x00, 0x01);
2854		break;
2855	case SEN_OV6630:
2856	case SEN_OV8610:
2857		i2c_w_mask(ov, 0x28, enable?0x00:0x10, 0x10);
2858		break;
2859	case SEN_SAA7111A:
2860		PDEBUG(5, "Unsupported with this sensor");
2861		return -EPERM;
2862	default:
2863		err("Sensor not supported for set_auto_exposure");
2864		return -EINVAL;
2865	}
2866
2867	ov->auto_exp = enable;
2868
2869	return 0;
2870}
2871
2872/* If enable is true, turn on the sensor's auto gain control, otherwise
2873 * turn it off.
2874 *
2875 * Returns: 0 for success
2876 */
2877static int
2878sensor_set_auto_gain(struct usb_ov511 *ov, int enable)
2879{
2880	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2881
2882	switch (ov->sensor) {
2883	case SEN_OV7640:
2884		i2c_w_mask(ov, 0x13, enable?0x02:0x00, 0x02);
2885		break;
2886	default:
2887		PDEBUG(5, "Unsupported with this sensor");
2888		return -EPERM;
2889//	default:
2890//		err("Sensor not supported for set_auto_gain");
2891//		return -EINVAL;
2892	}
2893
2894	ov->auto_gain = enable;
2895
2896	return 0;
2897}
2898
2899/* Modifies the sensor's exposure algorithm to allow proper exposure of objects
2900 * that are illuminated from behind.
2901 *
2902 * Tested with: OV6620, OV7620
2903 * Unsupported: OV7610, OV7640, OV76BE, KS0127, KS0127B, SAA7111A
2904 * Returns: 0 for success
2905 */
2906static int
2907sensor_set_backlight(struct usb_ov511 *ov, int enable)
2908{
2909	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2910
2911	switch (ov->sensor) {
2912	case SEN_OV8610:
2913		// change AEC/AGC Reference level
2914		i2c_w_mask(ov, 0x68, enable?0xef:0xcf, 0xff);
2915		// select central 1/4 image to calculate AEC/AGC
2916		i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2917		// increase gain 3dB
2918		i2c_w_mask(ov, 0x28, enable?0x02:0x00, 0x02);
2919		break;
2920	case SEN_OV7620:
2921	case SEN_OV8600:
2922		// change AEC/AGC Reference level
2923		i2c_w_mask(ov, 0x68, enable?0xe0:0xc0, 0xe0);
2924		// select central 1/4 image to calculate AEC/AGC
2925		i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2926		// increase gain 3dB
2927		i2c_w_mask(ov, 0x28, enable?0x02:0x00, 0x02);
2928		break;
2929	case SEN_OV6620:
2930		i2c_w_mask(ov, 0x4e, enable?0xe0:0xc0, 0xe0);
2931		i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2932		i2c_w_mask(ov, 0x0e, enable?0x80:0x00, 0x80);
2933		break;
2934	case SEN_OV6630:
2935		i2c_w_mask(ov, 0x4e, enable?0x80:0x60, 0xe0);
2936		i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2937		i2c_w_mask(ov, 0x28, enable?0x02:0x00, 0x02);
2938		break;
2939	case SEN_OV7610:
2940	case SEN_OV7640:
2941	case SEN_OV76BE:
2942	case SEN_SAA7111A:
2943		PDEBUG(5, "Unsupported with this sensor");
2944		return -EPERM;
2945	default:
2946		err("Sensor not supported for set_backlight");
2947		return -EINVAL;
2948	}
2949
2950	ov->backlight = enable;
2951
2952	return 0;
2953}
2954
2955static int
2956sensor_set_mirror(struct usb_ov511 *ov, int enable)
2957{
2958	PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2959
2960	switch (ov->sensor) {
2961	case SEN_OV6620:
2962	case SEN_OV6630:
2963	case SEN_OV7610:
2964	case SEN_OV7620:
2965	case SEN_OV76BE:
2966	case SEN_OV7640:
2967	case SEN_OV8600:
2968	case SEN_OV8610:
2969		i2c_w_mask(ov, 0x12, enable?0x40:0x00, 0x40);
2970		break;
2971	case SEN_SAA7111A:
2972		PDEBUG(5, "Unsupported with this sensor");
2973		return -EPERM;
2974	default:
2975		err("Sensor not supported for set_mirror");
2976		return -EINVAL;
2977	}
2978
2979	ov->mirror = enable;
2980
2981	return 0;
2982}
2983
2984/* Returns number of bits per pixel (regardless of where they are located;
2985 * planar or not), or zero for unsupported format.
2986 */
2987static inline int
2988get_depth(int palette)
2989{
2990	switch (palette) {
2991	case VIDEO_PALETTE_GREY:    return 8;
2992	case VIDEO_PALETTE_YUV420:  return 12;
2993	case VIDEO_PALETTE_YUV420P: return 12; /* Planar */
2994#ifdef OV511_ALLOW_CONVERSION
2995	case VIDEO_PALETTE_RGB565:  return 16;
2996	case VIDEO_PALETTE_RGB24:   return 24;
2997	case VIDEO_PALETTE_YUV422:  return 16;
2998	case VIDEO_PALETTE_YUYV:    return 16;
2999	case VIDEO_PALETTE_YUV422P: return 16; /* Planar */
3000#endif
3001	default:		    return 0;  /* Invalid format */
3002	}
3003}
3004
3005/* Bytes per frame. Used by read(). Return of 0 indicates error */
3006static inline long int
3007get_frame_length(struct usb_ov511 *ov, struct ov511_frame *frame)
3008{
3009	if (!frame) {
3010		return 0;
3011	} else {
3012		if (ov->bclass == BCL_OV519) {
3013			return (frame->bytes_recvd);
3014		} else {
3015			return ((frame->width * frame->height
3016				 * get_depth(frame->format)) >> 3);
3017		}
3018	}
3019}
3020
3021static int
3022mode_init_ov_sensor_regs(struct usb_ov511 *ov, struct ovsensor_window *win)
3023{
3024	int qvga = win->quarter;
3025
3026	/******** Mode (VGA/QVGA) and sensor specific regs ********/
3027
3028	switch (ov->sensor) {
3029	case SEN_OV8610:
3030		// For OV8610 qvga means qsvga
3031		i2c_setbit(ov, OV7610_REG_COM_C, qvga?1:0, 5);
3032	// FIXME: Does this improve the image quality or frame rate?
3033#if 0
3034		i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
3035		i2c_w(ov, 0x24, 0x10);
3036		i2c_w(ov, 0x25, qvga?0x40:0x8a);
3037		i2c_w(ov, 0x2f, qvga?0x30:0xb0);
3038		i2c_w(ov, 0x35, qvga?0x1c:0x9c);
3039#endif
3040		break;
3041	case SEN_OV7610:
3042		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3043// FIXME: Does this improve the image quality or frame rate?
3044#if 0
3045		i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
3046		i2c_w(ov, 0x24, 0x10);
3047		i2c_w(ov, 0x25, qvga?0x40:0x8a);
3048		i2c_w(ov, 0x2f, qvga?0x30:0xb0);
3049		i2c_w(ov, 0x35, qvga?0x1c:0x9c);
3050#endif
3051		break;
3052	case SEN_OV7620:
3053//		i2c_w(ov, 0x2b, 0x00);
3054		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3055		i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
3056		i2c_w(ov, 0x24, qvga?0x20:0x3a);
3057		i2c_w(ov, 0x25, qvga?0x30:0x60);
3058		i2c_w_mask(ov, 0x2d, qvga?0x40:0x00, 0x40);
3059		i2c_w_mask(ov, 0x67, qvga?0xf0:0x90, 0xf0);
3060		i2c_w_mask(ov, 0x74, qvga?0x20:0x00, 0x20);
3061		break;
3062	case SEN_OV76BE:
3063//		i2c_w(ov, 0x2b, 0x00);
3064		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3065// FIXME: Enable this once 7620AE uses 7620 initial settings
3066#if 0
3067		i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
3068		i2c_w(ov, 0x24, qvga?0x20:0x3a);
3069		i2c_w(ov, 0x25, qvga?0x30:0x60);
3070		i2c_w_mask(ov, 0x2d, qvga?0x40:0x00, 0x40);
3071		i2c_w_mask(ov, 0x67, qvga?0xb0:0x90, 0xf0);
3072		i2c_w_mask(ov, 0x74, qvga?0x20:0x00, 0x20);
3073#endif
3074		break;
3075	case SEN_OV7640:
3076//		i2c_w(ov, 0x2b, 0x00);
3077		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3078		i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
3079//		i2c_w(ov, 0x24, qvga?0x20:0x3a);
3080//		i2c_w(ov, 0x25, qvga?0x30:0x60);
3081//		i2c_w_mask(ov, 0x2d, qvga?0x40:0x00, 0x40);
3082//		i2c_w_mask(ov, 0x67, qvga?0xf0:0x90, 0xf0);
3083//		i2c_w_mask(ov, 0x74, qvga?0x20:0x00, 0x20);
3084		break;
3085	case SEN_OV6620:
3086		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3087		break;
3088	case SEN_OV6630:
3089		i2c_w_mask(ov, 0x14, qvga?0x20:0x00, 0x20);
3090		break;
3091	default:
3092		return -EINVAL;
3093	}
3094
3095	/******** Palette-specific regs ********/
3096
3097	if (win->format == VIDEO_PALETTE_GREY) {
3098		if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
3099			/* these aren't valid on the OV6620/OV7620/6630? */
3100			i2c_w_mask(ov, 0x0e, 0x40, 0x40);
3101		}
3102
3103		/* OV6630 default reg 0x13 value is always right */
3104		/* OV7640 is 8-bit only */
3105		if (ov->sensor != SEN_OV6630 && ov->sensor != SEN_OV7640)
3106			i2c_w_mask(ov, 0x13, 0x20, 0x20);
3107		else
3108			return -EINVAL;	/* No OV6630 greyscale support yet */
3109	} else {
3110		if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
3111			/* not valid on the OV6620/OV7620/6630? */
3112			i2c_w_mask(ov, 0x0e, 0x00, 0x40);
3113		}
3114
3115		/* The OV518 needs special treatment. Although both the OV518
3116		 * and the OV6630 support a 16-bit video bus, only the 8 bit Y
3117		 * bus is actually used. The UV bus is tied to ground.
3118		 * Therefore, the OV6630 needs to be in 8-bit multiplexed
3119		 * output mode */
3120
3121		/* OV7640 is 8-bit only */
3122
3123		if (ov->sensor != SEN_OV6630 && ov->sensor != SEN_OV7640)
3124			i2c_w_mask(ov, 0x13, 0x00, 0x20);
3125	}
3126
3127	/******** Clock programming ********/
3128
3129	/* The OV6620 needs special handling. This prevents the
3130	 * severe banding that normally occurs */
3131	if (ov->sensor == SEN_OV6620) {
3132		/* Clock down */
3133
3134		i2c_w(ov, 0x2a, 0x04);
3135		i2c_w(ov, 0x11, win->clockdiv);
3136		i2c_w(ov, 0x2a, 0x84);
3137		/* This next setting is critical. It seems to improve
3138		 * the gain or the contrast. The "reserved" bits seem
3139		 * to have some effect in this case. */
3140		i2c_w(ov, 0x2d, 0x85);
3141	} else if (win->clockdiv >= 0) {
3142		i2c_w(ov, 0x11, win->clockdiv);
3143	}
3144
3145	/******** Special Features ********/
3146
3147	if (framedrop >= 0 && ov->sensor != SEN_OV7640)
3148		i2c_w(ov, 0x16, framedrop);
3149
3150	/* Test Pattern */
3151	if (ov->sensor != SEN_OV7640)
3152		i2c_w_mask(ov, 0x12, (testpat?0x02:0x00), 0x02);
3153
3154	/* Enable auto white balance */
3155	i2c_w_mask(ov, 0x12, 0x04, 0x04);
3156
3157	// This will go away as soon as ov51x_mode_init_sensor_regs()
3158	// is fully tested.
3159	/* 7620/6620/6630? don't have register 0x35, so play it safe */
3160	if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
3161		if (win->width == 640 && win->height == 480)
3162			i2c_w(ov, 0x35, 0x9e);
3163		else
3164			i2c_w(ov, 0x35, 0x1e);
3165	}
3166
3167	return 0;
3168}
3169
3170static int
3171set_ov_sensor_window(struct usb_ov511 *ov, struct ovsensor_window *win)
3172{
3173	int hwsbase, hwebase, vwsbase, vwebase, hwscale, vwscale, ret;
3174
3175	/* The different sensor ICs handle setting up of window differently.
3176	 * IF YOU SET IT WRONG, YOU WILL GET ALL ZERO ISOC DATA FROM OV51x!!! */
3177	switch (ov->sensor) {
3178	case SEN_OV8610:
3179		hwsbase = 0x1e;
3180		hwebase = 0x1e;
3181		vwsbase = 0x02;
3182		vwebase = 0x02;
3183		break;
3184	case SEN_OV7610:
3185	case SEN_OV76BE:
3186		hwsbase = 0x38;
3187		hwebase = 0x3a;
3188		vwsbase = vwebase = 0x05;
3189		break;
3190	case SEN_OV6620:
3191	case SEN_OV6630:
3192		hwsbase = 0x38;
3193		hwebase = 0x3a;
3194		vwsbase = 0x05;
3195		vwebase = 0x06;
3196		break;
3197	case SEN_OV7620:
3198		hwsbase = 0x2f;		/* From 7620.SET (spec is wrong) */
3199		hwebase = 0x2f;
3200		vwsbase = vwebase = 0x05;
3201		break;
3202	case SEN_OV7640:
3203		hwsbase = 0x1a;
3204		hwebase = 0x1a;
3205		vwsbase = vwebase = 0x03;
3206		break;
3207	default:
3208		return -EINVAL;
3209	}
3210
3211	switch (ov->sensor) {
3212		case SEN_OV6620:
3213		case SEN_OV6630:
3214			if (win->quarter) {	/* QCIF */
3215				hwscale = 0;
3216				vwscale = 0;
3217			} else {		/* CIF */
3218				hwscale = 1;
3219				vwscale = 1;  /* The datasheet says 0; it's wrong */
3220			}
3221			break;
3222		case SEN_OV8610:
3223			if (win->quarter) {	/* QSVGA */
3224				hwscale = 1;
3225				vwscale = 1;
3226			} else {		/* SVGA */
3227				hwscale = 2;
3228				vwscale = 2;
3229			}
3230			break;
3231		default: //SEN_OV7xx0
3232			if (win->quarter) {	/* QVGA */
3233				hwscale = 1;
3234				vwscale = 0;
3235			} else {		/* VGA */
3236				hwscale = 2;
3237				vwscale = 1;
3238			}
3239	}
3240
3241	ret = mode_init_ov_sensor_regs(ov, win);
3242	if (ret < 0)
3243		return ret;
3244
3245	if (ov->sensor == SEN_OV8610) {
3246		i2c_w_mask(ov, 0x2d, 0x05, 0x40);  /* old 0x95, new 0x05 from windrv 090403 *//* bits 5-7: reserved */
3247		i2c_w_mask(ov, 0x28, 0x20, 0x20); /* bit 5: progressive mode on */
3248	}
3249
3250	i2c_w(ov, 0x17, hwsbase + (win->x >> hwscale));
3251	i2c_w(ov, 0x18, hwebase + ((win->x + win->width) >> hwscale));
3252	i2c_w(ov, 0x19, vwsbase + (win->y >> vwscale));
3253	i2c_w(ov, 0x1a, vwebase + ((win->y + win->height) >> vwscale));
3254
3255#ifdef OV511_DEBUG
3256	if (dump_sensor)
3257		dump_i2c_regs(ov);
3258#endif
3259
3260	return 0;
3261}
3262
3263static int
3264ov_sensor_mode_setup(struct usb_ov511 *ov,
3265		     int width, int height, int mode, int sub_flag)
3266{
3267	struct ovsensor_window win;
3268	int half_w = ov->maxwidth / 2;
3269	int half_h = ov->maxheight / 2;
3270
3271	win.format = mode;
3272
3273	/* Unless subcapture is enabled, center the image window and downsample
3274	 * if possible to increase the field of view */
3275	if (sub_flag) {
3276		win.x = ov->subx;
3277		win.y = ov->suby;
3278		win.width = ov->subw;
3279		win.height = ov->subh;
3280		win.quarter = 0;
3281	} else {
3282		/* NOTE: OV518(+) and OV519 does downsampling on its own */
3283		if ((width > half_w && height > half_h)
3284		    || (ov->bclass == BCL_OV518)
3285			|| (ov->bclass == BCL_OV519)) {
3286			win.width = ov->maxwidth;
3287			win.height = ov->maxheight;
3288			win.quarter = 0;
3289		} else if (width > half_w || height > half_h) {
3290			err("Illegal dimensions");
3291			return -EINVAL;
3292		} else {
3293			win.width = half_w;
3294			win.height = half_h;
3295			win.quarter = 1;
3296		}
3297
3298		/* Center it */
3299		win.x = (win.width - width) / 2;
3300		win.y = (win.height - height) / 2;
3301	}
3302
3303	if (clockdiv >= 0) {
3304		/* Manual override */
3305		win.clockdiv = clockdiv;
3306	} else if (ov->bridge == BRG_OV518) {
3307		/* OV518 controls the clock externally */
3308		win.clockdiv = 0;
3309	} else if (ov->bridge == BRG_OV518PLUS) {
3310		/* OV518+ controls the clock externally */
3311		win.clockdiv = 1;
3312	} else if (ov->bridge == BRG_OV519) {
3313		/* Clock is determined by OV519 frame rate code */
3314		win.clockdiv = ov->clockdiv;
3315	} else if (ov->compress) {
3316		/* Use the highest possible rate, to maximize FPS */
3317		switch (ov->sensor) {
3318		case SEN_OV6620:
3319			/* ...except with this sensor, which doesn't like
3320			 * higher rates yet */
3321			win.clockdiv = 3;
3322			break;
3323		case SEN_OV6630:
3324			win.clockdiv = 0;
3325			break;
3326		case SEN_OV76BE:
3327		case SEN_OV7610:
3328		case SEN_OV7620:
3329			win.clockdiv = 1;
3330			break;
3331		case SEN_OV8610:
3332			win.clockdiv = 0;
3333			break;
3334		default:
3335			err("Invalid sensor");
3336			return -EINVAL;
3337		}
3338	} else {
3339		switch (ov->sensor) {
3340		case SEN_OV6620:
3341		case SEN_OV6630:
3342			win.clockdiv = 3;
3343			break;
3344		case SEN_OV76BE:
3345		case SEN_OV7610:
3346		case SEN_OV7620:
3347			/* Use slowest possible clock without sacrificing
3348			 * frame rate */
3349			win.clockdiv = ((sub_flag ? ov->subw * ov->subh
3350			      : width * height)
3351			     * (win.format == VIDEO_PALETTE_GREY ? 2 : 3) / 2)
3352			    / 66000;
3353			break;
3354		default:
3355			err("Invalid sensor");
3356			return -EINVAL;
3357		}
3358	}
3359
3360	PDEBUG(4, "Setting clock divider to %d", win.clockdiv);
3361
3362	return set_ov_sensor_window(ov, &win);
3363}
3364
3365/* Set up the OV511/OV511+ with the given image parameters.
3366 *
3367 * Do not put any sensor-specific code in here (including I2C I/O functions)
3368 */
3369static int
3370ov511_mode_init_regs(struct usb_ov511 *ov,
3371		     int width, int height, int mode, int sub_flag)
3372{
3373	int hsegs, vsegs;
3374
3375	if (sub_flag) {
3376		width = ov->subw;
3377		height = ov->subh;
3378	}
3379
3380	PDEBUG(3, "width:%d, height:%d, mode:%d, sub:%d",
3381	       width, height, mode, sub_flag);
3382
3383	// FIXME: This should be moved to a 7111a-specific function once
3384	// subcapture is dealt with properly
3385	if (ov->sensor == SEN_SAA7111A) {
3386		if (width == 320 && height == 240) {
3387			/* No need to do anything special */
3388		} else if (width == 640 && height == 480) {
3389			/* Set the OV511 up as 320x480, but keep the
3390			 * V4L resolution as 640x480 */
3391			width = 320;
3392		} else {
3393			err("SAA7111A only allows 320x240 or 640x480");
3394			return -EINVAL;
3395		}
3396	}
3397
3398	/* Make sure width and height are a multiple of 8 */
3399	if (width % 8 || height % 8) {
3400		err("Invalid size (%d, %d) (mode = %d)", width, height, mode);
3401		return -EINVAL;
3402	}
3403
3404	if (width < ov->minwidth || height < ov->minheight) {
3405		err("Requested dimensions are too small");
3406		return -EINVAL;
3407	}
3408
3409	if (ov51x_stop(ov) < 0)
3410		return -EIO;
3411
3412	if (mode == VIDEO_PALETTE_GREY) {
3413		reg_w(ov, R511_CAM_UV_EN, 0x00);
3414		reg_w(ov, R511_SNAP_UV_EN, 0x00);
3415		reg_w(ov, R511_SNAP_OPTS, 0x01);
3416	} else {
3417		reg_w(ov, R511_CAM_UV_EN, 0x01);
3418		reg_w(ov, R511_SNAP_UV_EN, 0x01);
3419		reg_w(ov, R511_SNAP_OPTS, 0x03);
3420	}
3421
3422	/* Here I'm assuming that snapshot size == image size.
3423	 * I hope that's always true. --claudio
3424	 */
3425	hsegs = (width >> 3) - 1;
3426	vsegs = (height >> 3) - 1;
3427
3428	reg_w(ov, R511_CAM_PXCNT, hsegs);
3429	reg_w(ov, R511_CAM_LNCNT, vsegs);
3430	reg_w(ov, R511_CAM_PXDIV, 0x00);
3431	reg_w(ov, R511_CAM_LNDIV, 0x00);
3432
3433	/* YUV420, low pass filter on */
3434	reg_w(ov, R511_CAM_OPTS, 0x03);
3435
3436	/* Snapshot additions */
3437	reg_w(ov, R511_SNAP_PXCNT, hsegs);
3438	reg_w(ov, R511_SNAP_LNCNT, vsegs);
3439	reg_w(ov, R511_SNAP_PXDIV, 0x00);
3440	reg_w(ov, R511_SNAP_LNDIV, 0x00);
3441
3442	if (ov->compress) {
3443		/* Enable Y and UV quantization and compression */
3444		reg_w(ov, R511_COMP_EN, 0x07);
3445		reg_w(ov, R511_COMP_LUT_EN, 0x03);
3446		ov51x_reset(ov, OV511_RESET_OMNICE);
3447	}
3448
3449	if (ov51x_restart(ov) < 0)
3450		return -EIO;
3451
3452	return 0;
3453}
3454
3455/* Sets up the OV518/OV518+ with the given image parameters
3456 *
3457 * OV518 needs a completely different approach, until we can figure out what
3458 * the individual registers do. Also, only 15 FPS is supported now.
3459 *
3460 * Do not put any sensor-specific code in here (including I2C I/O functions)
3461 */
3462static int
3463ov518_mode_init_regs(struct usb_ov511 *ov,
3464		     int width, int height, int mode, int sub_flag)
3465{
3466	int hsegs, vsegs, hi_res;
3467
3468	if (sub_flag) {
3469		width = ov->subw;
3470		height = ov->subh;
3471	}
3472
3473	PDEBUG(3, "width:%d, height:%d, mode:%d, sub:%d",
3474	       width, height, mode, sub_flag);
3475
3476	if (width % 16 || height % 8) {
3477		err("Invalid size (%d, %d)", width, height);
3478		return -EINVAL;
3479	}
3480
3481	if (width < ov->minwidth || height < ov->minheight) {
3482		err("Requested dimensions are too small");
3483		return -EINVAL;
3484	}
3485
3486	if (width >= 320 && height >= 240) {
3487		hi_res = 1;
3488	} else if (width >= 320 || height >= 240) {
3489		err("Invalid width/height combination (%d, %d)", width, height);
3490		return -EINVAL;
3491	} else {
3492		hi_res = 0;
3493	}
3494
3495	if (ov51x_stop(ov) < 0)
3496		return -EIO;
3497
3498	/******** Set the mode ********/
3499
3500	reg_w(ov, 0x2b, 0);
3501	reg_w(ov, 0x2c, 0);
3502	reg_w(ov, 0x2d, 0);
3503	reg_w(ov, 0x2e, 0);
3504	reg_w(ov, 0x3b, 0);
3505	reg_w(ov, 0x3c, 0);
3506	reg_w(ov, 0x3d, 0);
3507	reg_w(ov, 0x3e, 0);
3508
3509	if (ov->bridge == BRG_OV518 && ov518_color) {
3510	 	if (mode == VIDEO_PALETTE_GREY) {
3511			/* Set 16-bit input format (UV data are ignored) */
3512			reg_w_mask(ov, 0x20, 0x00, 0x08);
3513
3514			/* Set 8-bit (4:0:0) output format */
3515			reg_w_mask(ov, 0x28, 0x00, 0xf0);
3516			reg_w_mask(ov, 0x38, 0x00, 0xf0);
3517		} else {
3518			/* Set 8-bit (YVYU) input format */
3519			reg_w_mask(ov, 0x20, 0x08, 0x08);
3520
3521			/* Set 12-bit (4:2:0) output format */
3522			reg_w_mask(ov, 0x28, 0x80, 0xf0);
3523			reg_w_mask(ov, 0x38, 0x80, 0xf0);
3524		}
3525	} else {
3526		reg_w(ov, 0x28, (mode == VIDEO_PALETTE_GREY) ? 0x00:0x80);
3527		reg_w(ov, 0x38, (mode == VIDEO_PALETTE_GREY) ? 0x00:0x80);
3528	}
3529
3530	hsegs = width / 16;
3531	vsegs = height / 4;
3532
3533	reg_w(ov, 0x29, hsegs);
3534	reg_w(ov, 0x2a, vsegs);
3535
3536	reg_w(ov, 0x39, hsegs);
3537	reg_w(ov, 0x3a, vsegs);
3538
3539	/* Windows driver does this here; who knows why */
3540	reg_w(ov, 0x2f, 0x80);
3541
3542	/******** Set the framerate (to 30 FPS) ********/
3543
3544	/* Mode independent, but framerate dependent, regs */
3545	reg_w(ov, 0x51, 0x04);	/* Clock divider; lower==faster */
3546	reg_w(ov, 0x22, 0x18);
3547	reg_w(ov, 0x23, 0xff);
3548
3549	if (ov->bridge == BRG_OV518PLUS)
3550		reg_w(ov, 0x21, 0x19);
3551	else
3552		reg_w(ov, 0x71, 0x17);	/* Compression-related? */
3553
3554	// FIXME: Sensor-specific
3555	/* Bit 5 is what matters here. Of course, it is "reserved" */
3556	i2c_w(ov, 0x54, 0x23);
3557
3558	reg_w(ov, 0x2f, 0x80);
3559
3560	if (ov->bridge == BRG_OV518PLUS) {
3561		reg_w(ov, 0x24, 0x94);
3562		reg_w(ov, 0x25, 0x90);
3563		ov518_reg_w32(ov, 0xc4,    400, 2);	/* 190h   */
3564		ov518_reg_w32(ov, 0xc6,    540, 2);	/* 21ch   */
3565		ov518_reg_w32(ov, 0xc7,    540, 2);	/* 21ch   */
3566		ov518_reg_w32(ov, 0xc8,    108, 2);	/* 6ch    */
3567		ov518_reg_w32(ov, 0xca, 131098, 3);	/* 2001ah */
3568		ov518_reg_w32(ov, 0xcb,    532, 2);	/* 214h   */
3569		ov518_reg_w32(ov, 0xcc,   2400, 2);	/* 960h   */
3570		ov518_reg_w32(ov, 0xcd,     32, 2);	/* 20h    */
3571		ov518_reg_w32(ov, 0xce,    608, 2);	/* 260h   */
3572	} else {
3573		reg_w(ov, 0x24, 0x9f);
3574		reg_w(ov, 0x25, 0x90);
3575		ov518_reg_w32(ov, 0xc4,    400, 2);	/* 190h   */
3576		ov518_reg_w32(ov, 0xc6,    381, 2);	/* 17dh   */
3577		ov518_reg_w32(ov, 0xc7,    381, 2);	/* 17dh   */
3578		ov518_reg_w32(ov, 0xc8,    128, 2);	/* 80h    */
3579		ov518_reg_w32(ov, 0xca, 183331, 3);	/* 2cc23h */
3580		ov518_reg_w32(ov, 0xcb,    746, 2);	/* 2eah   */
3581		ov518_reg_w32(ov, 0xcc,   1750, 2);	/* 6d6h   */
3582		ov518_reg_w32(ov, 0xcd,     45, 2);	/* 2dh    */
3583		ov518_reg_w32(ov, 0xce,    851, 2);	/* 353h   */
3584	}
3585
3586	reg_w(ov, 0x2f, 0x80);
3587
3588	if (ov51x_restart(ov) < 0)
3589		return -EIO;
3590
3591	/* Reset it just for good measure */
3592	if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
3593		return -EIO;
3594
3595	return 0;
3596}
3597
3598/* Sets up the OV519 with the given image parameters
3599 *
3600 * OV519 needs a completely different approach, until we can figure out what
3601 * the individual registers do.
3602 *
3603 * Do not put any sensor-specific code in here (including I2C I/O functions)
3604 */
3605static int
3606ov519_mode_init_regs(struct usb_ov511 *ov,
3607		     int width, int height, int mode, int sub_flag)
3608{
3609	static struct ov511_regvals regvals_mode_init_519[] = {
3610		{ OV511_REG_BUS, 0x5d,	0x03 }, /* Turn off suspend mode */
3611		{ OV511_REG_BUS, 0x53,	0x9f }, /* was 9b in 1.65-1.08 */
3612		{ OV511_REG_BUS, 0x54,	0x0f }, /* bit2 (jpeg enable) */
3613		{ OV511_REG_BUS, 0xa2,	0x20 }, /* a2-a5 are undocumented */
3614		{ OV511_REG_BUS, 0xa3,	0x18 },
3615		{ OV511_REG_BUS, 0xa4,	0x04 },
3616		{ OV511_REG_BUS, 0xa5,	0x28 },
3617		{ OV511_REG_BUS, 0x37,	0x00 },	/* SetUsbInit */
3618		{ OV511_REG_BUS, 0x55,	0x02 }, /* 4.096 Mhz audio clock */
3619		/* Enable both fields, YUV Input, disable defect comp (why?) */
3620		{ OV511_REG_BUS, 0x22,	0x1d },
3621		{ OV511_REG_BUS, 0x17,	0x50 }, /* undocumented */
3622		{ OV511_REG_BUS, 0x37,	0x00 }, /* undocumented */
3623		{ OV511_REG_BUS, 0x40,	0xff }, /* I2C timeout counter */
3624		{ OV511_REG_BUS, 0x46,	0x00 }, /* I2C clock prescaler */
3625		{ OV511_REG_BUS, 0x59,	0x04 },	/* new from windrv 090403 */
3626		{ OV511_REG_BUS, 0xff,	0x00 }, /* undocumented */
3627		/* windows reads 0x55 at this point, why? */
3628		{ OV511_DONE_BUS, 0x0, 0x00},
3629	};
3630
3631//	int hi_res;
3632
3633	if (sub_flag) {
3634		width = ov->subw;
3635		height = ov->subh;
3636	}
3637
3638	PDEBUG(3, "width:%d, height:%d, mode:%d, sub:%d",
3639	       width, height, mode, sub_flag);
3640
3641	if ((width % 16) || (height % 8)) {
3642		err("Invalid size (%d, %d)", width, height);
3643		return -EINVAL;
3644	}
3645
3646	if (width < ov->minwidth || height < ov->minheight) {
3647		err("Requested dimensions are too small %dx%d", width, height);
3648		return -EINVAL;
3649	}
3650
3651//	if (width >= 800 && height >= 600) {
3652//		hi_res = 1;
3653//	} else
3654	if (width > ov->maxwidth || height > ov->maxheight) {
3655		err("Requested dimensions are too big %dx%d", width, height);
3656		return -EINVAL;
3657	}
3658//	 else {
3659//		hi_res = 0;
3660//	}
3661
3662	if (ov51x_stop(ov) < 0)
3663		return -EIO;
3664
3665	/******** Set the mode ********/
3666
3667	if (write_regvals(ov, regvals_mode_init_519))
3668		return -EIO;
3669
3670	if (ov->sensor == SEN_OV7640) {
3671		/* Select 8-bit input mode */
3672		reg_w_mask(ov, OV519_CAM_DFR, 0x10, 0x10);
3673	}
3674
3675	reg_w(ov, OV519_CAM_H_SIZE,	width>>4);
3676	reg_w(ov, OV519_CAM_V_SIZE,	height>>3);
3677	reg_w(ov, OV519_CAM_X_OFFSETL,	0x00);
3678	reg_w(ov, OV519_CAM_X_OFFSETH,	0x00);
3679	reg_w(ov, OV519_CAM_Y_OFFSETL,	0x00);
3680	reg_w(ov, OV519_CAM_Y_OFFSETH,	0x00);
3681	reg_w(ov, OV519_CAM_DIVIDER,	0x00);
3682	reg_w(ov, OV519_CAM_FORMAT,	0x03); /* YUV422 */
3683	reg_w(ov, 0x26,			0x00); /* Undocumented */
3684
3685
3686	/******** Set the framerate ********/
3687	if (framerate > 0) {
3688		ov->framerate = framerate;
3689	}
3690
3691// FIXME: These are only valid at the max resolution.
3692	if (ov->sensor == SEN_OV7640) {
3693		switch (ov->framerate) {
3694		case 30:
3695			reg_w(ov, 0xa4, 0x0c);
3696			reg_w(ov, 0x23, 0xff);
3697			ov->clockdiv = 0;
3698			break;
3699		case 25:
3700			reg_w(ov, 0xa4, 0x0c);
3701			reg_w(ov, 0x23, 0x1f);
3702			ov->clockdiv = 0;
3703			break;
3704		case 20:
3705			reg_w(ov, 0xa4, 0x0c);
3706			reg_w(ov, 0x23, 0x1b);
3707			ov->clockdiv = 0;
3708			break;
3709		case 15:
3710			reg_w(ov, 0xa4, 0x04);
3711			reg_w(ov, 0x23, 0xff);
3712			ov->clockdiv = 1;
3713			break;
3714		case 10:
3715			reg_w(ov, 0xa4, 0x04);
3716			reg_w(ov, 0x23, 0x1f);
3717			ov->clockdiv = 1;
3718			break;
3719		case 5:
3720			reg_w(ov, 0xa4, 0x04);
3721			reg_w(ov, 0x23, 0x1b);
3722			ov->clockdiv = 1;
3723			break;
3724		default:	// 30 fps
3725			reg_w(ov, 0xa4, 0x0c);
3726			reg_w(ov, 0x23, 0xff);
3727			ov->clockdiv = 0;
3728		}
3729	} else if (ov->sensor == SEN_OV8610) {
3730		switch (ov->framerate) {
3731		case 15:
3732			reg_w(ov, 0xa4, 0x06);
3733			reg_w(ov, 0x23, 0xff);
3734			break;
3735		case 10:
3736			reg_w(ov, 0xa4, 0x06);
3737			reg_w(ov, 0x23, 0x1f);
3738			break;
3739		case 5:
3740			reg_w(ov, 0xa4, 0x06);
3741			reg_w(ov, 0x23, 0x1b);
3742			break;
3743		default:	// 15 fps
3744			reg_w(ov, 0xa4, 0x06);
3745			reg_w(ov, 0x23, 0xff);
3746		}
3747
3748		ov->clockdiv = 0;
3749	} else {
3750		err("Sensor not supported for OV519!");
3751		return -EINVAL;
3752	}
3753
3754	if (ov51x_restart(ov) < 0)
3755		return -EIO;
3756
3757	/* Reset it just for good measure */
3758	if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
3759		return -EIO;
3760
3761	return 0;
3762}
3763
3764/* This is a wrapper around the OV511, OV518, and sensor specific functions */
3765static int
3766mode_init_regs(struct usb_ov511 *ov,
3767	       int width, int height, int mode, int sub_flag)
3768{
3769	int rc = 0;
3770
3771	if (!ov || !ov->dev)
3772		return -EFAULT;
3773
3774	switch (ov->bclass) {
3775		case BCL_OV511:
3776			rc = ov511_mode_init_regs(ov, width, height, mode, sub_flag);
3777			break;
3778		case BCL_OV518:
3779			rc = ov518_mode_init_regs(ov, width, height, mode, sub_flag);
3780			break;
3781		case BCL_OV519:
3782			rc = ov519_mode_init_regs(ov, width, height, mode, sub_flag);
3783			break;
3784		default:
3785			err("mode_init_regs: Invalid bridge class");
3786			rc = -EINVAL;
3787	}
3788
3789	if (FATAL_ERROR(rc))
3790		return rc;
3791
3792	switch (ov->sensor) {
3793		case SEN_OV8610:
3794		case SEN_OV7610:
3795		case SEN_OV7620:
3796		case SEN_OV76BE:
3797		case SEN_OV7640:
3798		case SEN_OV8600:
3799		case SEN_OV6620:
3800		case SEN_OV6630:
3801			rc = ov_sensor_mode_setup(ov, width, height, mode, sub_flag);
3802			break;
3803
3804		case SEN_SAA7111A:
3805//			rc = mode_init_saa_sensor_regs(ov, width, height, mode,
3806//				       sub_flag);
3807
3808			PDEBUG(1, "SAA status = 0x%02X", i2c_r(ov, 0x1f));
3809			break;
3810		default:
3811			rc = -EINVAL;
3812	}
3813
3814	if (FATAL_ERROR(rc))
3815		return rc;
3816
3817	/* Sensor-independent settings */
3818	rc = sensor_set_auto_brightness(ov, ov->auto_brt);
3819	if (FATAL_ERROR(rc))
3820		return rc;
3821
3822	rc = sensor_set_auto_exposure(ov, ov->auto_exp);
3823	if (FATAL_ERROR(rc))
3824		return rc;
3825
3826	rc = sensor_set_auto_gain(ov, ov->auto_gain);
3827	if (FATAL_ERROR(rc))
3828		return rc;
3829
3830	rc = sensor_set_banding_filter(ov, bandingfilter);
3831	if (FATAL_ERROR(rc))
3832		return rc;
3833
3834	if (ov->lightfreq) {
3835		rc = sensor_set_light_freq(ov, lightfreq);
3836		if (FATAL_ERROR(rc))
3837			return rc;
3838	}
3839
3840	rc = sensor_set_backlight(ov, ov->backlight);
3841	if (FATAL_ERROR(rc))
3842		return rc;
3843
3844	rc = sensor_set_mirror(ov, ov->mirror);
3845	if (FATAL_ERROR(rc))
3846		return rc;
3847
3848	return 0;
3849}
3850
3851/* This sets the default image parameters. This is useful for apps that use
3852 * read() and do not set these.
3853 */
3854static int
3855ov51x_set_default_params(struct usb_ov511 *ov)
3856{
3857	int i;
3858
3859	/* Set default sizes in case IOCTL (VIDIOCMCAPTURE) is not used
3860	 * (using read() instead). */
3861	for (i = 0; i < OV511_NUMFRAMES; i++) {
3862		ov->frame[i].width = ov->maxwidth;
3863		ov->frame[i].height = ov->maxheight;
3864		ov->frame[i].bytes_read = 0;
3865		if (force_palette)
3866			ov->frame[i].format = force_palette;
3867		else
3868#ifdef OV511_ALLOW_CONVERSION
3869			ov->frame[i].format = VIDEO_PALETTE_RGB24;
3870#else
3871			ov->frame[i].format = VIDEO_PALETTE_YUV420;
3872#endif
3873		ov->frame[i].depth = get_depth(ov->frame[i].format);
3874	}
3875
3876	PDEBUG(3, "%dx%d, %s", ov->maxwidth, ov->maxheight,
3877	       symbolic(v4l1_plist, ov->frame[0].format));
3878
3879	/* Initialize to max width/height, YUV420 or RGB24 (if supported) */
3880	if (mode_init_regs(ov, ov->maxwidth, ov->maxheight,
3881			   ov->frame[0].format, 0) < 0)
3882		return -EINVAL;
3883
3884	return 0;
3885}
3886
3887/**********************************************************************
3888 *
3889 * Video decoder stuff
3890 *
3891 **********************************************************************/
3892
3893/* Set analog input port of decoder */
3894static int
3895decoder_set_input(struct usb_ov511 *ov, int input)
3896{
3897	PDEBUG(4, "port %d", input);
3898
3899	switch (ov->sensor) {
3900	case SEN_SAA7111A:
3901	{
3902		/* Select mode */
3903		i2c_w_mask(ov, 0x02, input, 0x07);
3904		/* Bypass chrominance trap for modes 4..7 */
3905		i2c_w_mask(ov, 0x09, (input > 3) ? 0x80:0x00, 0x80);
3906		break;
3907	}
3908	default:
3909		return -EINVAL;
3910	}
3911
3912	return 0;
3913}
3914
3915/* Get ASCII name of video input */
3916static int
3917decoder_get_input_name(struct usb_ov511 *ov, int input, char *name)
3918{
3919	switch (ov->sensor) {
3920	case SEN_SAA7111A:
3921	{
3922		if (input < 0 || input > 7)
3923			return -EINVAL;
3924		else if (input < 4)
3925			sprintf(name, "CVBS-%d", input);
3926		else // if (input < 8)
3927			sprintf(name, "S-Video-%d", input - 4);
3928		break;
3929	}
3930	default:
3931		sprintf(name, "%s", "Camera");
3932	}
3933
3934	return 0;
3935}
3936
3937/* Set norm (NTSC, PAL, SECAM, AUTO) */
3938static int
3939decoder_set_norm(struct usb_ov511 *ov, int norm)
3940{
3941	PDEBUG(4, "%d", norm);
3942
3943	switch (ov->sensor) {
3944	case SEN_SAA7111A:
3945	{
3946		int reg_8, reg_e;
3947
3948		if (norm == VIDEO_MODE_NTSC) {
3949			reg_8 = 0x40;	/* 60 Hz */
3950			reg_e = 0x00;	/* NTSC M / PAL BGHI */
3951		} else if (norm == VIDEO_MODE_PAL) {
3952			reg_8 = 0x00;	/* 50 Hz */
3953			reg_e = 0x00;	/* NTSC M / PAL BGHI */
3954		} else if (norm == VIDEO_MODE_AUTO) {
3955			reg_8 = 0x80;	/* Auto field detect */
3956			reg_e = 0x00;	/* NTSC M / PAL BGHI */
3957		} else if (norm == VIDEO_MODE_SECAM) {
3958			reg_8 = 0x00;	/* 50 Hz */
3959			reg_e = 0x50;	/* SECAM / PAL 4.43 */
3960		} else {
3961			return -EINVAL;
3962		}
3963
3964		i2c_w_mask(ov, 0x08, reg_8, 0xc0);
3965		i2c_w_mask(ov, 0x0e, reg_e, 0x70);
3966		break;
3967	}
3968	default:
3969		return -EINVAL;
3970	}
3971
3972	return 0;
3973}
3974
3975#ifdef OV511_ALLOW_CONVERSION
3976/**********************************************************************
3977 *
3978 * Color correction functions
3979 *
3980 **********************************************************************/
3981
3982/*
3983 * Turn a YUV4:2:0 block into an RGB block
3984 *
3985 * Video4Linux seems to use the blue, green, red channel
3986 * order convention-- rgb[0] is blue, rgb[1] is green, rgb[2] is red.
3987 *
3988 * Color space conversion coefficients taken from the excellent
3989 * http://www.inforamp.net/~poynton/ColorFAQ.html
3990 * In his terminology, this is a CCIR 601.1 YCbCr -> RGB.
3991 * Y values are given for all 4 pixels, but the U (Pb)
3992 * and V (Pr) are assumed constant over the 2x2 block.
3993 *
3994 * To avoid floating point arithmetic, the color conversion
3995 * coefficients are scaled into 16.16 fixed-point integers.
3996 * They were determined as follows:
3997 *
3998 *	double brightness = 1.0;  (0->black; 1->full scale)
3999 *	double saturation = 1.0;  (0->greyscale; 1->full color)
4000 *	double fixScale = brightness * 256 * 256;
4001 *	int rvScale = (int)(1.402 * saturation * fixScale);
4002 *	int guScale = (int)(-0.344136 * saturation * fixScale);
4003 *	int gvScale = (int)(-0.714136 * saturation * fixScale);
4004 *	int buScale = (int)(1.772 * saturation * fixScale);
4005 *	int yScale = (int)(fixScale);
4006 */
4007
4008/* LIMIT: convert a 16.16 fixed-point value to a byte, with clipping. */
4009#define LIMIT(x) ((x)>0xffffff?0xff: ((x)<=0xffff?0:((x)>>16)))
4010
4011static inline void
4012move_420_block(int yTL, int yTR, int yBL, int yBR, int u, int v,
4013	       int rowPixels, unsigned char * rgb, int bits)
4014{
4015	const int rvScale = 91881;
4016	const int guScale = -22553;
4017	const int gvScale = -46801;
4018	const int buScale = 116129;
4019	const int yScale  = 65536;
4020	int r, g, b;
4021
4022	g = guScale * u + gvScale * v;
4023	if (force_rgb) {
4024		r = buScale * u;
4025		b = rvScale * v;
4026	} else {
4027		r = rvScale * v;
4028		b = buScale * u;
4029	}
4030
4031	yTL *= yScale; yTR *= yScale;
4032	yBL *= yScale; yBR *= yScale;
4033
4034	if (bits == 24) {
4035		/* Write out top two pixels */
4036		rgb[0] = LIMIT(b+yTL); rgb[1] = LIMIT(g+yTL);
4037		rgb[2] = LIMIT(r+yTL);
4038
4039		rgb[3] = LIMIT(b+yTR); rgb[4] = LIMIT(g+yTR);
4040		rgb[5] = LIMIT(r+yTR);
4041
4042		/* Skip down to next line to write out bottom two pixels */
4043		rgb += 3 * rowPixels;
4044		rgb[0] = LIMIT(b+yBL); rgb[1] = LIMIT(g+yBL);
4045		rgb[2] = LIMIT(r+yBL);
4046
4047		rgb[3] = LIMIT(b+yBR); rgb[4] = LIMIT(g+yBR);
4048		rgb[5] = LIMIT(r+yBR);
4049	} else if (bits == 16) {
4050		/* Write out top two pixels */
4051		rgb[0] = ((LIMIT(b+yTL) >> 3) & 0x1F)
4052			| ((LIMIT(g+yTL) << 3) & 0xE0);
4053		rgb[1] = ((LIMIT(g+yTL) >> 5) & 0x07)
4054			| (LIMIT(r+yTL) & 0xF8);
4055
4056		rgb[2] = ((LIMIT(b+yTR) >> 3) & 0x1F)
4057			| ((LIMIT(g+yTR) << 3) & 0xE0);
4058		rgb[3] = ((LIMIT(g+yTR) >> 5) & 0x07)
4059			| (LIMIT(r+yTR) & 0xF8);
4060
4061		/* Skip down to next line to write out bottom two pixels */
4062		rgb += 2 * rowPixels;
4063
4064		rgb[0] = ((LIMIT(b+yBL) >> 3) & 0x1F)
4065			| ((LIMIT(g+yBL) << 3) & 0xE0);
4066		rgb[1] = ((LIMIT(g+yBL) >> 5) & 0x07)
4067			| (LIMIT(r+yBL) & 0xF8);
4068
4069		rgb[2] = ((LIMIT(b+yBR) >> 3) & 0x1F)
4070			| ((LIMIT(g+yBR) << 3) & 0xE0);
4071		rgb[3] = ((LIMIT(g+yBR) >> 5) & 0x07)
4072			| (LIMIT(r+yBR) & 0xF8);
4073	}
4074}
4075
4076#endif	/* OV511_ALLOW_CONVERSION */
4077
4078/**********************************************************************
4079 *
4080 * Raw data parsing
4081 *
4082 **********************************************************************/
4083
4084/* Copies a 64-byte segment at pIn to an 8x8 block at pOut. The width of the
4085 * image at pOut is specified by w.
4086 */
4087static inline void
4088make_8x8(unsigned char *pIn, unsigned char *pOut, int w)
4089{
4090	unsigned char *pOut1 = pOut;
4091	int x, y;
4092
4093	for (y = 0; y < 8; y++) {
4094		pOut1 = pOut;
4095		for (x = 0; x < 8; x++) {
4096			*pOut1++ = *pIn++;
4097		}
4098		pOut += w;
4099	}
4100}
4101
4102/*
4103 * For RAW BW (YUV 4:0:0) images, data show up in 256 byte segments.
4104 * The segments represent 4 squares of 8x8 pixels as follows:
4105 *
4106 *      0  1 ...  7    64  65 ...  71   ...  192 193 ... 199
4107 *      8  9 ... 15    72  73 ...  79        200 201 ... 207
4108 *           ...              ...                    ...
4109 *     56 57 ... 63   120 121 ... 127        248 249 ... 255
4110 *
4111 */
4112static void
4113yuv400raw_to_yuv400p(struct ov511_frame *frame,
4114		     unsigned char *pIn0, unsigned char *pOut0)
4115{
4116	int x, y;
4117	unsigned char *pIn, *pOut, *pOutLine;
4118
4119	/* Copy Y */
4120	pIn = pIn0;
4121	pOutLine = pOut0;
4122	for (y = 0; y < frame->rawheight - 1; y += 8) {
4123		pOut = pOutLine;
4124		for (x = 0; x < frame->rawwidth - 1; x += 8) {
4125			make_8x8(pIn, pOut, frame->rawwidth);
4126			pIn += 64;
4127			pOut += 8;
4128		}
4129		pOutLine += 8 * frame->rawwidth;
4130	}
4131}
4132
4133/*
4134 * For YUV 4:2:0 images, the data show up in 384 byte segments.
4135 * The first 64 bytes of each segment are U, the next 64 are V.  The U and
4136 * V are arranged as follows:
4137 *
4138 *      0  1 ...  7
4139 *      8  9 ... 15
4140 *           ...
4141 *     56 57 ... 63
4142 *
4143 * U and V are shipped at half resolution (1 U,V sample -> one 2x2 block).
4144 *
4145 * The next 256 bytes are full resolution Y data and represent 4 squares
4146 * of 8x8 pixels as follows:
4147 *
4148 *      0  1 ...  7    64  65 ...  71   ...  192 193 ... 199
4149 *      8  9 ... 15    72  73 ...  79        200 201 ... 207
4150 *           ...              ...                    ...
4151 *     56 57 ... 63   120 121 ... 127   ...  248 249 ... 255
4152 *
4153 * Note that the U and V data in one segment represent a 16 x 16 pixel
4154 * area, but the Y data represent a 32 x 8 pixel area. If the width is not an
4155 * even multiple of 32, the extra 8x8 blocks within a 32x8 block belong to the
4156 * next horizontal stripe.
4157 *
4158 * If dumppix module param is set, _parse_data just dumps the incoming segments,
4159 * verbatim, in order, into the frame. When used with vidcat -f ppm -s 640x480
4160 * this puts the data on the standard output and can be analyzed with the
4161 * parseppm.c utility I wrote.  That's a much faster way for figuring out how
4162 * these data are scrambled.
4163 */
4164
4165/* Converts from raw, uncompressed segments at pIn0 to a YUV420P frame at pOut0.
4166 *
4167 * FIXME: Currently only handles width and height that are multiples of 16
4168 */
4169static void
4170yuv420raw_to_yuv420p(struct ov511_frame *frame,
4171		     unsigned char *pIn0, unsigned char *pOut0)
4172{
4173	int k, x, y;
4174	unsigned char *pIn, *pOut, *pOutLine;
4175	const unsigned int a = frame->rawwidth * frame->rawheight;
4176	const unsigned int w = frame->rawwidth / 2;
4177
4178	/* Copy U and V */
4179	pIn = pIn0;
4180	pOutLine = pOut0 + a;
4181	for (y = 0; y < frame->rawheight - 1; y += 16) {
4182		pOut = pOutLine;
4183		for (x = 0; x < frame->rawwidth - 1; x += 16) {
4184			make_8x8(pIn, pOut, w);
4185			make_8x8(pIn + 64, pOut + a/4, w);
4186			pIn += 384;
4187			pOut += 8;
4188		}
4189		pOutLine += 8 * w;
4190	}
4191
4192	/* Copy Y */
4193	pIn = pIn0 + 128;
4194	pOutLine = pOut0;
4195	k = 0;
4196	for (y = 0; y < frame->rawheight - 1; y += 8) {
4197		pOut = pOutLine;
4198		for (x = 0; x < frame->rawwidth - 1; x += 8) {
4199			make_8x8(pIn, pOut, frame->rawwidth);
4200			pIn += 64;
4201			pOut += 8;
4202			if ((++k) > 3) {
4203				k = 0;
4204				pIn += 128;
4205			}
4206		}
4207		pOutLine += 8 * frame->rawwidth;
4208	}
4209}
4210
4211#ifdef OV511_ALLOW_CONVERSION
4212/*
4213 * fixFrameRGBoffset--
4214 * My camera seems to return the red channel about 1 pixel
4215 * low, and the blue channel about 1 pixel high. After YUV->RGB
4216 * conversion, we can correct this easily. OSL 2/24/2000.
4217 */
4218static void
4219fixFrameRGBoffset(struct ov511_frame *frame)
4220{
4221	int x, y;
4222	int rowBytes = frame->width*3, w = frame->width;
4223	unsigned char *rgb = frame->data;
4224	const int shift = 1;  /* Distance to shift pixels by, vertically */
4225
4226	/* Don't bother with little images */
4227	if (frame->width < 400)
4228		return;
4229
4230	/* This only works with RGB24 */
4231	if (frame->format != VIDEO_PALETTE_RGB24)
4232		return;
4233
4234	/* Shift red channel up */
4235	for (y = shift; y < frame->height; y++)	{
4236		int lp = (y-shift)*rowBytes;     /* Previous line offset */
4237		int lc = y*rowBytes;             /* Current line offset */
4238		for (x = 0; x < w; x++)
4239			rgb[lp+x*3+2] = rgb[lc+x*3+2]; /* Shift red up */
4240	}
4241
4242	/* Shift blue channel down */
4243	for (y = frame->height-shift-1; y >= 0; y--) {
4244		int ln = (y + shift) * rowBytes;  /* Next line offset */
4245		int lc = y * rowBytes;            /* Current line offset */
4246		for (x = 0; x < w; x++)
4247			rgb[ln+x*3+0] = rgb[lc+x*3+0]; /* Shift blue down */
4248	}
4249}
4250#endif
4251
4252/**********************************************************************
4253 *
4254 * Decompression
4255 *
4256 **********************************************************************/
4257
4258/* Chooses a decompression module, locks it, and sets ov->decomp_ops
4259 * accordingly. Returns -ENXIO if decompressor is not available, otherwise
4260 * returns 0 if no other error.
4261 */
4262static int
4263request_decompressor(struct usb_ov511 *ov)
4264{
4265	if (!ov)
4266		return -ENODEV;
4267
4268	if (ov->decomp_ops) {
4269		err("ERROR: Decompressor already requested!");
4270		return -EINVAL;
4271	}
4272
4273	lock_kernel();
4274
4275	/* Try to get MMX, and fall back on no-MMX if necessary */
4276	if (ov->bclass == BCL_OV511) {
4277		if (ov511_mmx_decomp_ops) {
4278			PDEBUG(3, "Using OV511 MMX decompressor");
4279			ov->decomp_ops = ov511_mmx_decomp_ops;
4280		} else if (ov511_decomp_ops) {
4281			PDEBUG(3, "Using OV511 decompressor");
4282			ov->decomp_ops = ov511_decomp_ops;
4283		} else {
4284			err("No decompressor available");
4285		}
4286	} else if (ov->bclass == BCL_OV518) {
4287		if (ov518_mmx_decomp_ops) {
4288			PDEBUG(3, "Using OV518 MMX decompressor");
4289			ov->decomp_ops = ov518_mmx_decomp_ops;
4290		} else if (ov518_decomp_ops) {
4291			PDEBUG(3, "Using OV518 decompressor");
4292			ov->decomp_ops = ov518_decomp_ops;
4293		} else {
4294			err("No decompressor available");
4295		}
4296	} else if (ov->bclass == BCL_OV519) {
4297		info("OV519 doesn't need proprietary decompressor. It uses standard JPEG");
4298	} else {
4299		err("Decompressor: Unknown bridge");
4300	}
4301
4302	if (ov->decomp_ops) {
4303		if (!ov->decomp_ops->owner) {
4304			ov->decomp_ops = NULL;
4305			unlock_kernel();
4306			return -ENOSYS;
4307		}
4308		__MOD_INC_USE_COUNT(ov->decomp_ops->owner);
4309		unlock_kernel();
4310		return 0;
4311	} else {
4312		unlock_kernel();
4313		if (ov->bclass == BCL_OV519)
4314			return 0;
4315		else
4316			return -ENOSYS;
4317	}
4318}
4319
4320/* Unlocks decompression module and nulls ov->decomp_ops. Safe to call even
4321 * if ov->decomp_ops is NULL.
4322 */
4323static void
4324release_decompressor(struct usb_ov511 *ov)
4325{
4326	int released = 0;	/* Did we actually do anything? */
4327
4328	if (!ov)
4329		return;
4330
4331	if (ov->bclass == BCL_OV519) {
4332		ov->compress_inited = 0;
4333		return;
4334	}
4335
4336	lock_kernel();
4337
4338	if (ov->decomp_ops && ov->decomp_ops->owner) {
4339		__MOD_DEC_USE_COUNT(ov->decomp_ops->owner);
4340		released = 1;
4341	}
4342
4343	ov->decomp_ops = NULL;
4344
4345	unlock_kernel();
4346
4347	if (released)
4348		PDEBUG(3, "Decompressor released");
4349}
4350
4351static void
4352decompress(struct usb_ov511 *ov, struct ov511_frame *frame,
4353	   unsigned char *pIn0, unsigned char *pOut0)
4354{
4355	if (!ov->decomp_ops)
4356		if (request_decompressor(ov))
4357			return;
4358
4359	PDEBUG(4, "Decompressing %d bytes", frame->bytes_recvd);
4360
4361	if (frame->format == VIDEO_PALETTE_GREY
4362	    && ov->decomp_ops->decomp_400) {
4363		int ret = ov->decomp_ops->decomp_400(
4364			pIn0,
4365			pOut0,
4366			frame->compbuf,
4367			frame->rawwidth,
4368			frame->rawheight,
4369			frame->bytes_recvd);
4370		PDEBUG(4, "DEBUG: decomp_400 returned %d", ret);
4371	} else if (frame->format != VIDEO_PALETTE_GREY
4372		   && ov->decomp_ops->decomp_420) {
4373		int ret = ov->decomp_ops->decomp_420(
4374			pIn0,
4375			pOut0,
4376			frame->compbuf,
4377			frame->rawwidth,
4378			frame->rawheight,
4379			frame->bytes_recvd);
4380		PDEBUG(4, "DEBUG: decomp_420 returned %d", ret);
4381	} else {
4382		err("Decompressor does not support this format");
4383	}
4384}
4385
4386/**********************************************************************
4387 *
4388 * Format conversion
4389 *
4390 **********************************************************************/
4391
4392#ifdef OV511_ALLOW_CONVERSION
4393
4394/* Converts from planar YUV420 to RGB24. */
4395static void
4396yuv420p_to_rgb(struct ov511_frame *frame,
4397	       unsigned char *pIn0, unsigned char *pOut0, int bits)
4398{
4399	const int numpix = frame->width * frame->height;
4400	const int bytes = bits >> 3;
4401	int i, j, y00, y01, y10, y11, u, v;
4402	unsigned char *pY = pIn0;
4403	unsigned char *pU = pY + numpix;
4404	unsigned char *pV = pU + numpix / 4;
4405	unsigned char *pOut = pOut0;
4406
4407	for (j = 0; j <= frame->height - 2; j += 2) {
4408		for (i = 0; i <= frame->width - 2; i += 2) {
4409			y00 = *pY;
4410			y01 = *(pY + 1);
4411			y10 = *(pY + frame->width);
4412			y11 = *(pY + frame->width + 1);
4413			u = (*pU++) - 128;
4414			v = (*pV++) - 128;
4415
4416			move_420_block(y00, y01, y10, y11, u, v,
4417				       frame->width, pOut, bits);
4418
4419			pY += 2;
4420			pOut += 2 * bytes;
4421		}
4422		pY += frame->width;
4423		pOut += frame->width * bytes;
4424	}
4425}
4426
4427/* Converts from planar YUV420 to YUV422 (YUYV). */
4428static void
4429yuv420p_to_yuv422(struct ov511_frame *frame,
4430		  unsigned char *pIn0, unsigned char *pOut0)
4431{
4432	const int numpix = frame->width * frame->height;
4433	int i, j;
4434	unsigned char *pY = pIn0;
4435	unsigned char *pU = pY + numpix;
4436	unsigned char *pV = pU + numpix / 4;
4437	unsigned char *pOut = pOut0;
4438
4439	for (i = 0; i < numpix; i++) {
4440		*pOut = *(pY + i);
4441		pOut += 2;
4442	}
4443
4444	pOut = pOut0 + 1;
4445	for (j = 0; j <= frame->height - 2 ; j += 2) {
4446		for (i = 0; i <= frame->width - 2; i += 2) {
4447			int u = *pU++;
4448			int v = *pV++;
4449
4450			*pOut = u;
4451			*(pOut+2) = v;
4452			*(pOut+frame->width*2) = u;
4453			*(pOut+frame->width*2+2) = v;
4454			pOut += 4;
4455		}
4456		pOut += (frame->width * 2);
4457	}
4458}
4459
4460/* Converts pData from planar YUV420 to planar YUV422 **in place**. */
4461static void
4462yuv420p_to_yuv422p(struct ov511_frame *frame, unsigned char *pData)
4463{
4464	const int numpix = frame->width * frame->height;
4465	const int w = frame->width;
4466	int j;
4467	unsigned char *pIn, *pOut;
4468
4469	/* Clear U and V */
4470	memset(pData + numpix + numpix / 2, 127, numpix / 2);
4471
4472	/* Convert V starting from beginning and working forward */
4473	pIn = pData + numpix + numpix / 4;
4474	pOut = pData + numpix +numpix / 2;
4475	for (j = 0; j <= frame->height - 2; j += 2) {
4476		memmove(pOut, pIn, w/2);
4477		memmove(pOut + w/2, pIn, w/2);
4478		pIn += w/2;
4479		pOut += w;
4480	}
4481
4482	/* Convert U, starting from end and working backward */
4483	pIn = pData + numpix + numpix / 4;
4484	pOut = pData + numpix + numpix / 2;
4485	for (j = 0; j <= frame->height - 2; j += 2) {
4486		pIn -= w/2;
4487		pOut -= w;
4488		memmove(pOut, pIn, w/2);
4489		memmove(pOut + w/2, pIn, w/2);
4490	}
4491}
4492
4493#endif	/* OV511_ALLOW_CONVERSION */
4494
4495/* Fuses even and odd fields together, and doubles width.
4496 * INPUT: an odd field followed by an even field at pIn0, in YUV planar format
4497 * OUTPUT: a normal YUV planar image, with correct aspect ratio
4498 */
4499static void
4500deinterlace(struct ov511_frame *frame, int rawformat,
4501            unsigned char *pIn0, unsigned char *pOut0)
4502{
4503	const int fieldheight = frame->rawheight / 2;
4504	const int fieldpix = fieldheight * frame->rawwidth;
4505	const int w = frame->width;
4506	int x, y;
4507	unsigned char *pInEven, *pInOdd, *pOut;
4508
4509	PDEBUG(5, "fieldheight=%d", fieldheight);
4510
4511	if (frame->rawheight != frame->height) {
4512		err("invalid height");
4513		return;
4514	}
4515
4516	if ((frame->rawwidth * 2) != frame->width) {
4517		err("invalid width");
4518		return;
4519	}
4520
4521	/* Y */
4522	pInOdd = pIn0;
4523	pInEven = pInOdd + fieldpix;
4524	pOut = pOut0;
4525	for (y = 0; y < fieldheight; y++) {
4526		for (x = 0; x < frame->rawwidth; x++) {
4527			*pOut = *pInEven;
4528			*(pOut+1) = *pInEven++;
4529			*(pOut+w) = *pInOdd;
4530			*(pOut+w+1) = *pInOdd++;
4531			pOut += 2;
4532		}
4533		pOut += w;
4534	}
4535
4536	if (rawformat == RAWFMT_YUV420) {
4537	/* U */
4538		pInOdd = pIn0 + fieldpix * 2;
4539		pInEven = pInOdd + fieldpix / 4;
4540		for (y = 0; y < fieldheight / 2; y++) {
4541			for (x = 0; x < frame->rawwidth / 2; x++) {
4542				*pOut = *pInEven;
4543				*(pOut+1) = *pInEven++;
4544				*(pOut+w/2) = *pInOdd;
4545				*(pOut+w/2+1) = *pInOdd++;
4546				pOut += 2;
4547			}
4548			pOut += w/2;
4549		}
4550	/* V */
4551		pInOdd = pIn0 + fieldpix * 2 + fieldpix / 2;
4552		pInEven = pInOdd + fieldpix / 4;
4553		for (y = 0; y < fieldheight / 2; y++) {
4554			for (x = 0; x < frame->rawwidth / 2; x++) {
4555				*pOut = *pInEven;
4556				*(pOut+1) = *pInEven++;
4557				*(pOut+w/2) = *pInOdd;
4558				*(pOut+w/2+1) = *pInOdd++;
4559				pOut += 2;
4560			}
4561			pOut += w/2;
4562		}
4563	}
4564}
4565
4566static void
4567ov51x_postprocess_grey(struct usb_ov511 *ov, struct ov511_frame *frame)
4568{
4569		/* Deinterlace frame, if necessary */
4570		if (ov->sensor == SEN_SAA7111A && frame->rawheight >= 480) {
4571			if (frame->compressed)
4572				decompress(ov, frame, frame->rawdata,
4573						 frame->tempdata);
4574			else
4575				yuv400raw_to_yuv400p(frame, frame->rawdata,
4576						     frame->tempdata);
4577
4578			deinterlace(frame, RAWFMT_YUV400, frame->tempdata,
4579			            frame->data);
4580		} else {
4581			if (frame->compressed)
4582				decompress(ov, frame, frame->rawdata,
4583						 frame->data);
4584			else
4585				yuv400raw_to_yuv400p(frame, frame->rawdata,
4586						     frame->data);
4587		}
4588}
4589
4590#ifdef OV511_ALLOW_CONVERSION
4591/* Process raw YUV420 data into the format requested by the app. Conversion
4592 * between V4L formats is allowed.
4593 */
4594static void
4595ov51x_postprocess_yuv420(struct usb_ov511 *ov, struct ov511_frame *frame)
4596{
4597	/* Process frame->rawdata to frame->tempdata */
4598	if (frame->compressed)
4599		decompress(ov, frame, frame->rawdata, frame->tempdata);
4600	else
4601		yuv420raw_to_yuv420p(frame, frame->rawdata, frame->tempdata);
4602
4603	/* Deinterlace frame, if necessary */
4604	if (ov->sensor == SEN_SAA7111A && frame->rawheight >= 480) {
4605		memcpy(frame->rawdata, frame->tempdata,
4606			MAX_RAW_DATA_SIZE(frame->width, frame->height));
4607		deinterlace(frame, RAWFMT_YUV420, frame->rawdata,
4608		            frame->tempdata);
4609	}
4610
4611	/* Frame should be (width x height) and not (rawwidth x rawheight) at
4612         * this point. */
4613
4614	/* Process frame->tempdata to frame->data */
4615	switch (frame->format) {
4616	case VIDEO_PALETTE_RGB565:
4617		yuv420p_to_rgb(frame, frame->tempdata, frame->data, 16);
4618		break;
4619	case VIDEO_PALETTE_RGB24:
4620		yuv420p_to_rgb(frame, frame->tempdata, frame->data, 24);
4621		break;
4622	case VIDEO_PALETTE_YUV422:
4623	case VIDEO_PALETTE_YUYV:
4624		yuv420p_to_yuv422(frame, frame->tempdata, frame->data);
4625		break;
4626	case VIDEO_PALETTE_YUV420:
4627	case VIDEO_PALETTE_YUV420P:
4628		memcpy(frame->data, frame->tempdata,
4629			MAX_RAW_DATA_SIZE(frame->width, frame->height));
4630		break;
4631	case VIDEO_PALETTE_YUV422P:
4632		/* Data is converted in place, so copy it in advance */
4633		memcpy(frame->data, frame->tempdata,
4634			MAX_RAW_DATA_SIZE(frame->width, frame->height));
4635
4636		yuv420p_to_yuv422p(frame, frame->data);
4637		break;
4638	default:
4639		err("Cannot convert YUV420 to %s",
4640		    symbolic(v4l1_plist, frame->format));
4641	}
4642
4643	if (fix_rgb_offset)
4644		fixFrameRGBoffset(frame);
4645}
4646
4647#else /* if conversion not allowed */
4648
4649/* Process raw YUV420 data into standard YUV420P */
4650static void
4651ov51x_postprocess_yuv420(struct usb_ov511 *ov, struct ov511_frame *frame)
4652{
4653	/* Deinterlace frame, if necessary */
4654	if (ov->sensor == SEN_SAA7111A && frame->rawheight >= 480) {
4655		if (frame->compressed)
4656			decompress(ov, frame, frame->rawdata, frame->tempdata);
4657		else
4658			yuv420raw_to_yuv420p(frame, frame->rawdata,
4659					     frame->tempdata);
4660
4661		deinterlace(frame, RAWFMT_YUV420, frame->tempdata,
4662		            frame->data);
4663	} else {
4664		if (frame->compressed)
4665			decompress(ov, frame, frame->rawdata, frame->data);
4666		else
4667			yuv420raw_to_yuv420p(frame, frame->rawdata,
4668					     frame->data);
4669	}
4670}
4671#endif /* OV511_ALLOW_CONVERSION */
4672
4673/* Post-processes the specified frame. This consists of:
4674 * 	1. Decompress frame, if necessary
4675 *	2. Deinterlace frame and scale to proper size, if necessary
4676 * 	3. Convert from YUV planar to destination format, if necessary
4677 * 	4. Fix the RGB offset, if necessary
4678 */
4679static void
4680ov51x_postprocess(struct usb_ov511 *ov, struct ov511_frame *frame)
4681{
4682	if (dumppix) {
4683		memset(frame->data, 0,
4684			MAX_DATA_SIZE(ov->maxwidth, ov->maxheight));
4685		PDEBUG(4, "Dumping %d bytes", frame->bytes_recvd);
4686		memcpy(frame->data, frame->rawdata, frame->bytes_recvd);
4687	} else {
4688		switch (frame->format) {
4689		case VIDEO_PALETTE_GREY:
4690			ov51x_postprocess_grey(ov, frame);
4691			break;
4692		case VIDEO_PALETTE_YUV420:
4693		case VIDEO_PALETTE_YUV420P:
4694#ifdef OV511_ALLOW_CONVERSION
4695		case VIDEO_PALETTE_RGB565:
4696		case VIDEO_PALETTE_RGB24:
4697		case VIDEO_PALETTE_YUV422:
4698		case VIDEO_PALETTE_YUYV:
4699		case VIDEO_PALETTE_YUV422P:
4700#endif
4701			ov51x_postprocess_yuv420(ov, frame);
4702			break;
4703		default:
4704			err("Cannot convert data to %s",
4705			    symbolic(v4l1_plist, frame->format));
4706		}
4707	}
4708}
4709
4710/**********************************************************************
4711 *
4712 * OV51x data transfer, IRQ handler
4713 *
4714 **********************************************************************/
4715
4716static inline void
4717ov511_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
4718{
4719	int num, offset;
4720	int pnum = in[ov->packet_size - 1];		/* Get packet number */
4721	int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
4722	struct ov511_frame *frame = &ov->frame[ov->curframe];
4723	struct timeval *ts;
4724
4725	/* SOF/EOF packets have 1st to 8th bytes zeroed and the 9th
4726	 * byte non-zero. The EOF packet has image width/height in the
4727	 * 10th and 11th bytes. The 9th byte is given as follows:
4728	 *
4729	 * bit 7: EOF
4730	 *     6: compression enabled
4731	 *     5: 422/420/400 modes
4732	 *     4: 422/420/400 modes
4733	 *     3: 1
4734	 *     2: snapshot button on
4735	 *     1: snapshot frame
4736	 *     0: even/odd field
4737	 */
4738
4739	if (printph) {
4740		info("ph(%3d): %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x",
4741		     pnum, in[0], in[1], in[2], in[3], in[4], in[5], in[6],
4742		     in[7], in[8], in[9], in[10], in[11]);
4743	}
4744
4745	/* Check for SOF/EOF packet */
4746	if ((in[0] | in[1] | in[2] | in[3] | in[4] | in[5] | in[6] | in[7]) ||
4747	    (~in[8] & 0x08))
4748		goto check_middle;
4749
4750	/* Frame end */
4751	if (in[8] & 0x80) {
4752		ts = (struct timeval *)(frame->data
4753		      + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
4754		do_gettimeofday(ts);
4755
4756		/* Get the actual frame size from the EOF header */
4757		frame->rawwidth = ((int)(in[9]) + 1) * 8;
4758		frame->rawheight = ((int)(in[10]) + 1) * 8;
4759
4760 		PDEBUG(4, "Frame end, frame=%d, pnum=%d, w=%d, h=%d, recvd=%d",
4761			ov->curframe, pnum, frame->rawwidth, frame->rawheight,
4762			frame->bytes_recvd);
4763
4764		/* Validate the header data */
4765		RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
4766		RESTRICT_TO_RANGE(frame->rawheight, ov->minheight,
4767				  ov->maxheight);
4768
4769		/* Don't allow byte count to exceed buffer size */
4770		RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
4771
4772		if (frame->scanstate == STATE_LINES) {
4773	    		int nextf;
4774
4775			frame->grabstate = FRAME_DONE;
4776			wake_up_interruptible(&frame->wq);
4777
4778			/* If next frame is ready or grabbing,
4779			 * point to it */
4780			nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
4781			if (ov->frame[nextf].grabstate == FRAME_READY
4782			    || ov->frame[nextf].grabstate == FRAME_GRABBING) {
4783				ov->curframe = nextf;
4784				ov->frame[nextf].scanstate = STATE_SCANNING;
4785			} else {
4786				if (ov->frame[nextf].grabstate == FRAME_DONE) {
4787					PDEBUG(4, "No empty frames left");
4788				} else {
4789					PDEBUG(4, "Frame not ready? state = %d",
4790						ov->frame[nextf].grabstate);
4791				}
4792
4793				ov->curframe = -1;
4794			}
4795		} else {
4796			PDEBUG(5, "Frame done, but not scanning");
4797		}
4798		/* Image corruption caused by misplaced frame->segment = 0
4799		 * fixed by carlosf@conectiva.com.br
4800		 */
4801	} else {
4802		/* Frame start */
4803		PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
4804
4805		/* Check to see if it's a snapshot frame */
4806		/* FIXME?? Should the snapshot reset go here? Performance? */
4807		if (in[8] & 0x02) {
4808			frame->snapshot = 1;
4809			PDEBUG(3, "snapshot detected");
4810		}
4811
4812		frame->scanstate = STATE_LINES;
4813		frame->bytes_recvd = 0;
4814		frame->compressed = in[8] & 0x40;
4815	}
4816
4817check_middle:
4818	/* Are we in a frame? */
4819	if (frame->scanstate != STATE_LINES) {
4820		PDEBUG(5, "Not in a frame; packet skipped");
4821		return;
4822	}
4823
4824	/* If frame start, skip header */
4825	if (frame->bytes_recvd == 0)
4826		offset = 9;
4827	else
4828		offset = 0;
4829
4830	num = n - offset - 1;
4831
4832	/* Dump all data exactly as received */
4833	if (dumppix == 2) {
4834		frame->bytes_recvd += n - 1;
4835		if (frame->bytes_recvd <= max_raw)
4836			memcpy(frame->rawdata + frame->bytes_recvd - (n - 1),
4837				in, n - 1);
4838		else
4839			PDEBUG(3, "Raw data buffer overrun!! (%d)",
4840				frame->bytes_recvd - max_raw);
4841	} else if (!frame->compressed && !remove_zeros) {
4842		frame->bytes_recvd += num;
4843		if (frame->bytes_recvd <= max_raw)
4844			memcpy(frame->rawdata + frame->bytes_recvd - num,
4845				in + offset, num);
4846		else
4847			PDEBUG(3, "Raw data buffer overrun!! (%d)",
4848				frame->bytes_recvd - max_raw);
4849	} else { /* Remove all-zero FIFO lines (aligned 32-byte blocks) */
4850		int b, read = 0, allzero, copied = 0;
4851		if (offset) {
4852			frame->bytes_recvd += 32 - offset;	// Bytes out
4853			memcpy(frame->rawdata,	in + offset, 32 - offset);
4854			read += 32;
4855		}
4856
4857		while (read < n - 1) {
4858			allzero = 1;
4859			for (b = 0; b < 32; b++) {
4860				if (in[read + b]) {
4861					allzero = 0;
4862					break;
4863				}
4864			}
4865
4866			if (allzero) {
4867				/* Don't copy it */
4868			} else {
4869				if (frame->bytes_recvd + copied + 32 <= max_raw)
4870				{
4871					memcpy(frame->rawdata
4872						+ frame->bytes_recvd + copied,
4873						in + read, 32);
4874					copied += 32;
4875				} else {
4876					PDEBUG(3, "Raw data buffer overrun!!");
4877				}
4878			}
4879			read += 32;
4880		}
4881
4882		frame->bytes_recvd += copied;
4883	}
4884}
4885
4886static inline void
4887ov518_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
4888{
4889	int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
4890	struct ov511_frame *frame = &ov->frame[ov->curframe];
4891	struct timeval *ts;
4892
4893	/* Don't copy the packet number byte */
4894	if (ov->packet_numbering)
4895		--n;
4896
4897	/* A false positive here is likely, until OVT gives me
4898	 * the definitive SOF/EOF format */
4899	if ((!(in[0] | in[1] | in[2] | in[3] | in[5])) && in[6]) {
4900		if (printph) {
4901			info("ph: %2x %2x %2x %2x %2x %2x %2x %2x", in[0],
4902			     in[1], in[2], in[3], in[4], in[5], in[6], in[7]);
4903		}
4904
4905		if (frame->scanstate == STATE_LINES) {
4906			PDEBUG(4, "Detected frame end/start");
4907			goto eof;
4908		} else { //scanstate == STATE_SCANNING
4909			/* Frame start */
4910			PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
4911			goto sof;
4912		}
4913	} else {
4914		goto check_middle;
4915	}
4916
4917eof:
4918	ts = (struct timeval *)(frame->data
4919	      + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
4920	do_gettimeofday(ts);
4921
4922	PDEBUG(4, "Frame end, curframe = %d, hw=%d, vw=%d, recvd=%d",
4923		ov->curframe,
4924		(int)(in[9]), (int)(in[10]), frame->bytes_recvd);
4925
4926	// FIXME: Since we don't know the header formats yet,
4927	// there is no way to know what the actual image size is
4928	frame->rawwidth = frame->width;
4929	frame->rawheight = frame->height;
4930
4931	/* Validate the header data */
4932	RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
4933	RESTRICT_TO_RANGE(frame->rawheight, ov->minheight, ov->maxheight);
4934
4935	/* Don't allow byte count to exceed buffer size */
4936	RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
4937
4938	if (frame->scanstate == STATE_LINES) {
4939    		int nextf;
4940
4941		frame->grabstate = FRAME_DONE;
4942		wake_up_interruptible(&frame->wq);
4943
4944		/* If next frame is ready or grabbing,
4945		 * point to it */
4946		nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
4947		if (ov->frame[nextf].grabstate == FRAME_READY
4948		    || ov->frame[nextf].grabstate == FRAME_GRABBING) {
4949			ov->curframe = nextf;
4950			ov->frame[nextf].scanstate = STATE_SCANNING;
4951			frame = &ov->frame[nextf];
4952		} else {
4953			if (ov->frame[nextf].grabstate == FRAME_DONE) {
4954				PDEBUG(4, "No empty frames left");
4955			} else {
4956				PDEBUG(4, "Frame not ready? state = %d",
4957				       ov->frame[nextf].grabstate);
4958			}
4959
4960			ov->curframe = -1;
4961			PDEBUG(4, "SOF dropped (no active frame)");
4962			return;  /* Nowhere to store this frame */
4963		}
4964	}
4965sof:
4966	PDEBUG(4, "Starting capture on frame %d", frame->framenum);
4967
4968// Snapshot not reverse-engineered yet.
4969#if 0
4970	/* Check to see if it's a snapshot frame */
4971	/* FIXME?? Should the snapshot reset go here? Performance? */
4972	if (in[8] & 0x02) {
4973		frame->snapshot = 1;
4974		PDEBUG(3, "snapshot detected");
4975	}
4976#endif
4977	frame->scanstate = STATE_LINES;
4978	frame->bytes_recvd = 0;
4979	frame->compressed = 1;
4980
4981check_middle:
4982	/* Are we in a frame? */
4983	if (frame->scanstate != STATE_LINES) {
4984		PDEBUG(4, "scanstate: no SOF yet");
4985		return;
4986	}
4987
4988	/* Dump all data exactly as received */
4989	if (dumppix == 2) {
4990		frame->bytes_recvd += n;
4991		if (frame->bytes_recvd <= max_raw)
4992			memcpy(frame->rawdata + frame->bytes_recvd - n, in, n);
4993		else
4994			PDEBUG(3, "Raw data buffer overrun!! (%d)",
4995				frame->bytes_recvd - max_raw);
4996	} else {
4997		/* All incoming data are divided into 8-byte segments. If the
4998		 * segment contains all zero bytes, it must be skipped. These
4999		 * zero-segments allow the OV518 to mainain a constant data rate
5000		 * regardless of the effectiveness of the compression. Segments
5001		 * are aligned relative to the beginning of each isochronous
5002		 * packet. The first segment in each image is a header (the
5003		 * decompressor skips it later).
5004		 */
5005
5006		int b, read = 0, allzero, copied = 0;
5007
5008		while (read < n) {
5009			allzero = 1;
5010			for (b = 0; b < 8; b++) {
5011				if (in[read + b]) {
5012					allzero = 0;
5013					break;
5014				}
5015			}
5016
5017			if (allzero) {
5018			/* Don't copy it */
5019			} else {
5020				if (frame->bytes_recvd + copied + 8 <= max_raw)
5021				{
5022					memcpy(frame->rawdata
5023						+ frame->bytes_recvd + copied,
5024						in + read, 8);
5025					copied += 8;
5026				} else {
5027					PDEBUG(3, "Raw data buffer overrun!!");
5028				}
5029			}
5030			read += 8;
5031		}
5032		frame->bytes_recvd += copied;
5033	}
5034}
5035
5036static inline void
5037ov519_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
5038{
5039	int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
5040	struct ov511_frame *frame = &ov->frame[ov->curframe];
5041	struct timeval *ts;
5042
5043	/* Don't copy the packet number byte */
5044//	if (ov->packet_numbering)
5045//		--n;
5046/* Header of ov519 is 16 bytes:
5047 * Byte     Value      Description
5048 *	0		0xff	magic
5049 *	1		0xff	magic
5050 *	2		0xff	magic
5051 *	3		0xXX	0x50 = SOF, 0x51 = EOF
5052 *	9		0xXX	0x01 initial frame without data, 0x00 standard frame with image
5053 *	14		Lo		in EOF: length of image data / 8
5054 *	15		Hi
5055 */
5056
5057	// Start Of Frame
5058	if ((in[0]==0xff) && (in[1]==0xff) && (in[2]==0xff)) {
5059
5060		if (printph) {
5061			info("ph: %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x",
5062				in[0], in[1], in[2],  in[3],  in[4],  in[5],  in[6],  in[7],
5063				in[8], in[9], in[10], in[11], in[12], in[13], in[14], in[15]);
5064		}
5065
5066		if (in[3]==0x50) {
5067			PDEBUG(4, "Start Of Frame, framenum = %d", ov->curframe);
5068			goto sof;
5069		} else if (in[3]==0x51) {
5070			PDEBUG(4, "End Of Frame");
5071			goto eof;
5072		} else {
5073			goto check_middle;
5074		}
5075	} else {
5076		goto check_middle;
5077	}
5078
5079eof:
5080	ts = (struct timeval *)(frame->data
5081	      + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
5082	do_gettimeofday(ts);
5083	PDEBUG(4, "Frame end, curframe=%d, length=%d, recvd=%d",
5084		ov->curframe, (int)((in[14]) + ((int)(in[15])<<8))<<3, frame->bytes_recvd - (jpeginfo?2:0));
5085
5086
5087	if (in[9]) {
5088		PDEBUG(1, "initial frame");
5089		frame->scanstate = STATE_SCANNING;
5090		return;
5091	}
5092
5093	// FIXME: Since we don't know the header formats yet,
5094	// there is no way to know what the actual image size is
5095	frame->rawwidth = frame->width;
5096	frame->rawheight = frame->height;
5097
5098	/* Validate the header data */
5099	RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
5100	RESTRICT_TO_RANGE(frame->rawheight, ov->minheight, ov->maxheight);
5101
5102	/* Don't allow byte count to exceed buffer size */
5103	//RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
5104
5105	if (frame->scanstate == STATE_LINES) {
5106		int nextf;
5107
5108		if (((int)((in[14]) + ((int)(in[15])<<8))<<3) != (frame->bytes_recvd - (jpeginfo?2:0))) {
5109			info("Data length in header and number of received bytes differ");
5110			frame->scanstate = STATE_SCANNING;
5111			return;
5112		}
5113
5114	if (jpeginfo) {
5115		frame->data[0] = in[14];
5116		frame->data[1] = in[15];
5117	}
5118		frame->grabstate = FRAME_DONE;
5119		wake_up_interruptible(&frame->wq);
5120
5121		/* If next frame is ready or grabbing,
5122		 * point to it */
5123		nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
5124		if (ov->frame[nextf].grabstate == FRAME_READY
5125		    || ov->frame[nextf].grabstate == FRAME_GRABBING) {
5126			ov->curframe = nextf;
5127			ov->frame[nextf].scanstate = STATE_SCANNING;
5128		} else {
5129			ov->curframe = -1;
5130		}
5131	} else {
5132		info("EOF without SOF"); // This happens if there was no active frame when SOF arrived
5133	}
5134	return;
5135
5136sof:
5137	PDEBUG(4, "Starting capture on frame %d", frame->framenum);
5138
5139	// Skip SOF Header:
5140	in += 16;
5141	n  -= 16;
5142
5143	frame->scanstate = STATE_LINES;
5144	if (jpeginfo) {
5145		frame->bytes_recvd = 2; // Space for length bytes. Will be written at EOF
5146		frame->data[0] = 0;
5147		frame->data[1] = 0;
5148	} else {
5149		frame->bytes_recvd = 0;
5150	}
5151	frame->compressed = 1;
5152
5153check_middle:
5154	/* Are we in a frame? */
5155	if (frame->scanstate != STATE_LINES) {
5156		PDEBUG(4, "scanstate: no SOF yet");
5157		return;
5158	}
5159
5160	/* Dump all data exactly as received. It is standard JPEG */
5161	frame->bytes_recvd += n;
5162	if (frame->bytes_recvd <= max_raw) {
5163		memcpy(frame->data + frame->bytes_recvd - n, in, n);
5164	} else {
5165		PDEBUG(3, "Raw data buffer overrun!! (%d)", frame->bytes_recvd - max_raw);
5166	}
5167}
5168
5169static void
5170ov51x_isoc_irq(struct urb *urb)
5171{
5172	int i;
5173	struct usb_ov511 *ov;
5174	struct ov511_sbuf *sbuf;
5175
5176	if (!urb->context) {
5177		PDEBUG(4, "no context");
5178		return;
5179	}
5180
5181	sbuf = urb->context;
5182	ov = sbuf->ov;
5183
5184	if (!ov || !ov->dev || !ov->user) {
5185		PDEBUG(4, "no device, or not open");
5186		return;
5187	}
5188
5189	if (!ov->streaming) {
5190		PDEBUG(4, "hmmm... not streaming, but got interrupt");
5191		return;
5192	}
5193
5194        if (urb->status == -ENOENT || urb->status == -ECONNRESET) {
5195                PDEBUG(4, "URB unlinked");
5196                return;
5197        }
5198
5199	if (urb->status != -EINPROGRESS && urb->status != 0) {
5200		err("ERROR: urb->status=%d: %s", urb->status,
5201		    symbolic(urb_errlist, urb->status));
5202	}
5203
5204	/* Copy the data received into our frame buffer */
5205	PDEBUG(5, "sbuf[%d]: Moving %d packets", sbuf->n,
5206	       urb->number_of_packets);
5207	for (i = 0; i < urb->number_of_packets; i++) {
5208		/* Warning: Don't call *_move_data() if no frame active! */
5209		if (ov->curframe >= 0) {
5210			int n = urb->iso_frame_desc[i].actual_length;
5211			int st = urb->iso_frame_desc[i].status;
5212			unsigned char *cdata;
5213
5214			urb->iso_frame_desc[i].actual_length = 0;
5215			urb->iso_frame_desc[i].status = 0;
5216
5217			cdata = urb->transfer_buffer
5218				+ urb->iso_frame_desc[i].offset;
5219
5220			if (!n) {
5221				PDEBUG(4, "Zero-length packet");
5222				continue;
5223			}
5224
5225			if (st)
5226				PDEBUG(2, "data error: [%d] len=%d, status=%d",
5227				       i, n, st);
5228
5229			switch (ov->bclass) {
5230				case BCL_OV511:
5231					ov511_move_data(ov, cdata, n);
5232					break;
5233				case BCL_OV518:
5234					ov518_move_data(ov, cdata, n);
5235					break;
5236				case BCL_OV519:
5237					ov519_move_data(ov, cdata, n);
5238					break;
5239				default:
5240					err("Unknown bridge device (%d)", ov->bridge);
5241			}
5242		} else if (waitqueue_active(&ov->wq)) {
5243			wake_up_interruptible(&ov->wq);
5244		}
5245	}
5246
5247	/* Resubmit this URB */
5248	urb->dev = ov->dev;
5249#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 18)
5250	if ((i = usb_submit_urb(urb, GFP_ATOMIC)) != 0)
5251#else
5252	if ((i = usb_submit_urb(urb)) != 0)
5253#endif
5254		err("usb_submit_urb() ret %d", i);
5255
5256	return;
5257}
5258
5259/****************************************************************************
5260 *
5261 * Stream initialization and termination
5262 *
5263 ***************************************************************************/
5264
5265static int
5266ov51x_init_isoc(struct usb_ov511 *ov)
5267{
5268	struct urb *urb;
5269	int fx, err, n, size;
5270
5271	PDEBUG(3, "*** Initializing capture ***");
5272
5273	ov->curframe = -1;
5274
5275	switch (ov->bridge) {
5276		case BRG_OV511:
5277			if (cams == 1)				size = 993;
5278			else if (cams == 2)			size = 513;
5279			else if (cams == 3 || cams == 4)	size = 257;
5280			else {
5281				err("\"cams\" parameter too high!");
5282				return -1;
5283			}
5284			break;
5285		case BRG_OV511PLUS:
5286			if (cams == 1)				size = 961;
5287			else if (cams == 2)			size = 513;
5288			else if (cams == 3 || cams == 4)	size = 257;
5289			else if (cams >= 5 && cams <= 8)	size = 129;
5290			else if (cams >= 9 && cams <= 31)	size = 33;
5291			else {
5292				err("\"cams\" parameter too high!");
5293				return -1;
5294			}
5295			break;
5296		case BRG_OV518:
5297		case BRG_OV518PLUS:
5298			if (cams == 1)				size = 896;
5299			else if (cams == 2)			size = 512;
5300			else if (cams == 3 || cams == 4)	size = 256;
5301			else if (cams >= 5 && cams <= 8)	size = 128;
5302			else {
5303				err("\"cams\" parameter too high!");
5304				return -1;
5305			}
5306			break;
5307		case BRG_OV519:
5308			if (cams == 1)				size = 896;
5309			else if (cams == 2)			size = 512;
5310			else {
5311				err("\"cams\" parameter too high!");
5312				return -1;
5313			}
5314			break;
5315		default:
5316			err("invalid bridge type");
5317			return -1;
5318	}
5319
5320	// FIXME: OV518+ is hardcoded to 15 FPS (alternate 5) for now
5321	if (ov->bridge == BRG_OV518PLUS) {
5322		if (packetsize == -1) {
5323			ov518_set_packet_size(ov, 640);
5324		} else {
5325			info("Forcing packet size to %d", packetsize);
5326			ov518_set_packet_size(ov, packetsize);
5327		}
5328	} else if (ov->bridge == BRG_OV518) {
5329		if (packetsize == -1) {
5330			ov518_set_packet_size(ov, 896);
5331		} else {
5332			info("Forcing packet size to %d", packetsize);
5333			ov518_set_packet_size(ov, packetsize);
5334		}
5335	} else if (ov->bridge == BRG_OV519) {
5336		if (packetsize == -1) {
5337			ov519_set_packet_size(ov, size);
5338		} else {
5339			info("Forcing packet size to %d", packetsize);
5340			ov519_set_packet_size(ov, packetsize);
5341		}
5342	} else {
5343		if (packetsize == -1) {
5344			ov511_set_packet_size(ov, size);
5345		} else {
5346			info("Forcing packet size to %d", packetsize);
5347			ov511_set_packet_size(ov, packetsize);
5348		}
5349	}
5350
5351	for (n = 0; n < OV511_NUMSBUF; n++) {
5352#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 5)
5353		urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
5354#else
5355		urb = usb_alloc_urb(FRAMES_PER_DESC);
5356#endif
5357		if (!urb) {
5358			err("init isoc: usb_alloc_urb ret. NULL");
5359			return -ENOMEM;
5360		}
5361		ov->sbuf[n].urb = urb;
5362		urb->dev = ov->dev;
5363		urb->context = &ov->sbuf[n];
5364		urb->pipe = usb_rcvisocpipe(ov->dev, OV511_ENDPOINT_ADDRESS);
5365#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 45)
5366		urb->transfer_flags = URB_ISO_ASAP;
5367#else
5368		urb->transfer_flags = USB_ISO_ASAP;
5369#endif
5370		urb->transfer_buffer = ov->sbuf[n].data;
5371		urb->complete = ov51x_isoc_irq;
5372		urb->number_of_packets = FRAMES_PER_DESC;
5373		urb->transfer_buffer_length = ov->packet_size * FRAMES_PER_DESC;
5374		urb->interval = 1;
5375		for (fx = 0; fx < FRAMES_PER_DESC; fx++) {
5376			urb->iso_frame_desc[fx].offset = ov->packet_size * fx;
5377			urb->iso_frame_desc[fx].length = ov->packet_size;
5378		}
5379	}
5380
5381	ov->streaming = 1;
5382
5383	for (n = 0; n < OV511_NUMSBUF; n++) {
5384		ov->sbuf[n].urb->dev = ov->dev;
5385#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 4)
5386		err = usb_submit_urb(ov->sbuf[n].urb, GFP_KERNEL);
5387#else
5388		err = usb_submit_urb(ov->sbuf[n].urb);
5389#endif
5390		if (err) {
5391			err("init isoc: usb_submit_urb(%d) ret %d", n, err);
5392			return err;
5393		}
5394	}
5395
5396	return 0;
5397}
5398
5399static void
5400ov51x_unlink_isoc(struct usb_ov511 *ov)
5401{
5402	int n;
5403
5404	/* Unschedule all of the iso td's */
5405	for (n = OV511_NUMSBUF - 1; n >= 0; n--) {
5406		if (ov->sbuf[n].urb) {
5407			usb_unlink_urb(ov->sbuf[n].urb);
5408			usb_free_urb(ov->sbuf[n].urb);
5409			ov->sbuf[n].urb = NULL;
5410		}
5411	}
5412}
5413
5414static void
5415ov51x_stop_isoc(struct usb_ov511 *ov)
5416{
5417	if (!ov->streaming || !ov->dev)
5418		return;
5419
5420	PDEBUG(3, "*** Stopping capture ***");
5421
5422	switch (ov->bclass) {
5423		case BCL_OV511:
5424			ov511_set_packet_size(ov, 0);
5425			break;
5426		case BCL_OV518:
5427			ov518_set_packet_size(ov, 0);
5428			break;
5429		case BCL_OV519:
5430			ov519_set_packet_size(ov, 0);
5431			break;
5432	}
5433	ov->streaming = 0;
5434
5435	ov51x_unlink_isoc(ov);
5436}
5437
5438static int
5439ov51x_new_frame(struct usb_ov511 *ov, int framenum)
5440{
5441	struct ov511_frame *frame;
5442	int newnum;
5443
5444	PDEBUG(4, "ov->curframe = %d, framenum = %d", ov->curframe, framenum);
5445
5446	if (!ov->dev)
5447		return -1;
5448
5449	/* If we're not grabbing a frame right now and the other frame is */
5450	/* ready to be grabbed into, then use it instead */
5451	if (ov->curframe == -1) {
5452		newnum = (framenum - 1 + OV511_NUMFRAMES) % OV511_NUMFRAMES;
5453		if (ov->frame[newnum].grabstate == FRAME_READY)
5454			framenum = newnum;
5455	} else
5456		return 0;
5457
5458	frame = &ov->frame[framenum];
5459
5460	PDEBUG(4, "framenum = %d, width = %d, height = %d", framenum,
5461	       frame->width, frame->height);
5462
5463	frame->grabstate = FRAME_GRABBING;
5464	frame->scanstate = STATE_SCANNING;
5465	frame->snapshot = 0;
5466
5467	ov->curframe = framenum;
5468
5469	/* Make sure it's not too big */
5470	if (frame->width > ov->maxwidth)
5471		frame->width = ov->maxwidth;
5472
5473	frame->width &= ~7L;		/* Multiple of 8 */
5474
5475	if (frame->height > ov->maxheight)
5476		frame->height = ov->maxheight;
5477
5478	frame->height &= ~3L;		/* Multiple of 4 */
5479
5480	return 0;
5481}
5482
5483/****************************************************************************
5484 *
5485 * Buffer management
5486 *
5487 ***************************************************************************/
5488
5489/*
5490 * - You must acquire buf_lock before entering this function.
5491 * - Because this code will free any non-null pointer, you must be sure to null
5492 *   them if you explicitly free them somewhere else!
5493 */
5494static void
5495ov51x_do_dealloc(struct usb_ov511 *ov)
5496{
5497	int i;
5498	PDEBUG(4, "entered");
5499
5500	if (ov->fbuf) {
5501		rvfree(ov->fbuf, OV511_NUMFRAMES
5502		       * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight));
5503		ov->fbuf = NULL;
5504	}
5505
5506	if (ov->rawfbuf) {
5507		vfree(ov->rawfbuf);
5508		ov->rawfbuf = NULL;
5509	}
5510
5511	if (ov->tempfbuf) {
5512		vfree(ov->tempfbuf);
5513		ov->tempfbuf = NULL;
5514	}
5515
5516	for (i = 0; i < OV511_NUMSBUF; i++) {
5517		if (ov->sbuf[i].data) {
5518			kfree(ov->sbuf[i].data);
5519			ov->sbuf[i].data = NULL;
5520		}
5521	}
5522
5523	for (i = 0; i < OV511_NUMFRAMES; i++) {
5524		ov->frame[i].data = NULL;
5525		ov->frame[i].rawdata = NULL;
5526		ov->frame[i].tempdata = NULL;
5527		if (ov->frame[i].compbuf) {
5528			free_page((unsigned long) ov->frame[i].compbuf);
5529			ov->frame[i].compbuf = NULL;
5530		}
5531	}
5532
5533	PDEBUG(4, "buffer memory deallocated");
5534	ov->buf_state = BUF_NOT_ALLOCATED;
5535	PDEBUG(4, "leaving");
5536}
5537
5538static int
5539ov51x_alloc(struct usb_ov511 *ov)
5540{
5541	int i;
5542	const int w = ov->maxwidth;
5543	const int h = ov->maxheight;
5544	const int data_bufsize = OV511_NUMFRAMES * MAX_DATA_SIZE(w, h);
5545	const int raw_bufsize = OV511_NUMFRAMES * MAX_RAW_DATA_SIZE(w, h);
5546
5547	PDEBUG(4, "entered");
5548	down(&ov->buf_lock);
5549
5550	if (ov->buf_state == BUF_ALLOCATED)
5551		goto out;
5552
5553	ov->fbuf = rvmalloc(data_bufsize);
5554	if (!ov->fbuf)
5555		goto error;
5556
5557	ov->rawfbuf = vmalloc(raw_bufsize);
5558	if (!ov->rawfbuf)
5559		goto error;
5560
5561	memset(ov->rawfbuf, 0, raw_bufsize);
5562
5563	ov->tempfbuf = vmalloc(raw_bufsize);
5564	if (!ov->tempfbuf)
5565		goto error;
5566
5567	memset(ov->tempfbuf, 0, raw_bufsize);
5568
5569	for (i = 0; i < OV511_NUMSBUF; i++) {
5570		ov->sbuf[i].data = kmalloc(FRAMES_PER_DESC *
5571			MAX_FRAME_SIZE_PER_DESC, GFP_KERNEL);
5572		if (!ov->sbuf[i].data)
5573			goto error;
5574
5575		PDEBUG(4, "sbuf[%d] @ %p", i, ov->sbuf[i].data);
5576	}
5577
5578	for (i = 0; i < OV511_NUMFRAMES; i++) {
5579		ov->frame[i].data = ov->fbuf + i * MAX_DATA_SIZE(w, h);
5580		ov->frame[i].rawdata = ov->rawfbuf
5581		 + i * MAX_RAW_DATA_SIZE(w, h);
5582		ov->frame[i].tempdata = ov->tempfbuf
5583		 + i * MAX_RAW_DATA_SIZE(w, h);
5584
5585		ov->frame[i].compbuf =
5586		 (unsigned char *) __get_free_page(GFP_KERNEL);
5587		if (!ov->frame[i].compbuf)
5588			goto error;
5589
5590		PDEBUG(4, "frame[%d] @ %p", i, ov->frame[i].data);
5591	}
5592
5593	ov->buf_state = BUF_ALLOCATED;
5594out:
5595	up(&ov->buf_lock);
5596	PDEBUG(4, "leaving");
5597	return 0;
5598error:
5599	ov51x_do_dealloc(ov);
5600	up(&ov->buf_lock);
5601	PDEBUG(4, "errored");
5602	return -ENOMEM;
5603}
5604
5605static void
5606ov51x_dealloc(struct usb_ov511 *ov)
5607{
5608	PDEBUG(4, "entered");
5609	down(&ov->buf_lock);
5610	ov51x_do_dealloc(ov);
5611	up(&ov->buf_lock);
5612	PDEBUG(4, "leaving");
5613}
5614
5615/****************************************************************************
5616 *
5617 * V4L 1 API
5618 *
5619 ***************************************************************************/
5620
5621#ifdef OV511_OLD_V4L
5622static int
5623ov51x_v4l1_open(struct video_device *vdev, int flags)
5624{
5625#else
5626static int
5627ov51x_v4l1_open(struct inode *inode, struct file *file)
5628{
5629	struct video_device *vdev = video_devdata(file);
5630#endif
5631	struct usb_ov511 *ov = vdev->priv;
5632	int err, i;
5633
5634/* 2.2.x needs explicit module-locking */
5635#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 17)
5636	MOD_INC_USE_COUNT;
5637#endif
5638
5639	PDEBUG(4, "opening");
5640
5641	down(&ov->lock);
5642
5643	err = -EBUSY;
5644	if (ov->user)
5645		goto out;
5646
5647	ov->sub_flag = 0;
5648
5649	/* In case app doesn't set them... */
5650	err = ov51x_set_default_params(ov);
5651	if (err < 0)
5652		goto out;
5653
5654	/* Make sure frames are reset */
5655	for (i = 0; i < OV511_NUMFRAMES; i++) {
5656		ov->frame[i].grabstate = FRAME_UNUSED;
5657		ov->frame[i].bytes_read = 0;
5658	}
5659
5660	/* If compression is on, make sure now that a
5661	 * decompressor can be loaded */
5662	if (ov->compress && !ov->decomp_ops) {
5663		err = request_decompressor(ov);
5664		if (err && !dumppix)
5665			goto out;
5666	}
5667
5668	err = ov51x_alloc(ov);
5669	if (err < 0)
5670		goto out;
5671
5672	err = ov51x_init_isoc(ov);
5673	if (err) {
5674		ov51x_dealloc(ov);
5675		goto out;
5676	}
5677
5678	ov->user++;
5679// If using _NEW_ V4L...
5680#if !defined(OV511_OLD_V4L)
5681	file->private_data = vdev;
5682#endif
5683
5684	if (ov->led_policy == LED_AUTO)
5685		ov51x_led_control(ov, 1);
5686
5687out:
5688	up(&ov->lock);
5689
5690#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 17)
5691	if (err)
5692		MOD_DEC_USE_COUNT;
5693#endif
5694
5695	return err;
5696}
5697
5698#ifdef OV511_OLD_V4L
5699static void
5700ov51x_v4l1_close(struct video_device *vdev)
5701{
5702#else
5703static int
5704ov51x_v4l1_close(struct inode *inode, struct file *file)
5705{
5706	struct video_device *vdev = file->private_data;
5707#endif
5708	struct usb_ov511 *ov = vdev->priv;
5709
5710	PDEBUG(4, "ov511_close");
5711
5712	down(&ov->lock);
5713
5714	ov->user--;
5715	ov51x_stop_isoc(ov);
5716
5717	release_decompressor(ov);
5718
5719	if (ov->led_policy == LED_AUTO)
5720		ov51x_led_control(ov, 0);
5721
5722	if (ov->dev)
5723		ov51x_dealloc(ov);
5724
5725	up(&ov->lock);
5726
5727	/* Device unplugged while open. Only a minimum of unregistration is done
5728	 * here; the disconnect callback already did the rest. */
5729	if (!ov->dev) {
5730		down(&ov->cbuf_lock);
5731		kfree(ov->cbuf);
5732		ov->cbuf = NULL;
5733		up(&ov->cbuf_lock);
5734
5735		ov51x_dealloc(ov);
5736#ifdef OV511_OLD_V4L
5737		video_unregister_device(&ov->vdev);
5738#endif
5739		kfree(ov);
5740		ov = NULL;
5741	}
5742
5743#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 17)
5744	MOD_DEC_USE_COUNT;
5745#endif
5746
5747#ifdef OV511_OLD_V4L
5748	return;
5749#else
5750	file->private_data = NULL;
5751	return 0;
5752#endif
5753}
5754
5755/* Do not call this function directly! */
5756static int
5757#ifdef OV511_OLD_V4L
5758ov51x_v4l1_ioctl_internal(struct usb_ov511 *ov, unsigned int cmd,
5759			  void *arg)
5760{
5761#else
5762ov51x_v4l1_ioctl_internal(struct inode *inode, struct file *file,
5763			  unsigned int cmd, void *arg)
5764{
5765	struct video_device *vdev = file->private_data;
5766	struct usb_ov511 *ov = vdev->priv;
5767#endif
5768	PDEBUG(5, "IOCtl: 0x%X", cmd);
5769
5770	if (!ov->dev)
5771		return -EIO;
5772
5773	switch (cmd) {
5774	case VIDIOCGCAP:
5775	{
5776		struct video_capability *b = arg;
5777
5778		PDEBUG(4, "VIDIOCGCAP");
5779
5780		memset(b, 0, sizeof(struct video_capability));
5781		sprintf(b->name, "%s USB Camera",
5782			symbolic(brglist, ov->bridge));
5783		b->type = VID_TYPE_CAPTURE | VID_TYPE_SUBCAPTURE;
5784		b->channels = ov->num_inputs;
5785		b->audios = 0;
5786		b->maxwidth = ov->maxwidth;
5787		b->maxheight = ov->maxheight;
5788		b->minwidth = ov->minwidth;
5789		b->minheight = ov->minheight;
5790
5791		return 0;
5792	}
5793	case VIDIOCGCHAN:
5794	{
5795		struct video_channel *v = arg;
5796
5797		PDEBUG(4, "VIDIOCGCHAN");
5798
5799		if ((unsigned)(v->channel) >= ov->num_inputs) {
5800			err("Invalid channel (%d)", v->channel);
5801			return -EINVAL;
5802		}
5803
5804		v->norm = ov->norm;
5805		v->type = VIDEO_TYPE_CAMERA;
5806		v->flags = 0;
5807//		v->flags |= (ov->has_decoder) ? VIDEO_VC_NORM : 0;
5808		v->tuners = 0;
5809		decoder_get_input_name(ov, v->channel, v->name);
5810
5811		return 0;
5812	}
5813	case VIDIOCSCHAN:
5814	{
5815		struct video_channel *v = arg;
5816		int err;
5817
5818		PDEBUG(4, "VIDIOCSCHAN");
5819
5820		/* Make sure it's not a camera */
5821		if (!ov->has_decoder) {
5822			if (v->channel == 0)
5823				return 0;
5824			else
5825				return -EINVAL;
5826		}
5827
5828		if (v->norm != VIDEO_MODE_PAL &&
5829		    v->norm != VIDEO_MODE_NTSC &&
5830		    v->norm != VIDEO_MODE_SECAM &&
5831		    v->norm != VIDEO_MODE_AUTO) {
5832			err("Invalid norm (%d)", v->norm);
5833			return -EINVAL;
5834		}
5835
5836		if ((unsigned)(v->channel) >= ov->num_inputs) {
5837			err("Invalid channel (%d)", v->channel);
5838			return -EINVAL;
5839		}
5840
5841		err = decoder_set_input(ov, v->channel);
5842		if (err)
5843			return err;
5844
5845		err = decoder_set_norm(ov, v->norm);
5846		if (err)
5847			return err;
5848
5849		return 0;
5850	}
5851	case VIDIOCGPICT:
5852	{
5853		struct video_picture *p = arg;
5854
5855		PDEBUG(4, "VIDIOCGPICT");
5856
5857		memset(p, 0, sizeof(struct video_picture));
5858		if (sensor_get_picture(ov, p))
5859			return -EIO;
5860
5861		/* Can we get these from frame[0]? -claudio? */
5862		p->depth = ov->frame[0].depth;
5863		p->palette = ov->frame[0].format;
5864
5865		return 0;
5866	}
5867	case VIDIOCSPICT:
5868	{
5869		struct video_picture *p = arg;
5870		int i, rc;
5871
5872		PDEBUG(4, "VIDIOCSPICT");
5873
5874		if (!get_depth(p->palette))
5875			return -EINVAL;
5876
5877		if (sensor_set_picture(ov, p))
5878			return -EIO;
5879
5880		if (force_palette && p->palette != force_palette) {
5881			info("Palette rejected (%s)",
5882			     symbolic(v4l1_plist, p->palette));
5883			return -EINVAL;
5884		}
5885
5886		// FIXME: Format should be independent of frames
5887		if (p->palette != ov->frame[0].format) {
5888			PDEBUG(4, "Detected format change");
5889
5890			rc = ov51x_wait_frames_inactive(ov);
5891			if (rc)
5892				return rc;
5893
5894			mode_init_regs(ov, ov->frame[0].width,
5895				ov->frame[0].height, p->palette, ov->sub_flag);
5896		}
5897
5898		PDEBUG(4, "Setting depth=%d, palette=%s",
5899		       p->depth, symbolic(v4l1_plist, p->palette));
5900
5901		for (i = 0; i < OV511_NUMFRAMES; i++) {
5902			ov->frame[i].depth = p->depth;
5903			ov->frame[i].format = p->palette;
5904		}
5905
5906		return 0;
5907	}
5908	case VIDIOCGCAPTURE:
5909	{
5910		int *vf = arg;
5911
5912		PDEBUG(4, "VIDIOCGCAPTURE");
5913
5914		ov->sub_flag = *vf;
5915		return 0;
5916	}
5917	case VIDIOCSCAPTURE:
5918	{
5919		struct video_capture *vc = arg;
5920
5921		PDEBUG(4, "VIDIOCSCAPTURE");
5922
5923		if (vc->flags)
5924			return -EINVAL;
5925		if (vc->decimation)
5926			return -EINVAL;
5927
5928		vc->x &= ~3L;
5929		vc->y &= ~1L;
5930		vc->y &= ~31L;
5931
5932		if (vc->width == 0)
5933			vc->width = 32;
5934
5935		vc->height /= 16;
5936		vc->height *= 16;
5937		if (vc->height == 0)
5938			vc->height = 16;
5939
5940		ov->subx = vc->x;
5941		ov->suby = vc->y;
5942		ov->subw = vc->width;
5943		ov->subh = vc->height;
5944
5945		return 0;
5946	}
5947	case VIDIOCSWIN:
5948	{
5949		struct video_window *vw = arg;
5950		int i, rc;
5951
5952		PDEBUG(4, "VIDIOCSWIN: %dx%d", vw->width, vw->height);
5953
5954#if 0
5955		if (vw->flags)
5956			return -EINVAL;
5957		if (vw->clipcount)
5958			return -EINVAL;
5959		if (vw->height != ov->maxheight)
5960			return -EINVAL;
5961		if (vw->width != ov->maxwidth)
5962			return -EINVAL;
5963#endif
5964
5965		rc = ov51x_wait_frames_inactive(ov);
5966		if (rc)
5967			return rc;
5968
5969		rc = mode_init_regs(ov, vw->width, vw->height,
5970			ov->frame[0].format, ov->sub_flag);
5971		if (rc < 0)
5972			return rc;
5973
5974		for (i = 0; i < OV511_NUMFRAMES; i++) {
5975			ov->frame[i].width = vw->width;
5976			ov->frame[i].height = vw->height;
5977		}
5978
5979		return 0;
5980	}
5981	case VIDIOCGWIN:
5982	{
5983		struct video_window *vw = arg;
5984
5985		memset(vw, 0, sizeof(struct video_window));
5986		vw->x = 0;		/* FIXME */
5987		vw->y = 0;
5988		vw->width = ov->frame[0].width;
5989		vw->height = ov->frame[0].height;
5990		vw->flags = 30;
5991
5992		PDEBUG(4, "VIDIOCGWIN: %dx%d", vw->width, vw->height);
5993
5994		return 0;
5995	}
5996	case VIDIOCGMBUF:
5997	{
5998		struct video_mbuf *vm = arg;
5999		int i;
6000
6001		PDEBUG(4, "VIDIOCGMBUF");
6002
6003		memset(vm, 0, sizeof(struct video_mbuf));
6004		vm->size = OV511_NUMFRAMES
6005			   * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
6006		vm->frames = OV511_NUMFRAMES;
6007
6008		vm->offsets[0] = 0;
6009		for (i = 1; i < OV511_NUMFRAMES; i++) {
6010			vm->offsets[i] = vm->offsets[i-1]
6011			   + MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
6012		}
6013
6014		return 0;
6015	}
6016	case VIDIOCMCAPTURE:
6017	{
6018		struct video_mmap *vm = arg;
6019		int rc, depth;
6020		unsigned int f = vm->frame;
6021
6022		PDEBUG(4, "VIDIOCMCAPTURE: frame: %d, %dx%d, %s", f, vm->width,
6023			vm->height, symbolic(v4l1_plist, vm->format));
6024
6025		depth = get_depth(vm->format);
6026		if (!depth) {
6027			PDEBUG(2, "VIDIOCMCAPTURE: invalid format (%s)",
6028			       symbolic(v4l1_plist, vm->format));
6029			return -EINVAL;
6030		}
6031
6032		if (f >= OV511_NUMFRAMES) {
6033			err("VIDIOCMCAPTURE: invalid frame (%d)", f);
6034			return -EINVAL;
6035		}
6036
6037		if (vm->width > ov->maxwidth
6038		    || vm->height > ov->maxheight) {
6039			err("VIDIOCMCAPTURE: requested dimensions too big");
6040			return -EINVAL;
6041		}
6042
6043		if (ov->frame[f].grabstate == FRAME_GRABBING) {
6044			PDEBUG(4, "VIDIOCMCAPTURE: already grabbing");
6045			return -EBUSY;
6046		}
6047
6048		if (force_palette && (vm->format != force_palette)) {
6049			PDEBUG(2, "palette rejected (%s)",
6050			       symbolic(v4l1_plist, vm->format));
6051			return -EINVAL;
6052		}
6053
6054		if ((ov->frame[f].width != vm->width) ||
6055		    (ov->frame[f].height != vm->height) ||
6056		    (ov->frame[f].format != vm->format) ||
6057		    (ov->frame[f].sub_flag != ov->sub_flag) ||
6058		    (ov->frame[f].depth != depth)) {
6059			PDEBUG(4, "VIDIOCMCAPTURE: change in image parameters");
6060
6061			rc = ov51x_wait_frames_inactive(ov);
6062			if (rc)
6063				return rc;
6064
6065			rc = mode_init_regs(ov, vm->width, vm->height,
6066				vm->format, ov->sub_flag);
6067#if 0
6068			if (rc < 0) {
6069				PDEBUG(1, "Got error while initializing regs ");
6070				return ret;
6071			}
6072#endif
6073			ov->frame[f].width = vm->width;
6074			ov->frame[f].height = vm->height;
6075			ov->frame[f].format = vm->format;
6076			ov->frame[f].sub_flag = ov->sub_flag;
6077			ov->frame[f].depth = depth;
6078		}
6079
6080		/* Mark it as ready */
6081		ov->frame[f].grabstate = FRAME_READY;
6082
6083		PDEBUG(4, "VIDIOCMCAPTURE: renewing frame %d", f);
6084
6085		return ov51x_new_frame(ov, f);
6086	}
6087	case VIDIOCSYNC:
6088	{
6089		unsigned int fnum = *((unsigned int *) arg);
6090		struct ov511_frame *frame;
6091		int rc;
6092
6093		if (fnum >= OV511_NUMFRAMES) {
6094			err("VIDIOCSYNC: invalid frame (%d)", fnum);
6095			return -EINVAL;
6096		}
6097
6098		frame = &ov->frame[fnum];
6099
6100		PDEBUG(4, "syncing to frame %d, grabstate = %d", fnum,
6101		       frame->grabstate);
6102
6103		switch (frame->grabstate) {
6104		case FRAME_UNUSED:
6105			return -EINVAL;
6106		case FRAME_READY:
6107		case FRAME_GRABBING:
6108		case FRAME_ERROR:
6109redo:
6110			if (!ov->dev)
6111				return -EIO;
6112
6113			rc = wait_event_interruptible(frame->wq,
6114			    (frame->grabstate == FRAME_DONE)
6115			    || (frame->grabstate == FRAME_ERROR));
6116
6117			if (rc)
6118				return rc;
6119
6120			if (frame->grabstate == FRAME_ERROR) {
6121				if ((rc = ov51x_new_frame(ov, fnum)) < 0)
6122					return rc;
6123				goto redo;
6124			}
6125			/* Fall through */
6126		case FRAME_DONE:
6127			if (ov->snap_enabled && !frame->snapshot) {
6128				if ((rc = ov51x_new_frame(ov, fnum)) < 0)
6129					return rc;
6130				goto redo;
6131			}
6132
6133			frame->grabstate = FRAME_UNUSED;
6134
6135			/* Reset the hardware snapshot button */
6136			/* FIXME - Is this the best place for this? */
6137			if ((ov->snap_enabled) && (frame->snapshot)) {
6138				frame->snapshot = 0;
6139				ov51x_clear_snapshot(ov);
6140			}
6141
6142			/* Decompression, format conversion, etc... */
6143			if (ov->bclass != BCL_OV519) {
6144				ov51x_postprocess(ov, frame);
6145			}
6146
6147			break;
6148		} /* end switch */
6149
6150		return 0;
6151	}
6152	case VIDIOCGFBUF:
6153	{
6154		struct video_buffer *vb = arg;
6155
6156		PDEBUG(4, "VIDIOCGFBUF");
6157
6158		memset(vb, 0, sizeof(struct video_buffer));
6159
6160		return 0;
6161	}
6162	case VIDIOCGUNIT:
6163	{
6164		struct video_unit *vu = arg;
6165
6166		PDEBUG(4, "VIDIOCGUNIT");
6167
6168		memset(vu, 0, sizeof(struct video_unit));
6169
6170		vu->video = ov->vdev.minor;
6171		vu->vbi = VIDEO_NO_UNIT;
6172		vu->radio = VIDEO_NO_UNIT;
6173		vu->audio = VIDEO_NO_UNIT;
6174		vu->teletext = VIDEO_NO_UNIT;
6175
6176		return 0;
6177	}
6178	case OV511IOC_WI2C:
6179	{
6180		struct ov511_i2c_struct *w = arg;
6181
6182		return i2c_w_slave(ov, w->slave, w->reg, w->value, w->mask);
6183	}
6184	case OV511IOC_RI2C:
6185	{
6186		struct ov511_i2c_struct *r = arg;
6187		int rc;
6188
6189		rc = i2c_r_slave(ov, r->slave, r->reg);
6190		if (rc < 0)
6191			return rc;
6192
6193		r->value = rc;
6194		return 0;
6195	}
6196	default:
6197		PDEBUG(3, "Unsupported IOCtl: 0x%X", cmd);
6198		return -ENOIOCTLCMD;
6199	} /* end switch */
6200
6201	return 0;
6202}
6203
6204#ifdef OV511_OLD_V4L
6205/* This is implemented as video_generic_ioctl() in the new V4L's videodev.c */
6206static int
6207ov51x_v4l1_generic_ioctl(struct video_device *vdev, unsigned int cmd, void *arg)
6208{
6209	char	sbuf[128];
6210	void    *mbuf = NULL;
6211	void	*parg = NULL;
6212	int	err  = -EINVAL;
6213
6214	/*  Copy arguments into temp kernel buffer  */
6215	switch (_IOC_DIR(cmd)) {
6216	case _IOC_NONE:
6217		parg = arg;
6218		break;
6219	case _IOC_READ: /* some v4l ioctls are marked wrong ... */
6220	case _IOC_WRITE:
6221	case (_IOC_WRITE | _IOC_READ):
6222		if (_IOC_SIZE(cmd) <= sizeof(sbuf)) {
6223			parg = sbuf;
6224		} else {
6225			/* too big to allocate from stack */
6226			mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL);
6227			if (NULL == mbuf)
6228				return -ENOMEM;
6229			parg = mbuf;
6230		}
6231
6232		err = -EFAULT;
6233		if (copy_from_user(parg, arg, _IOC_SIZE(cmd)))
6234			goto out;
6235		break;
6236	}
6237
6238	err = ov51x_v4l1_ioctl_internal(vdev->priv, cmd, parg);
6239	if (err == -ENOIOCTLCMD)
6240		err = -EINVAL;
6241	if (err < 0)
6242		goto out;
6243
6244	/*  Copy results into user buffer  */
6245	switch (_IOC_DIR(cmd))
6246	{
6247	case _IOC_READ:
6248	case (_IOC_WRITE | _IOC_READ):
6249		if (copy_to_user(arg, parg, _IOC_SIZE(cmd)))
6250			err = -EFAULT;
6251		break;
6252	}
6253
6254out:
6255	if (mbuf)
6256		kfree(mbuf);
6257	return err;
6258}
6259
6260static int
6261ov51x_v4l1_ioctl(struct video_device *vdev, unsigned int cmd, void *arg)
6262{
6263	struct usb_ov511 *ov = vdev->priv;
6264	int rc;
6265
6266	if (down_interruptible(&ov->lock))
6267		return -EINTR;
6268
6269	rc = ov51x_v4l1_generic_ioctl(vdev, cmd, arg);
6270
6271	up(&ov->lock);
6272	return rc;
6273}
6274
6275#else	/* If new V4L API */
6276
6277static int
6278ov51x_v4l1_ioctl(struct inode *inode, struct file *file,
6279		 unsigned int cmd, unsigned long arg)
6280{
6281	struct video_device *vdev = file->private_data;
6282	struct usb_ov511 *ov = vdev->priv;
6283	int rc;
6284
6285	if (down_interruptible(&ov->lock))
6286		return -EINTR;
6287
6288	rc = video_usercopy(inode, file, cmd, arg, ov51x_v4l1_ioctl_internal);
6289
6290	up(&ov->lock);
6291	return rc;
6292}
6293#endif	/* OV511_OLD_V4L */
6294
6295#ifdef OV511_OLD_V4L
6296static inline long
6297ov51x_v4l1_read(struct video_device *vdev, char *buf, unsigned long count,
6298		int noblock)
6299{
6300#else
6301static inline int
6302ov51x_v4l1_read(struct file *file, char *buf, size_t cnt, loff_t *ppos)
6303{
6304	struct video_device *vdev = file->private_data;
6305	int noblock = file->f_flags&O_NONBLOCK;
6306	unsigned long count = cnt;
6307#endif
6308	struct usb_ov511 *ov = vdev->priv;
6309	int i, rc = 0, frmx = -1;
6310	struct ov511_frame *frame;
6311
6312	if (down_interruptible(&ov->lock))
6313		return -EINTR;
6314
6315	PDEBUG(4, "%ld bytes, noblock=%d", count, noblock);
6316
6317	if (!vdev || !buf) {
6318		rc = -EFAULT;
6319		goto error;
6320	}
6321
6322	if (!ov->dev) {
6323		rc = -EIO;
6324		goto error;
6325	}
6326
6327// FIXME: Only supports two frames
6328	/* See if a frame is completed, then use it. */
6329	if (ov->frame[0].grabstate >= FRAME_DONE)	/* _DONE or _ERROR */
6330		frmx = 0;
6331	else if (ov->frame[1].grabstate >= FRAME_DONE)/* _DONE or _ERROR */
6332		frmx = 1;
6333
6334	/* If nonblocking we return immediately */
6335	if (noblock && (frmx == -1)) {
6336		rc = -EAGAIN;
6337		goto error;
6338	}
6339
6340	/* If no FRAME_DONE, look for a FRAME_GRABBING state. */
6341	/* See if a frame is in process (grabbing), then use it. */
6342	if (frmx == -1) {
6343		if (ov->frame[0].grabstate == FRAME_GRABBING)
6344			frmx = 0;
6345		else if (ov->frame[1].grabstate == FRAME_GRABBING)
6346			frmx = 1;
6347	}
6348
6349	/* If no frame is active, start one. */
6350	if (frmx == -1) {
6351		if ((rc = ov51x_new_frame(ov, frmx = 0))) {
6352			err("read: ov51x_new_frame error");
6353			goto error;
6354		}
6355	}
6356
6357	frame = &ov->frame[frmx];
6358
6359restart:
6360	if (!ov->dev) {
6361		rc = -EIO;
6362		goto error;
6363	}
6364
6365	/* Wait while we're grabbing the image */
6366	PDEBUG(4, "Waiting image grabbing");
6367	rc = wait_event_interruptible(frame->wq,
6368		(frame->grabstate == FRAME_DONE)
6369		|| (frame->grabstate == FRAME_ERROR));
6370
6371	if (rc)
6372		goto error;
6373
6374	PDEBUG(4, "Got image, frame->grabstate = %d", frame->grabstate);
6375	PDEBUG(4, "bytes_recvd = %d", frame->bytes_recvd);
6376
6377	if (frame->grabstate == FRAME_ERROR) {
6378		frame->bytes_read = 0;
6379		err("** ick! ** Errored frame %d", ov->curframe);
6380		if (ov51x_new_frame(ov, frmx)) {
6381			err("read: ov51x_new_frame error");
6382			goto error;
6383		}
6384		goto restart;
6385	}
6386
6387
6388	/* Repeat until we get a snapshot frame */
6389	if (ov->snap_enabled)
6390		PDEBUG(4, "Waiting snapshot frame");
6391	if (ov->snap_enabled && !frame->snapshot) {
6392		frame->bytes_read = 0;
6393		if ((rc = ov51x_new_frame(ov, frmx))) {
6394			err("read: ov51x_new_frame error");
6395			goto error;
6396		}
6397		goto restart;
6398	}
6399
6400	/* Clear the snapshot */
6401	if (ov->snap_enabled && frame->snapshot) {
6402		frame->snapshot = 0;
6403		ov51x_clear_snapshot(ov);
6404	}
6405
6406	/* Decompression, format conversion, etc... */
6407	if (ov->bclass != BCL_OV519) {
6408		ov51x_postprocess(ov, frame);
6409	}
6410
6411	PDEBUG(4, "frmx=%d, bytes_read=%ld, length=%ld", frmx,
6412		frame->bytes_read,
6413		get_frame_length(ov, frame));
6414
6415	/* copy bytes to user space; we allow for partials reads */
6416	if ((count + frame->bytes_read) > get_frame_length(ov, (struct ov511_frame *)frame)) {
6417		count = frame->bytes_recvd - frame->bytes_read;
6418		PDEBUG(4, "set count to %d", (int)count);
6419	}
6420
6421	/* FIXME - count hardwired to be one frame... */
6422	//count = get_frame_length(ov, frame);
6423
6424	PDEBUG(4, "Copy to user space: %ld bytes", count);
6425	if ((i = copy_to_user(buf, frame->data + frame->bytes_read, count))) {
6426		PDEBUG(4, "Copy failed! %d bytes not copied", i);
6427		rc = -EFAULT;
6428		goto error;
6429	}
6430
6431	frame->bytes_read += count;
6432	PDEBUG(4, "{copy} count used=%ld, new bytes_read=%ld",
6433		count, frame->bytes_read);
6434
6435	/* If all data have been read... */
6436	if (frame->bytes_read >= get_frame_length(ov, frame)) {
6437		frame->bytes_read = 0;
6438
6439// FIXME: Only supports two frames
6440		/* Mark it as available to be used again. */
6441		ov->frame[frmx].grabstate = FRAME_UNUSED;
6442		if ((rc = ov51x_new_frame(ov, !frmx))) {
6443			err("ov51x_new_frame returned error");
6444			goto error;
6445		}
6446	}
6447
6448	PDEBUG(4, "read finished, returning %ld (sweet)", count);
6449
6450	up(&ov->lock);
6451	return count;
6452
6453error:
6454	up(&ov->lock);
6455	return rc;
6456}
6457
6458static int
6459#ifdef OV511_OLD_V4L
6460  #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 3)
6461ov51x_v4l1_mmap(struct vm_area_struct *vma, struct video_device *vdev,
6462		const char *adr, unsigned long size)
6463  #else
6464ov51x_v4l1_mmap(struct video_device *vdev, const char *adr, unsigned long size)
6465  #endif	/* LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 3) */
6466{
6467	unsigned long start = (unsigned long)adr;
6468
6469#else	/* New V4L API */
6470
6471ov51x_v4l1_mmap(struct file *file, struct vm_area_struct *vma)
6472{
6473	struct video_device *vdev = file->private_data;
6474	unsigned long start = vma->vm_start;
6475	unsigned long size  = vma->vm_end - vma->vm_start;
6476#endif	/* OV511_OLD_V4L */
6477
6478	struct usb_ov511 *ov = vdev->priv;
6479	unsigned long page, pos;
6480
6481	if (ov->dev == NULL)
6482		return -EIO;
6483
6484	PDEBUG(4, "mmap: %ld (%lX) bytes", size, size);
6485
6486	if (size > (((OV511_NUMFRAMES
6487	              * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight)
6488	              + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))))
6489		return -EINVAL;
6490
6491	if (down_interruptible(&ov->lock))
6492		return -EINTR;
6493
6494	pos = (unsigned long)ov->fbuf;
6495	while (size > 0) {
6496		page = kvirt_to_pa(pos);
6497#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 3)
6498		if (remap_page_range(vma, start, page, PAGE_SIZE,
6499				     PAGE_SHARED)) {
6500#else
6501		if (remap_page_range(start, page, PAGE_SIZE, PAGE_SHARED)) {
6502#endif
6503			up(&ov->lock);
6504			return -EAGAIN;
6505		}
6506		start += PAGE_SIZE;
6507		pos += PAGE_SIZE;
6508		if (size > PAGE_SIZE)
6509			size -= PAGE_SIZE;
6510		else
6511			size = 0;
6512	}
6513
6514	up(&ov->lock);
6515	return 0;
6516}
6517
6518#ifdef OV511_OLD_V4L
6519static struct video_device vdev_template = {
6520#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 17)
6521	.owner =	THIS_MODULE,
6522#endif
6523	.name =		"OV511 USB Camera",
6524	.type =		VID_TYPE_CAPTURE,
6525	.hardware =	VID_HARDWARE_OV511,
6526	.open =		ov51x_v4l1_open,
6527	.close =	ov51x_v4l1_close,
6528	.read =		ov51x_v4l1_read,
6529	.ioctl =	ov51x_v4l1_ioctl,
6530	.mmap =		ov51x_v4l1_mmap,
6531};
6532
6533#else	/* New V4L API */
6534
6535static struct file_operations ov511_fops = {
6536	.owner =	THIS_MODULE,
6537	.open =		ov51x_v4l1_open,
6538	.release =	ov51x_v4l1_close,
6539	.read =		ov51x_v4l1_read,
6540	.mmap =		ov51x_v4l1_mmap,
6541	.ioctl =	ov51x_v4l1_ioctl,
6542	.llseek =	no_llseek,
6543};
6544
6545static struct video_device vdev_template = {
6546	.owner =	THIS_MODULE,
6547	.name =		"OV51x USB Camera",
6548	.type =		VID_TYPE_CAPTURE,
6549	.hardware =	VID_HARDWARE_OV511,
6550	.fops =		&ov511_fops,
6551};
6552#endif	/* OV511_OLD_V4L */
6553
6554#if defined(CONFIG_VIDEO_PROC_FS)
6555static int
6556ov51x_control_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
6557		    unsigned long ularg)
6558{
6559#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 5)
6560	struct proc_dir_entry *pde = PDE(inode);
6561#else
6562	struct proc_dir_entry *pde = inode->u.generic_ip;
6563#endif
6564	struct usb_ov511 *ov;
6565	void *arg = (void *) ularg;
6566	int rc;
6567
6568	if (!pde)
6569		return -ENOENT;
6570
6571	ov = pde->data;
6572	if (!ov)
6573		return -ENODEV;
6574
6575	if (!ov->dev)
6576		return -EIO;
6577
6578	/* Should we pass through standard V4L IOCTLs? */
6579
6580	switch (cmd) {
6581	case OV511IOC_GINTVER:
6582	{
6583		return OV511_INTERFACE_VER;
6584	}
6585	case OV511IOC_GUSHORT:
6586	{
6587		struct ov511_ushort_opt opt;
6588
6589		if (copy_from_user(&opt, arg, sizeof(opt)))
6590			return -EFAULT;
6591
6592		switch (opt.optnum) {
6593		case OV511_USOPT_BRIGHT:
6594			rc = sensor_get_brightness(ov, &(opt.val));
6595			if (rc)	return rc;
6596			break;
6597		case OV511_USOPT_SAT:
6598			rc = sensor_get_saturation(ov, &(opt.val));
6599			if (rc)	return rc;
6600			break;
6601		case OV511_USOPT_HUE:
6602			rc = sensor_get_hue(ov, &(opt.val));
6603			if (rc)	return rc;
6604			break;
6605		case OV511_USOPT_CONTRAST:
6606			rc = sensor_get_contrast(ov, &(opt.val));
6607			if (rc)	return rc;
6608			break;
6609		default:
6610			err("Invalid get short option number");
6611			return -EINVAL;
6612		}
6613
6614		if (copy_to_user(arg, &opt, sizeof(opt)))
6615			return -EFAULT;
6616
6617		return 0;
6618	}
6619	case OV511IOC_SUSHORT:
6620	{
6621		struct ov511_ushort_opt opt;
6622
6623		if (copy_from_user(&opt, arg, sizeof(opt)))
6624			return -EFAULT;
6625
6626		switch (opt.optnum) {
6627		case OV511_USOPT_BRIGHT:
6628			rc = sensor_set_brightness(ov, opt.val);
6629			if (rc)	return rc;
6630			break;
6631		case OV511_USOPT_SAT:
6632			rc = sensor_set_saturation(ov, opt.val);
6633			if (rc)	return rc;
6634			break;
6635		case OV511_USOPT_HUE:
6636			rc = sensor_set_hue(ov, opt.val);
6637			if (rc)	return rc;
6638			break;
6639		case OV511_USOPT_CONTRAST:
6640			rc = sensor_set_contrast(ov, opt.val);
6641			if (rc)	return rc;
6642			break;
6643		default:
6644			err("Invalid set short option number");
6645			return -EINVAL;
6646		}
6647
6648		return 0;
6649	}
6650	case OV511IOC_GUINT:
6651	{
6652		struct ov511_uint_opt opt;
6653
6654		if (copy_from_user(&opt, arg, sizeof(opt)))
6655			return -EFAULT;
6656
6657		switch (opt.optnum) {
6658		case OV511_UIOPT_POWER_FREQ:
6659			opt.val = ov->lightfreq;
6660			break;
6661		case OV511_UIOPT_BFILTER:
6662			opt.val = ov->bandfilt;
6663			break;
6664		case OV511_UIOPT_LED:
6665			opt.val = ov->led_policy;
6666			break;
6667		case OV511_UIOPT_LED2:
6668			opt.val = ov->led2_policy;
6669			break;
6670		case OV511_UIOPT_DEBUG:
6671			opt.val = debug;
6672			break;
6673		case OV511_UIOPT_COMPRESS:
6674			opt.val = ov->compress;
6675			break;
6676		default:
6677			err("Invalid get int option number");
6678			return -EINVAL;
6679		}
6680
6681		if (copy_to_user(arg, &opt, sizeof(opt)))
6682			return -EFAULT;
6683
6684		return 0;
6685	}
6686	case OV511IOC_SUINT:
6687	{
6688		struct ov511_uint_opt opt;
6689
6690		if (copy_from_user(&opt, arg, sizeof(opt)))
6691			return -EFAULT;
6692
6693		switch (opt.optnum) {
6694		case OV511_UIOPT_POWER_FREQ:
6695			rc = sensor_set_light_freq(ov, opt.val);
6696			if (rc)	return rc;
6697			break;
6698		case OV511_UIOPT_BFILTER:
6699			rc = sensor_set_banding_filter(ov, opt.val);
6700			if (rc)	return rc;
6701			break;
6702		case OV511_UIOPT_LED:
6703			if (opt.val <= 2) {
6704				ov->led_policy = opt.val;
6705				if (ov->led_policy == LED_OFF)
6706					ov51x_led_control(ov, 0);
6707				else if (ov->led_policy == LED_ON)
6708					ov51x_led_control(ov, 1);
6709			} else {
6710				return -EINVAL;
6711			}
6712			break;
6713		case OV511_UIOPT_LED2:
6714			if (opt.val <= 2) {
6715				ov->led2_policy = opt.val;
6716				if (ov->led2_policy == LED_OFF)
6717					ov51x_led_control(ov, 0);
6718				else if (ov->led2_policy == LED_ON)
6719					ov51x_led_control(ov, 1);
6720			} else {
6721				return -EINVAL;
6722			}
6723			break;
6724		case OV511_UIOPT_DEBUG:
6725			if (opt.val <= 5)
6726				debug = opt.val;
6727			else
6728				return -EINVAL;
6729			break;
6730		case OV511_UIOPT_COMPRESS:
6731			ov->compress = opt.val;
6732			if (ov->compress) {
6733				if (ov->bclass == BCL_OV511)
6734					ov511_init_compression(ov);
6735				else if (ov->bclass == BCL_OV518)
6736					ov518_init_compression(ov);
6737				else if (ov->bclass == BCL_OV519)
6738					ov519_init_compression(ov);
6739			}
6740			break;
6741		default:
6742			err("Invalid get int option number");
6743			return -EINVAL;
6744		}
6745
6746		return 0;
6747	}
6748	case OV511IOC_WI2C:
6749	{
6750		struct ov511_i2c_struct w;
6751
6752		if (copy_from_user(&w, arg, sizeof(w)))
6753			return -EFAULT;
6754
6755		return i2c_w_slave(ov, w.slave, w.reg, w.value,	w.mask);
6756	}
6757	case OV511IOC_RI2C:
6758	{
6759		struct ov511_i2c_struct r;
6760
6761		if (copy_from_user(&r, arg, sizeof(r)))
6762			return -EFAULT;
6763
6764		rc = i2c_r_slave(ov, r.slave, r.reg);
6765		if (rc < 0)
6766			return rc;
6767
6768		r.value = rc;
6769
6770		if (copy_to_user(arg, &r, sizeof(r)))
6771			return -EFAULT;
6772
6773		return 0;
6774	}
6775	default:
6776		return -EINVAL;
6777	}
6778
6779	return 0;
6780}
6781#endif
6782
6783/****************************************************************************
6784 *
6785 * OV511 and sensor configuration
6786 *
6787 ***************************************************************************/
6788
6789/* This initializes the OV8110, OV8610 sensor. The OV8110 uses
6790 * the same register settings as the OV8610, since they are very similar.
6791 */
6792static int
6793ov8xx0_configure(struct usb_ov511 *ov)
6794{
6795	int rc;
6796
6797	static struct ov511_regvals regvals_norm_8610[] = {
6798		{ OV511_I2C_BUS, 0x12, 0x80 },
6799		{ OV511_I2C_BUS, 0x00, 0x00 },
6800		{ OV511_I2C_BUS, 0x01, 0x80 },
6801		{ OV511_I2C_BUS, 0x02, 0x80 },
6802		{ OV511_I2C_BUS, 0x03, 0xc0 },
6803		{ OV511_I2C_BUS, 0x04, 0x30 },
6804		{ OV511_I2C_BUS, 0x05, 0x30 }, /* was 0x10, new from windrv 090403 */
6805		{ OV511_I2C_BUS, 0x06, 0x70 }, /* was 0x80, new from windrv 090403 */
6806		{ OV511_I2C_BUS, 0x0a, 0x86 },
6807		{ OV511_I2C_BUS, 0x0b, 0xb0 },
6808		{ OV511_I2C_BUS, 0x0c, 0x20 },
6809		{ OV511_I2C_BUS, 0x0d, 0x20 },
6810		{ OV511_I2C_BUS, 0x11, 0x01 },
6811		{ OV511_I2C_BUS, 0x12, 0x25 },
6812		{ OV511_I2C_BUS, 0x13, 0x01 },
6813		{ OV511_I2C_BUS, 0x14, 0x04 },
6814		{ OV511_I2C_BUS, 0x15, 0x01 }, /* Lin and Win think different about UV order */
6815		{ OV511_I2C_BUS, 0x16, 0x03 },
6816		{ OV511_I2C_BUS, 0x17, 0x38 }, /* was 0x2f, new from windrv 090403 */
6817		{ OV511_I2C_BUS, 0x18, 0xea }, /* was 0xcf, new from windrv 090403 */
6818		{ OV511_I2C_BUS, 0x19, 0x02 }, /* was 0x06, new from windrv 090403 */
6819		{ OV511_I2C_BUS, 0x1a, 0xf5 },
6820		{ OV511_I2C_BUS, 0x1b, 0x00 },
6821		{ OV511_I2C_BUS, 0x20, 0xd0 }, /* was 0x90, new from windrv 090403 */
6822		{ OV511_I2C_BUS, 0x23, 0xc0 }, /* was 0x00, new from windrv 090403 */
6823		{ OV511_I2C_BUS, 0x24, 0x30 }, /* was 0x1d, new from windrv 090403 */
6824		{ OV511_I2C_BUS, 0x25, 0x50 }, /* was 0x57, new from windrv 090403 */
6825		{ OV511_I2C_BUS, 0x26, 0xa2 },
6826		{ OV511_I2C_BUS, 0x27, 0xea },
6827		{ OV511_I2C_BUS, 0x28, 0x00 },
6828		{ OV511_I2C_BUS, 0x29, 0x00 },
6829		{ OV511_I2C_BUS, 0x2a, 0x80 },
6830		{ OV511_I2C_BUS, 0x2b, 0xc8 }, /* was 0xcc, new from windrv 090403 */
6831		{ OV511_I2C_BUS, 0x2c, 0xac },
6832		{ OV511_I2C_BUS, 0x2d, 0x45 }, /* was 0xd5, new from windrv 090403 */
6833		{ OV511_I2C_BUS, 0x2e, 0x80 },
6834		{ OV511_I2C_BUS, 0x2f, 0x14 }, /* was 0x01, new from windrv 090403 */
6835		{ OV511_I2C_BUS, 0x4c, 0x00 },
6836		{ OV511_I2C_BUS, 0x4d, 0x30 }, /* was 0x10, new from windrv 090403 */
6837		{ OV511_I2C_BUS, 0x60, 0x02 }, /* was 0x01, new from windrv 090403 */
6838		{ OV511_I2C_BUS, 0x61, 0x00 }, /* was 0x09, new from windrv 090403 */
6839		{ OV511_I2C_BUS, 0x62, 0x5f }, /* was 0xd7, new from windrv 090403 */
6840		{ OV511_I2C_BUS, 0x63, 0xff },
6841		{ OV511_I2C_BUS, 0x64, 0x53 }, /* new windrv 090403 says 0x57, maybe thats wrong */
6842		{ OV511_I2C_BUS, 0x65, 0x00 },
6843		{ OV511_I2C_BUS, 0x66, 0x55 },
6844		{ OV511_I2C_BUS, 0x67, 0xb0 },
6845		{ OV511_I2C_BUS, 0x68, 0xc0 }, /* was 0xaf, new from windrv 090403 */
6846		{ OV511_I2C_BUS, 0x69, 0x02 },
6847		{ OV511_I2C_BUS, 0x6a, 0x22 },
6848		{ OV511_I2C_BUS, 0x6b, 0x00 },
6849		{ OV511_I2C_BUS, 0x6c, 0x99 }, /* was 0x80, old windrv says 0x00, but deleting bit7 colors the first images red */
6850		{ OV511_I2C_BUS, 0x6d, 0x11 }, /* was 0x00, new from windrv 090403 */
6851		{ OV511_I2C_BUS, 0x6e, 0x11 }, /* was 0x00, new from windrv 090403 */
6852		{ OV511_I2C_BUS, 0x6f, 0x01 },
6853		{ OV511_I2C_BUS, 0x70, 0x8b },
6854		{ OV511_I2C_BUS, 0x71, 0x00 },
6855		{ OV511_I2C_BUS, 0x72, 0x14 },
6856		{ OV511_I2C_BUS, 0x73, 0x54 },
6857		{ OV511_I2C_BUS, 0x74, 0x00 },//0x60? /* was 0x00, new from windrv 090403 */
6858		{ OV511_I2C_BUS, 0x75, 0x0e },
6859		{ OV511_I2C_BUS, 0x76, 0x02 }, /* was 0x02, new from windrv 090403 */
6860		{ OV511_I2C_BUS, 0x77, 0xff },
6861		{ OV511_I2C_BUS, 0x78, 0x80 },
6862		{ OV511_I2C_BUS, 0x79, 0x80 },
6863		{ OV511_I2C_BUS, 0x7a, 0x80 },
6864		{ OV511_I2C_BUS, 0x7b, 0x10 }, /* was 0x13, new from windrv 090403 */
6865		{ OV511_I2C_BUS, 0x7c, 0x00 },
6866		{ OV511_I2C_BUS, 0x7d, 0x08 }, /* was 0x09, new from windrv 090403 */
6867		{ OV511_I2C_BUS, 0x7e, 0x08 }, /* was 0xc0, new from windrv 090403 */
6868		{ OV511_I2C_BUS, 0x7f, 0xfb },
6869		{ OV511_I2C_BUS, 0x80, 0x28 },
6870		{ OV511_I2C_BUS, 0x81, 0x00 },
6871		{ OV511_I2C_BUS, 0x82, 0x23 },
6872		{ OV511_I2C_BUS, 0x83, 0x0b },
6873		{ OV511_I2C_BUS, 0x84, 0x00 },
6874		{ OV511_I2C_BUS, 0x85, 0x62 }, /* was 0x61, new from windrv 090403 */
6875		{ OV511_I2C_BUS, 0x86, 0xc9 },
6876		{ OV511_I2C_BUS, 0x87, 0x00 },
6877		{ OV511_I2C_BUS, 0x88, 0x00 },
6878		{ OV511_I2C_BUS, 0x89, 0x01 },
6879		{ OV511_I2C_BUS, 0x12, 0x20 },
6880		{ OV511_I2C_BUS, 0x12, 0x25 }, /* was 0x24, new from windrv 090403 */
6881		{ OV511_DONE_BUS, 0x0, 0x00 },
6882	};
6883
6884	PDEBUG(4, "starting configuration");
6885
6886	if (init_ov_sensor(ov) < 0) {
6887		err("Failed to read sensor ID. You might not have an");
6888		err("OV8600/10, or it might not be responding. Report");
6889		err("this to <joerg@heckenbach-aw.de");
6890		err("This is only a warning. You can attempt to use");
6891		err("your camera anyway");
6892	} else {
6893		PDEBUG(1, "OV86x0 initialized");
6894	}
6895
6896	/* Detect sensor (sub)type */
6897	rc = i2c_r(ov, OV7610_REG_COM_I);
6898
6899	if (rc < 0) {
6900		err("Error detecting sensor type");
6901		return -1;
6902	} else if ((rc & 3) == 1) {
6903		info("Sensor is an OV8610");
6904		ov->sensor = SEN_OV8610;
6905	} else {
6906		err("Unknown image sensor version: %d", rc & 3);
6907		return -1;
6908	}
6909
6910	PDEBUG(4, "Writing 8610 registers");
6911	if (write_regvals(ov, regvals_norm_8610))
6912		return -1;
6913
6914	/* Set sensor-specific vars */
6915	ov->maxwidth = 800;
6916	ov->maxheight = 600;
6917	ov->minwidth = 64;
6918	ov->minheight = 48;
6919
6920	// FIXME: These do not match the actual settings yet
6921	ov->brightness = 0x80 << 8;
6922	ov->contrast = 0x80 << 8;
6923	ov->colour = 0x80 << 8;
6924	ov->hue = 0x80 << 8;
6925
6926	return 0;
6927}
6928
6929/* This initializes the OV7610, OV7620, or OV76BE sensor. The OV76BE uses
6930 * the same register settings as the OV7610, since they are very similar.
6931 */
6932static int
6933ov7xx0_configure(struct usb_ov511 *ov)
6934{
6935	int rc, high, low;
6936
6937	/* Lawrence Glaister <lg@jfm.bc.ca> reports:
6938	 *
6939	 * Register 0x0f in the 7610 has the following effects:
6940	 *
6941	 * 0x85 (AEC method 1): Best overall, good contrast range
6942	 * 0x45 (AEC method 2): Very overexposed
6943	 * 0xa5 (spec sheet default): Ok, but the black level is
6944	 *	shifted resulting in loss of contrast
6945	 * 0x05 (old driver setting): very overexposed, too much
6946	 *	contrast
6947	 */
6948	static struct ov511_regvals regvals_norm_7610[] = {
6949		{ OV511_I2C_BUS, 0x10, 0xff },
6950		{ OV511_I2C_BUS, 0x16, 0x06 },
6951		{ OV511_I2C_BUS, 0x28, 0x24 },
6952		{ OV511_I2C_BUS, 0x2b, 0xac },
6953		{ OV511_I2C_BUS, 0x12, 0x00 },
6954		{ OV511_I2C_BUS, 0x38, 0x81 },
6955		{ OV511_I2C_BUS, 0x28, 0x24 },	/* 0c */
6956		{ OV511_I2C_BUS, 0x0f, 0x85 },	/* lg's setting */
6957		{ OV511_I2C_BUS, 0x15, 0x01 },
6958		{ OV511_I2C_BUS, 0x20, 0x1c },
6959		{ OV511_I2C_BUS, 0x23, 0x2a },
6960		{ OV511_I2C_BUS, 0x24, 0x10 },
6961		{ OV511_I2C_BUS, 0x25, 0x8a },
6962		{ OV511_I2C_BUS, 0x26, 0xa2 },
6963		{ OV511_I2C_BUS, 0x27, 0xc2 },
6964		{ OV511_I2C_BUS, 0x2a, 0x04 },
6965		{ OV511_I2C_BUS, 0x2c, 0xfe },
6966		{ OV511_I2C_BUS, 0x2d, 0x93 },
6967		{ OV511_I2C_BUS, 0x30, 0x71 },
6968		{ OV511_I2C_BUS, 0x31, 0x60 },
6969		{ OV511_I2C_BUS, 0x32, 0x26 },
6970		{ OV511_I2C_BUS, 0x33, 0x20 },
6971		{ OV511_I2C_BUS, 0x34, 0x48 },
6972		{ OV511_I2C_BUS, 0x12, 0x24 },
6973		{ OV511_I2C_BUS, 0x11, 0x01 },
6974		{ OV511_I2C_BUS, 0x0c, 0x24 },
6975		{ OV511_I2C_BUS, 0x0d, 0x24 },
6976		{ OV511_DONE_BUS, 0x0, 0x00 },
6977	};
6978
6979	static struct ov511_regvals regvals_norm_7620[] = {
6980		{ OV511_I2C_BUS, 0x00, 0x00 },
6981		{ OV511_I2C_BUS, 0x01, 0x80 },
6982		{ OV511_I2C_BUS, 0x02, 0x80 },
6983		{ OV511_I2C_BUS, 0x03, 0xc0 },
6984		{ OV511_I2C_BUS, 0x06, 0x60 },
6985		{ OV511_I2C_BUS, 0x07, 0x00 },
6986		{ OV511_I2C_BUS, 0x0c, 0x24 },
6987		{ OV511_I2C_BUS, 0x0c, 0x24 },
6988		{ OV511_I2C_BUS, 0x0d, 0x24 },
6989		{ OV511_I2C_BUS, 0x11, 0x01 },
6990		{ OV511_I2C_BUS, 0x12, 0x24 },
6991		{ OV511_I2C_BUS, 0x13, 0x01 },
6992		{ OV511_I2C_BUS, 0x14, 0x84 },
6993		{ OV511_I2C_BUS, 0x15, 0x01 },
6994		{ OV511_I2C_BUS, 0x16, 0x03 },
6995		{ OV511_I2C_BUS, 0x17, 0x2f },
6996		{ OV511_I2C_BUS, 0x18, 0xcf },
6997		{ OV511_I2C_BUS, 0x19, 0x06 },
6998		{ OV511_I2C_BUS, 0x1a, 0xf5 },
6999		{ OV511_I2C_BUS, 0x1b, 0x00 },
7000		{ OV511_I2C_BUS, 0x20, 0x18 },
7001		{ OV511_I2C_BUS, 0x21, 0x80 },
7002		{ OV511_I2C_BUS, 0x22, 0x80 },
7003		{ OV511_I2C_BUS, 0x23, 0x00 },
7004		{ OV511_I2C_BUS, 0x26, 0xa2 },
7005		{ OV511_I2C_BUS, 0x27, 0xea },
7006		{ OV511_I2C_BUS, 0x28, 0x20 },
7007		{ OV511_I2C_BUS, 0x29, 0x00 },
7008		{ OV511_I2C_BUS, 0x2a, 0x10 },
7009		{ OV511_I2C_BUS, 0x2b, 0x00 },
7010		{ OV511_I2C_BUS, 0x2c, 0x88 },
7011		{ OV511_I2C_BUS, 0x2d, 0x91 },
7012		{ OV511_I2C_BUS, 0x2e, 0x80 },
7013		{ OV511_I2C_BUS, 0x2f, 0x44 },
7014		{ OV511_I2C_BUS, 0x60, 0x27 },
7015		{ OV511_I2C_BUS, 0x61, 0x02 },
7016		{ OV511_I2C_BUS, 0x62, 0x5f },
7017		{ OV511_I2C_BUS, 0x63, 0xd5 },
7018		{ OV511_I2C_BUS, 0x64, 0x57 },
7019		{ OV511_I2C_BUS, 0x65, 0x83 },
7020		{ OV511_I2C_BUS, 0x66, 0x55 },
7021		{ OV511_I2C_BUS, 0x67, 0x92 },
7022		{ OV511_I2C_BUS, 0x68, 0xcf },
7023		{ OV511_I2C_BUS, 0x69, 0x76 },
7024		{ OV511_I2C_BUS, 0x6a, 0x22 },
7025		{ OV511_I2C_BUS, 0x6b, 0x00 },
7026		{ OV511_I2C_BUS, 0x6c, 0x02 },
7027		{ OV511_I2C_BUS, 0x6d, 0x44 },
7028		{ OV511_I2C_BUS, 0x6e, 0x80 },
7029		{ OV511_I2C_BUS, 0x6f, 0x1d },
7030		{ OV511_I2C_BUS, 0x70, 0x8b },
7031		{ OV511_I2C_BUS, 0x71, 0x00 },
7032		{ OV511_I2C_BUS, 0x72, 0x14 },
7033		{ OV511_I2C_BUS, 0x73, 0x54 },
7034		{ OV511_I2C_BUS, 0x74, 0x00 },
7035		{ OV511_I2C_BUS, 0x75, 0x8e },
7036		{ OV511_I2C_BUS, 0x76, 0x00 },
7037		{ OV511_I2C_BUS, 0x77, 0xff },
7038		{ OV511_I2C_BUS, 0x78, 0x80 },
7039		{ OV511_I2C_BUS, 0x79, 0x80 },
7040		{ OV511_I2C_BUS, 0x7a, 0x80 },
7041		{ OV511_I2C_BUS, 0x7b, 0xe2 },
7042		{ OV511_I2C_BUS, 0x7c, 0x00 },
7043		{ OV511_DONE_BUS, 0x0, 0x00 },
7044	};
7045
7046	/* 7640 and 7648. The defaults should be OK for most registers. */
7047	static struct ov511_regvals regvals_norm_7640[] = {
7048		{ OV511_I2C_BUS, 0x12, 0x80 },
7049		{ OV511_I2C_BUS, 0x12, 0x14 },
7050		{ OV511_DONE_BUS, 0x0, 0x00 },
7051	};
7052
7053	PDEBUG(4, "starting configuration");
7054
7055	if (init_ov_sensor(ov) < 0) {
7056		err("Failed to read sensor ID. You might not have an");
7057		err("OV76xx, or it might not be responding. Report");
7058		err("this to " EMAIL);
7059		err("This is only a warning. You can attempt to use");
7060		err("your camera anyway");
7061	} else {
7062		PDEBUG(1, "OV7xx0 initialized");
7063	}
7064
7065	/* Detect sensor (sub)type */
7066	rc = i2c_r(ov, OV7610_REG_COM_I);
7067
7068	if (rc < 0) {
7069		err("Error detecting sensor type");
7070		return -1;
7071	} else if ((rc & 3) == 3) {
7072		info("Sensor is an OV7610");
7073		ov->sensor = SEN_OV7610;
7074	} else if ((rc & 3) == 1) {
7075		/* I don't know what's different about the 76BE yet. */
7076		if (i2c_r(ov, 0x15) & 1)
7077			info("Sensor is an OV7620AE");
7078		else
7079			info("Sensor is an OV76BE");
7080
7081		/* OV511+ will return all zero isoc data unless we
7082		 * configure the sensor as a 7620. Someone needs to
7083		 * find the exact reg. setting that causes this. */
7084		if (ov->bridge == BRG_OV511PLUS)
7085			ov->sensor = SEN_OV7620;
7086		else
7087			ov->sensor = SEN_OV76BE;
7088	} else if ((rc & 3) == 0) {
7089		/* try to read product id registers */
7090		high = i2c_r(ov, 0x0a);
7091		if (high < 0) {
7092			err("Error detecting camera chip PID");
7093			return high;
7094		}
7095		low = i2c_r(ov, 0x0b);
7096		if (low < 0) {
7097			err("Error detecting camera chip VER");
7098			return low;
7099		}
7100		if (high == 0x76) {
7101			if (low == 0x30) {
7102				info("Sensor is an OV7630/OV7635");
7103				ov->sensor = SEN_OV7630;
7104			}
7105			else if (low == 0x40) {
7106				info("Sensor is an OV7645");
7107				ov->sensor = SEN_OV7640; // FIXME
7108			}
7109			else if (low == 0x45) {
7110				info("Sensor is an OV7645B");
7111				ov->sensor = SEN_OV7640; // FIXME
7112			}
7113			else if (low == 0x48) {
7114				info("Sensor is an OV7648");
7115				ov->sensor = SEN_OV7640; // FIXME
7116			}
7117			else {
7118				err("Unknown sensor: 0x76%X", low);
7119				return -1;
7120			}
7121		} else {
7122			info("Sensor is an OV7620");
7123			ov->sensor = SEN_OV7620;
7124		}
7125	} else {
7126		err("Unknown image sensor version: %d", rc & 3);
7127		return -1;
7128	}
7129
7130	if (ov->sensor == SEN_OV7620) {
7131		PDEBUG(4, "Writing 7620 registers");
7132		if (write_regvals(ov, regvals_norm_7620))
7133			return -1;
7134	} else if (ov->sensor == SEN_OV7630) {
7135		PDEBUG(4, "7630 is not supported by this driver version");
7136		return -1;
7137	} else if (ov->sensor == SEN_OV7640) {
7138		PDEBUG(4, "Writing 7640 registers");
7139		if (write_regvals(ov, regvals_norm_7640))
7140			return -1;
7141	} else {
7142		PDEBUG(4, "Writing 7610 registers");
7143		if (write_regvals(ov, regvals_norm_7610))
7144			return -1;
7145	}
7146
7147	/* Set sensor-specific vars */
7148	ov->maxwidth = 640;
7149	ov->maxheight = 480;
7150	ov->minwidth = 64;
7151	ov->minheight = 48;
7152
7153	// FIXME: These do not match the actual settings yet
7154	ov->brightness = 0x80 << 8;
7155	ov->contrast = 0x80 << 8;
7156	ov->colour = 0x80 << 8;
7157	ov->hue = 0x80 << 8;
7158
7159	return 0;
7160}
7161
7162/* This initializes the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
7163static int
7164ov6xx0_configure(struct usb_ov511 *ov)
7165{
7166	int rc;
7167
7168	static struct ov511_regvals regvals_norm_6x20[] = {
7169		{ OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
7170		{ OV511_I2C_BUS, 0x11, 0x01 },
7171		{ OV511_I2C_BUS, 0x03, 0x60 },
7172		{ OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
7173		{ OV511_I2C_BUS, 0x07, 0xa8 },
7174		/* The ratio of 0x0c and 0x0d  controls the white point */
7175		{ OV511_I2C_BUS, 0x0c, 0x24 },
7176		{ OV511_I2C_BUS, 0x0d, 0x24 },
7177		{ OV511_I2C_BUS, 0x0f, 0x15 }, /* COMS */
7178		{ OV511_I2C_BUS, 0x10, 0x75 }, /* AEC Exposure time */
7179		{ OV511_I2C_BUS, 0x12, 0x24 }, /* Enable AGC */
7180		{ OV511_I2C_BUS, 0x14, 0x04 },
7181		/* 0x16: 0x06 helps frame stability with moving objects */
7182		{ OV511_I2C_BUS, 0x16, 0x06 },
7183//		{ OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
7184		{ OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
7185		/* 0x28: 0x05 Selects RGB format if RGB on */
7186		{ OV511_I2C_BUS, 0x28, 0x05 },
7187		{ OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
7188//		{ OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
7189		{ OV511_I2C_BUS, 0x2d, 0x99 },
7190		{ OV511_I2C_BUS, 0x33, 0xa0 }, /* Color Procesing Parameter */
7191		{ OV511_I2C_BUS, 0x34, 0xd2 }, /* Max A/D range */
7192		{ OV511_I2C_BUS, 0x38, 0x8b },
7193		{ OV511_I2C_BUS, 0x39, 0x40 },
7194
7195		{ OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
7196		{ OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
7197		{ OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
7198
7199		{ OV511_I2C_BUS, 0x3d, 0x80 },
7200		/* These next two registers (0x4a, 0x4b) are undocumented. They
7201		 * control the color balance */
7202		{ OV511_I2C_BUS, 0x4a, 0x80 },
7203		{ OV511_I2C_BUS, 0x4b, 0x80 },
7204		{ OV511_I2C_BUS, 0x4d, 0xd2 }, /* This reduces noise a bit */
7205		{ OV511_I2C_BUS, 0x4e, 0xc1 },
7206		{ OV511_I2C_BUS, 0x4f, 0x04 },
7207// Do 50-53 have any effect?
7208// Toggle 0x12[2] off and on here?
7209		{ OV511_DONE_BUS, 0x0, 0x00 },	/* END MARKER */
7210	};
7211
7212	static struct ov511_regvals regvals_norm_6x30[] = {
7213		{ OV511_I2C_BUS, 0x12, 0x80 }, /* Reset */
7214		{ OV511_I2C_BUS, 0x00, 0x1f }, /* Gain */
7215		{ OV511_I2C_BUS, 0x01, 0x99 }, /* Blue gain */
7216		{ OV511_I2C_BUS, 0x02, 0x7c }, /* Red gain */
7217		{ OV511_I2C_BUS, 0x03, 0xc0 }, /* Saturation */
7218		{ OV511_I2C_BUS, 0x05, 0x0a }, /* Contrast */
7219		{ OV511_I2C_BUS, 0x06, 0x95 }, /* Brightness */
7220		{ OV511_I2C_BUS, 0x07, 0x2d }, /* Sharpness */
7221		{ OV511_I2C_BUS, 0x0c, 0x20 },
7222		{ OV511_I2C_BUS, 0x0d, 0x20 },
7223		{ OV511_I2C_BUS, 0x0e, 0x20 },
7224		{ OV511_I2C_BUS, 0x0f, 0x05 },
7225		{ OV511_I2C_BUS, 0x10, 0x9a },
7226		{ OV511_I2C_BUS, 0x11, 0x00 }, /* Pixel clock = fastest */
7227		{ OV511_I2C_BUS, 0x12, 0x24 }, /* Enable AGC and AWB */
7228		{ OV511_I2C_BUS, 0x13, 0x21 },
7229		{ OV511_I2C_BUS, 0x14, 0x80 },
7230		{ OV511_I2C_BUS, 0x15, 0x01 },
7231		{ OV511_I2C_BUS, 0x16, 0x03 },
7232		{ OV511_I2C_BUS, 0x17, 0x38 },
7233		{ OV511_I2C_BUS, 0x18, 0xea },
7234		{ OV511_I2C_BUS, 0x19, 0x04 },
7235		{ OV511_I2C_BUS, 0x1a, 0x93 },
7236		{ OV511_I2C_BUS, 0x1b, 0x00 },
7237		{ OV511_I2C_BUS, 0x1e, 0xc4 },
7238		{ OV511_I2C_BUS, 0x1f, 0x04 },
7239		{ OV511_I2C_BUS, 0x20, 0x20 },
7240		{ OV511_I2C_BUS, 0x21, 0x10 },
7241		{ OV511_I2C_BUS, 0x22, 0x88 },
7242		{ OV511_I2C_BUS, 0x23, 0xc0 }, /* Crystal circuit power level */
7243		{ OV511_I2C_BUS, 0x25, 0x9a }, /* Increase AEC black ratio */
7244		{ OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
7245		{ OV511_I2C_BUS, 0x27, 0xa2 },
7246		{ OV511_I2C_BUS, 0x28, 0x00 },
7247		{ OV511_I2C_BUS, 0x29, 0x00 },
7248		{ OV511_I2C_BUS, 0x2a, 0x84 }, /* 60 Hz power */
7249		{ OV511_I2C_BUS, 0x2b, 0xa8 }, /* 60 Hz power */
7250		{ OV511_I2C_BUS, 0x2c, 0xa0 },
7251		{ OV511_I2C_BUS, 0x2d, 0x95 }, /* Enable auto-brightness */
7252		{ OV511_I2C_BUS, 0x2e, 0x88 },
7253		{ OV511_I2C_BUS, 0x33, 0x26 },
7254		{ OV511_I2C_BUS, 0x34, 0x03 },
7255		{ OV511_I2C_BUS, 0x36, 0x8f },
7256		{ OV511_I2C_BUS, 0x37, 0x80 },
7257		{ OV511_I2C_BUS, 0x38, 0x83 },
7258		{ OV511_I2C_BUS, 0x39, 0x80 },
7259		{ OV511_I2C_BUS, 0x3a, 0x0f },
7260		{ OV511_I2C_BUS, 0x3b, 0x3c },
7261		{ OV511_I2C_BUS, 0x3c, 0x1a },
7262		{ OV511_I2C_BUS, 0x3d, 0x80 },
7263		{ OV511_I2C_BUS, 0x3e, 0x80 },
7264		{ OV511_I2C_BUS, 0x3f, 0x0e },
7265		{ OV511_I2C_BUS, 0x40, 0x00 }, /* White bal */
7266		{ OV511_I2C_BUS, 0x41, 0x00 }, /* White bal */
7267		{ OV511_I2C_BUS, 0x42, 0x80 },
7268		{ OV511_I2C_BUS, 0x43, 0x3f }, /* White bal */
7269		{ OV511_I2C_BUS, 0x44, 0x80 },
7270		{ OV511_I2C_BUS, 0x45, 0x20 },
7271		{ OV511_I2C_BUS, 0x46, 0x20 },
7272		{ OV511_I2C_BUS, 0x47, 0x80 },
7273		{ OV511_I2C_BUS, 0x48, 0x7f },
7274		{ OV511_I2C_BUS, 0x49, 0x00 },
7275		{ OV511_I2C_BUS, 0x4a, 0x00 },
7276		{ OV511_I2C_BUS, 0x4b, 0x80 },
7277		{ OV511_I2C_BUS, 0x4c, 0xd0 },
7278		{ OV511_I2C_BUS, 0x4d, 0x10 }, /* U = 0.563u, V = 0.714v */
7279		{ OV511_I2C_BUS, 0x4e, 0x40 },
7280		{ OV511_I2C_BUS, 0x4f, 0x07 }, /* UV avg., col. killer: max */
7281		{ OV511_I2C_BUS, 0x50, 0xff },
7282		{ OV511_I2C_BUS, 0x54, 0x23 }, /* Max AGC gain: 18dB */
7283		{ OV511_I2C_BUS, 0x55, 0xff },
7284		{ OV511_I2C_BUS, 0x56, 0x12 },
7285		{ OV511_I2C_BUS, 0x57, 0x81 },
7286		{ OV511_I2C_BUS, 0x58, 0x75 },
7287		{ OV511_I2C_BUS, 0x59, 0x01 }, /* AGC dark current comp.: +1 */
7288		{ OV511_I2C_BUS, 0x5a, 0x2c },
7289		{ OV511_I2C_BUS, 0x5b, 0x0f }, /* AWB chrominance levels */
7290		{ OV511_I2C_BUS, 0x5c, 0x10 },
7291		{ OV511_I2C_BUS, 0x3d, 0x80 },
7292		{ OV511_I2C_BUS, 0x27, 0xa6 },
7293		{ OV511_I2C_BUS, 0x12, 0x20 }, /* Toggle AWB */
7294		{ OV511_I2C_BUS, 0x12, 0x24 },
7295		{ OV511_DONE_BUS, 0x0, 0x00 },	/* END MARKER */
7296	};
7297
7298	PDEBUG(4, "starting sensor configuration");
7299
7300	if (init_ov_sensor(ov) < 0) {
7301		err("Failed to read sensor ID. You might not have an OV6xx0,");
7302		err("or it may be not responding. Report this to " EMAIL);
7303		return -1;
7304	} else {
7305		PDEBUG(1, "OV6xx0 sensor detected");
7306	}
7307
7308	/* Detect sensor (sub)type */
7309	rc = i2c_r(ov, OV7610_REG_COM_I);
7310
7311	if (rc < 0) {
7312		err("Error detecting sensor type");
7313		return -1;
7314	}
7315
7316	/* Ugh. The first two bits are the version bits, but the entire register
7317	 * value must be used. I guess OVT underestimated how many variants
7318	 * they would make. */
7319	if (rc == 0x00) {
7320		ov->sensor = SEN_OV6630;
7321		info("WARNING: Sensor is an OV66308. Your camera may have");
7322		info("been misdetected in previous driver versions. Please");
7323		info("report this to Mark.");
7324	} else if (rc == 0x01) {
7325		ov->sensor = SEN_OV6620;
7326		info("Sensor is an OV6620");
7327	} else if (rc == 0x02) {
7328		ov->sensor = SEN_OV6630;
7329		info("Sensor is an OV66308AE");
7330	} else if (rc == 0x03) {
7331		ov->sensor = SEN_OV6630;
7332		info("Sensor is an OV66308AF");
7333	} else if (rc == 0x90) {
7334		ov->sensor = SEN_OV6630;
7335		info("WARNING: Sensor is an OV66307. Your camera may have");
7336		info("been misdetected in previous driver versions. Please");
7337		info("report this to Mark.");
7338	} else {
7339		err("FATAL: Unknown sensor version: 0x%02x", rc);
7340		return -1;
7341	}
7342
7343	/* Set sensor-specific vars */
7344	ov->maxwidth = 352;
7345	ov->maxheight = 288;
7346	ov->minwidth = 64;
7347	ov->minheight = 48;
7348
7349	// FIXME: These do not match the actual settings yet
7350	ov->brightness = 0x80 << 8;
7351	ov->contrast = 0x80 << 8;
7352	ov->colour = 0x80 << 8;
7353	ov->hue = 0x80 << 8;
7354
7355	if (ov->sensor == SEN_OV6620) {
7356		PDEBUG(4, "Writing 6x20 registers");
7357		if (write_regvals(ov, regvals_norm_6x20))
7358			return -1;
7359	} else {
7360		PDEBUG(4, "Writing 6x30 registers");
7361		if (write_regvals(ov, regvals_norm_6x30))
7362			return -1;
7363	}
7364
7365	return 0;
7366}
7367
7368/* This initializes the KS0127 and KS0127B video decoders. */
7369static int
7370ks0127_configure(struct usb_ov511 *ov)
7371{
7372	int rc;
7373
7374	/* Detect decoder subtype */
7375	rc = i2c_r(ov, 0x00);
7376	if (rc < 0) {
7377		err("Error detecting sensor type");
7378		return -1;
7379	} else if (rc & 0x08) {
7380		rc = i2c_r(ov, 0x3d);
7381		if (rc < 0) {
7382			err("Error detecting sensor type");
7383			return -1;
7384		} else if ((rc & 0x0f) == 0) {
7385			info("Sensor is a KS0127");
7386		} else if ((rc & 0x0f) == 9) {
7387			info("Sensor is a KS0127B Rev. A");
7388		}
7389	} else {
7390		info("Sensor is a KS0122");
7391	}
7392
7393	/* This device is not supported yet. Bail out now... */
7394	err("This sensor is not supported yet.");
7395	return -1;
7396}
7397
7398/* This initializes the SAA7111A video decoder. */
7399static int
7400saa7111a_configure(struct usb_ov511 *ov)
7401{
7402	int rc;
7403
7404	/* Since there is no register reset command, all registers must be
7405	 * written, otherwise gives erratic results */
7406	static struct ov511_regvals regvals_norm_SAA7111A[] = {
7407		{ OV511_I2C_BUS, 0x06, 0xce },
7408		{ OV511_I2C_BUS, 0x07, 0x00 },
7409		{ OV511_I2C_BUS, 0x10, 0x44 }, /* YUV422, 240/286 lines */
7410		{ OV511_I2C_BUS, 0x0e, 0x01 }, /* NTSC M or PAL BGHI */
7411		{ OV511_I2C_BUS, 0x00, 0x00 },
7412		{ OV511_I2C_BUS, 0x01, 0x00 },
7413		{ OV511_I2C_BUS, 0x03, 0x23 },
7414		{ OV511_I2C_BUS, 0x04, 0x00 },
7415		{ OV511_I2C_BUS, 0x05, 0x00 },
7416		{ OV511_I2C_BUS, 0x08, 0xc8 }, /* Auto field freq */
7417		{ OV511_I2C_BUS, 0x09, 0x01 }, /* Chrom. trap off, APER=0.25 */
7418		{ OV511_I2C_BUS, 0x0a, 0x80 }, /* BRIG=128 */
7419		{ OV511_I2C_BUS, 0x0b, 0x40 }, /* CONT=1.0 */
7420		{ OV511_I2C_BUS, 0x0c, 0x40 }, /* SATN=1.0 */
7421		{ OV511_I2C_BUS, 0x0d, 0x00 }, /* HUE=0 */
7422		{ OV511_I2C_BUS, 0x0f, 0x00 },
7423		{ OV511_I2C_BUS, 0x11, 0x0c },
7424		{ OV511_I2C_BUS, 0x12, 0x00 },
7425		{ OV511_I2C_BUS, 0x13, 0x00 },
7426		{ OV511_I2C_BUS, 0x14, 0x00 },
7427		{ OV511_I2C_BUS, 0x15, 0x00 },
7428		{ OV511_I2C_BUS, 0x16, 0x00 },
7429		{ OV511_I2C_BUS, 0x17, 0x00 },
7430		{ OV511_I2C_BUS, 0x02, 0xc0 },	/* Composite input 0 */
7431		{ OV511_DONE_BUS, 0x0, 0x00 },
7432	};
7433
7434	/* 640x480 not supported with PAL */
7435	if (ov->pal) {
7436		ov->maxwidth = 320;
7437		ov->maxheight = 240;		/* Even field only */
7438	} else {
7439		ov->maxwidth = 640;
7440		ov->maxheight = 480;		/* Even/Odd fields */
7441	}
7442
7443	ov->minwidth = 320;
7444	ov->minheight = 240;		/* Even field only */
7445
7446	ov->has_decoder = 1;
7447	ov->num_inputs = 8;
7448	ov->norm = VIDEO_MODE_AUTO;
7449	ov->stop_during_set = 0;	/* Decoder guarantees stable image */
7450
7451	/* Decoder doesn't change these values, so we use these instead of
7452	 * acutally reading the registers (which doesn't work) */
7453	ov->brightness = 0x80 << 8;
7454	ov->contrast = 0x40 << 9;
7455	ov->colour = 0x40 << 9;
7456	ov->hue = 32768;
7457
7458	PDEBUG(4, "Writing SAA7111A registers");
7459	if (write_regvals(ov, regvals_norm_SAA7111A))
7460		return -1;
7461
7462	/* Detect version of decoder. This must be done after writing the
7463         * initial regs or the decoder will lock up. */
7464	rc = i2c_r(ov, 0x00);
7465
7466	if (rc < 0) {
7467		err("Error detecting sensor version");
7468		return -1;
7469	} else {
7470		info("Sensor is an SAA7111A (version 0x%x)", rc);
7471		ov->sensor = SEN_SAA7111A;
7472	}
7473
7474	/* Latch to negative edge of clock. Otherwise, we get incorrect
7475	 * colors and jitter in the digital signal. */
7476	if (ov->bclass == BCL_OV511)
7477		reg_w(ov, 0x11, 0x00);
7478	else
7479		warn("SAA7111A not yet supported with OV518/OV518+");
7480
7481	return 0;
7482}
7483
7484/* This initializes the OV511/OV511+ and the sensor */
7485static int
7486ov511_configure(struct usb_ov511 *ov)
7487{
7488	static struct ov511_regvals regvals_init_511[] = {
7489		{ OV511_REG_BUS, R51x_SYS_RESET,	0x7f },
7490	 	{ OV511_REG_BUS, R51x_SYS_INIT,		0x01 },
7491	 	{ OV511_REG_BUS, R51x_SYS_RESET,	0x7f },
7492		{ OV511_REG_BUS, R51x_SYS_INIT,		0x01 },
7493		{ OV511_REG_BUS, R51x_SYS_RESET,	0x3f },
7494		{ OV511_REG_BUS, R51x_SYS_INIT,		0x01 },
7495		{ OV511_REG_BUS, R51x_SYS_RESET,	0x3d },
7496		{ OV511_DONE_BUS, 0x0, 0x00},
7497	};
7498
7499	static struct ov511_regvals regvals_norm_511[] = {
7500		{ OV511_REG_BUS, R511_DRAM_FLOW_CTL, 	0x01 },
7501		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x00 },
7502		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x02 },
7503		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x00 },
7504		{ OV511_REG_BUS, R511_FIFO_OPTS,	0x1f },
7505		{ OV511_REG_BUS, R511_COMP_EN,		0x00 },
7506		{ OV511_REG_BUS, R511_COMP_LUT_EN,	0x03 },
7507		{ OV511_DONE_BUS, 0x0, 0x00 },
7508	};
7509
7510	static struct ov511_regvals regvals_norm_511_plus[] = {
7511		{ OV511_REG_BUS, R511_DRAM_FLOW_CTL,	0xff },
7512		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x00 },
7513		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x02 },
7514		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x00 },
7515		{ OV511_REG_BUS, R511_FIFO_OPTS,	0xff },
7516		{ OV511_REG_BUS, R511_COMP_EN,		0x00 },
7517		{ OV511_REG_BUS, R511_COMP_LUT_EN,	0x03 },
7518		{ OV511_DONE_BUS, 0x0, 0x00 },
7519	};
7520
7521	PDEBUG(4, "");
7522
7523	ov->customid = reg_r(ov, R511_SYS_CUST_ID);
7524	if (ov->customid < 0) {
7525		err("Unable to read camera bridge registers");
7526		goto error;
7527	}
7528
7529	PDEBUG (1, "CustomID = %d", ov->customid);
7530	ov->desc = symbolic(camlist, ov->customid);
7531	info("model: %s", ov->desc);
7532
7533	if (0 == strcmp(ov->desc, NOT_DEFINED_STR)) {
7534		err("Camera type (%d) not recognized", ov->customid);
7535		err("Please notify " EMAIL " of the name,");
7536		err("manufacturer, model, and this number of your camera.");
7537		err("Also include the output of the detection process.");
7538	}
7539
7540	if (ov->customid == 70)		/* USB Life TV (PAL/SECAM) */
7541		ov->pal = 1;
7542
7543	if (write_regvals(ov, regvals_init_511)) goto error;
7544
7545	if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
7546		ov51x_led_control(ov, 0);
7547
7548	/* The OV511+ has undocumented bits in the flow control register.
7549	 * Setting it to 0xff fixes the corruption with moving objects. */
7550	if (ov->bridge == BRG_OV511) {
7551		if (write_regvals(ov, regvals_norm_511)) goto error;
7552	} else if (ov->bridge == BRG_OV511PLUS) {
7553		if (write_regvals(ov, regvals_norm_511_plus)) goto error;
7554	} else {
7555		err("Invalid bridge");
7556	}
7557
7558	if (ov511_init_compression(ov)) goto error;
7559
7560	ov->packet_numbering = 1;
7561	ov511_set_packet_size(ov, 0);
7562
7563	ov->snap_enabled = snapshot;
7564
7565	/* Test for 7xx0 */
7566	PDEBUG(3, "Testing for 0V7xx0");
7567	ov->primary_i2c_slave = OV7xx0_SID;
7568	if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
7569		goto error;
7570
7571	if (i2c_w(ov, 0x12, 0x80) < 0) {
7572		/* Test for 6xx0 */
7573		PDEBUG(3, "Testing for 0V6xx0");
7574		ov->primary_i2c_slave = OV6xx0_SID;
7575		if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
7576			goto error;
7577
7578		if (i2c_w(ov, 0x12, 0x80) < 0) {
7579			/* Test for 8xx0 */
7580			PDEBUG(3, "Testing for 0V8xx0");
7581			ov->primary_i2c_slave = OV8xx0_SID;
7582			if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
7583				goto error;
7584
7585			if (i2c_w(ov, 0x12, 0x80) < 0) {
7586				/* Test for SAA7111A */
7587				PDEBUG(3, "Testing for SAA7111A");
7588				ov->primary_i2c_slave = SAA7111A_SID;
7589				if (ov51x_set_slave_ids(ov, SAA7111A_SID) < 0)
7590					goto error;
7591
7592				if (i2c_w(ov, 0x0d, 0x00) < 0) {
7593					/* Test for KS0127 */
7594					PDEBUG(3, "Testing for KS0127");
7595					ov->primary_i2c_slave = KS0127_SID;
7596					if (ov51x_set_slave_ids(ov, KS0127_SID) < 0)
7597						goto error;
7598
7599					if (i2c_w(ov, 0x10, 0x00) < 0) {
7600						err("Can't determine sensor slave IDs");
7601		 				goto error;
7602					} else {
7603						if (ks0127_configure(ov) < 0) {
7604							err("Failed to configure KS0127");
7605	 						goto error;
7606						}
7607					}
7608				} else {
7609					if (saa7111a_configure(ov) < 0) {
7610						err("Failed to configure SAA7111A");
7611	 					goto error;
7612					}
7613				}
7614			} else {
7615				if (ov8xx0_configure(ov) < 0) {
7616					err("Failed to configure OV8xx0 sensor");
7617					goto error;
7618				}
7619			}
7620		} else {
7621			if (ov6xx0_configure(ov) < 0) {
7622				err("Failed to configure OV6xx0");
7623 				goto error;
7624			}
7625		}
7626	} else {
7627		if (ov7xx0_configure(ov) < 0) {
7628			err("Failed to configure OV7xx0");
7629	 		goto error;
7630		}
7631	}
7632
7633	return 0;
7634
7635error:
7636	err("OV511 Config failed");
7637
7638	return -EBUSY;
7639}
7640
7641/* This initializes the OV518/OV518+ and the sensor */
7642static int
7643ov518_configure(struct usb_ov511 *ov)
7644{
7645	/* For 518 and 518+ */
7646	static struct ov511_regvals regvals_init_518[] = {
7647		{ OV511_REG_BUS, R51x_SYS_RESET,	0x40 },
7648	 	{ OV511_REG_BUS, R51x_SYS_INIT,		0xe1 },
7649	 	{ OV511_REG_BUS, R51x_SYS_RESET,	0x3e },
7650		{ OV511_REG_BUS, R51x_SYS_INIT,		0xe1 },
7651		{ OV511_REG_BUS, R51x_SYS_RESET,	0x00 },
7652		{ OV511_REG_BUS, R51x_SYS_INIT,		0xe1 },
7653		{ OV511_REG_BUS, 0x46,			0x00 },
7654		{ OV511_REG_BUS, 0x5d,			0x03 },
7655		{ OV511_DONE_BUS, 0x0, 0x00},
7656	};
7657
7658	static struct ov511_regvals regvals_norm_518[] = {
7659		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x02 }, /* Reset */
7660		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x01 }, /* Enable */
7661		{ OV511_REG_BUS, 0x31, 			0x0f },
7662		{ OV511_REG_BUS, 0x5d,			0x03 },
7663		{ OV511_REG_BUS, 0x24,			0x9f },
7664		{ OV511_REG_BUS, 0x25,			0x90 },
7665		{ OV511_REG_BUS, 0x20,			0x00 },
7666		{ OV511_REG_BUS, 0x51,			0x04 },
7667		{ OV511_REG_BUS, 0x71,			0x19 },
7668		{ OV511_REG_BUS, 0x2f,			0x80 },
7669		{ OV511_DONE_BUS, 0x0, 0x00 },
7670	};
7671
7672	static struct ov511_regvals regvals_norm_518_plus[] = {
7673		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x02 }, /* Reset */
7674		{ OV511_REG_BUS, R51x_SYS_SNAP,		0x01 }, /* Enable */
7675		{ OV511_REG_BUS, 0x31, 			0x0f },
7676		{ OV511_REG_BUS, 0x5d,			0x03 },
7677		{ OV511_REG_BUS, 0x24,			0x9f },
7678		{ OV511_REG_BUS, 0x25,			0x90 },
7679		{ OV511_REG_BUS, 0x20,			0x60 },
7680		{ OV511_REG_BUS, 0x51,			0x02 },
7681		{ OV511_REG_BUS, 0x71,			0x19 },
7682		{ OV511_REG_BUS, 0x40,			0xff },
7683		{ OV511_REG_BUS, 0x41,			0x42 },
7684		{ OV511_REG_BUS, 0x46,			0x00 },
7685		{ OV511_REG_BUS, 0x33,			0x04 },
7686		{ OV511_REG_BUS, 0x21,			0x19 },
7687		{ OV511_REG_BUS, 0x3f,			0x10 },
7688		{ OV511_REG_BUS, 0x2f,			0x80 },
7689		{ OV511_DONE_BUS, 0x0, 0x00 },
7690	};
7691
7692	PDEBUG(4, "");
7693
7694	/* First 5 bits of custom ID reg are a revision ID on OV518 */
7695	info("Device revision %d", 0x1F & reg_r(ov, R511_SYS_CUST_ID));
7696
7697	/* Give it the default description */
7698	ov->desc = symbolic(camlist, 0);
7699
7700	if (write_regvals(ov, regvals_init_518)) goto error;
7701
7702	/* Set LED GPIO pin to output mode */
7703	if (reg_w_mask(ov, 0x57, 0x00, 0x02) < 0) goto error;
7704
7705	/* LED is off by default with OV518; have to explicitly turn it on */
7706	if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
7707		ov51x_led_control(ov, 0);
7708	else
7709		ov51x_led_control(ov, 1);
7710
7711	/* Don't require compression if dumppix is enabled; otherwise it's
7712	 * required. OV518 has no uncompressed mode, to save RAM. */
7713	if (!dumppix && !ov->compress) {
7714		ov->compress = 1;
7715		warn("Compression required with OV518...enabling");
7716	}
7717
7718	if (ov->bridge == BRG_OV518) {
7719		if (write_regvals(ov, regvals_norm_518)) goto error;
7720	} else if (ov->bridge == BRG_OV518PLUS) {
7721		if (write_regvals(ov, regvals_norm_518_plus)) goto error;
7722	} else {
7723		err("Invalid bridge");
7724	}
7725
7726	if (ov518_init_compression(ov)) goto error;
7727
7728	if (ov->bridge == BRG_OV518)
7729	{
7730		struct usb_interface *ifp = &ov->dev->config[0].interface[0];
7731		__u16 mxps = ifp->altsetting[7].endpoint[0].wMaxPacketSize;
7732
7733		/* Some OV518s have packet numbering by default, some don't */
7734		if (mxps == 897)
7735			ov->packet_numbering = 1;
7736		else
7737			ov->packet_numbering = 0;
7738	} else {
7739		/* OV518+ has packet numbering turned on by default */
7740		ov->packet_numbering = 1;
7741	}
7742
7743	ov518_set_packet_size(ov, 0);
7744
7745	ov->snap_enabled = snapshot;
7746
7747	/* Test for 76xx */
7748	ov->primary_i2c_slave = OV7xx0_SID;
7749	if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
7750		goto error;
7751
7752	/* The OV518 must be more aggressive about sensor detection since
7753	 * I2C write will never fail if the sensor is not present. We have
7754	 * to try to initialize the sensor to detect its presence */
7755
7756	if (init_ov_sensor(ov) < 0) {
7757		/* Test for 6xx0 */
7758		ov->primary_i2c_slave = OV6xx0_SID;
7759		if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
7760			goto error;
7761
7762		if (init_ov_sensor(ov) < 0) {
7763			/* Test for 8xx0 */
7764			ov->primary_i2c_slave = OV8xx0_SID;
7765			if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
7766				goto error;
7767
7768			if (init_ov_sensor(ov) < 0) {
7769				err("Can't determine sensor slave IDs");
7770 				goto error;
7771			} else {
7772				if (ov8xx0_configure(ov) < 0) {
7773					err("Failed to configure OV8xx0 sensor");
7774					goto error;
7775				}
7776			}
7777		} else {
7778			if (ov6xx0_configure(ov) < 0) {
7779				err("Failed to configure OV6xx0");
7780 				goto error;
7781			}
7782		}
7783	} else {
7784		if (ov7xx0_configure(ov) < 0) {
7785			err("Failed to configure OV7xx0");
7786	 		goto error;
7787		}
7788	}
7789
7790	ov->maxwidth = 352;
7791	ov->maxheight = 288;
7792
7793	// The OV518 cannot go as low as the sensor can
7794	ov->minwidth = 160;
7795	ov->minheight = 120;
7796
7797	return 0;
7798
7799error:
7800	err("OV518 Config failed");
7801
7802	return -EBUSY;
7803}
7804
7805/* This initializes the OV518/OV518+ and the sensor */
7806static int
7807ov519_configure(struct usb_ov511 *ov)
7808{
7809
7810	static struct ov511_regvals regvals_init_519[] = {
7811		{ OV511_REG_BUS, 0x5a,	0x6d }, /* EnableSystem */
7812		/* windows reads 0x53 at this point*/
7813		{ OV511_REG_BUS, 0x53,	0x9b },
7814		{ OV511_REG_BUS, 0x54,	0x0f }, // set bit2 to enable jpeg
7815		{ OV511_REG_BUS, 0x5d,	0x03 },
7816		{ OV511_REG_BUS, 0x49,	0x01 },
7817		{ OV511_REG_BUS, 0x48,	0x00 },
7818
7819		/* Set LED pin to output mode. Bit 4 must be cleared or sensor
7820		 * detection will fail. This deserves further investigation. */
7821		{ OV511_REG_BUS, OV519_GPIO_IO_CTRL0,	0xee },
7822
7823		{ OV511_REG_BUS, 0x51,	0x0f },	/* SetUsbInit */
7824		{ OV511_REG_BUS, 0x51,	0x00 },
7825		{ OV511_REG_BUS, 0x22,	0x00 },
7826		/* windows reads 0x55 at this point*/
7827		{ OV511_DONE_BUS, 0x0, 0x00},
7828	};
7829
7830	PDEBUG(4, "");
7831
7832	/* Give it the default description */
7833	ov->desc = symbolic(camlist, 0);
7834
7835	if (write_regvals(ov, regvals_init_519))
7836		goto error;
7837
7838	if (ov->imp == IMP_EYETOY) {
7839		/* LED is annoyingly bright. Only turn it on if requested to. */
7840		if (ov->led2_policy == LED_ON)
7841			ov51x_led_control(ov, 1);
7842		else
7843			ov51x_led_control(ov, 0);
7844	} else {
7845		/* LED might be off by default */
7846		if (ov->led_policy == LED_ON)
7847			ov51x_led_control(ov, 1);
7848		else
7849			ov51x_led_control(ov, 0);
7850	}
7851
7852	/* Don't require compression if dumppix is enabled; otherwise it's
7853	 * required. OV519 probably has no uncompressed mode, to save RAM. */
7854	if (!dumppix && !ov->compress)
7855		ov->compress = 1;
7856
7857	ov->packet_numbering = 0;
7858
7859	ov519_set_packet_size(ov, 0);
7860
7861	ov->snap_enabled = snapshot;
7862
7863	/* Test for 76xx */
7864	ov->primary_i2c_slave = OV7xx0_SID;
7865	if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
7866		goto error;
7867
7868	/* The OV519 must be more aggressive about sensor detection since
7869	 * I2C write will never fail if the sensor is not present. We have
7870	 * to try to initialize the sensor to detect its presence */
7871
7872	if (init_ov_sensor(ov) < 0) {
7873		/* Test for 6xx0 */
7874		ov->primary_i2c_slave = OV6xx0_SID;
7875		if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
7876			goto error;
7877
7878		if (init_ov_sensor(ov) < 0) {
7879			/* Test for 8xx0 */
7880			ov->primary_i2c_slave = OV8xx0_SID;
7881			if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
7882				goto error;
7883
7884			if (init_ov_sensor(ov) < 0) {
7885				err("Can't determine sensor slave IDs");
7886 				goto error;
7887			} else {
7888				if (ov8xx0_configure(ov) < 0) {
7889					err("Failed to configure OV8xx0 sensor");
7890					goto error;
7891				}
7892			}
7893		} else {
7894			if (ov6xx0_configure(ov) < 0) {
7895				err("Failed to configure OV6xx0");
7896 				goto error;
7897			}
7898		}
7899	} else {
7900		if (ov7xx0_configure(ov) < 0) {
7901			err("Failed to configure OV7xx0");
7902	 		goto error;
7903		}
7904	}
7905
7906	return 0;
7907
7908error:
7909	err("OV519 Config failed");
7910
7911	return -EBUSY;
7912}
7913
7914/****************************************************************************
7915 *
7916 *  USB routines
7917 *
7918 ***************************************************************************/
7919
7920#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
7921static int
7922ov51x_probe(struct usb_interface *intf, const struct usb_device_id *id)
7923{
7924	struct usb_device *dev = interface_to_usbdev(intf);
7925#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 0)
7926static void *
7927ov51x_probe(struct usb_device *dev, unsigned int ifnum,
7928	    const struct usb_device_id *id)
7929#else
7930static void *
7931ov51x_probe(struct usb_device *dev, unsigned int ifnum)
7932#endif
7933{
7934	struct usb_interface_descriptor *idesc;
7935	struct usb_ov511 *ov;
7936	int i;
7937	int registered = 0;
7938
7939	PDEBUG(1, "probing for device...");
7940
7941#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
7942	/* We don't handle multi-config cameras */
7943	if (dev->descriptor.bNumConfigurations != 1)
7944		return -ENODEV;
7945
7946	idesc = &intf->altsetting[0];
7947#else
7948	/* We don't handle multi-config cameras */
7949	if (dev->descriptor.bNumConfigurations != 1)
7950		return NULL;
7951
7952	idesc = &dev->actconfig->interface[ifnum].altsetting[0];
7953#endif
7954
7955/* 2.2.x compatibility */
7956#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 0)
7957	/* Is it an OV511/OV511+? */
7958	if (dev->descriptor.idVendor != VEND_OMNIVISION
7959	 && dev->descriptor.idVendor != VEND_MATTEL)
7960		return NULL;
7961
7962	if (dev->descriptor.idVendor == VEND_OMNIVISION
7963	 && dev->descriptor.idProduct != PROD_OV511
7964	 && dev->descriptor.idProduct != PROD_OV518
7965	 && dev->descriptor.idProduct != PROD_OV511PLUS
7966	 && dev->descriptor.idProduct != PROD_OV518PLUS
7967	 && dev->descriptor.idProduct != 0x0155
7968	 && dev->descriptor.idProduct != PROD_OV519)
7969		return NULL;
7970
7971	if (dev->descriptor.idVendor == VEND_MATTEL
7972	 && dev->descriptor.idProduct != PROD_ME2CAM)
7973		return NULL;
7974#endif
7975
7976#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
7977	if (idesc->bInterfaceClass != 0xFF)
7978		return -ENODEV;
7979	if (idesc->bInterfaceSubClass != 0x00)
7980		return -ENODEV;
7981#else
7982	if (idesc->bInterfaceClass != 0xFF)
7983		return NULL;
7984	if (idesc->bInterfaceSubClass != 0x00)
7985		return NULL;
7986#endif
7987
7988#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 20)
7989	/* Since code below may sleep, we use this as a lock */
7990	MOD_INC_USE_COUNT;
7991#endif
7992
7993	if ((ov = kmalloc(sizeof(*ov), GFP_KERNEL)) == NULL) {
7994		err("couldn't kmalloc ov struct");
7995		goto error_out;
7996	}
7997
7998	memset(ov, 0, sizeof(*ov));
7999
8000	ov->dev = dev;
8001	ov->iface = idesc->bInterfaceNumber;
8002	ov->led_policy = led;
8003	ov->led2_policy = led2;
8004	ov->compress = compress;
8005	ov->lightfreq = lightfreq;
8006	ov->num_inputs = 1;	   /* Video decoder init functs. change this */
8007	ov->stop_during_set = !fastset;
8008	ov->backlight = backlight;
8009	ov->mirror = mirror;
8010	ov->auto_brt = autobright;
8011	ov->auto_gain = autogain;
8012	ov->auto_exp = autoexp;
8013	ov->imp = IMP_GENERIC;
8014
8015	switch (dev->descriptor.idProduct) {
8016	case PROD_OV511:
8017		ov->bridge = BRG_OV511;
8018		ov->bclass = BCL_OV511;
8019		break;
8020	case PROD_OV511PLUS:
8021		ov->bridge = BRG_OV511PLUS;
8022		ov->bclass = BCL_OV511;
8023		break;
8024	case PROD_OV518:
8025		ov->bridge = BRG_OV518;
8026		ov->bclass = BCL_OV518;
8027		break;
8028	case PROD_OV518PLUS:
8029		ov->bridge = BRG_OV518PLUS;
8030		ov->bclass = BCL_OV518;
8031		break;
8032	case PROD_OV519:
8033	case PROD_OV519A:
8034		ov->bridge = BRG_OV519;
8035		ov->bclass = BCL_OV519;
8036		break;
8037	case PROD_EYETOY:
8038		ov->bridge = BRG_OV519;
8039		ov->bclass = BCL_OV519;
8040		ov->imp = IMP_EYETOY;
8041		break;
8042	case PROD_ME2CAM:
8043		if (dev->descriptor.idVendor != VEND_MATTEL)
8044			goto error;
8045		ov->bridge = BRG_OV511PLUS;
8046		ov->bclass = BCL_OV511;
8047		break;
8048	default:
8049		err("Unknown product ID 0x%04x", dev->descriptor.idProduct);
8050		goto error_dealloc;
8051	}
8052
8053	info("USB %s video device found", symbolic(brglist, ov->bridge));
8054
8055#ifdef OV511_ALLOW_CONVERSION
8056	/* Workaround for some applications that want data in RGB
8057	 * instead of BGR. */
8058	if (force_rgb)
8059		info("data format set to RGB");
8060#endif
8061
8062	init_waitqueue_head(&ov->wq);
8063
8064	init_MUTEX(&ov->lock);	/* to 1 == available */
8065	init_MUTEX(&ov->buf_lock);
8066	init_MUTEX(&ov->param_lock);
8067	init_MUTEX(&ov->i2c_lock);
8068	init_MUTEX(&ov->cbuf_lock);
8069
8070	ov->buf_state = BUF_NOT_ALLOCATED;
8071
8072#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 20)
8073	if (usb_make_path(dev, ov->usb_path, OV511_USB_PATH_LEN) < 0) {
8074		err("usb_make_path error");
8075		goto error_dealloc;
8076	}
8077#endif
8078
8079	/* Allocate control transfer buffer. */
8080	/* Must be kmalloc()'ed, for DMA compatibility */
8081	ov->cbuf = kmalloc(OV511_CBUF_SIZE, GFP_KERNEL);
8082	if (!ov->cbuf)
8083		goto error;
8084
8085	switch (ov->bclass) {
8086		case BCL_OV511:
8087			if (ov511_configure(ov) < 0)
8088				goto error;
8089			break;
8090		case BCL_OV518:
8091			if (ov518_configure(ov) < 0)
8092				goto error;
8093			break;
8094		case BCL_OV519:
8095			if (ov519_configure(ov) < 0)
8096				goto error;
8097			break;
8098		default:
8099			goto error;
8100	}
8101
8102	for (i = 0; i < OV511_NUMFRAMES; i++) {
8103		ov->frame[i].framenum = i;
8104		init_waitqueue_head(&ov->frame[i].wq);
8105	}
8106
8107	for (i = 0; i < OV511_NUMSBUF; i++) {
8108		ov->sbuf[i].ov = ov;
8109		spin_lock_init(&ov->sbuf[i].lock);
8110		ov->sbuf[i].n = i;
8111	}
8112
8113	/* Unnecessary? (This is done on open(). Need to make sure variables
8114	 * are properly initialized without this before removing it, though). */
8115	if (ov51x_set_default_params(ov) < 0)
8116		goto error;
8117
8118#ifdef OV511_DEBUG
8119	if (dump_bridge) {
8120		if (ov->bclass == BCL_OV511)
8121			ov511_dump_regs(ov);
8122		else
8123			ov518_dump_regs(ov);
8124	}
8125#endif
8126
8127	memcpy(&ov->vdev, &vdev_template, sizeof(vdev_template));
8128	ov->vdev.priv = ov;
8129
8130#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 5)
8131	for (i = 0; i < OV511_MAX_UNIT_VIDEO; i++) {
8132		/* Minor 0 cannot be specified; assume user wants autodetect */
8133		if (unit_video[i] == 0)
8134			break;
8135
8136		if (video_register_device(&ov->vdev, VFL_TYPE_GRABBER,
8137			unit_video[i]) >= 0) {
8138			registered = 1;
8139			break;
8140		}
8141	}
8142
8143	/* Use the next available one */
8144	if (!registered &&
8145	    video_register_device(&ov->vdev, VFL_TYPE_GRABBER, -1) < 0) {
8146#else
8147	if (video_register_device(&ov->vdev, VFL_TYPE_GRABBER) < 0) {
8148#endif
8149		err("video_register_device failed");
8150		goto error;
8151	}
8152
8153#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 20)
8154	info("Device at %s registered to minor %d", ov->usb_path,
8155	     ov->vdev.minor);
8156#else
8157	info("Device %d on bus %d registered to minor %d", dev->devnum,
8158	     dev->bus->busnum, ov->vdev.minor);
8159#endif
8160
8161	create_proc_ov511_cam(ov);
8162
8163#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 20)
8164	MOD_DEC_USE_COUNT;
8165#endif
8166#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
8167	dev_set_drvdata(&intf->dev, ov);
8168	return 0;
8169#else
8170	return ov;
8171#endif
8172
8173error:
8174	destroy_proc_ov511_cam(ov);
8175
8176	if (ov->cbuf) {
8177		down(&ov->cbuf_lock);
8178		kfree(ov->cbuf);
8179		ov->cbuf = NULL;
8180		up(&ov->cbuf_lock);
8181	}
8182
8183error_dealloc:
8184	if (ov) {
8185		kfree(ov);
8186		ov = NULL;
8187	}
8188
8189error_out:
8190#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 20)
8191	MOD_DEC_USE_COUNT;
8192#endif
8193	err("Camera initialization failed");
8194#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
8195	return -EIO;
8196#else
8197	return NULL;
8198#endif
8199}
8200
8201static void
8202#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
8203ov51x_disconnect(struct usb_interface *intf)
8204{
8205	struct usb_ov511 *ov = dev_get_drvdata(&intf->dev);
8206#else
8207ov51x_disconnect(struct usb_device *dev, void *ptr)
8208{
8209	struct usb_ov511 *ov = (struct usb_ov511 *) ptr;
8210#endif
8211	int n;
8212
8213#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 20)
8214	MOD_INC_USE_COUNT;
8215#endif
8216
8217	PDEBUG(3, "");
8218
8219#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 36)
8220	dev_set_drvdata(&intf->dev, NULL);
8221#endif
8222	if (!ov)
8223		return;
8224
8225#ifdef OV511_OLD_V4L
8226	/* We don't want people trying to open up the device */
8227	if (!ov->user)
8228		video_unregister_device(&ov->vdev);
8229	else
8230		PDEBUG(3, "Device open...deferring video_unregister_device");
8231#else
8232	video_unregister_device(&ov->vdev);
8233	if (ov->user)
8234		PDEBUG(3, "Device open...deferring video_unregister_device");
8235#endif
8236
8237	for (n = 0; n < OV511_NUMFRAMES; n++)
8238		ov->frame[n].grabstate = FRAME_ERROR;
8239
8240	ov->curframe = -1;
8241
8242	/* This will cause the process to request another frame */
8243	for (n = 0; n < OV511_NUMFRAMES; n++)
8244		wake_up_interruptible(&ov->frame[n].wq);
8245
8246	wake_up_interruptible(&ov->wq);
8247
8248	ov->streaming = 0;
8249	ov51x_unlink_isoc(ov);
8250
8251        destroy_proc_ov511_cam(ov);
8252
8253	ov->dev = NULL;
8254
8255	/* Free the memory */
8256	if (ov && !ov->user) {
8257		down(&ov->cbuf_lock);
8258		kfree(ov->cbuf);
8259		ov->cbuf = NULL;
8260		up(&ov->cbuf_lock);
8261
8262		ov51x_dealloc(ov);
8263		kfree(ov);
8264		ov = NULL;
8265	}
8266
8267#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 4, 20)
8268	MOD_DEC_USE_COUNT;
8269#endif
8270	PDEBUG(3, "Disconnect complete");
8271}
8272
8273static struct usb_driver ov511_driver = {
8274#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 20)
8275	.owner =	THIS_MODULE,
8276#endif
8277	.name =		"ov51x",
8278#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 0)
8279	.id_table =	device_table,
8280#endif
8281	.probe =	ov51x_probe,
8282	.disconnect =	ov51x_disconnect
8283};
8284
8285/****************************************************************************
8286 *
8287 *  Module routines
8288 *
8289 ***************************************************************************/
8290
8291/* Returns 0 for success */
8292int
8293ov511_register_decomp_module(int ver, struct ov51x_decomp_ops *ops, int ov518,
8294			     int mmx)
8295{
8296	if (ver != DECOMP_INTERFACE_VER) {
8297		err("Decompression module has incompatible");
8298		err("interface version %d", ver);
8299		err("Interface version %d is required", DECOMP_INTERFACE_VER);
8300		return -EINVAL;
8301	}
8302
8303	if (!ops)
8304		return -EFAULT;
8305
8306	if (mmx && !ov51x_mmx_available) {
8307		err("MMX not available on this system or kernel");
8308		return -EINVAL;
8309	}
8310
8311	lock_kernel();
8312
8313	if (ov518) {
8314		if (mmx) {
8315			if (ov518_mmx_decomp_ops)
8316				goto err_in_use;
8317			else
8318				ov518_mmx_decomp_ops = ops;
8319		} else {
8320			if (ov518_decomp_ops)
8321				goto err_in_use;
8322			else
8323				ov518_decomp_ops = ops;
8324		}
8325	} else {
8326		if (mmx) {
8327			if (ov511_mmx_decomp_ops)
8328				goto err_in_use;
8329			else
8330				ov511_mmx_decomp_ops = ops;
8331		} else {
8332			if (ov511_decomp_ops)
8333				goto err_in_use;
8334			else
8335				ov511_decomp_ops = ops;
8336		}
8337	}
8338
8339	MOD_INC_USE_COUNT;
8340
8341	unlock_kernel();
8342	return 0;
8343
8344err_in_use:
8345	unlock_kernel();
8346	return -EBUSY;
8347}
8348
8349void
8350ov511_deregister_decomp_module(int ov518, int mmx)
8351{
8352	lock_kernel();
8353
8354	if (ov518) {
8355		if (mmx)
8356			ov518_mmx_decomp_ops = NULL;
8357		else
8358			ov518_decomp_ops = NULL;
8359	} else {
8360		if (mmx)
8361			ov511_mmx_decomp_ops = NULL;
8362		else
8363			ov511_decomp_ops = NULL;
8364	}
8365
8366	MOD_DEC_USE_COUNT;
8367
8368	unlock_kernel();
8369}
8370
8371static int __init
8372usb_ov511_init(void)
8373{
8374        proc_ov511_create();
8375
8376	if (usb_register(&ov511_driver) < 0)
8377		return -1;
8378
8379#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 4, 0)
8380#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
8381#if defined (__i386__)
8382	if (test_bit(X86_FEATURE_MMX, boot_cpu_data.x86_capability))
8383		ov51x_mmx_available = 1;
8384#endif
8385#endif
8386#endif
8387
8388	info(DRIVER_VERSION " : " DRIVER_DESC);
8389
8390	return 0;
8391}
8392
8393static void __exit
8394usb_ov511_exit(void)
8395{
8396	usb_deregister(&ov511_driver);
8397	info("driver deregistered");
8398
8399        proc_ov511_destroy();
8400}
8401
8402module_init(usb_ov511_init);
8403module_exit(usb_ov511_exit);
8404
8405EXPORT_SYMBOL(ov511_register_decomp_module);
8406EXPORT_SYMBOL(ov511_deregister_decomp_module);
8407