Merge git://git.kernel.org/pub/scm/linux/kernel/git/rusty/linux-2.6-for-linus
[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                 dev_info(&ov->dev->dev, "Sensor[0x%02X] = 0x%02X\n", i, rc);
978         }
979 }
980
981 static void
982 dump_i2c_regs(struct usb_ov511 *ov)
983 {
984         dev_info(&ov->dev->dev, "I2C REGS\n");
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                 dev_info(&ov->dev->dev, "OV511[0x%02X] = 0x%02X\n", i, rc);
996         }
997 }
998
999 static void
1000 ov511_dump_regs(struct usb_ov511 *ov)
1001 {
1002         dev_info(&ov->dev->dev, "CAMERA INTERFACE REGS\n");
1003         dump_reg_range(ov, 0x10, 0x1f);
1004         dev_info(&ov->dev->dev, "DRAM INTERFACE REGS\n");
1005         dump_reg_range(ov, 0x20, 0x23);
1006         dev_info(&ov->dev->dev, "ISO FIFO REGS\n");
1007         dump_reg_range(ov, 0x30, 0x31);
1008         dev_info(&ov->dev->dev, "PIO REGS\n");
1009         dump_reg_range(ov, 0x38, 0x39);
1010         dump_reg_range(ov, 0x3e, 0x3e);
1011         dev_info(&ov->dev->dev, "I2C REGS\n");
1012         dump_reg_range(ov, 0x40, 0x49);
1013         dev_info(&ov->dev->dev, "SYSTEM CONTROL REGS\n");
1014         dump_reg_range(ov, 0x50, 0x55);
1015         dump_reg_range(ov, 0x5e, 0x5f);
1016         dev_info(&ov->dev->dev, "OmniCE REGS\n");
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         dev_info(&ov->dev->dev, "VIDEO MODE REGS\n");
1029         dump_reg_range(ov, 0x20, 0x2f);
1030         dev_info(&ov->dev->dev, "DATA PUMP AND SNAPSHOT REGS\n");
1031         dump_reg_range(ov, 0x30, 0x3f);
1032         dev_info(&ov->dev->dev, "I2C REGS\n");
1033         dump_reg_range(ov, 0x40, 0x4f);
1034         dev_info(&ov->dev->dev, "SYSTEM CONTROL AND VENDOR REGS\n");
1035         dump_reg_range(ov, 0x50, 0x5f);
1036         dev_info(&ov->dev->dev, "60 - 6F\n");
1037         dump_reg_range(ov, 0x60, 0x6f);
1038         dev_info(&ov->dev->dev, "70 - 7F\n");
1039         dump_reg_range(ov, 0x70, 0x7f);
1040         dev_info(&ov->dev->dev, "Y QUANTIZATION TABLE\n");
1041         dump_reg_range(ov, 0x80, 0x8f);
1042         dev_info(&ov->dev->dev, "UV QUANTIZATION TABLE\n");
1043         dump_reg_range(ov, 0x90, 0x9f);
1044         dev_info(&ov->dev->dev, "A0 - BF\n");
1045         dump_reg_range(ov, 0xa0, 0xbf);
1046         dev_info(&ov->dev->dev, "CBR\n");
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                 dev_info(&ov->dev->dev,
3209                          "ph(%3d): %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x\n",
3210                          pnum, in[0], in[1], in[2], in[3], in[4], in[5], in[6],
3211                          in[7], in[8], in[9], in[10], in[11]);
3212         }
3213
3214         /* Check for SOF/EOF packet */
3215         if ((in[0] | in[1] | in[2] | in[3] | in[4] | in[5] | in[6] | in[7]) ||
3216             (~in[8] & 0x08))
3217                 goto check_middle;
3218
3219         /* Frame end */
3220         if (in[8] & 0x80) {
3221                 ts = (struct timeval *)(frame->data
3222                       + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
3223                 do_gettimeofday(ts);
3224
3225                 /* Get the actual frame size from the EOF header */
3226                 frame->rawwidth = ((int)(in[9]) + 1) * 8;
3227                 frame->rawheight = ((int)(in[10]) + 1) * 8;
3228
3229                 PDEBUG(4, "Frame end, frame=%d, pnum=%d, w=%d, h=%d, recvd=%d",
3230                         ov->curframe, pnum, frame->rawwidth, frame->rawheight,
3231                         frame->bytes_recvd);
3232
3233                 /* Validate the header data */
3234                 RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
3235                 RESTRICT_TO_RANGE(frame->rawheight, ov->minheight,
3236                                   ov->maxheight);
3237
3238                 /* Don't allow byte count to exceed buffer size */
3239                 RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
3240
3241                 if (frame->scanstate == STATE_LINES) {
3242                         int nextf;
3243
3244                         frame->grabstate = FRAME_DONE;
3245                         wake_up_interruptible(&frame->wq);
3246
3247                         /* If next frame is ready or grabbing,
3248                          * point to it */
3249                         nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
3250                         if (ov->frame[nextf].grabstate == FRAME_READY
3251                             || ov->frame[nextf].grabstate == FRAME_GRABBING) {
3252                                 ov->curframe = nextf;
3253                                 ov->frame[nextf].scanstate = STATE_SCANNING;
3254                         } else {
3255                                 if (frame->grabstate == FRAME_DONE) {
3256                                         PDEBUG(4, "** Frame done **");
3257                                 } else {
3258                                         PDEBUG(4, "Frame not ready? state = %d",
3259                                                 ov->frame[nextf].grabstate);
3260                                 }
3261
3262                                 ov->curframe = -1;
3263                         }
3264                 } else {
3265                         PDEBUG(5, "Frame done, but not scanning");
3266                 }
3267                 /* Image corruption caused by misplaced frame->segment = 0
3268                  * fixed by carlosf@conectiva.com.br
3269                  */
3270         } else {
3271                 /* Frame start */
3272                 PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
3273
3274                 /* Check to see if it's a snapshot frame */
3275                 /* FIXME?? Should the snapshot reset go here? Performance? */
3276                 if (in[8] & 0x02) {
3277                         frame->snapshot = 1;
3278                         PDEBUG(3, "snapshot detected");
3279                 }
3280
3281                 frame->scanstate = STATE_LINES;
3282                 frame->bytes_recvd = 0;
3283                 frame->compressed = in[8] & 0x40;
3284         }
3285
3286 check_middle:
3287         /* Are we in a frame? */
3288         if (frame->scanstate != STATE_LINES) {
3289                 PDEBUG(5, "Not in a frame; packet skipped");
3290                 return;
3291         }
3292
3293         /* If frame start, skip header */
3294         if (frame->bytes_recvd == 0)
3295                 offset = 9;
3296         else
3297                 offset = 0;
3298
3299         num = n - offset - 1;
3300
3301         /* Dump all data exactly as received */
3302         if (dumppix == 2) {
3303                 frame->bytes_recvd += n - 1;
3304                 if (frame->bytes_recvd <= max_raw)
3305                         memcpy(frame->rawdata + frame->bytes_recvd - (n - 1),
3306                                 in, n - 1);
3307                 else
3308                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3309                                 frame->bytes_recvd - max_raw);
3310         } else if (!frame->compressed && !remove_zeros) {
3311                 frame->bytes_recvd += num;
3312                 if (frame->bytes_recvd <= max_raw)
3313                         memcpy(frame->rawdata + frame->bytes_recvd - num,
3314                                 in + offset, num);
3315                 else
3316                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3317                                 frame->bytes_recvd - max_raw);
3318         } else { /* Remove all-zero FIFO lines (aligned 32-byte blocks) */
3319                 int b, read = 0, allzero, copied = 0;
3320                 if (offset) {
3321                         frame->bytes_recvd += 32 - offset;      // Bytes out
3322                         memcpy(frame->rawdata,  in + offset, 32 - offset);
3323                         read += 32;
3324                 }
3325
3326                 while (read < n - 1) {
3327                         allzero = 1;
3328                         for (b = 0; b < 32; b++) {
3329                                 if (in[read + b]) {
3330                                         allzero = 0;
3331                                         break;
3332                                 }
3333                         }
3334
3335                         if (allzero) {
3336                                 /* Don't copy it */
3337                         } else {
3338                                 if (frame->bytes_recvd + copied + 32 <= max_raw)
3339                                 {
3340                                         memcpy(frame->rawdata
3341                                                 + frame->bytes_recvd + copied,
3342                                                 in + read, 32);
3343                                         copied += 32;
3344                                 } else {
3345                                         PDEBUG(3, "Raw data buffer overrun!!");
3346                                 }
3347                         }
3348                         read += 32;
3349                 }
3350
3351                 frame->bytes_recvd += copied;
3352         }
3353 }
3354
3355 static inline void
3356 ov518_move_data(struct usb_ov511 *ov, unsigned char *in, int n)
3357 {
3358         int max_raw = MAX_RAW_DATA_SIZE(ov->maxwidth, ov->maxheight);
3359         struct ov511_frame *frame = &ov->frame[ov->curframe];
3360         struct timeval *ts;
3361
3362         /* Don't copy the packet number byte */
3363         if (ov->packet_numbering)
3364                 --n;
3365
3366         /* A false positive here is likely, until OVT gives me
3367          * the definitive SOF/EOF format */
3368         if ((!(in[0] | in[1] | in[2] | in[3] | in[5])) && in[6]) {
3369                 if (printph) {
3370                         dev_info(&ov->dev->dev,
3371                                  "ph: %2x %2x %2x %2x %2x %2x %2x %2x\n",
3372                                  in[0], in[1], in[2], in[3], in[4], in[5],
3373                                  in[6], in[7]);
3374                 }
3375
3376                 if (frame->scanstate == STATE_LINES) {
3377                         PDEBUG(4, "Detected frame end/start");
3378                         goto eof;
3379                 } else { //scanstate == STATE_SCANNING
3380                         /* Frame start */
3381                         PDEBUG(4, "Frame start, framenum = %d", ov->curframe);
3382                         goto sof;
3383                 }
3384         } else {
3385                 goto check_middle;
3386         }
3387
3388 eof:
3389         ts = (struct timeval *)(frame->data
3390               + MAX_FRAME_SIZE(ov->maxwidth, ov->maxheight));
3391         do_gettimeofday(ts);
3392
3393         PDEBUG(4, "Frame end, curframe = %d, hw=%d, vw=%d, recvd=%d",
3394                 ov->curframe,
3395                 (int)(in[9]), (int)(in[10]), frame->bytes_recvd);
3396
3397         // FIXME: Since we don't know the header formats yet,
3398         // there is no way to know what the actual image size is
3399         frame->rawwidth = frame->width;
3400         frame->rawheight = frame->height;
3401
3402         /* Validate the header data */
3403         RESTRICT_TO_RANGE(frame->rawwidth, ov->minwidth, ov->maxwidth);
3404         RESTRICT_TO_RANGE(frame->rawheight, ov->minheight, ov->maxheight);
3405
3406         /* Don't allow byte count to exceed buffer size */
3407         RESTRICT_TO_RANGE(frame->bytes_recvd, 8, max_raw);
3408
3409         if (frame->scanstate == STATE_LINES) {
3410                 int nextf;
3411
3412                 frame->grabstate = FRAME_DONE;
3413                 wake_up_interruptible(&frame->wq);
3414
3415                 /* If next frame is ready or grabbing,
3416                  * point to it */
3417                 nextf = (ov->curframe + 1) % OV511_NUMFRAMES;
3418                 if (ov->frame[nextf].grabstate == FRAME_READY
3419                     || ov->frame[nextf].grabstate == FRAME_GRABBING) {
3420                         ov->curframe = nextf;
3421                         ov->frame[nextf].scanstate = STATE_SCANNING;
3422                         frame = &ov->frame[nextf];
3423                 } else {
3424                         if (frame->grabstate == FRAME_DONE) {
3425                                 PDEBUG(4, "** Frame done **");
3426                         } else {
3427                                 PDEBUG(4, "Frame not ready? state = %d",
3428                                        ov->frame[nextf].grabstate);
3429                         }
3430
3431                         ov->curframe = -1;
3432                         PDEBUG(4, "SOF dropped (no active frame)");
3433                         return;  /* Nowhere to store this frame */
3434                 }
3435         }
3436 sof:
3437         PDEBUG(4, "Starting capture on frame %d", frame->framenum);
3438
3439 // Snapshot not reverse-engineered yet.
3440 #if 0
3441         /* Check to see if it's a snapshot frame */
3442         /* FIXME?? Should the snapshot reset go here? Performance? */
3443         if (in[8] & 0x02) {
3444                 frame->snapshot = 1;
3445                 PDEBUG(3, "snapshot detected");
3446         }
3447 #endif
3448         frame->scanstate = STATE_LINES;
3449         frame->bytes_recvd = 0;
3450         frame->compressed = 1;
3451
3452 check_middle:
3453         /* Are we in a frame? */
3454         if (frame->scanstate != STATE_LINES) {
3455                 PDEBUG(4, "scanstate: no SOF yet");
3456                 return;
3457         }
3458
3459         /* Dump all data exactly as received */
3460         if (dumppix == 2) {
3461                 frame->bytes_recvd += n;
3462                 if (frame->bytes_recvd <= max_raw)
3463                         memcpy(frame->rawdata + frame->bytes_recvd - n, in, n);
3464                 else
3465                         PDEBUG(3, "Raw data buffer overrun!! (%d)",
3466                                 frame->bytes_recvd - max_raw);
3467         } else {
3468                 /* All incoming data are divided into 8-byte segments. If the
3469                  * segment contains all zero bytes, it must be skipped. These
3470                  * zero-segments allow the OV518 to mainain a constant data rate
3471                  * regardless of the effectiveness of the compression. Segments
3472                  * are aligned relative to the beginning of each isochronous
3473                  * packet. The first segment in each image is a header (the
3474                  * decompressor skips it later).
3475                  */
3476
3477                 int b, read = 0, allzero, copied = 0;
3478
3479                 while (read < n) {
3480                         allzero = 1;
3481                         for (b = 0; b < 8; b++) {
3482                                 if (in[read + b]) {
3483                                         allzero = 0;
3484                                         break;
3485                                 }
3486                         }
3487
3488                         if (allzero) {
3489                         /* Don't copy it */
3490                         } else {
3491                                 if (frame->bytes_recvd + copied + 8 <= max_raw)
3492                                 {
3493                                         memcpy(frame->rawdata
3494                                                 + frame->bytes_recvd + copied,
3495                                                 in + read, 8);
3496                                         copied += 8;
3497                                 } else {
3498                                         PDEBUG(3, "Raw data buffer overrun!!");
3499                                 }
3500                         }
3501                         read += 8;
3502                 }
3503                 frame->bytes_recvd += copied;
3504         }
3505 }
3506
3507 static void
3508 ov51x_isoc_irq(struct urb *urb)
3509 {
3510         int i;
3511         struct usb_ov511 *ov;
3512         struct ov511_sbuf *sbuf;
3513
3514         if (!urb->context) {
3515                 PDEBUG(4, "no context");
3516                 return;
3517         }
3518
3519         sbuf = urb->context;
3520         ov = sbuf->ov;
3521
3522         if (!ov || !ov->dev || !ov->user) {
3523                 PDEBUG(4, "no device, or not open");
3524                 return;
3525         }
3526
3527         if (!ov->streaming) {
3528                 PDEBUG(4, "hmmm... not streaming, but got interrupt");
3529                 return;
3530         }
3531
3532         if (urb->status == -ENOENT || urb->status == -ECONNRESET) {
3533                 PDEBUG(4, "URB unlinked");
3534                 return;
3535         }
3536
3537         if (urb->status != -EINPROGRESS && urb->status != 0) {
3538                 err("ERROR: urb->status=%d: %s", urb->status,
3539                     symbolic(urb_errlist, urb->status));
3540         }
3541
3542         /* Copy the data received into our frame buffer */
3543         PDEBUG(5, "sbuf[%d]: Moving %d packets", sbuf->n,
3544                urb->number_of_packets);
3545         for (i = 0; i < urb->number_of_packets; i++) {
3546                 /* Warning: Don't call *_move_data() if no frame active! */
3547                 if (ov->curframe >= 0) {
3548                         int n = urb->iso_frame_desc[i].actual_length;
3549                         int st = urb->iso_frame_desc[i].status;
3550                         unsigned char *cdata;
3551
3552                         urb->iso_frame_desc[i].actual_length = 0;
3553                         urb->iso_frame_desc[i].status = 0;
3554
3555                         cdata = urb->transfer_buffer
3556                                 + urb->iso_frame_desc[i].offset;
3557
3558                         if (!n) {
3559                                 PDEBUG(4, "Zero-length packet");
3560                                 continue;
3561                         }
3562
3563                         if (st)
3564                                 PDEBUG(2, "data error: [%d] len=%d, status=%d",
3565                                        i, n, st);
3566
3567                         if (ov->bclass == BCL_OV511)
3568                                 ov511_move_data(ov, cdata, n);
3569                         else if (ov->bclass == BCL_OV518)
3570                                 ov518_move_data(ov, cdata, n);
3571                         else
3572                                 err("Unknown bridge device (%d)", ov->bridge);
3573
3574                 } else if (waitqueue_active(&ov->wq)) {
3575                         wake_up_interruptible(&ov->wq);
3576                 }
3577         }
3578
3579         /* Resubmit this URB */
3580         urb->dev = ov->dev;
3581         if ((i = usb_submit_urb(urb, GFP_ATOMIC)) != 0)
3582                 err("usb_submit_urb() ret %d", i);
3583
3584         return;
3585 }
3586
3587 /****************************************************************************
3588  *
3589  * Stream initialization and termination
3590  *
3591  ***************************************************************************/
3592
3593 static int
3594 ov51x_init_isoc(struct usb_ov511 *ov)
3595 {
3596         struct urb *urb;
3597         int fx, err, n, i, size;
3598
3599         PDEBUG(3, "*** Initializing capture ***");
3600
3601         ov->curframe = -1;
3602
3603         if (ov->bridge == BRG_OV511) {
3604                 if (cams == 1)
3605                         size = 993;
3606                 else if (cams == 2)
3607                         size = 513;
3608                 else if (cams == 3 || cams == 4)
3609                         size = 257;
3610                 else {
3611                         err("\"cams\" parameter too high!");
3612                         return -1;
3613                 }
3614         } else if (ov->bridge == BRG_OV511PLUS) {
3615                 if (cams == 1)
3616                         size = 961;
3617                 else if (cams == 2)
3618                         size = 513;
3619                 else if (cams == 3 || cams == 4)
3620                         size = 257;
3621                 else if (cams >= 5 && cams <= 8)
3622                         size = 129;
3623                 else if (cams >= 9 && cams <= 31)
3624                         size = 33;
3625                 else {
3626                         err("\"cams\" parameter too high!");
3627                         return -1;
3628                 }
3629         } else if (ov->bclass == BCL_OV518) {
3630                 if (cams == 1)
3631                         size = 896;
3632                 else if (cams == 2)
3633                         size = 512;
3634                 else if (cams == 3 || cams == 4)
3635                         size = 256;
3636                 else if (cams >= 5 && cams <= 8)
3637                         size = 128;
3638                 else {
3639                         err("\"cams\" parameter too high!");
3640                         return -1;
3641                 }
3642         } else {
3643                 err("invalid bridge type");
3644                 return -1;
3645         }
3646
3647         // FIXME: OV518 is hardcoded to 15 FPS (alternate 5) for now
3648         if (ov->bclass == BCL_OV518) {
3649                 if (packetsize == -1) {
3650                         ov518_set_packet_size(ov, 640);
3651                 } else {
3652                         dev_info(&ov->dev->dev, "Forcing packet size to %d\n",
3653                                  packetsize);
3654                         ov518_set_packet_size(ov, packetsize);
3655                 }
3656         } else {
3657                 if (packetsize == -1) {
3658                         ov511_set_packet_size(ov, size);
3659                 } else {
3660                         dev_info(&ov->dev->dev, "Forcing packet size to %d\n",
3661                                  packetsize);
3662                         ov511_set_packet_size(ov, packetsize);
3663                 }
3664         }
3665
3666         for (n = 0; n < OV511_NUMSBUF; n++) {
3667                 urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
3668                 if (!urb) {
3669                         err("init isoc: usb_alloc_urb ret. NULL");
3670                         for (i = 0; i < n; i++)
3671                                 usb_free_urb(ov->sbuf[i].urb);
3672                         return -ENOMEM;
3673                 }
3674                 ov->sbuf[n].urb = urb;
3675                 urb->dev = ov->dev;
3676                 urb->context = &ov->sbuf[n];
3677                 urb->pipe = usb_rcvisocpipe(ov->dev, OV511_ENDPOINT_ADDRESS);
3678                 urb->transfer_flags = URB_ISO_ASAP;
3679                 urb->transfer_buffer = ov->sbuf[n].data;
3680                 urb->complete = ov51x_isoc_irq;
3681                 urb->number_of_packets = FRAMES_PER_DESC;
3682                 urb->transfer_buffer_length = ov->packet_size * FRAMES_PER_DESC;
3683                 urb->interval = 1;
3684                 for (fx = 0; fx < FRAMES_PER_DESC; fx++) {
3685                         urb->iso_frame_desc[fx].offset = ov->packet_size * fx;
3686                         urb->iso_frame_desc[fx].length = ov->packet_size;
3687                 }
3688         }
3689
3690         ov->streaming = 1;
3691
3692         for (n = 0; n < OV511_NUMSBUF; n++) {
3693                 ov->sbuf[n].urb->dev = ov->dev;
3694                 err = usb_submit_urb(ov->sbuf[n].urb, GFP_KERNEL);
3695                 if (err) {
3696                         err("init isoc: usb_submit_urb(%d) ret %d", n, err);
3697                         return err;
3698                 }
3699         }
3700
3701         return 0;
3702 }
3703
3704 static void
3705 ov51x_unlink_isoc(struct usb_ov511 *ov)
3706 {
3707         int n;
3708
3709         /* Unschedule all of the iso td's */
3710         for (n = OV511_NUMSBUF - 1; n >= 0; n--) {
3711                 if (ov->sbuf[n].urb) {
3712                         usb_kill_urb(ov->sbuf[n].urb);
3713                         usb_free_urb(ov->sbuf[n].urb);
3714                         ov->sbuf[n].urb = NULL;
3715                 }
3716         }
3717 }
3718
3719 static void
3720 ov51x_stop_isoc(struct usb_ov511 *ov)
3721 {
3722         if (!ov->streaming || !ov->dev)
3723                 return;
3724
3725         PDEBUG(3, "*** Stopping capture ***");
3726
3727         if (ov->bclass == BCL_OV518)
3728                 ov518_set_packet_size(ov, 0);
3729         else
3730                 ov511_set_packet_size(ov, 0);
3731
3732         ov->streaming = 0;
3733
3734         ov51x_unlink_isoc(ov);
3735 }
3736
3737 static int
3738 ov51x_new_frame(struct usb_ov511 *ov, int framenum)
3739 {
3740         struct ov511_frame *frame;
3741         int newnum;
3742
3743         PDEBUG(4, "ov->curframe = %d, framenum = %d", ov->curframe, framenum);
3744
3745         if (!ov->dev)
3746                 return -1;
3747
3748         /* If we're not grabbing a frame right now and the other frame is */
3749         /* ready to be grabbed into, then use it instead */
3750         if (ov->curframe == -1) {
3751                 newnum = (framenum - 1 + OV511_NUMFRAMES) % OV511_NUMFRAMES;
3752                 if (ov->frame[newnum].grabstate == FRAME_READY)
3753                         framenum = newnum;
3754         } else
3755                 return 0;
3756
3757         frame = &ov->frame[framenum];
3758
3759         PDEBUG(4, "framenum = %d, width = %d, height = %d", framenum,
3760                frame->width, frame->height);
3761
3762         frame->grabstate = FRAME_GRABBING;
3763         frame->scanstate = STATE_SCANNING;
3764         frame->snapshot = 0;
3765
3766         ov->curframe = framenum;
3767
3768         /* Make sure it's not too big */
3769         if (frame->width > ov->maxwidth)
3770                 frame->width = ov->maxwidth;
3771
3772         frame->width &= ~7L;            /* Multiple of 8 */
3773
3774         if (frame->height > ov->maxheight)
3775                 frame->height = ov->maxheight;
3776
3777         frame->height &= ~3L;           /* Multiple of 4 */
3778
3779         return 0;
3780 }
3781
3782 /****************************************************************************
3783  *
3784  * Buffer management
3785  *
3786  ***************************************************************************/
3787
3788 /*
3789  * - You must acquire buf_lock before entering this function.
3790  * - Because this code will free any non-null pointer, you must be sure to null
3791  *   them if you explicitly free them somewhere else!
3792  */
3793 static void
3794 ov51x_do_dealloc(struct usb_ov511 *ov)
3795 {
3796         int i;
3797         PDEBUG(4, "entered");
3798
3799         if (ov->fbuf) {
3800                 rvfree(ov->fbuf, OV511_NUMFRAMES
3801                        * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight));
3802                 ov->fbuf = NULL;
3803         }
3804
3805         vfree(ov->rawfbuf);
3806         ov->rawfbuf = NULL;
3807
3808         vfree(ov->tempfbuf);
3809         ov->tempfbuf = NULL;
3810
3811         for (i = 0; i < OV511_NUMSBUF; i++) {
3812                 kfree(ov->sbuf[i].data);
3813                 ov->sbuf[i].data = NULL;
3814         }
3815
3816         for (i = 0; i < OV511_NUMFRAMES; i++) {
3817                 ov->frame[i].data = NULL;
3818                 ov->frame[i].rawdata = NULL;
3819                 ov->frame[i].tempdata = NULL;
3820                 if (ov->frame[i].compbuf) {
3821                         free_page((unsigned long) ov->frame[i].compbuf);
3822                         ov->frame[i].compbuf = NULL;
3823                 }
3824         }
3825
3826         PDEBUG(4, "buffer memory deallocated");
3827         ov->buf_state = BUF_NOT_ALLOCATED;
3828         PDEBUG(4, "leaving");
3829 }
3830
3831 static int
3832 ov51x_alloc(struct usb_ov511 *ov)
3833 {
3834         int i;
3835         const int w = ov->maxwidth;
3836         const int h = ov->maxheight;
3837         const int data_bufsize = OV511_NUMFRAMES * MAX_DATA_SIZE(w, h);
3838         const int raw_bufsize = OV511_NUMFRAMES * MAX_RAW_DATA_SIZE(w, h);
3839
3840         PDEBUG(4, "entered");
3841         mutex_lock(&ov->buf_lock);
3842
3843         if (ov->buf_state == BUF_ALLOCATED)
3844                 goto out;
3845
3846         ov->fbuf = rvmalloc(data_bufsize);
3847         if (!ov->fbuf)
3848                 goto error;
3849
3850         ov->rawfbuf = vmalloc(raw_bufsize);
3851         if (!ov->rawfbuf)
3852                 goto error;
3853
3854         memset(ov->rawfbuf, 0, raw_bufsize);
3855
3856         ov->tempfbuf = vmalloc(raw_bufsize);
3857         if (!ov->tempfbuf)
3858                 goto error;
3859
3860         memset(ov->tempfbuf, 0, raw_bufsize);
3861
3862         for (i = 0; i < OV511_NUMSBUF; i++) {
3863                 ov->sbuf[i].data = kmalloc(FRAMES_PER_DESC *
3864                         MAX_FRAME_SIZE_PER_DESC, GFP_KERNEL);
3865                 if (!ov->sbuf[i].data)
3866                         goto error;
3867
3868                 PDEBUG(4, "sbuf[%d] @ %p", i, ov->sbuf[i].data);
3869         }
3870
3871         for (i = 0; i < OV511_NUMFRAMES; i++) {
3872                 ov->frame[i].data = ov->fbuf + i * MAX_DATA_SIZE(w, h);
3873                 ov->frame[i].rawdata = ov->rawfbuf
3874                  + i * MAX_RAW_DATA_SIZE(w, h);
3875                 ov->frame[i].tempdata = ov->tempfbuf
3876                  + i * MAX_RAW_DATA_SIZE(w, h);
3877
3878                 ov->frame[i].compbuf =
3879                  (unsigned char *) __get_free_page(GFP_KERNEL);
3880                 if (!ov->frame[i].compbuf)
3881                         goto error;
3882
3883                 PDEBUG(4, "frame[%d] @ %p", i, ov->frame[i].data);
3884         }
3885
3886         ov->buf_state = BUF_ALLOCATED;
3887 out:
3888         mutex_unlock(&ov->buf_lock);
3889         PDEBUG(4, "leaving");
3890         return 0;
3891 error:
3892         ov51x_do_dealloc(ov);
3893         mutex_unlock(&ov->buf_lock);
3894         PDEBUG(4, "errored");
3895         return -ENOMEM;
3896 }
3897
3898 static void
3899 ov51x_dealloc(struct usb_ov511 *ov)
3900 {
3901         PDEBUG(4, "entered");
3902         mutex_lock(&ov->buf_lock);
3903         ov51x_do_dealloc(ov);
3904         mutex_unlock(&ov->buf_lock);
3905         PDEBUG(4, "leaving");
3906 }
3907
3908 /****************************************************************************
3909  *
3910  * V4L 1 API
3911  *
3912  ***************************************************************************/
3913
3914 static int
3915 ov51x_v4l1_open(struct inode *inode, struct file *file)
3916 {
3917         struct video_device *vdev = video_devdata(file);
3918         struct usb_ov511 *ov = video_get_drvdata(vdev);
3919         int err, i;
3920
3921         PDEBUG(4, "opening");
3922
3923         mutex_lock(&ov->lock);
3924
3925         err = -EBUSY;
3926         if (ov->user)
3927                 goto out;
3928
3929         ov->sub_flag = 0;
3930
3931         /* In case app doesn't set them... */
3932         err = ov51x_set_default_params(ov);
3933         if (err < 0)
3934                 goto out;
3935
3936         /* Make sure frames are reset */
3937         for (i = 0; i < OV511_NUMFRAMES; i++) {
3938                 ov->frame[i].grabstate = FRAME_UNUSED;
3939                 ov->frame[i].bytes_read = 0;
3940         }
3941
3942         /* If compression is on, make sure now that a
3943          * decompressor can be loaded */
3944         if (ov->compress && !ov->decomp_ops) {
3945                 err = request_decompressor(ov);
3946                 if (err && !dumppix)
3947                         goto out;
3948         }
3949
3950         err = ov51x_alloc(ov);
3951         if (err < 0)
3952                 goto out;
3953
3954         err = ov51x_init_isoc(ov);
3955         if (err) {
3956                 ov51x_dealloc(ov);
3957                 goto out;
3958         }
3959
3960         ov->user++;
3961         file->private_data = vdev;
3962
3963         if (ov->led_policy == LED_AUTO)
3964                 ov51x_led_control(ov, 1);
3965
3966 out:
3967         mutex_unlock(&ov->lock);
3968         return err;
3969 }
3970
3971 static int
3972 ov51x_v4l1_close(struct inode *inode, struct file *file)
3973 {
3974         struct video_device *vdev = file->private_data;
3975         struct usb_ov511 *ov = video_get_drvdata(vdev);
3976
3977         PDEBUG(4, "ov511_close");
3978
3979         mutex_lock(&ov->lock);
3980
3981         ov->user--;
3982         ov51x_stop_isoc(ov);
3983
3984         if (ov->led_policy == LED_AUTO)
3985                 ov51x_led_control(ov, 0);
3986
3987         if (ov->dev)
3988                 ov51x_dealloc(ov);
3989
3990         mutex_unlock(&ov->lock);
3991
3992         /* Device unplugged while open. Only a minimum of unregistration is done
3993          * here; the disconnect callback already did the rest. */
3994         if (!ov->dev) {
3995                 mutex_lock(&ov->cbuf_lock);
3996                 kfree(ov->cbuf);
3997                 ov->cbuf = NULL;
3998                 mutex_unlock(&ov->cbuf_lock);
3999
4000                 ov51x_dealloc(ov);
4001                 kfree(ov);
4002                 ov = NULL;
4003         }
4004
4005         file->private_data = NULL;
4006         return 0;
4007 }
4008
4009 /* Do not call this function directly! */
4010 static int
4011 ov51x_v4l1_ioctl_internal(struct inode *inode, struct file *file,
4012                           unsigned int cmd, void *arg)
4013 {
4014         struct video_device *vdev = file->private_data;
4015         struct usb_ov511 *ov = video_get_drvdata(vdev);
4016         PDEBUG(5, "IOCtl: 0x%X", cmd);
4017
4018         if (!ov->dev)
4019                 return -EIO;
4020
4021         switch (cmd) {
4022         case VIDIOCGCAP:
4023         {
4024                 struct video_capability *b = arg;
4025
4026                 PDEBUG(4, "VIDIOCGCAP");
4027
4028                 memset(b, 0, sizeof(struct video_capability));
4029                 sprintf(b->name, "%s USB Camera",
4030                         symbolic(brglist, ov->bridge));
4031                 b->type = VID_TYPE_CAPTURE | VID_TYPE_SUBCAPTURE;
4032                 b->channels = ov->num_inputs;
4033                 b->audios = 0;
4034                 b->maxwidth = ov->maxwidth;
4035                 b->maxheight = ov->maxheight;
4036                 b->minwidth = ov->minwidth;
4037                 b->minheight = ov->minheight;
4038
4039                 return 0;
4040         }
4041         case VIDIOCGCHAN:
4042         {
4043                 struct video_channel *v = arg;
4044
4045                 PDEBUG(4, "VIDIOCGCHAN");
4046
4047                 if ((unsigned)(v->channel) >= ov->num_inputs) {
4048                         err("Invalid channel (%d)", v->channel);
4049                         return -EINVAL;
4050                 }
4051
4052                 v->norm = ov->norm;
4053                 v->type = VIDEO_TYPE_CAMERA;
4054                 v->flags = 0;
4055 //              v->flags |= (ov->has_decoder) ? VIDEO_VC_NORM : 0;
4056                 v->tuners = 0;
4057                 decoder_get_input_name(ov, v->channel, v->name);
4058
4059                 return 0;
4060         }
4061         case VIDIOCSCHAN:
4062         {
4063                 struct video_channel *v = arg;
4064                 int err;
4065
4066                 PDEBUG(4, "VIDIOCSCHAN");
4067
4068                 /* Make sure it's not a camera */
4069                 if (!ov->has_decoder) {
4070                         if (v->channel == 0)
4071                                 return 0;
4072                         else
4073                                 return -EINVAL;
4074                 }
4075
4076                 if (v->norm != VIDEO_MODE_PAL &&
4077                     v->norm != VIDEO_MODE_NTSC &&
4078                     v->norm != VIDEO_MODE_SECAM &&
4079                     v->norm != VIDEO_MODE_AUTO) {
4080                         err("Invalid norm (%d)", v->norm);
4081                         return -EINVAL;
4082                 }
4083
4084                 if ((unsigned)(v->channel) >= ov->num_inputs) {
4085                         err("Invalid channel (%d)", v->channel);
4086                         return -EINVAL;
4087                 }
4088
4089                 err = decoder_set_input(ov, v->channel);
4090                 if (err)
4091                         return err;
4092
4093                 err = decoder_set_norm(ov, v->norm);
4094                 if (err)
4095                         return err;
4096
4097                 return 0;
4098         }
4099         case VIDIOCGPICT:
4100         {
4101                 struct video_picture *p = arg;
4102
4103                 PDEBUG(4, "VIDIOCGPICT");
4104
4105                 memset(p, 0, sizeof(struct video_picture));
4106                 if (sensor_get_picture(ov, p))
4107                         return -EIO;
4108
4109                 /* Can we get these from frame[0]? -claudio? */
4110                 p->depth = ov->frame[0].depth;
4111                 p->palette = ov->frame[0].format;
4112
4113                 return 0;
4114         }
4115         case VIDIOCSPICT:
4116         {
4117                 struct video_picture *p = arg;
4118                 int i, rc;
4119
4120                 PDEBUG(4, "VIDIOCSPICT");
4121
4122                 if (!get_depth(p->palette))
4123                         return -EINVAL;
4124
4125                 if (sensor_set_picture(ov, p))
4126                         return -EIO;
4127
4128                 if (force_palette && p->palette != force_palette) {
4129                         dev_info(&ov->dev->dev, "Palette rejected (%s)\n",
4130                              symbolic(v4l1_plist, p->palette));
4131                         return -EINVAL;
4132                 }
4133
4134                 // FIXME: Format should be independent of frames
4135                 if (p->palette != ov->frame[0].format) {
4136                         PDEBUG(4, "Detected format change");
4137
4138                         rc = ov51x_wait_frames_inactive(ov);
4139                         if (rc)
4140                                 return rc;
4141
4142                         mode_init_regs(ov, ov->frame[0].width,
4143                                 ov->frame[0].height, p->palette, ov->sub_flag);
4144                 }
4145
4146                 PDEBUG(4, "Setting depth=%d, palette=%s",
4147                        p->depth, symbolic(v4l1_plist, p->palette));
4148
4149                 for (i = 0; i < OV511_NUMFRAMES; i++) {
4150                         ov->frame[i].depth = p->depth;
4151                         ov->frame[i].format = p->palette;
4152                 }
4153
4154                 return 0;
4155         }
4156         case VIDIOCGCAPTURE:
4157         {
4158                 int *vf = arg;
4159
4160                 PDEBUG(4, "VIDIOCGCAPTURE");
4161
4162                 ov->sub_flag = *vf;
4163                 return 0;
4164         }
4165         case VIDIOCSCAPTURE:
4166         {
4167                 struct video_capture *vc = arg;
4168
4169                 PDEBUG(4, "VIDIOCSCAPTURE");
4170
4171                 if (vc->flags)
4172                         return -EINVAL;
4173                 if (vc->decimation)
4174                         return -EINVAL;
4175
4176                 vc->x &= ~3L;
4177                 vc->y &= ~1L;
4178                 vc->y &= ~31L;
4179
4180                 if (vc->width == 0)
4181                         vc->width = 32;
4182
4183                 vc->height /= 16;
4184                 vc->height *= 16;
4185                 if (vc->height == 0)
4186                         vc->height = 16;
4187
4188                 ov->subx = vc->x;
4189                 ov->suby = vc->y;
4190                 ov->subw = vc->width;
4191                 ov->subh = vc->height;
4192
4193                 return 0;
4194         }
4195         case VIDIOCSWIN:
4196         {
4197                 struct video_window *vw = arg;
4198                 int i, rc;
4199
4200                 PDEBUG(4, "VIDIOCSWIN: %dx%d", vw->width, vw->height);
4201
4202 #if 0
4203                 if (vw->flags)
4204                         return -EINVAL;
4205                 if (vw->clipcount)
4206                         return -EINVAL;
4207                 if (vw->height != ov->maxheight)
4208                         return -EINVAL;
4209                 if (vw->width != ov->maxwidth)
4210                         return -EINVAL;
4211 #endif
4212
4213                 rc = ov51x_wait_frames_inactive(ov);
4214                 if (rc)
4215                         return rc;
4216
4217                 rc = mode_init_regs(ov, vw->width, vw->height,
4218                         ov->frame[0].format, ov->sub_flag);
4219                 if (rc < 0)
4220                         return rc;
4221
4222                 for (i = 0; i < OV511_NUMFRAMES; i++) {
4223                         ov->frame[i].width = vw->width;
4224                         ov->frame[i].height = vw->height;
4225                 }
4226
4227                 return 0;
4228         }
4229         case VIDIOCGWIN:
4230         {
4231                 struct video_window *vw = arg;
4232
4233                 memset(vw, 0, sizeof(struct video_window));
4234                 vw->x = 0;              /* FIXME */
4235                 vw->y = 0;
4236                 vw->width = ov->frame[0].width;
4237                 vw->height = ov->frame[0].height;
4238                 vw->flags = 30;
4239
4240                 PDEBUG(4, "VIDIOCGWIN: %dx%d", vw->width, vw->height);
4241
4242                 return 0;
4243         }
4244         case VIDIOCGMBUF:
4245         {
4246                 struct video_mbuf *vm = arg;
4247                 int i;
4248
4249                 PDEBUG(4, "VIDIOCGMBUF");
4250
4251                 memset(vm, 0, sizeof(struct video_mbuf));
4252                 vm->size = OV511_NUMFRAMES
4253                            * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
4254                 vm->frames = OV511_NUMFRAMES;
4255
4256                 vm->offsets[0] = 0;
4257                 for (i = 1; i < OV511_NUMFRAMES; i++) {
4258                         vm->offsets[i] = vm->offsets[i-1]
4259                            + MAX_DATA_SIZE(ov->maxwidth, ov->maxheight);
4260                 }
4261
4262                 return 0;
4263         }
4264         case VIDIOCMCAPTURE:
4265         {
4266                 struct video_mmap *vm = arg;
4267                 int rc, depth;
4268                 unsigned int f = vm->frame;
4269
4270                 PDEBUG(4, "VIDIOCMCAPTURE: frame: %d, %dx%d, %s", f, vm->width,
4271                         vm->height, symbolic(v4l1_plist, vm->format));
4272
4273                 depth = get_depth(vm->format);
4274                 if (!depth) {
4275                         PDEBUG(2, "VIDIOCMCAPTURE: invalid format (%s)",
4276                                symbolic(v4l1_plist, vm->format));
4277                         return -EINVAL;
4278                 }
4279
4280                 if (f >= OV511_NUMFRAMES) {
4281                         err("VIDIOCMCAPTURE: invalid frame (%d)", f);
4282                         return -EINVAL;
4283                 }
4284
4285                 if (vm->width > ov->maxwidth
4286                     || vm->height > ov->maxheight) {
4287                         err("VIDIOCMCAPTURE: requested dimensions too big");
4288                         return -EINVAL;
4289                 }
4290
4291                 if (ov->frame[f].grabstate == FRAME_GRABBING) {
4292                         PDEBUG(4, "VIDIOCMCAPTURE: already grabbing");
4293                         return -EBUSY;
4294                 }
4295
4296                 if (force_palette && (vm->format != force_palette)) {
4297                         PDEBUG(2, "palette rejected (%s)",
4298                                symbolic(v4l1_plist, vm->format));
4299                         return -EINVAL;
4300                 }
4301
4302                 if ((ov->frame[f].width != vm->width) ||
4303                     (ov->frame[f].height != vm->height) ||
4304                     (ov->frame[f].format != vm->format) ||
4305                     (ov->frame[f].sub_flag != ov->sub_flag) ||
4306                     (ov->frame[f].depth != depth)) {
4307                         PDEBUG(4, "VIDIOCMCAPTURE: change in image parameters");
4308
4309                         rc = ov51x_wait_frames_inactive(ov);
4310                         if (rc)
4311                                 return rc;
4312
4313                         rc = mode_init_regs(ov, vm->width, vm->height,
4314                                 vm->format, ov->sub_flag);
4315 #if 0
4316                         if (rc < 0) {
4317                                 PDEBUG(1, "Got error while initializing regs ");
4318                                 return ret;
4319                         }
4320 #endif
4321                         ov->frame[f].width = vm->width;
4322                         ov->frame[f].height = vm->height;
4323                         ov->frame[f].format = vm->format;
4324                         ov->frame[f].sub_flag = ov->sub_flag;
4325                         ov->frame[f].depth = depth;
4326                 }
4327
4328                 /* Mark it as ready */
4329                 ov->frame[f].grabstate = FRAME_READY;
4330
4331                 PDEBUG(4, "VIDIOCMCAPTURE: renewing frame %d", f);
4332
4333                 return ov51x_new_frame(ov, f);
4334         }
4335         case VIDIOCSYNC:
4336         {
4337                 unsigned int fnum = *((unsigned int *) arg);
4338                 struct ov511_frame *frame;
4339                 int rc;
4340
4341                 if (fnum >= OV511_NUMFRAMES) {
4342                         err("VIDIOCSYNC: invalid frame (%d)", fnum);
4343                         return -EINVAL;
4344                 }
4345
4346                 frame = &ov->frame[fnum];
4347
4348                 PDEBUG(4, "syncing to frame %d, grabstate = %d", fnum,
4349                        frame->grabstate);
4350
4351                 switch (frame->grabstate) {
4352                 case FRAME_UNUSED:
4353                         return -EINVAL;
4354                 case FRAME_READY:
4355                 case FRAME_GRABBING:
4356                 case FRAME_ERROR:
4357 redo:
4358                         if (!ov->dev)
4359                                 return -EIO;
4360
4361                         rc = wait_event_interruptible(frame->wq,
4362                             (frame->grabstate == FRAME_DONE)
4363                             || (frame->grabstate == FRAME_ERROR));
4364
4365                         if (rc)
4366                                 return rc;
4367
4368                         if (frame->grabstate == FRAME_ERROR) {
4369                                 if ((rc = ov51x_new_frame(ov, fnum)) < 0)
4370                                         return rc;
4371                                 goto redo;
4372                         }
4373                         /* Fall through */
4374                 case FRAME_DONE:
4375                         if (ov->snap_enabled && !frame->snapshot) {
4376                                 if ((rc = ov51x_new_frame(ov, fnum)) < 0)
4377                                         return rc;
4378                                 goto redo;
4379                         }
4380
4381                         frame->grabstate = FRAME_UNUSED;
4382
4383                         /* Reset the hardware snapshot button */
4384                         /* FIXME - Is this the best place for this? */
4385                         if ((ov->snap_enabled) && (frame->snapshot)) {
4386                                 frame->snapshot = 0;
4387                                 ov51x_clear_snapshot(ov);
4388                         }
4389
4390                         /* Decompression, format conversion, etc... */
4391                         ov51x_postprocess(ov, frame);
4392
4393                         break;
4394                 } /* end switch */
4395
4396                 return 0;
4397         }
4398         case VIDIOCGFBUF:
4399         {
4400                 struct video_buffer *vb = arg;
4401
4402                 PDEBUG(4, "VIDIOCGFBUF");
4403
4404                 memset(vb, 0, sizeof(struct video_buffer));
4405
4406                 return 0;
4407         }
4408         case VIDIOCGUNIT:
4409         {
4410                 struct video_unit *vu = arg;
4411
4412                 PDEBUG(4, "VIDIOCGUNIT");
4413
4414                 memset(vu, 0, sizeof(struct video_unit));
4415
4416                 vu->video = ov->vdev->minor;
4417                 vu->vbi = VIDEO_NO_UNIT;
4418                 vu->radio = VIDEO_NO_UNIT;
4419                 vu->audio = VIDEO_NO_UNIT;
4420                 vu->teletext = VIDEO_NO_UNIT;
4421
4422                 return 0;
4423         }
4424         case OV511IOC_WI2C:
4425         {
4426                 struct ov511_i2c_struct *w = arg;
4427
4428                 return i2c_w_slave(ov, w->slave, w->reg, w->value, w->mask);
4429         }
4430         case OV511IOC_RI2C:
4431         {
4432                 struct ov511_i2c_struct *r = arg;
4433                 int rc;
4434
4435                 rc = i2c_r_slave(ov, r->slave, r->reg);
4436                 if (rc < 0)
4437                         return rc;
4438
4439                 r->value = rc;
4440                 return 0;
4441         }
4442         default:
4443                 PDEBUG(3, "Unsupported IOCtl: 0x%X", cmd);
4444                 return -ENOIOCTLCMD;
4445         } /* end switch */
4446
4447         return 0;
4448 }
4449
4450 static int
4451 ov51x_v4l1_ioctl(struct inode *inode, struct file *file,
4452                  unsigned int cmd, unsigned long arg)
4453 {
4454         struct video_device *vdev = file->private_data;
4455         struct usb_ov511 *ov = video_get_drvdata(vdev);
4456         int rc;
4457
4458         if (mutex_lock_interruptible(&ov->lock))
4459                 return -EINTR;
4460
4461         rc = video_usercopy(inode, file, cmd, arg, ov51x_v4l1_ioctl_internal);
4462
4463         mutex_unlock(&ov->lock);
4464         return rc;
4465 }
4466
4467 static ssize_t
4468 ov51x_v4l1_read(struct file *file, char __user *buf, size_t cnt, loff_t *ppos)
4469 {
4470         struct video_device *vdev = file->private_data;
4471         int noblock = file->f_flags&O_NONBLOCK;
4472         unsigned long count = cnt;
4473         struct usb_ov511 *ov = video_get_drvdata(vdev);
4474         int i, rc = 0, frmx = -1;
4475         struct ov511_frame *frame;
4476
4477         if (mutex_lock_interruptible(&ov->lock))
4478                 return -EINTR;
4479
4480         PDEBUG(4, "%ld bytes, noblock=%d", count, noblock);
4481
4482         if (!vdev || !buf) {
4483                 rc = -EFAULT;
4484                 goto error;
4485         }
4486
4487         if (!ov->dev) {
4488                 rc = -EIO;
4489                 goto error;
4490         }
4491
4492 // FIXME: Only supports two frames
4493         /* See if a frame is completed, then use it. */
4494         if (ov->frame[0].grabstate >= FRAME_DONE)       /* _DONE or _ERROR */
4495                 frmx = 0;
4496         else if (ov->frame[1].grabstate >= FRAME_DONE)/* _DONE or _ERROR */
4497                 frmx = 1;
4498
4499         /* If nonblocking we return immediately */
4500         if (noblock && (frmx == -1)) {
4501                 rc = -EAGAIN;
4502                 goto error;
4503         }
4504
4505         /* If no FRAME_DONE, look for a FRAME_GRABBING state. */
4506         /* See if a frame is in process (grabbing), then use it. */
4507         if (frmx == -1) {
4508                 if (ov->frame[0].grabstate == FRAME_GRABBING)
4509                         frmx = 0;
4510                 else if (ov->frame[1].grabstate == FRAME_GRABBING)
4511                         frmx = 1;
4512         }
4513
4514         /* If no frame is active, start one. */
4515         if (frmx == -1) {
4516                 if ((rc = ov51x_new_frame(ov, frmx = 0))) {
4517                         err("read: ov51x_new_frame error");
4518                         goto error;
4519                 }
4520         }
4521
4522         frame = &ov->frame[frmx];
4523
4524 restart:
4525         if (!ov->dev) {
4526                 rc = -EIO;
4527                 goto error;
4528         }
4529
4530         /* Wait while we're grabbing the image */
4531         PDEBUG(4, "Waiting image grabbing");
4532         rc = wait_event_interruptible(frame->wq,
4533                 (frame->grabstate == FRAME_DONE)
4534                 || (frame->grabstate == FRAME_ERROR));
4535
4536         if (rc)
4537                 goto error;
4538
4539         PDEBUG(4, "Got image, frame->grabstate = %d", frame->grabstate);
4540         PDEBUG(4, "bytes_recvd = %d", frame->bytes_recvd);
4541
4542         if (frame->grabstate == FRAME_ERROR) {
4543                 frame->bytes_read = 0;
4544                 err("** ick! ** Errored frame %d", ov->curframe);
4545                 if (ov51x_new_frame(ov, frmx)) {
4546                         err("read: ov51x_new_frame error");
4547                         goto error;
4548                 }
4549                 goto restart;
4550         }
4551
4552
4553         /* Repeat until we get a snapshot frame */
4554         if (ov->snap_enabled)
4555                 PDEBUG(4, "Waiting snapshot frame");
4556         if (ov->snap_enabled && !frame->snapshot) {
4557                 frame->bytes_read = 0;
4558                 if ((rc = ov51x_new_frame(ov, frmx))) {
4559                         err("read: ov51x_new_frame error");
4560                         goto error;
4561                 }
4562                 goto restart;
4563         }
4564
4565         /* Clear the snapshot */
4566         if (ov->snap_enabled && frame->snapshot) {
4567                 frame->snapshot = 0;
4568                 ov51x_clear_snapshot(ov);
4569         }
4570
4571         /* Decompression, format conversion, etc... */
4572         ov51x_postprocess(ov, frame);
4573
4574         PDEBUG(4, "frmx=%d, bytes_read=%ld, length=%ld", frmx,
4575                 frame->bytes_read,
4576                 get_frame_length(frame));
4577
4578         /* copy bytes to user space; we allow for partials reads */
4579 //      if ((count + frame->bytes_read)
4580 //          > get_frame_length((struct ov511_frame *)frame))
4581 //              count = frame->scanlength - frame->bytes_read;
4582
4583         /* FIXME - count hardwired to be one frame... */
4584         count = get_frame_length(frame);
4585
4586         PDEBUG(4, "Copy to user space: %ld bytes", count);
4587         if ((i = copy_to_user(buf, frame->data + frame->bytes_read, count))) {
4588                 PDEBUG(4, "Copy failed! %d bytes not copied", i);
4589                 rc = -EFAULT;
4590                 goto error;
4591         }
4592
4593         frame->bytes_read += count;
4594         PDEBUG(4, "{copy} count used=%ld, new bytes_read=%ld",
4595                 count, frame->bytes_read);
4596
4597         /* If all data have been read... */
4598         if (frame->bytes_read
4599             >= get_frame_length(frame)) {
4600                 frame->bytes_read = 0;
4601
4602 // FIXME: Only supports two frames
4603                 /* Mark it as available to be used again. */
4604                 ov->frame[frmx].grabstate = FRAME_UNUSED;
4605                 if ((rc = ov51x_new_frame(ov, !frmx))) {
4606                         err("ov51x_new_frame returned error");
4607                         goto error;
4608                 }
4609         }
4610
4611         PDEBUG(4, "read finished, returning %ld (sweet)", count);
4612
4613         mutex_unlock(&ov->lock);
4614         return count;
4615
4616 error:
4617         mutex_unlock(&ov->lock);
4618         return rc;
4619 }
4620
4621 static int
4622 ov51x_v4l1_mmap(struct file *file, struct vm_area_struct *vma)
4623 {
4624         struct video_device *vdev = file->private_data;
4625         unsigned long start = vma->vm_start;
4626         unsigned long size  = vma->vm_end - vma->vm_start;
4627         struct usb_ov511 *ov = video_get_drvdata(vdev);
4628         unsigned long page, pos;
4629
4630         if (ov->dev == NULL)
4631                 return -EIO;
4632
4633         PDEBUG(4, "mmap: %ld (%lX) bytes", size, size);
4634
4635         if (size > (((OV511_NUMFRAMES
4636                       * MAX_DATA_SIZE(ov->maxwidth, ov->maxheight)
4637                       + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))))
4638                 return -EINVAL;
4639
4640         if (mutex_lock_interruptible(&ov->lock))
4641                 return -EINTR;
4642
4643         pos = (unsigned long)ov->fbuf;
4644         while (size > 0) {
4645                 page = vmalloc_to_pfn((void *)pos);
4646                 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) {
4647                         mutex_unlock(&ov->lock);
4648                         return -EAGAIN;
4649                 }
4650                 start += PAGE_SIZE;
4651                 pos += PAGE_SIZE;
4652                 if (size > PAGE_SIZE)
4653                         size -= PAGE_SIZE;
4654                 else
4655                         size = 0;
4656         }
4657
4658         mutex_unlock(&ov->lock);
4659         return 0;
4660 }
4661
4662 static const struct file_operations ov511_fops = {
4663         .owner =        THIS_MODULE,
4664         .open =         ov51x_v4l1_open,
4665         .release =      ov51x_v4l1_close,
4666         .read =         ov51x_v4l1_read,
4667         .mmap =         ov51x_v4l1_mmap,
4668         .ioctl =        ov51x_v4l1_ioctl,
4669 #ifdef CONFIG_COMPAT
4670         .compat_ioctl = v4l_compat_ioctl32,
4671 #endif
4672         .llseek =       no_llseek,
4673 };
4674
4675 static struct video_device vdev_template = {
4676         .name =         "OV511 USB Camera",
4677         .fops =         &ov511_fops,
4678         .release =      video_device_release,
4679         .minor =        -1,
4680 };
4681
4682 /****************************************************************************
4683  *
4684  * OV511 and sensor configuration
4685  *
4686  ***************************************************************************/
4687
4688 /* This initializes the OV7610, OV7620, or OV76BE sensor. The OV76BE uses
4689  * the same register settings as the OV7610, since they are very similar.
4690  */
4691 static int
4692 ov7xx0_configure(struct usb_ov511 *ov)
4693 {
4694         int i, success;
4695         int rc;
4696
4697         /* Lawrence Glaister <lg@jfm.bc.ca> reports:
4698          *
4699          * Register 0x0f in the 7610 has the following effects:
4700          *
4701          * 0x85 (AEC method 1): Best overall, good contrast range
4702          * 0x45 (AEC method 2): Very overexposed
4703          * 0xa5 (spec sheet default): Ok, but the black level is
4704          *      shifted resulting in loss of contrast
4705          * 0x05 (old driver setting): very overexposed, too much
4706          *      contrast
4707          */
4708         static struct ov511_regvals aRegvalsNorm7610[] = {
4709                 { OV511_I2C_BUS, 0x10, 0xff },
4710                 { OV511_I2C_BUS, 0x16, 0x06 },
4711                 { OV511_I2C_BUS, 0x28, 0x24 },
4712                 { OV511_I2C_BUS, 0x2b, 0xac },
4713                 { OV511_I2C_BUS, 0x12, 0x00 },
4714                 { OV511_I2C_BUS, 0x38, 0x81 },
4715                 { OV511_I2C_BUS, 0x28, 0x24 },  /* 0c */
4716                 { OV511_I2C_BUS, 0x0f, 0x85 },  /* lg's setting */
4717                 { OV511_I2C_BUS, 0x15, 0x01 },
4718                 { OV511_I2C_BUS, 0x20, 0x1c },
4719                 { OV511_I2C_BUS, 0x23, 0x2a },
4720                 { OV511_I2C_BUS, 0x24, 0x10 },
4721                 { OV511_I2C_BUS, 0x25, 0x8a },
4722                 { OV511_I2C_BUS, 0x26, 0xa2 },
4723                 { OV511_I2C_BUS, 0x27, 0xc2 },
4724                 { OV511_I2C_BUS, 0x2a, 0x04 },
4725                 { OV511_I2C_BUS, 0x2c, 0xfe },
4726                 { OV511_I2C_BUS, 0x2d, 0x93 },
4727                 { OV511_I2C_BUS, 0x30, 0x71 },
4728                 { OV511_I2C_BUS, 0x31, 0x60 },
4729                 { OV511_I2C_BUS, 0x32, 0x26 },
4730                 { OV511_I2C_BUS, 0x33, 0x20 },
4731                 { OV511_I2C_BUS, 0x34, 0x48 },
4732                 { OV511_I2C_BUS, 0x12, 0x24 },
4733                 { OV511_I2C_BUS, 0x11, 0x01 },
4734                 { OV511_I2C_BUS, 0x0c, 0x24 },
4735                 { OV511_I2C_BUS, 0x0d, 0x24 },
4736                 { OV511_DONE_BUS, 0x0, 0x00 },
4737         };
4738
4739         static struct ov511_regvals aRegvalsNorm7620[] = {
4740                 { OV511_I2C_BUS, 0x00, 0x00 },
4741                 { OV511_I2C_BUS, 0x01, 0x80 },
4742                 { OV511_I2C_BUS, 0x02, 0x80 },
4743                 { OV511_I2C_BUS, 0x03, 0xc0 },
4744                 { OV511_I2C_BUS, 0x06, 0x60 },
4745                 { OV511_I2C_BUS, 0x07, 0x00 },
4746                 { OV511_I2C_BUS, 0x0c, 0x24 },
4747                 { OV511_I2C_BUS, 0x0c, 0x24 },
4748                 { OV511_I2C_BUS, 0x0d, 0x24 },
4749                 { OV511_I2C_BUS, 0x11, 0x01 },
4750                 { OV511_I2C_BUS, 0x12, 0x24 },
4751                 { OV511_I2C_BUS, 0x13, 0x01 },
4752                 { OV511_I2C_BUS, 0x14, 0x84 },
4753                 { OV511_I2C_BUS, 0x15, 0x01 },
4754                 { OV511_I2C_BUS, 0x16, 0x03 },
4755                 { OV511_I2C_BUS, 0x17, 0x2f },
4756                 { OV511_I2C_BUS, 0x18, 0xcf },
4757                 { OV511_I2C_BUS, 0x19, 0x06 },
4758                 { OV511_I2C_BUS, 0x1a, 0xf5 },
4759                 { OV511_I2C_BUS, 0x1b, 0x00 },
4760                 { OV511_I2C_BUS, 0x20, 0x18 },
4761                 { OV511_I2C_BUS, 0x21, 0x80 },
4762                 { OV511_I2C_BUS, 0x22, 0x80 },
4763                 { OV511_I2C_BUS, 0x23, 0x00 },
4764                 { OV511_I2C_BUS, 0x26, 0xa2 },
4765                 { OV511_I2C_BUS, 0x27, 0xea },
4766                 { OV511_I2C_BUS, 0x28, 0x20 },
4767                 { OV511_I2C_BUS, 0x29, 0x00 },
4768                 { OV511_I2C_BUS, 0x2a, 0x10 },
4769                 { OV511_I2C_BUS, 0x2b, 0x00 },
4770                 { OV511_I2C_BUS, 0x2c, 0x88 },
4771                 { OV511_I2C_BUS, 0x2d, 0x91 },
4772                 { OV511_I2C_BUS, 0x2e, 0x80 },
4773                 { OV511_I2C_BUS, 0x2f, 0x44 },
4774                 { OV511_I2C_BUS, 0x60, 0x27 },
4775                 { OV511_I2C_BUS, 0x61, 0x02 },
4776                 { OV511_I2C_BUS, 0x62, 0x5f },
4777                 { OV511_I2C_BUS, 0x63, 0xd5 },
4778                 { OV511_I2C_BUS, 0x64, 0x57 },
4779                 { OV511_I2C_BUS, 0x65, 0x83 },
4780                 { OV511_I2C_BUS, 0x66, 0x55 },
4781                 { OV511_I2C_BUS, 0x67, 0x92 },
4782                 { OV511_I2C_BUS, 0x68, 0xcf },
4783                 { OV511_I2C_BUS, 0x69, 0x76 },
4784                 { OV511_I2C_BUS, 0x6a, 0x22 },
4785                 { OV511_I2C_BUS, 0x6b, 0x00 },
4786                 { OV511_I2C_BUS, 0x6c, 0x02 },
4787                 { OV511_I2C_BUS, 0x6d, 0x44 },
4788                 { OV511_I2C_BUS, 0x6e, 0x80 },
4789                 { OV511_I2C_BUS, 0x6f, 0x1d },
4790                 { OV511_I2C_BUS, 0x70, 0x8b },
4791                 { OV511_I2C_BUS, 0x71, 0x00 },
4792                 { OV511_I2C_BUS, 0x72, 0x14 },
4793                 { OV511_I2C_BUS, 0x73, 0x54 },
4794                 { OV511_I2C_BUS, 0x74, 0x00 },
4795                 { OV511_I2C_BUS, 0x75, 0x8e },
4796                 { OV511_I2C_BUS, 0x76, 0x00 },
4797                 { OV511_I2C_BUS, 0x77, 0xff },
4798                 { OV511_I2C_BUS, 0x78, 0x80 },
4799                 { OV511_I2C_BUS, 0x79, 0x80 },
4800                 { OV511_I2C_BUS, 0x7a, 0x80 },
4801                 { OV511_I2C_BUS, 0x7b, 0xe2 },
4802                 { OV511_I2C_BUS, 0x7c, 0x00 },
4803                 { OV511_DONE_BUS, 0x0, 0x00 },
4804         };
4805
4806         PDEBUG(4, "starting configuration");
4807
4808         /* This looks redundant, but is necessary for WebCam 3 */
4809         ov->primary_i2c_slave = OV7xx0_SID;
4810         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
4811                 return -1;
4812
4813         if (init_ov_sensor(ov) >= 0) {
4814                 PDEBUG(1, "OV7xx0 sensor initalized (method 1)");
4815         } else {
4816                 /* Reset the 76xx */
4817                 if (i2c_w(ov, 0x12, 0x80) < 0)
4818                         return -1;
4819
4820                 /* Wait for it to initialize */
4821                 msleep(150);
4822
4823                 i = 0;
4824                 success = 0;
4825                 while (i <= i2c_detect_tries) {
4826                         if ((i2c_r(ov, OV7610_REG_ID_HIGH) == 0x7F) &&
4827                             (i2c_r(ov, OV7610_REG_ID_LOW) == 0xA2)) {
4828                                 success = 1;
4829                                 break;
4830                         } else {
4831                                 i++;
4832                         }
4833                 }
4834
4835 // Was (i == i2c_detect_tries) previously. This obviously used to always report
4836 // success. Whether anyone actually depended on that bug is unknown
4837                 if ((i >= i2c_detect_tries) && (success == 0)) {
4838                         err("Failed to read sensor ID. You might not have an");
4839                         err("OV7610/20, or it may be not responding. Report");
4840                         err("this to " EMAIL);
4841                         err("This is only a warning. You can attempt to use");
4842                         err("your camera anyway");
4843 // Only issue a warning for now
4844 //                      return -1;
4845                 } else {
4846                         PDEBUG(1, "OV7xx0 initialized (method 2, %dx)", i+1);
4847                 }
4848         }
4849
4850         /* Detect sensor (sub)type */
4851         rc = i2c_r(ov, OV7610_REG_COM_I);
4852
4853         if (rc < 0) {
4854                 err("Error detecting sensor type");
4855                 return -1;
4856         } else if ((rc & 3) == 3) {
4857                 dev_info(&ov->dev->dev, "Sensor is an OV7610\n");
4858                 ov->sensor = SEN_OV7610;
4859         } else if ((rc & 3) == 1) {
4860                 /* I don't know what's different about the 76BE yet. */
4861                 if (i2c_r(ov, 0x15) & 1)
4862                         dev_info(&ov->dev->dev, "Sensor is an OV7620AE\n");
4863                 else
4864                         dev_info(&ov->dev->dev, "Sensor is an OV76BE\n");
4865
4866                 /* OV511+ will return all zero isoc data unless we
4867                  * configure the sensor as a 7620. Someone needs to
4868                  * find the exact reg. setting that causes this. */
4869                 if (ov->bridge == BRG_OV511PLUS) {
4870                         dev_info(&ov->dev->dev,
4871                                  "Enabling 511+/7620AE workaround\n");
4872                         ov->sensor = SEN_OV7620;
4873                 } else {
4874                         ov->sensor = SEN_OV76BE;
4875                 }
4876         } else if ((rc & 3) == 0) {
4877                 dev_info(&ov->dev->dev, "Sensor is an OV7620\n");
4878                 ov->sensor = SEN_OV7620;
4879         } else {
4880                 err("Unknown image sensor version: %d", rc & 3);
4881                 return -1;
4882         }
4883
4884         if (ov->sensor == SEN_OV7620) {
4885                 PDEBUG(4, "Writing 7620 registers");
4886                 if (write_regvals(ov, aRegvalsNorm7620))
4887                         return -1;
4888         } else {
4889                 PDEBUG(4, "Writing 7610 registers");
4890                 if (write_regvals(ov, aRegvalsNorm7610))
4891                         return -1;
4892         }
4893
4894         /* Set sensor-specific vars */
4895         ov->maxwidth = 640;
4896         ov->maxheight = 480;
4897         ov->minwidth = 64;
4898         ov->minheight = 48;
4899
4900         // FIXME: These do not match the actual settings yet
4901         ov->brightness = 0x80 << 8;
4902         ov->contrast = 0x80 << 8;
4903         ov->colour = 0x80 << 8;
4904         ov->hue = 0x80 << 8;
4905
4906         return 0;
4907 }
4908
4909 /* This initializes the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
4910 static int
4911 ov6xx0_configure(struct usb_ov511 *ov)
4912 {
4913         int rc;
4914
4915         static struct ov511_regvals aRegvalsNorm6x20[] = {
4916                 { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4917                 { OV511_I2C_BUS, 0x11, 0x01 },
4918                 { OV511_I2C_BUS, 0x03, 0x60 },
4919                 { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4920                 { OV511_I2C_BUS, 0x07, 0xa8 },
4921                 /* The ratio of 0x0c and 0x0d  controls the white point */
4922                 { OV511_I2C_BUS, 0x0c, 0x24 },
4923                 { OV511_I2C_BUS, 0x0d, 0x24 },
4924                 { OV511_I2C_BUS, 0x0f, 0x15 }, /* COMS */
4925                 { OV511_I2C_BUS, 0x10, 0x75 }, /* AEC Exposure time */
4926                 { OV511_I2C_BUS, 0x12, 0x24 }, /* Enable AGC */
4927                 { OV511_I2C_BUS, 0x14, 0x04 },
4928                 /* 0x16: 0x06 helps frame stability with moving objects */
4929                 { OV511_I2C_BUS, 0x16, 0x06 },
4930 //              { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4931                 { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4932                 /* 0x28: 0x05 Selects RGB format if RGB on */
4933                 { OV511_I2C_BUS, 0x28, 0x05 },
4934                 { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4935 //              { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4936                 { OV511_I2C_BUS, 0x2d, 0x99 },
4937                 { OV511_I2C_BUS, 0x33, 0xa0 }, /* Color Processing Parameter */
4938                 { OV511_I2C_BUS, 0x34, 0xd2 }, /* Max A/D range */
4939                 { OV511_I2C_BUS, 0x38, 0x8b },
4940                 { OV511_I2C_BUS, 0x39, 0x40 },
4941
4942                 { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4943                 { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4944                 { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4945
4946                 { OV511_I2C_BUS, 0x3d, 0x80 },
4947                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4948                  * control the color balance */
4949                 { OV511_I2C_BUS, 0x4a, 0x80 },
4950                 { OV511_I2C_BUS, 0x4b, 0x80 },
4951                 { OV511_I2C_BUS, 0x4d, 0xd2 }, /* This reduces noise a bit */
4952                 { OV511_I2C_BUS, 0x4e, 0xc1 },
4953                 { OV511_I2C_BUS, 0x4f, 0x04 },
4954 // Do 50-53 have any effect?
4955 // Toggle 0x12[2] off and on here?
4956                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
4957         };
4958
4959         static struct ov511_regvals aRegvalsNorm6x30[] = {
4960         /*OK*/  { OV511_I2C_BUS, 0x12, 0x80 }, /* reset */
4961                 { OV511_I2C_BUS, 0x11, 0x00 },
4962         /*OK*/  { OV511_I2C_BUS, 0x03, 0x60 },
4963         /*0A?*/ { OV511_I2C_BUS, 0x05, 0x7f }, /* For when autoadjust is off */
4964                 { OV511_I2C_BUS, 0x07, 0xa8 },
4965                 /* The ratio of 0x0c and 0x0d  controls the white point */
4966         /*OK*/  { OV511_I2C_BUS, 0x0c, 0x24 },
4967         /*OK*/  { OV511_I2C_BUS, 0x0d, 0x24 },
4968         /*A*/   { OV511_I2C_BUS, 0x0e, 0x20 },
4969 //      /*04?*/ { OV511_I2C_BUS, 0x14, 0x80 },
4970                 { OV511_I2C_BUS, 0x16, 0x03 },
4971 //      /*OK*/  { OV511_I2C_BUS, 0x20, 0x30 }, /* Aperture correction enable */
4972                 // 21 & 22? The suggested values look wrong. Go with default
4973         /*A*/   { OV511_I2C_BUS, 0x23, 0xc0 },
4974         /*A*/   { OV511_I2C_BUS, 0x25, 0x9a }, // Check this against default
4975 //      /*OK*/  { OV511_I2C_BUS, 0x26, 0xb2 }, /* BLC enable */
4976
4977                 /* 0x28: 0x05 Selects RGB format if RGB on */
4978 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x05 },
4979 //      /*04?*/ { OV511_I2C_BUS, 0x28, 0x45 }, // DEBUG: Tristate UV bus
4980
4981         /*OK*/  { OV511_I2C_BUS, 0x2a, 0x04 }, /* Disable framerate adjust */
4982 //      /*OK*/  { OV511_I2C_BUS, 0x2b, 0xac }, /* Framerate; Set 2a[7] first */
4983                 { OV511_I2C_BUS, 0x2d, 0x99 },
4984 //      /*A*/   { OV511_I2C_BUS, 0x33, 0x26 }, // Reserved bits on 6620
4985 //      /*d2?*/ { OV511_I2C_BUS, 0x34, 0x03 }, /* Max A/D range */
4986 //      /*8b?*/ { OV511_I2C_BUS, 0x38, 0x83 },
4987 //      /*40?*/ { OV511_I2C_BUS, 0x39, 0xc0 }, // 6630 adds bit 7
4988 //              { OV511_I2C_BUS, 0x3c, 0x39 }, /* Enable AEC mode changing */
4989 //              { OV511_I2C_BUS, 0x3c, 0x3c }, /* Change AEC mode */
4990 //              { OV511_I2C_BUS, 0x3c, 0x24 }, /* Disable AEC mode changing */
4991                 { OV511_I2C_BUS, 0x3d, 0x80 },
4992 //      /*A*/   { OV511_I2C_BUS, 0x3f, 0x0e },
4993
4994                 /* These next two registers (0x4a, 0x4b) are undocumented. They
4995                  * control the color balance */
4996 //      /*OK?*/ { OV511_I2C_BUS, 0x4a, 0x80 }, // Check these
4997 //      /*OK?*/ { OV511_I2C_BUS, 0x4b, 0x80 },
4998                 { OV511_I2C_BUS, 0x4d, 0x10 }, /* U = 0.563u, V = 0.714v */
4999         /*c1?*/ { OV511_I2C_BUS, 0x4e, 0x40 },
5000
5001                 /* UV average mode, color killer: strongest */
5002                 { OV511_I2C_BUS, 0x4f, 0x07 },
5003
5004                 { OV511_I2C_BUS, 0x54, 0x23 }, /* Max AGC gain: 18dB */
5005                 { OV511_I2C_BUS, 0x57, 0x81 }, /* (default) */
5006                 { OV511_I2C_BUS, 0x59, 0x01 }, /* AGC dark current comp: +1 */
5007                 { OV511_I2C_BUS, 0x5a, 0x2c }, /* (undocumented) */
5008                 { OV511_I2C_BUS, 0x5b, 0x0f }, /* AWB chrominance levels */
5009 //              { OV511_I2C_BUS, 0x5c, 0x10 },
5010                 { OV511_DONE_BUS, 0x0, 0x00 },  /* END MARKER */
5011         };
5012
5013         PDEBUG(4, "starting sensor configuration");
5014
5015         if (init_ov_sensor(ov) < 0) {
5016                 err("Failed to read sensor ID. You might not have an OV6xx0,");
5017                 err("or it may be not responding. Report this to " EMAIL);
5018                 return -1;
5019         } else {
5020                 PDEBUG(1, "OV6xx0 sensor detected");
5021         }
5022
5023         /* Detect sensor (sub)type */
5024         rc = i2c_r(ov, OV7610_REG_COM_I);
5025
5026         if (rc < 0) {
5027                 err("Error detecting sensor type");
5028                 return -1;
5029         }
5030
5031         if ((rc & 3) == 0) {
5032                 ov->sensor = SEN_OV6630;
5033                 dev_info(&ov->dev->dev, "Sensor is an OV6630\n");
5034         } else if ((rc & 3) == 1) {
5035                 ov->sensor = SEN_OV6620;
5036                 dev_info(&ov->dev->dev, "Sensor is an OV6620\n");
5037         } else if ((rc & 3) == 2) {
5038                 ov->sensor = SEN_OV6630;
5039                 dev_info(&ov->dev->dev, "Sensor is an OV6630AE\n");
5040         } else if ((rc & 3) == 3) {
5041                 ov->sensor = SEN_OV6630;
5042                 dev_info(&ov->dev->dev, "Sensor is an OV6630AF\n");
5043         }
5044
5045         /* Set sensor-specific vars */
5046         ov->maxwidth = 352;
5047         ov->maxheight = 288;
5048         ov->minwidth = 64;
5049         ov->minheight = 48;
5050
5051         // FIXME: These do not match the actual settings yet
5052         ov->brightness = 0x80 << 8;
5053         ov->contrast = 0x80 << 8;
5054         ov->colour = 0x80 << 8;
5055         ov->hue = 0x80 << 8;
5056
5057         if (ov->sensor == SEN_OV6620) {
5058                 PDEBUG(4, "Writing 6x20 registers");
5059                 if (write_regvals(ov, aRegvalsNorm6x20))
5060                         return -1;
5061         } else {
5062                 PDEBUG(4, "Writing 6x30 registers");
5063                 if (write_regvals(ov, aRegvalsNorm6x30))
5064                         return -1;
5065         }
5066
5067         return 0;
5068 }
5069
5070 /* This initializes the KS0127 and KS0127B video decoders. */
5071 static int
5072 ks0127_configure(struct usb_ov511 *ov)
5073 {
5074         int rc;
5075
5076 // FIXME: I don't know how to sync or reset it yet
5077 #if 0
5078         if (ov51x_init_ks_sensor(ov) < 0) {
5079                 err("Failed to initialize the KS0127");
5080                 return -1;
5081         } else {
5082                 PDEBUG(1, "KS012x(B) sensor detected");
5083         }
5084 #endif
5085
5086         /* Detect decoder subtype */
5087         rc = i2c_r(ov, 0x00);
5088         if (rc < 0) {
5089                 err("Error detecting sensor type");
5090                 return -1;
5091         } else if (rc & 0x08) {
5092                 rc = i2c_r(ov, 0x3d);
5093                 if (rc < 0) {
5094                         err("Error detecting sensor type");
5095                         return -1;
5096                 } else if ((rc & 0x0f) == 0) {
5097                         dev_info(&ov->dev->dev, "Sensor is a KS0127\n");
5098                         ov->sensor = SEN_KS0127;
5099                 } else if ((rc & 0x0f) == 9) {
5100                         dev_info(&ov->dev->dev, "Sensor is a KS0127B Rev. A\n");
5101                         ov->sensor = SEN_KS0127B;
5102                 }
5103         } else {
5104                 err("Error: Sensor is an unsupported KS0122");
5105                 return -1;
5106         }
5107
5108         /* Set sensor-specific vars */
5109         ov->maxwidth = 640;
5110         ov->maxheight = 480;
5111         ov->minwidth = 64;
5112         ov->minheight = 48;
5113
5114         // FIXME: These do not match the actual settings yet
5115         ov->brightness = 0x80 << 8;
5116         ov->contrast = 0x80 << 8;
5117         ov->colour = 0x80 << 8;
5118         ov->hue = 0x80 << 8;
5119
5120         /* This device is not supported yet. Bail out now... */
5121         err("This sensor is not supported yet.");
5122         return -1;
5123
5124         return 0;
5125 }
5126
5127 /* This initializes the SAA7111A video decoder. */
5128 static int
5129 saa7111a_configure(struct usb_ov511 *ov)
5130 {
5131         int rc;
5132
5133         /* Since there is no register reset command, all registers must be
5134          * written, otherwise gives erratic results */
5135         static struct ov511_regvals aRegvalsNormSAA7111A[] = {
5136                 { OV511_I2C_BUS, 0x06, 0xce },
5137                 { OV511_I2C_BUS, 0x07, 0x00 },
5138                 { OV511_I2C_BUS, 0x10, 0x44 }, /* YUV422, 240/286 lines */
5139                 { OV511_I2C_BUS, 0x0e, 0x01 }, /* NTSC M or PAL BGHI */
5140                 { OV511_I2C_BUS, 0x00, 0x00 },
5141                 { OV511_I2C_BUS, 0x01, 0x00 },
5142                 { OV511_I2C_BUS, 0x03, 0x23 },
5143                 { OV511_I2C_BUS, 0x04, 0x00 },
5144                 { OV511_I2C_BUS, 0x05, 0x00 },
5145                 { OV511_I2C_BUS, 0x08, 0xc8 }, /* Auto field freq */
5146                 { OV511_I2C_BUS, 0x09, 0x01 }, /* Chrom. trap off, APER=0.25 */
5147                 { OV511_I2C_BUS, 0x0a, 0x80 }, /* BRIG=128 */
5148                 { OV511_I2C_BUS, 0x0b, 0x40 }, /* CONT=1.0 */
5149                 { OV511_I2C_BUS, 0x0c, 0x40 }, /* SATN=1.0 */
5150                 { OV511_I2C_BUS, 0x0d, 0x00 }, /* HUE=0 */
5151                 { OV511_I2C_BUS, 0x0f, 0x00 },
5152                 { OV511_I2C_BUS, 0x11, 0x0c },
5153                 { OV511_I2C_BUS, 0x12, 0x00 },
5154                 { OV511_I2C_BUS, 0x13, 0x00 },
5155                 { OV511_I2C_BUS, 0x14, 0x00 },
5156                 { OV511_I2C_BUS, 0x15, 0x00 },
5157                 { OV511_I2C_BUS, 0x16, 0x00 },
5158                 { OV511_I2C_BUS, 0x17, 0x00 },
5159                 { OV511_I2C_BUS, 0x02, 0xc0 },  /* Composite input 0 */
5160                 { OV511_DONE_BUS, 0x0, 0x00 },
5161         };
5162
5163 // FIXME: I don't know how to sync or reset it yet
5164 #if 0
5165         if (ov51x_init_saa_sensor(ov) < 0) {
5166                 err("Failed to initialize the SAA7111A");
5167                 return -1;
5168         } else {
5169                 PDEBUG(1, "SAA7111A sensor detected");
5170         }
5171 #endif
5172
5173         /* 640x480 not supported with PAL */
5174         if (ov->pal) {
5175                 ov->maxwidth = 320;
5176                 ov->maxheight = 240;            /* Even field only */
5177         } else {
5178                 ov->maxwidth = 640;
5179                 ov->maxheight = 480;            /* Even/Odd fields */
5180         }
5181
5182         ov->minwidth = 320;
5183         ov->minheight = 240;            /* Even field only */
5184
5185         ov->has_decoder = 1;
5186         ov->num_inputs = 8;
5187         ov->norm = VIDEO_MODE_AUTO;
5188         ov->stop_during_set = 0;        /* Decoder guarantees stable image */
5189
5190         /* Decoder doesn't change these values, so we use these instead of
5191          * acutally reading the registers (which doesn't work) */
5192         ov->brightness = 0x80 << 8;
5193         ov->contrast = 0x40 << 9;
5194         ov->colour = 0x40 << 9;
5195         ov->hue = 32768;
5196
5197         PDEBUG(4, "Writing SAA7111A registers");
5198         if (write_regvals(ov, aRegvalsNormSAA7111A))
5199                 return -1;
5200
5201         /* Detect version of decoder. This must be done after writing the
5202          * initial regs or the decoder will lock up. */
5203         rc = i2c_r(ov, 0x00);
5204
5205         if (rc < 0) {
5206                 err("Error detecting sensor version");
5207                 return -1;
5208         } else {
5209                 dev_info(&ov->dev->dev,
5210                          "Sensor is an SAA7111A (version 0x%x)\n", rc);
5211                 ov->sensor = SEN_SAA7111A;
5212         }
5213
5214         // FIXME: Fix this for OV518(+)
5215         /* Latch to negative edge of clock. Otherwise, we get incorrect
5216          * colors and jitter in the digital signal. */
5217         if (ov->bclass == BCL_OV511)
5218                 reg_w(ov, 0x11, 0x00);
5219         else
5220                 warn("SAA7111A not yet supported with OV518/OV518+");
5221
5222         return 0;
5223 }
5224
5225 /* This initializes the OV511/OV511+ and the sensor */
5226 static int
5227 ov511_configure(struct usb_ov511 *ov)
5228 {
5229         static struct ov511_regvals aRegvalsInit511[] = {
5230                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5231                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5232                 { OV511_REG_BUS, R51x_SYS_RESET,        0x7f },
5233                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5234                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3f },
5235                 { OV511_REG_BUS, R51x_SYS_INIT,         0x01 },
5236                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3d },
5237                 { OV511_DONE_BUS, 0x0, 0x00},
5238         };
5239
5240         static struct ov511_regvals aRegvalsNorm511[] = {
5241                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0x01 },
5242                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5243                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5244                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5245                 { OV511_REG_BUS, R511_FIFO_OPTS,        0x1f },
5246                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5247                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5248                 { OV511_DONE_BUS, 0x0, 0x00 },
5249         };
5250
5251         static struct ov511_regvals aRegvalsNorm511Plus[] = {
5252                 { OV511_REG_BUS, R511_DRAM_FLOW_CTL,    0xff },
5253                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5254                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 },
5255                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x00 },
5256                 { OV511_REG_BUS, R511_FIFO_OPTS,        0xff },
5257                 { OV511_REG_BUS, R511_COMP_EN,          0x00 },
5258                 { OV511_REG_BUS, R511_COMP_LUT_EN,      0x03 },
5259                 { OV511_DONE_BUS, 0x0, 0x00 },
5260         };
5261
5262         PDEBUG(4, "");
5263
5264         ov->customid = reg_r(ov, R511_SYS_CUST_ID);
5265         if (ov->customid < 0) {
5266                 err("Unable to read camera bridge registers");
5267                 goto error;
5268         }
5269
5270         PDEBUG (1, "CustomID = %d", ov->customid);
5271         ov->desc = symbolic(camlist, ov->customid);
5272         dev_info(&ov->dev->dev, "model: %s\n", ov->desc);
5273
5274         if (0 == strcmp(ov->desc, NOT_DEFINED_STR)) {
5275                 err("Camera type (%d) not recognized", ov->customid);
5276                 err("Please notify " EMAIL " of the name,");
5277                 err("manufacturer, model, and this number of your camera.");
5278                 err("Also include the output of the detection process.");
5279         }
5280
5281         if (ov->customid == 70)         /* USB Life TV (PAL/SECAM) */
5282                 ov->pal = 1;
5283
5284         if (write_regvals(ov, aRegvalsInit511))
5285                 goto error;
5286
5287         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5288                 ov51x_led_control(ov, 0);
5289
5290         /* The OV511+ has undocumented bits in the flow control register.
5291          * Setting it to 0xff fixes the corruption with moving objects. */
5292         if (ov->bridge == BRG_OV511) {
5293                 if (write_regvals(ov, aRegvalsNorm511))
5294                         goto error;
5295         } else if (ov->bridge == BRG_OV511PLUS) {
5296                 if (write_regvals(ov, aRegvalsNorm511Plus))
5297                         goto error;
5298         } else {
5299                 err("Invalid bridge");
5300         }
5301
5302         if (ov511_init_compression(ov))
5303                 goto error;
5304
5305         ov->packet_numbering = 1;
5306         ov511_set_packet_size(ov, 0);
5307
5308         ov->snap_enabled = snapshot;
5309
5310         /* Test for 7xx0 */
5311         PDEBUG(3, "Testing for 0V7xx0");
5312         ov->primary_i2c_slave = OV7xx0_SID;
5313         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5314                 goto error;
5315
5316         if (i2c_w(ov, 0x12, 0x80) < 0) {
5317                 /* Test for 6xx0 */
5318                 PDEBUG(3, "Testing for 0V6xx0");
5319                 ov->primary_i2c_slave = OV6xx0_SID;
5320                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5321                         goto error;
5322
5323                 if (i2c_w(ov, 0x12, 0x80) < 0) {
5324                         /* Test for 8xx0 */
5325                         PDEBUG(3, "Testing for 0V8xx0");
5326                         ov->primary_i2c_slave = OV8xx0_SID;
5327                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5328                                 goto error;
5329
5330                         if (i2c_w(ov, 0x12, 0x80) < 0) {
5331                                 /* Test for SAA7111A */
5332                                 PDEBUG(3, "Testing for SAA7111A");
5333                                 ov->primary_i2c_slave = SAA7111A_SID;
5334                                 if (ov51x_set_slave_ids(ov, SAA7111A_SID) < 0)
5335                                         goto error;
5336
5337                                 if (i2c_w(ov, 0x0d, 0x00) < 0) {
5338                                         /* Test for KS0127 */
5339                                         PDEBUG(3, "Testing for KS0127");
5340                                         ov->primary_i2c_slave = KS0127_SID;
5341                                         if (ov51x_set_slave_ids(ov, KS0127_SID) < 0)
5342                                                 goto error;
5343
5344                                         if (i2c_w(ov, 0x10, 0x00) < 0) {
5345                                                 err("Can't determine sensor slave IDs");
5346                                                 goto error;
5347                                         } else {
5348                                                 if (ks0127_configure(ov) < 0) {
5349                                                         err("Failed to configure KS0127");
5350                                                         goto error;
5351                                                 }
5352                                         }
5353                                 } else {
5354                                         if (saa7111a_configure(ov) < 0) {
5355                                                 err("Failed to configure SAA7111A");
5356                                                 goto error;
5357                                         }
5358                                 }
5359                         } else {
5360                                 err("Detected unsupported OV8xx0 sensor");
5361                                 goto error;
5362                         }
5363                 } else {
5364                         if (ov6xx0_configure(ov) < 0) {
5365                                 err("Failed to configure OV6xx0");
5366                                 goto error;
5367                         }
5368                 }
5369         } else {
5370                 if (ov7xx0_configure(ov) < 0) {
5371                         err("Failed to configure OV7xx0");
5372                         goto error;
5373                 }
5374         }
5375
5376         return 0;
5377
5378 error:
5379         err("OV511 Config failed");
5380
5381         return -EBUSY;
5382 }
5383
5384 /* This initializes the OV518/OV518+ and the sensor */
5385 static int
5386 ov518_configure(struct usb_ov511 *ov)
5387 {
5388         /* For 518 and 518+ */
5389         static struct ov511_regvals aRegvalsInit518[] = {
5390                 { OV511_REG_BUS, R51x_SYS_RESET,        0x40 },
5391                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5392                 { OV511_REG_BUS, R51x_SYS_RESET,        0x3e },
5393                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5394                 { OV511_REG_BUS, R51x_SYS_RESET,        0x00 },
5395                 { OV511_REG_BUS, R51x_SYS_INIT,         0xe1 },
5396                 { OV511_REG_BUS, 0x46,                  0x00 },
5397                 { OV511_REG_BUS, 0x5d,                  0x03 },
5398                 { OV511_DONE_BUS, 0x0, 0x00},
5399         };
5400
5401         static struct ov511_regvals aRegvalsNorm518[] = {
5402                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5403                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5404                 { OV511_REG_BUS, 0x31,                  0x0f },
5405                 { OV511_REG_BUS, 0x5d,                  0x03 },
5406                 { OV511_REG_BUS, 0x24,                  0x9f },
5407                 { OV511_REG_BUS, 0x25,                  0x90 },
5408                 { OV511_REG_BUS, 0x20,                  0x00 },
5409                 { OV511_REG_BUS, 0x51,                  0x04 },
5410                 { OV511_REG_BUS, 0x71,                  0x19 },
5411                 { OV511_DONE_BUS, 0x0, 0x00 },
5412         };
5413
5414         static struct ov511_regvals aRegvalsNorm518Plus[] = {
5415                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x02 }, /* Reset */
5416                 { OV511_REG_BUS, R51x_SYS_SNAP,         0x01 }, /* Enable */
5417                 { OV511_REG_BUS, 0x31,                  0x0f },
5418                 { OV511_REG_BUS, 0x5d,                  0x03 },
5419                 { OV511_REG_BUS, 0x24,                  0x9f },
5420                 { OV511_REG_BUS, 0x25,                  0x90 },
5421                 { OV511_REG_BUS, 0x20,                  0x60 },
5422                 { OV511_REG_BUS, 0x51,                  0x02 },
5423                 { OV511_REG_BUS, 0x71,                  0x19 },
5424                 { OV511_REG_BUS, 0x40,                  0xff },
5425                 { OV511_REG_BUS, 0x41,                  0x42 },
5426                 { OV511_REG_BUS, 0x46,                  0x00 },
5427                 { OV511_REG_BUS, 0x33,                  0x04 },
5428                 { OV511_REG_BUS, 0x21,                  0x19 },
5429                 { OV511_REG_BUS, 0x3f,                  0x10 },
5430                 { OV511_DONE_BUS, 0x0, 0x00 },
5431         };
5432
5433         PDEBUG(4, "");
5434
5435         /* First 5 bits of custom ID reg are a revision ID on OV518 */
5436         dev_info(&ov->dev->dev, "Device revision %d\n",
5437                  0x1F & reg_r(ov, R511_SYS_CUST_ID));
5438
5439         /* Give it the default description */
5440         ov->desc = symbolic(camlist, 0);
5441
5442         if (write_regvals(ov, aRegvalsInit518))
5443                 goto error;
5444
5445         /* Set LED GPIO pin to output mode */
5446         if (reg_w_mask(ov, 0x57, 0x00, 0x02) < 0)
5447                 goto error;
5448
5449         /* LED is off by default with OV518; have to explicitly turn it on */
5450         if (ov->led_policy == LED_OFF || ov->led_policy == LED_AUTO)
5451                 ov51x_led_control(ov, 0);
5452         else
5453                 ov51x_led_control(ov, 1);
5454
5455         /* Don't require compression if dumppix is enabled; otherwise it's
5456          * required. OV518 has no uncompressed mode, to save RAM. */
5457         if (!dumppix && !ov->compress) {
5458                 ov->compress = 1;
5459                 warn("Compression required with OV518...enabling");
5460         }
5461
5462         if (ov->bridge == BRG_OV518) {
5463                 if (write_regvals(ov, aRegvalsNorm518))
5464                         goto error;
5465         } else if (ov->bridge == BRG_OV518PLUS) {
5466                 if (write_regvals(ov, aRegvalsNorm518Plus))
5467                         goto error;
5468         } else {
5469                 err("Invalid bridge");
5470         }
5471
5472         if (reg_w(ov, 0x2f, 0x80) < 0)
5473                 goto error;
5474
5475         if (ov518_init_compression(ov))
5476                 goto error;
5477
5478         if (ov->bridge == BRG_OV518)
5479         {
5480                 struct usb_interface *ifp;
5481                 struct usb_host_interface *alt;
5482                 __u16 mxps = 0;
5483
5484                 ifp = usb_ifnum_to_if(ov->dev, 0);
5485                 if (ifp) {
5486                         alt = usb_altnum_to_altsetting(ifp, 7);
5487                         if (alt)
5488                                 mxps = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
5489                 }
5490
5491                 /* Some OV518s have packet numbering by default, some don't */
5492                 if (mxps == 897)
5493                         ov->packet_numbering = 1;
5494                 else
5495                         ov->packet_numbering = 0;
5496         } else {
5497                 /* OV518+ has packet numbering turned on by default */
5498                 ov->packet_numbering = 1;
5499         }
5500
5501         ov518_set_packet_size(ov, 0);
5502
5503         ov->snap_enabled = snapshot;
5504
5505         /* Test for 76xx */
5506         ov->primary_i2c_slave = OV7xx0_SID;
5507         if (ov51x_set_slave_ids(ov, OV7xx0_SID) < 0)
5508                 goto error;
5509
5510         /* The OV518 must be more aggressive about sensor detection since
5511          * I2C write will never fail if the sensor is not present. We have
5512          * to try to initialize the sensor to detect its presence */
5513
5514         if (init_ov_sensor(ov) < 0) {
5515                 /* Test for 6xx0 */
5516                 ov->primary_i2c_slave = OV6xx0_SID;
5517                 if (ov51x_set_slave_ids(ov, OV6xx0_SID) < 0)
5518                         goto error;
5519
5520                 if (init_ov_sensor(ov) < 0) {
5521                         /* Test for 8xx0 */
5522                         ov->primary_i2c_slave = OV8xx0_SID;
5523                         if (ov51x_set_slave_ids(ov, OV8xx0_SID) < 0)
5524                                 goto error;
5525
5526                         if (init_ov_sensor(ov) < 0) {
5527                                 err("Can't determine sensor slave IDs");
5528                                 goto error;
5529                         } else {
5530                                 err("Detected unsupported OV8xx0 sensor");
5531                                 goto error;
5532                         }
5533                 } else {
5534                         if (ov6xx0_configure(ov) < 0) {
5535                                 err("Failed to configure OV6xx0");
5536                                 goto error;
5537                         }
5538                 }
5539         } else {
5540                 if (ov7xx0_configure(ov) < 0) {
5541                         err("Failed to configure OV7xx0");
5542                         goto error;
5543                 }
5544         }
5545
5546         ov->maxwidth = 352;
5547         ov->maxheight = 288;
5548
5549         // The OV518 cannot go as low as the sensor can
5550         ov->minwidth = 160;
5551         ov->minheight = 120;
5552
5553         return 0;
5554
5555 error:
5556         err("OV518 Config failed");
5557
5558         return -EBUSY;
5559 }
5560
5561 /****************************************************************************
5562  *  sysfs
5563  ***************************************************************************/
5564
5565 static inline struct usb_ov511 *cd_to_ov(struct device *cd)
5566 {
5567         struct video_device *vdev = to_video_device(cd);
5568         return video_get_drvdata(vdev);
5569 }
5570
5571 static ssize_t show_custom_id(struct device *cd,
5572                               struct device_attribute *attr, char *buf)
5573 {
5574         struct usb_ov511 *ov = cd_to_ov(cd);
5575         return sprintf(buf, "%d\n", ov->customid);
5576 }
5577 static DEVICE_ATTR(custom_id, S_IRUGO, show_custom_id, NULL);
5578
5579 static ssize_t show_model(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", ov->desc);
5584 }
5585 static DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
5586
5587 static ssize_t show_bridge(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(brglist, ov->bridge));
5592 }
5593 static DEVICE_ATTR(bridge, S_IRUGO, show_bridge, NULL);
5594
5595 static ssize_t show_sensor(struct device *cd,
5596                            struct device_attribute *attr, char *buf)
5597 {
5598         struct usb_ov511 *ov = cd_to_ov(cd);
5599         return sprintf(buf, "%s\n", symbolic(senlist, ov->sensor));
5600 }
5601 static DEVICE_ATTR(sensor, S_IRUGO, show_sensor, NULL);
5602
5603 static ssize_t show_brightness(struct device *cd,
5604                                struct device_attribute *attr, char *buf)
5605 {
5606         struct usb_ov511 *ov = cd_to_ov(cd);
5607         unsigned short x;
5608
5609         if (!ov->dev)
5610                 return -ENODEV;
5611         sensor_get_brightness(ov, &x);
5612         return sprintf(buf, "%d\n", x >> 8);
5613 }
5614 static DEVICE_ATTR(brightness, S_IRUGO, show_brightness, NULL);
5615
5616 static ssize_t show_saturation(struct device *cd,
5617                                struct device_attribute *attr, char *buf)
5618 {
5619         struct usb_ov511 *ov = cd_to_ov(cd);
5620         unsigned short x;
5621
5622         if (!ov->dev)
5623                 return -ENODEV;
5624         sensor_get_saturation(ov, &x);
5625         return sprintf(buf, "%d\n", x >> 8);
5626 }
5627 static DEVICE_ATTR(saturation, S_IRUGO, show_saturation, NULL);
5628
5629 static ssize_t show_contrast(struct device *cd,
5630                              struct device_attribute *attr, char *buf)
5631 {
5632         struct usb_ov511 *ov = cd_to_ov(cd);
5633         unsigned short x;
5634
5635         if (!ov->dev)
5636                 return -ENODEV;
5637         sensor_get_contrast(ov, &x);
5638         return sprintf(buf, "%d\n", x >> 8);
5639 }
5640 static DEVICE_ATTR(contrast, S_IRUGO, show_contrast, NULL);
5641
5642 static ssize_t show_hue(struct device *cd,
5643                         struct device_attribute *attr, char *buf)
5644 {
5645         struct usb_ov511 *ov = cd_to_ov(cd);
5646         unsigned short x;
5647
5648         if (!ov->dev)
5649                 return -ENODEV;
5650         sensor_get_hue(ov, &x);
5651         return sprintf(buf, "%d\n", x >> 8);
5652 }
5653 static DEVICE_ATTR(hue, S_IRUGO, show_hue, NULL);
5654
5655 static ssize_t show_exposure(struct device *cd,
5656                              struct device_attribute *attr, char *buf)
5657 {
5658         struct usb_ov511 *ov = cd_to_ov(cd);
5659         unsigned char exp = 0;
5660
5661         if (!ov->dev)
5662                 return -ENODEV;
5663         sensor_get_exposure(ov, &exp);
5664         return sprintf(buf, "%d\n", exp);
5665 }
5666 static DEVICE_ATTR(exposure, S_IRUGO, show_exposure, NULL);
5667
5668 static int ov_create_sysfs(struct video_device *vdev)
5669 {
5670         int rc;
5671
5672         rc = device_create_file(&vdev->dev, &dev_attr_custom_id);
5673         if (rc) goto err;
5674         rc = device_create_file(&vdev->dev, &dev_attr_model);
5675         if (rc) goto err_id;
5676         rc = device_create_file(&vdev->dev, &dev_attr_bridge);
5677         if (rc) goto err_model;
5678         rc = device_create_file(&vdev->dev, &dev_attr_sensor);
5679         if (rc) goto err_bridge;
5680         rc = device_create_file(&vdev->dev, &dev_attr_brightness);
5681         if (rc) goto err_sensor;
5682         rc = device_create_file(&vdev->dev, &dev_attr_saturation);
5683         if (rc) goto err_bright;
5684         rc = device_create_file(&vdev->dev, &dev_attr_contrast);
5685         if (rc) goto err_sat;
5686         rc = device_create_file(&vdev->dev, &dev_attr_hue);
5687         if (rc) goto err_contrast;
5688         rc = device_create_file(&vdev->dev, &dev_attr_exposure);
5689         if (rc) goto err_hue;
5690
5691         return 0;
5692
5693 err_hue:
5694         device_remove_file(&vdev->dev, &dev_attr_hue);
5695 err_contrast:
5696         device_remove_file(&vdev->dev, &dev_attr_contrast);
5697 err_sat:
5698         device_remove_file(&vdev->dev, &dev_attr_saturation);
5699 err_bright:
5700         device_remove_file(&vdev->dev, &dev_attr_brightness);
5701 err_sensor:
5702         device_remove_file(&vdev->dev, &dev_attr_sensor);
5703 err_bridge:
5704         device_remove_file(&vdev->dev, &dev_attr_bridge);
5705 err_model:
5706         device_remove_file(&vdev->dev, &dev_attr_model);
5707 err_id:
5708         device_remove_file(&vdev->dev, &dev_attr_custom_id);
5709 err:
5710         return rc;
5711 }
5712
5713 /****************************************************************************
5714  *  USB routines
5715  ***************************************************************************/
5716
5717 static int
5718 ov51x_probe(struct usb_interface *intf, const struct usb_device_id *id)
5719 {
5720         struct usb_device *dev = interface_to_usbdev(intf);
5721         struct usb_interface_descriptor *idesc;
5722         struct usb_ov511 *ov;
5723         int i;
5724
5725         PDEBUG(1, "probing for device...");
5726
5727         /* We don't handle multi-config cameras */
5728         if (dev->descriptor.bNumConfigurations != 1)
5729                 return -ENODEV;
5730
5731         idesc = &intf->cur_altsetting->desc;
5732
5733         if (idesc->bInterfaceClass != 0xFF)
5734                 return -ENODEV;
5735         if (idesc->bInterfaceSubClass != 0x00)
5736                 return -ENODEV;
5737
5738         if ((ov = kzalloc(sizeof(*ov), GFP_KERNEL)) == NULL) {
5739                 err("couldn't kmalloc ov struct");
5740                 goto error_out;
5741         }
5742
5743         ov->dev = dev;
5744         ov->iface = idesc->bInterfaceNumber;
5745         ov->led_policy = led;
5746         ov->compress = compress;
5747         ov->lightfreq = lightfreq;
5748         ov->num_inputs = 1;        /* Video decoder init functs. change this */
5749         ov->stop_during_set = !fastset;
5750         ov->backlight = backlight;
5751         ov->mirror = mirror;
5752         ov->auto_brt = autobright;
5753         ov->auto_gain = autogain;
5754         ov->auto_exp = autoexp;
5755
5756         switch (le16_to_cpu(dev->descriptor.idProduct)) {
5757         case PROD_OV511:
5758                 ov->bridge = BRG_OV511;
5759                 ov->bclass = BCL_OV511;
5760                 break;
5761         case PROD_OV511PLUS:
5762                 ov->bridge = BRG_OV511PLUS;
5763                 ov->bclass = BCL_OV511;
5764                 break;
5765         case PROD_OV518:
5766                 ov->bridge = BRG_OV518;
5767                 ov->bclass = BCL_OV518;
5768                 break;
5769         case PROD_OV518PLUS:
5770                 ov->bridge = BRG_OV518PLUS;
5771                 ov->bclass = BCL_OV518;
5772                 break;
5773         case PROD_ME2CAM:
5774                 if (le16_to_cpu(dev->descriptor.idVendor) != VEND_MATTEL)
5775                         goto error;
5776                 ov->bridge = BRG_OV511PLUS;
5777                 ov->bclass = BCL_OV511;
5778                 break;
5779         default:
5780                 err("Unknown product ID 0x%04x", le16_to_cpu(dev->descriptor.idProduct));
5781                 goto error;
5782         }
5783
5784         dev_info(&intf->dev, "USB %s video device found\n",
5785                  symbolic(brglist, ov->bridge));
5786
5787         init_waitqueue_head(&ov->wq);
5788
5789         mutex_init(&ov->lock);  /* to 1 == available */
5790         mutex_init(&ov->buf_lock);
5791         mutex_init(&ov->i2c_lock);
5792         mutex_init(&ov->cbuf_lock);
5793
5794         ov->buf_state = BUF_NOT_ALLOCATED;
5795
5796         if (usb_make_path(dev, ov->usb_path, OV511_USB_PATH_LEN) < 0) {
5797                 err("usb_make_path error");
5798                 goto error;
5799         }
5800
5801         /* Allocate control transfer buffer. */
5802         /* Must be kmalloc()'ed, for DMA compatibility */
5803         ov->cbuf = kmalloc(OV511_CBUF_SIZE, GFP_KERNEL);
5804         if (!ov->cbuf)
5805                 goto error;
5806
5807         if (ov->bclass == BCL_OV518) {
5808                 if (ov518_configure(ov) < 0)
5809                         goto error;
5810         } else {
5811                 if (ov511_configure(ov) < 0)
5812                         goto error;
5813         }
5814
5815         for (i = 0; i < OV511_NUMFRAMES; i++) {
5816                 ov->frame[i].framenum = i;
5817                 init_waitqueue_head(&ov->frame[i].wq);
5818         }
5819
5820         for (i = 0; i < OV511_NUMSBUF; i++) {
5821                 ov->sbuf[i].ov = ov;
5822                 spin_lock_init(&ov->sbuf[i].lock);
5823                 ov->sbuf[i].n = i;
5824         }
5825
5826         /* Unnecessary? (This is done on open(). Need to make sure variables
5827          * are properly initialized without this before removing it, though). */
5828         if (ov51x_set_default_params(ov) < 0)
5829                 goto error;
5830
5831 #ifdef OV511_DEBUG
5832         if (dump_bridge) {
5833                 if (ov->bclass == BCL_OV511)
5834                         ov511_dump_regs(ov);
5835                 else
5836                         ov518_dump_regs(ov);
5837         }
5838 #endif
5839
5840         ov->vdev = video_device_alloc();
5841         if (!ov->vdev)
5842                 goto error;
5843
5844         memcpy(ov->vdev, &vdev_template, sizeof(*ov->vdev));
5845         ov->vdev->parent = &intf->dev;
5846         video_set_drvdata(ov->vdev, ov);
5847
5848         for (i = 0; i < OV511_MAX_UNIT_VIDEO; i++) {
5849                 /* Minor 0 cannot be specified; assume user wants autodetect */
5850                 if (unit_video[i] == 0)
5851                         break;
5852
5853                 if (video_register_device(ov->vdev, VFL_TYPE_GRABBER,
5854                         unit_video[i]) >= 0) {
5855                         break;
5856                 }
5857         }
5858
5859         /* Use the next available one */
5860         if ((ov->vdev->minor == -1) &&
5861             video_register_device(ov->vdev, VFL_TYPE_GRABBER, -1) < 0) {
5862                 err("video_register_device failed");
5863                 goto error;
5864         }
5865
5866         dev_info(&intf->dev, "Device at %s registered to minor %d\n",
5867                  ov->usb_path, ov->vdev->minor);
5868
5869         usb_set_intfdata(intf, ov);
5870         if (ov_create_sysfs(ov->vdev)) {
5871                 err("ov_create_sysfs failed");
5872                 goto error;
5873         }
5874
5875         return 0;
5876
5877 error:
5878         if (ov->vdev) {
5879                 if (-1 == ov->vdev->minor)
5880                         video_device_release(ov->vdev);
5881                 else
5882                         video_unregister_device(ov->vdev);
5883                 ov->vdev = NULL;
5884         }
5885
5886         if (ov->cbuf) {
5887                 mutex_lock(&ov->cbuf_lock);
5888                 kfree(ov->cbuf);
5889                 ov->cbuf = NULL;
5890                 mutex_unlock(&ov->cbuf_lock);
5891         }
5892
5893         kfree(ov);
5894         ov = NULL;
5895
5896 error_out:
5897         err("Camera initialization failed");
5898         return -EIO;
5899 }
5900
5901 static void
5902 ov51x_disconnect(struct usb_interface *intf)
5903 {
5904         struct usb_ov511 *ov = usb_get_intfdata(intf);
5905         int n;
5906
5907         PDEBUG(3, "");
5908
5909         usb_set_intfdata (intf, NULL);
5910
5911         if (!ov)
5912                 return;
5913
5914         if (ov->vdev)
5915                 video_unregister_device(ov->vdev);
5916
5917         for (n = 0; n < OV511_NUMFRAMES; n++)
5918                 ov->frame[n].grabstate = FRAME_ERROR;
5919
5920         ov->curframe = -1;
5921
5922         /* This will cause the process to request another frame */
5923         for (n = 0; n < OV511_NUMFRAMES; n++)
5924                 wake_up_interruptible(&ov->frame[n].wq);
5925
5926         wake_up_interruptible(&ov->wq);
5927
5928         ov->streaming = 0;
5929         ov51x_unlink_isoc(ov);
5930
5931         ov->dev = NULL;
5932
5933         /* Free the memory */
5934         if (ov && !ov->user) {
5935                 mutex_lock(&ov->cbuf_lock);
5936                 kfree(ov->cbuf);
5937                 ov->cbuf = NULL;
5938                 mutex_unlock(&ov->cbuf_lock);
5939
5940                 ov51x_dealloc(ov);
5941                 kfree(ov);
5942                 ov = NULL;
5943         }
5944
5945         PDEBUG(3, "Disconnect complete");
5946 }
5947
5948 static struct usb_driver ov511_driver = {
5949         .name =         "ov511",
5950         .id_table =     device_table,
5951         .probe =        ov51x_probe,
5952         .disconnect =   ov51x_disconnect
5953 };
5954
5955 /****************************************************************************
5956  *
5957  *  Module routines
5958  *
5959  ***************************************************************************/
5960
5961 static int __init
5962 usb_ov511_init(void)
5963 {
5964         int retval;
5965
5966         retval = usb_register(&ov511_driver);
5967         if (retval)
5968                 goto out;
5969
5970         printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
5971                DRIVER_DESC "\n");
5972
5973 out:
5974         return retval;
5975 }
5976
5977 static void __exit
5978 usb_ov511_exit(void)
5979 {
5980         usb_deregister(&ov511_driver);
5981         printk(KERN_INFO KBUILD_MODNAME ": driver deregistered\n");
5982 }
5983
5984 module_init(usb_ov511_init);
5985 module_exit(usb_ov511_exit);
5986