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