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