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