V4L/DVB (7402): add macro validation for v4l_compat_ioctl32
[safe/jmp/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         .owner =        THIS_MODULE,
4670         .name =         "OV511 USB Camera",
4671         .type =         VID_TYPE_CAPTURE,
4672         .fops =         &ov511_fops,
4673         .release =      video_device_release,
4674         .minor =        -1,
4675 };
4676
4677 /****************************************************************************
4678  *
4679  * OV511 and sensor configuration
4680  *
4681  ***************************************************************************/
4682
4683 /* This initializes the OV7610, OV7620, or OV76BE sensor. The OV76BE uses
4684  * the same register settings as the OV7610, since they are very similar.
4685  */
4686 static int
4687 ov7xx0_configure(struct usb_ov511 *ov)
4688 {
4689         int i, success;
4690         int rc;
4691
4692         /* Lawrence Glaister <lg@jfm.bc.ca> reports:
4693          *
4694          * Register 0x0f in the 7610 has the following effects:
4695          *
4696          * 0x85 (AEC method 1): Best overall, good contrast range
4697          * 0x45 (AEC method 2): Very overexposed
4698          * 0xa5 (spec sheet default): Ok, but the black level is
4699          *      shifted resulting in loss of contrast
4700          * 0x05 (old driver setting): very overexposed, too much
4701          *      contrast
4702          */
4703         static struct ov511_regvals aRegvalsNorm7610[] = {
4704                 { OV511_I2C_BUS, 0x10, 0xff },
4705                 { OV511_I2C_BUS, 0x16, 0x06 },
4706                 { OV511_I2C_BUS, 0x28, 0x24 },
4707                 { OV511_I2C_BUS, 0x2b, 0xac },
4708                 { OV511_I2C_BUS, 0x12, 0x00 },
4709                 { OV511_I2C_BUS, 0x38, 0x81 },
4710                 { OV511_I2C_BUS, 0x28, 0x24 },  /* 0c */
4711                 { OV511_I2C_BUS, 0x0f, 0x85 },  /* lg's setting */
4712                 { OV511_I2C_BUS, 0x15, 0x01 },
4713                 { OV511_I2C_BUS, 0x20, 0x1c },
4714                 { OV511_I2C_BUS, 0x23, 0x2a },
4715                 { OV511_I2C_BUS, 0x24, 0x10 },
4716                 { OV511_I2C_BUS, 0x25, 0x8a },
4717                 { OV511_I2C_BUS, 0x26, 0xa2 },
4718                 { OV511_I2C_BUS, 0x27, 0xc2 },
4719                 { OV511_I2C_BUS, 0x2a, 0x04 },
4720                 { OV511_I2C_BUS, 0x2c, 0xfe },
4721                 { OV511_I2C_BUS, 0x2d, 0x93 },
4722                 { OV511_I2C_BUS, 0x30, 0x71 },
4723                 { OV511_I2C_BUS, 0x31, 0x60 },
4724                 { OV511_I2C_BUS, 0x32, 0x26 },
4725                 { OV511_I2C_BUS, 0x33, 0x20 },
4726                 { OV511_I2C_BUS, 0x34, 0x48 },
4727                 { OV511_I2C_BUS, 0x12, 0x24 },
4728                 { OV511_I2C_BUS, 0x11, 0x01 },
4729                 { OV511_I2C_BUS, 0x0c, 0x24 },
4730                 { OV511_I2C_BUS, 0x0d, 0x24 },
4731                 { OV511_DONE_BUS, 0x0, 0x00 },
4732         };
4733
4734         static struct ov511_regvals aRegvalsNorm7620[] = {
4735                 { OV511_I2C_BUS, 0x00, 0x00 },
4736                 { OV511_I2C_BUS, 0x01, 0x80 },
4737                 { OV511_I2C_BUS, 0x02, 0x80 },
4738                 { OV511_I2C_BUS, 0x03, 0xc0 },
4739                 { OV511_I2C_BUS, 0x06, 0x60 },
4740                 { OV511_I2C_BUS, 0x07, 0x00 },
4741                 { OV511_I2C_BUS, 0x0c, 0x24 },
4742                 { OV511_I2C_BUS, 0x0c, 0x24 },
4743                 { OV511_I2C_BUS, 0x0d, 0x24 },
4744                 { OV511_I2C_BUS, 0x11, 0x01 },
4745                 { OV511_I2C_BUS, 0x12, 0x24 },
4746                 { OV511_I2C_BUS, 0x13, 0x01 },
4747                 { OV511_I2C_BUS, 0x14, 0x84 },
4748                 { OV511_I2C_BUS, 0x15, 0x01 },
4749                 { OV511_I2C_BUS, 0x16, 0x03 },
4750                 { OV511_I2C_BUS, 0x17, 0x2f },
4751                 { OV511_I2C_BUS, 0x18, 0xcf },
4752                 { OV511_I2C_BUS, 0x19, 0x06 },
4753                 { OV511_I2C_BUS, 0x1a, 0xf5 },
4754                 { OV511_I2C_BUS, 0x1b, 0x00 },
4755                 { OV511_I2C_BUS, 0x20, 0x18 },
4756                 { OV511_I2C_BUS, 0x21, 0x80 },
4757                 { OV511_I2C_BUS, 0x22, 0x80 },
4758                 { OV511_I2C_BUS, 0x23, 0x00 },
4759                 { OV511_I2C_BUS, 0x26, 0xa2 },
4760                 { OV511_I2C_BUS, 0x27, 0xea },
4761                 { OV511_I2C_BUS, 0x28, 0x20 },
4762                 { OV511_I2C_BUS, 0x29, 0x00 },
4763                 { OV511_I2C_BUS, 0x2a, 0x10 },
4764                 { OV511_I2C_BUS, 0x2b, 0x00 },
4765                 { OV511_I2C_BUS, 0x2c, 0x88 },
4766                 { OV511_I2C_BUS, 0x2d, 0x91 },
4767                 { OV511_I2C_BUS, 0x2e, 0x80 },
4768                 { OV511_I2C_BUS, 0x2f, 0x44 },
4769                 { OV511_I2C_BUS, 0x60, 0x27 },
4770                 { OV511_I2C_BUS, 0x61, 0x02 },
4771                 { OV511_I2C_BUS, 0x62, 0x5f },
4772                 { OV511_I2C_BUS, 0x63, 0xd5 },
4773                 { OV511_I2C_BUS, 0x64, 0x57 },
4774                 { OV511_I2C_BUS, 0x65, 0x83 },
4775                 { OV511_I2C_BUS, 0x66, 0x55 },
4776                 { OV511_I2C_BUS, 0x67, 0x92 },
4777                 { OV511_I2C_BUS, 0x68, 0xcf },
4778                 { OV511_I2C_BUS, 0x69, 0x76 },
4779                 { OV511_I2C_BUS, 0x6a, 0x22 },
4780                 { OV511_I2C_BUS, 0x6b, 0x00 },
4781                 { OV511_I2C_BUS, 0x6c, 0x02 },
4782                 { OV511_I2C_BUS, 0x6d, 0x44 },
4783                 { OV511_I2C_BUS, 0x6e, 0x80 },
4784                 { OV511_I2C_BUS, 0x6f, 0x1d },
4785                 { OV511_I2C_BUS, 0x70, 0x8b },
4786                 { OV511_I2C_BUS, 0x71, 0x00 },
4787                 { OV511_I2C_BUS, 0x72, 0x14 },
4788                 { OV511_I2C_BUS, 0x73, 0x54 },
4789                 { OV511_I2C_BUS, 0x74, 0x00 },
4790                 { OV511_I2C_BUS, 0x75, 0x8e },
4791                 { OV511_I2C_BUS, 0x76, 0x00 },
4792                 { OV511_I2C_BUS, 0x77, 0xff },
4793                 { OV511_I2C_BUS, 0x78, 0x80 },
4794                 { OV511_I2C_BUS, 0x79, 0x80 },
4795                 { OV511_I2C_BUS, 0x7a, 0x80 },
4796                 { OV511_I2C_BUS, 0x7b, 0xe2 },
4797                 { OV511_I2C_BUS, 0x7c, 0x00 },
4798                 { OV511_DONE_BUS, 0x0, 0x00 },
4799         };
4800
4801         PDEBUG(4, "starting configuration");
4802
4803         /* This looks redundant, but is necessary for WebCam 3 */
4804         ov->primary_i2c_slave = OV7xx0_SID;
4805         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
4806                 return -1;
4807
4808         if (init_ov_sensor(ov) >= 0) {
4809                 PDEBUG(1, "OV7xx0 sensor initalized (method 1)");
4810         } else {
4811                 /* Reset the 76xx */
4812                 if (i2c_w(ov, 0x12, 0x80) < 0)
4813                         return -1;
4814
4815                 /* Wait for it to initialize */
4816                 msleep(150);
4817
4818                 i = 0;
4819                 success = 0;
4820                 while (i <= i2c_detect_tries) {
4821                         if ((i2c_r(ov, OV7610_REG_ID_HIGH) == 0x7F) &&
4822                             (i2c_r(ov, OV7610_REG_ID_LOW) == 0xA2)) {
4823                                 success = 1;
4824                                 break;
4825                         } else {
4826                                 i++;
4827                         }
4828                 }
4829
4830 // Was (i == i2c_detect_tries) previously. This obviously used to always report
4831 // success. Whether anyone actually depended on that bug is unknown
4832                 if ((i >= i2c_detect_tries) && (success == 0)) {
4833                         err("Failed to read sensor ID. You might not have an");
4834                         err("OV7610/20, or it may be not responding. Report");
4835                         err("this to " EMAIL);
4836                         err("This is only a warning. You can attempt to use");
4837                         err("your camera anyway");
4838 // Only issue a warning for now
4839 //                      return -1;
4840                 } else {
4841                         PDEBUG(1, "OV7xx0 initialized (method 2, %dx)", i+1);
4842                 }
4843         }
4844
4845         /* Detect sensor (sub)type */
4846         rc = i2c_r(ov, OV7610_REG_COM_I);
4847
4848         if (rc < 0) {
4849                 err("Error detecting sensor type");
4850                 return -1;
4851         } else if ((rc & 3) == 3) {
4852                 info("Sensor is an OV7610");
4853                 ov->sensor = SEN_OV7610;
4854         } else if ((rc & 3) == 1) {
4855                 /* I don't know what's different about the 76BE yet. */
4856                 if (i2c_r(ov, 0x15) & 1)
4857                         info("Sensor is an OV7620AE");
4858                 else
4859                         info("Sensor is an OV76BE");
4860
4861                 /* OV511+ will return all zero isoc data unless we
4862                  * configure the sensor as a 7620. Someone needs to
4863                  * find the exact reg. setting that causes this. */
4864                 if (ov->bridge == BRG_OV511PLUS) {
4865                         info("Enabling 511+/7620AE workaround");
4866                         ov->sensor = SEN_OV7620;
4867                 } else {
4868                         ov->sensor = SEN_OV76BE;
4869                 }
4870         } else if ((rc & 3) == 0) {
4871                 info("Sensor is an OV7620");
4872                 ov->sensor = SEN_OV7620;
4873         } else {
4874                 err("Unknown image sensor version: %d", rc & 3);
4875                 return -1;
4876         }
4877
4878         if (ov->sensor == SEN_OV7620) {
4879                 PDEBUG(4, "Writing 7620 registers");
4880                 if (write_regvals(ov, aRegvalsNorm7620))
4881                         return -1;
4882         } else {
4883                 PDEBUG(4, "Writing 7610 registers");
4884                 if (write_regvals(ov, aRegvalsNorm7610))
4885                         return -1;
4886         }
4887
4888         /* Set sensor-specific vars */
4889         ov->maxwidth = 640;
4890         ov->maxheight = 480;
4891         ov->minwidth = 64;
4892         ov->minheight = 48;
4893
4894         // FIXME: These do not match the actual settings yet
4895         ov->brightness = 0x80 << 8;
4896         ov->contrast = 0x80 << 8;
4897         ov->colour = 0x80 << 8;
4898         ov->hue = 0x80 << 8;
4899
4900         return 0;
4901 }
4902
4903 /* This initializes the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
4904 static int
4905 ov6xx0_configure(struct usb_ov511 *ov)
4906 {
4907         int rc;
4908
4909         static struct ov511_regvals aRegvalsNorm6x20[] = {
4910                 { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4911                 { OV511_I2C_BUS, 0x11, 0x01 },
4912                 { OV511_I2C_BUS, 0x03, 0x60 },
4913                 { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4914                 { OV511_I2C_BUS, 0x07, 0xa8 },
4915                 /* The ratio of 0x0c and 0x0d  controls the white point */
4916                 { OV511_I2C_BUS, 0x0c, 0x24 },
4917                 { OV511_I2C_BUS, 0x0d, 0x24 },
4918                 { OV511_I2C_BUS, 0x0f, 0x15 }, /* COMS */
4919                 { OV511_I2C_BUS, 0x10, 0x75 }, /* AEC Exposure time */
4920                 { OV511_I2C_BUS, 0x12, 0x24 }, /* Enable AGC */
4921                 { OV511_I2C_BUS, 0x14, 0x04 },
4922                 /* 0x16: 0x06 helps frame stability with moving objects */
4923                 { OV511_I2C_BUS, 0x16, 0x06 },
4924 //              { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4925                 { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4926                 /* 0x28: 0x05 Selects RGB format if RGB on */
4927                 { OV511_I2C_BUS, 0x28, 0x05 },
4928                 { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4929 //              { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4930                 { OV511_I2C_BUS, 0x2d, 0x99 },
4931                 { OV511_I2C_BUS, 0x33, 0xa0 }, /* Color Processing Parameter */
4932                 { OV511_I2C_BUS, 0x34, 0xd2 }, /* Max A/D range */
4933                 { OV511_I2C_BUS, 0x38, 0x8b },
4934                 { OV511_I2C_BUS, 0x39, 0x40 },
4935
4936                 { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4937                 { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4938                 { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4939
4940                 { OV511_I2C_BUS, 0x3d, 0x80 },
4941                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4942                  * control the color balance */
4943                 { OV511_I2C_BUS, 0x4a, 0x80 },
4944                 { OV511_I2C_BUS, 0x4b, 0x80 },
4945                 { OV511_I2C_BUS, 0x4d, 0xd2 }, /* This reduces noise a bit */
4946                 { OV511_I2C_BUS, 0x4e, 0xc1 },
4947                 { OV511_I2C_BUS, 0x4f, 0x04 },
4948 // Do 50-53 have any effect?
4949 // Toggle 0x12[2] off and on here?
4950                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
4951         };
4952
4953         static struct ov511_regvals aRegvalsNorm6x30[] = {
4954         /*OK*/  { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4955                 { OV511_I2C_BUS, 0x11, 0x00 },
4956         /*OK*/  { OV511_I2C_BUS, 0x03, 0x60 },
4957         /*0A?*/ { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4958                 { OV511_I2C_BUS, 0x07, 0xa8 },
4959                 /* The ratio of 0x0c and 0x0d  controls the white point */
4960         /*OK*/  { OV511_I2C_BUS, 0x0c, 0x24 },
4961         /*OK*/  { OV511_I2C_BUS, 0x0d, 0x24 },
4962         /*A*/   { OV511_I2C_BUS, 0x0e, 0x20 },
4963 //      /*04?*/ { OV511_I2C_BUS, 0x14, 0x80 },
4964                 { OV511_I2C_BUS, 0x16, 0x03 },
4965 //      /*OK*/  { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4966                 // 21 & 22? The suggested values look wrong. Go with default
4967         /*A*/   { OV511_I2C_BUS, 0x23, 0xc0 },
4968         /*A*/   { OV511_I2C_BUS, 0x25, 0x9a }, // Check this against default
4969 //      /*OK*/  { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4970
4971                 /* 0x28: 0x05 Selects RGB format if RGB on */
4972 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x05 },
4973 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x45 }, // DEBUG: Tristate UV bus
4974
4975         /*OK*/  { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4976 //      /*OK*/  { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4977                 { OV511_I2C_BUS, 0x2d, 0x99 },
4978 //      /*A*/   { OV511_I2C_BUS, 0x33, 0x26 }, // Reserved bits on 6620
4979 //      /*d2?*/ { OV511_I2C_BUS, 0x34, 0x03 }, /* Max A/D range */
4980 //      /*8b?*/ { OV511_I2C_BUS, 0x38, 0x83 },
4981 //      /*40?*/ { OV511_I2C_BUS, 0x39, 0xc0 }, // 6630 adds bit 7
4982 //              { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4983 //              { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4984 //              { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4985                 { OV511_I2C_BUS, 0x3d, 0x80 },
4986 //      /*A*/   { OV511_I2C_BUS, 0x3f, 0x0e },
4987
4988                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4989                  * control the color balance */
4990 //      /*OK?*/ { OV511_I2C_BUS, 0x4a, 0x80 }, // Check these
4991 //      /*OK?*/ { OV511_I2C_BUS, 0x4b, 0x80 },
4992                 { OV511_I2C_BUS, 0x4d, 0x10 }, /* U = 0.563u, V = 0.714v */
4993         /*c1?*/ { OV511_I2C_BUS, 0x4e, 0x40 },
4994
4995                 /* UV average mode, color killer: strongest */
4996                 { OV511_I2C_BUS, 0x4f, 0x07 },
4997
4998                 { OV511_I2C_BUS, 0x54, 0x23 }, /* Max AGC gain: 18dB */
4999                 { OV511_I2C_BUS, 0x57, 0x81 }, /* (default) */
5000                 { OV511_I2C_BUS, 0x59, 0x01 }, /* AGC dark current comp: +1 */
5001                 { OV511_I2C_BUS, 0x5a, 0x2c }, /* (undocumented) */
5002                 { OV511_I2C_BUS, 0x5b, 0x0f }, /* AWB chrominance levels */
5003 //              { OV511_I2C_BUS, 0x5c, 0x10 },
5004                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
5005         };
5006
5007         PDEBUG(4, "starting sensor configuration");
5008
5009         if (init_ov_sensor(ov) < 0) {
5010                 err("Failed to read sensor ID. You might not have an OV6xx0,");
5011                 err("or it may be not responding. Report this to " EMAIL);
5012                 return -1;
5013         } else {
5014                 PDEBUG(1, "OV6xx0 sensor detected");
5015         }
5016
5017         /* Detect sensor (sub)type */
5018         rc = i2c_r(ov, OV7610_REG_COM_I);
5019
5020         if (rc < 0) {
5021                 err("Error detecting sensor type");
5022                 return -1;
5023         }
5024
5025         if ((rc & 3) == 0) {
5026                 ov->sensor = SEN_OV6630;
5027                 info("Sensor is an OV6630");
5028         } else if ((rc & 3) == 1) {
5029                 ov->sensor = SEN_OV6620;
5030                 info("Sensor is an OV6620");
5031         } else if ((rc & 3) == 2) {
5032                 ov->sensor = SEN_OV6630;
5033                 info("Sensor is an OV6630AE");
5034         } else if ((rc & 3) == 3) {
5035                 ov->sensor = SEN_OV6630;
5036                 info("Sensor is an OV6630AF");
5037         }
5038
5039         /* Set sensor-specific vars */
5040         ov->maxwidth = 352;
5041         ov->maxheight = 288;
5042         ov->minwidth = 64;
5043         ov->minheight = 48;
5044
5045         // FIXME: These do not match the actual settings yet
5046         ov->brightness = 0x80 << 8;
5047         ov->contrast = 0x80 << 8;
5048         ov->colour = 0x80 << 8;
5049         ov->hue = 0x80 << 8;
5050
5051         if (ov->sensor == SEN_OV6620) {
5052                 PDEBUG(4, "Writing 6x20 registers");
5053                 if (write_regvals(ov, aRegvalsNorm6x20))
5054                         return -1;
5055         } else {
5056                 PDEBUG(4, "Writing 6x30 registers");
5057                 if (write_regvals(ov, aRegvalsNorm6x30))
5058                         return -1;
5059         }
5060
5061         return 0;
5062 }
5063
5064 /* This initializes the KS0127 and KS0127B video decoders. */
5065 static int
5066 ks0127_configure(struct usb_ov511 *ov)
5067 {
5068         int rc;
5069
5070 // FIXME: I don't know how to sync or reset it yet
5071 #if 0
5072         if (ov51x_init_ks_sensor(ov) < 0) {
5073                 err("Failed to initialize the KS0127");
5074                 return -1;
5075         } else {
5076                 PDEBUG(1, "KS012x(B) sensor detected");
5077         }
5078 #endif
5079
5080         /* Detect decoder subtype */
5081         rc = i2c_r(ov, 0x00);
5082         if (rc < 0) {
5083                 err("Error detecting sensor type");
5084                 return -1;
5085         } else if (rc & 0x08) {
5086                 rc = i2c_r(ov, 0x3d);
5087                 if (rc < 0) {
5088                         err("Error detecting sensor type");
5089                         return -1;
5090                 } else if ((rc & 0x0f) == 0) {
5091                         info("Sensor is a KS0127");
5092                         ov->sensor = SEN_KS0127;
5093                 } else if ((rc & 0x0f) == 9) {
5094                         info("Sensor is a KS0127B Rev. A");
5095                         ov->sensor = SEN_KS0127B;
5096                 }
5097         } else {
5098                 err("Error: Sensor is an unsupported KS0122");
5099                 return -1;
5100         }
5101
5102         /* Set sensor-specific vars */
5103         ov->maxwidth = 640;
5104         ov->maxheight = 480;
5105         ov->minwidth = 64;
5106         ov->minheight = 48;
5107
5108         // FIXME: These do not match the actual settings yet
5109         ov->brightness = 0x80 << 8;
5110         ov->contrast = 0x80 << 8;
5111         ov->colour = 0x80 << 8;
5112         ov->hue = 0x80 << 8;
5113
5114         /* This device is not supported yet. Bail out now... */
5115         err("This sensor is not supported yet.");
5116         return -1;
5117
5118         return 0;
5119 }
5120
5121 /* This initializes the SAA7111A video decoder. */
5122 static int
5123 saa7111a_configure(struct usb_ov511 *ov)
5124 {
5125         int rc;
5126
5127         /* Since there is no register reset command, all registers must be
5128          * written, otherwise gives erratic results */
5129         static struct ov511_regvals aRegvalsNormSAA7111A[] = {
5130                 { OV511_I2C_BUS, 0x06, 0xce },
5131                 { OV511_I2C_BUS, 0x07, 0x00 },
5132                 { OV511_I2C_BUS, 0x10, 0x44 }, /* YUV422, 240/286 lines */
5133                 { OV511_I2C_BUS, 0x0e, 0x01 }, /* NTSC M or PAL BGHI */
5134                 { OV511_I2C_BUS, 0x00, 0x00 },
5135                 { OV511_I2C_BUS, 0x01, 0x00 },
5136                 { OV511_I2C_BUS, 0x03, 0x23 },
5137                 { OV511_I2C_BUS, 0x04, 0x00 },
5138                 { OV511_I2C_BUS, 0x05, 0x00 },
5139                 { OV511_I2C_BUS, 0x08, 0xc8 }, /* Auto field freq */
5140                 { OV511_I2C_BUS, 0x09, 0x01 }, /* Chrom. trap off, APER=0.25 */
5141                 { OV511_I2C_BUS, 0x0a, 0x80 }, /* BRIG=128 */
5142                 { OV511_I2C_BUS, 0x0b, 0x40 }, /* CONT=1.0 */
5143                 { OV511_I2C_BUS, 0x0c, 0x40 }, /* SATN=1.0 */
5144                 { OV511_I2C_BUS, 0x0d, 0x00 }, /* HUE=0 */
5145                 { OV511_I2C_BUS, 0x0f, 0x00 },
5146                 { OV511_I2C_BUS, 0x11, 0x0c },
5147                 { OV511_I2C_BUS, 0x12, 0x00 },
5148                 { OV511_I2C_BUS, 0x13, 0x00 },
5149                 { OV511_I2C_BUS, 0x14, 0x00 },
5150                 { OV511_I2C_BUS, 0x15, 0x00 },
5151                 { OV511_I2C_BUS, 0x16, 0x00 },
5152                 { OV511_I2C_BUS, 0x17, 0x00 },
5153                 { OV511_I2C_BUS, 0x02, 0xc0 },  /* Composite input 0 */
5154                 { OV511_DONE_BUS, 0x0, 0x00 },
5155         };
5156
5157 // FIXME: I don't know how to sync or reset it yet
5158 #if 0
5159         if (ov51x_init_saa_sensor(ov) < 0) {
5160                 err("Failed to initialize the SAA7111A");
5161                 return -1;
5162         } else {
5163                 PDEBUG(1, "SAA7111A sensor detected");
5164         }
5165 #endif
5166
5167         /* 640x480 not supported with PAL */
5168         if (ov->pal) {
5169                 ov->maxwidth = 320;
5170                 ov->maxheight = 240;            /* Even field only */
5171         } else {
5172                 ov->maxwidth = 640;
5173                 ov->maxheight = 480;            /* Even/Odd fields */
5174         }
5175
5176         ov->minwidth = 320;
5177         ov->minheight = 240;            /* Even field only */
5178
5179         ov->has_decoder = 1;
5180         ov->num_inputs = 8;
5181         ov->norm = VIDEO_MODE_AUTO;
5182         ov->stop_during_set = 0;        /* Decoder guarantees stable image */
5183
5184         /* Decoder doesn't change these values, so we use these instead of
5185          * acutally reading the registers (which doesn't work) */
5186         ov->brightness = 0x80 << 8;
5187         ov->contrast = 0x40 << 9;
5188         ov->colour = 0x40 << 9;
5189         ov->hue = 32768;
5190
5191         PDEBUG(4, "Writing SAA7111A registers");
5192         if (write_regvals(ov, aRegvalsNormSAA7111A))
5193                 return -1;
5194
5195         /* Detect version of decoder. This must be done after writing the
5196          * initial regs or the decoder will lock up. */
5197         rc = i2c_r(ov, 0x00);
5198
5199         if (rc < 0) {
5200                 err("Error detecting sensor version");
5201                 return -1;
5202         } else {
5203                 info("Sensor is an SAA7111A (version 0x%x)", rc);
5204                 ov->sensor = SEN_SAA7111A;
5205         }
5206
5207         // FIXME: Fix this for OV518(+)
5208         /* Latch to negative edge of clock. Otherwise, we get incorrect
5209          * colors and jitter in the digital signal. */
5210         if (ov->bclass == BCL_OV511)
5211                 reg_w(ov, 0x11, 0x00);
5212         else
5213                 warn("SAA7111A not yet supported with OV518/OV518+");
5214
5215         return 0;
5216 }
5217
5218 /* This initializes the OV511/OV511+ and the sensor */
5219 static int
5220 ov511_configure(struct usb_ov511 *ov)
5221 {
5222         static struct ov511_regvals aRegvalsInit511[] = {
5223                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5224                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5225                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5226                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5227                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3f },
5228                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5229                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3d },
5230                 { OV511_DONE_BUS, 0x0, 0x00},
5231         };
5232
5233         static struct ov511_regvals aRegvalsNorm511[] = {
5234                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0x01 },
5235                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5236                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5237                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5238                 { OV511_REG_BUS, R511_FIFO_OPTS,        0x1f },
5239                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5240                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5241                 { OV511_DONE_BUS, 0x0, 0x00 },
5242         };
5243
5244         static struct ov511_regvals aRegvalsNorm511Plus[] = {
5245                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0xff },
5246                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5247                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5248                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5249                 { OV511_REG_BUS, R511_FIFO_OPTS,        0xff },
5250                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5251                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5252                 { OV511_DONE_BUS, 0x0, 0x00 },
5253         };
5254
5255         PDEBUG(4, "");
5256
5257         ov->customid = reg_r(ov, R511_SYS_CUST_ID);
5258         if (ov->customid < 0) {
5259                 err("Unable to read camera bridge registers");
5260                 goto error;
5261         }
5262
5263         PDEBUG (1, "CustomID = %d", ov->customid);
5264         ov->desc = symbolic(camlist, ov->customid);
5265         info("model: %s", ov->desc);
5266
5267         if (0 == strcmp(ov->desc, NOT_DEFINED_STR)) {
5268                 err("Camera type (%d) not recognized", ov->customid);
5269                 err("Please notify " EMAIL " of the name,");
5270                 err("manufacturer, model, and this number of your camera.");
5271                 err("Also include the output of the detection process.");
5272         }
5273
5274         if (ov->customid == 70)         /* USB Life TV (PAL/SECAM) */
5275                 ov->pal = 1;
5276
5277         if (write_regvals(ov, aRegvalsInit511))
5278                 goto error;
5279
5280         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5281                 ov51x_led_control(ov, 0);
5282
5283         /* The OV511+ has undocumented bits in the flow control register.
5284          * Setting it to 0xff fixes the corruption with moving objects. */
5285         if (ov->bridge == BRG_OV511) {
5286                 if (write_regvals(ov, aRegvalsNorm511))
5287                         goto error;
5288         } else if (ov->bridge == BRG_OV511PLUS) {
5289                 if (write_regvals(ov, aRegvalsNorm511Plus))
5290                         goto error;
5291         } else {
5292                 err("Invalid bridge");
5293         }
5294
5295         if (ov511_init_compression(ov))
5296                 goto error;
5297
5298         ov->packet_numbering = 1;
5299         ov511_set_packet_size(ov, 0);
5300
5301         ov->snap_enabled = snapshot;
5302
5303         /* Test for 7xx0 */
5304         PDEBUG(3, "Testing for 0V7xx0");
5305         ov->primary_i2c_slave = OV7xx0_SID;
5306         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5307                 goto error;
5308
5309         if (i2c_w(ov, 0x12, 0x80) < 0) {
5310                 /* Test for 6xx0 */
5311                 PDEBUG(3, "Testing for 0V6xx0");
5312                 ov->primary_i2c_slave = OV6xx0_SID;
5313                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5314                         goto error;
5315
5316                 if (i2c_w(ov, 0x12, 0x80) < 0) {
5317                         /* Test for 8xx0 */
5318                         PDEBUG(3, "Testing for 0V8xx0");
5319                         ov->primary_i2c_slave = OV8xx0_SID;
5320                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5321                                 goto error;
5322
5323                         if (i2c_w(ov, 0x12, 0x80) < 0) {
5324                                 /* Test for SAA7111A */
5325                                 PDEBUG(3, "Testing for SAA7111A");
5326                                 ov->primary_i2c_slave = SAA7111A_SID;
5327                                 if (ov51x_set_slave_ids(ov, SAA7111A_SID) < 0)
5328                                         goto error;
5329
5330                                 if (i2c_w(ov, 0x0d, 0x00) < 0) {
5331                                         /* Test for KS0127 */
5332                                         PDEBUG(3, "Testing for KS0127");
5333                                         ov->primary_i2c_slave = KS0127_SID;
5334                                         if (ov51x_set_slave_ids(ov, KS0127_SID) < 0)
5335                                                 goto error;
5336
5337                                         if (i2c_w(ov, 0x10, 0x00) < 0) {
5338                                                 err("Can't determine sensor slave IDs");
5339                                                 goto error;
5340                                         } else {
5341                                                 if (ks0127_configure(ov) < 0) {
5342                                                         err("Failed to configure KS0127");
5343                                                         goto error;
5344                                                 }
5345                                         }
5346                                 } else {
5347                                         if (saa7111a_configure(ov) < 0) {
5348                                                 err("Failed to configure SAA7111A");
5349                                                 goto error;
5350                                         }
5351                                 }
5352                         } else {
5353                                 err("Detected unsupported OV8xx0 sensor");
5354                                 goto error;
5355                         }
5356                 } else {
5357                         if (ov6xx0_configure(ov) < 0) {
5358                                 err("Failed to configure OV6xx0");
5359                                 goto error;
5360                         }
5361                 }
5362         } else {
5363                 if (ov7xx0_configure(ov) < 0) {
5364                         err("Failed to configure OV7xx0");
5365                         goto error;
5366                 }
5367         }
5368
5369         return 0;
5370
5371 error:
5372         err("OV511 Config failed");
5373
5374         return -EBUSY;
5375 }
5376
5377 /* This initializes the OV518/OV518+ and the sensor */
5378 static int
5379 ov518_configure(struct usb_ov511 *ov)
5380 {
5381         /* For 518 and 518+ */
5382         static struct ov511_regvals aRegvalsInit518[] = {
5383                 { OV511_REG_BUS, R51x_SYS_RESET,        0x40 },
5384                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5385                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3e },
5386                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5387                 { OV511_REG_BUS, R51x_SYS_RESET,        0x00 },
5388                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5389                 { OV511_REG_BUS, 0x46,                  0x00 },
5390                 { OV511_REG_BUS, 0x5d,                  0x03 },
5391                 { OV511_DONE_BUS, 0x0, 0x00},
5392         };
5393
5394         static struct ov511_regvals aRegvalsNorm518[] = {
5395                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5396                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5397                 { OV511_REG_BUS, 0x31,                  0x0f },
5398                 { OV511_REG_BUS, 0x5d,                  0x03 },
5399                 { OV511_REG_BUS, 0x24,                  0x9f },
5400                 { OV511_REG_BUS, 0x25,                  0x90 },
5401                 { OV511_REG_BUS, 0x20,                  0x00 },
5402                 { OV511_REG_BUS, 0x51,                  0x04 },
5403                 { OV511_REG_BUS, 0x71,                  0x19 },
5404                 { OV511_DONE_BUS, 0x0, 0x00 },
5405         };
5406
5407         static struct ov511_regvals aRegvalsNorm518Plus[] = {
5408                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5409                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5410                 { OV511_REG_BUS, 0x31,                  0x0f },
5411                 { OV511_REG_BUS, 0x5d,                  0x03 },
5412                 { OV511_REG_BUS, 0x24,                  0x9f },
5413                 { OV511_REG_BUS, 0x25,                  0x90 },
5414                 { OV511_REG_BUS, 0x20,                  0x60 },
5415                 { OV511_REG_BUS, 0x51,                  0x02 },
5416                 { OV511_REG_BUS, 0x71,                  0x19 },
5417                 { OV511_REG_BUS, 0x40,                  0xff },
5418                 { OV511_REG_BUS, 0x41,                  0x42 },
5419                 { OV511_REG_BUS, 0x46,                  0x00 },
5420                 { OV511_REG_BUS, 0x33,                  0x04 },
5421                 { OV511_REG_BUS, 0x21,                  0x19 },
5422                 { OV511_REG_BUS, 0x3f,                  0x10 },
5423                 { OV511_DONE_BUS, 0x0, 0x00 },
5424         };
5425
5426         PDEBUG(4, "");
5427
5428         /* First 5 bits of custom ID reg are a revision ID on OV518 */
5429         info("Device revision %d", 0x1F & reg_r(ov, R511_SYS_CUST_ID));
5430
5431         /* Give it the default description */
5432         ov->desc = symbolic(camlist, 0);
5433
5434         if (write_regvals(ov, aRegvalsInit518))
5435                 goto error;
5436
5437         /* Set LED GPIO pin to output mode */
5438         if (reg_w_mask(ov, 0x57, 0x00, 0x02) < 0)
5439                 goto error;
5440
5441         /* LED is off by default with OV518; have to explicitly turn it on */
5442         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5443                 ov51x_led_control(ov, 0);
5444         else
5445                 ov51x_led_control(ov, 1);
5446
5447         /* Don't require compression if dumppix is enabled; otherwise it's
5448          * required. OV518 has no uncompressed mode, to save RAM. */
5449         if (!dumppix && !ov->compress) {
5450                 ov->compress = 1;
5451                 warn("Compression required with OV518...enabling");
5452         }
5453
5454         if (ov->bridge == BRG_OV518) {
5455                 if (write_regvals(ov, aRegvalsNorm518))
5456                         goto error;
5457         } else if (ov->bridge == BRG_OV518PLUS) {
5458                 if (write_regvals(ov, aRegvalsNorm518Plus))
5459                         goto error;
5460         } else {
5461                 err("Invalid bridge");
5462         }
5463
5464         if (reg_w(ov, 0x2f, 0x80) < 0)
5465                 goto error;
5466
5467         if (ov518_init_compression(ov))
5468                 goto error;
5469
5470         if (ov->bridge == BRG_OV518)
5471         {
5472                 struct usb_interface *ifp;
5473                 struct usb_host_interface *alt;
5474                 __u16 mxps = 0;
5475
5476                 ifp = usb_ifnum_to_if(ov->dev, 0);
5477                 if (ifp) {
5478                         alt = usb_altnum_to_altsetting(ifp, 7);
5479                         if (alt)
5480                                 mxps = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
5481                 }
5482
5483                 /* Some OV518s have packet numbering by default, some don't */
5484                 if (mxps == 897)
5485                         ov->packet_numbering = 1;
5486                 else
5487                         ov->packet_numbering = 0;
5488         } else {
5489                 /* OV518+ has packet numbering turned on by default */
5490                 ov->packet_numbering = 1;
5491         }
5492
5493         ov518_set_packet_size(ov, 0);
5494
5495         ov->snap_enabled = snapshot;
5496
5497         /* Test for 76xx */
5498         ov->primary_i2c_slave = OV7xx0_SID;
5499         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5500                 goto error;
5501
5502         /* The OV518 must be more aggressive about sensor detection since
5503          * I2C write will never fail if the sensor is not present. We have
5504          * to try to initialize the sensor to detect its presence */
5505
5506         if (init_ov_sensor(ov) < 0) {
5507                 /* Test for 6xx0 */
5508                 ov->primary_i2c_slave = OV6xx0_SID;
5509                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5510                         goto error;
5511
5512                 if (init_ov_sensor(ov) < 0) {
5513                         /* Test for 8xx0 */
5514                         ov->primary_i2c_slave = OV8xx0_SID;
5515                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5516                                 goto error;
5517
5518                         if (init_ov_sensor(ov) < 0) {
5519                                 err("Can't determine sensor slave IDs");
5520                                 goto error;
5521                         } else {
5522                                 err("Detected unsupported OV8xx0 sensor");
5523                                 goto error;
5524                         }
5525                 } else {
5526                         if (ov6xx0_configure(ov) < 0) {
5527                                 err("Failed to configure OV6xx0");
5528                                 goto error;
5529                         }
5530                 }
5531         } else {
5532                 if (ov7xx0_configure(ov) < 0) {
5533                         err("Failed to configure OV7xx0");
5534                         goto error;
5535                 }
5536         }
5537
5538         ov->maxwidth = 352;
5539         ov->maxheight = 288;
5540
5541         // The OV518 cannot go as low as the sensor can
5542         ov->minwidth = 160;
5543         ov->minheight = 120;
5544
5545         return 0;
5546
5547 error:
5548         err("OV518 Config failed");
5549
5550         return -EBUSY;
5551 }
5552
5553 /****************************************************************************
5554  *  sysfs
5555  ***************************************************************************/
5556
5557 static inline struct usb_ov511 *cd_to_ov(struct device *cd)
5558 {
5559         struct video_device *vdev = to_video_device(cd);
5560         return video_get_drvdata(vdev);
5561 }
5562
5563 static ssize_t show_custom_id(struct device *cd,
5564                               struct device_attribute *attr, char *buf)
5565 {
5566         struct usb_ov511 *ov = cd_to_ov(cd);
5567         return sprintf(buf, "%d\n", ov->customid);
5568 }
5569 static DEVICE_ATTR(custom_id, S_IRUGO, show_custom_id, NULL);
5570
5571 static ssize_t show_model(struct device *cd,
5572                           struct device_attribute *attr, char *buf)
5573 {
5574         struct usb_ov511 *ov = cd_to_ov(cd);
5575         return sprintf(buf, "%s\n", ov->desc);
5576 }
5577 static DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
5578
5579 static ssize_t show_bridge(struct device *cd,
5580                            struct device_attribute *attr, char *buf)
5581 {
5582         struct usb_ov511 *ov = cd_to_ov(cd);
5583         return sprintf(buf, "%s\n", symbolic(brglist, ov->bridge));
5584 }
5585 static DEVICE_ATTR(bridge, S_IRUGO, show_bridge, NULL);
5586
5587 static ssize_t show_sensor(struct device *cd,
5588                            struct device_attribute *attr, char *buf)
5589 {
5590         struct usb_ov511 *ov = cd_to_ov(cd);
5591         return sprintf(buf, "%s\n", symbolic(senlist, ov->sensor));
5592 }
5593 static DEVICE_ATTR(sensor, S_IRUGO, show_sensor, NULL);
5594
5595 static ssize_t show_brightness(struct device *cd,
5596                                struct device_attribute *attr, char *buf)
5597 {
5598         struct usb_ov511 *ov = cd_to_ov(cd);
5599         unsigned short x;
5600
5601         if (!ov->dev)
5602                 return -ENODEV;
5603         sensor_get_brightness(ov, &x);
5604         return sprintf(buf, "%d\n", x >> 8);
5605 }
5606 static DEVICE_ATTR(brightness, S_IRUGO, show_brightness, NULL);
5607
5608 static ssize_t show_saturation(struct device *cd,
5609                                struct device_attribute *attr, char *buf)
5610 {
5611         struct usb_ov511 *ov = cd_to_ov(cd);
5612         unsigned short x;
5613
5614         if (!ov->dev)
5615                 return -ENODEV;
5616         sensor_get_saturation(ov, &x);
5617         return sprintf(buf, "%d\n", x >> 8);
5618 }
5619 static DEVICE_ATTR(saturation, S_IRUGO, show_saturation, NULL);
5620
5621 static ssize_t show_contrast(struct device *cd,
5622                              struct device_attribute *attr, char *buf)
5623 {
5624         struct usb_ov511 *ov = cd_to_ov(cd);
5625         unsigned short x;
5626
5627         if (!ov->dev)
5628                 return -ENODEV;
5629         sensor_get_contrast(ov, &x);
5630         return sprintf(buf, "%d\n", x >> 8);
5631 }
5632 static DEVICE_ATTR(contrast, S_IRUGO, show_contrast, NULL);
5633
5634 static ssize_t show_hue(struct device *cd,
5635                         struct device_attribute *attr, char *buf)
5636 {
5637         struct usb_ov511 *ov = cd_to_ov(cd);
5638         unsigned short x;
5639
5640         if (!ov->dev)
5641                 return -ENODEV;
5642         sensor_get_hue(ov, &x);
5643         return sprintf(buf, "%d\n", x >> 8);
5644 }
5645 static DEVICE_ATTR(hue, S_IRUGO, show_hue, NULL);
5646
5647 static ssize_t show_exposure(struct device *cd,
5648                              struct device_attribute *attr, char *buf)
5649 {
5650         struct usb_ov511 *ov = cd_to_ov(cd);
5651         unsigned char exp = 0;
5652
5653         if (!ov->dev)
5654                 return -ENODEV;
5655         sensor_get_exposure(ov, &exp);
5656         return sprintf(buf, "%d\n", exp >> 8);
5657 }
5658 static DEVICE_ATTR(exposure, S_IRUGO, show_exposure, NULL);
5659
5660 static int ov_create_sysfs(struct video_device *vdev)
5661 {
5662         int rc;
5663
5664         rc = video_device_create_file(vdev, &dev_attr_custom_id);
5665         if (rc) goto err;
5666         rc = video_device_create_file(vdev, &dev_attr_model);
5667         if (rc) goto err_id;
5668         rc = video_device_create_file(vdev, &dev_attr_bridge);
5669         if (rc) goto err_model;
5670         rc = video_device_create_file(vdev, &dev_attr_sensor);
5671         if (rc) goto err_bridge;
5672         rc = video_device_create_file(vdev, &dev_attr_brightness);
5673         if (rc) goto err_sensor;
5674         rc = video_device_create_file(vdev, &dev_attr_saturation);
5675         if (rc) goto err_bright;
5676         rc = video_device_create_file(vdev, &dev_attr_contrast);
5677         if (rc) goto err_sat;
5678         rc = video_device_create_file(vdev, &dev_attr_hue);
5679         if (rc) goto err_contrast;
5680         rc = video_device_create_file(vdev, &dev_attr_exposure);
5681         if (rc) goto err_hue;
5682
5683         return 0;
5684
5685 err_hue:
5686         video_device_remove_file(vdev, &dev_attr_hue);
5687 err_contrast:
5688         video_device_remove_file(vdev, &dev_attr_contrast);
5689 err_sat:
5690         video_device_remove_file(vdev, &dev_attr_saturation);
5691 err_bright:
5692         video_device_remove_file(vdev, &dev_attr_brightness);
5693 err_sensor:
5694         video_device_remove_file(vdev, &dev_attr_sensor);
5695 err_bridge:
5696         video_device_remove_file(vdev, &dev_attr_bridge);
5697 err_model:
5698         video_device_remove_file(vdev, &dev_attr_model);
5699 err_id:
5700         video_device_remove_file(vdev, &dev_attr_custom_id);
5701 err:
5702         return rc;
5703 }
5704
5705 /****************************************************************************
5706  *  USB routines
5707  ***************************************************************************/
5708
5709 static int
5710 ov51x_probe(struct usb_interface *intf, const struct usb_device_id *id)
5711 {
5712         struct usb_device *dev = interface_to_usbdev(intf);
5713         struct usb_interface_descriptor *idesc;
5714         struct usb_ov511 *ov;
5715         int i;
5716
5717         PDEBUG(1, "probing for device...");
5718
5719         /* We don't handle multi-config cameras */
5720         if (dev->descriptor.bNumConfigurations != 1)
5721                 return -ENODEV;
5722
5723         idesc = &intf->cur_altsetting->desc;
5724
5725         if (idesc->bInterfaceClass != 0xFF)
5726                 return -ENODEV;
5727         if (idesc->bInterfaceSubClass != 0x00)
5728                 return -ENODEV;
5729
5730         if ((ov = kzalloc(sizeof(*ov), GFP_KERNEL)) == NULL) {
5731                 err("couldn't kmalloc ov struct");
5732                 goto error_out;
5733         }
5734
5735         ov->dev = dev;
5736         ov->iface = idesc->bInterfaceNumber;
5737         ov->led_policy = led;
5738         ov->compress = compress;
5739         ov->lightfreq = lightfreq;
5740         ov->num_inputs = 1;        /* Video decoder init functs. change this */
5741         ov->stop_during_set = !fastset;
5742         ov->backlight = backlight;
5743         ov->mirror = mirror;
5744         ov->auto_brt = autobright;
5745         ov->auto_gain = autogain;
5746         ov->auto_exp = autoexp;
5747
5748         switch (le16_to_cpu(dev->descriptor.idProduct)) {
5749         case PROD_OV511:
5750                 ov->bridge = BRG_OV511;
5751                 ov->bclass = BCL_OV511;
5752                 break;
5753         case PROD_OV511PLUS:
5754                 ov->bridge = BRG_OV511PLUS;
5755                 ov->bclass = BCL_OV511;
5756                 break;
5757         case PROD_OV518:
5758                 ov->bridge = BRG_OV518;
5759                 ov->bclass = BCL_OV518;
5760                 break;
5761         case PROD_OV518PLUS:
5762                 ov->bridge = BRG_OV518PLUS;
5763                 ov->bclass = BCL_OV518;
5764                 break;
5765         case PROD_ME2CAM:
5766                 if (le16_to_cpu(dev->descriptor.idVendor) != VEND_MATTEL)
5767                         goto error;
5768                 ov->bridge = BRG_OV511PLUS;
5769                 ov->bclass = BCL_OV511;
5770                 break;
5771         default:
5772                 err("Unknown product ID 0x%04x", le16_to_cpu(dev->descriptor.idProduct));
5773                 goto error;
5774         }
5775
5776         info("USB %s video device found", symbolic(brglist, ov->bridge));
5777
5778         init_waitqueue_head(&ov->wq);
5779
5780         mutex_init(&ov->lock);  /* to 1 == available */
5781         mutex_init(&ov->buf_lock);
5782         mutex_init(&ov->i2c_lock);
5783         mutex_init(&ov->cbuf_lock);
5784
5785         ov->buf_state = BUF_NOT_ALLOCATED;
5786
5787         if (usb_make_path(dev, ov->usb_path, OV511_USB_PATH_LEN) < 0) {
5788                 err("usb_make_path error");
5789                 goto error;
5790         }
5791
5792         /* Allocate control transfer buffer. */
5793         /* Must be kmalloc()'ed, for DMA compatibility */
5794         ov->cbuf = kmalloc(OV511_CBUF_SIZE, GFP_KERNEL);
5795         if (!ov->cbuf)
5796                 goto error;
5797
5798         if (ov->bclass == BCL_OV518) {
5799                 if (ov518_configure(ov) < 0)
5800                         goto error;
5801         } else {
5802                 if (ov511_configure(ov) < 0)
5803                         goto error;
5804         }
5805
5806         for (i = 0; i < OV511_NUMFRAMES; i++) {
5807                 ov->frame[i].framenum = i;
5808                 init_waitqueue_head(&ov->frame[i].wq);
5809         }
5810
5811         for (i = 0; i < OV511_NUMSBUF; i++) {
5812                 ov->sbuf[i].ov = ov;
5813                 spin_lock_init(&ov->sbuf[i].lock);
5814                 ov->sbuf[i].n = i;
5815         }
5816
5817         /* Unnecessary? (This is done on open(). Need to make sure variables
5818          * are properly initialized without this before removing it, though). */
5819         if (ov51x_set_default_params(ov) < 0)
5820                 goto error;
5821
5822 #ifdef OV511_DEBUG
5823         if (dump_bridge) {
5824                 if (ov->bclass == BCL_OV511)
5825                         ov511_dump_regs(ov);
5826                 else
5827                         ov518_dump_regs(ov);
5828         }
5829 #endif
5830
5831         ov->vdev = video_device_alloc();
5832         if (!ov->vdev)
5833                 goto error;
5834
5835         memcpy(ov->vdev, &vdev_template, sizeof(*ov->vdev));
5836         ov->vdev->dev = &dev->dev;
5837         video_set_drvdata(ov->vdev, ov);
5838
5839         for (i = 0; i < OV511_MAX_UNIT_VIDEO; i++) {
5840                 /* Minor 0 cannot be specified; assume user wants autodetect */
5841                 if (unit_video[i] == 0)
5842                         break;
5843
5844                 if (video_register_device(ov->vdev, VFL_TYPE_GRABBER,
5845                         unit_video[i]) >= 0) {
5846                         break;
5847                 }
5848         }
5849
5850         /* Use the next available one */
5851         if ((ov->vdev->minor == -1) &&
5852             video_register_device(ov->vdev, VFL_TYPE_GRABBER, -1) < 0) {
5853                 err("video_register_device failed");
5854                 goto error;
5855         }
5856
5857         info("Device at %s registered to minor %d", ov->usb_path,
5858              ov->vdev->minor);
5859
5860         usb_set_intfdata(intf, ov);
5861         if (ov_create_sysfs(ov->vdev)) {
5862                 err("ov_create_sysfs failed");
5863                 goto error;
5864         }
5865
5866         return 0;
5867
5868 error:
5869         if (ov->vdev) {
5870                 if (-1 == ov->vdev->minor)
5871                         video_device_release(ov->vdev);
5872                 else
5873                         video_unregister_device(ov->vdev);
5874                 ov->vdev = NULL;
5875         }
5876
5877         if (ov->cbuf) {
5878                 mutex_lock(&ov->cbuf_lock);
5879                 kfree(ov->cbuf);
5880                 ov->cbuf = NULL;
5881                 mutex_unlock(&ov->cbuf_lock);
5882         }
5883
5884         kfree(ov);
5885         ov = NULL;
5886
5887 error_out:
5888         err("Camera initialization failed");
5889         return -EIO;
5890 }
5891
5892 static void
5893 ov51x_disconnect(struct usb_interface *intf)
5894 {
5895         struct usb_ov511 *ov = usb_get_intfdata(intf);
5896         int n;
5897
5898         PDEBUG(3, "");
5899
5900         usb_set_intfdata (intf, NULL);
5901
5902         if (!ov)
5903                 return;
5904
5905         if (ov->vdev)
5906                 video_unregister_device(ov->vdev);
5907
5908         for (n = 0; n < OV511_NUMFRAMES; n++)
5909                 ov->frame[n].grabstate = FRAME_ERROR;
5910
5911         ov->curframe = -1;
5912
5913         /* This will cause the process to request another frame */
5914         for (n = 0; n < OV511_NUMFRAMES; n++)
5915                 wake_up_interruptible(&ov->frame[n].wq);
5916
5917         wake_up_interruptible(&ov->wq);
5918
5919         ov->streaming = 0;
5920         ov51x_unlink_isoc(ov);
5921
5922         ov->dev = NULL;
5923
5924         /* Free the memory */
5925         if (ov && !ov->user) {
5926                 mutex_lock(&ov->cbuf_lock);
5927                 kfree(ov->cbuf);
5928                 ov->cbuf = NULL;
5929                 mutex_unlock(&ov->cbuf_lock);
5930
5931                 ov51x_dealloc(ov);
5932                 kfree(ov);
5933                 ov = NULL;
5934         }
5935
5936         PDEBUG(3, "Disconnect complete");
5937 }
5938
5939 static struct usb_driver ov511_driver = {
5940         .name =         "ov511",
5941         .id_table =     device_table,
5942         .probe =        ov51x_probe,
5943         .disconnect =   ov51x_disconnect
5944 };
5945
5946 /****************************************************************************
5947  *
5948  *  Module routines
5949  *
5950  ***************************************************************************/
5951
5952 static int __init
5953 usb_ov511_init(void)
5954 {
5955         int retval;
5956
5957         retval = usb_register(&ov511_driver);
5958         if (retval)
5959                 goto out;
5960
5961         info(DRIVER_VERSION " : " DRIVER_DESC);
5962
5963 out:
5964         return retval;
5965 }
5966
5967 static void __exit
5968 usb_ov511_exit(void)
5969 {
5970         usb_deregister(&ov511_driver);
5971         info("driver deregistered");
5972
5973 }
5974
5975 module_init(usb_ov511_init);
5976 module_exit(usb_ov511_exit);
5977