V4L/DVB (8885): cpia2_usb: fix memory leak
[linux-2.6] / drivers / media / video / ov511.c
1 /*
2  * OmniVision OV511 Camera-to-USB Bridge Driver
3  *
4  * Copyright (c) 1999-2003 Mark W. McClelland
5  * Original decompression code Copyright 1998-2000 OmniVision Technologies
6  * Many improvements by Bret Wallach <bwallac1@san.rr.com>
7  * Color fixes by by Orion Sky Lawlor <olawlor@acm.org> (2/26/2000)
8  * Snapshot code by Kevin Moore
9  * OV7620 fixes by Charl P. Botha <cpbotha@ieee.org>
10  * Changes by Claudio Matsuoka <claudio@conectiva.com>
11  * Original SAA7111A code by Dave Perks <dperks@ibm.net>
12  * URB error messages from pwc driver by Nemosoft
13  * generic_ioctl() code from videodev.c by Gerd Knorr and Alan Cox
14  * Memory management (rvmalloc) code from bttv driver, by Gerd Knorr and others
15  *
16  * Based on the Linux CPiA driver written by Peter Pregler,
17  * Scott J. Bertin and Johannes Erdfelt.
18  *
19  * Please see the file: Documentation/usb/ov511.txt
20  * and the website at:  http://alpha.dyndns.org/ov511
21  * for more info.
22  *
23  * This program is free software; you can redistribute it and/or modify it
24  * under the terms of the GNU General Public License as published by the
25  * Free Software Foundation; either version 2 of the License, or (at your
26  * option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful, but
29  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
30  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
31  * for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program; if not, write to the Free Software Foundation,
35  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36  */
37
38 #include <linux/module.h>
39 #include <linux/init.h>
40 #include <linux/vmalloc.h>
41 #include <linux/slab.h>
42 #include <linux/ctype.h>
43 #include <linux/pagemap.h>
44 #include <asm/processor.h>
45 #include <linux/mm.h>
46 #include <linux/device.h>
47
48 #if defined (__i386__)
49         #include <asm/cpufeature.h>
50 #endif
51
52 #include "ov511.h"
53
54 /*
55  * Version Information
56  */
57 #define DRIVER_VERSION "v1.64 for Linux 2.5"
58 #define EMAIL "mark@alpha.dyndns.org"
59 #define DRIVER_AUTHOR "Mark McClelland <mark@alpha.dyndns.org> & Bret Wallach \
60         & Orion Sky Lawlor <olawlor@acm.org> & Kevin Moore & Charl P. Botha \
61         <cpbotha@ieee.org> & Claudio Matsuoka <claudio@conectiva.com>"
62 #define DRIVER_DESC "ov511 USB Camera Driver"
63
64 #define OV511_I2C_RETRIES 3
65 #define ENABLE_Y_QUANTABLE 1
66 #define ENABLE_UV_QUANTABLE 1
67
68 #define OV511_MAX_UNIT_VIDEO 16
69
70 /* Pixel count * bytes per YUV420 pixel (1.5) */
71 #define MAX_FRAME_SIZE(w, h) ((w) * (h) * 3 / 2)
72
73 #define MAX_DATA_SIZE(w, h) (MAX_FRAME_SIZE(w, h) + sizeof(struct timeval))
74
75 /* Max size * bytes per YUV420 pixel (1.5) + one extra isoc frame for safety */
76 #define MAX_RAW_DATA_SIZE(w, h) ((w) * (h) * 3 / 2 + 1024)
77
78 #define FATAL_ERROR(rc) ((rc) < 0 && (rc) != -EPERM)
79
80 /**********************************************************************
81  * Module Parameters
82  * (See ov511.txt for detailed descriptions of these)
83  **********************************************************************/
84
85 /* These variables (and all static globals) default to zero */
86 static int autobright           = 1;
87 static int autogain             = 1;
88 static int autoexp              = 1;
89 static int debug;
90 static int snapshot;
91 static int cams                 = 1;
92 static int compress;
93 static int testpat;
94 static int dumppix;
95 static int led                  = 1;
96 static int dump_bridge;
97 static int dump_sensor;
98 static int printph;
99 static int phy                  = 0x1f;
100 static int phuv                 = 0x05;
101 static int pvy                  = 0x06;
102 static int pvuv                 = 0x06;
103 static int qhy                  = 0x14;
104 static int qhuv                 = 0x03;
105 static int qvy                  = 0x04;
106 static int qvuv                 = 0x04;
107 static int lightfreq;
108 static int bandingfilter;
109 static int clockdiv             = -1;
110 static int packetsize           = -1;
111 static int framedrop            = -1;
112 static int fastset;
113 static int force_palette;
114 static int backlight;
115 static int unit_video[OV511_MAX_UNIT_VIDEO];
116 static int remove_zeros;
117 static int mirror;
118 static int ov518_color;
119
120 module_param(autobright, int, 0);
121 MODULE_PARM_DESC(autobright, "Sensor automatically changes brightness");
122 module_param(autogain, int, 0);
123 MODULE_PARM_DESC(autogain, "Sensor automatically changes gain");
124 module_param(autoexp, int, 0);
125 MODULE_PARM_DESC(autoexp, "Sensor automatically changes exposure");
126 module_param(debug, int, 0);
127 MODULE_PARM_DESC(debug,
128   "Debug level: 0=none, 1=inits, 2=warning, 3=config, 4=functions, 5=max");
129 module_param(snapshot, int, 0);
130 MODULE_PARM_DESC(snapshot, "Enable snapshot mode");
131 module_param(cams, int, 0);
132 MODULE_PARM_DESC(cams, "Number of simultaneous cameras");
133 module_param(compress, int, 0);
134 MODULE_PARM_DESC(compress, "Turn on compression");
135 module_param(testpat, int, 0);
136 MODULE_PARM_DESC(testpat,
137   "Replace image with vertical bar testpattern (only partially working)");
138 module_param(dumppix, int, 0);
139 MODULE_PARM_DESC(dumppix, "Dump raw pixel data");
140 module_param(led, int, 0);
141 MODULE_PARM_DESC(led,
142   "LED policy (OV511+ or later). 0=off, 1=on (default), 2=auto (on when open)");
143 module_param(dump_bridge, int, 0);
144 MODULE_PARM_DESC(dump_bridge, "Dump the bridge registers");
145 module_param(dump_sensor, int, 0);
146 MODULE_PARM_DESC(dump_sensor, "Dump the sensor registers");
147 module_param(printph, int, 0);
148 MODULE_PARM_DESC(printph, "Print frame start/end headers");
149 module_param(phy, int, 0);
150 MODULE_PARM_DESC(phy, "Prediction range (horiz. Y)");
151 module_param(phuv, int, 0);
152 MODULE_PARM_DESC(phuv, "Prediction range (horiz. UV)");
153 module_param(pvy, int, 0);
154 MODULE_PARM_DESC(pvy, "Prediction range (vert. Y)");
155 module_param(pvuv, int, 0);
156 MODULE_PARM_DESC(pvuv, "Prediction range (vert. UV)");
157 module_param(qhy, int, 0);
158 MODULE_PARM_DESC(qhy, "Quantization threshold (horiz. Y)");
159 module_param(qhuv, int, 0);
160 MODULE_PARM_DESC(qhuv, "Quantization threshold (horiz. UV)");
161 module_param(qvy, int, 0);
162 MODULE_PARM_DESC(qvy, "Quantization threshold (vert. Y)");
163 module_param(qvuv, int, 0);
164 MODULE_PARM_DESC(qvuv, "Quantization threshold (vert. UV)");
165 module_param(lightfreq, int, 0);
166 MODULE_PARM_DESC(lightfreq,
167   "Light frequency. Set to 50 or 60 Hz, or zero for default settings");
168 module_param(bandingfilter, int, 0);
169 MODULE_PARM_DESC(bandingfilter,
170   "Enable banding filter (to reduce effects of fluorescent lighting)");
171 module_param(clockdiv, int, 0);
172 MODULE_PARM_DESC(clockdiv, "Force pixel clock divisor to a specific value");
173 module_param(packetsize, int, 0);
174 MODULE_PARM_DESC(packetsize, "Force a specific isoc packet size");
175 module_param(framedrop, int, 0);
176 MODULE_PARM_DESC(framedrop, "Force a specific frame drop register setting");
177 module_param(fastset, int, 0);
178 MODULE_PARM_DESC(fastset, "Allows picture settings to take effect immediately");
179 module_param(force_palette, int, 0);
180 MODULE_PARM_DESC(force_palette, "Force the palette to a specific value");
181 module_param(backlight, int, 0);
182 MODULE_PARM_DESC(backlight, "For objects that are lit from behind");
183 static unsigned int num_uv;
184 module_param_array(unit_video, int, &num_uv, 0);
185 MODULE_PARM_DESC(unit_video,
186   "Force use of specific minor number(s). 0 is not allowed.");
187 module_param(remove_zeros, int, 0);
188 MODULE_PARM_DESC(remove_zeros,
189   "Remove zero-padding from uncompressed incoming data");
190 module_param(mirror, int, 0);
191 MODULE_PARM_DESC(mirror, "Reverse image horizontally");
192 module_param(ov518_color, int, 0);
193 MODULE_PARM_DESC(ov518_color, "Enable OV518 color (experimental)");
194
195 MODULE_AUTHOR(DRIVER_AUTHOR);
196 MODULE_DESCRIPTION(DRIVER_DESC);
197 MODULE_LICENSE("GPL");
198
199 /**********************************************************************
200  * Miscellaneous Globals
201  **********************************************************************/
202
203 static struct usb_driver ov511_driver;
204
205 /* Number of times to retry a failed I2C transaction. Increase this if you
206  * are getting "Failed to read sensor ID..." */
207 static const int i2c_detect_tries = 5;
208
209 static struct usb_device_id device_table [] = {
210         { USB_DEVICE(VEND_OMNIVISION, PROD_OV511) },
211         { USB_DEVICE(VEND_OMNIVISION, PROD_OV511PLUS) },
212         { USB_DEVICE(VEND_OMNIVISION, PROD_OV518) },
213         { USB_DEVICE(VEND_OMNIVISION, PROD_OV518PLUS) },
214         { USB_DEVICE(VEND_MATTEL, PROD_ME2CAM) },
215         { }  /* Terminating entry */
216 };
217
218 MODULE_DEVICE_TABLE (usb, device_table);
219
220 static unsigned char yQuanTable511[] = OV511_YQUANTABLE;
221 static unsigned char uvQuanTable511[] = OV511_UVQUANTABLE;
222 static unsigned char yQuanTable518[] = OV518_YQUANTABLE;
223 static unsigned char uvQuanTable518[] = OV518_UVQUANTABLE;
224
225 /**********************************************************************
226  * Symbolic Names
227  **********************************************************************/
228
229 /* Known OV511-based cameras */
230 static struct symbolic_list camlist[] = {
231         {   0, "Generic Camera (no ID)" },
232         {   1, "Mustek WCam 3X" },
233         {   3, "D-Link DSB-C300" },
234         {   4, "Generic OV511/OV7610" },
235         {   5, "Puretek PT-6007" },
236         {   6, "Lifeview USB Life TV (NTSC)" },
237         {  21, "Creative Labs WebCam 3" },
238         {  22, "Lifeview USB Life TV (PAL D/K+B/G)" },
239         {  36, "Koala-Cam" },
240         {  38, "Lifeview USB Life TV (PAL)" },
241         {  41, "Samsung Anycam MPC-M10" },
242         {  43, "Mtekvision Zeca MV402" },
243         {  46, "Suma eON" },
244         {  70, "Lifeview USB Life TV (PAL/SECAM)" },
245         { 100, "Lifeview RoboCam" },
246         { 102, "AverMedia InterCam Elite" },
247         { 112, "MediaForte MV300" },    /* or OV7110 evaluation kit */
248         { 134, "Ezonics EZCam II" },
249         { 192, "Webeye 2000B" },
250         { 253, "Alpha Vision Tech. AlphaCam SE" },
251         {  -1, NULL }
252 };
253
254 /* Video4Linux1 Palettes */
255 static struct symbolic_list v4l1_plist[] = {
256         { VIDEO_PALETTE_GREY,   "GREY" },
257         { VIDEO_PALETTE_HI240,  "HI240" },
258         { VIDEO_PALETTE_RGB565, "RGB565" },
259         { VIDEO_PALETTE_RGB24,  "RGB24" },
260         { VIDEO_PALETTE_RGB32,  "RGB32" },
261         { VIDEO_PALETTE_RGB555, "RGB555" },
262         { VIDEO_PALETTE_YUV422, "YUV422" },
263         { VIDEO_PALETTE_YUYV,   "YUYV" },
264         { VIDEO_PALETTE_UYVY,   "UYVY" },
265         { VIDEO_PALETTE_YUV420, "YUV420" },
266         { VIDEO_PALETTE_YUV411, "YUV411" },
267         { VIDEO_PALETTE_RAW,    "RAW" },
268         { VIDEO_PALETTE_YUV422P,"YUV422P" },
269         { VIDEO_PALETTE_YUV411P,"YUV411P" },
270         { VIDEO_PALETTE_YUV420P,"YUV420P" },
271         { VIDEO_PALETTE_YUV410P,"YUV410P" },
272         { -1, NULL }
273 };
274
275 static struct symbolic_list brglist[] = {
276         { BRG_OV511,            "OV511" },
277         { BRG_OV511PLUS,        "OV511+" },
278         { BRG_OV518,            "OV518" },
279         { BRG_OV518PLUS,        "OV518+" },
280         { -1, NULL }
281 };
282
283 static struct symbolic_list senlist[] = {
284         { SEN_OV76BE,   "OV76BE" },
285         { SEN_OV7610,   "OV7610" },
286         { SEN_OV7620,   "OV7620" },
287         { SEN_OV7620AE, "OV7620AE" },
288         { SEN_OV6620,   "OV6620" },
289         { SEN_OV6630,   "OV6630" },
290         { SEN_OV6630AE, "OV6630AE" },
291         { SEN_OV6630AF, "OV6630AF" },
292         { SEN_OV8600,   "OV8600" },
293         { SEN_KS0127,   "KS0127" },
294         { SEN_KS0127B,  "KS0127B" },
295         { SEN_SAA7111A, "SAA7111A" },
296         { -1, NULL }
297 };
298
299 /* URB error codes: */
300 static struct symbolic_list urb_errlist[] = {
301         { -ENOSR,       "Buffer error (overrun)" },
302         { -EPIPE,       "Stalled (device not responding)" },
303         { -EOVERFLOW,   "Babble (device sends too much data)" },
304         { -EPROTO,      "Bit-stuff error (bad cable?)" },
305         { -EILSEQ,      "CRC/Timeout (bad cable?)" },
306         { -ETIME,       "Device does not respond to token" },
307         { -ETIMEDOUT,   "Device does not respond to command" },
308         { -1, NULL }
309 };
310
311 /**********************************************************************
312  * Memory management
313  **********************************************************************/
314 static void *
315 rvmalloc(unsigned long size)
316 {
317         void *mem;
318         unsigned long adr;
319
320         size = PAGE_ALIGN(size);
321         mem = vmalloc_32(size);
322         if (!mem)
323                 return NULL;
324
325         memset(mem, 0, size); /* Clear the ram out, no junk to the user */
326         adr = (unsigned long) mem;
327         while (size > 0) {
328                 SetPageReserved(vmalloc_to_page((void *)adr));
329                 adr += PAGE_SIZE;
330                 size -= PAGE_SIZE;
331         }
332
333         return mem;
334 }
335
336 static void
337 rvfree(void *mem, unsigned long size)
338 {
339         unsigned long adr;
340
341         if (!mem)
342                 return;
343
344         adr = (unsigned long) mem;
345         while ((long) size > 0) {
346                 ClearPageReserved(vmalloc_to_page((void *)adr));
347                 adr += PAGE_SIZE;
348                 size -= PAGE_SIZE;
349         }
350         vfree(mem);
351 }
352
353 /**********************************************************************
354  *
355  * Register I/O
356  *
357  **********************************************************************/
358
359 /* Write an OV51x register */
360 static int
361 reg_w(struct usb_ov511 *ov, unsigned char reg, unsigned char value)
362 {
363         int rc;
364
365         PDEBUG(5, "0x%02X:0x%02X", reg, value);
366
367         mutex_lock(&ov->cbuf_lock);
368         ov->cbuf[0] = value;
369         rc = usb_control_msg(ov->dev,
370                              usb_sndctrlpipe(ov->dev, 0),
371                              (ov->bclass == BCL_OV518)?1:2 /* REG_IO */,
372                              USB_TYPE_VENDOR | USB_RECIP_DEVICE,
373                              0, (__u16)reg, &ov->cbuf[0], 1, 1000);
374         mutex_unlock(&ov->cbuf_lock);
375
376         if (rc < 0)
377                 err("reg write: error %d: %s", rc, symbolic(urb_errlist, rc));
378
379         return rc;
380 }
381
382 /* Read from an OV51x register */
383 /* returns: negative is error, pos or zero is data */
384 static int
385 reg_r(struct usb_ov511 *ov, unsigned char reg)
386 {
387         int rc;
388
389         mutex_lock(&ov->cbuf_lock);
390         rc = usb_control_msg(ov->dev,
391                              usb_rcvctrlpipe(ov->dev, 0),
392                              (ov->bclass == BCL_OV518)?1:3 /* REG_IO */,
393                              USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
394                              0, (__u16)reg, &ov->cbuf[0], 1, 1000);
395
396         if (rc < 0) {
397                 err("reg read: error %d: %s", rc, symbolic(urb_errlist, rc));
398         } else {
399                 rc = ov->cbuf[0];
400                 PDEBUG(5, "0x%02X:0x%02X", reg, ov->cbuf[0]);
401         }
402
403         mutex_unlock(&ov->cbuf_lock);
404
405         return rc;
406 }
407
408 /*
409  * Writes bits at positions specified by mask to an OV51x reg. Bits that are in
410  * the same position as 1's in "mask" are cleared and set to "value". Bits
411  * that are in the same position as 0's in "mask" are preserved, regardless
412  * of their respective state in "value".
413  */
414 static int
415 reg_w_mask(struct usb_ov511 *ov,
416            unsigned char reg,
417            unsigned char value,
418            unsigned char mask)
419 {
420         int ret;
421         unsigned char oldval, newval;
422
423         ret = reg_r(ov, reg);
424         if (ret < 0)
425                 return ret;
426
427         oldval = (unsigned char) ret;
428         oldval &= (~mask);              /* Clear the masked bits */
429         value &= mask;                  /* Enforce mask on value */
430         newval = oldval | value;        /* Set the desired bits */
431
432         return (reg_w(ov, reg, newval));
433 }
434
435 /*
436  * Writes multiple (n) byte value to a single register. Only valid with certain
437  * registers (0x30 and 0xc4 - 0xce).
438  */
439 static int
440 ov518_reg_w32(struct usb_ov511 *ov, unsigned char reg, u32 val, int n)
441 {
442         int rc;
443
444         PDEBUG(5, "0x%02X:%7d, n=%d", reg, val, n);
445
446         mutex_lock(&ov->cbuf_lock);
447
448         *((__le32 *)ov->cbuf) = __cpu_to_le32(val);
449
450         rc = usb_control_msg(ov->dev,
451                              usb_sndctrlpipe(ov->dev, 0),
452                              1 /* REG_IO */,
453                              USB_TYPE_VENDOR | USB_RECIP_DEVICE,
454                              0, (__u16)reg, ov->cbuf, n, 1000);
455         mutex_unlock(&ov->cbuf_lock);
456
457         if (rc < 0)
458                 err("reg write multiple: error %d: %s", rc,
459                     symbolic(urb_errlist, rc));
460
461         return rc;
462 }
463
464 static int
465 ov511_upload_quan_tables(struct usb_ov511 *ov)
466 {
467         unsigned char *pYTable = yQuanTable511;
468         unsigned char *pUVTable = uvQuanTable511;
469         unsigned char val0, val1;
470         int i, rc, reg = R511_COMP_LUT_BEGIN;
471
472         PDEBUG(4, "Uploading quantization tables");
473
474         for (i = 0; i < OV511_QUANTABLESIZE / 2; i++) {
475                 if (ENABLE_Y_QUANTABLE) {
476                         val0 = *pYTable++;
477                         val1 = *pYTable++;
478                         val0 &= 0x0f;
479                         val1 &= 0x0f;
480                         val0 |= val1 << 4;
481                         rc = reg_w(ov, reg, val0);
482                         if (rc < 0)
483                                 return rc;
484                 }
485
486                 if (ENABLE_UV_QUANTABLE) {
487                         val0 = *pUVTable++;
488                         val1 = *pUVTable++;
489                         val0 &= 0x0f;
490                         val1 &= 0x0f;
491                         val0 |= val1 << 4;
492                         rc = reg_w(ov, reg + OV511_QUANTABLESIZE/2, val0);
493                         if (rc < 0)
494                                 return rc;
495                 }
496
497                 reg++;
498         }
499
500         return 0;
501 }
502
503 /* OV518 quantization tables are 8x4 (instead of 8x8) */
504 static int
505 ov518_upload_quan_tables(struct usb_ov511 *ov)
506 {
507         unsigned char *pYTable = yQuanTable518;
508         unsigned char *pUVTable = uvQuanTable518;
509         unsigned char val0, val1;
510         int i, rc, reg = R511_COMP_LUT_BEGIN;
511
512         PDEBUG(4, "Uploading quantization tables");
513
514         for (i = 0; i < OV518_QUANTABLESIZE / 2; i++) {
515                 if (ENABLE_Y_QUANTABLE) {
516                         val0 = *pYTable++;
517                         val1 = *pYTable++;
518                         val0 &= 0x0f;
519                         val1 &= 0x0f;
520                         val0 |= val1 << 4;
521                         rc = reg_w(ov, reg, val0);
522                         if (rc < 0)
523                                 return rc;
524                 }
525
526                 if (ENABLE_UV_QUANTABLE) {
527                         val0 = *pUVTable++;
528                         val1 = *pUVTable++;
529                         val0 &= 0x0f;
530                         val1 &= 0x0f;
531                         val0 |= val1 << 4;
532                         rc = reg_w(ov, reg + OV518_QUANTABLESIZE/2, val0);
533                         if (rc < 0)
534                                 return rc;
535                 }
536
537                 reg++;
538         }
539
540         return 0;
541 }
542
543 static int
544 ov51x_reset(struct usb_ov511 *ov, unsigned char reset_type)
545 {
546         int rc;
547
548         /* Setting bit 0 not allowed on 518/518Plus */
549         if (ov->bclass == BCL_OV518)
550                 reset_type &= 0xfe;
551
552         PDEBUG(4, "Reset: type=0x%02X", reset_type);
553
554         rc = reg_w(ov, R51x_SYS_RESET, reset_type);
555         rc = reg_w(ov, R51x_SYS_RESET, 0);
556
557         if (rc < 0)
558                 err("reset: command failed");
559
560         return rc;
561 }
562
563 /**********************************************************************
564  *
565  * Low-level I2C I/O functions
566  *
567  **********************************************************************/
568
569 /* NOTE: Do not call this function directly!
570  * The OV518 I2C I/O procedure is different, hence, this function.
571  * This is normally only called from i2c_w(). Note that this function
572  * always succeeds regardless of whether the sensor is present and working.
573  */
574 static int
575 ov518_i2c_write_internal(struct usb_ov511 *ov,
576                          unsigned char reg,
577                          unsigned char value)
578 {
579         int rc;
580
581         PDEBUG(5, "0x%02X:0x%02X", reg, value);
582
583         /* Select camera register */
584         rc = reg_w(ov, R51x_I2C_SADDR_3, reg);
585         if (rc < 0)
586                 return rc;
587
588         /* Write "value" to I2C data port of OV511 */
589         rc = reg_w(ov, R51x_I2C_DATA, value);
590         if (rc < 0)
591                 return rc;
592
593         /* Initiate 3-byte write cycle */
594         rc = reg_w(ov, R518_I2C_CTL, 0x01);
595         if (rc < 0)
596                 return rc;
597
598         return 0;
599 }
600
601 /* NOTE: Do not call this function directly! */
602 static int
603 ov511_i2c_write_internal(struct usb_ov511 *ov,
604                          unsigned char reg,
605                          unsigned char value)
606 {
607         int rc, retries;
608
609         PDEBUG(5, "0x%02X:0x%02X", reg, value);
610
611         /* Three byte write cycle */
612         for (retries = OV511_I2C_RETRIES; ; ) {
613                 /* Select camera register */
614                 rc = reg_w(ov, R51x_I2C_SADDR_3, reg);
615                 if (rc < 0)
616                         break;
617
618                 /* Write "value" to I2C data port of OV511 */
619                 rc = reg_w(ov, R51x_I2C_DATA, value);
620                 if (rc < 0)
621                         break;
622
623                 /* Initiate 3-byte write cycle */
624                 rc = reg_w(ov, R511_I2C_CTL, 0x01);
625                 if (rc < 0)
626                         break;
627
628                 /* Retry until idle */
629                 do {
630                         rc = reg_r(ov, R511_I2C_CTL);
631                 } while (rc > 0 && ((rc&1) == 0));
632                 if (rc < 0)
633                         break;
634
635                 /* Ack? */
636                 if ((rc&2) == 0) {
637                         rc = 0;
638                         break;
639                 }
640 #if 0
641                 /* I2C abort */
642                 reg_w(ov, R511_I2C_CTL, 0x10);
643 #endif
644                 if (--retries < 0) {
645                         err("i2c write retries exhausted");
646                         rc = -1;
647                         break;
648                 }
649         }
650
651         return rc;
652 }
653
654 /* NOTE: Do not call this function directly!
655  * The OV518 I2C I/O procedure is different, hence, this function.
656  * This is normally only called from i2c_r(). Note that this function
657  * always succeeds regardless of whether the sensor is present and working.
658  */
659 static int
660 ov518_i2c_read_internal(struct usb_ov511 *ov, unsigned char reg)
661 {
662         int rc, value;
663
664         /* Select camera register */
665         rc = reg_w(ov, R51x_I2C_SADDR_2, reg);
666         if (rc < 0)
667                 return rc;
668
669         /* Initiate 2-byte write cycle */
670         rc = reg_w(ov, R518_I2C_CTL, 0x03);
671         if (rc < 0)
672                 return rc;
673
674         /* Initiate 2-byte read cycle */
675         rc = reg_w(ov, R518_I2C_CTL, 0x05);
676         if (rc < 0)
677                 return rc;
678
679         value = reg_r(ov, R51x_I2C_DATA);
680
681         PDEBUG(5, "0x%02X:0x%02X", reg, value);
682
683         return value;
684 }
685
686 /* NOTE: Do not call this function directly!
687  * returns: negative is error, pos or zero is data */
688 static int
689 ov511_i2c_read_internal(struct usb_ov511 *ov, unsigned char reg)
690 {
691         int rc, value, retries;
692
693         /* Two byte write cycle */
694         for (retries = OV511_I2C_RETRIES; ; ) {
695                 /* Select camera register */
696                 rc = reg_w(ov, R51x_I2C_SADDR_2, reg);
697                 if (rc < 0)
698                         return rc;
699
700                 /* Initiate 2-byte write cycle */
701                 rc = reg_w(ov, R511_I2C_CTL, 0x03);
702                 if (rc < 0)
703                         return rc;
704
705                 /* Retry until idle */
706                 do {
707                         rc = reg_r(ov, R511_I2C_CTL);
708                 } while (rc > 0 && ((rc & 1) == 0));
709                 if (rc < 0)
710                         return rc;
711
712                 if ((rc&2) == 0) /* Ack? */
713                         break;
714
715                 /* I2C abort */
716                 reg_w(ov, R511_I2C_CTL, 0x10);
717
718                 if (--retries < 0) {
719                         err("i2c write retries exhausted");
720                         return -1;
721                 }
722         }
723
724         /* Two byte read cycle */
725         for (retries = OV511_I2C_RETRIES; ; ) {
726                 /* Initiate 2-byte read cycle */
727                 rc = reg_w(ov, R511_I2C_CTL, 0x05);
728                 if (rc < 0)
729                         return rc;
730
731                 /* Retry until idle */
732                 do {
733                         rc = reg_r(ov, R511_I2C_CTL);
734                 } while (rc > 0 && ((rc&1) == 0));
735                 if (rc < 0)
736                         return rc;
737
738                 if ((rc&2) == 0) /* Ack? */
739                         break;
740
741                 /* I2C abort */
742                 rc = reg_w(ov, R511_I2C_CTL, 0x10);
743                 if (rc < 0)
744                         return rc;
745
746                 if (--retries < 0) {
747                         err("i2c read retries exhausted");
748                         return -1;
749                 }
750         }
751
752         value = reg_r(ov, R51x_I2C_DATA);
753
754         PDEBUG(5, "0x%02X:0x%02X", reg, value);
755
756         /* This is needed to make i2c_w() work */
757         rc = reg_w(ov, R511_I2C_CTL, 0x05);
758         if (rc < 0)
759                 return rc;
760
761         return value;
762 }
763
764 /* returns: negative is error, pos or zero is data */
765 static int
766 i2c_r(struct usb_ov511 *ov, unsigned char reg)
767 {
768         int rc;
769
770         mutex_lock(&ov->i2c_lock);
771
772         if (ov->bclass == BCL_OV518)
773                 rc = ov518_i2c_read_internal(ov, reg);
774         else
775                 rc = ov511_i2c_read_internal(ov, reg);
776
777         mutex_unlock(&ov->i2c_lock);
778
779         return rc;
780 }
781
782 static int
783 i2c_w(struct usb_ov511 *ov, unsigned char reg, unsigned char value)
784 {
785         int rc;
786
787         mutex_lock(&ov->i2c_lock);
788
789         if (ov->bclass == BCL_OV518)
790                 rc = ov518_i2c_write_internal(ov, reg, value);
791         else
792                 rc = ov511_i2c_write_internal(ov, reg, value);
793
794         mutex_unlock(&ov->i2c_lock);
795
796         return rc;
797 }
798
799 /* Do not call this function directly! */
800 static int
801 ov51x_i2c_write_mask_internal(struct usb_ov511 *ov,
802                               unsigned char reg,
803                               unsigned char value,
804                               unsigned char mask)
805 {
806         int rc;
807         unsigned char oldval, newval;
808
809         if (mask == 0xff) {
810                 newval = value;
811         } else {
812                 if (ov->bclass == BCL_OV518)
813                         rc = ov518_i2c_read_internal(ov, reg);
814                 else
815                         rc = ov511_i2c_read_internal(ov, reg);
816                 if (rc < 0)
817                         return rc;
818
819                 oldval = (unsigned char) rc;
820                 oldval &= (~mask);              /* Clear the masked bits */
821                 value &= mask;                  /* Enforce mask on value */
822                 newval = oldval | value;        /* Set the desired bits */
823         }
824
825         if (ov->bclass == BCL_OV518)
826                 return (ov518_i2c_write_internal(ov, reg, newval));
827         else
828                 return (ov511_i2c_write_internal(ov, reg, newval));
829 }
830
831 /* Writes bits at positions specified by mask to an I2C reg. Bits that are in
832  * the same position as 1's in "mask" are cleared and set to "value". Bits
833  * that are in the same position as 0's in "mask" are preserved, regardless
834  * of their respective state in "value".
835  */
836 static int
837 i2c_w_mask(struct usb_ov511 *ov,
838            unsigned char reg,
839            unsigned char value,
840            unsigned char mask)
841 {
842         int rc;
843
844         mutex_lock(&ov->i2c_lock);
845         rc = ov51x_i2c_write_mask_internal(ov, reg, value, mask);
846         mutex_unlock(&ov->i2c_lock);
847
848         return rc;
849 }
850
851 /* Set the read and write slave IDs. The "slave" argument is the write slave,
852  * and the read slave will be set to (slave + 1). ov->i2c_lock should be held
853  * when calling this. This should not be called from outside the i2c I/O
854  * functions.
855  */
856 static int
857 i2c_set_slave_internal(struct usb_ov511 *ov, unsigned char slave)
858 {
859         int rc;
860
861         rc = reg_w(ov, R51x_I2C_W_SID, slave);
862         if (rc < 0)
863                 return rc;
864
865         rc = reg_w(ov, R51x_I2C_R_SID, slave + 1);
866         if (rc < 0)
867                 return rc;
868
869         return 0;
870 }
871
872 /* Write to a specific I2C slave ID and register, using the specified mask */
873 static int
874 i2c_w_slave(struct usb_ov511 *ov,
875             unsigned char slave,
876             unsigned char reg,
877             unsigned char value,
878             unsigned char mask)
879 {
880         int rc = 0;
881
882         mutex_lock(&ov->i2c_lock);
883
884         /* Set new slave IDs */
885         rc = i2c_set_slave_internal(ov, slave);
886         if (rc < 0)
887                 goto out;
888
889         rc = ov51x_i2c_write_mask_internal(ov, reg, value, mask);
890
891 out:
892         /* Restore primary IDs */
893         if (i2c_set_slave_internal(ov, ov->primary_i2c_slave) < 0)
894                 err("Couldn't restore primary I2C slave");
895
896         mutex_unlock(&ov->i2c_lock);
897         return rc;
898 }
899
900 /* Read from a specific I2C slave ID and register */
901 static int
902 i2c_r_slave(struct usb_ov511 *ov,
903             unsigned char slave,
904             unsigned char reg)
905 {
906         int rc;
907
908         mutex_lock(&ov->i2c_lock);
909
910         /* Set new slave IDs */
911         rc = i2c_set_slave_internal(ov, slave);
912         if (rc < 0)
913                 goto out;
914
915         if (ov->bclass == BCL_OV518)
916                 rc = ov518_i2c_read_internal(ov, reg);
917         else
918                 rc = ov511_i2c_read_internal(ov, reg);
919
920 out:
921         /* Restore primary IDs */
922         if (i2c_set_slave_internal(ov, ov->primary_i2c_slave) < 0)
923                 err("Couldn't restore primary I2C slave");
924
925         mutex_unlock(&ov->i2c_lock);
926         return rc;
927 }
928
929 /* Sets I2C read and write slave IDs. Returns <0 for error */
930 static int
931 ov51x_set_slave_ids(struct usb_ov511 *ov, unsigned char sid)
932 {
933         int rc;
934
935         mutex_lock(&ov->i2c_lock);
936
937         rc = i2c_set_slave_internal(ov, sid);
938         if (rc < 0)
939                 goto out;
940
941         // FIXME: Is this actually necessary?
942         rc = ov51x_reset(ov, OV511_RESET_NOREGS);
943 out:
944         mutex_unlock(&ov->i2c_lock);
945         return rc;
946 }
947
948 static int
949 write_regvals(struct usb_ov511 *ov, struct ov511_regvals * pRegvals)
950 {
951         int rc;
952
953         while (pRegvals->bus != OV511_DONE_BUS) {
954                 if (pRegvals->bus == OV511_REG_BUS) {
955                         if ((rc = reg_w(ov, pRegvals->reg, pRegvals->val)) < 0)
956                                 return rc;
957                 } else if (pRegvals->bus == OV511_I2C_BUS) {
958                         if ((rc = i2c_w(ov, pRegvals->reg, pRegvals->val)) < 0)
959                                 return rc;
960                 } else {
961                         err("Bad regval array");
962                         return -1;
963                 }
964                 pRegvals++;
965         }
966         return 0;
967 }
968
969 #ifdef OV511_DEBUG
970 static void
971 dump_i2c_range(struct usb_ov511 *ov, int reg1, int regn)
972 {
973         int i, rc;
974
975         for (i = reg1; i <= regn; i++) {
976                 rc = i2c_r(ov, i);
977                 info("Sensor[0x%02X] = 0x%02X", i, rc);
978         }
979 }
980
981 static void
982 dump_i2c_regs(struct usb_ov511 *ov)
983 {
984         info("I2C REGS");
985         dump_i2c_range(ov, 0x00, 0x7C);
986 }
987
988 static void
989 dump_reg_range(struct usb_ov511 *ov, int reg1, int regn)
990 {
991         int i, rc;
992
993         for (i = reg1; i <= regn; i++) {
994                 rc = reg_r(ov, i);
995                 info("OV511[0x%02X] = 0x%02X", i, rc);
996         }
997 }
998
999 static void
1000 ov511_dump_regs(struct usb_ov511 *ov)
1001 {
1002         info("CAMERA INTERFACE REGS");
1003         dump_reg_range(ov, 0x10, 0x1f);
1004         info("DRAM INTERFACE REGS");
1005         dump_reg_range(ov, 0x20, 0x23);
1006         info("ISO FIFO REGS");
1007         dump_reg_range(ov, 0x30, 0x31);
1008         info("PIO REGS");
1009         dump_reg_range(ov, 0x38, 0x39);
1010         dump_reg_range(ov, 0x3e, 0x3e);
1011         info("I2C REGS");
1012         dump_reg_range(ov, 0x40, 0x49);
1013         info("SYSTEM CONTROL REGS");
1014         dump_reg_range(ov, 0x50, 0x55);
1015         dump_reg_range(ov, 0x5e, 0x5f);
1016         info("OmniCE REGS");
1017         dump_reg_range(ov, 0x70, 0x79);
1018         /* NOTE: Quantization tables are not readable. You will get the value
1019          * in reg. 0x79 for every table register */
1020         dump_reg_range(ov, 0x80, 0x9f);
1021         dump_reg_range(ov, 0xa0, 0xbf);
1022
1023 }
1024
1025 static void
1026 ov518_dump_regs(struct usb_ov511 *ov)
1027 {
1028         info("VIDEO MODE REGS");
1029         dump_reg_range(ov, 0x20, 0x2f);
1030         info("DATA PUMP AND SNAPSHOT REGS");
1031         dump_reg_range(ov, 0x30, 0x3f);
1032         info("I2C REGS");
1033         dump_reg_range(ov, 0x40, 0x4f);
1034         info("SYSTEM CONTROL AND VENDOR REGS");
1035         dump_reg_range(ov, 0x50, 0x5f);
1036         info("60 - 6F");
1037         dump_reg_range(ov, 0x60, 0x6f);
1038         info("70 - 7F");
1039         dump_reg_range(ov, 0x70, 0x7f);
1040         info("Y QUANTIZATION TABLE");
1041         dump_reg_range(ov, 0x80, 0x8f);
1042         info("UV QUANTIZATION TABLE");
1043         dump_reg_range(ov, 0x90, 0x9f);
1044         info("A0 - BF");
1045         dump_reg_range(ov, 0xa0, 0xbf);
1046         info("CBR");
1047         dump_reg_range(ov, 0xc0, 0xcf);
1048 }
1049 #endif
1050
1051 /*****************************************************************************/
1052
1053 /* Temporarily stops OV511 from functioning. Must do this before changing
1054  * registers while the camera is streaming */
1055 static inline int
1056 ov51x_stop(struct usb_ov511 *ov)
1057 {
1058         PDEBUG(4, "stopping");
1059         ov->stopped = 1;
1060         if (ov->bclass == BCL_OV518)
1061                 return (reg_w_mask(ov, R51x_SYS_RESET, 0x3a, 0x3a));
1062         else
1063                 return (reg_w(ov, R51x_SYS_RESET, 0x3d));
1064 }
1065
1066 /* Restarts OV511 after ov511_stop() is called. Has no effect if it is not
1067  * actually stopped (for performance). */
1068 static inline int
1069 ov51x_restart(struct usb_ov511 *ov)
1070 {
1071         if (ov->stopped) {
1072                 PDEBUG(4, "restarting");
1073                 ov->stopped = 0;
1074
1075                 /* Reinitialize the stream */
1076                 if (ov->bclass == BCL_OV518)
1077                         reg_w(ov, 0x2f, 0x80);
1078
1079                 return (reg_w(ov, R51x_SYS_RESET, 0x00));
1080         }
1081
1082         return 0;
1083 }
1084
1085 /* Sleeps until no frames are active. Returns !0 if got signal */
1086 static int
1087 ov51x_wait_frames_inactive(struct usb_ov511 *ov)
1088 {
1089         return wait_event_interruptible(ov->wq, ov->curframe < 0);
1090 }
1091
1092 /* Resets the hardware snapshot button */
1093 static void
1094 ov51x_clear_snapshot(struct usb_ov511 *ov)
1095 {
1096         if (ov->bclass == BCL_OV511) {
1097                 reg_w(ov, R51x_SYS_SNAP, 0x00);
1098                 reg_w(ov, R51x_SYS_SNAP, 0x02);
1099                 reg_w(ov, R51x_SYS_SNAP, 0x00);
1100         } else if (ov->bclass == BCL_OV518) {
1101                 warn("snapshot reset not supported yet on OV518(+)");
1102         } else {
1103                 err("clear snap: invalid bridge type");
1104         }
1105 }
1106
1107 #if 0
1108 /* Checks the status of the snapshot button. Returns 1 if it was pressed since
1109  * it was last cleared, and zero in all other cases (including errors) */
1110 static int
1111 ov51x_check_snapshot(struct usb_ov511 *ov)
1112 {
1113         int ret, status = 0;
1114
1115         if (ov->bclass == BCL_OV511) {
1116                 ret = reg_r(ov, R51x_SYS_SNAP);
1117                 if (ret < 0) {
1118                         err("Error checking snspshot status (%d)", ret);
1119                 } else if (ret & 0x08) {
1120                         status = 1;
1121                 }
1122         } else if (ov->bclass == BCL_OV518) {
1123                 warn("snapshot check not supported yet on OV518(+)");
1124         } else {
1125                 err("check snap: invalid bridge type");
1126         }
1127
1128         return status;
1129 }
1130 #endif
1131
1132 /* This does an initial reset of an OmniVision sensor and ensures that I2C
1133  * is synchronized. Returns <0 for failure.
1134  */
1135 static int
1136 init_ov_sensor(struct usb_ov511 *ov)
1137 {
1138         int i, success;
1139
1140         /* Reset the sensor */
1141         if (i2c_w(ov, 0x12, 0x80) < 0)
1142                 return -EIO;
1143
1144         /* Wait for it to initialize */
1145         msleep(150);
1146
1147         for (i = 0, success = 0; i < i2c_detect_tries && !success; i++) {
1148                 if ((i2c_r(ov, OV7610_REG_ID_HIGH) == 0x7F) &&
1149                     (i2c_r(ov, OV7610_REG_ID_LOW) == 0xA2)) {
1150                         success = 1;
1151                         continue;
1152                 }
1153
1154                 /* Reset the sensor */
1155                 if (i2c_w(ov, 0x12, 0x80) < 0)
1156                         return -EIO;
1157                 /* Wait for it to initialize */
1158                 msleep(150);
1159                 /* Dummy read to sync I2C */
1160                 if (i2c_r(ov, 0x00) < 0)
1161                         return -EIO;
1162         }
1163
1164         if (!success)
1165                 return -EIO;
1166
1167         PDEBUG(1, "I2C synced in %d attempt(s)", i);
1168
1169         return 0;
1170 }
1171
1172 static int
1173 ov511_set_packet_size(struct usb_ov511 *ov, int size)
1174 {
1175         int alt, mult;
1176
1177         if (ov51x_stop(ov) < 0)
1178                 return -EIO;
1179
1180         mult = size >> 5;
1181
1182         if (ov->bridge == BRG_OV511) {
1183                 if (size == 0)
1184                         alt = OV511_ALT_SIZE_0;
1185                 else if (size == 257)
1186                         alt = OV511_ALT_SIZE_257;
1187                 else if (size == 513)
1188                         alt = OV511_ALT_SIZE_513;
1189                 else if (size == 769)
1190                         alt = OV511_ALT_SIZE_769;
1191                 else if (size == 993)
1192                         alt = OV511_ALT_SIZE_993;
1193                 else {
1194                         err("Set packet size: invalid size (%d)", size);
1195                         return -EINVAL;
1196                 }
1197         } else if (ov->bridge == BRG_OV511PLUS) {
1198                 if (size == 0)
1199                         alt = OV511PLUS_ALT_SIZE_0;
1200                 else if (size == 33)
1201                         alt = OV511PLUS_ALT_SIZE_33;
1202                 else if (size == 129)
1203                         alt = OV511PLUS_ALT_SIZE_129;
1204                 else if (size == 257)
1205                         alt = OV511PLUS_ALT_SIZE_257;
1206                 else if (size == 385)
1207                         alt = OV511PLUS_ALT_SIZE_385;
1208                 else if (size == 513)
1209                         alt = OV511PLUS_ALT_SIZE_513;
1210                 else if (size == 769)
1211                         alt = OV511PLUS_ALT_SIZE_769;
1212                 else if (size == 961)
1213                         alt = OV511PLUS_ALT_SIZE_961;
1214                 else {
1215                         err("Set packet size: invalid size (%d)", size);
1216                         return -EINVAL;
1217                 }
1218         } else {
1219                 err("Set packet size: Invalid bridge type");
1220                 return -EINVAL;
1221         }
1222
1223         PDEBUG(3, "%d, mult=%d, alt=%d", size, mult, alt);
1224
1225         if (reg_w(ov, R51x_FIFO_PSIZE, mult) < 0)
1226                 return -EIO;
1227
1228         if (usb_set_interface(ov->dev, ov->iface, alt) < 0) {
1229                 err("Set packet size: set interface error");
1230                 return -EBUSY;
1231         }
1232
1233         if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
1234                 return -EIO;
1235
1236         ov->packet_size = size;
1237
1238         if (ov51x_restart(ov) < 0)
1239                 return -EIO;
1240
1241         return 0;
1242 }
1243
1244 /* Note: Unlike the OV511/OV511+, the size argument does NOT include the
1245  * optional packet number byte. The actual size *is* stored in ov->packet_size,
1246  * though. */
1247 static int
1248 ov518_set_packet_size(struct usb_ov511 *ov, int size)
1249 {
1250         int alt;
1251
1252         if (ov51x_stop(ov) < 0)
1253                 return -EIO;
1254
1255         if (ov->bclass == BCL_OV518) {
1256                 if (size == 0)
1257                         alt = OV518_ALT_SIZE_0;
1258                 else if (size == 128)
1259                         alt = OV518_ALT_SIZE_128;
1260                 else if (size == 256)
1261                         alt = OV518_ALT_SIZE_256;
1262                 else if (size == 384)
1263                         alt = OV518_ALT_SIZE_384;
1264                 else if (size == 512)
1265                         alt = OV518_ALT_SIZE_512;
1266                 else if (size == 640)
1267                         alt = OV518_ALT_SIZE_640;
1268                 else if (size == 768)
1269                         alt = OV518_ALT_SIZE_768;
1270                 else if (size == 896)
1271                         alt = OV518_ALT_SIZE_896;
1272                 else {
1273                         err("Set packet size: invalid size (%d)", size);
1274                         return -EINVAL;
1275                 }
1276         } else {
1277                 err("Set packet size: Invalid bridge type");
1278                 return -EINVAL;
1279         }
1280
1281         PDEBUG(3, "%d, alt=%d", size, alt);
1282
1283         ov->packet_size = size;
1284         if (size > 0) {
1285                 /* Program ISO FIFO size reg (packet number isn't included) */
1286                 ov518_reg_w32(ov, 0x30, size, 2);
1287
1288                 if (ov->packet_numbering)
1289                         ++ov->packet_size;
1290         }
1291
1292         if (usb_set_interface(ov->dev, ov->iface, alt) < 0) {
1293                 err("Set packet size: set interface error");
1294                 return -EBUSY;
1295         }
1296
1297         /* Initialize the stream */
1298         if (reg_w(ov, 0x2f, 0x80) < 0)
1299                 return -EIO;
1300
1301         if (ov51x_restart(ov) < 0)
1302                 return -EIO;
1303
1304         if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
1305                 return -EIO;
1306
1307         return 0;
1308 }
1309
1310 /* Upload compression params and quantization tables. Returns 0 for success. */
1311 static int
1312 ov511_init_compression(struct usb_ov511 *ov)
1313 {
1314         int rc = 0;
1315
1316         if (!ov->compress_inited) {
1317                 reg_w(ov, 0x70, phy);
1318                 reg_w(ov, 0x71, phuv);
1319                 reg_w(ov, 0x72, pvy);
1320                 reg_w(ov, 0x73, pvuv);
1321                 reg_w(ov, 0x74, qhy);
1322                 reg_w(ov, 0x75, qhuv);
1323                 reg_w(ov, 0x76, qvy);
1324                 reg_w(ov, 0x77, qvuv);
1325
1326                 if (ov511_upload_quan_tables(ov) < 0) {
1327                         err("Error uploading quantization tables");
1328                         rc = -EIO;
1329                         goto out;
1330                 }
1331         }
1332
1333         ov->compress_inited = 1;
1334 out:
1335         return rc;
1336 }
1337
1338 /* Upload compression params and quantization tables. Returns 0 for success. */
1339 static int
1340 ov518_init_compression(struct usb_ov511 *ov)
1341 {
1342         int rc = 0;
1343
1344         if (!ov->compress_inited) {
1345                 if (ov518_upload_quan_tables(ov) < 0) {
1346                         err("Error uploading quantization tables");
1347                         rc = -EIO;
1348                         goto out;
1349                 }
1350         }
1351
1352         ov->compress_inited = 1;
1353 out:
1354         return rc;
1355 }
1356
1357 /* -------------------------------------------------------------------------- */
1358
1359 /* Sets sensor's contrast setting to "val" */
1360 static int
1361 sensor_set_contrast(struct usb_ov511 *ov, unsigned short val)
1362 {
1363         int rc;
1364
1365         PDEBUG(3, "%d", val);
1366
1367         if (ov->stop_during_set)
1368                 if (ov51x_stop(ov) < 0)
1369                         return -EIO;
1370
1371         switch (ov->sensor) {
1372         case SEN_OV7610:
1373         case SEN_OV6620:
1374         {
1375                 rc = i2c_w(ov, OV7610_REG_CNT, val >> 8);
1376                 if (rc < 0)
1377                         goto out;
1378                 break;
1379         }
1380         case SEN_OV6630:
1381         {
1382                 rc = i2c_w_mask(ov, OV7610_REG_CNT, val >> 12, 0x0f);
1383                 if (rc < 0)
1384                         goto out;
1385                 break;
1386         }
1387         case SEN_OV7620:
1388         {
1389                 unsigned char ctab[] = {
1390                         0x01, 0x05, 0x09, 0x11, 0x15, 0x35, 0x37, 0x57,
1391                         0x5b, 0xa5, 0xa7, 0xc7, 0xc9, 0xcf, 0xef, 0xff
1392                 };
1393
1394                 /* Use Y gamma control instead. Bit 0 enables it. */
1395                 rc = i2c_w(ov, 0x64, ctab[val>>12]);
1396                 if (rc < 0)
1397                         goto out;
1398                 break;
1399         }
1400         case SEN_SAA7111A:
1401         {
1402                 rc = i2c_w(ov, 0x0b, val >> 9);
1403                 if (rc < 0)
1404                         goto out;
1405                 break;
1406         }
1407         default:
1408         {
1409                 PDEBUG(3, "Unsupported with this sensor");
1410                 rc = -EPERM;
1411                 goto out;
1412         }
1413         }
1414
1415         rc = 0;         /* Success */
1416         ov->contrast = val;
1417 out:
1418         if (ov51x_restart(ov) < 0)
1419                 return -EIO;
1420
1421         return rc;
1422 }
1423
1424 /* Gets sensor's contrast setting */
1425 static int
1426 sensor_get_contrast(struct usb_ov511 *ov, unsigned short *val)
1427 {
1428         int rc;
1429
1430         switch (ov->sensor) {
1431         case SEN_OV7610:
1432         case SEN_OV6620:
1433                 rc = i2c_r(ov, OV7610_REG_CNT);
1434                 if (rc < 0)
1435                         return rc;
1436                 else
1437                         *val = rc << 8;
1438                 break;
1439         case SEN_OV6630:
1440                 rc = i2c_r(ov, OV7610_REG_CNT);
1441                 if (rc < 0)
1442                         return rc;
1443                 else
1444                         *val = rc << 12;
1445                 break;
1446         case SEN_OV7620:
1447                 /* Use Y gamma reg instead. Bit 0 is the enable bit. */
1448                 rc = i2c_r(ov, 0x64);
1449                 if (rc < 0)
1450                         return rc;
1451                 else
1452                         *val = (rc & 0xfe) << 8;
1453                 break;
1454         case SEN_SAA7111A:
1455                 *val = ov->contrast;
1456                 break;
1457         default:
1458                 PDEBUG(3, "Unsupported with this sensor");
1459                 return -EPERM;
1460         }
1461
1462         PDEBUG(3, "%d", *val);
1463         ov->contrast = *val;
1464
1465         return 0;
1466 }
1467
1468 /* -------------------------------------------------------------------------- */
1469
1470 /* Sets sensor's brightness setting to "val" */
1471 static int
1472 sensor_set_brightness(struct usb_ov511 *ov, unsigned short val)
1473 {
1474         int rc;
1475
1476         PDEBUG(4, "%d", val);
1477
1478         if (ov->stop_during_set)
1479                 if (ov51x_stop(ov) < 0)
1480                         return -EIO;
1481
1482         switch (ov->sensor) {
1483         case SEN_OV7610:
1484         case SEN_OV76BE:
1485         case SEN_OV6620:
1486         case SEN_OV6630:
1487                 rc = i2c_w(ov, OV7610_REG_BRT, val >> 8);
1488                 if (rc < 0)
1489                         goto out;
1490                 break;
1491         case SEN_OV7620:
1492                 /* 7620 doesn't like manual changes when in auto mode */
1493                 if (!ov->auto_brt) {
1494                         rc = i2c_w(ov, OV7610_REG_BRT, val >> 8);
1495                         if (rc < 0)
1496                                 goto out;
1497                 }
1498                 break;
1499         case SEN_SAA7111A:
1500                 rc = i2c_w(ov, 0x0a, val >> 8);
1501                 if (rc < 0)
1502                         goto out;
1503                 break;
1504         default:
1505                 PDEBUG(3, "Unsupported with this sensor");
1506                 rc = -EPERM;
1507                 goto out;
1508         }
1509
1510         rc = 0;         /* Success */
1511         ov->brightness = val;
1512 out:
1513         if (ov51x_restart(ov) < 0)
1514                 return -EIO;
1515
1516         return rc;
1517 }
1518
1519 /* Gets sensor's brightness setting */
1520 static int
1521 sensor_get_brightness(struct usb_ov511 *ov, unsigned short *val)
1522 {
1523         int rc;
1524
1525         switch (ov->sensor) {
1526         case SEN_OV7610:
1527         case SEN_OV76BE:
1528         case SEN_OV7620:
1529         case SEN_OV6620:
1530         case SEN_OV6630:
1531                 rc = i2c_r(ov, OV7610_REG_BRT);
1532                 if (rc < 0)
1533                         return rc;
1534                 else
1535                         *val = rc << 8;
1536                 break;
1537         case SEN_SAA7111A:
1538                 *val = ov->brightness;
1539                 break;
1540         default:
1541                 PDEBUG(3, "Unsupported with this sensor");
1542                 return -EPERM;
1543         }
1544
1545         PDEBUG(3, "%d", *val);
1546         ov->brightness = *val;
1547
1548         return 0;
1549 }
1550
1551 /* -------------------------------------------------------------------------- */
1552
1553 /* Sets sensor's saturation (color intensity) setting to "val" */
1554 static int
1555 sensor_set_saturation(struct usb_ov511 *ov, unsigned short val)
1556 {
1557         int rc;
1558
1559         PDEBUG(3, "%d", val);
1560
1561         if (ov->stop_during_set)
1562                 if (ov51x_stop(ov) < 0)
1563                         return -EIO;
1564
1565         switch (ov->sensor) {
1566         case SEN_OV7610:
1567         case SEN_OV76BE:
1568         case SEN_OV6620:
1569         case SEN_OV6630:
1570                 rc = i2c_w(ov, OV7610_REG_SAT, val >> 8);
1571                 if (rc < 0)
1572                         goto out;
1573                 break;
1574         case SEN_OV7620:
1575 //              /* Use UV gamma control instead. Bits 0 & 7 are reserved. */
1576 //              rc = ov_i2c_write(ov->dev, 0x62, (val >> 9) & 0x7e);
1577 //              if (rc < 0)
1578 //                      goto out;
1579                 rc = i2c_w(ov, OV7610_REG_SAT, val >> 8);
1580                 if (rc < 0)
1581                         goto out;
1582                 break;
1583         case SEN_SAA7111A:
1584                 rc = i2c_w(ov, 0x0c, val >> 9);
1585                 if (rc < 0)
1586                         goto out;
1587                 break;
1588         default:
1589                 PDEBUG(3, "Unsupported with this sensor");
1590                 rc = -EPERM;
1591                 goto out;
1592         }
1593
1594         rc = 0;         /* Success */
1595         ov->colour = val;
1596 out:
1597         if (ov51x_restart(ov) < 0)
1598                 return -EIO;
1599
1600         return rc;
1601 }
1602
1603 /* Gets sensor's saturation (color intensity) setting */
1604 static int
1605 sensor_get_saturation(struct usb_ov511 *ov, unsigned short *val)
1606 {
1607         int rc;
1608
1609         switch (ov->sensor) {
1610         case SEN_OV7610:
1611         case SEN_OV76BE:
1612         case SEN_OV6620:
1613         case SEN_OV6630:
1614                 rc = i2c_r(ov, OV7610_REG_SAT);
1615                 if (rc < 0)
1616                         return rc;
1617                 else
1618                         *val = rc << 8;
1619                 break;
1620         case SEN_OV7620:
1621 //              /* Use UV gamma reg instead. Bits 0 & 7 are reserved. */
1622 //              rc = i2c_r(ov, 0x62);
1623 //              if (rc < 0)
1624 //                      return rc;
1625 //              else
1626 //                      *val = (rc & 0x7e) << 9;
1627                 rc = i2c_r(ov, OV7610_REG_SAT);
1628                 if (rc < 0)
1629                         return rc;
1630                 else
1631                         *val = rc << 8;
1632                 break;
1633         case SEN_SAA7111A:
1634                 *val = ov->colour;
1635                 break;
1636         default:
1637                 PDEBUG(3, "Unsupported with this sensor");
1638                 return -EPERM;
1639         }
1640
1641         PDEBUG(3, "%d", *val);
1642         ov->colour = *val;
1643
1644         return 0;
1645 }
1646
1647 /* -------------------------------------------------------------------------- */
1648
1649 /* Sets sensor's hue (red/blue balance) setting to "val" */
1650 static int
1651 sensor_set_hue(struct usb_ov511 *ov, unsigned short val)
1652 {
1653         int rc;
1654
1655         PDEBUG(3, "%d", val);
1656
1657         if (ov->stop_during_set)
1658                 if (ov51x_stop(ov) < 0)
1659                         return -EIO;
1660
1661         switch (ov->sensor) {
1662         case SEN_OV7610:
1663         case SEN_OV6620:
1664         case SEN_OV6630:
1665                 rc = i2c_w(ov, OV7610_REG_RED, 0xFF - (val >> 8));
1666                 if (rc < 0)
1667                         goto out;
1668
1669                 rc = i2c_w(ov, OV7610_REG_BLUE, val >> 8);
1670                 if (rc < 0)
1671                         goto out;
1672                 break;
1673         case SEN_OV7620:
1674 // Hue control is causing problems. I will enable it once it's fixed.
1675 #if 0
1676                 rc = i2c_w(ov, 0x7a, (unsigned char)(val >> 8) + 0xb);
1677                 if (rc < 0)
1678                         goto out;
1679
1680                 rc = i2c_w(ov, 0x79, (unsigned char)(val >> 8) + 0xb);
1681                 if (rc < 0)
1682                         goto out;
1683 #endif
1684                 break;
1685         case SEN_SAA7111A:
1686                 rc = i2c_w(ov, 0x0d, (val + 32768) >> 8);
1687                 if (rc < 0)
1688                         goto out;
1689                 break;
1690         default:
1691                 PDEBUG(3, "Unsupported with this sensor");
1692                 rc = -EPERM;
1693                 goto out;
1694         }
1695
1696         rc = 0;         /* Success */
1697         ov->hue = val;
1698 out:
1699         if (ov51x_restart(ov) < 0)
1700                 return -EIO;
1701
1702         return rc;
1703 }
1704
1705 /* Gets sensor's hue (red/blue balance) setting */
1706 static int
1707 sensor_get_hue(struct usb_ov511 *ov, unsigned short *val)
1708 {
1709         int rc;
1710
1711         switch (ov->sensor) {
1712         case SEN_OV7610:
1713         case SEN_OV6620:
1714         case SEN_OV6630:
1715                 rc = i2c_r(ov, OV7610_REG_BLUE);
1716                 if (rc < 0)
1717                         return rc;
1718                 else
1719                         *val = rc << 8;
1720                 break;
1721         case SEN_OV7620:
1722                 rc = i2c_r(ov, 0x7a);
1723                 if (rc < 0)
1724                         return rc;
1725                 else
1726                         *val = rc << 8;
1727                 break;
1728         case SEN_SAA7111A:
1729                 *val = ov->hue;
1730                 break;
1731         default:
1732                 PDEBUG(3, "Unsupported with this sensor");
1733                 return -EPERM;
1734         }
1735
1736         PDEBUG(3, "%d", *val);
1737         ov->hue = *val;
1738
1739         return 0;
1740 }
1741
1742 /* -------------------------------------------------------------------------- */
1743
1744 static int
1745 sensor_set_picture(struct usb_ov511 *ov, struct video_picture *p)
1746 {
1747         int rc;
1748
1749         PDEBUG(4, "sensor_set_picture");
1750
1751         ov->whiteness = p->whiteness;
1752
1753         /* Don't return error if a setting is unsupported, or rest of settings
1754          * will not be performed */
1755
1756         rc = sensor_set_contrast(ov, p->contrast);
1757         if (FATAL_ERROR(rc))
1758                 return rc;
1759
1760         rc = sensor_set_brightness(ov, p->brightness);
1761         if (FATAL_ERROR(rc))
1762                 return rc;
1763
1764         rc = sensor_set_saturation(ov, p->colour);
1765         if (FATAL_ERROR(rc))
1766                 return rc;
1767
1768         rc = sensor_set_hue(ov, p->hue);
1769         if (FATAL_ERROR(rc))
1770                 return rc;
1771
1772         return 0;
1773 }
1774
1775 static int
1776 sensor_get_picture(struct usb_ov511 *ov, struct video_picture *p)
1777 {
1778         int rc;
1779
1780         PDEBUG(4, "sensor_get_picture");
1781
1782         /* Don't return error if a setting is unsupported, or rest of settings
1783          * will not be performed */
1784
1785         rc = sensor_get_contrast(ov, &(p->contrast));
1786         if (FATAL_ERROR(rc))
1787                 return rc;
1788
1789         rc = sensor_get_brightness(ov, &(p->brightness));
1790         if (FATAL_ERROR(rc))
1791                 return rc;
1792
1793         rc = sensor_get_saturation(ov, &(p->colour));
1794         if (FATAL_ERROR(rc))
1795                 return rc;
1796
1797         rc = sensor_get_hue(ov, &(p->hue));
1798         if (FATAL_ERROR(rc))
1799                 return rc;
1800
1801         p->whiteness = 105 << 8;
1802
1803         return 0;
1804 }
1805
1806 #if 0
1807 // FIXME: Exposure range is only 0x00-0x7f in interlace mode
1808 /* Sets current exposure for sensor. This only has an effect if auto-exposure
1809  * is off */
1810 static inline int
1811 sensor_set_exposure(struct usb_ov511 *ov, unsigned char val)
1812 {
1813         int rc;
1814
1815         PDEBUG(3, "%d", val);
1816
1817         if (ov->stop_during_set)
1818                 if (ov51x_stop(ov) < 0)
1819                         return -EIO;
1820
1821         switch (ov->sensor) {
1822         case SEN_OV6620:
1823         case SEN_OV6630:
1824         case SEN_OV7610:
1825         case SEN_OV7620:
1826         case SEN_OV76BE:
1827         case SEN_OV8600:
1828                 rc = i2c_w(ov, 0x10, val);
1829                 if (rc < 0)
1830                         goto out;
1831
1832                 break;
1833         case SEN_KS0127:
1834         case SEN_KS0127B:
1835         case SEN_SAA7111A:
1836                 PDEBUG(3, "Unsupported with this sensor");
1837                 return -EPERM;
1838         default:
1839                 err("Sensor not supported for set_exposure");
1840                 return -EINVAL;
1841         }
1842
1843         rc = 0;         /* Success */
1844         ov->exposure = val;
1845 out:
1846         if (ov51x_restart(ov) < 0)
1847                 return -EIO;
1848
1849         return rc;
1850 }
1851 #endif
1852
1853 /* Gets current exposure level from sensor, regardless of whether it is under
1854  * manual control. */
1855 static int
1856 sensor_get_exposure(struct usb_ov511 *ov, unsigned char *val)
1857 {
1858         int rc;
1859
1860         switch (ov->sensor) {
1861         case SEN_OV7610:
1862         case SEN_OV6620:
1863         case SEN_OV6630:
1864         case SEN_OV7620:
1865         case SEN_OV76BE:
1866         case SEN_OV8600:
1867                 rc = i2c_r(ov, 0x10);
1868                 if (rc < 0)
1869                         return rc;
1870                 else
1871                         *val = rc;
1872                 break;
1873         case SEN_KS0127:
1874         case SEN_KS0127B:
1875         case SEN_SAA7111A:
1876                 val = NULL;
1877                 PDEBUG(3, "Unsupported with this sensor");
1878                 return -EPERM;
1879         default:
1880                 err("Sensor not supported for get_exposure");
1881                 return -EINVAL;
1882         }
1883
1884         PDEBUG(3, "%d", *val);
1885         ov->exposure = *val;
1886
1887         return 0;
1888 }
1889
1890 /* Turns on or off the LED. Only has an effect with OV511+/OV518(+) */
1891 static void
1892 ov51x_led_control(struct usb_ov511 *ov, int enable)
1893 {
1894         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
1895
1896         if (ov->bridge == BRG_OV511PLUS)
1897                 reg_w(ov, R511_SYS_LED_CTL, enable ? 1 : 0);
1898         else if (ov->bclass == BCL_OV518)
1899                 reg_w_mask(ov, R518_GPIO_OUT, enable ? 0x02 : 0x00, 0x02);
1900
1901         return;
1902 }
1903
1904 /* Matches the sensor's internal frame rate to the lighting frequency.
1905  * Valid frequencies are:
1906  *      50 - 50Hz, for European and Asian lighting
1907  *      60 - 60Hz, for American lighting
1908  *
1909  * Tested with: OV7610, OV7620, OV76BE, OV6620
1910  * Unsupported: KS0127, KS0127B, SAA7111A
1911  * Returns: 0 for success
1912  */
1913 static int
1914 sensor_set_light_freq(struct usb_ov511 *ov, int freq)
1915 {
1916         int sixty;
1917
1918         PDEBUG(4, "%d Hz", freq);
1919
1920         if (freq == 60)
1921                 sixty = 1;
1922         else if (freq == 50)
1923                 sixty = 0;
1924         else {
1925                 err("Invalid light freq (%d Hz)", freq);
1926                 return -EINVAL;
1927         }
1928
1929         switch (ov->sensor) {
1930         case SEN_OV7610:
1931                 i2c_w_mask(ov, 0x2a, sixty?0x00:0x80, 0x80);
1932                 i2c_w(ov, 0x2b, sixty?0x00:0xac);
1933                 i2c_w_mask(ov, 0x13, 0x10, 0x10);
1934                 i2c_w_mask(ov, 0x13, 0x00, 0x10);
1935                 break;
1936         case SEN_OV7620:
1937         case SEN_OV76BE:
1938         case SEN_OV8600:
1939                 i2c_w_mask(ov, 0x2a, sixty?0x00:0x80, 0x80);
1940                 i2c_w(ov, 0x2b, sixty?0x00:0xac);
1941                 i2c_w_mask(ov, 0x76, 0x01, 0x01);
1942                 break;
1943         case SEN_OV6620:
1944         case SEN_OV6630:
1945                 i2c_w(ov, 0x2b, sixty?0xa8:0x28);
1946                 i2c_w(ov, 0x2a, sixty?0x84:0xa4);
1947                 break;
1948         case SEN_KS0127:
1949         case SEN_KS0127B:
1950         case SEN_SAA7111A:
1951                 PDEBUG(5, "Unsupported with this sensor");
1952                 return -EPERM;
1953         default:
1954                 err("Sensor not supported for set_light_freq");
1955                 return -EINVAL;
1956         }
1957
1958         ov->lightfreq = freq;
1959
1960         return 0;
1961 }
1962
1963 /* If enable is true, turn on the sensor's banding filter, otherwise turn it
1964  * off. This filter tries to reduce the pattern of horizontal light/dark bands
1965  * caused by some (usually fluorescent) lighting. The light frequency must be
1966  * set either before or after enabling it with ov51x_set_light_freq().
1967  *
1968  * Tested with: OV7610, OV7620, OV76BE, OV6620.
1969  * Unsupported: KS0127, KS0127B, SAA7111A
1970  * Returns: 0 for success
1971  */
1972 static int
1973 sensor_set_banding_filter(struct usb_ov511 *ov, int enable)
1974 {
1975         int rc;
1976
1977         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
1978
1979         if (ov->sensor == SEN_KS0127 || ov->sensor == SEN_KS0127B
1980                 || ov->sensor == SEN_SAA7111A) {
1981                 PDEBUG(5, "Unsupported with this sensor");
1982                 return -EPERM;
1983         }
1984
1985         rc = i2c_w_mask(ov, 0x2d, enable?0x04:0x00, 0x04);
1986         if (rc < 0)
1987                 return rc;
1988
1989         ov->bandfilt = enable;
1990
1991         return 0;
1992 }
1993
1994 /* If enable is true, turn on the sensor's auto brightness control, otherwise
1995  * turn it off.
1996  *
1997  * Unsupported: KS0127, KS0127B, SAA7111A
1998  * Returns: 0 for success
1999  */
2000 static int
2001 sensor_set_auto_brightness(struct usb_ov511 *ov, int enable)
2002 {
2003         int rc;
2004
2005         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2006
2007         if (ov->sensor == SEN_KS0127 || ov->sensor == SEN_KS0127B
2008                 || ov->sensor == SEN_SAA7111A) {
2009                 PDEBUG(5, "Unsupported with this sensor");
2010                 return -EPERM;
2011         }
2012
2013         rc = i2c_w_mask(ov, 0x2d, enable?0x10:0x00, 0x10);
2014         if (rc < 0)
2015                 return rc;
2016
2017         ov->auto_brt = enable;
2018
2019         return 0;
2020 }
2021
2022 /* If enable is true, turn on the sensor's auto exposure control, otherwise
2023  * turn it off.
2024  *
2025  * Unsupported: KS0127, KS0127B, SAA7111A
2026  * Returns: 0 for success
2027  */
2028 static int
2029 sensor_set_auto_exposure(struct usb_ov511 *ov, int enable)
2030 {
2031         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2032
2033         switch (ov->sensor) {
2034         case SEN_OV7610:
2035                 i2c_w_mask(ov, 0x29, enable?0x00:0x80, 0x80);
2036                 break;
2037         case SEN_OV6620:
2038         case SEN_OV7620:
2039         case SEN_OV76BE:
2040         case SEN_OV8600:
2041                 i2c_w_mask(ov, 0x13, enable?0x01:0x00, 0x01);
2042                 break;
2043         case SEN_OV6630:
2044                 i2c_w_mask(ov, 0x28, enable?0x00:0x10, 0x10);
2045                 break;
2046         case SEN_KS0127:
2047         case SEN_KS0127B:
2048         case SEN_SAA7111A:
2049                 PDEBUG(5, "Unsupported with this sensor");
2050                 return -EPERM;
2051         default:
2052                 err("Sensor not supported for set_auto_exposure");
2053                 return -EINVAL;
2054         }
2055
2056         ov->auto_exp = enable;
2057
2058         return 0;
2059 }
2060
2061 /* Modifies the sensor's exposure algorithm to allow proper exposure of objects
2062  * that are illuminated from behind.
2063  *
2064  * Tested with: OV6620, OV7620
2065  * Unsupported: OV7610, OV76BE, KS0127, KS0127B, SAA7111A
2066  * Returns: 0 for success
2067  */
2068 static int
2069 sensor_set_backlight(struct usb_ov511 *ov, int enable)
2070 {
2071         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2072
2073         switch (ov->sensor) {
2074         case SEN_OV7620:
2075         case SEN_OV8600:
2076                 i2c_w_mask(ov, 0x68, enable?0xe0:0xc0, 0xe0);
2077                 i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2078                 i2c_w_mask(ov, 0x28, enable?0x02:0x00, 0x02);
2079                 break;
2080         case SEN_OV6620:
2081                 i2c_w_mask(ov, 0x4e, enable?0xe0:0xc0, 0xe0);
2082                 i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2083                 i2c_w_mask(ov, 0x0e, enable?0x80:0x00, 0x80);
2084                 break;
2085         case SEN_OV6630:
2086                 i2c_w_mask(ov, 0x4e, enable?0x80:0x60, 0xe0);
2087                 i2c_w_mask(ov, 0x29, enable?0x08:0x00, 0x08);
2088                 i2c_w_mask(ov, 0x28, enable?0x02:0x00, 0x02);
2089                 break;
2090         case SEN_OV7610:
2091         case SEN_OV76BE:
2092         case SEN_KS0127:
2093         case SEN_KS0127B:
2094         case SEN_SAA7111A:
2095                 PDEBUG(5, "Unsupported with this sensor");
2096                 return -EPERM;
2097         default:
2098                 err("Sensor not supported for set_backlight");
2099                 return -EINVAL;
2100         }
2101
2102         ov->backlight = enable;
2103
2104         return 0;
2105 }
2106
2107 static int
2108 sensor_set_mirror(struct usb_ov511 *ov, int enable)
2109 {
2110         PDEBUG(4, " (%s)", enable ? "turn on" : "turn off");
2111
2112         switch (ov->sensor) {
2113         case SEN_OV6620:
2114         case SEN_OV6630:
2115         case SEN_OV7610:
2116         case SEN_OV7620:
2117         case SEN_OV76BE:
2118         case SEN_OV8600:
2119                 i2c_w_mask(ov, 0x12, enable?0x40:0x00, 0x40);
2120                 break;
2121         case SEN_KS0127:
2122         case SEN_KS0127B:
2123         case SEN_SAA7111A:
2124                 PDEBUG(5, "Unsupported with this sensor");
2125                 return -EPERM;
2126         default:
2127                 err("Sensor not supported for set_mirror");
2128                 return -EINVAL;
2129         }
2130
2131         ov->mirror = enable;
2132
2133         return 0;
2134 }
2135
2136 /* Returns number of bits per pixel (regardless of where they are located;
2137  * planar or not), or zero for unsupported format.
2138  */
2139 static inline int
2140 get_depth(int palette)
2141 {
2142         switch (palette) {
2143         case VIDEO_PALETTE_GREY:    return 8;
2144         case VIDEO_PALETTE_YUV420:  return 12;
2145         case VIDEO_PALETTE_YUV420P: return 12; /* Planar */
2146         default:                    return 0;  /* Invalid format */
2147         }
2148 }
2149
2150 /* Bytes per frame. Used by read(). Return of 0 indicates error */
2151 static inline long int
2152 get_frame_length(struct ov511_frame *frame)
2153 {
2154         if (!frame)
2155                 return 0;
2156         else
2157                 return ((frame->width * frame->height
2158                          * get_depth(frame->format)) >> 3);
2159 }
2160
2161 static int
2162 mode_init_ov_sensor_regs(struct usb_ov511 *ov, int width, int height,
2163                          int mode, int sub_flag, int qvga)
2164 {
2165         int clock;
2166
2167         /******** Mode (VGA/QVGA) and sensor specific regs ********/
2168
2169         switch (ov->sensor) {
2170         case SEN_OV7610:
2171                 i2c_w(ov, 0x14, qvga?0x24:0x04);
2172 // FIXME: Does this improve the image quality or frame rate?
2173 #if 0
2174                 i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
2175                 i2c_w(ov, 0x24, 0x10);
2176                 i2c_w(ov, 0x25, qvga?0x40:0x8a);
2177                 i2c_w(ov, 0x2f, qvga?0x30:0xb0);
2178                 i2c_w(ov, 0x35, qvga?0x1c:0x9c);
2179 #endif
2180                 break;
2181         case SEN_OV7620:
2182 //              i2c_w(ov, 0x2b, 0x00);
2183                 i2c_w(ov, 0x14, qvga?0xa4:0x84);
2184                 i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
2185                 i2c_w(ov, 0x24, qvga?0x20:0x3a);
2186                 i2c_w(ov, 0x25, qvga?0x30:0x60);
2187                 i2c_w_mask(ov, 0x2d, qvga?0x40:0x00, 0x40);
2188                 i2c_w_mask(ov, 0x67, qvga?0xf0:0x90, 0xf0);
2189                 i2c_w_mask(ov, 0x74, qvga?0x20:0x00, 0x20);
2190                 break;
2191         case SEN_OV76BE:
2192 //              i2c_w(ov, 0x2b, 0x00);
2193                 i2c_w(ov, 0x14, qvga?0xa4:0x84);
2194 // FIXME: Enable this once 7620AE uses 7620 initial settings
2195 #if 0
2196                 i2c_w_mask(ov, 0x28, qvga?0x00:0x20, 0x20);
2197                 i2c_w(ov, 0x24, qvga?0x20:0x3a);
2198                 i2c_w(ov, 0x25, qvga?0x30:0x60);
2199                 i2c_w_mask(ov, 0x2d, qvga?0x40:0x00, 0x40);
2200                 i2c_w_mask(ov, 0x67, qvga?0xb0:0x90, 0xf0);
2201                 i2c_w_mask(ov, 0x74, qvga?0x20:0x00, 0x20);
2202 #endif
2203                 break;
2204         case SEN_OV6620:
2205                 i2c_w(ov, 0x14, qvga?0x24:0x04);
2206                 break;
2207         case SEN_OV6630:
2208                 i2c_w(ov, 0x14, qvga?0xa0:0x80);
2209                 break;
2210         default:
2211                 err("Invalid sensor");
2212                 return -EINVAL;
2213         }
2214
2215         /******** Palette-specific regs ********/
2216
2217         if (mode == VIDEO_PALETTE_GREY) {
2218                 if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
2219                         /* these aren't valid on the OV6620/OV7620/6630? */
2220                         i2c_w_mask(ov, 0x0e, 0x40, 0x40);
2221                 }
2222
2223                 if (ov->sensor == SEN_OV6630 && ov->bridge == BRG_OV518
2224                     && ov518_color) {
2225                         i2c_w_mask(ov, 0x12, 0x00, 0x10);
2226                         i2c_w_mask(ov, 0x13, 0x00, 0x20);
2227                 } else {
2228                         i2c_w_mask(ov, 0x13, 0x20, 0x20);
2229                 }
2230         } else {
2231                 if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
2232                         /* not valid on the OV6620/OV7620/6630? */
2233                         i2c_w_mask(ov, 0x0e, 0x00, 0x40);
2234                 }
2235
2236                 /* The OV518 needs special treatment. Although both the OV518
2237                  * and the OV6630 support a 16-bit video bus, only the 8 bit Y
2238                  * bus is actually used. The UV bus is tied to ground.
2239                  * Therefore, the OV6630 needs to be in 8-bit multiplexed
2240                  * output mode */
2241
2242                 if (ov->sensor == SEN_OV6630 && ov->bridge == BRG_OV518
2243                     && ov518_color) {
2244                         i2c_w_mask(ov, 0x12, 0x10, 0x10);
2245                         i2c_w_mask(ov, 0x13, 0x20, 0x20);
2246                 } else {
2247                         i2c_w_mask(ov, 0x13, 0x00, 0x20);
2248                 }
2249         }
2250
2251         /******** Clock programming ********/
2252
2253         /* The OV6620 needs special handling. This prevents the
2254          * severe banding that normally occurs */
2255         if (ov->sensor == SEN_OV6620 || ov->sensor == SEN_OV6630)
2256         {
2257                 /* Clock down */
2258
2259                 i2c_w(ov, 0x2a, 0x04);
2260
2261                 if (ov->compress) {
2262 //                      clock = 0;    /* This ensures the highest frame rate */
2263                         clock = 3;
2264                 } else if (clockdiv == -1) {   /* If user didn't override it */
2265                         clock = 3;    /* Gives better exposure time */
2266                 } else {
2267                         clock = clockdiv;
2268                 }
2269
2270                 PDEBUG(4, "Setting clock divisor to %d", clock);
2271
2272                 i2c_w(ov, 0x11, clock);
2273
2274                 i2c_w(ov, 0x2a, 0x84);
2275                 /* This next setting is critical. It seems to improve
2276                  * the gain or the contrast. The "reserved" bits seem
2277                  * to have some effect in this case. */
2278                 i2c_w(ov, 0x2d, 0x85);
2279         }
2280         else
2281         {
2282                 if (ov->compress) {
2283                         clock = 1;    /* This ensures the highest frame rate */
2284                 } else if (clockdiv == -1) {   /* If user didn't override it */
2285                         /* Calculate and set the clock divisor */
2286                         clock = ((sub_flag ? ov->subw * ov->subh
2287                                   : width * height)
2288                                  * (mode == VIDEO_PALETTE_GREY ? 2 : 3) / 2)
2289                                  / 66000;
2290                 } else {
2291                         clock = clockdiv;
2292                 }
2293
2294                 PDEBUG(4, "Setting clock divisor to %d", clock);
2295
2296                 i2c_w(ov, 0x11, clock);
2297         }
2298
2299         /******** Special Features ********/
2300
2301         if (framedrop >= 0)
2302                 i2c_w(ov, 0x16, framedrop);
2303
2304         /* Test Pattern */
2305         i2c_w_mask(ov, 0x12, (testpat?0x02:0x00), 0x02);
2306
2307         /* Enable auto white balance */
2308         i2c_w_mask(ov, 0x12, 0x04, 0x04);
2309
2310         // This will go away as soon as ov51x_mode_init_sensor_regs()
2311         // is fully tested.
2312         /* 7620/6620/6630? don't have register 0x35, so play it safe */
2313         if (ov->sensor == SEN_OV7610 || ov->sensor == SEN_OV76BE) {
2314                 if (width == 640 && height == 480)
2315                         i2c_w(ov, 0x35, 0x9e);
2316                 else
2317                         i2c_w(ov, 0x35, 0x1e);
2318         }
2319
2320         return 0;
2321 }
2322
2323 static int
2324 set_ov_sensor_window(struct usb_ov511 *ov, int width, int height, int mode,
2325                      int sub_flag)
2326 {
2327         int ret;
2328         int hwsbase, hwebase, vwsbase, vwebase, hwsize, vwsize;
2329         int hoffset, voffset, hwscale = 0, vwscale = 0;
2330
2331         /* The different sensor ICs handle setting up of window differently.
2332          * IF YOU SET IT WRONG, YOU WILL GET ALL ZERO ISOC DATA FROM OV51x!!! */
2333         switch (ov->sensor) {
2334         case SEN_OV7610:
2335         case SEN_OV76BE:
2336                 hwsbase = 0x38;
2337                 hwebase = 0x3a;
2338                 vwsbase = vwebase = 0x05;
2339                 break;
2340         case SEN_OV6620:
2341         case SEN_OV6630:
2342                 hwsbase = 0x38;
2343                 hwebase = 0x3a;
2344                 vwsbase = 0x05;
2345                 vwebase = 0x06;
2346                 break;
2347         case SEN_OV7620:
2348                 hwsbase = 0x2f;         /* From 7620.SET (spec is wrong) */
2349                 hwebase = 0x2f;
2350                 vwsbase = vwebase = 0x05;
2351                 break;
2352         default:
2353                 err("Invalid sensor");
2354                 return -EINVAL;
2355         }
2356
2357         if (ov->sensor == SEN_OV6620 || ov->sensor == SEN_OV6630) {
2358                 /* Note: OV518(+) does downsample on its own) */
2359                 if ((width > 176 && height > 144)
2360                     || ov->bclass == BCL_OV518) {  /* CIF */
2361                         ret = mode_init_ov_sensor_regs(ov, width, height,
2362                                 mode, sub_flag, 0);
2363                         if (ret < 0)
2364                                 return ret;
2365                         hwscale = 1;
2366                         vwscale = 1;  /* The datasheet says 0; it's wrong */
2367                         hwsize = 352;
2368                         vwsize = 288;
2369                 } else if (width > 176 || height > 144) {
2370                         err("Illegal dimensions");
2371                         return -EINVAL;
2372                 } else {                            /* QCIF */
2373                         ret = mode_init_ov_sensor_regs(ov, width, height,
2374                                 mode, sub_flag, 1);
2375                         if (ret < 0)
2376                                 return ret;
2377                         hwsize = 176;
2378                         vwsize = 144;
2379                 }
2380         } else {
2381                 if (width > 320 && height > 240) {  /* VGA */
2382                         ret = mode_init_ov_sensor_regs(ov, width, height,
2383                                 mode, sub_flag, 0);
2384                         if (ret < 0)
2385                                 return ret;
2386                         hwscale = 2;
2387                         vwscale = 1;
2388                         hwsize = 640;
2389                         vwsize = 480;
2390                 } else if (width > 320 || height > 240) {
2391                         err("Illegal dimensions");
2392                         return -EINVAL;
2393                 } else {                            /* QVGA */
2394                         ret = mode_init_ov_sensor_regs(ov, width, height,
2395                                 mode, sub_flag, 1);
2396                         if (ret < 0)
2397                                 return ret;
2398                         hwscale = 1;
2399                         hwsize = 320;
2400                         vwsize = 240;
2401                 }
2402         }
2403
2404         /* Center the window */
2405         hoffset = ((hwsize - width) / 2) >> hwscale;
2406         voffset = ((vwsize - height) / 2) >> vwscale;
2407
2408         /* FIXME! - This needs to be changed to support 160x120 and 6620!!! */
2409         if (sub_flag) {
2410                 i2c_w(ov, 0x17, hwsbase+(ov->subx>>hwscale));
2411                 i2c_w(ov, 0x18, hwebase+((ov->subx+ov->subw)>>hwscale));
2412                 i2c_w(ov, 0x19, vwsbase+(ov->suby>>vwscale));
2413                 i2c_w(ov, 0x1a, vwebase+((ov->suby+ov->subh)>>vwscale));
2414         } else {
2415                 i2c_w(ov, 0x17, hwsbase + hoffset);
2416                 i2c_w(ov, 0x18, hwebase + hoffset + (hwsize>>hwscale));
2417                 i2c_w(ov, 0x19, vwsbase + voffset);
2418                 i2c_w(ov, 0x1a, vwebase + voffset + (vwsize>>vwscale));
2419         }
2420
2421 #ifdef OV511_DEBUG
2422         if (dump_sensor)
2423                 dump_i2c_regs(ov);
2424 #endif
2425
2426         return 0;
2427 }
2428
2429 /* Set up the OV511/OV511+ with the given image parameters.
2430  *
2431  * Do not put any sensor-specific code in here (including I2C I/O functions)
2432  */
2433 static int
2434 ov511_mode_init_regs(struct usb_ov511 *ov,
2435                      int width, int height, int mode, int sub_flag)
2436 {
2437         int hsegs, vsegs;
2438
2439         if (sub_flag) {
2440                 width = ov->subw;
2441                 height = ov->subh;
2442         }
2443
2444         PDEBUG(3, "width:%d, height:%d, mode:%d, sub:%d",
2445                width, height, mode, sub_flag);
2446
2447         // FIXME: This should be moved to a 7111a-specific function once
2448         // subcapture is dealt with properly
2449         if (ov->sensor == SEN_SAA7111A) {
2450                 if (width == 320 && height == 240) {
2451                         /* No need to do anything special */
2452                 } else if (width == 640 && height == 480) {
2453                         /* Set the OV511 up as 320x480, but keep the
2454                          * V4L resolution as 640x480 */
2455                         width = 320;
2456                 } else {
2457                         err("SAA7111A only allows 320x240 or 640x480");
2458                         return -EINVAL;
2459                 }
2460         }
2461
2462         /* Make sure width and height are a multiple of 8 */
2463         if (width % 8 || height % 8) {
2464                 err("Invalid size (%d, %d) (mode = %d)", width, height, mode);
2465                 return -EINVAL;
2466         }
2467
2468         if (width < ov->minwidth || height < ov->minheight) {
2469                 err("Requested dimensions are too small");
2470                 return -EINVAL;
2471         }
2472
2473         if (ov51x_stop(ov) < 0)
2474                 return -EIO;
2475
2476         if (mode == VIDEO_PALETTE_GREY) {
2477                 reg_w(ov, R511_CAM_UV_EN, 0x00);
2478                 reg_w(ov, R511_SNAP_UV_EN, 0x00);
2479                 reg_w(ov, R511_SNAP_OPTS, 0x01);
2480         } else {
2481                 reg_w(ov, R511_CAM_UV_EN, 0x01);
2482                 reg_w(ov, R511_SNAP_UV_EN, 0x01);
2483                 reg_w(ov, R511_SNAP_OPTS, 0x03);
2484         }
2485
2486         /* Here I'm assuming that snapshot size == image size.
2487          * I hope that's always true. --claudio
2488          */
2489         hsegs = (width >> 3) - 1;
2490         vsegs = (height >> 3) - 1;
2491
2492         reg_w(ov, R511_CAM_PXCNT, hsegs);
2493         reg_w(ov, R511_CAM_LNCNT, vsegs);
2494         reg_w(ov, R511_CAM_PXDIV, 0x00);
2495         reg_w(ov, R511_CAM_LNDIV, 0x00);
2496
2497         /* YUV420, low pass filter on */
2498         reg_w(ov, R511_CAM_OPTS, 0x03);
2499
2500         /* Snapshot additions */
2501         reg_w(ov, R511_SNAP_PXCNT, hsegs);
2502         reg_w(ov, R511_SNAP_LNCNT, vsegs);
2503         reg_w(ov, R511_SNAP_PXDIV, 0x00);
2504         reg_w(ov, R511_SNAP_LNDIV, 0x00);
2505
2506         if (ov->compress) {
2507                 /* Enable Y and UV quantization and compression */
2508                 reg_w(ov, R511_COMP_EN, 0x07);
2509                 reg_w(ov, R511_COMP_LUT_EN, 0x03);
2510                 ov51x_reset(ov, OV511_RESET_OMNICE);
2511         }
2512
2513         if (ov51x_restart(ov) < 0)
2514                 return -EIO;
2515
2516         return 0;
2517 }
2518
2519 /* Sets up the OV518/OV518+ with the given image parameters
2520  *
2521  * OV518 needs a completely different approach, until we can figure out what
2522  * the individual registers do. Also, only 15 FPS is supported now.
2523  *
2524  * Do not put any sensor-specific code in here (including I2C I/O functions)
2525  */
2526 static int
2527 ov518_mode_init_regs(struct usb_ov511 *ov,
2528                      int width, int height, int mode, int sub_flag)
2529 {
2530         int hsegs, vsegs, hi_res;
2531
2532         if (sub_flag) {
2533                 width = ov->subw;
2534                 height = ov->subh;
2535         }
2536
2537         PDEBUG(3, "width:%d, height:%d, mode:%d, sub:%d",
2538                width, height, mode, sub_flag);
2539
2540         if (width % 16 || height % 8) {
2541                 err("Invalid size (%d, %d)", width, height);
2542                 return -EINVAL;
2543         }
2544
2545         if (width < ov->minwidth || height < ov->minheight) {
2546                 err("Requested dimensions are too small");
2547                 return -EINVAL;
2548         }
2549
2550         if (width >= 320 && height >= 240) {
2551                 hi_res = 1;
2552         } else if (width >= 320 || height >= 240) {
2553                 err("Invalid width/height combination (%d, %d)", width, height);
2554                 return -EINVAL;
2555         } else {
2556                 hi_res = 0;
2557         }
2558
2559         if (ov51x_stop(ov) < 0)
2560                 return -EIO;
2561
2562         /******** Set the mode ********/
2563
2564         reg_w(ov, 0x2b, 0);
2565         reg_w(ov, 0x2c, 0);
2566         reg_w(ov, 0x2d, 0);
2567         reg_w(ov, 0x2e, 0);
2568         reg_w(ov, 0x3b, 0);
2569         reg_w(ov, 0x3c, 0);
2570         reg_w(ov, 0x3d, 0);
2571         reg_w(ov, 0x3e, 0);
2572
2573         if (ov->bridge == BRG_OV518 && ov518_color) {
2574                 /* OV518 needs U and V swapped */
2575                 i2c_w_mask(ov, 0x15, 0x00, 0x01);
2576
2577                 if (mode == VIDEO_PALETTE_GREY) {
2578                         /* Set 16-bit input format (UV data are ignored) */
2579                         reg_w_mask(ov, 0x20, 0x00, 0x08);
2580
2581                         /* Set 8-bit (4:0:0) output format */
2582                         reg_w_mask(ov, 0x28, 0x00, 0xf0);
2583                         reg_w_mask(ov, 0x38, 0x00, 0xf0);
2584                 } else {
2585                         /* Set 8-bit (YVYU) input format */
2586                         reg_w_mask(ov, 0x20, 0x08, 0x08);
2587
2588                         /* Set 12-bit (4:2:0) output format */
2589                         reg_w_mask(ov, 0x28, 0x80, 0xf0);
2590                         reg_w_mask(ov, 0x38, 0x80, 0xf0);
2591                 }
2592         } else {
2593                 reg_w(ov, 0x28, (mode == VIDEO_PALETTE_GREY) ? 0x00:0x80);
2594                 reg_w(ov, 0x38, (mode == VIDEO_PALETTE_GREY) ? 0x00:0x80);
2595         }
2596
2597         hsegs = width / 16;
2598         vsegs = height / 4;
2599
2600         reg_w(ov, 0x29, hsegs);
2601         reg_w(ov, 0x2a, vsegs);
2602
2603         reg_w(ov, 0x39, hsegs);
2604         reg_w(ov, 0x3a, vsegs);
2605
2606         /* Windows driver does this here; who knows why */
2607         reg_w(ov, 0x2f, 0x80);
2608
2609         /******** Set the framerate (to 15 FPS) ********/
2610
2611         /* Mode independent, but framerate dependent, regs */
2612         reg_w(ov, 0x51, 0x02);  /* Clock divider; lower==faster */
2613         reg_w(ov, 0x22, 0x18);
2614         reg_w(ov, 0x23, 0xff);
2615
2616         if (ov->bridge == BRG_OV518PLUS)
2617                 reg_w(ov, 0x21, 0x19);
2618         else
2619                 reg_w(ov, 0x71, 0x19);  /* Compression-related? */
2620
2621         // FIXME: Sensor-specific
2622         /* Bit 5 is what matters here. Of course, it is "reserved" */
2623         i2c_w(ov, 0x54, 0x23);
2624
2625         reg_w(ov, 0x2f, 0x80);
2626
2627         if (ov->bridge == BRG_OV518PLUS) {
2628                 reg_w(ov, 0x24, 0x94);
2629                 reg_w(ov, 0x25, 0x90);
2630                 ov518_reg_w32(ov, 0xc4,    400, 2);     /* 190h   */
2631                 ov518_reg_w32(ov, 0xc6,    540, 2);     /* 21ch   */
2632                 ov518_reg_w32(ov, 0xc7,    540, 2);     /* 21ch   */
2633                 ov518_reg_w32(ov, 0xc8,    108, 2);     /* 6ch    */
2634                 ov518_reg_w32(ov, 0xca, 131098, 3);     /* 2001ah */
2635                 ov518_reg_w32(ov, 0xcb,    532, 2);     /* 214h   */
2636                 ov518_reg_w32(ov, 0xcc,   2400, 2);     /* 960h   */
2637                 ov518_reg_w32(ov, 0xcd,     32, 2);     /* 20h    */
2638                 ov518_reg_w32(ov, 0xce,    608, 2);     /* 260h   */
2639         } else {
2640                 reg_w(ov, 0x24, 0x9f);
2641                 reg_w(ov, 0x25, 0x90);
2642                 ov518_reg_w32(ov, 0xc4,    400, 2);     /* 190h   */
2643                 ov518_reg_w32(ov, 0xc6,    500, 2);     /* 1f4h   */
2644                 ov518_reg_w32(ov, 0xc7,    500, 2);     /* 1f4h   */
2645                 ov518_reg_w32(ov, 0xc8,    142, 2);     /* 8eh    */
2646                 ov518_reg_w32(ov, 0xca, 131098, 3);     /* 2001ah */
2647                 ov518_reg_w32(ov, 0xcb,    532, 2);     /* 214h   */
2648                 ov518_reg_w32(ov, 0xcc,   2000, 2);     /* 7d0h   */
2649                 ov518_reg_w32(ov, 0xcd,     32, 2);     /* 20h    */
2650                 ov518_reg_w32(ov, 0xce,    608, 2);     /* 260h   */
2651         }
2652
2653         reg_w(ov, 0x2f, 0x80);
2654
2655         if (ov51x_restart(ov) < 0)
2656                 return -EIO;
2657
2658         /* Reset it just for good measure */
2659         if (ov51x_reset(ov, OV511_RESET_NOREGS) < 0)
2660                 return -EIO;
2661
2662         return 0;
2663 }
2664
2665 /* This is a wrapper around the OV511, OV518, and sensor specific functions */
2666 static int
2667 mode_init_regs(struct usb_ov511 *ov,
2668                int width, int height, int mode, int sub_flag)
2669 {
2670         int rc = 0;
2671
2672         if (!ov || !ov->dev)
2673                 return -EFAULT;
2674
2675         if (ov->bclass == BCL_OV518) {
2676                 rc = ov518_mode_init_regs(ov, width, height, mode, sub_flag);
2677         } else {
2678                 rc = ov511_mode_init_regs(ov, width, height, mode, sub_flag);
2679         }
2680
2681         if (FATAL_ERROR(rc))
2682                 return rc;
2683
2684         switch (ov->sensor) {
2685         case SEN_OV7610:
2686         case SEN_OV7620:
2687         case SEN_OV76BE:
2688         case SEN_OV8600:
2689         case SEN_OV6620:
2690         case SEN_OV6630:
2691                 rc = set_ov_sensor_window(ov, width, height, mode, sub_flag);
2692                 break;
2693         case SEN_KS0127:
2694         case SEN_KS0127B:
2695                 err("KS0127-series decoders not supported yet");
2696                 rc = -EINVAL;
2697                 break;
2698         case SEN_SAA7111A:
2699 //              rc = mode_init_saa_sensor_regs(ov, width, height, mode,
2700 //                                             sub_flag);
2701
2702                 PDEBUG(1, "SAA status = 0x%02X", i2c_r(ov, 0x1f));
2703                 break;
2704         default:
2705                 err("Unknown sensor");
2706                 rc = -EINVAL;
2707         }
2708
2709         if (FATAL_ERROR(rc))
2710                 return rc;
2711
2712         /* Sensor-independent settings */
2713         rc = sensor_set_auto_brightness(ov, ov->auto_brt);
2714         if (FATAL_ERROR(rc))
2715                 return rc;
2716
2717         rc = sensor_set_auto_exposure(ov, ov->auto_exp);
2718         if (FATAL_ERROR(rc))
2719                 return rc;
2720
2721         rc = sensor_set_banding_filter(ov, bandingfilter);
2722         if (FATAL_ERROR(rc))
2723                 return rc;
2724
2725         if (ov->lightfreq) {
2726                 rc = sensor_set_light_freq(ov, lightfreq);
2727                 if (FATAL_ERROR(rc))
2728                         return rc;
2729         }
2730
2731         rc = sensor_set_backlight(ov, ov->backlight);
2732         if (FATAL_ERROR(rc))
2733                 return rc;
2734
2735         rc = sensor_set_mirror(ov, ov->mirror);
2736         if (FATAL_ERROR(rc))
2737                 return rc;
2738
2739         return 0;
2740 }
2741
2742 /* This sets the default image parameters. This is useful for apps that use
2743  * read() and do not set these.
2744  */
2745 static int
2746 ov51x_set_default_params(struct usb_ov511 *ov)
2747 {
2748         int i;
2749
2750         /* Set default sizes in case IOCTL (VIDIOCMCAPTURE) is not used
2751          * (using read() instead). */
2752         for (i = 0; i < OV511_NUMFRAMES; i++) {
2753                 ov->frame[i].width = ov->maxwidth;
2754                 ov->frame[i].height = ov->maxheight;
2755                 ov->frame[i].bytes_read = 0;
2756                 if (force_palette)
2757                         ov->frame[i].format = force_palette;
2758                 else
2759                         ov->frame[i].format = VIDEO_PALETTE_YUV420;
2760
2761                 ov->frame[i].depth = get_depth(ov->frame[i].format);
2762         }
2763
2764         PDEBUG(3, "%dx%d, %s", ov->maxwidth, ov->maxheight,
2765                symbolic(v4l1_plist, ov->frame[0].format));
2766
2767         /* Initialize to max width/height, YUV420 or RGB24 (if supported) */
2768         if (mode_init_regs(ov, ov->maxwidth, ov->maxheight,
2769                            ov->frame[0].format, 0) < 0)
2770                 return -EINVAL;
2771
2772         return 0;
2773 }
2774
2775 /**********************************************************************
2776  *
2777  * Video decoder stuff
2778  *
2779  **********************************************************************/
2780
2781 /* Set analog input port of decoder */
2782 static int
2783 decoder_set_input(struct usb_ov511 *ov, int input)
2784 {
2785         PDEBUG(4, "port %d", input);
2786
2787         switch (ov->sensor) {
2788         case SEN_SAA7111A:
2789         {
2790                 /* Select mode */
2791                 i2c_w_mask(ov, 0x02, input, 0x07);
2792                 /* Bypass chrominance trap for modes 4..7 */
2793                 i2c_w_mask(ov, 0x09, (input > 3) ? 0x80:0x00, 0x80);
2794                 break;
2795         }
2796         default:
2797                 return -EINVAL;
2798         }
2799
2800         return 0;
2801 }
2802
2803 /* Get ASCII name of video input */
2804 static int
2805 decoder_get_input_name(struct usb_ov511 *ov, int input, char *name)
2806 {
2807         switch (ov->sensor) {
2808         case SEN_SAA7111A:
2809         {
2810                 if (input < 0 || input > 7)
2811                         return -EINVAL;
2812                 else if (input < 4)
2813                         sprintf(name, "CVBS-%d", input);
2814                 else // if (input < 8)
2815                         sprintf(name, "S-Video-%d", input - 4);
2816                 break;
2817         }
2818         default:
2819                 sprintf(name, "%s", "Camera");
2820         }
2821
2822         return 0;
2823 }
2824
2825 /* Set norm (NTSC, PAL, SECAM, AUTO) */
2826 static int
2827 decoder_set_norm(struct usb_ov511 *ov, int norm)
2828 {
2829         PDEBUG(4, "%d", norm);
2830
2831         switch (ov->sensor) {
2832         case SEN_SAA7111A:
2833         {
2834                 int reg_8, reg_e;
2835
2836                 if (norm == VIDEO_MODE_NTSC) {
2837                         reg_8 = 0x40;   /* 60 Hz */
2838                         reg_e = 0x00;   /* NTSC M / PAL BGHI */
2839                 } else if (norm == VIDEO_MODE_PAL) {
2840                         reg_8 = 0x00;   /* 50 Hz */
2841                         reg_e = 0x00;   /* NTSC M / PAL BGHI */
2842                 } else if (norm == VIDEO_MODE_AUTO) {
2843                         reg_8 = 0x80;   /* Auto field detect */
2844                         reg_e = 0x00;   /* NTSC M / PAL BGHI */
2845                 } else if (norm == VIDEO_MODE_SECAM) {
2846                         reg_8 = 0x00;   /* 50 Hz */
2847                         reg_e = 0x50;   /* SECAM / PAL 4.43 */
2848                 } else {
2849                         return -EINVAL;
2850                 }
2851
2852                 i2c_w_mask(ov, 0x08, reg_8, 0xc0);
2853                 i2c_w_mask(ov, 0x0e, reg_e, 0x70);
2854                 break;
2855         }
2856         default:
2857                 return -EINVAL;
2858         }
2859
2860         return 0;
2861 }
2862
2863 /**********************************************************************
2864  *
2865  * Raw data parsing
2866  *
2867  **********************************************************************/
2868
2869 /* Copies a 64-byte segment at pIn to an 8x8 block at pOut. The width of the
2870  * image at pOut is specified by w.
2871  */
2872 static inline void
2873 make_8x8(unsigned char *pIn, unsigned char *pOut, int w)
2874 {
2875         unsigned char *pOut1 = pOut;
2876         int x, y;
2877
2878         for (y = 0; y < 8; y++) {
2879                 pOut1 = pOut;
2880                 for (x = 0; x < 8; x++) {
2881                         *pOut1++ = *pIn++;
2882                 }
2883                 pOut += w;
2884         }
2885 }
2886
2887 /*
2888  * For RAW BW (YUV 4:0:0) images, data show up in 256 byte segments.
2889  * The segments represent 4 squares of 8x8 pixels as follows:
2890  *
2891  *      0  1 ...  7    64  65 ...  71   ...  192 193 ... 199
2892  *      8  9 ... 15    72  73 ...  79        200 201 ... 207
2893  *           ...              ...                    ...
2894  *     56 57 ... 63   120 121 ... 127        248 249 ... 255
2895  *
2896  */
2897 static void
2898 yuv400raw_to_yuv400p(struct ov511_frame *frame,
2899                      unsigned char *pIn0, unsigned char *pOut0)
2900 {
2901         int x, y;
2902         unsigned char *pIn, *pOut, *pOutLine;
2903
2904         /* Copy Y */
2905         pIn = pIn0;
2906         pOutLine = pOut0;
2907         for (y = 0; y < frame->rawheight - 1; y += 8) {
2908                 pOut = pOutLine;
2909                 for (x = 0; x < frame->rawwidth - 1; x += 8) {
2910                         make_8x8(pIn, pOut, frame->rawwidth);
2911                         pIn += 64;
2912                         pOut += 8;
2913                 }
2914                 pOutLine += 8 * frame->rawwidth;
2915         }
2916 }
2917
2918 /*
2919  * For YUV 4:2:0 images, the data show up in 384 byte segments.
2920  * The first 64 bytes of each segment are U, the next 64 are V.  The U and
2921  * V are arranged as follows:
2922  *
2923  *      0  1 ...  7
2924  *      8  9 ... 15
2925  *           ...
2926  *     56 57 ... 63
2927  *
2928  * U and V are shipped at half resolution (1 U,V sample -> one 2x2 block).
2929  *
2930  * The next 256 bytes are full resolution Y data and represent 4 squares
2931  * of 8x8 pixels as follows:
2932  *
2933  *      0  1 ...  7    64  65 ...  71   ...  192 193 ... 199
2934  *      8  9 ... 15    72  73 ...  79        200 201 ... 207
2935  *           ...              ...                    ...
2936  *     56 57 ... 63   120 121 ... 127   ...  248 249 ... 255
2937  *
2938  * Note that the U and V data in one segment represent a 16 x 16 pixel
2939  * area, but the Y data represent a 32 x 8 pixel area. If the width is not an
2940  * even multiple of 32, the extra 8x8 blocks within a 32x8 block belong to the
2941  * next horizontal stripe.
2942  *
2943  * If dumppix module param is set, _parse_data just dumps the incoming segments,
2944  * verbatim, in order, into the frame. When used with vidcat -f ppm -s 640x480
2945  * this puts the data on the standard output and can be analyzed with the
2946  * parseppm.c utility I wrote.  That's a much faster way for figuring out how
2947  * these data are scrambled.
2948  */
2949
2950 /* Converts from raw, uncompressed segments at pIn0 to a YUV420P frame at pOut0.
2951  *
2952  * FIXME: Currently only handles width and height that are multiples of 16
2953  */
2954 static void
2955 yuv420raw_to_yuv420p(struct ov511_frame *frame,
2956                      unsigned char *pIn0, unsigned char *pOut0)
2957 {
2958         int k, x, y;
2959         unsigned char *pIn, *pOut, *pOutLine;
2960         const unsigned int a = frame->rawwidth * frame->rawheight;
2961         const unsigned int w = frame->rawwidth / 2;
2962
2963         /* Copy U and V */
2964         pIn = pIn0;
2965         pOutLine = pOut0 + a;
2966         for (y = 0; y < frame->rawheight - 1; y += 16) {
2967                 pOut = pOutLine;
2968                 for (x = 0; x < frame->rawwidth - 1; x += 16) {
2969                         make_8x8(pIn, pOut, w);
2970                         make_8x8(pIn + 64, pOut + a/4, w);
2971                         pIn += 384;
2972                         pOut += 8;
2973                 }
2974                 pOutLine += 8 * w;
2975         }
2976
2977         /* Copy Y */
2978         pIn = pIn0 + 128;
2979         pOutLine = pOut0;
2980         k = 0;
2981         for (y = 0; y < frame->rawheight - 1; y += 8) {
2982                 pOut = pOutLine;
2983                 for (x = 0; x < frame->rawwidth - 1; x += 8) {
2984                         make_8x8(pIn, pOut, frame->rawwidth);
2985                         pIn += 64;
2986                         pOut += 8;
2987                         if ((++k) > 3) {
2988                                 k = 0;
2989                                 pIn += 128;
2990                         }
2991                 }
2992                 pOutLine += 8 * frame->rawwidth;
2993         }
2994 }
2995
2996 /**********************************************************************
2997  *
2998  * Decompression
2999  *
3000  **********************************************************************/
3001
3002 static int
3003 request_decompressor(struct usb_ov511 *ov)
3004 {
3005         if (ov->bclass == BCL_OV511 || ov->bclass == BCL_OV518) {
3006                 err("No decompressor available");
3007         } else {
3008                 err("Unknown bridge");
3009         }
3010
3011         return -ENOSYS;
3012 }
3013
3014 static void
3015 decompress(struct usb_ov511 *ov, struct ov511_frame *frame,
3016            unsigned char *pIn0, unsigned char *pOut0)
3017 {
3018         if (!ov->decomp_ops)
3019                 if (request_decompressor(ov))
3020                         return;
3021
3022 }
3023
3024 /**********************************************************************
3025  *
3026  * Format conversion
3027  *
3028  **********************************************************************/
3029
3030 /* Fuses even and odd fields together, and doubles width.
3031  * INPUT: an odd field followed by an even field at pIn0, in YUV planar format
3032  * OUTPUT: a normal YUV planar image, with correct aspect ratio
3033  */
3034 static void
3035 deinterlace(struct ov511_frame *frame, int rawformat,
3036             unsigned char *pIn0, unsigned char *pOut0)
3037 {
3038         const int fieldheight = frame->rawheight / 2;
3039         const int fieldpix = fieldheight * frame->rawwidth;
3040         const int w = frame->width;
3041         int x, y;
3042         unsigned char *pInEven, *pInOdd, *pOut;
3043
3044         PDEBUG(5, "fieldheight=%d", fieldheight);
3045
3046         if (frame->rawheight != frame->height) {
3047                 err("invalid height");
3048                 return;
3049         }
3050
3051         if ((frame->rawwidth * 2) != frame->width) {
3052                 err("invalid width");
3053                 return;
3054         }
3055
3056         /* Y */
3057         pInOdd = pIn0;
3058         pInEven = pInOdd + fieldpix;
3059         pOut = pOut0;
3060         for (y = 0; y < fieldheight; y++) {
3061                 for (x = 0; x < frame->rawwidth; x++) {
3062                         *pOut = *pInEven;
3063                         *(pOut+1) = *pInEven++;
3064                         *(pOut+w) = *pInOdd;
3065                         *(pOut+w+1) = *pInOdd++;
3066                         pOut += 2;
3067                 }
3068                 pOut += w;
3069         }
3070
3071         if (rawformat == RAWFMT_YUV420) {
3072         /* U */
3073                 pInOdd = pIn0 + fieldpix * 2;
3074                 pInEven = pInOdd + fieldpix / 4;
3075                 for (y = 0; y < fieldheight / 2; y++) {
3076                         for (x = 0; x < frame->rawwidth / 2; x++) {
3077                                 *pOut = *pInEven;
3078                                 *(pOut+1) = *pInEven++;
3079                                 *(pOut+w/2) = *pInOdd;
3080                                 *(pOut+w/2+1) = *pInOdd++;
3081                                 pOut += 2;
3082                         }
3083                         pOut += w/2;
3084                 }
3085         /* V */
3086                 pInOdd = pIn0 + fieldpix * 2 + fieldpix / 2;
3087                 pInEven = pInOdd + fieldpix / 4;
3088                 for (y = 0; y < fieldheight / 2; y++) {
3089                         for (x = 0; x < frame->rawwidth / 2; x++) {
3090                                 *pOut = *pInEven;
3091                                 *(pOut+1) = *pInEven++;
3092                                 *(pOut+w/2) = *pInOdd;
3093                                 *(pOut+w/2+1) = *pInOdd++;
3094                                 pOut += 2;
3095                         }
3096                         pOut += w/2;
3097                 }
3098         }
3099 }
3100
3101 static void
3102 ov51x_postprocess_grey(struct usb_ov511 *ov, struct ov511_frame *frame)
3103 {
3104                 /* Deinterlace frame, if necessary */
3105                 if (ov->sensor == SEN_SAA7111A && frame->rawheight >= 480) {
3106                         if (frame->compressed)
3107                                 decompress(ov, frame, frame->rawdata,
3108                                                  frame->tempdata);
3109                         else
3110                                 yuv400raw_to_yuv400p(frame, frame->rawdata,
3111                                                      frame->tempdata);
3112
3113                         deinterlace(frame, RAWFMT_YUV400, frame->tempdata,
3114                                     frame->data);
3115                 } else {
3116                         if (frame->compressed)
3117                                 decompress(ov, frame, frame->rawdata,
3118                                                  frame->data);
3119                         else
3120                                 yuv400raw_to_yuv400p(frame, frame->rawdata,
3121                                                      frame->data);
3122                 }
3123 }
3124
3125 /* Process raw YUV420 data into standard YUV420P */
3126 static void
3127 ov51x_postprocess_yuv420(struct usb_ov511 *ov, struct ov511_frame *frame)
3128 {
3129         /* Deinterlace frame, if necessary */
3130         if (ov->sensor == SEN_SAA7111A && frame->rawheight >= 480) {
3131                 if (frame->compressed)
3132                         decompress(ov, frame, frame->rawdata, frame->tempdata);
3133                 else
3134                         yuv420raw_to_yuv420p(frame, frame->rawdata,
3135                                              frame->tempdata);
3136
3137                 deinterlace(frame, RAWFMT_YUV420, frame->tempdata,
3138                             frame->data);
3139         } else {
3140                 if (frame->compressed)
3141                         decompress(ov, frame, frame->rawdata, frame->data);
3142                 else
3143                         yuv420raw_to_yuv420p(frame, frame->rawdata,
3144                                              frame->data);
3145         }
3146 }
3147
3148 /* Post-processes the specified frame. This consists of:
3149  *      1. Decompress frame, if necessary
3150  *      2. Deinterlace frame and scale to proper size, if necessary
3151  *      3. Convert from YUV planar to destination format, if necessary
3152  *      4. Fix the RGB offset, if necessary
3153  */
3154 static void
3155 ov51x_postprocess(struct usb_ov511 *ov, struct ov511_frame *frame)
3156 {
3157         if (dumppix) {
3158                 memset(frame->data, 0,
3159                         MAX_DATA_SIZE(ov->maxwidth, ov->maxheight));
3160                 PDEBUG(4, "Dumping %d bytes", frame->bytes_recvd);
3161                 memcpy(frame->data, frame->rawdata, frame->bytes_recvd);
3162         } else {
3163                 switch (frame->format) {
3164                 case VIDEO_PALETTE_GREY:
3165                         ov51x_postprocess_grey(ov, frame);
3166                         break;
3167                 case VIDEO_PALETTE_YUV420:
3168                 case VIDEO_PALETTE_YUV420P:
3169                         ov51x_postprocess_yuv420(ov, frame);
3170                         break;
3171                 default:
3172                         err("Cannot convert data to %s",
3173                             symbolic(v4l1_plist, frame->format));
3174                 }
3175         }
3176 }
3177
3178 /**********************************************************************
3179  *
3180  * OV51x data transfer, IRQ handler
3181  *
3182  **********************************************************************/
3183
3184 static inline void
3185 ov511_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
3186 {
3187         int num, offset;
3188         int pnum = in[ov->packet_size - 1];             /* Get packet number */
3189         int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
3190         struct ov511_frame *frame = &ov->frame[ov->curframe];
3191         struct timeval *ts;
3192
3193         /* SOF/EOF packets have 1st to 8th bytes zeroed and the 9th
3194          * byte non-zero. The EOF packet has image width/height in the
3195          * 10th and 11th bytes. The 9th byte is given as follows:
3196          *
3197          * bit 7: EOF
3198          *     6: compression enabled
3199          *     5: 422/420/400 modes
3200          *     4: 422/420/400 modes
3201          *     3: 1
3202          *     2: snapshot button on
3203          *     1: snapshot frame
3204          *     0: even/odd field
3205          */
3206
3207         if (printph) {
3208                 info("ph(%3d): %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x",
3209                      pnum, in[0], in[1], in[2], in[3], in[4], in[5], in[6],
3210                      in[7], in[8], in[9], in[10], in[11]);
3211         }
3212
3213         /* Check for SOF/EOF packet */
3214         if ((in[0] | in[1] | in[2] | in[3] | in[4] | in[5] | in[6] | in[7]) ||
3215             (~in[8] & 0x08))
3216                 goto check_middle;
3217
3218         /* Frame end */
3219         if (in[8] & 0x80) {
3220                 ts = (struct timeval *)(frame->data
3221                       + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
3222                 do_gettimeofday(ts);
3223
3224                 /* Get the actual frame size from the EOF header */
3225                 frame->rawwidth = ((int)(in[9]) + 1) * 8;
3226                 frame->rawheight = ((int)(in[10]) + 1) * 8;
3227
3228                 PDEBUG(4, "Frame end, frame=%d, pnum=%d, w=%d, h=%d, recvd=%d",
3229                         ov->curframe, pnum, frame->rawwidth, frame->rawheight,
3230                         frame->bytes_recvd);
3231
3232                 /* Validate the header data */
3233                 RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
3234                 RESTRICT_TO_RANGE(frame->rawheight, ov->minheight,
3235                                   ov->maxheight);
3236
3237                 /* Don't allow byte count to exceed buffer size */
3238                 RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
3239
3240                 if (frame->scanstate == STATE_LINES) {
3241                         int nextf;
3242
3243                         frame->grabstate = FRAME_DONE;
3244                         wake_up_interruptible(&frame->wq);
3245
3246                         /* If next frame is ready or grabbing,
3247                          * point to it */
3248                         nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
3249                         if (ov->frame[nextf].grabstate == FRAME_READY
3250                             || ov->frame[nextf].grabstate == FRAME_GRABBING) {
3251                                 ov->curframe = nextf;
3252                                 ov->frame[nextf].scanstate = STATE_SCANNING;
3253                         } else {
3254                                 if (frame->grabstate == FRAME_DONE) {
3255                                         PDEBUG(4, "** Frame done **");
3256                                 } else {
3257                                         PDEBUG(4, "Frame not ready? state = %d",
3258                                                 ov->frame[nextf].grabstate);
3259                                 }
3260
3261                                 ov->curframe = -1;
3262                         }
3263                 } else {
3264                         PDEBUG(5, "Frame done, but not scanning");
3265                 }
3266                 /* Image corruption caused by misplaced frame->segment = 0
3267                  * fixed by carlosf@conectiva.com.br
3268                  */
3269         } else {
3270                 /* Frame start */
3271                 PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
3272
3273                 /* Check to see if it's a snapshot frame */
3274                 /* FIXME?? Should the snapshot reset go here? Performance? */
3275                 if (in[8] & 0x02) {
3276                         frame->snapshot = 1;
3277                         PDEBUG(3, "snapshot detected");
3278                 }
3279
3280                 frame->scanstate = STATE_LINES;
3281                 frame->bytes_recvd = 0;
3282                 frame->compressed = in[8] & 0x40;
3283         }
3284
3285 check_middle:
3286         /* Are we in a frame? */
3287         if (frame->scanstate != STATE_LINES) {
3288                 PDEBUG(5, "Not in a frame; packet skipped");
3289                 return;
3290         }
3291
3292         /* If frame start, skip header */
3293         if (frame->bytes_recvd == 0)
3294                 offset = 9;
3295         else
3296                 offset = 0;
3297
3298         num = n - offset - 1;
3299
3300         /* Dump all data exactly as received */
3301         if (dumppix == 2) {
3302                 frame->bytes_recvd += n - 1;
3303                 if (frame->bytes_recvd <= max_raw)
3304                         memcpy(frame->rawdata + frame->bytes_recvd - (n - 1),
3305                                 in, n - 1);
3306                 else
3307                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3308                                 frame->bytes_recvd - max_raw);
3309         } else if (!frame->compressed && !remove_zeros) {
3310                 frame->bytes_recvd += num;
3311                 if (frame->bytes_recvd <= max_raw)
3312                         memcpy(frame->rawdata + frame->bytes_recvd - num,
3313                                 in + offset, num);
3314                 else
3315                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3316                                 frame->bytes_recvd - max_raw);
3317         } else { /* Remove all-zero FIFO lines (aligned 32-byte blocks) */
3318                 int b, read = 0, allzero, copied = 0;
3319                 if (offset) {
3320                         frame->bytes_recvd += 32 - offset;      // Bytes out
3321                         memcpy(frame->rawdata,  in + offset, 32 - offset);
3322                         read += 32;
3323                 }
3324
3325                 while (read < n - 1) {
3326                         allzero = 1;
3327                         for (b = 0; b < 32; b++) {
3328                                 if (in[read + b]) {
3329                                         allzero = 0;
3330                                         break;
3331                                 }
3332                         }
3333
3334                         if (allzero) {
3335                                 /* Don't copy it */
3336                         } else {
3337                                 if (frame->bytes_recvd + copied + 32 <= max_raw)
3338                                 {
3339                                         memcpy(frame->rawdata
3340                                                 + frame->bytes_recvd + copied,
3341                                                 in + read, 32);
3342                                         copied += 32;
3343                                 } else {
3344                                         PDEBUG(3, "Raw data buffer overrun!!");
3345                                 }
3346                         }
3347                         read += 32;
3348                 }
3349
3350                 frame->bytes_recvd += copied;
3351         }
3352 }
3353
3354 static inline void
3355 ov518_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
3356 {
3357         int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
3358         struct ov511_frame *frame = &ov->frame[ov->curframe];
3359         struct timeval *ts;
3360
3361         /* Don't copy the packet number byte */
3362         if (ov->packet_numbering)
3363                 --n;
3364
3365         /* A false positive here is likely, until OVT gives me
3366          * the definitive SOF/EOF format */
3367         if ((!(in[0] | in[1] | in[2] | in[3] | in[5])) && in[6]) {
3368                 if (printph) {
3369                         info("ph: %2x %2x %2x %2x %2x %2x %2x %2x", in[0],
3370                              in[1], in[2], in[3], in[4], in[5], in[6], in[7]);
3371                 }
3372
3373                 if (frame->scanstate == STATE_LINES) {
3374                         PDEBUG(4, "Detected frame end/start");
3375                         goto eof;
3376                 } else { //scanstate == STATE_SCANNING
3377                         /* Frame start */
3378                         PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
3379                         goto sof;
3380                 }
3381         } else {
3382                 goto check_middle;
3383         }
3384
3385 eof:
3386         ts = (struct timeval *)(frame->data
3387               + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
3388         do_gettimeofday(ts);
3389
3390         PDEBUG(4, "Frame end, curframe = %d, hw=%d, vw=%d, recvd=%d",
3391                 ov->curframe,
3392                 (int)(in[9]), (int)(in[10]), frame->bytes_recvd);
3393
3394         // FIXME: Since we don't know the header formats yet,
3395         // there is no way to know what the actual image size is
3396         frame->rawwidth = frame->width;
3397         frame->rawheight = frame->height;
3398
3399         /* Validate the header data */
3400         RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
3401         RESTRICT_TO_RANGE(frame->rawheight, ov->minheight, ov->maxheight);
3402
3403         /* Don't allow byte count to exceed buffer size */
3404         RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
3405
3406         if (frame->scanstate == STATE_LINES) {
3407                 int nextf;
3408
3409                 frame->grabstate = FRAME_DONE;
3410                 wake_up_interruptible(&frame->wq);
3411
3412                 /* If next frame is ready or grabbing,
3413                  * point to it */
3414                 nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
3415                 if (ov->frame[nextf].grabstate == FRAME_READY
3416                     || ov->frame[nextf].grabstate == FRAME_GRABBING) {
3417                         ov->curframe = nextf;
3418                         ov->frame[nextf].scanstate = STATE_SCANNING;
3419                         frame = &ov->frame[nextf];
3420                 } else {
3421                         if (frame->grabstate == FRAME_DONE) {
3422                                 PDEBUG(4, "** Frame done **");
3423                         } else {
3424                                 PDEBUG(4, "Frame not ready? state = %d",
3425                                        ov->frame[nextf].grabstate);
3426                         }
3427
3428                         ov->curframe = -1;
3429                         PDEBUG(4, "SOF dropped (no active frame)");
3430                         return;  /* Nowhere to store this frame */
3431                 }
3432         }
3433 sof:
3434         PDEBUG(4, "Starting capture on frame %d", frame->framenum);
3435
3436 // Snapshot not reverse-engineered yet.
3437 #if 0
3438         /* Check to see if it's a snapshot frame */
3439         /* FIXME?? Should the snapshot reset go here? Performance? */
3440         if (in[8] & 0x02) {
3441                 frame->snapshot = 1;
3442                 PDEBUG(3, "snapshot detected");
3443         }
3444 #endif
3445         frame->scanstate = STATE_LINES;
3446         frame->bytes_recvd = 0;
3447         frame->compressed = 1;
3448
3449 check_middle:
3450         /* Are we in a frame? */
3451         if (frame->scanstate != STATE_LINES) {
3452                 PDEBUG(4, "scanstate: no SOF yet");
3453                 return;
3454         }
3455
3456         /* Dump all data exactly as received */
3457         if (dumppix == 2) {
3458                 frame->bytes_recvd += n;
3459                 if (frame->bytes_recvd <= max_raw)
3460                         memcpy(frame->rawdata + frame->bytes_recvd - n, in, n);
3461                 else
3462                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3463                                 frame->bytes_recvd - max_raw);
3464         } else {
3465                 /* All incoming data are divided into 8-byte segments. If the
3466                  * segment contains all zero bytes, it must be skipped. These
3467                  * zero-segments allow the OV518 to mainain a constant data rate
3468                  * regardless of the effectiveness of the compression. Segments
3469                  * are aligned relative to the beginning of each isochronous
3470                  * packet. The first segment in each image is a header (the
3471                  * decompressor skips it later).
3472                  */
3473
3474                 int b, read = 0, allzero, copied = 0;
3475
3476                 while (read < n) {
3477                         allzero = 1;
3478                         for (b = 0; b < 8; b++) {
3479                                 if (in[read + b]) {
3480                                         allzero = 0;
3481                                         break;
3482                                 }
3483                         }
3484
3485                         if (allzero) {
3486                         /* Don't copy it */
3487                         } else {
3488                                 if (frame->bytes_recvd + copied + 8 <= max_raw)
3489                                 {
3490                                         memcpy(frame->rawdata
3491                                                 + frame->bytes_recvd + copied,
3492                                                 in + read, 8);
3493                                         copied += 8;
3494                                 } else {
3495                                         PDEBUG(3, "Raw data buffer overrun!!");
3496                                 }
3497                         }
3498                         read += 8;
3499                 }
3500                 frame->bytes_recvd += copied;
3501         }
3502 }
3503
3504 static void
3505 ov51x_isoc_irq(struct urb *urb)
3506 {
3507         int i;
3508         struct usb_ov511 *ov;
3509         struct ov511_sbuf *sbuf;
3510
3511         if (!urb->context) {
3512                 PDEBUG(4, "no context");
3513                 return;
3514         }
3515
3516         sbuf = urb->context;
3517         ov = sbuf->ov;
3518
3519         if (!ov || !ov->dev || !ov->user) {
3520                 PDEBUG(4, "no device, or not open");
3521                 return;
3522         }
3523
3524         if (!ov->streaming) {
3525                 PDEBUG(4, "hmmm... not streaming, but got interrupt");
3526                 return;
3527         }
3528
3529         if (urb->status == -ENOENT || urb->status == -ECONNRESET) {
3530                 PDEBUG(4, "URB unlinked");
3531                 return;
3532         }
3533
3534         if (urb->status != -EINPROGRESS && urb->status != 0) {
3535                 err("ERROR: urb->status=%d: %s", urb->status,
3536                     symbolic(urb_errlist, urb->status));
3537         }
3538
3539         /* Copy the data received into our frame buffer */
3540         PDEBUG(5, "sbuf[%d]: Moving %d packets", sbuf->n,
3541                urb->number_of_packets);
3542         for (i = 0; i < urb->number_of_packets; i++) {
3543                 /* Warning: Don't call *_move_data() if no frame active! */
3544                 if (ov->curframe >= 0) {
3545                         int n = urb->iso_frame_desc[i].actual_length;
3546                         int st = urb->iso_frame_desc[i].status;
3547                         unsigned char *cdata;
3548
3549                         urb->iso_frame_desc[i].actual_length = 0;
3550                         urb->iso_frame_desc[i].status = 0;
3551
3552                         cdata = urb->transfer_buffer
3553                                 + urb->iso_frame_desc[i].offset;
3554
3555                         if (!n) {
3556                                 PDEBUG(4, "Zero-length packet");
3557                                 continue;
3558                         }
3559
3560                         if (st)
3561                                 PDEBUG(2, "data error: [%d] len=%d, status=%d",
3562                                        i, n, st);
3563
3564                         if (ov->bclass == BCL_OV511)
3565                                 ov511_move_data(ov, cdata, n);
3566                         else if (ov->bclass == BCL_OV518)
3567                                 ov518_move_data(ov, cdata, n);
3568                         else
3569                                 err("Unknown bridge device (%d)", ov->bridge);
3570
3571                 } else if (waitqueue_active(&ov->wq)) {
3572                         wake_up_interruptible(&ov->wq);
3573                 }
3574         }
3575
3576         /* Resubmit this URB */
3577         urb->dev = ov->dev;
3578         if ((i = usb_submit_urb(urb, GFP_ATOMIC)) != 0)
3579                 err("usb_submit_urb() ret %d", i);
3580
3581         return;
3582 }
3583
3584 /****************************************************************************
3585  *
3586  * Stream initialization and termination
3587  *
3588  ***************************************************************************/
3589
3590 static int
3591 ov51x_init_isoc(struct usb_ov511 *ov)
3592 {
3593         struct urb *urb;
3594         int fx, err, n, size;
3595
3596         PDEBUG(3, "*** Initializing capture ***");
3597
3598         ov->curframe = -1;
3599
3600         if (ov->bridge == BRG_OV511) {
3601                 if (cams == 1)
3602                         size = 993;
3603                 else if (cams == 2)
3604                         size = 513;
3605                 else if (cams == 3 || cams == 4)
3606                         size = 257;
3607                 else {
3608                         err("\"cams\" parameter too high!");
3609                         return -1;
3610                 }
3611         } else if (ov->bridge == BRG_OV511PLUS) {
3612                 if (cams == 1)
3613                         size = 961;
3614                 else if (cams == 2)
3615                         size = 513;
3616                 else if (cams == 3 || cams == 4)
3617                         size = 257;
3618                 else if (cams >= 5 && cams <= 8)
3619                         size = 129;
3620                 else if (cams >= 9 && cams <= 31)
3621                         size = 33;
3622                 else {
3623                         err("\"cams\" parameter too high!");
3624                         return -1;
3625                 }
3626         } else if (ov->bclass == BCL_OV518) {
3627                 if (cams == 1)
3628                         size = 896;
3629                 else if (cams == 2)
3630                         size = 512;
3631                 else if (cams == 3 || cams == 4)
3632                         size = 256;
3633                 else if (cams >= 5 && cams <= 8)
3634                         size = 128;
3635                 else {
3636                         err("\"cams\" parameter too high!");
3637                         return -1;
3638                 }
3639         } else {
3640                 err("invalid bridge type");
3641                 return -1;
3642         }
3643
3644         // FIXME: OV518 is hardcoded to 15 FPS (alternate 5) for now
3645         if (ov->bclass == BCL_OV518) {
3646                 if (packetsize == -1) {
3647                         ov518_set_packet_size(ov, 640);
3648                 } else {
3649                         info("Forcing packet size to %d", packetsize);
3650                         ov518_set_packet_size(ov, packetsize);
3651                 }
3652         } else {
3653                 if (packetsize == -1) {
3654                         ov511_set_packet_size(ov, size);
3655                 } else {
3656                         info("Forcing packet size to %d", packetsize);
3657                         ov511_set_packet_size(ov, packetsize);
3658                 }
3659         }
3660
3661         for (n = 0; n < OV511_NUMSBUF; n++) {
3662                 urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
3663                 if (!urb) {
3664                         err("init isoc: usb_alloc_urb ret. NULL");
3665                         return -ENOMEM;
3666                 }
3667                 ov->sbuf[n].urb = urb;
3668                 urb->dev = ov->dev;
3669                 urb->context = &ov->sbuf[n];
3670                 urb->pipe = usb_rcvisocpipe(ov->dev, OV511_ENDPOINT_ADDRESS);
3671                 urb->transfer_flags = URB_ISO_ASAP;
3672                 urb->transfer_buffer = ov->sbuf[n].data;
3673                 urb->complete = ov51x_isoc_irq;
3674                 urb->number_of_packets = FRAMES_PER_DESC;
3675                 urb->transfer_buffer_length = ov->packet_size * FRAMES_PER_DESC;
3676                 urb->interval = 1;
3677                 for (fx = 0; fx < FRAMES_PER_DESC; fx++) {
3678                         urb->iso_frame_desc[fx].offset = ov->packet_size * fx;
3679                         urb->iso_frame_desc[fx].length = ov->packet_size;
3680                 }
3681         }
3682
3683         ov->streaming = 1;
3684
3685         for (n = 0; n < OV511_NUMSBUF; n++) {
3686                 ov->sbuf[n].urb->dev = ov->dev;
3687                 err = usb_submit_urb(ov->sbuf[n].urb, GFP_KERNEL);
3688                 if (err) {
3689                         err("init isoc: usb_submit_urb(%d) ret %d", n, err);
3690                         return err;
3691                 }
3692         }
3693
3694         return 0;
3695 }
3696
3697 static void
3698 ov51x_unlink_isoc(struct usb_ov511 *ov)
3699 {
3700         int n;
3701
3702         /* Unschedule all of the iso td's */
3703         for (n = OV511_NUMSBUF - 1; n >= 0; n--) {
3704                 if (ov->sbuf[n].urb) {
3705                         usb_kill_urb(ov->sbuf[n].urb);
3706                         usb_free_urb(ov->sbuf[n].urb);
3707                         ov->sbuf[n].urb = NULL;
3708                 }
3709         }
3710 }
3711
3712 static void
3713 ov51x_stop_isoc(struct usb_ov511 *ov)
3714 {
3715         if (!ov->streaming || !ov->dev)
3716                 return;
3717
3718         PDEBUG(3, "*** Stopping capture ***");
3719
3720         if (ov->bclass == BCL_OV518)
3721                 ov518_set_packet_size(ov, 0);
3722         else
3723                 ov511_set_packet_size(ov, 0);
3724
3725         ov->streaming = 0;
3726
3727         ov51x_unlink_isoc(ov);
3728 }
3729
3730 static int
3731 ov51x_new_frame(struct usb_ov511 *ov, int framenum)
3732 {
3733         struct ov511_frame *frame;
3734         int newnum;
3735
3736         PDEBUG(4, "ov->curframe = %d, framenum = %d", ov->curframe, framenum);
3737
3738         if (!ov->dev)
3739                 return -1;
3740
3741         /* If we're not grabbing a frame right now and the other frame is */
3742         /* ready to be grabbed into, then use it instead */
3743         if (ov->curframe == -1) {
3744                 newnum = (framenum - 1 + OV511_NUMFRAMES) % OV511_NUMFRAMES;
3745                 if (ov->frame[newnum].grabstate == FRAME_READY)
3746                         framenum = newnum;
3747         } else
3748                 return 0;
3749
3750         frame = &ov->frame[framenum];
3751
3752         PDEBUG(4, "framenum = %d, width = %d, height = %d", framenum,
3753                frame->width, frame->height);
3754
3755         frame->grabstate = FRAME_GRABBING;
3756         frame->scanstate = STATE_SCANNING;
3757         frame->snapshot = 0;
3758
3759         ov->curframe = framenum;
3760
3761         /* Make sure it's not too big */
3762         if (frame->width > ov->maxwidth)
3763                 frame->width = ov->maxwidth;
3764
3765         frame->width &= ~7L;            /* Multiple of 8 */
3766
3767         if (frame->height > ov->maxheight)
3768                 frame->height = ov->maxheight;
3769
3770         frame->height &= ~3L;           /* Multiple of 4 */
3771
3772         return 0;
3773 }
3774
3775 /****************************************************************************
3776  *
3777  * Buffer management
3778  *
3779  ***************************************************************************/
3780
3781 /*
3782  * - You must acquire buf_lock before entering this function.
3783  * - Because this code will free any non-null pointer, you must be sure to null
3784  *   them if you explicitly free them somewhere else!
3785  */
3786 static void
3787 ov51x_do_dealloc(struct usb_ov511 *ov)
3788 {
3789         int i;
3790         PDEBUG(4, "entered");
3791
3792         if (ov->fbuf) {
3793                 rvfree(ov->fbuf, OV511_NUMFRAMES
3794                        * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight));
3795                 ov->fbuf = NULL;
3796         }
3797
3798         vfree(ov->rawfbuf);
3799         ov->rawfbuf = NULL;
3800
3801         vfree(ov->tempfbuf);
3802         ov->tempfbuf = NULL;
3803
3804         for (i = 0; i < OV511_NUMSBUF; i++) {
3805                 kfree(ov->sbuf[i].data);
3806                 ov->sbuf[i].data = NULL;
3807         }
3808
3809         for (i = 0; i < OV511_NUMFRAMES; i++) {
3810                 ov->frame[i].data = NULL;
3811                 ov->frame[i].rawdata = NULL;
3812                 ov->frame[i].tempdata = NULL;
3813                 if (ov->frame[i].compbuf) {
3814                         free_page((unsigned long) ov->frame[i].compbuf);
3815                         ov->frame[i].compbuf = NULL;
3816                 }
3817         }
3818
3819         PDEBUG(4, "buffer memory deallocated");
3820         ov->buf_state = BUF_NOT_ALLOCATED;
3821         PDEBUG(4, "leaving");
3822 }
3823
3824 static int
3825 ov51x_alloc(struct usb_ov511 *ov)
3826 {
3827         int i;
3828         const int w = ov->maxwidth;
3829         const int h = ov->maxheight;
3830         const int data_bufsize = OV511_NUMFRAMES * MAX_DATA_SIZE(w, h);
3831         const int raw_bufsize = OV511_NUMFRAMES * MAX_RAW_DATA_SIZE(w, h);
3832
3833         PDEBUG(4, "entered");
3834         mutex_lock(&ov->buf_lock);
3835
3836         if (ov->buf_state == BUF_ALLOCATED)
3837                 goto out;
3838
3839         ov->fbuf = rvmalloc(data_bufsize);
3840         if (!ov->fbuf)
3841                 goto error;
3842
3843         ov->rawfbuf = vmalloc(raw_bufsize);
3844         if (!ov->rawfbuf)
3845                 goto error;
3846
3847         memset(ov->rawfbuf, 0, raw_bufsize);
3848
3849         ov->tempfbuf = vmalloc(raw_bufsize);
3850         if (!ov->tempfbuf)
3851                 goto error;
3852
3853         memset(ov->tempfbuf, 0, raw_bufsize);
3854
3855         for (i = 0; i < OV511_NUMSBUF; i++) {
3856                 ov->sbuf[i].data = kmalloc(FRAMES_PER_DESC *
3857                         MAX_FRAME_SIZE_PER_DESC, GFP_KERNEL);
3858                 if (!ov->sbuf[i].data)
3859                         goto error;
3860
3861                 PDEBUG(4, "sbuf[%d] @ %p", i, ov->sbuf[i].data);
3862         }
3863
3864         for (i = 0; i < OV511_NUMFRAMES; i++) {
3865                 ov->frame[i].data = ov->fbuf + i * MAX_DATA_SIZE(w, h);
3866                 ov->frame[i].rawdata = ov->rawfbuf
3867                  + i * MAX_RAW_DATA_SIZE(w, h);
3868                 ov->frame[i].tempdata = ov->tempfbuf
3869                  + i * MAX_RAW_DATA_SIZE(w, h);
3870
3871                 ov->frame[i].compbuf =
3872                  (unsigned char *) __get_free_page(GFP_KERNEL);
3873                 if (!ov->frame[i].compbuf)
3874                         goto error;
3875
3876                 PDEBUG(4, "frame[%d] @ %p", i, ov->frame[i].data);
3877         }
3878
3879         ov->buf_state = BUF_ALLOCATED;
3880 out:
3881         mutex_unlock(&ov->buf_lock);
3882         PDEBUG(4, "leaving");
3883         return 0;
3884 error:
3885         ov51x_do_dealloc(ov);
3886         mutex_unlock(&ov->buf_lock);
3887         PDEBUG(4, "errored");
3888         return -ENOMEM;
3889 }
3890
3891 static void
3892 ov51x_dealloc(struct usb_ov511 *ov)
3893 {
3894         PDEBUG(4, "entered");
3895         mutex_lock(&ov->buf_lock);
3896         ov51x_do_dealloc(ov);
3897         mutex_unlock(&ov->buf_lock);
3898         PDEBUG(4, "leaving");
3899 }
3900
3901 /****************************************************************************
3902  *
3903  * V4L 1 API
3904  *
3905  ***************************************************************************/
3906
3907 static int
3908 ov51x_v4l1_open(struct inode *inode, struct file *file)
3909 {
3910         struct video_device *vdev = video_devdata(file);
3911         struct usb_ov511 *ov = video_get_drvdata(vdev);
3912         int err, i;
3913
3914         PDEBUG(4, "opening");
3915
3916         mutex_lock(&ov->lock);
3917
3918         err = -EBUSY;
3919         if (ov->user)
3920                 goto out;
3921
3922         ov->sub_flag = 0;
3923
3924         /* In case app doesn't set them... */
3925         err = ov51x_set_default_params(ov);
3926         if (err < 0)
3927                 goto out;
3928
3929         /* Make sure frames are reset */
3930         for (i = 0; i < OV511_NUMFRAMES; i++) {
3931                 ov->frame[i].grabstate = FRAME_UNUSED;
3932                 ov->frame[i].bytes_read = 0;
3933         }
3934
3935         /* If compression is on, make sure now that a
3936          * decompressor can be loaded */
3937         if (ov->compress && !ov->decomp_ops) {
3938                 err = request_decompressor(ov);
3939                 if (err && !dumppix)
3940                         goto out;
3941         }
3942
3943         err = ov51x_alloc(ov);
3944         if (err < 0)
3945                 goto out;
3946
3947         err = ov51x_init_isoc(ov);
3948         if (err) {
3949                 ov51x_dealloc(ov);
3950                 goto out;
3951         }
3952
3953         ov->user++;
3954         file->private_data = vdev;
3955
3956         if (ov->led_policy == LED_AUTO)
3957                 ov51x_led_control(ov, 1);
3958
3959 out:
3960         mutex_unlock(&ov->lock);
3961         return err;
3962 }
3963
3964 static int
3965 ov51x_v4l1_close(struct inode *inode, struct file *file)
3966 {
3967         struct video_device *vdev = file->private_data;
3968         struct usb_ov511 *ov = video_get_drvdata(vdev);
3969
3970         PDEBUG(4, "ov511_close");
3971
3972         mutex_lock(&ov->lock);
3973
3974         ov->user--;
3975         ov51x_stop_isoc(ov);
3976
3977         if (ov->led_policy == LED_AUTO)
3978                 ov51x_led_control(ov, 0);
3979
3980         if (ov->dev)
3981                 ov51x_dealloc(ov);
3982
3983         mutex_unlock(&ov->lock);
3984
3985         /* Device unplugged while open. Only a minimum of unregistration is done
3986          * here; the disconnect callback already did the rest. */
3987         if (!ov->dev) {
3988                 mutex_lock(&ov->cbuf_lock);
3989                 kfree(ov->cbuf);
3990                 ov->cbuf = NULL;
3991                 mutex_unlock(&ov->cbuf_lock);
3992
3993                 ov51x_dealloc(ov);
3994                 kfree(ov);
3995                 ov = NULL;
3996         }
3997
3998         file->private_data = NULL;
3999         return 0;
4000 }
4001
4002 /* Do not call this function directly! */
4003 static int
4004 ov51x_v4l1_ioctl_internal(struct inode *inode, struct file *file,
4005                           unsigned int cmd, void *arg)
4006 {
4007         struct video_device *vdev = file->private_data;
4008         struct usb_ov511 *ov = video_get_drvdata(vdev);
4009         PDEBUG(5, "IOCtl: 0x%X", cmd);
4010
4011         if (!ov->dev)
4012                 return -EIO;
4013
4014         switch (cmd) {
4015         case VIDIOCGCAP:
4016         {
4017                 struct video_capability *b = arg;
4018
4019                 PDEBUG(4, "VIDIOCGCAP");
4020
4021                 memset(b, 0, sizeof(struct video_capability));
4022                 sprintf(b->name, "%s USB Camera",
4023                         symbolic(brglist, ov->bridge));
4024                 b->type = VID_TYPE_CAPTURE | VID_TYPE_SUBCAPTURE;
4025                 b->channels = ov->num_inputs;
4026                 b->audios = 0;
4027                 b->maxwidth = ov->maxwidth;
4028                 b->maxheight = ov->maxheight;
4029                 b->minwidth = ov->minwidth;
4030                 b->minheight = ov->minheight;
4031
4032                 return 0;
4033         }
4034         case VIDIOCGCHAN:
4035         {
4036                 struct video_channel *v = arg;
4037
4038                 PDEBUG(4, "VIDIOCGCHAN");
4039
4040                 if ((unsigned)(v->channel) >= ov->num_inputs) {
4041                         err("Invalid channel (%d)", v->channel);
4042                         return -EINVAL;
4043                 }
4044
4045                 v->norm = ov->norm;
4046                 v->type = VIDEO_TYPE_CAMERA;
4047                 v->flags = 0;
4048 //              v->flags |= (ov->has_decoder) ? VIDEO_VC_NORM : 0;
4049                 v->tuners = 0;
4050                 decoder_get_input_name(ov, v->channel, v->name);
4051
4052                 return 0;
4053         }
4054         case VIDIOCSCHAN:
4055         {
4056                 struct video_channel *v = arg;
4057                 int err;
4058
4059                 PDEBUG(4, "VIDIOCSCHAN");
4060
4061                 /* Make sure it's not a camera */
4062                 if (!ov->has_decoder) {
4063                         if (v->channel == 0)
4064                                 return 0;
4065                         else
4066                                 return -EINVAL;
4067                 }
4068
4069                 if (v->norm != VIDEO_MODE_PAL &&
4070                     v->norm != VIDEO_MODE_NTSC &&
4071                     v->norm != VIDEO_MODE_SECAM &&
4072                     v->norm != VIDEO_MODE_AUTO) {
4073                         err("Invalid norm (%d)", v->norm);
4074                         return -EINVAL;
4075                 }
4076
4077                 if ((unsigned)(v->channel) >= ov->num_inputs) {
4078                         err("Invalid channel (%d)", v->channel);
4079                         return -EINVAL;
4080                 }
4081
4082                 err = decoder_set_input(ov, v->channel);
4083                 if (err)
4084                         return err;
4085
4086                 err = decoder_set_norm(ov, v->norm);
4087                 if (err)
4088                         return err;
4089
4090                 return 0;
4091         }
4092         case VIDIOCGPICT:
4093         {
4094                 struct video_picture *p = arg;
4095
4096                 PDEBUG(4, "VIDIOCGPICT");
4097
4098                 memset(p, 0, sizeof(struct video_picture));
4099                 if (sensor_get_picture(ov, p))
4100                         return -EIO;
4101
4102                 /* Can we get these from frame[0]? -claudio? */
4103                 p->depth = ov->frame[0].depth;
4104                 p->palette = ov->frame[0].format;
4105
4106                 return 0;
4107         }
4108         case VIDIOCSPICT:
4109         {
4110                 struct video_picture *p = arg;
4111                 int i, rc;
4112
4113                 PDEBUG(4, "VIDIOCSPICT");
4114
4115                 if (!get_depth(p->palette))
4116                         return -EINVAL;
4117
4118                 if (sensor_set_picture(ov, p))
4119                         return -EIO;
4120
4121                 if (force_palette && p->palette != force_palette) {
4122                         info("Palette rejected (%s)",
4123                              symbolic(v4l1_plist, p->palette));
4124                         return -EINVAL;
4125                 }
4126
4127                 // FIXME: Format should be independent of frames
4128                 if (p->palette != ov->frame[0].format) {
4129                         PDEBUG(4, "Detected format change");
4130
4131                         rc = ov51x_wait_frames_inactive(ov);
4132                         if (rc)
4133                                 return rc;
4134
4135                         mode_init_regs(ov, ov->frame[0].width,
4136                                 ov->frame[0].height, p->palette, ov->sub_flag);
4137                 }
4138
4139                 PDEBUG(4, "Setting depth=%d, palette=%s",
4140                        p->depth, symbolic(v4l1_plist, p->palette));
4141
4142                 for (i = 0; i < OV511_NUMFRAMES; i++) {
4143                         ov->frame[i].depth = p->depth;
4144                         ov->frame[i].format = p->palette;
4145                 }
4146
4147                 return 0;
4148         }
4149         case VIDIOCGCAPTURE:
4150         {
4151                 int *vf = arg;
4152
4153                 PDEBUG(4, "VIDIOCGCAPTURE");
4154
4155                 ov->sub_flag = *vf;
4156                 return 0;
4157         }
4158         case VIDIOCSCAPTURE:
4159         {
4160                 struct video_capture *vc = arg;
4161
4162                 PDEBUG(4, "VIDIOCSCAPTURE");
4163
4164                 if (vc->flags)
4165                         return -EINVAL;
4166                 if (vc->decimation)
4167                         return -EINVAL;
4168
4169                 vc->x &= ~3L;
4170                 vc->y &= ~1L;
4171                 vc->y &= ~31L;
4172
4173                 if (vc->width == 0)
4174                         vc->width = 32;
4175
4176                 vc->height /= 16;
4177                 vc->height *= 16;
4178                 if (vc->height == 0)
4179                         vc->height = 16;
4180
4181                 ov->subx = vc->x;
4182                 ov->suby = vc->y;
4183                 ov->subw = vc->width;
4184                 ov->subh = vc->height;
4185
4186                 return 0;
4187         }
4188         case VIDIOCSWIN:
4189         {
4190                 struct video_window *vw = arg;
4191                 int i, rc;
4192
4193                 PDEBUG(4, "VIDIOCSWIN: %dx%d", vw->width, vw->height);
4194
4195 #if 0
4196                 if (vw->flags)
4197                         return -EINVAL;
4198                 if (vw->clipcount)
4199                         return -EINVAL;
4200                 if (vw->height != ov->maxheight)
4201                         return -EINVAL;
4202                 if (vw->width != ov->maxwidth)
4203                         return -EINVAL;
4204 #endif
4205
4206                 rc = ov51x_wait_frames_inactive(ov);
4207                 if (rc)
4208                         return rc;
4209
4210                 rc = mode_init_regs(ov, vw->width, vw->height,
4211                         ov->frame[0].format, ov->sub_flag);
4212                 if (rc < 0)
4213                         return rc;
4214
4215                 for (i = 0; i < OV511_NUMFRAMES; i++) {
4216                         ov->frame[i].width = vw->width;
4217                         ov->frame[i].height = vw->height;
4218                 }
4219
4220                 return 0;
4221         }
4222         case VIDIOCGWIN:
4223         {
4224                 struct video_window *vw = arg;
4225
4226                 memset(vw, 0, sizeof(struct video_window));
4227                 vw->x = 0;              /* FIXME */
4228                 vw->y = 0;
4229                 vw->width = ov->frame[0].width;
4230                 vw->height = ov->frame[0].height;
4231                 vw->flags = 30;
4232
4233                 PDEBUG(4, "VIDIOCGWIN: %dx%d", vw->width, vw->height);
4234
4235                 return 0;
4236         }
4237         case VIDIOCGMBUF:
4238         {
4239                 struct video_mbuf *vm = arg;
4240                 int i;
4241
4242                 PDEBUG(4, "VIDIOCGMBUF");
4243
4244                 memset(vm, 0, sizeof(struct video_mbuf));
4245                 vm->size = OV511_NUMFRAMES
4246                            * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
4247                 vm->frames = OV511_NUMFRAMES;
4248
4249                 vm->offsets[0] = 0;
4250                 for (i = 1; i < OV511_NUMFRAMES; i++) {
4251                         vm->offsets[i] = vm->offsets[i-1]
4252                            + MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
4253                 }
4254
4255                 return 0;
4256         }
4257         case VIDIOCMCAPTURE:
4258         {
4259                 struct video_mmap *vm = arg;
4260                 int rc, depth;
4261                 unsigned int f = vm->frame;
4262
4263                 PDEBUG(4, "VIDIOCMCAPTURE: frame: %d, %dx%d, %s", f, vm->width,
4264                         vm->height, symbolic(v4l1_plist, vm->format));
4265
4266                 depth = get_depth(vm->format);
4267                 if (!depth) {
4268                         PDEBUG(2, "VIDIOCMCAPTURE: invalid format (%s)",
4269                                symbolic(v4l1_plist, vm->format));
4270                         return -EINVAL;
4271                 }
4272
4273                 if (f >= OV511_NUMFRAMES) {
4274                         err("VIDIOCMCAPTURE: invalid frame (%d)", f);
4275                         return -EINVAL;
4276                 }
4277
4278                 if (vm->width > ov->maxwidth
4279                     || vm->height > ov->maxheight) {
4280                         err("VIDIOCMCAPTURE: requested dimensions too big");
4281                         return -EINVAL;
4282                 }
4283
4284                 if (ov->frame[f].grabstate == FRAME_GRABBING) {
4285                         PDEBUG(4, "VIDIOCMCAPTURE: already grabbing");
4286                         return -EBUSY;
4287                 }
4288
4289                 if (force_palette && (vm->format != force_palette)) {
4290                         PDEBUG(2, "palette rejected (%s)",
4291                                symbolic(v4l1_plist, vm->format));
4292                         return -EINVAL;
4293                 }
4294
4295                 if ((ov->frame[f].width != vm->width) ||
4296                     (ov->frame[f].height != vm->height) ||
4297                     (ov->frame[f].format != vm->format) ||
4298                     (ov->frame[f].sub_flag != ov->sub_flag) ||
4299                     (ov->frame[f].depth != depth)) {
4300                         PDEBUG(4, "VIDIOCMCAPTURE: change in image parameters");
4301
4302                         rc = ov51x_wait_frames_inactive(ov);
4303                         if (rc)
4304                                 return rc;
4305
4306                         rc = mode_init_regs(ov, vm->width, vm->height,
4307                                 vm->format, ov->sub_flag);
4308 #if 0
4309                         if (rc < 0) {
4310                                 PDEBUG(1, "Got error while initializing regs ");
4311                                 return ret;
4312                         }
4313 #endif
4314                         ov->frame[f].width = vm->width;
4315                         ov->frame[f].height = vm->height;
4316                         ov->frame[f].format = vm->format;
4317                         ov->frame[f].sub_flag = ov->sub_flag;
4318                         ov->frame[f].depth = depth;
4319                 }
4320
4321                 /* Mark it as ready */
4322                 ov->frame[f].grabstate = FRAME_READY;
4323
4324                 PDEBUG(4, "VIDIOCMCAPTURE: renewing frame %d", f);
4325
4326                 return ov51x_new_frame(ov, f);
4327         }
4328         case VIDIOCSYNC:
4329         {
4330                 unsigned int fnum = *((unsigned int *) arg);
4331                 struct ov511_frame *frame;
4332                 int rc;
4333
4334                 if (fnum >= OV511_NUMFRAMES) {
4335                         err("VIDIOCSYNC: invalid frame (%d)", fnum);
4336                         return -EINVAL;
4337                 }
4338
4339                 frame = &ov->frame[fnum];
4340
4341                 PDEBUG(4, "syncing to frame %d, grabstate = %d", fnum,
4342                        frame->grabstate);
4343
4344                 switch (frame->grabstate) {
4345                 case FRAME_UNUSED:
4346                         return -EINVAL;
4347                 case FRAME_READY:
4348                 case FRAME_GRABBING:
4349                 case FRAME_ERROR:
4350 redo:
4351                         if (!ov->dev)
4352                                 return -EIO;
4353
4354                         rc = wait_event_interruptible(frame->wq,
4355                             (frame->grabstate == FRAME_DONE)
4356                             || (frame->grabstate == FRAME_ERROR));
4357
4358                         if (rc)
4359                                 return rc;
4360
4361                         if (frame->grabstate == FRAME_ERROR) {
4362                                 if ((rc = ov51x_new_frame(ov, fnum)) < 0)
4363                                         return rc;
4364                                 goto redo;
4365                         }
4366                         /* Fall through */
4367                 case FRAME_DONE:
4368                         if (ov->snap_enabled && !frame->snapshot) {
4369                                 if ((rc = ov51x_new_frame(ov, fnum)) < 0)
4370                                         return rc;
4371                                 goto redo;
4372                         }
4373
4374                         frame->grabstate = FRAME_UNUSED;
4375
4376                         /* Reset the hardware snapshot button */
4377                         /* FIXME - Is this the best place for this? */
4378                         if ((ov->snap_enabled) && (frame->snapshot)) {
4379                                 frame->snapshot = 0;
4380                                 ov51x_clear_snapshot(ov);
4381                         }
4382
4383                         /* Decompression, format conversion, etc... */
4384                         ov51x_postprocess(ov, frame);
4385
4386                         break;
4387                 } /* end switch */
4388
4389                 return 0;
4390         }
4391         case VIDIOCGFBUF:
4392         {
4393                 struct video_buffer *vb = arg;
4394
4395                 PDEBUG(4, "VIDIOCGFBUF");
4396
4397                 memset(vb, 0, sizeof(struct video_buffer));
4398
4399                 return 0;
4400         }
4401         case VIDIOCGUNIT:
4402         {
4403                 struct video_unit *vu = arg;
4404
4405                 PDEBUG(4, "VIDIOCGUNIT");
4406
4407                 memset(vu, 0, sizeof(struct video_unit));
4408
4409                 vu->video = ov->vdev->minor;
4410                 vu->vbi = VIDEO_NO_UNIT;
4411                 vu->radio = VIDEO_NO_UNIT;
4412                 vu->audio = VIDEO_NO_UNIT;
4413                 vu->teletext = VIDEO_NO_UNIT;
4414
4415                 return 0;
4416         }
4417         case OV511IOC_WI2C:
4418         {
4419                 struct ov511_i2c_struct *w = arg;
4420
4421                 return i2c_w_slave(ov, w->slave, w->reg, w->value, w->mask);
4422         }
4423         case OV511IOC_RI2C:
4424         {
4425                 struct ov511_i2c_struct *r = arg;
4426                 int rc;
4427
4428                 rc = i2c_r_slave(ov, r->slave, r->reg);
4429                 if (rc < 0)
4430                         return rc;
4431
4432                 r->value = rc;
4433                 return 0;
4434         }
4435         default:
4436                 PDEBUG(3, "Unsupported IOCtl: 0x%X", cmd);
4437                 return -ENOIOCTLCMD;
4438         } /* end switch */
4439
4440         return 0;
4441 }
4442
4443 static int
4444 ov51x_v4l1_ioctl(struct inode *inode, struct file *file,
4445                  unsigned int cmd, unsigned long arg)
4446 {
4447         struct video_device *vdev = file->private_data;
4448         struct usb_ov511 *ov = video_get_drvdata(vdev);
4449         int rc;
4450
4451         if (mutex_lock_interruptible(&ov->lock))
4452                 return -EINTR;
4453
4454         rc = video_usercopy(inode, file, cmd, arg, ov51x_v4l1_ioctl_internal);
4455
4456         mutex_unlock(&ov->lock);
4457         return rc;
4458 }
4459
4460 static ssize_t
4461 ov51x_v4l1_read(struct file *file, char __user *buf, size_t cnt, loff_t *ppos)
4462 {
4463         struct video_device *vdev = file->private_data;
4464         int noblock = file->f_flags&O_NONBLOCK;
4465         unsigned long count = cnt;
4466         struct usb_ov511 *ov = video_get_drvdata(vdev);
4467         int i, rc = 0, frmx = -1;
4468         struct ov511_frame *frame;
4469
4470         if (mutex_lock_interruptible(&ov->lock))
4471                 return -EINTR;
4472
4473         PDEBUG(4, "%ld bytes, noblock=%d", count, noblock);
4474
4475         if (!vdev || !buf) {
4476                 rc = -EFAULT;
4477                 goto error;
4478         }
4479
4480         if (!ov->dev) {
4481                 rc = -EIO;
4482                 goto error;
4483         }
4484
4485 // FIXME: Only supports two frames
4486         /* See if a frame is completed, then use it. */
4487         if (ov->frame[0].grabstate >= FRAME_DONE)       /* _DONE or _ERROR */
4488                 frmx = 0;
4489         else if (ov->frame[1].grabstate >= FRAME_DONE)/* _DONE or _ERROR */
4490                 frmx = 1;
4491
4492         /* If nonblocking we return immediately */
4493         if (noblock && (frmx == -1)) {
4494                 rc = -EAGAIN;
4495                 goto error;
4496         }
4497
4498         /* If no FRAME_DONE, look for a FRAME_GRABBING state. */
4499         /* See if a frame is in process (grabbing), then use it. */
4500         if (frmx == -1) {
4501                 if (ov->frame[0].grabstate == FRAME_GRABBING)
4502                         frmx = 0;
4503                 else if (ov->frame[1].grabstate == FRAME_GRABBING)
4504                         frmx = 1;
4505         }
4506
4507         /* If no frame is active, start one. */
4508         if (frmx == -1) {
4509                 if ((rc = ov51x_new_frame(ov, frmx = 0))) {
4510                         err("read: ov51x_new_frame error");
4511                         goto error;
4512                 }
4513         }
4514
4515         frame = &ov->frame[frmx];
4516
4517 restart:
4518         if (!ov->dev) {
4519                 rc = -EIO;
4520                 goto error;
4521         }
4522
4523         /* Wait while we're grabbing the image */
4524         PDEBUG(4, "Waiting image grabbing");
4525         rc = wait_event_interruptible(frame->wq,
4526                 (frame->grabstate == FRAME_DONE)
4527                 || (frame->grabstate == FRAME_ERROR));
4528
4529         if (rc)
4530                 goto error;
4531
4532         PDEBUG(4, "Got image, frame->grabstate = %d", frame->grabstate);
4533         PDEBUG(4, "bytes_recvd = %d", frame->bytes_recvd);
4534
4535         if (frame->grabstate == FRAME_ERROR) {
4536                 frame->bytes_read = 0;
4537                 err("** ick! ** Errored frame %d", ov->curframe);
4538                 if (ov51x_new_frame(ov, frmx)) {
4539                         err("read: ov51x_new_frame error");
4540                         goto error;
4541                 }
4542                 goto restart;
4543         }
4544
4545
4546         /* Repeat until we get a snapshot frame */
4547         if (ov->snap_enabled)
4548                 PDEBUG(4, "Waiting snapshot frame");
4549         if (ov->snap_enabled && !frame->snapshot) {
4550                 frame->bytes_read = 0;
4551                 if ((rc = ov51x_new_frame(ov, frmx))) {
4552                         err("read: ov51x_new_frame error");
4553                         goto error;
4554                 }
4555                 goto restart;
4556         }
4557
4558         /* Clear the snapshot */
4559         if (ov->snap_enabled && frame->snapshot) {
4560                 frame->snapshot = 0;
4561                 ov51x_clear_snapshot(ov);
4562         }
4563
4564         /* Decompression, format conversion, etc... */
4565         ov51x_postprocess(ov, frame);
4566
4567         PDEBUG(4, "frmx=%d, bytes_read=%ld, length=%ld", frmx,
4568                 frame->bytes_read,
4569                 get_frame_length(frame));
4570
4571         /* copy bytes to user space; we allow for partials reads */
4572 //      if ((count + frame->bytes_read)
4573 //          > get_frame_length((struct ov511_frame *)frame))
4574 //              count = frame->scanlength - frame->bytes_read;
4575
4576         /* FIXME - count hardwired to be one frame... */
4577         count = get_frame_length(frame);
4578
4579         PDEBUG(4, "Copy to user space: %ld bytes", count);
4580         if ((i = copy_to_user(buf, frame->data + frame->bytes_read, count))) {
4581                 PDEBUG(4, "Copy failed! %d bytes not copied", i);
4582                 rc = -EFAULT;
4583                 goto error;
4584         }
4585
4586         frame->bytes_read += count;
4587         PDEBUG(4, "{copy} count used=%ld, new bytes_read=%ld",
4588                 count, frame->bytes_read);
4589
4590         /* If all data have been read... */
4591         if (frame->bytes_read
4592             >= get_frame_length(frame)) {
4593                 frame->bytes_read = 0;
4594
4595 // FIXME: Only supports two frames
4596                 /* Mark it as available to be used again. */
4597                 ov->frame[frmx].grabstate = FRAME_UNUSED;
4598                 if ((rc = ov51x_new_frame(ov, !frmx))) {
4599                         err("ov51x_new_frame returned error");
4600                         goto error;
4601                 }
4602         }
4603
4604         PDEBUG(4, "read finished, returning %ld (sweet)", count);
4605
4606         mutex_unlock(&ov->lock);
4607         return count;
4608
4609 error:
4610         mutex_unlock(&ov->lock);
4611         return rc;
4612 }
4613
4614 static int
4615 ov51x_v4l1_mmap(struct file *file, struct vm_area_struct *vma)
4616 {
4617         struct video_device *vdev = file->private_data;
4618         unsigned long start = vma->vm_start;
4619         unsigned long size  = vma->vm_end - vma->vm_start;
4620         struct usb_ov511 *ov = video_get_drvdata(vdev);
4621         unsigned long page, pos;
4622
4623         if (ov->dev == NULL)
4624                 return -EIO;
4625
4626         PDEBUG(4, "mmap: %ld (%lX) bytes", size, size);
4627
4628         if (size > (((OV511_NUMFRAMES
4629                       * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight)
4630                       + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))))
4631                 return -EINVAL;
4632
4633         if (mutex_lock_interruptible(&ov->lock))
4634                 return -EINTR;
4635
4636         pos = (unsigned long)ov->fbuf;
4637         while (size > 0) {
4638                 page = vmalloc_to_pfn((void *)pos);
4639                 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) {
4640                         mutex_unlock(&ov->lock);
4641                         return -EAGAIN;
4642                 }
4643                 start += PAGE_SIZE;
4644                 pos += PAGE_SIZE;
4645                 if (size > PAGE_SIZE)
4646                         size -= PAGE_SIZE;
4647                 else
4648                         size = 0;
4649         }
4650
4651         mutex_unlock(&ov->lock);
4652         return 0;
4653 }
4654
4655 static const struct file_operations ov511_fops = {
4656         .owner =        THIS_MODULE,
4657         .open =         ov51x_v4l1_open,
4658         .release =      ov51x_v4l1_close,
4659         .read =         ov51x_v4l1_read,
4660         .mmap =         ov51x_v4l1_mmap,
4661         .ioctl =        ov51x_v4l1_ioctl,
4662 #ifdef CONFIG_COMPAT
4663         .compat_ioctl = v4l_compat_ioctl32,
4664 #endif
4665         .llseek =       no_llseek,
4666 };
4667
4668 static struct video_device vdev_template = {
4669         .name =         "OV511 USB Camera",
4670         .fops =         &ov511_fops,
4671         .release =      video_device_release,
4672         .minor =        -1,
4673 };
4674
4675 /****************************************************************************
4676  *
4677  * OV511 and sensor configuration
4678  *
4679  ***************************************************************************/
4680
4681 /* This initializes the OV7610, OV7620, or OV76BE sensor. The OV76BE uses
4682  * the same register settings as the OV7610, since they are very similar.
4683  */
4684 static int
4685 ov7xx0_configure(struct usb_ov511 *ov)
4686 {
4687         int i, success;
4688         int rc;
4689
4690         /* Lawrence Glaister <lg@jfm.bc.ca> reports:
4691          *
4692          * Register 0x0f in the 7610 has the following effects:
4693          *
4694          * 0x85 (AEC method 1): Best overall, good contrast range
4695          * 0x45 (AEC method 2): Very overexposed
4696          * 0xa5 (spec sheet default): Ok, but the black level is
4697          *      shifted resulting in loss of contrast
4698          * 0x05 (old driver setting): very overexposed, too much
4699          *      contrast
4700          */
4701         static struct ov511_regvals aRegvalsNorm7610[] = {
4702                 { OV511_I2C_BUS, 0x10, 0xff },
4703                 { OV511_I2C_BUS, 0x16, 0x06 },
4704                 { OV511_I2C_BUS, 0x28, 0x24 },
4705                 { OV511_I2C_BUS, 0x2b, 0xac },
4706                 { OV511_I2C_BUS, 0x12, 0x00 },
4707                 { OV511_I2C_BUS, 0x38, 0x81 },
4708                 { OV511_I2C_BUS, 0x28, 0x24 },  /* 0c */
4709                 { OV511_I2C_BUS, 0x0f, 0x85 },  /* lg's setting */
4710                 { OV511_I2C_BUS, 0x15, 0x01 },
4711                 { OV511_I2C_BUS, 0x20, 0x1c },
4712                 { OV511_I2C_BUS, 0x23, 0x2a },
4713                 { OV511_I2C_BUS, 0x24, 0x10 },
4714                 { OV511_I2C_BUS, 0x25, 0x8a },
4715                 { OV511_I2C_BUS, 0x26, 0xa2 },
4716                 { OV511_I2C_BUS, 0x27, 0xc2 },
4717                 { OV511_I2C_BUS, 0x2a, 0x04 },
4718                 { OV511_I2C_BUS, 0x2c, 0xfe },
4719                 { OV511_I2C_BUS, 0x2d, 0x93 },
4720                 { OV511_I2C_BUS, 0x30, 0x71 },
4721                 { OV511_I2C_BUS, 0x31, 0x60 },
4722                 { OV511_I2C_BUS, 0x32, 0x26 },
4723                 { OV511_I2C_BUS, 0x33, 0x20 },
4724                 { OV511_I2C_BUS, 0x34, 0x48 },
4725                 { OV511_I2C_BUS, 0x12, 0x24 },
4726                 { OV511_I2C_BUS, 0x11, 0x01 },
4727                 { OV511_I2C_BUS, 0x0c, 0x24 },
4728                 { OV511_I2C_BUS, 0x0d, 0x24 },
4729                 { OV511_DONE_BUS, 0x0, 0x00 },
4730         };
4731
4732         static struct ov511_regvals aRegvalsNorm7620[] = {
4733                 { OV511_I2C_BUS, 0x00, 0x00 },
4734                 { OV511_I2C_BUS, 0x01, 0x80 },
4735                 { OV511_I2C_BUS, 0x02, 0x80 },
4736                 { OV511_I2C_BUS, 0x03, 0xc0 },
4737                 { OV511_I2C_BUS, 0x06, 0x60 },
4738                 { OV511_I2C_BUS, 0x07, 0x00 },
4739                 { OV511_I2C_BUS, 0x0c, 0x24 },
4740                 { OV511_I2C_BUS, 0x0c, 0x24 },
4741                 { OV511_I2C_BUS, 0x0d, 0x24 },
4742                 { OV511_I2C_BUS, 0x11, 0x01 },
4743                 { OV511_I2C_BUS, 0x12, 0x24 },
4744                 { OV511_I2C_BUS, 0x13, 0x01 },
4745                 { OV511_I2C_BUS, 0x14, 0x84 },
4746                 { OV511_I2C_BUS, 0x15, 0x01 },
4747                 { OV511_I2C_BUS, 0x16, 0x03 },
4748                 { OV511_I2C_BUS, 0x17, 0x2f },
4749                 { OV511_I2C_BUS, 0x18, 0xcf },
4750                 { OV511_I2C_BUS, 0x19, 0x06 },
4751                 { OV511_I2C_BUS, 0x1a, 0xf5 },
4752                 { OV511_I2C_BUS, 0x1b, 0x00 },
4753                 { OV511_I2C_BUS, 0x20, 0x18 },
4754                 { OV511_I2C_BUS, 0x21, 0x80 },
4755                 { OV511_I2C_BUS, 0x22, 0x80 },
4756                 { OV511_I2C_BUS, 0x23, 0x00 },
4757                 { OV511_I2C_BUS, 0x26, 0xa2 },
4758                 { OV511_I2C_BUS, 0x27, 0xea },
4759                 { OV511_I2C_BUS, 0x28, 0x20 },
4760                 { OV511_I2C_BUS, 0x29, 0x00 },
4761                 { OV511_I2C_BUS, 0x2a, 0x10 },
4762                 { OV511_I2C_BUS, 0x2b, 0x00 },
4763                 { OV511_I2C_BUS, 0x2c, 0x88 },
4764                 { OV511_I2C_BUS, 0x2d, 0x91 },
4765                 { OV511_I2C_BUS, 0x2e, 0x80 },
4766                 { OV511_I2C_BUS, 0x2f, 0x44 },
4767                 { OV511_I2C_BUS, 0x60, 0x27 },
4768                 { OV511_I2C_BUS, 0x61, 0x02 },
4769                 { OV511_I2C_BUS, 0x62, 0x5f },
4770                 { OV511_I2C_BUS, 0x63, 0xd5 },
4771                 { OV511_I2C_BUS, 0x64, 0x57 },
4772                 { OV511_I2C_BUS, 0x65, 0x83 },
4773                 { OV511_I2C_BUS, 0x66, 0x55 },
4774                 { OV511_I2C_BUS, 0x67, 0x92 },
4775                 { OV511_I2C_BUS, 0x68, 0xcf },
4776                 { OV511_I2C_BUS, 0x69, 0x76 },
4777                 { OV511_I2C_BUS, 0x6a, 0x22 },
4778                 { OV511_I2C_BUS, 0x6b, 0x00 },
4779                 { OV511_I2C_BUS, 0x6c, 0x02 },
4780                 { OV511_I2C_BUS, 0x6d, 0x44 },
4781                 { OV511_I2C_BUS, 0x6e, 0x80 },
4782                 { OV511_I2C_BUS, 0x6f, 0x1d },
4783                 { OV511_I2C_BUS, 0x70, 0x8b },
4784                 { OV511_I2C_BUS, 0x71, 0x00 },
4785                 { OV511_I2C_BUS, 0x72, 0x14 },
4786                 { OV511_I2C_BUS, 0x73, 0x54 },
4787                 { OV511_I2C_BUS, 0x74, 0x00 },
4788                 { OV511_I2C_BUS, 0x75, 0x8e },
4789                 { OV511_I2C_BUS, 0x76, 0x00 },
4790                 { OV511_I2C_BUS, 0x77, 0xff },
4791                 { OV511_I2C_BUS, 0x78, 0x80 },
4792                 { OV511_I2C_BUS, 0x79, 0x80 },
4793                 { OV511_I2C_BUS, 0x7a, 0x80 },
4794                 { OV511_I2C_BUS, 0x7b, 0xe2 },
4795                 { OV511_I2C_BUS, 0x7c, 0x00 },
4796                 { OV511_DONE_BUS, 0x0, 0x00 },
4797         };
4798
4799         PDEBUG(4, "starting configuration");
4800
4801         /* This looks redundant, but is necessary for WebCam 3 */
4802         ov->primary_i2c_slave = OV7xx0_SID;
4803         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
4804                 return -1;
4805
4806         if (init_ov_sensor(ov) >= 0) {
4807                 PDEBUG(1, "OV7xx0 sensor initalized (method 1)");
4808         } else {
4809                 /* Reset the 76xx */
4810                 if (i2c_w(ov, 0x12, 0x80) < 0)
4811                         return -1;
4812
4813                 /* Wait for it to initialize */
4814                 msleep(150);
4815
4816                 i = 0;
4817                 success = 0;
4818                 while (i <= i2c_detect_tries) {
4819                         if ((i2c_r(ov, OV7610_REG_ID_HIGH) == 0x7F) &&
4820                             (i2c_r(ov, OV7610_REG_ID_LOW) == 0xA2)) {
4821                                 success = 1;
4822                                 break;
4823                         } else {
4824                                 i++;
4825                         }
4826                 }
4827
4828 // Was (i == i2c_detect_tries) previously. This obviously used to always report
4829 // success. Whether anyone actually depended on that bug is unknown
4830                 if ((i >= i2c_detect_tries) && (success == 0)) {
4831                         err("Failed to read sensor ID. You might not have an");
4832                         err("OV7610/20, or it may be not responding. Report");
4833                         err("this to " EMAIL);
4834                         err("This is only a warning. You can attempt to use");
4835                         err("your camera anyway");
4836 // Only issue a warning for now
4837 //                      return -1;
4838                 } else {
4839                         PDEBUG(1, "OV7xx0 initialized (method 2, %dx)", i+1);
4840                 }
4841         }
4842
4843         /* Detect sensor (sub)type */
4844         rc = i2c_r(ov, OV7610_REG_COM_I);
4845
4846         if (rc < 0) {
4847                 err("Error detecting sensor type");
4848                 return -1;
4849         } else if ((rc & 3) == 3) {
4850                 info("Sensor is an OV7610");
4851                 ov->sensor = SEN_OV7610;
4852         } else if ((rc & 3) == 1) {
4853                 /* I don't know what's different about the 76BE yet. */
4854                 if (i2c_r(ov, 0x15) & 1)
4855                         info("Sensor is an OV7620AE");
4856                 else
4857                         info("Sensor is an OV76BE");
4858
4859                 /* OV511+ will return all zero isoc data unless we
4860                  * configure the sensor as a 7620. Someone needs to
4861                  * find the exact reg. setting that causes this. */
4862                 if (ov->bridge == BRG_OV511PLUS) {
4863                         info("Enabling 511+/7620AE workaround");
4864                         ov->sensor = SEN_OV7620;
4865                 } else {
4866                         ov->sensor = SEN_OV76BE;
4867                 }
4868         } else if ((rc & 3) == 0) {
4869                 info("Sensor is an OV7620");
4870                 ov->sensor = SEN_OV7620;
4871         } else {
4872                 err("Unknown image sensor version: %d", rc & 3);
4873                 return -1;
4874         }
4875
4876         if (ov->sensor == SEN_OV7620) {
4877                 PDEBUG(4, "Writing 7620 registers");
4878                 if (write_regvals(ov, aRegvalsNorm7620))
4879                         return -1;
4880         } else {
4881                 PDEBUG(4, "Writing 7610 registers");
4882                 if (write_regvals(ov, aRegvalsNorm7610))
4883                         return -1;
4884         }
4885
4886         /* Set sensor-specific vars */
4887         ov->maxwidth = 640;
4888         ov->maxheight = 480;
4889         ov->minwidth = 64;
4890         ov->minheight = 48;
4891
4892         // FIXME: These do not match the actual settings yet
4893         ov->brightness = 0x80 << 8;
4894         ov->contrast = 0x80 << 8;
4895         ov->colour = 0x80 << 8;
4896         ov->hue = 0x80 << 8;
4897
4898         return 0;
4899 }
4900
4901 /* This initializes the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
4902 static int
4903 ov6xx0_configure(struct usb_ov511 *ov)
4904 {
4905         int rc;
4906
4907         static struct ov511_regvals aRegvalsNorm6x20[] = {
4908                 { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4909                 { OV511_I2C_BUS, 0x11, 0x01 },
4910                 { OV511_I2C_BUS, 0x03, 0x60 },
4911                 { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4912                 { OV511_I2C_BUS, 0x07, 0xa8 },
4913                 /* The ratio of 0x0c and 0x0d  controls the white point */
4914                 { OV511_I2C_BUS, 0x0c, 0x24 },
4915                 { OV511_I2C_BUS, 0x0d, 0x24 },
4916                 { OV511_I2C_BUS, 0x0f, 0x15 }, /* COMS */
4917                 { OV511_I2C_BUS, 0x10, 0x75 }, /* AEC Exposure time */
4918                 { OV511_I2C_BUS, 0x12, 0x24 }, /* Enable AGC */
4919                 { OV511_I2C_BUS, 0x14, 0x04 },
4920                 /* 0x16: 0x06 helps frame stability with moving objects */
4921                 { OV511_I2C_BUS, 0x16, 0x06 },
4922 //              { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4923                 { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4924                 /* 0x28: 0x05 Selects RGB format if RGB on */
4925                 { OV511_I2C_BUS, 0x28, 0x05 },
4926                 { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4927 //              { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4928                 { OV511_I2C_BUS, 0x2d, 0x99 },
4929                 { OV511_I2C_BUS, 0x33, 0xa0 }, /* Color Processing Parameter */
4930                 { OV511_I2C_BUS, 0x34, 0xd2 }, /* Max A/D range */
4931                 { OV511_I2C_BUS, 0x38, 0x8b },
4932                 { OV511_I2C_BUS, 0x39, 0x40 },
4933
4934                 { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4935                 { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4936                 { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4937
4938                 { OV511_I2C_BUS, 0x3d, 0x80 },
4939                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4940                  * control the color balance */
4941                 { OV511_I2C_BUS, 0x4a, 0x80 },
4942                 { OV511_I2C_BUS, 0x4b, 0x80 },
4943                 { OV511_I2C_BUS, 0x4d, 0xd2 }, /* This reduces noise a bit */
4944                 { OV511_I2C_BUS, 0x4e, 0xc1 },
4945                 { OV511_I2C_BUS, 0x4f, 0x04 },
4946 // Do 50-53 have any effect?
4947 // Toggle 0x12[2] off and on here?
4948                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
4949         };
4950
4951         static struct ov511_regvals aRegvalsNorm6x30[] = {
4952         /*OK*/  { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4953                 { OV511_I2C_BUS, 0x11, 0x00 },
4954         /*OK*/  { OV511_I2C_BUS, 0x03, 0x60 },
4955         /*0A?*/ { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4956                 { OV511_I2C_BUS, 0x07, 0xa8 },
4957                 /* The ratio of 0x0c and 0x0d  controls the white point */
4958         /*OK*/  { OV511_I2C_BUS, 0x0c, 0x24 },
4959         /*OK*/  { OV511_I2C_BUS, 0x0d, 0x24 },
4960         /*A*/   { OV511_I2C_BUS, 0x0e, 0x20 },
4961 //      /*04?*/ { OV511_I2C_BUS, 0x14, 0x80 },
4962                 { OV511_I2C_BUS, 0x16, 0x03 },
4963 //      /*OK*/  { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4964                 // 21 & 22? The suggested values look wrong. Go with default
4965         /*A*/   { OV511_I2C_BUS, 0x23, 0xc0 },
4966         /*A*/   { OV511_I2C_BUS, 0x25, 0x9a }, // Check this against default
4967 //      /*OK*/  { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4968
4969                 /* 0x28: 0x05 Selects RGB format if RGB on */
4970 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x05 },
4971 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x45 }, // DEBUG: Tristate UV bus
4972
4973         /*OK*/  { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4974 //      /*OK*/  { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4975                 { OV511_I2C_BUS, 0x2d, 0x99 },
4976 //      /*A*/   { OV511_I2C_BUS, 0x33, 0x26 }, // Reserved bits on 6620
4977 //      /*d2?*/ { OV511_I2C_BUS, 0x34, 0x03 }, /* Max A/D range */
4978 //      /*8b?*/ { OV511_I2C_BUS, 0x38, 0x83 },
4979 //      /*40?*/ { OV511_I2C_BUS, 0x39, 0xc0 }, // 6630 adds bit 7
4980 //              { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4981 //              { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4982 //              { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4983                 { OV511_I2C_BUS, 0x3d, 0x80 },
4984 //      /*A*/   { OV511_I2C_BUS, 0x3f, 0x0e },
4985
4986                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4987                  * control the color balance */
4988 //      /*OK?*/ { OV511_I2C_BUS, 0x4a, 0x80 }, // Check these
4989 //      /*OK?*/ { OV511_I2C_BUS, 0x4b, 0x80 },
4990                 { OV511_I2C_BUS, 0x4d, 0x10 }, /* U = 0.563u, V = 0.714v */
4991         /*c1?*/ { OV511_I2C_BUS, 0x4e, 0x40 },
4992
4993                 /* UV average mode, color killer: strongest */
4994                 { OV511_I2C_BUS, 0x4f, 0x07 },
4995
4996                 { OV511_I2C_BUS, 0x54, 0x23 }, /* Max AGC gain: 18dB */
4997                 { OV511_I2C_BUS, 0x57, 0x81 }, /* (default) */
4998                 { OV511_I2C_BUS, 0x59, 0x01 }, /* AGC dark current comp: +1 */
4999                 { OV511_I2C_BUS, 0x5a, 0x2c }, /* (undocumented) */
5000                 { OV511_I2C_BUS, 0x5b, 0x0f }, /* AWB chrominance levels */
5001 //              { OV511_I2C_BUS, 0x5c, 0x10 },
5002                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
5003         };
5004
5005         PDEBUG(4, "starting sensor configuration");
5006
5007         if (init_ov_sensor(ov) < 0) {
5008                 err("Failed to read sensor ID. You might not have an OV6xx0,");
5009                 err("or it may be not responding. Report this to " EMAIL);
5010                 return -1;
5011         } else {
5012                 PDEBUG(1, "OV6xx0 sensor detected");
5013         }
5014
5015         /* Detect sensor (sub)type */
5016         rc = i2c_r(ov, OV7610_REG_COM_I);
5017
5018         if (rc < 0) {
5019                 err("Error detecting sensor type");
5020                 return -1;
5021         }
5022
5023         if ((rc & 3) == 0) {
5024                 ov->sensor = SEN_OV6630;
5025                 info("Sensor is an OV6630");
5026         } else if ((rc & 3) == 1) {
5027                 ov->sensor = SEN_OV6620;
5028                 info("Sensor is an OV6620");
5029         } else if ((rc & 3) == 2) {
5030                 ov->sensor = SEN_OV6630;
5031                 info("Sensor is an OV6630AE");
5032         } else if ((rc & 3) == 3) {
5033                 ov->sensor = SEN_OV6630;
5034                 info("Sensor is an OV6630AF");
5035         }
5036
5037         /* Set sensor-specific vars */
5038         ov->maxwidth = 352;
5039         ov->maxheight = 288;
5040         ov->minwidth = 64;
5041         ov->minheight = 48;
5042
5043         // FIXME: These do not match the actual settings yet
5044         ov->brightness = 0x80 << 8;
5045         ov->contrast = 0x80 << 8;
5046         ov->colour = 0x80 << 8;
5047         ov->hue = 0x80 << 8;
5048
5049         if (ov->sensor == SEN_OV6620) {
5050                 PDEBUG(4, "Writing 6x20 registers");
5051                 if (write_regvals(ov, aRegvalsNorm6x20))
5052                         return -1;
5053         } else {
5054                 PDEBUG(4, "Writing 6x30 registers");
5055                 if (write_regvals(ov, aRegvalsNorm6x30))
5056                         return -1;
5057         }
5058
5059         return 0;
5060 }
5061
5062 /* This initializes the KS0127 and KS0127B video decoders. */
5063 static int
5064 ks0127_configure(struct usb_ov511 *ov)
5065 {
5066         int rc;
5067
5068 // FIXME: I don't know how to sync or reset it yet
5069 #if 0
5070         if (ov51x_init_ks_sensor(ov) < 0) {
5071                 err("Failed to initialize the KS0127");
5072                 return -1;
5073         } else {
5074                 PDEBUG(1, "KS012x(B) sensor detected");
5075         }
5076 #endif
5077
5078         /* Detect decoder subtype */
5079         rc = i2c_r(ov, 0x00);
5080         if (rc < 0) {
5081                 err("Error detecting sensor type");
5082                 return -1;
5083         } else if (rc & 0x08) {
5084                 rc = i2c_r(ov, 0x3d);
5085                 if (rc < 0) {
5086                         err("Error detecting sensor type");
5087                         return -1;
5088                 } else if ((rc & 0x0f) == 0) {
5089                         info("Sensor is a KS0127");
5090                         ov->sensor = SEN_KS0127;
5091                 } else if ((rc & 0x0f) == 9) {
5092                         info("Sensor is a KS0127B Rev. A");
5093                         ov->sensor = SEN_KS0127B;
5094                 }
5095         } else {
5096                 err("Error: Sensor is an unsupported KS0122");
5097                 return -1;
5098         }
5099
5100         /* Set sensor-specific vars */
5101         ov->maxwidth = 640;
5102         ov->maxheight = 480;
5103         ov->minwidth = 64;
5104         ov->minheight = 48;
5105
5106         // FIXME: These do not match the actual settings yet
5107         ov->brightness = 0x80 << 8;
5108         ov->contrast = 0x80 << 8;
5109         ov->colour = 0x80 << 8;
5110         ov->hue = 0x80 << 8;
5111
5112         /* This device is not supported yet. Bail out now... */
5113         err("This sensor is not supported yet.");
5114         return -1;
5115
5116         return 0;
5117 }
5118
5119 /* This initializes the SAA7111A video decoder. */
5120 static int
5121 saa7111a_configure(struct usb_ov511 *ov)
5122 {
5123         int rc;
5124
5125         /* Since there is no register reset command, all registers must be
5126          * written, otherwise gives erratic results */
5127         static struct ov511_regvals aRegvalsNormSAA7111A[] = {
5128                 { OV511_I2C_BUS, 0x06, 0xce },
5129                 { OV511_I2C_BUS, 0x07, 0x00 },
5130                 { OV511_I2C_BUS, 0x10, 0x44 }, /* YUV422, 240/286 lines */
5131                 { OV511_I2C_BUS, 0x0e, 0x01 }, /* NTSC M or PAL BGHI */
5132                 { OV511_I2C_BUS, 0x00, 0x00 },
5133                 { OV511_I2C_BUS, 0x01, 0x00 },
5134                 { OV511_I2C_BUS, 0x03, 0x23 },
5135                 { OV511_I2C_BUS, 0x04, 0x00 },
5136                 { OV511_I2C_BUS, 0x05, 0x00 },
5137                 { OV511_I2C_BUS, 0x08, 0xc8 }, /* Auto field freq */
5138                 { OV511_I2C_BUS, 0x09, 0x01 }, /* Chrom. trap off, APER=0.25 */
5139                 { OV511_I2C_BUS, 0x0a, 0x80 }, /* BRIG=128 */
5140                 { OV511_I2C_BUS, 0x0b, 0x40 }, /* CONT=1.0 */
5141                 { OV511_I2C_BUS, 0x0c, 0x40 }, /* SATN=1.0 */
5142                 { OV511_I2C_BUS, 0x0d, 0x00 }, /* HUE=0 */
5143                 { OV511_I2C_BUS, 0x0f, 0x00 },
5144                 { OV511_I2C_BUS, 0x11, 0x0c },
5145                 { OV511_I2C_BUS, 0x12, 0x00 },
5146                 { OV511_I2C_BUS, 0x13, 0x00 },
5147                 { OV511_I2C_BUS, 0x14, 0x00 },
5148                 { OV511_I2C_BUS, 0x15, 0x00 },
5149                 { OV511_I2C_BUS, 0x16, 0x00 },
5150                 { OV511_I2C_BUS, 0x17, 0x00 },
5151                 { OV511_I2C_BUS, 0x02, 0xc0 },  /* Composite input 0 */
5152                 { OV511_DONE_BUS, 0x0, 0x00 },
5153         };
5154
5155 // FIXME: I don't know how to sync or reset it yet
5156 #if 0
5157         if (ov51x_init_saa_sensor(ov) < 0) {
5158                 err("Failed to initialize the SAA7111A");
5159                 return -1;
5160         } else {
5161                 PDEBUG(1, "SAA7111A sensor detected");
5162         }
5163 #endif
5164
5165         /* 640x480 not supported with PAL */
5166         if (ov->pal) {
5167                 ov->maxwidth = 320;
5168                 ov->maxheight = 240;            /* Even field only */
5169         } else {
5170                 ov->maxwidth = 640;
5171                 ov->maxheight = 480;            /* Even/Odd fields */
5172         }
5173
5174         ov->minwidth = 320;
5175         ov->minheight = 240;            /* Even field only */
5176
5177         ov->has_decoder = 1;
5178         ov->num_inputs = 8;
5179         ov->norm = VIDEO_MODE_AUTO;
5180         ov->stop_during_set = 0;        /* Decoder guarantees stable image */
5181
5182         /* Decoder doesn't change these values, so we use these instead of
5183          * acutally reading the registers (which doesn't work) */
5184         ov->brightness = 0x80 << 8;
5185         ov->contrast = 0x40 << 9;
5186         ov->colour = 0x40 << 9;
5187         ov->hue = 32768;
5188
5189         PDEBUG(4, "Writing SAA7111A registers");
5190         if (write_regvals(ov, aRegvalsNormSAA7111A))
5191                 return -1;
5192
5193         /* Detect version of decoder. This must be done after writing the
5194          * initial regs or the decoder will lock up. */
5195         rc = i2c_r(ov, 0x00);
5196
5197         if (rc < 0) {
5198                 err("Error detecting sensor version");
5199                 return -1;
5200         } else {
5201                 info("Sensor is an SAA7111A (version 0x%x)", rc);
5202                 ov->sensor = SEN_SAA7111A;
5203         }
5204
5205         // FIXME: Fix this for OV518(+)
5206         /* Latch to negative edge of clock. Otherwise, we get incorrect
5207          * colors and jitter in the digital signal. */
5208         if (ov->bclass == BCL_OV511)
5209                 reg_w(ov, 0x11, 0x00);
5210         else
5211                 warn("SAA7111A not yet supported with OV518/OV518+");
5212
5213         return 0;
5214 }
5215
5216 /* This initializes the OV511/OV511+ and the sensor */
5217 static int
5218 ov511_configure(struct usb_ov511 *ov)
5219 {
5220         static struct ov511_regvals aRegvalsInit511[] = {
5221                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5222                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5223                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5224                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5225                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3f },
5226                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5227                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3d },
5228                 { OV511_DONE_BUS, 0x0, 0x00},
5229         };
5230
5231         static struct ov511_regvals aRegvalsNorm511[] = {
5232                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0x01 },
5233                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5234                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5235                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5236                 { OV511_REG_BUS, R511_FIFO_OPTS,        0x1f },
5237                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5238                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5239                 { OV511_DONE_BUS, 0x0, 0x00 },
5240         };
5241
5242         static struct ov511_regvals aRegvalsNorm511Plus[] = {
5243                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0xff },
5244                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5245                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5246                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5247                 { OV511_REG_BUS, R511_FIFO_OPTS,        0xff },
5248                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5249                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5250                 { OV511_DONE_BUS, 0x0, 0x00 },
5251         };
5252
5253         PDEBUG(4, "");
5254
5255         ov->customid = reg_r(ov, R511_SYS_CUST_ID);
5256         if (ov->customid < 0) {
5257                 err("Unable to read camera bridge registers");
5258                 goto error;
5259         }
5260
5261         PDEBUG (1, "CustomID = %d", ov->customid);
5262         ov->desc = symbolic(camlist, ov->customid);
5263         info("model: %s", ov->desc);
5264
5265         if (0 == strcmp(ov->desc, NOT_DEFINED_STR)) {
5266                 err("Camera type (%d) not recognized", ov->customid);
5267                 err("Please notify " EMAIL " of the name,");
5268                 err("manufacturer, model, and this number of your camera.");
5269                 err("Also include the output of the detection process.");
5270         }
5271
5272         if (ov->customid == 70)         /* USB Life TV (PAL/SECAM) */
5273                 ov->pal = 1;
5274
5275         if (write_regvals(ov, aRegvalsInit511))
5276                 goto error;
5277
5278         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5279                 ov51x_led_control(ov, 0);
5280
5281         /* The OV511+ has undocumented bits in the flow control register.
5282          * Setting it to 0xff fixes the corruption with moving objects. */
5283         if (ov->bridge == BRG_OV511) {
5284                 if (write_regvals(ov, aRegvalsNorm511))
5285                         goto error;
5286         } else if (ov->bridge == BRG_OV511PLUS) {
5287                 if (write_regvals(ov, aRegvalsNorm511Plus))
5288                         goto error;
5289         } else {
5290                 err("Invalid bridge");
5291         }
5292
5293         if (ov511_init_compression(ov))
5294                 goto error;
5295
5296         ov->packet_numbering = 1;
5297         ov511_set_packet_size(ov, 0);
5298
5299         ov->snap_enabled = snapshot;
5300
5301         /* Test for 7xx0 */
5302         PDEBUG(3, "Testing for 0V7xx0");
5303         ov->primary_i2c_slave = OV7xx0_SID;
5304         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5305                 goto error;
5306
5307         if (i2c_w(ov, 0x12, 0x80) < 0) {
5308                 /* Test for 6xx0 */
5309                 PDEBUG(3, "Testing for 0V6xx0");
5310                 ov->primary_i2c_slave = OV6xx0_SID;
5311                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5312                         goto error;
5313
5314                 if (i2c_w(ov, 0x12, 0x80) < 0) {
5315                         /* Test for 8xx0 */
5316                         PDEBUG(3, "Testing for 0V8xx0");
5317                         ov->primary_i2c_slave = OV8xx0_SID;
5318                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5319                                 goto error;
5320
5321                         if (i2c_w(ov, 0x12, 0x80) < 0) {
5322                                 /* Test for SAA7111A */
5323                                 PDEBUG(3, "Testing for SAA7111A");
5324                                 ov->primary_i2c_slave = SAA7111A_SID;
5325                                 if (ov51x_set_slave_ids(ov, SAA7111A_SID) < 0)
5326                                         goto error;
5327
5328                                 if (i2c_w(ov, 0x0d, 0x00) < 0) {
5329                                         /* Test for KS0127 */
5330                                         PDEBUG(3, "Testing for KS0127");
5331                                         ov->primary_i2c_slave = KS0127_SID;
5332                                         if (ov51x_set_slave_ids(ov, KS0127_SID) < 0)
5333                                                 goto error;
5334
5335                                         if (i2c_w(ov, 0x10, 0x00) < 0) {
5336                                                 err("Can't determine sensor slave IDs");
5337                                                 goto error;
5338                                         } else {
5339                                                 if (ks0127_configure(ov) < 0) {
5340                                                         err("Failed to configure KS0127");
5341                                                         goto error;
5342                                                 }
5343                                         }
5344                                 } else {
5345                                         if (saa7111a_configure(ov) < 0) {
5346                                                 err("Failed to configure SAA7111A");
5347                                                 goto error;
5348                                         }
5349                                 }
5350                         } else {
5351                                 err("Detected unsupported OV8xx0 sensor");
5352                                 goto error;
5353                         }
5354                 } else {
5355                         if (ov6xx0_configure(ov) < 0) {
5356                                 err("Failed to configure OV6xx0");
5357                                 goto error;
5358                         }
5359                 }
5360         } else {
5361                 if (ov7xx0_configure(ov) < 0) {
5362                         err("Failed to configure OV7xx0");
5363                         goto error;
5364                 }
5365         }
5366
5367         return 0;
5368
5369 error:
5370         err("OV511 Config failed");
5371
5372         return -EBUSY;
5373 }
5374
5375 /* This initializes the OV518/OV518+ and the sensor */
5376 static int
5377 ov518_configure(struct usb_ov511 *ov)
5378 {
5379         /* For 518 and 518+ */
5380         static struct ov511_regvals aRegvalsInit518[] = {
5381                 { OV511_REG_BUS, R51x_SYS_RESET,        0x40 },
5382                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5383                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3e },
5384                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5385                 { OV511_REG_BUS, R51x_SYS_RESET,        0x00 },
5386                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5387                 { OV511_REG_BUS, 0x46,                  0x00 },
5388                 { OV511_REG_BUS, 0x5d,                  0x03 },
5389                 { OV511_DONE_BUS, 0x0, 0x00},
5390         };
5391
5392         static struct ov511_regvals aRegvalsNorm518[] = {
5393                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5394                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5395                 { OV511_REG_BUS, 0x31,                  0x0f },
5396                 { OV511_REG_BUS, 0x5d,                  0x03 },
5397                 { OV511_REG_BUS, 0x24,                  0x9f },
5398                 { OV511_REG_BUS, 0x25,                  0x90 },
5399                 { OV511_REG_BUS, 0x20,                  0x00 },
5400                 { OV511_REG_BUS, 0x51,                  0x04 },
5401                 { OV511_REG_BUS, 0x71,                  0x19 },
5402                 { OV511_DONE_BUS, 0x0, 0x00 },
5403         };
5404
5405         static struct ov511_regvals aRegvalsNorm518Plus[] = {
5406                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5407                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5408                 { OV511_REG_BUS, 0x31,                  0x0f },
5409                 { OV511_REG_BUS, 0x5d,                  0x03 },
5410                 { OV511_REG_BUS, 0x24,                  0x9f },
5411                 { OV511_REG_BUS, 0x25,                  0x90 },
5412                 { OV511_REG_BUS, 0x20,                  0x60 },
5413                 { OV511_REG_BUS, 0x51,                  0x02 },
5414                 { OV511_REG_BUS, 0x71,                  0x19 },
5415                 { OV511_REG_BUS, 0x40,                  0xff },
5416                 { OV511_REG_BUS, 0x41,                  0x42 },
5417                 { OV511_REG_BUS, 0x46,                  0x00 },
5418                 { OV511_REG_BUS, 0x33,                  0x04 },
5419                 { OV511_REG_BUS, 0x21,                  0x19 },
5420                 { OV511_REG_BUS, 0x3f,                  0x10 },
5421                 { OV511_DONE_BUS, 0x0, 0x00 },
5422         };
5423
5424         PDEBUG(4, "");
5425
5426         /* First 5 bits of custom ID reg are a revision ID on OV518 */
5427         info("Device revision %d", 0x1F & reg_r(ov, R511_SYS_CUST_ID));
5428
5429         /* Give it the default description */
5430         ov->desc = symbolic(camlist, 0);
5431
5432         if (write_regvals(ov, aRegvalsInit518))
5433                 goto error;
5434
5435         /* Set LED GPIO pin to output mode */
5436         if (reg_w_mask(ov, 0x57, 0x00, 0x02) < 0)
5437                 goto error;
5438
5439         /* LED is off by default with OV518; have to explicitly turn it on */
5440         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5441                 ov51x_led_control(ov, 0);
5442         else
5443                 ov51x_led_control(ov, 1);
5444
5445         /* Don't require compression if dumppix is enabled; otherwise it's
5446          * required. OV518 has no uncompressed mode, to save RAM. */
5447         if (!dumppix && !ov->compress) {
5448                 ov->compress = 1;
5449                 warn("Compression required with OV518...enabling");
5450         }
5451
5452         if (ov->bridge == BRG_OV518) {
5453                 if (write_regvals(ov, aRegvalsNorm518))
5454                         goto error;
5455         } else if (ov->bridge == BRG_OV518PLUS) {
5456                 if (write_regvals(ov, aRegvalsNorm518Plus))
5457                         goto error;
5458         } else {
5459                 err("Invalid bridge");
5460         }
5461
5462         if (reg_w(ov, 0x2f, 0x80) < 0)
5463                 goto error;
5464
5465         if (ov518_init_compression(ov))
5466                 goto error;
5467
5468         if (ov->bridge == BRG_OV518)
5469         {
5470                 struct usb_interface *ifp;
5471                 struct usb_host_interface *alt;
5472                 __u16 mxps = 0;
5473
5474                 ifp = usb_ifnum_to_if(ov->dev, 0);
5475                 if (ifp) {
5476                         alt = usb_altnum_to_altsetting(ifp, 7);
5477                         if (alt)
5478                                 mxps = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
5479                 }
5480
5481                 /* Some OV518s have packet numbering by default, some don't */
5482                 if (mxps == 897)
5483                         ov->packet_numbering = 1;
5484                 else
5485                         ov->packet_numbering = 0;
5486         } else {
5487                 /* OV518+ has packet numbering turned on by default */
5488                 ov->packet_numbering = 1;
5489         }
5490
5491         ov518_set_packet_size(ov, 0);
5492
5493         ov->snap_enabled = snapshot;
5494
5495         /* Test for 76xx */
5496         ov->primary_i2c_slave = OV7xx0_SID;
5497         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5498                 goto error;
5499
5500         /* The OV518 must be more aggressive about sensor detection since
5501          * I2C write will never fail if the sensor is not present. We have
5502          * to try to initialize the sensor to detect its presence */
5503
5504         if (init_ov_sensor(ov) < 0) {
5505                 /* Test for 6xx0 */
5506                 ov->primary_i2c_slave = OV6xx0_SID;
5507                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5508                         goto error;
5509
5510                 if (init_ov_sensor(ov) < 0) {
5511                         /* Test for 8xx0 */
5512                         ov->primary_i2c_slave = OV8xx0_SID;
5513                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5514                                 goto error;
5515
5516                         if (init_ov_sensor(ov) < 0) {
5517                                 err("Can't determine sensor slave IDs");
5518                                 goto error;
5519                         } else {
5520                                 err("Detected unsupported OV8xx0 sensor");
5521                                 goto error;
5522                         }
5523                 } else {
5524                         if (ov6xx0_configure(ov) < 0) {
5525                                 err("Failed to configure OV6xx0");
5526                                 goto error;
5527                         }
5528                 }
5529         } else {
5530                 if (ov7xx0_configure(ov) < 0) {
5531                         err("Failed to configure OV7xx0");
5532                         goto error;
5533                 }
5534         }
5535
5536         ov->maxwidth = 352;
5537         ov->maxheight = 288;
5538
5539         // The OV518 cannot go as low as the sensor can
5540         ov->minwidth = 160;
5541         ov->minheight = 120;
5542
5543         return 0;
5544
5545 error:
5546         err("OV518 Config failed");
5547
5548         return -EBUSY;
5549 }
5550
5551 /****************************************************************************
5552  *  sysfs
5553  ***************************************************************************/
5554
5555 static inline struct usb_ov511 *cd_to_ov(struct device *cd)
5556 {
5557         struct video_device *vdev = to_video_device(cd);
5558         return video_get_drvdata(vdev);
5559 }
5560
5561 static ssize_t show_custom_id(struct device *cd,
5562                               struct device_attribute *attr, char *buf)
5563 {
5564         struct usb_ov511 *ov = cd_to_ov(cd);
5565         return sprintf(buf, "%d\n", ov->customid);
5566 }
5567 static DEVICE_ATTR(custom_id, S_IRUGO, show_custom_id, NULL);
5568
5569 static ssize_t show_model(struct device *cd,
5570                           struct device_attribute *attr, char *buf)
5571 {
5572         struct usb_ov511 *ov = cd_to_ov(cd);
5573         return sprintf(buf, "%s\n", ov->desc);
5574 }
5575 static DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
5576
5577 static ssize_t show_bridge(struct device *cd,
5578                            struct device_attribute *attr, char *buf)
5579 {
5580         struct usb_ov511 *ov = cd_to_ov(cd);
5581         return sprintf(buf, "%s\n", symbolic(brglist, ov->bridge));
5582 }
5583 static DEVICE_ATTR(bridge, S_IRUGO, show_bridge, NULL);
5584
5585 static ssize_t show_sensor(struct device *cd,
5586                            struct device_attribute *attr, char *buf)
5587 {
5588         struct usb_ov511 *ov = cd_to_ov(cd);
5589         return sprintf(buf, "%s\n", symbolic(senlist, ov->sensor));
5590 }
5591 static DEVICE_ATTR(sensor, S_IRUGO, show_sensor, NULL);
5592
5593 static ssize_t show_brightness(struct device *cd,
5594                                struct device_attribute *attr, char *buf)
5595 {
5596         struct usb_ov511 *ov = cd_to_ov(cd);
5597         unsigned short x;
5598
5599         if (!ov->dev)
5600                 return -ENODEV;
5601         sensor_get_brightness(ov, &x);
5602         return sprintf(buf, "%d\n", x >> 8);
5603 }
5604 static DEVICE_ATTR(brightness, S_IRUGO, show_brightness, NULL);
5605
5606 static ssize_t show_saturation(struct device *cd,
5607                                struct device_attribute *attr, char *buf)
5608 {
5609         struct usb_ov511 *ov = cd_to_ov(cd);
5610         unsigned short x;
5611
5612         if (!ov->dev)
5613                 return -ENODEV;
5614         sensor_get_saturation(ov, &x);
5615         return sprintf(buf, "%d\n", x >> 8);
5616 }
5617 static DEVICE_ATTR(saturation, S_IRUGO, show_saturation, NULL);
5618
5619 static ssize_t show_contrast(struct device *cd,
5620                              struct device_attribute *attr, char *buf)
5621 {
5622         struct usb_ov511 *ov = cd_to_ov(cd);
5623         unsigned short x;
5624
5625         if (!ov->dev)
5626                 return -ENODEV;
5627         sensor_get_contrast(ov, &x);
5628         return sprintf(buf, "%d\n", x >> 8);
5629 }
5630 static DEVICE_ATTR(contrast, S_IRUGO, show_contrast, NULL);
5631
5632 static ssize_t show_hue(struct device *cd,
5633                         struct device_attribute *attr, char *buf)
5634 {
5635         struct usb_ov511 *ov = cd_to_ov(cd);
5636         unsigned short x;
5637
5638         if (!ov->dev)
5639                 return -ENODEV;
5640         sensor_get_hue(ov, &x);
5641         return sprintf(buf, "%d\n", x >> 8);
5642 }
5643 static DEVICE_ATTR(hue, S_IRUGO, show_hue, NULL);
5644
5645 static ssize_t show_exposure(struct device *cd,
5646                              struct device_attribute *attr, char *buf)
5647 {
5648         struct usb_ov511 *ov = cd_to_ov(cd);
5649         unsigned char exp = 0;
5650
5651         if (!ov->dev)
5652                 return -ENODEV;
5653         sensor_get_exposure(ov, &exp);
5654         return sprintf(buf, "%d\n", exp >> 8);
5655 }
5656 static DEVICE_ATTR(exposure, S_IRUGO, show_exposure, NULL);
5657
5658 static int ov_create_sysfs(struct video_device *vdev)
5659 {
5660         int rc;
5661
5662         rc = device_create_file(&vdev->dev, &dev_attr_custom_id);
5663         if (rc) goto err;
5664         rc = device_create_file(&vdev->dev, &dev_attr_model);
5665         if (rc) goto err_id;
5666         rc = device_create_file(&vdev->dev, &dev_attr_bridge);
5667         if (rc) goto err_model;
5668         rc = device_create_file(&vdev->dev, &dev_attr_sensor);
5669         if (rc) goto err_bridge;
5670         rc = device_create_file(&vdev->dev, &dev_attr_brightness);
5671         if (rc) goto err_sensor;
5672         rc = device_create_file(&vdev->dev, &dev_attr_saturation);
5673         if (rc) goto err_bright;
5674         rc = device_create_file(&vdev->dev, &dev_attr_contrast);
5675         if (rc) goto err_sat;
5676         rc = device_create_file(&vdev->dev, &dev_attr_hue);
5677         if (rc) goto err_contrast;
5678         rc = device_create_file(&vdev->dev, &dev_attr_exposure);
5679         if (rc) goto err_hue;
5680
5681         return 0;
5682
5683 err_hue:
5684         device_remove_file(&vdev->dev, &dev_attr_hue);
5685 err_contrast:
5686         device_remove_file(&vdev->dev, &dev_attr_contrast);
5687 err_sat:
5688         device_remove_file(&vdev->dev, &dev_attr_saturation);
5689 err_bright:
5690         device_remove_file(&vdev->dev, &dev_attr_brightness);
5691 err_sensor:
5692         device_remove_file(&vdev->dev, &dev_attr_sensor);
5693 err_bridge:
5694         device_remove_file(&vdev->dev, &dev_attr_bridge);
5695 err_model:
5696         device_remove_file(&vdev->dev, &dev_attr_model);
5697 err_id:
5698         device_remove_file(&vdev->dev, &dev_attr_custom_id);
5699 err:
5700         return rc;
5701 }
5702
5703 /****************************************************************************
5704  *  USB routines
5705  ***************************************************************************/
5706
5707 static int
5708 ov51x_probe(struct usb_interface *intf, const struct usb_device_id *id)
5709 {
5710         struct usb_device *dev = interface_to_usbdev(intf);
5711         struct usb_interface_descriptor *idesc;
5712         struct usb_ov511 *ov;
5713         int i;
5714
5715         PDEBUG(1, "probing for device...");
5716
5717         /* We don't handle multi-config cameras */
5718         if (dev->descriptor.bNumConfigurations != 1)
5719                 return -ENODEV;
5720
5721         idesc = &intf->cur_altsetting->desc;
5722
5723         if (idesc->bInterfaceClass != 0xFF)
5724                 return -ENODEV;
5725         if (idesc->bInterfaceSubClass != 0x00)
5726                 return -ENODEV;
5727
5728         if ((ov = kzalloc(sizeof(*ov), GFP_KERNEL)) == NULL) {
5729                 err("couldn't kmalloc ov struct");
5730                 goto error_out;
5731         }
5732
5733         ov->dev = dev;
5734         ov->iface = idesc->bInterfaceNumber;
5735         ov->led_policy = led;
5736         ov->compress = compress;
5737         ov->lightfreq = lightfreq;
5738         ov->num_inputs = 1;        /* Video decoder init functs. change this */
5739         ov->stop_during_set = !fastset;
5740         ov->backlight = backlight;
5741         ov->mirror = mirror;
5742         ov->auto_brt = autobright;
5743         ov->auto_gain = autogain;
5744         ov->auto_exp = autoexp;
5745
5746         switch (le16_to_cpu(dev->descriptor.idProduct)) {
5747         case PROD_OV511:
5748                 ov->bridge = BRG_OV511;
5749                 ov->bclass = BCL_OV511;
5750                 break;
5751         case PROD_OV511PLUS:
5752                 ov->bridge = BRG_OV511PLUS;
5753                 ov->bclass = BCL_OV511;
5754                 break;
5755         case PROD_OV518:
5756                 ov->bridge = BRG_OV518;
5757                 ov->bclass = BCL_OV518;
5758                 break;
5759         case PROD_OV518PLUS:
5760                 ov->bridge = BRG_OV518PLUS;
5761                 ov->bclass = BCL_OV518;
5762                 break;
5763         case PROD_ME2CAM:
5764                 if (le16_to_cpu(dev->descriptor.idVendor) != VEND_MATTEL)
5765                         goto error;
5766                 ov->bridge = BRG_OV511PLUS;
5767                 ov->bclass = BCL_OV511;
5768                 break;
5769         default:
5770                 err("Unknown product ID 0x%04x", le16_to_cpu(dev->descriptor.idProduct));
5771                 goto error;
5772         }
5773
5774         info("USB %s video device found", symbolic(brglist, ov->bridge));
5775
5776         init_waitqueue_head(&ov->wq);
5777
5778         mutex_init(&ov->lock);  /* to 1 == available */
5779         mutex_init(&ov->buf_lock);
5780         mutex_init(&ov->i2c_lock);
5781         mutex_init(&ov->cbuf_lock);
5782
5783         ov->buf_state = BUF_NOT_ALLOCATED;
5784
5785         if (usb_make_path(dev, ov->usb_path, OV511_USB_PATH_LEN) < 0) {
5786                 err("usb_make_path error");
5787                 goto error;
5788         }
5789
5790         /* Allocate control transfer buffer. */
5791         /* Must be kmalloc()'ed, for DMA compatibility */
5792         ov->cbuf = kmalloc(OV511_CBUF_SIZE, GFP_KERNEL);
5793         if (!ov->cbuf)
5794                 goto error;
5795
5796         if (ov->bclass == BCL_OV518) {
5797                 if (ov518_configure(ov) < 0)
5798                         goto error;
5799         } else {
5800                 if (ov511_configure(ov) < 0)
5801                         goto error;
5802         }
5803
5804         for (i = 0; i < OV511_NUMFRAMES; i++) {
5805                 ov->frame[i].framenum = i;
5806                 init_waitqueue_head(&ov->frame[i].wq);
5807         }
5808
5809         for (i = 0; i < OV511_NUMSBUF; i++) {
5810                 ov->sbuf[i].ov = ov;
5811                 spin_lock_init(&ov->sbuf[i].lock);
5812                 ov->sbuf[i].n = i;
5813         }
5814
5815         /* Unnecessary? (This is done on open(). Need to make sure variables
5816          * are properly initialized without this before removing it, though). */
5817         if (ov51x_set_default_params(ov) < 0)
5818                 goto error;
5819
5820 #ifdef OV511_DEBUG
5821         if (dump_bridge) {
5822                 if (ov->bclass == BCL_OV511)
5823                         ov511_dump_regs(ov);
5824                 else
5825                         ov518_dump_regs(ov);
5826         }
5827 #endif
5828
5829         ov->vdev = video_device_alloc();
5830         if (!ov->vdev)
5831                 goto error;
5832
5833         memcpy(ov->vdev, &vdev_template, sizeof(*ov->vdev));
5834         ov->vdev->parent = &intf->dev;
5835         video_set_drvdata(ov->vdev, ov);
5836
5837         for (i = 0; i < OV511_MAX_UNIT_VIDEO; i++) {
5838                 /* Minor 0 cannot be specified; assume user wants autodetect */
5839                 if (unit_video[i] == 0)
5840                         break;
5841
5842                 if (video_register_device(ov->vdev, VFL_TYPE_GRABBER,
5843                         unit_video[i]) >= 0) {
5844                         break;
5845                 }
5846         }
5847
5848         /* Use the next available one */
5849         if ((ov->vdev->minor == -1) &&
5850             video_register_device(ov->vdev, VFL_TYPE_GRABBER, -1) < 0) {
5851                 err("video_register_device failed");
5852                 goto error;
5853         }
5854
5855         info("Device at %s registered to minor %d", ov->usb_path,
5856              ov->vdev->minor);
5857
5858         usb_set_intfdata(intf, ov);
5859         if (ov_create_sysfs(ov->vdev)) {
5860                 err("ov_create_sysfs failed");
5861                 goto error;
5862         }
5863
5864         return 0;
5865
5866 error:
5867         if (ov->vdev) {
5868                 if (-1 == ov->vdev->minor)
5869                         video_device_release(ov->vdev);
5870                 else
5871                         video_unregister_device(ov->vdev);
5872                 ov->vdev = NULL;
5873         }
5874
5875         if (ov->cbuf) {
5876                 mutex_lock(&ov->cbuf_lock);
5877                 kfree(ov->cbuf);
5878                 ov->cbuf = NULL;
5879                 mutex_unlock(&ov->cbuf_lock);
5880         }
5881
5882         kfree(ov);
5883         ov = NULL;
5884
5885 error_out:
5886         err("Camera initialization failed");
5887         return -EIO;
5888 }
5889
5890 static void
5891 ov51x_disconnect(struct usb_interface *intf)
5892 {
5893         struct usb_ov511 *ov = usb_get_intfdata(intf);
5894         int n;
5895
5896         PDEBUG(3, "");
5897
5898         usb_set_intfdata (intf, NULL);
5899
5900         if (!ov)
5901                 return;
5902
5903         if (ov->vdev)
5904                 video_unregister_device(ov->vdev);
5905
5906         for (n = 0; n < OV511_NUMFRAMES; n++)
5907                 ov->frame[n].grabstate = FRAME_ERROR;
5908
5909         ov->curframe = -1;
5910
5911         /* This will cause the process to request another frame */
5912         for (n = 0; n < OV511_NUMFRAMES; n++)
5913                 wake_up_interruptible(&ov->frame[n].wq);
5914
5915         wake_up_interruptible(&ov->wq);
5916
5917         ov->streaming = 0;
5918         ov51x_unlink_isoc(ov);
5919
5920         ov->dev = NULL;
5921
5922         /* Free the memory */
5923         if (ov && !ov->user) {
5924                 mutex_lock(&ov->cbuf_lock);
5925                 kfree(ov->cbuf);
5926                 ov->cbuf = NULL;
5927                 mutex_unlock(&ov->cbuf_lock);
5928
5929                 ov51x_dealloc(ov);
5930                 kfree(ov);
5931                 ov = NULL;
5932         }
5933
5934         PDEBUG(3, "Disconnect complete");
5935 }
5936
5937 static struct usb_driver ov511_driver = {
5938         .name =         "ov511",
5939         .id_table =     device_table,
5940         .probe =        ov51x_probe,
5941         .disconnect =   ov51x_disconnect
5942 };
5943
5944 /****************************************************************************
5945  *
5946  *  Module routines
5947  *
5948  ***************************************************************************/
5949
5950 static int __init
5951 usb_ov511_init(void)
5952 {
5953         int retval;
5954
5955         retval = usb_register(&ov511_driver);
5956         if (retval)
5957                 goto out;
5958
5959         info(DRIVER_VERSION " : " DRIVER_DESC);
5960
5961 out:
5962         return retval;
5963 }
5964
5965 static void __exit
5966 usb_ov511_exit(void)
5967 {
5968         usb_deregister(&ov511_driver);
5969         info("driver deregistered");
5970
5971 }
5972
5973 module_init(usb_ov511_init);
5974 module_exit(usb_ov511_exit);
5975