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