[PATCH] i2c: Drop i2c_driver.{owner,name}, 5 of 11
[safe/jmp/linux-2.6] / drivers / usb / media / w9968cf.c
1 /***************************************************************************
2  * Video4Linux driver for W996[87]CF JPEG USB Dual Mode Camera Chip.       *
3  *                                                                         *
4  * Copyright (C) 2002-2004 by Luca Risolia <luca.risolia@studio.unibo.it>  *
5  *                                                                         *
6  * - Memory management code from bttv driver by Ralph Metzler,             *
7  *   Marcus Metzler and Gerd Knorr.                                        *
8  * - I2C interface to kernel, high-level image sensor control routines and *
9  *   some symbolic names from OV511 driver by Mark W. McClelland.          *
10  * - Low-level I2C fast write function by Piotr Czerczak.                  *
11  * - Low-level I2C read function by Frederic Jouault.                      *
12  *                                                                         *
13  * This program is free software; you can redistribute it and/or modify    *
14  * it under the terms of the GNU General Public License as published by    *
15  * the Free Software Foundation; either version 2 of the License, or       *
16  * (at your option) any later version.                                     *
17  *                                                                         *
18  * This program is distributed in the hope that it will be useful,         *
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
21  * GNU General Public License for more details.                            *
22  *                                                                         *
23  * You should have received a copy of the GNU General Public License       *
24  * along with this program; if not, write to the Free Software             *
25  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.               *
26  ***************************************************************************/
27
28 #include <linux/module.h>
29 #include <linux/kernel.h>
30 #include <linux/kmod.h>
31 #include <linux/init.h>
32 #include <linux/fs.h>
33 #include <linux/vmalloc.h>
34 #include <linux/slab.h>
35 #include <linux/mm.h>
36 #include <linux/string.h>
37 #include <linux/errno.h>
38 #include <linux/sched.h>
39 #include <linux/ioctl.h>
40 #include <linux/delay.h>
41 #include <linux/stddef.h>
42 #include <asm/page.h>
43 #include <asm/uaccess.h>
44 #include <linux/page-flags.h>
45 #include <linux/moduleparam.h>
46
47 #include "w9968cf.h"
48 #include "w9968cf_decoder.h"
49
50
51
52 /****************************************************************************
53  * Module macros and parameters                                             *
54  ****************************************************************************/
55
56 MODULE_DEVICE_TABLE(usb, winbond_id_table);
57
58 MODULE_AUTHOR(W9968CF_MODULE_AUTHOR" "W9968CF_AUTHOR_EMAIL);
59 MODULE_DESCRIPTION(W9968CF_MODULE_NAME);
60 MODULE_VERSION(W9968CF_MODULE_VERSION);
61 MODULE_LICENSE(W9968CF_MODULE_LICENSE);
62 MODULE_SUPPORTED_DEVICE("Video");
63
64 static int ovmod_load = W9968CF_OVMOD_LOAD;
65 static int vppmod_load = W9968CF_VPPMOD_LOAD;
66 static unsigned short simcams = W9968CF_SIMCAMS;
67 static short video_nr[]={[0 ... W9968CF_MAX_DEVICES-1] = -1}; /*-1=first free*/
68 static unsigned int packet_size[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
69                                      W9968CF_PACKET_SIZE};
70 static unsigned short max_buffers[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
71                                        W9968CF_BUFFERS};
72 static int double_buffer[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
73                               W9968CF_DOUBLE_BUFFER};
74 static int clamping[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_CLAMPING};
75 static unsigned short filter_type[]= {[0 ... W9968CF_MAX_DEVICES-1] = 
76                                       W9968CF_FILTER_TYPE};
77 static int largeview[]= {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_LARGEVIEW};
78 static unsigned short decompression[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
79                                          W9968CF_DECOMPRESSION};
80 static int upscaling[]= {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_UPSCALING};
81 static unsigned short force_palette[] = {[0 ... W9968CF_MAX_DEVICES-1] = 0};
82 static int force_rgb[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_FORCE_RGB};
83 static int autobright[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_AUTOBRIGHT};
84 static int autoexp[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_AUTOEXP};
85 static unsigned short lightfreq[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
86                                      W9968CF_LIGHTFREQ};
87 static int bandingfilter[] = {[0 ... W9968CF_MAX_DEVICES-1]=
88                               W9968CF_BANDINGFILTER};
89 static short clockdiv[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_CLOCKDIV};
90 static int backlight[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_BACKLIGHT};
91 static int mirror[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_MIRROR};
92 static int monochrome[] = {[0 ... W9968CF_MAX_DEVICES-1]=W9968CF_MONOCHROME};
93 static unsigned int brightness[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
94                                     W9968CF_BRIGHTNESS};
95 static unsigned int hue[] = {[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_HUE};
96 static unsigned int colour[]={[0 ... W9968CF_MAX_DEVICES-1] = W9968CF_COLOUR};
97 static unsigned int contrast[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
98                                   W9968CF_CONTRAST};
99 static unsigned int whiteness[] = {[0 ... W9968CF_MAX_DEVICES-1] = 
100                                    W9968CF_WHITENESS};
101 #ifdef W9968CF_DEBUG
102 static unsigned short debug = W9968CF_DEBUG_LEVEL;
103 static int specific_debug = W9968CF_SPECIFIC_DEBUG;
104 #endif
105
106 static unsigned int param_nv[24]; /* number of values per parameter */
107
108 #ifdef CONFIG_KMOD
109 module_param(ovmod_load, bool, 0644);
110 module_param(vppmod_load, bool, 0444);
111 #endif
112 module_param(simcams, ushort, 0644);
113 module_param_array(video_nr, short, &param_nv[0], 0444);
114 module_param_array(packet_size, uint, &param_nv[1], 0444);
115 module_param_array(max_buffers, ushort, &param_nv[2], 0444);
116 module_param_array(double_buffer, bool, &param_nv[3], 0444);
117 module_param_array(clamping, bool, &param_nv[4], 0444);
118 module_param_array(filter_type, ushort, &param_nv[5], 0444);
119 module_param_array(largeview, bool, &param_nv[6], 0444);
120 module_param_array(decompression, ushort, &param_nv[7], 0444);
121 module_param_array(upscaling, bool, &param_nv[8], 0444);
122 module_param_array(force_palette, ushort, &param_nv[9], 0444);
123 module_param_array(force_rgb, ushort, &param_nv[10], 0444);
124 module_param_array(autobright, bool, &param_nv[11], 0444);
125 module_param_array(autoexp, bool, &param_nv[12], 0444);
126 module_param_array(lightfreq, ushort, &param_nv[13], 0444);
127 module_param_array(bandingfilter, bool, &param_nv[14], 0444);
128 module_param_array(clockdiv, short, &param_nv[15], 0444);
129 module_param_array(backlight, bool, &param_nv[16], 0444);
130 module_param_array(mirror, bool, &param_nv[17], 0444);
131 module_param_array(monochrome, bool, &param_nv[18], 0444);
132 module_param_array(brightness, uint, &param_nv[19], 0444);
133 module_param_array(hue, uint, &param_nv[20], 0444);
134 module_param_array(colour, uint, &param_nv[21], 0444);
135 module_param_array(contrast, uint, &param_nv[22], 0444);
136 module_param_array(whiteness, uint, &param_nv[23], 0444);
137 #ifdef W9968CF_DEBUG
138 module_param(debug, ushort, 0644);
139 module_param(specific_debug, bool, 0644);
140 #endif
141
142 #ifdef CONFIG_KMOD
143 MODULE_PARM_DESC(ovmod_load, 
144                  "\n<0|1> Automatic 'ovcamchip' module loading."
145                  "\n0 disabled, 1 enabled."
146                  "\nIf enabled,'insmod' searches for the required 'ovcamchip'"
147                  "\nmodule in the system, according to its configuration, and"
148                  "\nattempts to load that module automatically. This action is"
149                  "\nperformed once as soon as the 'w9968cf' module is loaded"
150                  "\ninto memory."
151                  "\nDefault value is "__MODULE_STRING(W9968CF_OVMOD_LOAD)"."
152                  "\n");
153 MODULE_PARM_DESC(vppmod_load, 
154                  "\n<0|1> Automatic 'w9968cf-vpp' module loading."
155                  "\n0 disabled, 1 enabled."
156                  "\nIf enabled, every time an application attempts to open a"
157                  "\ncamera, 'insmod' searches for the video post-processing"
158                  "\nmodule in the system and loads it automatically (if"
159                  "\npresent). The optional 'w9968cf-vpp' module adds extra"
160                  "\n image manipulation functions to the 'w9968cf' module,like"
161                  "\nsoftware up-scaling,colour conversions and video decoding"
162                  "\nfor very high frame rates."
163                  "\nDefault value is "__MODULE_STRING(W9968CF_VPPMOD_LOAD)"."
164                  "\n");
165 #endif
166 MODULE_PARM_DESC(simcams, 
167                  "\n<n> Number of cameras allowed to stream simultaneously."
168                  "\nn may vary from 0 to "
169                  __MODULE_STRING(W9968CF_MAX_DEVICES)"."
170                  "\nDefault value is "__MODULE_STRING(W9968CF_SIMCAMS)"."
171                  "\n");
172 MODULE_PARM_DESC(video_nr,
173                  "\n<-1|n[,...]> Specify V4L minor mode number."
174                  "\n -1 = use next available (default)"
175                  "\n  n = use minor number n (integer >= 0)"
176                  "\nYou can specify up to "__MODULE_STRING(W9968CF_MAX_DEVICES)
177                  " cameras this way."
178                  "\nFor example:"
179                  "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
180                  "\nthe second camera and use auto for the first"
181                  "\none and for every other camera."
182                  "\n");
183 MODULE_PARM_DESC(packet_size,
184                  "\n<n[,...]> Specify the maximum data payload"
185                  "\nsize in bytes for alternate settings, for each device."
186                  "\nn is scaled between 63 and 1023 "
187                  "(default is "__MODULE_STRING(W9968CF_PACKET_SIZE)")."
188                  "\n");
189 MODULE_PARM_DESC(max_buffers,
190                  "\n<n[,...]> For advanced users."
191                  "\nSpecify the maximum number of video frame buffers"
192                  "\nto allocate for each device, from 2 to "
193                  __MODULE_STRING(W9968CF_MAX_BUFFERS)
194                  ". (default is "__MODULE_STRING(W9968CF_BUFFERS)")."
195                  "\n");
196 MODULE_PARM_DESC(double_buffer, 
197                  "\n<0|1[,...]> "
198                  "Hardware double buffering: 0 disabled, 1 enabled."
199                  "\nIt should be enabled if you want smooth video output: if"
200                  "\nyou obtain out of sync. video, disable it, or try to"
201                  "\ndecrease the 'clockdiv' module parameter value."
202                  "\nDefault value is "__MODULE_STRING(W9968CF_DOUBLE_BUFFER)
203                  " for every device."
204                  "\n");
205 MODULE_PARM_DESC(clamping, 
206                  "\n<0|1[,...]> Video data clamping: 0 disabled, 1 enabled."
207                  "\nDefault value is "__MODULE_STRING(W9968CF_CLAMPING)
208                  " for every device."
209                  "\n");
210 MODULE_PARM_DESC(filter_type, 
211                  "\n<0|1|2[,...]> Video filter type."
212                  "\n0 none, 1 (1-2-1) 3-tap filter, "
213                  "2 (2-3-6-3-2) 5-tap filter."
214                  "\nDefault value is "__MODULE_STRING(W9968CF_FILTER_TYPE)
215                  " for every device."
216                  "\nThe filter is used to reduce noise and aliasing artifacts"
217                  "\nproduced by the CCD or CMOS image sensor, and the scaling"
218                  " process."
219                  "\n");
220 MODULE_PARM_DESC(largeview, 
221                  "\n<0|1[,...]> Large view: 0 disabled, 1 enabled."
222                  "\nDefault value is "__MODULE_STRING(W9968CF_LARGEVIEW)
223                  " for every device."
224                  "\n");
225 MODULE_PARM_DESC(upscaling, 
226                  "\n<0|1[,...]> Software scaling (for non-compressed video):"
227                  "\n0 disabled, 1 enabled."
228                  "\nDisable it if you have a slow CPU or you don't have"
229                  " enough memory."
230                  "\nDefault value is "__MODULE_STRING(W9968CF_UPSCALING)
231                  " for every device."
232                  "\nIf 'w9968cf-vpp' is not present, this parameter is"
233                  " set to 0."
234                  "\n");
235 MODULE_PARM_DESC(decompression,
236                  "\n<0|1|2[,...]> Software video decompression:"
237                  "\n- 0 disables decompression (doesn't allow formats needing"
238                  " decompression)"
239                  "\n- 1 forces decompression (allows formats needing"
240                  " decompression only);"
241                  "\n- 2 allows any permitted formats."
242                  "\nFormats supporting compressed video are YUV422P and"
243                  " YUV420P/YUV420 "
244                  "\nin any resolutions where both width and height are "
245                  "a multiple of 16."
246                  "\nDefault value is "__MODULE_STRING(W9968CF_DECOMPRESSION)
247                  " for every device."
248                  "\nIf 'w9968cf-vpp' is not present, forcing decompression is "
249                  "\nnot allowed; in this case this parameter is set to 2."
250                  "\n");
251 MODULE_PARM_DESC(force_palette,
252                  "\n<0"
253                  "|" __MODULE_STRING(VIDEO_PALETTE_UYVY)
254                  "|" __MODULE_STRING(VIDEO_PALETTE_YUV420)
255                  "|" __MODULE_STRING(VIDEO_PALETTE_YUV422P)
256                  "|" __MODULE_STRING(VIDEO_PALETTE_YUV420P)
257                  "|" __MODULE_STRING(VIDEO_PALETTE_YUYV)
258                  "|" __MODULE_STRING(VIDEO_PALETTE_YUV422)
259                  "|" __MODULE_STRING(VIDEO_PALETTE_GREY)
260                  "|" __MODULE_STRING(VIDEO_PALETTE_RGB555)
261                  "|" __MODULE_STRING(VIDEO_PALETTE_RGB565)
262                  "|" __MODULE_STRING(VIDEO_PALETTE_RGB24)
263                  "|" __MODULE_STRING(VIDEO_PALETTE_RGB32)
264                  "[,...]>"
265                  " Force picture palette."
266                  "\nIn order:"
267                  "\n- 0 allows any of the following formats:"
268                  "\n- UYVY    16 bpp - Original video, compression disabled"
269                  "\n- YUV420  12 bpp - Original video, compression enabled"
270                  "\n- YUV422P 16 bpp - Original video, compression enabled"
271                  "\n- YUV420P 12 bpp - Original video, compression enabled"
272                  "\n- YUVY    16 bpp - Software conversion from UYVY"
273                  "\n- YUV422  16 bpp - Software conversion from UYVY"
274                  "\n- GREY     8 bpp - Software conversion from UYVY"
275                  "\n- RGB555  16 bpp - Software conversion from UYVY"
276                  "\n- RGB565  16 bpp - Software conversion from UYVY"
277                  "\n- RGB24   24 bpp - Software conversion from UYVY"
278                  "\n- RGB32   32 bpp - Software conversion from UYVY"
279                  "\nWhen not 0, this parameter will override 'decompression'."
280                  "\nDefault value is 0 for every device."
281                  "\nInitial palette is "
282                  __MODULE_STRING(W9968CF_PALETTE_DECOMP_ON)"."
283                  "\nIf 'w9968cf-vpp' is not present, this parameter is"
284                  " set to 9 (UYVY)."
285                  "\n");
286 MODULE_PARM_DESC(force_rgb, 
287                  "\n<0|1[,...]> Read RGB video data instead of BGR:"
288                  "\n 1 = use RGB component ordering."
289                  "\n 0 = use BGR component ordering."
290                  "\nThis parameter has effect when using RGBX palettes only."
291                  "\nDefault value is "__MODULE_STRING(W9968CF_FORCE_RGB)
292                  " for every device."
293                  "\n");
294 MODULE_PARM_DESC(autobright,
295                  "\n<0|1[,...]> Image sensor automatically changes brightness:"
296                  "\n 0 = no, 1 = yes"
297                  "\nDefault value is "__MODULE_STRING(W9968CF_AUTOBRIGHT)
298                  " for every device."
299                  "\n");
300 MODULE_PARM_DESC(autoexp,
301                  "\n<0|1[,...]> Image sensor automatically changes exposure:"
302                  "\n 0 = no, 1 = yes"
303                  "\nDefault value is "__MODULE_STRING(W9968CF_AUTOEXP)
304                  " for every device."
305                  "\n");
306 MODULE_PARM_DESC(lightfreq,
307                  "\n<50|60[,...]> Light frequency in Hz:"
308                  "\n 50 for European and Asian lighting,"
309                  " 60 for American lighting."
310                  "\nDefault value is "__MODULE_STRING(W9968CF_LIGHTFREQ)
311                  " for every device."
312                  "\n");
313 MODULE_PARM_DESC(bandingfilter,
314                  "\n<0|1[,...]> Banding filter to reduce effects of"
315                  " fluorescent lighting:"
316                  "\n 0 disabled, 1 enabled."
317                  "\nThis filter tries to reduce the pattern of horizontal"
318                  "\nlight/dark bands caused by some (usually fluorescent)"
319                  " lighting."
320                  "\nDefault value is "__MODULE_STRING(W9968CF_BANDINGFILTER)
321                  " for every device."
322                  "\n");
323 MODULE_PARM_DESC(clockdiv,
324                  "\n<-1|n[,...]> "
325                  "Force pixel clock divisor to a specific value (for experts):"
326                  "\n  n may vary from 0 to 127."
327                  "\n -1 for automatic value."
328                  "\nSee also the 'double_buffer' module parameter."
329                  "\nDefault value is "__MODULE_STRING(W9968CF_CLOCKDIV)
330                  " for every device."
331                  "\n");
332 MODULE_PARM_DESC(backlight,
333                  "\n<0|1[,...]> Objects are lit from behind:"
334                  "\n 0 = no, 1 = yes"
335                  "\nDefault value is "__MODULE_STRING(W9968CF_BACKLIGHT)
336                  " for every device."
337                  "\n");
338 MODULE_PARM_DESC(mirror,
339                  "\n<0|1[,...]> Reverse image horizontally:"
340                  "\n 0 = no, 1 = yes"
341                  "\nDefault value is "__MODULE_STRING(W9968CF_MIRROR)
342                  " for every device."
343                  "\n");
344 MODULE_PARM_DESC(monochrome,
345                  "\n<0|1[,...]> Use image sensor as monochrome sensor:"
346                  "\n 0 = no, 1 = yes"
347                  "\nNot all the sensors support monochrome color."
348                  "\nDefault value is "__MODULE_STRING(W9968CF_MONOCHROME)
349                  " for every device."
350                  "\n");
351 MODULE_PARM_DESC(brightness, 
352                  "\n<n[,...]> Set picture brightness (0-65535)."
353                  "\nDefault value is "__MODULE_STRING(W9968CF_BRIGHTNESS)
354                  " for every device."
355                  "\nThis parameter has no effect if 'autobright' is enabled."
356                  "\n");
357 MODULE_PARM_DESC(hue, 
358                  "\n<n[,...]> Set picture hue (0-65535)."
359                  "\nDefault value is "__MODULE_STRING(W9968CF_HUE)
360                  " for every device."
361                  "\n");
362 MODULE_PARM_DESC(colour, 
363                  "\n<n[,...]> Set picture saturation (0-65535)."
364                  "\nDefault value is "__MODULE_STRING(W9968CF_COLOUR)
365                  " for every device."
366                  "\n");
367 MODULE_PARM_DESC(contrast, 
368                  "\n<n[,...]> Set picture contrast (0-65535)."
369                  "\nDefault value is "__MODULE_STRING(W9968CF_CONTRAST)
370                  " for every device."
371                  "\n");
372 MODULE_PARM_DESC(whiteness, 
373                  "\n<n[,...]> Set picture whiteness (0-65535)."
374                  "\nDefault value is "__MODULE_STRING(W9968CF_WHITENESS)
375                  " for every device."
376                  "\n");
377 #ifdef W9968CF_DEBUG
378 MODULE_PARM_DESC(debug,
379                  "\n<n> Debugging information level, from 0 to 6:"
380                  "\n0 = none (use carefully)"
381                  "\n1 = critical errors"
382                  "\n2 = significant informations"
383                  "\n3 = configuration or general messages"
384                  "\n4 = warnings"
385                  "\n5 = called functions"
386                  "\n6 = function internals"
387                  "\nLevel 5 and 6 are useful for testing only, when only "
388                  "one device is used."
389                  "\nDefault value is "__MODULE_STRING(W9968CF_DEBUG_LEVEL)"."
390                  "\n");
391 MODULE_PARM_DESC(specific_debug,
392                  "\n<0|1> Enable or disable specific debugging messages:"
393                  "\n0 = print messages concerning every level"
394                  " <= 'debug' level."
395                  "\n1 = print messages concerning the level"
396                  " indicated by 'debug'."
397                  "\nDefault value is "
398                  __MODULE_STRING(W9968CF_SPECIFIC_DEBUG)"."
399                  "\n");
400 #endif /* W9968CF_DEBUG */
401
402
403
404 /****************************************************************************
405  * Some prototypes                                                          *
406  ****************************************************************************/
407
408 /* Video4linux interface */
409 static struct file_operations w9968cf_fops;
410 static int w9968cf_open(struct inode*, struct file*);
411 static int w9968cf_release(struct inode*, struct file*);
412 static int w9968cf_mmap(struct file*, struct vm_area_struct*);
413 static int w9968cf_ioctl(struct inode*, struct file*, unsigned, unsigned long);
414 static ssize_t w9968cf_read(struct file*, char __user *, size_t, loff_t*);
415 static int w9968cf_v4l_ioctl(struct inode*, struct file*, unsigned int,
416                              void __user *);
417
418 /* USB-specific */
419 static int w9968cf_start_transfer(struct w9968cf_device*);
420 static int w9968cf_stop_transfer(struct w9968cf_device*);
421 static int w9968cf_write_reg(struct w9968cf_device*, u16 value, u16 index);
422 static int w9968cf_read_reg(struct w9968cf_device*, u16 index);
423 static int w9968cf_write_fsb(struct w9968cf_device*, u16* data);
424 static int w9968cf_write_sb(struct w9968cf_device*, u16 value);
425 static int w9968cf_read_sb(struct w9968cf_device*);
426 static int w9968cf_upload_quantizationtables(struct w9968cf_device*);
427 static void w9968cf_urb_complete(struct urb *urb, struct pt_regs *regs);
428
429 /* Low-level I2C (SMBus) I/O */
430 static int w9968cf_smbus_start(struct w9968cf_device*);
431 static int w9968cf_smbus_stop(struct w9968cf_device*);
432 static int w9968cf_smbus_write_byte(struct w9968cf_device*, u8 v);
433 static int w9968cf_smbus_read_byte(struct w9968cf_device*, u8* v);
434 static int w9968cf_smbus_write_ack(struct w9968cf_device*);
435 static int w9968cf_smbus_read_ack(struct w9968cf_device*);
436 static int w9968cf_smbus_refresh_bus(struct w9968cf_device*);
437 static int w9968cf_i2c_adap_read_byte(struct w9968cf_device* cam,
438                                       u16 address, u8* value);
439 static int w9968cf_i2c_adap_read_byte_data(struct w9968cf_device*, u16 address, 
440                                            u8 subaddress, u8* value);
441 static int w9968cf_i2c_adap_write_byte(struct w9968cf_device*,
442                                        u16 address, u8 subaddress);
443 static int w9968cf_i2c_adap_fastwrite_byte_data(struct w9968cf_device*,
444                                                 u16 address, u8 subaddress,
445                                                 u8 value);
446
447 /* I2C interface to kernel */
448 static int w9968cf_i2c_init(struct w9968cf_device*);
449 static int w9968cf_i2c_smbus_xfer(struct i2c_adapter*, u16 addr, 
450                                   unsigned short flags, char read_write, 
451                                   u8 command, int size, union i2c_smbus_data*);
452 static u32 w9968cf_i2c_func(struct i2c_adapter*);
453 static int w9968cf_i2c_attach_inform(struct i2c_client*);
454 static int w9968cf_i2c_detach_inform(struct i2c_client*);
455 static int w9968cf_i2c_control(struct i2c_adapter*, unsigned int cmd,
456                                unsigned long arg);
457
458 /* Memory management */
459 static void* rvmalloc(unsigned long size);
460 static void rvfree(void *mem, unsigned long size);
461 static void w9968cf_deallocate_memory(struct w9968cf_device*);
462 static int  w9968cf_allocate_memory(struct w9968cf_device*);
463
464 /* High-level image sensor control functions */
465 static int w9968cf_sensor_set_control(struct w9968cf_device*,int cid,int val);
466 static int w9968cf_sensor_get_control(struct w9968cf_device*,int cid,int *val);
467 static int w9968cf_sensor_cmd(struct w9968cf_device*,
468                               unsigned int cmd, void *arg);
469 static int w9968cf_sensor_init(struct w9968cf_device*);
470 static int w9968cf_sensor_update_settings(struct w9968cf_device*);
471 static int w9968cf_sensor_get_picture(struct w9968cf_device*);
472 static int w9968cf_sensor_update_picture(struct w9968cf_device*, 
473                                          struct video_picture pict);
474
475 /* Other helper functions */
476 static void w9968cf_configure_camera(struct w9968cf_device*,struct usb_device*,
477                                      enum w9968cf_model_id, 
478                                      const unsigned short dev_nr);
479 static void w9968cf_adjust_configuration(struct w9968cf_device*);
480 static int w9968cf_turn_on_led(struct w9968cf_device*);
481 static int w9968cf_init_chip(struct w9968cf_device*);
482 static inline u16 w9968cf_valid_palette(u16 palette);
483 static inline u16 w9968cf_valid_depth(u16 palette);
484 static inline u8 w9968cf_need_decompression(u16 palette);
485 static int w9968cf_set_picture(struct w9968cf_device*, struct video_picture);
486 static int w9968cf_set_window(struct w9968cf_device*, struct video_window);
487 static int w9968cf_postprocess_frame(struct w9968cf_device*, 
488                                      struct w9968cf_frame_t*);
489 static int w9968cf_adjust_window_size(struct w9968cf_device*, u16* w, u16* h);
490 static void w9968cf_init_framelist(struct w9968cf_device*);
491 static void w9968cf_push_frame(struct w9968cf_device*, u8 f_num);
492 static void w9968cf_pop_frame(struct w9968cf_device*,struct w9968cf_frame_t**);
493 static void w9968cf_release_resources(struct w9968cf_device*);
494
495 /* Intermodule communication */
496 static int w9968cf_vppmod_detect(struct w9968cf_device*);
497 static void w9968cf_vppmod_release(struct w9968cf_device*);
498
499
500
501 /****************************************************************************
502  * Symbolic names                                                           *
503  ****************************************************************************/
504
505 /* Used to represent a list of values and their respective symbolic names */
506 struct w9968cf_symbolic_list {
507         const int num;
508         const char *name;
509 };
510
511 /*-------------------------------------------------------------------------- 
512   Returns the name of the matching element in the symbolic_list array. The
513   end of the list must be marked with an element that has a NULL name.
514   --------------------------------------------------------------------------*/
515 static inline const char * 
516 symbolic(struct w9968cf_symbolic_list list[], const int num)
517 {
518         int i;
519
520         for (i = 0; list[i].name != NULL; i++)
521                 if (list[i].num == num)
522                         return (list[i].name);
523
524         return "Unknown";
525 }
526
527 static struct w9968cf_symbolic_list camlist[] = {
528         { W9968CF_MOD_GENERIC, "W996[87]CF JPEG USB Dual Mode Camera" },
529         { W9968CF_MOD_CLVBWGP, "Creative Labs Video Blaster WebCam Go Plus" },
530
531         /* Other cameras (having the same descriptors as Generic W996[87]CF) */
532         { W9968CF_MOD_ADPVDMA, "Aroma Digi Pen VGA Dual Mode ADG-5000" },
533         { W9986CF_MOD_AAU, "AVerMedia AVerTV USB" },
534         { W9968CF_MOD_CLVBWG, "Creative Labs Video Blaster WebCam Go" },
535         { W9968CF_MOD_LL, "Lebon LDC-035A" },
536         { W9968CF_MOD_EEEMC, "Ezonics EZ-802 EZMega Cam" },
537         { W9968CF_MOD_OOE, "OmniVision OV8610-EDE" },
538         { W9968CF_MOD_ODPVDMPC, "OPCOM Digi Pen VGA Dual Mode Pen Camera" },
539         { W9968CF_MOD_PDPII, "Pretec Digi Pen-II" },
540         { W9968CF_MOD_PDP480, "Pretec DigiPen-480" },
541
542         {  -1, NULL }
543 };
544
545 static struct w9968cf_symbolic_list senlist[] = {
546         { CC_OV76BE,   "OV76BE" },
547         { CC_OV7610,   "OV7610" },
548         { CC_OV7620,   "OV7620" },
549         { CC_OV7620AE, "OV7620AE" },
550         { CC_OV6620,   "OV6620" },
551         { CC_OV6630,   "OV6630" },
552         { CC_OV6630AE, "OV6630AE" },
553         { CC_OV6630AF, "OV6630AF" },
554         { -1, NULL }
555 };
556
557 /* Video4Linux1 palettes */
558 static struct w9968cf_symbolic_list v4l1_plist[] = {
559         { VIDEO_PALETTE_GREY,    "GREY" },
560         { VIDEO_PALETTE_HI240,   "HI240" },
561         { VIDEO_PALETTE_RGB565,  "RGB565" },
562         { VIDEO_PALETTE_RGB24,   "RGB24" },
563         { VIDEO_PALETTE_RGB32,   "RGB32" },
564         { VIDEO_PALETTE_RGB555,  "RGB555" },
565         { VIDEO_PALETTE_YUV422,  "YUV422" },
566         { VIDEO_PALETTE_YUYV,    "YUYV" },
567         { VIDEO_PALETTE_UYVY,    "UYVY" },
568         { VIDEO_PALETTE_YUV420,  "YUV420" },
569         { VIDEO_PALETTE_YUV411,  "YUV411" },
570         { VIDEO_PALETTE_RAW,     "RAW" },
571         { VIDEO_PALETTE_YUV422P, "YUV422P" },
572         { VIDEO_PALETTE_YUV411P, "YUV411P" },
573         { VIDEO_PALETTE_YUV420P, "YUV420P" },
574         { VIDEO_PALETTE_YUV410P, "YUV410P" },
575         { -1, NULL }
576 };
577
578 /* Decoder error codes: */
579 static struct w9968cf_symbolic_list decoder_errlist[] = {
580         { W9968CF_DEC_ERR_CORRUPTED_DATA, "Corrupted data" },
581         { W9968CF_DEC_ERR_BUF_OVERFLOW,   "Buffer overflow" },
582         { W9968CF_DEC_ERR_NO_SOI,         "SOI marker not found" },     
583         { W9968CF_DEC_ERR_NO_SOF0,        "SOF0 marker not found" },
584         { W9968CF_DEC_ERR_NO_SOS,         "SOS marker not found" },
585         { W9968CF_DEC_ERR_NO_EOI,         "EOI marker not found" },
586         { -1, NULL }
587 };
588
589 /* URB error codes: */
590 static struct w9968cf_symbolic_list urb_errlist[] = {
591         { -ENOMEM,    "No memory for allocation of internal structures" },
592         { -ENOSPC,    "The host controller's bandwidth is already consumed" },
593         { -ENOENT,    "URB was canceled by unlink_urb" },
594         { -EXDEV,     "ISO transfer only partially completed" },
595         { -EAGAIN,    "Too match scheduled for the future" },
596         { -ENXIO,     "URB already queued" },
597         { -EFBIG,     "Too much ISO frames requested" },
598         { -ENOSR,     "Buffer error (overrun)" },
599         { -EPIPE,     "Specified endpoint is stalled (device not responding)"},
600         { -EOVERFLOW, "Babble (bad cable?)" },
601         { -EPROTO,    "Bit-stuff error (bad cable?)" },
602         { -EILSEQ,    "CRC/Timeout" },
603         { -ETIMEDOUT, "NAK (device does not respond)" },
604         { -1, NULL }
605 };
606
607
608
609 /****************************************************************************
610  * Memory management functions                                              *
611  ****************************************************************************/
612 static void* rvmalloc(unsigned long size)
613 {
614         void* mem;
615         unsigned long adr;
616
617         size = PAGE_ALIGN(size);
618         mem = vmalloc_32(size);
619         if (!mem)
620                 return NULL;
621
622         memset(mem, 0, size); /* Clear the ram out, no junk to the user */
623         adr = (unsigned long) mem;
624         while (size > 0) {
625                 SetPageReserved(vmalloc_to_page((void *)adr));
626                 adr += PAGE_SIZE;
627                 size -= PAGE_SIZE;
628         }
629
630         return mem;
631 }
632
633
634 static void rvfree(void* mem, unsigned long size)
635 {
636         unsigned long adr;
637
638         if (!mem)
639                 return;
640
641         adr = (unsigned long) mem;
642         while ((long) size > 0) {
643                 ClearPageReserved(vmalloc_to_page((void *)adr));
644                 adr += PAGE_SIZE;
645                 size -= PAGE_SIZE;
646         }
647         vfree(mem);
648 }
649
650
651 /*--------------------------------------------------------------------------
652   Deallocate previously allocated memory.
653   --------------------------------------------------------------------------*/
654 static void w9968cf_deallocate_memory(struct w9968cf_device* cam)
655 {
656         u8 i;
657
658         /* Free the isochronous transfer buffers */
659         for (i = 0; i < W9968CF_URBS; i++) {
660                 kfree(cam->transfer_buffer[i]);
661                 cam->transfer_buffer[i] = NULL;
662         }
663
664         /* Free temporary frame buffer */
665         if (cam->frame_tmp.buffer) {
666                 rvfree(cam->frame_tmp.buffer, cam->frame_tmp.size);
667                 cam->frame_tmp.buffer = NULL;
668         }
669
670         /* Free helper buffer */
671         if (cam->frame_vpp.buffer) {
672                 rvfree(cam->frame_vpp.buffer, cam->frame_vpp.size);
673                 cam->frame_vpp.buffer = NULL;
674         }
675
676         /* Free video frame buffers */
677         if (cam->frame[0].buffer) {
678                 rvfree(cam->frame[0].buffer, cam->nbuffers*cam->frame[0].size);
679                 cam->frame[0].buffer = NULL;
680         }
681
682         cam->nbuffers = 0;
683
684         DBG(5, "Memory successfully deallocated")
685 }
686
687
688 /*--------------------------------------------------------------------------
689   Allocate memory buffers for USB transfers and video frames.
690   This function is called by open() only.
691   Return 0 on success, a negative number otherwise.
692   --------------------------------------------------------------------------*/
693 static int w9968cf_allocate_memory(struct w9968cf_device* cam)
694 {
695         const u16 p_size = wMaxPacketSize[cam->altsetting-1];
696         void* buff = NULL;
697         unsigned long hw_bufsize, vpp_bufsize;
698         u8 i, bpp;
699
700         /* NOTE: Deallocation is done elsewhere in case of error */
701
702         /* Calculate the max amount of raw data per frame from the device */
703         hw_bufsize = cam->maxwidth*cam->maxheight*2;
704
705         /* Calculate the max buf. size needed for post-processing routines */
706         bpp = (w9968cf_vpp) ? 4 : 2;
707         if (cam->upscaling)
708                 vpp_bufsize = max(W9968CF_MAX_WIDTH*W9968CF_MAX_HEIGHT*bpp,
709                                   cam->maxwidth*cam->maxheight*bpp);
710         else
711                 vpp_bufsize = cam->maxwidth*cam->maxheight*bpp;
712
713         /* Allocate memory for the isochronous transfer buffers */
714         for (i = 0; i < W9968CF_URBS; i++) {
715                 if (!(cam->transfer_buffer[i] =
716                       kmalloc(W9968CF_ISO_PACKETS*p_size, GFP_KERNEL))) {
717                         DBG(1, "Couldn't allocate memory for the isochronous "
718                                "transfer buffers (%u bytes)", 
719                             p_size * W9968CF_ISO_PACKETS)
720                         return -ENOMEM;
721                 }
722                 memset(cam->transfer_buffer[i], 0, W9968CF_ISO_PACKETS*p_size);
723         }
724
725         /* Allocate memory for the temporary frame buffer */
726         if (!(cam->frame_tmp.buffer = rvmalloc(hw_bufsize))) {
727                 DBG(1, "Couldn't allocate memory for the temporary "
728                        "video frame buffer (%lu bytes)", hw_bufsize)
729                 return -ENOMEM;
730         }
731         cam->frame_tmp.size = hw_bufsize;
732         cam->frame_tmp.number = -1;
733
734         /* Allocate memory for the helper buffer */
735         if (w9968cf_vpp) {
736                 if (!(cam->frame_vpp.buffer = rvmalloc(vpp_bufsize))) {
737                         DBG(1, "Couldn't allocate memory for the helper buffer"
738                                " (%lu bytes)", vpp_bufsize)
739                         return -ENOMEM;
740                 }
741                 cam->frame_vpp.size = vpp_bufsize;
742         } else
743                 cam->frame_vpp.buffer = NULL;
744
745         /* Allocate memory for video frame buffers */
746         cam->nbuffers = cam->max_buffers;
747         while (cam->nbuffers >= 2) {
748                 if ((buff = rvmalloc(cam->nbuffers * vpp_bufsize)))
749                         break;
750                 else
751                         cam->nbuffers--;
752         }
753
754         if (!buff) {
755                 DBG(1, "Couldn't allocate memory for the video frame buffers")
756                 cam->nbuffers = 0;
757                 return -ENOMEM;
758         }
759
760         if (cam->nbuffers != cam->max_buffers)
761                 DBG(2, "Couldn't allocate memory for %u video frame buffers. "
762                        "Only memory for %u buffers has been allocated",
763                     cam->max_buffers, cam->nbuffers)
764
765         for (i = 0; i < cam->nbuffers; i++) {
766                 cam->frame[i].buffer = buff + i*vpp_bufsize;
767                 cam->frame[i].size = vpp_bufsize;
768                 cam->frame[i].number = i;
769                 /* Circular list */
770                 if (i != cam->nbuffers-1)
771                         cam->frame[i].next = &cam->frame[i+1];
772                 else
773                         cam->frame[i].next = &cam->frame[0];
774                 cam->frame[i].status = F_UNUSED;
775         }
776
777         DBG(5, "Memory successfully allocated")
778         return 0;
779 }
780
781
782
783 /****************************************************************************
784  * USB-specific functions                                                   *
785  ****************************************************************************/
786
787 /*--------------------------------------------------------------------------
788   This is an handler function which is called after the URBs are completed.
789   It collects multiple data packets coming from the camera by putting them
790   into frame buffers: one or more zero data length data packets are used to
791   mark the end of a video frame; the first non-zero data packet is the start
792   of the next video frame; if an error is encountered in a packet, the entire
793   video frame is discarded and grabbed again.
794   If there are no requested frames in the FIFO list, packets are collected into
795   a temporary buffer. 
796   --------------------------------------------------------------------------*/
797 static void w9968cf_urb_complete(struct urb *urb, struct pt_regs *regs)
798 {
799         struct w9968cf_device* cam = (struct w9968cf_device*)urb->context;
800         struct w9968cf_frame_t** f;
801         unsigned int len, status;
802         void* pos;
803         u8 i;
804         int err = 0;
805
806         if ((!cam->streaming) || cam->disconnected) {
807                 DBG(4, "Got interrupt, but not streaming")
808                 return;
809         }
810
811         /* "(*f)" will be used instead of "cam->frame_current" */
812         f = &cam->frame_current;
813
814         /* If a frame has been requested and we are grabbing into  
815            the temporary frame, we'll switch to that requested frame */
816         if ((*f) == &cam->frame_tmp && *cam->requested_frame) {
817                 if (cam->frame_tmp.status == F_GRABBING) {
818                         w9968cf_pop_frame(cam, &cam->frame_current);
819                         (*f)->status = F_GRABBING;
820                         (*f)->length = cam->frame_tmp.length;
821                         memcpy((*f)->buffer, cam->frame_tmp.buffer,
822                                (*f)->length);
823                         DBG(6, "Switched from temp. frame to frame #%d", 
824                             (*f)->number)
825                 }
826         }
827
828         for (i = 0; i < urb->number_of_packets; i++) {
829                 len = urb->iso_frame_desc[i].actual_length;
830                 status = urb->iso_frame_desc[i].status;
831                 pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;
832
833                 if (status && len != 0) {
834                         DBG(4, "URB failed, error in data packet "
835                                "(error #%u, %s)",
836                             status, symbolic(urb_errlist, status))
837                         (*f)->status = F_ERROR;
838                         continue;
839                 }
840
841                 if (len) { /* start of frame */
842
843                         if ((*f)->status == F_UNUSED) {
844                                 (*f)->status = F_GRABBING;
845                                 (*f)->length = 0;
846                         }
847
848                         /* Buffer overflows shouldn't happen, however...*/
849                         if ((*f)->length + len > (*f)->size) {
850                                 DBG(4, "Buffer overflow: bad data packets")
851                                 (*f)->status = F_ERROR;
852                         }
853
854                         if ((*f)->status == F_GRABBING) {
855                                 memcpy((*f)->buffer + (*f)->length, pos, len);
856                                 (*f)->length += len;
857                         }
858
859                 } else if ((*f)->status == F_GRABBING) { /* end of frame */
860
861                         DBG(6, "Frame #%d successfully grabbed", (*f)->number)
862
863                         if (cam->vpp_flag & VPP_DECOMPRESSION) {
864                                 err = w9968cf_vpp->check_headers((*f)->buffer,
865                                                                  (*f)->length);
866                                 if (err) {
867                                         DBG(4, "Skip corrupted frame: %s",
868                                             symbolic(decoder_errlist, err))
869                                         (*f)->status = F_UNUSED;
870                                         continue; /* grab this frame again */
871                                 }
872                         }
873
874                         (*f)->status = F_READY;
875                         (*f)->queued = 0;
876
877                         /* Take a pointer to the new frame from the FIFO list.
878                            If the list is empty,we'll use the temporary frame*/
879                         if (*cam->requested_frame)
880                                 w9968cf_pop_frame(cam, &cam->frame_current);
881                         else {
882                                 cam->frame_current = &cam->frame_tmp;
883                                 (*f)->status = F_UNUSED;
884                         }
885
886                 } else if ((*f)->status == F_ERROR)
887                         (*f)->status = F_UNUSED; /* grab it again */
888
889                 PDBGG("Frame length %lu | pack.#%u | pack.len. %u | state %d",
890                       (unsigned long)(*f)->length, i, len, (*f)->status)
891
892         } /* end for */
893
894         /* Resubmit this URB */
895         urb->dev = cam->usbdev;
896         urb->status = 0;
897         spin_lock(&cam->urb_lock);
898         if (cam->streaming)
899                 if ((err = usb_submit_urb(urb, GFP_ATOMIC))) {
900                         cam->misconfigured = 1;
901                         DBG(1, "Couldn't resubmit the URB: error %d, %s",
902                             err, symbolic(urb_errlist, err))
903                 }
904         spin_unlock(&cam->urb_lock);
905
906         /* Wake up the user process */
907         wake_up_interruptible(&cam->wait_queue);
908 }
909
910
911 /*---------------------------------------------------------------------------
912   Setup the URB structures for the isochronous transfer.
913   Submit the URBs so that the data transfer begins.
914   Return 0 on success, a negative number otherwise.
915   ---------------------------------------------------------------------------*/
916 static int w9968cf_start_transfer(struct w9968cf_device* cam)
917 {
918         struct usb_device *udev = cam->usbdev;
919         struct urb* urb;
920         const u16 p_size = wMaxPacketSize[cam->altsetting-1];
921         u16 w, h, d;
922         int vidcapt;
923         u32 t_size;
924         int err = 0;
925         s8 i, j;
926
927         for (i = 0; i < W9968CF_URBS; i++) {
928                 urb = usb_alloc_urb(W9968CF_ISO_PACKETS, GFP_KERNEL);
929                 cam->urb[i] = urb;
930                 if (!urb) {
931                         for (j = 0; j < i; j++)
932                                 usb_free_urb(cam->urb[j]);
933                         DBG(1, "Couldn't allocate the URB structures")
934                         return -ENOMEM;
935                 }
936
937                 urb->dev = udev;
938                 urb->context = (void*)cam;
939                 urb->pipe = usb_rcvisocpipe(udev, 1);
940                 urb->transfer_flags = URB_ISO_ASAP;
941                 urb->number_of_packets = W9968CF_ISO_PACKETS;
942                 urb->complete = w9968cf_urb_complete;
943                 urb->transfer_buffer = cam->transfer_buffer[i];
944                 urb->transfer_buffer_length = p_size*W9968CF_ISO_PACKETS;
945                 urb->interval = 1;
946                 for (j = 0; j < W9968CF_ISO_PACKETS; j++) {
947                         urb->iso_frame_desc[j].offset = p_size*j;
948                         urb->iso_frame_desc[j].length = p_size;
949                 }
950         }
951
952         /* Transfer size per frame, in WORD ! */
953         d = cam->hw_depth;
954         w = cam->hw_width;
955         h = cam->hw_height;
956
957         t_size = (w*h*d)/16;
958
959         err = w9968cf_write_reg(cam, 0xbf17, 0x00); /* reset everything */
960         err += w9968cf_write_reg(cam, 0xbf10, 0x00); /* normal operation */
961
962         /* Transfer size */
963         err += w9968cf_write_reg(cam, t_size & 0xffff, 0x3d); /* low bits */
964         err += w9968cf_write_reg(cam, t_size >> 16, 0x3e);    /* high bits */
965
966         if (cam->vpp_flag & VPP_DECOMPRESSION)
967                 err += w9968cf_upload_quantizationtables(cam);
968
969         vidcapt = w9968cf_read_reg(cam, 0x16); /* read picture settings */
970         err += w9968cf_write_reg(cam, vidcapt|0x8000, 0x16); /* capt. enable */
971
972         err += usb_set_interface(udev, 0, cam->altsetting);
973         err += w9968cf_write_reg(cam, 0x8a05, 0x3c); /* USB FIFO enable */
974
975         if (err || (vidcapt < 0)) {
976                 for (i = 0; i < W9968CF_URBS; i++)
977                         usb_free_urb(cam->urb[i]);
978                 DBG(1, "Couldn't tell the camera to start the data transfer")
979                 return err;
980         }
981
982         w9968cf_init_framelist(cam);
983
984         /* Begin to grab into the temporary buffer */
985         cam->frame_tmp.status = F_UNUSED;
986         cam->frame_tmp.queued = 0;
987         cam->frame_current = &cam->frame_tmp;
988
989         if (!(cam->vpp_flag & VPP_DECOMPRESSION))
990                 DBG(5, "Isochronous transfer size: %lu bytes/frame", 
991                     (unsigned long)t_size*2)
992
993         DBG(5, "Starting the isochronous transfer...")
994
995         cam->streaming = 1;
996
997         /* Submit the URBs */
998         for (i = 0; i < W9968CF_URBS; i++) {
999                 err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
1000                 if (err) {
1001                         cam->streaming = 0;
1002                         for (j = i-1; j >= 0; j--) {
1003                                 usb_kill_urb(cam->urb[j]);
1004                                 usb_free_urb(cam->urb[j]);
1005                         }
1006                         DBG(1, "Couldn't send a transfer request to the "
1007                                "USB core (error #%d, %s)", err, 
1008                             symbolic(urb_errlist, err))
1009                         return err;
1010                 }
1011         }
1012
1013         return 0;
1014 }
1015
1016
1017 /*--------------------------------------------------------------------------
1018   Stop the isochronous transfer and set alternate setting to 0 (0Mb/s).
1019   Return 0 on success, a negative number otherwise.
1020   --------------------------------------------------------------------------*/
1021 static int w9968cf_stop_transfer(struct w9968cf_device* cam)
1022 {
1023         struct usb_device *udev = cam->usbdev;
1024         unsigned long lock_flags;
1025         int err = 0;
1026         s8 i;
1027
1028         if (!cam->streaming)
1029                 return 0;
1030
1031         /* This avoids race conditions with usb_submit_urb() 
1032            in the URB completition handler */
1033         spin_lock_irqsave(&cam->urb_lock, lock_flags);
1034         cam->streaming = 0;
1035         spin_unlock_irqrestore(&cam->urb_lock, lock_flags);
1036
1037         for (i = W9968CF_URBS-1; i >= 0; i--)
1038                 if (cam->urb[i]) {
1039                         usb_kill_urb(cam->urb[i]);
1040                         usb_free_urb(cam->urb[i]);
1041                         cam->urb[i] = NULL;
1042                 }
1043
1044         if (cam->disconnected)
1045                 goto exit;
1046
1047         err = w9968cf_write_reg(cam, 0x0a05, 0x3c); /* stop USB transfer */
1048         err += usb_set_interface(udev, 0, 0); /* 0 Mb/s */
1049         err += w9968cf_write_reg(cam, 0x0000, 0x39); /* disable JPEG encoder */
1050         err += w9968cf_write_reg(cam, 0x0000, 0x16); /* stop video capture */
1051
1052         if (err) {
1053                 DBG(2, "Failed to tell the camera to stop the isochronous "
1054                        "transfer. However this is not a critical error.")
1055                 return -EIO;
1056         }
1057
1058 exit:
1059         DBG(5, "Isochronous transfer stopped")
1060         return 0;
1061 }
1062
1063
1064 /*--------------------------------------------------------------------------
1065   Write a W9968CF register. 
1066   Return 0 on success, -1 otherwise.
1067   --------------------------------------------------------------------------*/
1068 static int w9968cf_write_reg(struct w9968cf_device* cam, u16 value, u16 index)
1069 {
1070         struct usb_device* udev = cam->usbdev;
1071         int res;
1072
1073         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0,
1074                               USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
1075                               value, index, NULL, 0, W9968CF_USB_CTRL_TIMEOUT);
1076
1077         if (res < 0)
1078                 DBG(4, "Failed to write a register "
1079                        "(value 0x%04X, index 0x%02X, error #%d, %s)",
1080                     value, index, res, symbolic(urb_errlist, res))
1081
1082         return (res >= 0) ? 0 : -1;
1083 }
1084
1085
1086 /*--------------------------------------------------------------------------
1087   Read a W9968CF register. 
1088   Return the register value on success, -1 otherwise.
1089   --------------------------------------------------------------------------*/
1090 static int w9968cf_read_reg(struct w9968cf_device* cam, u16 index)
1091 {
1092         struct usb_device* udev = cam->usbdev;
1093         u16* buff = cam->control_buffer;
1094         int res;
1095
1096         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 1,
1097                               USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1098                               0, index, buff, 2, W9968CF_USB_CTRL_TIMEOUT);
1099
1100         if (res < 0)
1101                 DBG(4, "Failed to read a register "
1102                        "(index 0x%02X, error #%d, %s)",
1103                     index, res, symbolic(urb_errlist, res))
1104
1105         return (res >= 0) ? (int)(*buff) : -1;
1106 }
1107
1108
1109 /*--------------------------------------------------------------------------
1110   Write 64-bit data to the fast serial bus registers.
1111   Return 0 on success, -1 otherwise.
1112   --------------------------------------------------------------------------*/
1113 static int w9968cf_write_fsb(struct w9968cf_device* cam, u16* data)
1114 {
1115         struct usb_device* udev = cam->usbdev;
1116         u16 value;
1117         int res;
1118
1119         value = *data++;
1120
1121         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0,
1122                               USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
1123                               value, 0x06, data, 6, W9968CF_USB_CTRL_TIMEOUT);
1124
1125         if (res < 0)
1126                 DBG(4, "Failed to write the FSB registers "
1127                        "(error #%d, %s)", res, symbolic(urb_errlist, res))
1128
1129         return (res >= 0) ? 0 : -1;
1130 }
1131
1132
1133 /*--------------------------------------------------------------------------
1134   Write data to the serial bus control register.
1135   Return 0 on success, a negative number otherwise.
1136   --------------------------------------------------------------------------*/
1137 static int w9968cf_write_sb(struct w9968cf_device* cam, u16 value)
1138 {
1139         int err = 0;
1140
1141         err = w9968cf_write_reg(cam, value, 0x01);
1142         udelay(W9968CF_I2C_BUS_DELAY);
1143
1144         return err;
1145 }
1146
1147
1148 /*--------------------------------------------------------------------------
1149   Read data from the serial bus control register.
1150   Return 0 on success, a negative number otherwise.
1151   --------------------------------------------------------------------------*/
1152 static int w9968cf_read_sb(struct w9968cf_device* cam)
1153 {
1154         int v = 0;
1155
1156         v = w9968cf_read_reg(cam, 0x01);
1157         udelay(W9968CF_I2C_BUS_DELAY);
1158
1159         return v;
1160 }
1161
1162
1163 /*--------------------------------------------------------------------------
1164   Upload quantization tables for the JPEG compression.
1165   This function is called by w9968cf_start_transfer().
1166   Return 0 on success, a negative number otherwise.
1167   --------------------------------------------------------------------------*/
1168 static int w9968cf_upload_quantizationtables(struct w9968cf_device* cam)
1169 {
1170         u16 a, b;
1171         int err = 0, i, j;
1172
1173         err += w9968cf_write_reg(cam, 0x0010, 0x39); /* JPEG clock enable */
1174
1175         for (i = 0, j = 0; i < 32; i++, j += 2) {
1176                 a = Y_QUANTABLE[j] | ((unsigned)(Y_QUANTABLE[j+1]) << 8);
1177                 b = UV_QUANTABLE[j] | ((unsigned)(UV_QUANTABLE[j+1]) << 8);
1178                 err += w9968cf_write_reg(cam, a, 0x40+i);
1179                 err += w9968cf_write_reg(cam, b, 0x60+i);
1180         }
1181         err += w9968cf_write_reg(cam, 0x0012, 0x39); /* JPEG encoder enable */
1182
1183         return err;
1184 }
1185
1186
1187
1188 /****************************************************************************
1189  * Low-level I2C I/O functions.                                             *
1190  * The adapter supports the following I2C transfer functions:               *
1191  * i2c_adap_fastwrite_byte_data() (at 400 kHz bit frequency only)           *
1192  * i2c_adap_read_byte_data()                                                *
1193  * i2c_adap_read_byte()                                                     *
1194  ****************************************************************************/
1195
1196 static int w9968cf_smbus_start(struct w9968cf_device* cam)
1197 {
1198         int err = 0;
1199
1200         err += w9968cf_write_sb(cam, 0x0011); /* SDE=1, SDA=0, SCL=1 */
1201         err += w9968cf_write_sb(cam, 0x0010); /* SDE=1, SDA=0, SCL=0 */
1202
1203         return err;
1204 }
1205
1206
1207 static int w9968cf_smbus_stop(struct w9968cf_device* cam)
1208 {
1209         int err = 0;
1210
1211         err += w9968cf_write_sb(cam, 0x0011); /* SDE=1, SDA=0, SCL=1 */
1212         err += w9968cf_write_sb(cam, 0x0013); /* SDE=1, SDA=1, SCL=1 */
1213
1214         return err;
1215 }
1216
1217
1218 static int w9968cf_smbus_write_byte(struct w9968cf_device* cam, u8 v)
1219 {
1220         u8 bit;
1221         int err = 0, sda;
1222
1223         for (bit = 0 ; bit < 8 ; bit++) {
1224                 sda = (v & 0x80) ? 2 : 0;
1225                 v <<= 1;
1226                 /* SDE=1, SDA=sda, SCL=0 */
1227                 err += w9968cf_write_sb(cam, 0x10 | sda);
1228                 /* SDE=1, SDA=sda, SCL=1 */
1229                 err += w9968cf_write_sb(cam, 0x11 | sda);
1230                 /* SDE=1, SDA=sda, SCL=0 */
1231                 err += w9968cf_write_sb(cam, 0x10 | sda);
1232         }
1233
1234         return err;
1235 }
1236
1237
1238 static int w9968cf_smbus_read_byte(struct w9968cf_device* cam, u8* v)
1239 {
1240         u8 bit;
1241         int err = 0;
1242
1243         *v = 0;
1244         for (bit = 0 ; bit < 8 ; bit++) {
1245                 *v <<= 1;
1246                 err += w9968cf_write_sb(cam, 0x0013);
1247                 *v |= (w9968cf_read_sb(cam) & 0x0008) ? 1 : 0;
1248                 err += w9968cf_write_sb(cam, 0x0012);
1249         }
1250
1251         return err;
1252 }
1253
1254
1255 static int w9968cf_smbus_write_ack(struct w9968cf_device* cam)
1256 {
1257         int err = 0;
1258
1259         err += w9968cf_write_sb(cam, 0x0010); /* SDE=1, SDA=0, SCL=0 */
1260         err += w9968cf_write_sb(cam, 0x0011); /* SDE=1, SDA=0, SCL=1 */
1261         err += w9968cf_write_sb(cam, 0x0010); /* SDE=1, SDA=0, SCL=0 */
1262
1263         return err;
1264 }
1265
1266
1267 static int w9968cf_smbus_read_ack(struct w9968cf_device* cam)
1268 {
1269         int err = 0, sda;
1270
1271         err += w9968cf_write_sb(cam, 0x0013); /* SDE=1, SDA=1, SCL=1 */
1272         sda = (w9968cf_read_sb(cam) & 0x08) ? 1 : 0; /* sda = SDA */
1273         err += w9968cf_write_sb(cam, 0x0012); /* SDE=1, SDA=1, SCL=0 */
1274         if (sda < 0)
1275                 err += sda;
1276         if (sda == 1) {
1277                 DBG(6, "Couldn't receive the ACK")
1278                 err += -1;
1279         }
1280
1281         return err;
1282 }
1283
1284
1285 /* This seems to refresh the communication through the serial bus */
1286 static int w9968cf_smbus_refresh_bus(struct w9968cf_device* cam)
1287 {
1288         int err = 0, j;
1289
1290         for (j = 1; j <= 10; j++) {
1291                 err = w9968cf_write_reg(cam, 0x0020, 0x01);
1292                 err += w9968cf_write_reg(cam, 0x0000, 0x01);
1293                 if (err)
1294                         break;
1295         }
1296
1297         return err;
1298 }
1299
1300
1301 /* SMBus protocol: S Addr Wr [A] Subaddr [A] Value [A] P */
1302 static int 
1303 w9968cf_i2c_adap_fastwrite_byte_data(struct w9968cf_device* cam, 
1304                                      u16 address, u8 subaddress,u8 value)
1305 {
1306         u16* data = cam->data_buffer;
1307         int err = 0;
1308
1309         err += w9968cf_smbus_refresh_bus(cam);
1310
1311         /* Enable SBUS outputs */
1312         err += w9968cf_write_sb(cam, 0x0020);
1313
1314         data[0] = 0x082f | ((address & 0x80) ? 0x1500 : 0x0);
1315         data[0] |= (address & 0x40) ? 0x4000 : 0x0;
1316         data[1] = 0x2082 | ((address & 0x40) ? 0x0005 : 0x0);
1317         data[1] |= (address & 0x20) ? 0x0150 : 0x0;
1318         data[1] |= (address & 0x10) ? 0x5400 : 0x0;
1319         data[2] = 0x8208 | ((address & 0x08) ? 0x0015 : 0x0);
1320         data[2] |= (address & 0x04) ? 0x0540 : 0x0;
1321         data[2] |= (address & 0x02) ? 0x5000 : 0x0;
1322         data[3] = 0x1d20 | ((address & 0x02) ? 0x0001 : 0x0);
1323         data[3] |= (address & 0x01) ? 0x0054 : 0x0;
1324
1325         err += w9968cf_write_fsb(cam, data);
1326
1327         data[0] = 0x8208 | ((subaddress & 0x80) ? 0x0015 : 0x0);
1328         data[0] |= (subaddress & 0x40) ? 0x0540 : 0x0;
1329         data[0] |= (subaddress & 0x20) ? 0x5000 : 0x0;
1330         data[1] = 0x0820 | ((subaddress & 0x20) ? 0x0001 : 0x0);
1331         data[1] |= (subaddress & 0x10) ? 0x0054 : 0x0;
1332         data[1] |= (subaddress & 0x08) ? 0x1500 : 0x0;
1333         data[1] |= (subaddress & 0x04) ? 0x4000 : 0x0;
1334         data[2] = 0x2082 | ((subaddress & 0x04) ? 0x0005 : 0x0);
1335         data[2] |= (subaddress & 0x02) ? 0x0150 : 0x0;
1336         data[2] |= (subaddress & 0x01) ? 0x5400 : 0x0;
1337         data[3] = 0x001d;
1338
1339         err += w9968cf_write_fsb(cam, data);
1340
1341         data[0] = 0x8208 | ((value & 0x80) ? 0x0015 : 0x0);
1342         data[0] |= (value & 0x40) ? 0x0540 : 0x0;
1343         data[0] |= (value & 0x20) ? 0x5000 : 0x0;
1344         data[1] = 0x0820 | ((value & 0x20) ? 0x0001 : 0x0);
1345         data[1] |= (value & 0x10) ? 0x0054 : 0x0;
1346         data[1] |= (value & 0x08) ? 0x1500 : 0x0;
1347         data[1] |= (value & 0x04) ? 0x4000 : 0x0;
1348         data[2] = 0x2082 | ((value & 0x04) ? 0x0005 : 0x0);
1349         data[2] |= (value & 0x02) ? 0x0150 : 0x0;
1350         data[2] |= (value & 0x01) ? 0x5400 : 0x0;
1351         data[3] = 0xfe1d;
1352
1353         err += w9968cf_write_fsb(cam, data);
1354
1355         /* Disable SBUS outputs */
1356         err += w9968cf_write_sb(cam, 0x0000);
1357
1358         if (!err)
1359                 DBG(5, "I2C write byte data done, addr.0x%04X, subaddr.0x%02X "
1360                        "value 0x%02X", address, subaddress, value)
1361         else
1362                 DBG(5, "I2C write byte data failed, addr.0x%04X, "
1363                        "subaddr.0x%02X, value 0x%02X", 
1364                     address, subaddress, value)
1365
1366         return err;
1367 }
1368
1369
1370 /* SMBus protocol: S Addr Wr [A] Subaddr [A] P S Addr+1 Rd [A] [Value] NA P */
1371 static int 
1372 w9968cf_i2c_adap_read_byte_data(struct w9968cf_device* cam, 
1373                                 u16 address, u8 subaddress, 
1374                                 u8* value)
1375 {
1376         int err = 0;
1377
1378         /* Serial data enable */
1379         err += w9968cf_write_sb(cam, 0x0013); /* don't change ! */
1380
1381         err += w9968cf_smbus_start(cam);
1382         err += w9968cf_smbus_write_byte(cam, address);
1383         err += w9968cf_smbus_read_ack(cam);
1384         err += w9968cf_smbus_write_byte(cam, subaddress);
1385         err += w9968cf_smbus_read_ack(cam);
1386         err += w9968cf_smbus_stop(cam);
1387         err += w9968cf_smbus_start(cam);
1388         err += w9968cf_smbus_write_byte(cam, address + 1);
1389         err += w9968cf_smbus_read_ack(cam);
1390         err += w9968cf_smbus_read_byte(cam, value);
1391         err += w9968cf_smbus_write_ack(cam);
1392         err += w9968cf_smbus_stop(cam);
1393
1394         /* Serial data disable */
1395         err += w9968cf_write_sb(cam, 0x0000);
1396
1397         if (!err)
1398                 DBG(5, "I2C read byte data done, addr.0x%04X, "
1399                        "subaddr.0x%02X, value 0x%02X", 
1400                     address, subaddress, *value)
1401         else
1402                 DBG(5, "I2C read byte data failed, addr.0x%04X, "
1403                        "subaddr.0x%02X, wrong value 0x%02X",
1404                     address, subaddress, *value)
1405
1406         return err;
1407 }
1408
1409
1410 /* SMBus protocol: S Addr+1 Rd [A] [Value] NA P */
1411 static int 
1412 w9968cf_i2c_adap_read_byte(struct w9968cf_device* cam,
1413                            u16 address, u8* value)
1414 {
1415         int err = 0;
1416
1417         /* Serial data enable */
1418         err += w9968cf_write_sb(cam, 0x0013);
1419
1420         err += w9968cf_smbus_start(cam);
1421         err += w9968cf_smbus_write_byte(cam, address + 1);
1422         err += w9968cf_smbus_read_ack(cam);
1423         err += w9968cf_smbus_read_byte(cam, value);
1424         err += w9968cf_smbus_write_ack(cam);
1425         err += w9968cf_smbus_stop(cam);
1426  
1427         /* Serial data disable */
1428         err += w9968cf_write_sb(cam, 0x0000);
1429
1430         if (!err)
1431                 DBG(5, "I2C read byte done, addr.0x%04X, "
1432                        "value 0x%02X", address, *value)
1433         else
1434                 DBG(5, "I2C read byte failed, addr.0x%04X, "
1435                        "wrong value 0x%02X", address, *value)
1436
1437         return err;
1438 }
1439
1440
1441 /* SMBus protocol: S Addr Wr [A] Value [A] P */
1442 static int 
1443 w9968cf_i2c_adap_write_byte(struct w9968cf_device* cam,
1444                             u16 address, u8 value)
1445 {
1446         DBG(4, "i2c_write_byte() is an unsupported transfer mode")
1447         return -EINVAL;
1448 }
1449
1450
1451
1452 /****************************************************************************
1453  * I2C interface to kernel                                                  *
1454  ****************************************************************************/
1455
1456 static int
1457 w9968cf_i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, 
1458                        unsigned short flags, char read_write, u8 command,
1459                        int size, union i2c_smbus_data *data)
1460 {
1461         struct w9968cf_device* cam = i2c_get_adapdata(adapter);
1462         u8 i;
1463         int err = 0; 
1464
1465         switch (addr) {
1466                 case OV6xx0_SID:
1467                 case OV7xx0_SID:
1468                         break;
1469                 default:
1470                         DBG(4, "Rejected slave ID 0x%04X", addr)
1471                         return -EINVAL;
1472         }
1473
1474         if (size == I2C_SMBUS_BYTE) {
1475                 /* Why addr <<= 1? See OVXXX0_SID defines in ovcamchip.h */
1476                 addr <<= 1;
1477
1478                 if (read_write == I2C_SMBUS_WRITE)
1479                         err = w9968cf_i2c_adap_write_byte(cam, addr, command);
1480                 else if (read_write == I2C_SMBUS_READ) 
1481                         err = w9968cf_i2c_adap_read_byte(cam,addr,&data->byte);
1482
1483         } else if (size == I2C_SMBUS_BYTE_DATA) {
1484                 addr <<= 1;
1485
1486                 if (read_write == I2C_SMBUS_WRITE)
1487                         err = w9968cf_i2c_adap_fastwrite_byte_data(cam, addr,
1488                                                           command, data->byte);
1489                 else if (read_write == I2C_SMBUS_READ) {
1490                         for (i = 1; i <= W9968CF_I2C_RW_RETRIES; i++) {
1491                                 err = w9968cf_i2c_adap_read_byte_data(cam,addr,
1492                                                          command, &data->byte);
1493                                 if (err) {
1494                                         if (w9968cf_smbus_refresh_bus(cam)) {
1495                                                 err = -EIO;
1496                                                 break;
1497                                         }
1498                                 } else
1499                                         break;
1500                         }
1501
1502                 } else
1503                         return -EINVAL;
1504
1505         } else {
1506                 DBG(4, "Unsupported I2C transfer mode (%d)", size)
1507                 return -EINVAL;
1508         }
1509
1510         return err;
1511 }
1512
1513
1514 static u32 w9968cf_i2c_func(struct i2c_adapter* adap)
1515 {
1516         return I2C_FUNC_SMBUS_READ_BYTE |
1517                I2C_FUNC_SMBUS_READ_BYTE_DATA  |
1518                I2C_FUNC_SMBUS_WRITE_BYTE_DATA;
1519 }
1520
1521
1522 static int w9968cf_i2c_attach_inform(struct i2c_client* client)
1523 {
1524         struct w9968cf_device* cam = i2c_get_adapdata(client->adapter);
1525         int id = client->driver->id, err = 0;
1526
1527         if (id == I2C_DRIVERID_OVCAMCHIP) {
1528                 cam->sensor_client = client;
1529                 err = w9968cf_sensor_init(cam);
1530                 if (err) {
1531                         cam->sensor_client = NULL;
1532                         return err;
1533                 }
1534         } else {
1535                 DBG(4, "Rejected client [%s] with driver [%s]", 
1536                     client->name, client->driver->driver.name)
1537                 return -EINVAL;
1538         }
1539
1540         DBG(5, "I2C attach client [%s] with driver [%s]",
1541             client->name, client->driver->driver.name)
1542
1543         return 0;
1544 }
1545
1546
1547 static int w9968cf_i2c_detach_inform(struct i2c_client* client)
1548 {
1549         struct w9968cf_device* cam = i2c_get_adapdata(client->adapter);
1550
1551         if (cam->sensor_client == client)
1552                 cam->sensor_client = NULL;
1553
1554         DBG(5, "I2C detach client [%s]", client->name)
1555
1556         return 0;
1557 }
1558
1559
1560 static int 
1561 w9968cf_i2c_control(struct i2c_adapter* adapter, unsigned int cmd,
1562                     unsigned long arg)
1563 {
1564         return 0;
1565 }
1566
1567
1568 static int w9968cf_i2c_init(struct w9968cf_device* cam)
1569 {
1570         int err = 0;
1571
1572         static struct i2c_algorithm algo = {
1573                 .smbus_xfer =    w9968cf_i2c_smbus_xfer,
1574                 .algo_control =  w9968cf_i2c_control,
1575                 .functionality = w9968cf_i2c_func,
1576         };
1577
1578         static struct i2c_adapter adap = {
1579                 .id =                I2C_HW_SMBUS_W9968CF,
1580                 .class =             I2C_CLASS_CAM_DIGITAL,
1581                 .owner =             THIS_MODULE,
1582                 .client_register =   w9968cf_i2c_attach_inform,
1583                 .client_unregister = w9968cf_i2c_detach_inform,
1584                 .algo =              &algo,
1585         };
1586
1587         memcpy(&cam->i2c_adapter, &adap, sizeof(struct i2c_adapter));
1588         strcpy(cam->i2c_adapter.name, "w9968cf");
1589         i2c_set_adapdata(&cam->i2c_adapter, cam);
1590
1591         DBG(6, "Registering I2C adapter with kernel...")
1592
1593         err = i2c_add_adapter(&cam->i2c_adapter);
1594         if (err)
1595                 DBG(1, "Failed to register the I2C adapter")
1596         else
1597                 DBG(5, "I2C adapter registered")
1598
1599         return err;
1600 }
1601
1602
1603
1604 /****************************************************************************
1605  * Helper functions                                                         *
1606  ****************************************************************************/
1607
1608 /*--------------------------------------------------------------------------
1609   Turn on the LED on some webcams. A beep should be heard too.
1610   Return 0 on success, a negative number otherwise.
1611   --------------------------------------------------------------------------*/
1612 static int w9968cf_turn_on_led(struct w9968cf_device* cam)
1613 {
1614         int err = 0;
1615
1616         err += w9968cf_write_reg(cam, 0xff00, 0x00); /* power-down */
1617         err += w9968cf_write_reg(cam, 0xbf17, 0x00); /* reset everything */
1618         err += w9968cf_write_reg(cam, 0xbf10, 0x00); /* normal operation */
1619         err += w9968cf_write_reg(cam, 0x0010, 0x01); /* serial bus, SDS high */
1620         err += w9968cf_write_reg(cam, 0x0000, 0x01); /* serial bus, SDS low */
1621         err += w9968cf_write_reg(cam, 0x0010, 0x01); /* ..high 'beep-beep' */
1622
1623         if (err)
1624                 DBG(2, "Couldn't turn on the LED")
1625
1626         DBG(5, "LED turned on")
1627
1628         return err;
1629 }
1630
1631
1632 /*--------------------------------------------------------------------------
1633   Write some registers for the device initialization.
1634   This function is called once on open().
1635   Return 0 on success, a negative number otherwise.
1636   --------------------------------------------------------------------------*/
1637 static int w9968cf_init_chip(struct w9968cf_device* cam)
1638 {
1639         unsigned long hw_bufsize = cam->maxwidth*cam->maxheight*2,
1640                       y0 = 0x0000,
1641                       u0 = y0 + hw_bufsize/2,
1642                       v0 = u0 + hw_bufsize/4,
1643                       y1 = v0 + hw_bufsize/4,
1644                       u1 = y1 + hw_bufsize/2,
1645                       v1 = u1 + hw_bufsize/4;
1646         int err = 0;
1647
1648         err += w9968cf_write_reg(cam, 0xff00, 0x00); /* power off */
1649         err += w9968cf_write_reg(cam, 0xbf10, 0x00); /* power on */
1650
1651         err += w9968cf_write_reg(cam, 0x405d, 0x03); /* DRAM timings */
1652         err += w9968cf_write_reg(cam, 0x0030, 0x04); /* SDRAM timings */
1653
1654         err += w9968cf_write_reg(cam, y0 & 0xffff, 0x20); /* Y buf.0, low */
1655         err += w9968cf_write_reg(cam, y0 >> 16, 0x21);    /* Y buf.0, high */
1656         err += w9968cf_write_reg(cam, u0 & 0xffff, 0x24); /* U buf.0, low */
1657         err += w9968cf_write_reg(cam, u0 >> 16, 0x25);    /* U buf.0, high */
1658         err += w9968cf_write_reg(cam, v0 & 0xffff, 0x28); /* V buf.0, low */
1659         err += w9968cf_write_reg(cam, v0 >> 16, 0x29);    /* V buf.0, high */
1660
1661         err += w9968cf_write_reg(cam, y1 & 0xffff, 0x22); /* Y buf.1, low */
1662         err += w9968cf_write_reg(cam, y1 >> 16, 0x23);    /* Y buf.1, high */
1663         err += w9968cf_write_reg(cam, u1 & 0xffff, 0x26); /* U buf.1, low */
1664         err += w9968cf_write_reg(cam, u1 >> 16, 0x27);    /* U buf.1, high */
1665         err += w9968cf_write_reg(cam, v1 & 0xffff, 0x2a); /* V buf.1, low */
1666         err += w9968cf_write_reg(cam, v1 >> 16, 0x2b);    /* V buf.1, high */
1667
1668         err += w9968cf_write_reg(cam, y1 & 0xffff, 0x32); /* JPEG buf 0 low */
1669         err += w9968cf_write_reg(cam, y1 >> 16, 0x33);    /* JPEG buf 0 high */
1670
1671         err += w9968cf_write_reg(cam, y1 & 0xffff, 0x34); /* JPEG buf 1 low */
1672         err += w9968cf_write_reg(cam, y1 >> 16, 0x35);    /* JPEG bug 1 high */
1673
1674         err += w9968cf_write_reg(cam, 0x0000, 0x36);/* JPEG restart interval */
1675         err += w9968cf_write_reg(cam, 0x0804, 0x37);/*JPEG VLE FIFO threshold*/
1676         err += w9968cf_write_reg(cam, 0x0000, 0x38);/* disable hw up-scaling */
1677         err += w9968cf_write_reg(cam, 0x0000, 0x3f); /* JPEG/MCTL test data */
1678
1679         err += w9968cf_set_picture(cam, cam->picture); /* this before */
1680         err += w9968cf_set_window(cam, cam->window);
1681
1682         if (err)
1683                 DBG(1, "Chip initialization failed")
1684         else
1685                 DBG(5, "Chip successfully initialized")
1686
1687         return err;
1688 }
1689
1690
1691 /*--------------------------------------------------------------------------
1692   Return non-zero if the palette is supported, 0 otherwise.
1693   --------------------------------------------------------------------------*/
1694 static inline u16 w9968cf_valid_palette(u16 palette)
1695 {
1696         u8 i = 0;
1697         while (w9968cf_formatlist[i].palette != 0) {
1698                 if (palette == w9968cf_formatlist[i].palette)
1699                         return palette;
1700                 i++;
1701         }
1702         return 0;
1703 }
1704
1705
1706 /*--------------------------------------------------------------------------
1707   Return the depth corresponding to the given palette.
1708   Palette _must_ be supported !
1709   --------------------------------------------------------------------------*/
1710 static inline u16 w9968cf_valid_depth(u16 palette)
1711 {
1712         u8 i=0;
1713         while (w9968cf_formatlist[i].palette != palette)
1714                 i++;
1715
1716         return w9968cf_formatlist[i].depth;
1717 }
1718
1719
1720 /*--------------------------------------------------------------------------
1721   Return non-zero if the format requires decompression, 0 otherwise.
1722   --------------------------------------------------------------------------*/
1723 static inline u8 w9968cf_need_decompression(u16 palette)
1724 {
1725         u8 i = 0;
1726         while (w9968cf_formatlist[i].palette != 0) {
1727                 if (palette == w9968cf_formatlist[i].palette)
1728                         return w9968cf_formatlist[i].compression;
1729                 i++;
1730         }
1731         return 0;
1732 }
1733
1734
1735 /*--------------------------------------------------------------------------
1736   Change the picture settings of the camera.
1737   Return 0 on success, a negative number otherwise.
1738   --------------------------------------------------------------------------*/
1739 static int
1740 w9968cf_set_picture(struct w9968cf_device* cam, struct video_picture pict)
1741 {
1742         u16 fmt, hw_depth, hw_palette, reg_v = 0x0000;
1743         int err = 0;
1744
1745         /* Make sure we are using a valid depth */
1746         pict.depth = w9968cf_valid_depth(pict.palette);
1747
1748         fmt = pict.palette;
1749
1750         hw_depth = pict.depth; /* depth used by the winbond chip */
1751         hw_palette = pict.palette; /* palette used by the winbond chip */
1752
1753         /* VS & HS polarities */
1754         reg_v = (cam->vs_polarity << 12) | (cam->hs_polarity << 11);
1755
1756         switch (fmt)
1757         {
1758                 case VIDEO_PALETTE_UYVY:
1759                         reg_v |= 0x0000;
1760                         cam->vpp_flag = VPP_NONE;
1761                         break;
1762                 case VIDEO_PALETTE_YUV422P:
1763                         reg_v |= 0x0002;
1764                         cam->vpp_flag = VPP_DECOMPRESSION;
1765                         break;
1766                 case VIDEO_PALETTE_YUV420:
1767                 case VIDEO_PALETTE_YUV420P:
1768                         reg_v |= 0x0003;
1769                         cam->vpp_flag = VPP_DECOMPRESSION;
1770                         break;
1771                 case VIDEO_PALETTE_YUYV:
1772                 case VIDEO_PALETTE_YUV422:
1773                         reg_v |= 0x0000;
1774                         cam->vpp_flag = VPP_SWAP_YUV_BYTES;
1775                         hw_palette = VIDEO_PALETTE_UYVY;
1776                         break;
1777                 /* Original video is used instead of RGBX palettes. 
1778                    Software conversion later. */
1779                 case VIDEO_PALETTE_GREY:
1780                 case VIDEO_PALETTE_RGB555:
1781                 case VIDEO_PALETTE_RGB565:
1782                 case VIDEO_PALETTE_RGB24:
1783                 case VIDEO_PALETTE_RGB32:
1784                         reg_v |= 0x0000; /* UYVY 16 bit is used */
1785                         hw_depth = 16;
1786                         hw_palette = VIDEO_PALETTE_UYVY;
1787                         cam->vpp_flag = VPP_UYVY_TO_RGBX;
1788                         break;
1789         }
1790
1791         /* NOTE: due to memory issues, it is better to disable the hardware
1792                  double buffering during compression */
1793         if (cam->double_buffer && !(cam->vpp_flag & VPP_DECOMPRESSION))
1794                 reg_v |= 0x0080;
1795
1796         if (cam->clamping)
1797                 reg_v |= 0x0020;
1798
1799         if (cam->filter_type == 1)
1800                 reg_v |= 0x0008;
1801         else if (cam->filter_type == 2)
1802                 reg_v |= 0x000c;
1803
1804         if ((err = w9968cf_write_reg(cam, reg_v, 0x16)))
1805                 goto error;
1806
1807         if ((err = w9968cf_sensor_update_picture(cam, pict)))
1808                 goto error;
1809
1810         /* If all went well, update the device data structure */
1811         memcpy(&cam->picture, &pict, sizeof(pict));
1812         cam->hw_depth = hw_depth;
1813         cam->hw_palette = hw_palette;
1814
1815         /* Settings changed, so we clear the frame buffers */
1816         memset(cam->frame[0].buffer, 0, cam->nbuffers*cam->frame[0].size);
1817
1818         DBG(4, "Palette is %s, depth is %u bpp",
1819             symbolic(v4l1_plist, pict.palette), pict.depth)
1820
1821         return 0;
1822
1823 error:
1824         DBG(1, "Failed to change picture settings")
1825         return err;
1826 }
1827
1828
1829 /*--------------------------------------------------------------------------
1830   Change the capture area size of the camera.
1831   This function _must_ be called _after_ w9968cf_set_picture().
1832   Return 0 on success, a negative number otherwise.
1833   --------------------------------------------------------------------------*/
1834 static int
1835 w9968cf_set_window(struct w9968cf_device* cam, struct video_window win)
1836 {
1837         u16 x, y, w, h, scx, scy, cw, ch, ax, ay;
1838         unsigned long fw, fh;
1839         struct ovcamchip_window s_win;
1840         int err = 0;
1841
1842         /* Work around to avoid FP arithmetics */
1843         #define __SC(x) ((x) << 10)
1844         #define __UNSC(x) ((x) >> 10)
1845
1846         /* Make sure we are using a supported resolution */
1847         if ((err = w9968cf_adjust_window_size(cam, (u16*)&win.width, 
1848                                               (u16*)&win.height)))
1849                 goto error;
1850
1851         /* Scaling factors */
1852         fw = __SC(win.width) / cam->maxwidth;
1853         fh = __SC(win.height) / cam->maxheight;
1854
1855         /* Set up the width and height values used by the chip */
1856         if ((win.width > cam->maxwidth) || (win.height > cam->maxheight)) {
1857                 cam->vpp_flag |= VPP_UPSCALE;
1858                 /* Calculate largest w,h mantaining the same w/h ratio */
1859                 w = (fw >= fh) ? cam->maxwidth : __SC(win.width)/fh;
1860                 h = (fw >= fh) ? __SC(win.height)/fw : cam->maxheight;
1861                 if (w < cam->minwidth) /* just in case */
1862                         w = cam->minwidth;
1863                 if (h < cam->minheight) /* just in case */
1864                         h = cam->minheight;
1865         } else {
1866                 cam->vpp_flag &= ~VPP_UPSCALE;
1867                 w = win.width;
1868                 h = win.height;
1869         }
1870
1871         /* x,y offsets of the cropped area */
1872         scx = cam->start_cropx;
1873         scy = cam->start_cropy;
1874
1875         /* Calculate cropped area manteining the right w/h ratio */
1876         if (cam->largeview && !(cam->vpp_flag & VPP_UPSCALE)) {
1877                 cw = (fw >= fh) ? cam->maxwidth : __SC(win.width)/fh;
1878                 ch = (fw >= fh) ? __SC(win.height)/fw : cam->maxheight;
1879         } else {
1880                 cw = w;
1881                 ch = h;
1882         }
1883
1884         /* Setup the window of the sensor */
1885         s_win.format = VIDEO_PALETTE_UYVY;
1886         s_win.width = cam->maxwidth;
1887         s_win.height = cam->maxheight;
1888         s_win.quarter = 0; /* full progressive video */
1889
1890         /* Center it */
1891         s_win.x = (s_win.width - cw) / 2;
1892         s_win.y = (s_win.height - ch) / 2;
1893
1894         /* Clock divisor */
1895         if (cam->clockdiv >= 0)
1896                 s_win.clockdiv = cam->clockdiv; /* manual override */
1897         else
1898                 switch (cam->sensor) {
1899                         case CC_OV6620:
1900                                 s_win.clockdiv = 0;
1901                                 break;
1902                         case CC_OV6630:
1903                                 s_win.clockdiv = 0;
1904                                 break;
1905                         case CC_OV76BE:
1906                         case CC_OV7610:
1907                         case CC_OV7620:
1908                                 s_win.clockdiv = 0;
1909                                 break;
1910                         default:
1911                                 s_win.clockdiv = W9968CF_DEF_CLOCKDIVISOR;
1912                 }
1913
1914         /* We have to scale win.x and win.y offsets */
1915         if ( (cam->largeview && !(cam->vpp_flag & VPP_UPSCALE))
1916              || (cam->vpp_flag & VPP_UPSCALE) ) {
1917                 ax = __SC(win.x)/fw;
1918                 ay = __SC(win.y)/fh;
1919         } else {
1920                 ax = win.x;
1921                 ay = win.y;
1922         }
1923
1924         if ((ax + cw) > cam->maxwidth)
1925                 ax = cam->maxwidth - cw;
1926
1927         if ((ay + ch) > cam->maxheight)
1928                 ay = cam->maxheight - ch;
1929
1930         /* Adjust win.x, win.y */
1931         if ( (cam->largeview && !(cam->vpp_flag & VPP_UPSCALE))
1932              || (cam->vpp_flag & VPP_UPSCALE) ) {
1933                 win.x = __UNSC(ax*fw);
1934                 win.y = __UNSC(ay*fh);
1935         } else {
1936                 win.x = ax;
1937                 win.y = ay;
1938         }
1939
1940         /* Offsets used by the chip */
1941         x = ax + s_win.x;
1942         y = ay + s_win.y;
1943
1944         /* Go ! */
1945         if ((err = w9968cf_sensor_cmd(cam, OVCAMCHIP_CMD_S_MODE, &s_win)))
1946                 goto error;
1947
1948         err += w9968cf_write_reg(cam, scx + x, 0x10);
1949         err += w9968cf_write_reg(cam, scy + y, 0x11);
1950         err += w9968cf_write_reg(cam, scx + x + cw, 0x12);
1951         err += w9968cf_write_reg(cam, scy + y + ch, 0x13);
1952         err += w9968cf_write_reg(cam, w, 0x14);
1953         err += w9968cf_write_reg(cam, h, 0x15);
1954
1955         /* JPEG width & height */
1956         err += w9968cf_write_reg(cam, w, 0x30);
1957         err += w9968cf_write_reg(cam, h, 0x31);
1958
1959         /* Y & UV frame buffer strides (in WORD) */
1960         if (cam->vpp_flag & VPP_DECOMPRESSION) {
1961                 err += w9968cf_write_reg(cam, w/2, 0x2c);
1962                 err += w9968cf_write_reg(cam, w/4, 0x2d);
1963         } else
1964                 err += w9968cf_write_reg(cam, w, 0x2c);
1965
1966         if (err)
1967                 goto error;
1968
1969         /* If all went well, update the device data structure */
1970         memcpy(&cam->window, &win, sizeof(win));
1971         cam->hw_width = w;
1972         cam->hw_height = h;
1973
1974         /* Settings changed, so we clear the frame buffers */
1975         memset(cam->frame[0].buffer, 0, cam->nbuffers*cam->frame[0].size);
1976
1977         DBG(4, "The capture area is %dx%d, Offset (x,y)=(%u,%u)", 
1978             win.width, win.height, win.x, win.y)
1979
1980         PDBGG("x=%u ,y=%u, w=%u, h=%u, ax=%u, ay=%u, s_win.x=%u, s_win.y=%u, "
1981               "cw=%u, ch=%u, win.x=%u, win.y=%u, win.width=%u, win.height=%u",
1982               x, y, w, h, ax, ay, s_win.x, s_win.y, cw, ch, win.x, win.y,
1983               win.width, win.height)
1984
1985         return 0;
1986
1987 error:
1988         DBG(1, "Failed to change the capture area size")
1989         return err;
1990 }
1991
1992
1993 /*-------------------------------------------------------------------------- 
1994   Adjust the asked values for window width and height.
1995   Return 0 on success, -1 otherwise.
1996   --------------------------------------------------------------------------*/
1997 static int 
1998 w9968cf_adjust_window_size(struct w9968cf_device* cam, u16* width, u16* height)
1999 {
2000         u16 maxw, maxh;
2001
2002         if ((*width < cam->minwidth) || (*height < cam->minheight))
2003                 return -ERANGE;
2004
2005         maxw = cam->upscaling && !(cam->vpp_flag & VPP_DECOMPRESSION) &&
2006                w9968cf_vpp ? max((u16)W9968CF_MAX_WIDTH, cam->maxwidth)
2007                            : cam->maxwidth;
2008         maxh = cam->upscaling && !(cam->vpp_flag & VPP_DECOMPRESSION) &&
2009                w9968cf_vpp ? max((u16)W9968CF_MAX_HEIGHT, cam->maxheight)
2010                            : cam->maxheight;
2011
2012         if (*width > maxw)
2013                 *width = maxw;
2014         if (*height > maxh)
2015                 *height = maxh;
2016
2017         if (cam->vpp_flag & VPP_DECOMPRESSION) {
2018                 *width  &= ~15L; /* multiple of 16 */
2019                 *height &= ~15L;
2020         }
2021
2022         PDBGG("Window size adjusted w=%u, h=%u ", *width, *height)
2023
2024         return 0;
2025 }
2026
2027
2028 /*--------------------------------------------------------------------------
2029   Initialize the FIFO list of requested frames.
2030   --------------------------------------------------------------------------*/
2031 static void w9968cf_init_framelist(struct w9968cf_device* cam)
2032 {
2033         u8 i;
2034
2035         for (i = 0; i < cam->nbuffers; i++) {
2036                 cam->requested_frame[i] = NULL;
2037                 cam->frame[i].queued = 0;
2038                 cam->frame[i].status = F_UNUSED;
2039         }
2040 }
2041
2042
2043 /*--------------------------------------------------------------------------
2044   Add a frame in the FIFO list of requested frames.
2045   This function is called in process context.
2046   --------------------------------------------------------------------------*/
2047 static void w9968cf_push_frame(struct w9968cf_device* cam, u8 f_num)
2048 {
2049         u8 f;
2050         unsigned long lock_flags;
2051
2052         spin_lock_irqsave(&cam->flist_lock, lock_flags);
2053
2054         for (f=0; cam->requested_frame[f] != NULL; f++);
2055         cam->requested_frame[f] = &cam->frame[f_num];
2056         cam->frame[f_num].queued = 1;
2057         cam->frame[f_num].status = F_UNUSED; /* clear the status */
2058
2059         spin_unlock_irqrestore(&cam->flist_lock, lock_flags);
2060
2061         DBG(6, "Frame #%u pushed into the FIFO list. Position %u", f_num, f)
2062 }
2063
2064
2065 /*--------------------------------------------------------------------------
2066   Read, store and remove the first pointer in the FIFO list of requested
2067   frames. This function is called in interrupt context.
2068   --------------------------------------------------------------------------*/
2069 static void 
2070 w9968cf_pop_frame(struct w9968cf_device* cam, struct w9968cf_frame_t** framep)
2071 {
2072         u8 i;
2073
2074         spin_lock(&cam->flist_lock);
2075
2076         *framep = cam->requested_frame[0];
2077
2078         /* Shift the list of pointers */
2079         for (i = 0; i < cam->nbuffers-1; i++)
2080                 cam->requested_frame[i] = cam->requested_frame[i+1];
2081         cam->requested_frame[i] = NULL;
2082
2083         spin_unlock(&cam->flist_lock);
2084
2085         DBG(6,"Popped frame #%d from the list", (*framep)->number)
2086 }
2087
2088
2089 /*--------------------------------------------------------------------------
2090   High-level video post-processing routine on grabbed frames.
2091   Return 0 on success, a negative number otherwise.
2092   --------------------------------------------------------------------------*/
2093 static int 
2094 w9968cf_postprocess_frame(struct w9968cf_device* cam, 
2095                           struct w9968cf_frame_t* fr)
2096 {
2097         void *pIn = fr->buffer, *pOut = cam->frame_vpp.buffer, *tmp;
2098         u16 w = cam->window.width,
2099             h = cam->window.height,
2100             d = cam->picture.depth,
2101             fmt = cam->picture.palette,
2102             rgb = cam->force_rgb,
2103             hw_w = cam->hw_width,
2104             hw_h = cam->hw_height,
2105             hw_d = cam->hw_depth;
2106         int err = 0;
2107
2108         #define _PSWAP(pIn, pOut) {tmp = (pIn); (pIn) = (pOut); (pOut) = tmp;}
2109
2110         if (cam->vpp_flag & VPP_DECOMPRESSION) {
2111                 memcpy(pOut, pIn, fr->length);
2112                 _PSWAP(pIn, pOut)
2113                 err = w9968cf_vpp->decode(pIn, fr->length, hw_w, hw_h, pOut);
2114                 PDBGG("Compressed frame length: %lu",(unsigned long)fr->length)
2115                 fr->length = (hw_w*hw_h*hw_d)/8;
2116                 _PSWAP(pIn, pOut)
2117                 if (err) {
2118                         DBG(4, "An error occurred while decoding the frame: "
2119                                "%s", symbolic(decoder_errlist, err))
2120                         return err;
2121                 } else
2122                         DBG(6, "Frame decoded")
2123         }
2124
2125         if (cam->vpp_flag & VPP_SWAP_YUV_BYTES) {
2126                 w9968cf_vpp->swap_yuvbytes(pIn, fr->length);
2127                 DBG(6, "Original UYVY component ordering changed")
2128         }
2129
2130         if (cam->vpp_flag & VPP_UPSCALE) {
2131                 w9968cf_vpp->scale_up(pIn, pOut, hw_w, hw_h, hw_d, w, h);
2132                 fr->length = (w*h*hw_d)/8;
2133                 _PSWAP(pIn, pOut)
2134                 DBG(6, "Vertical up-scaling done: %u,%u,%ubpp->%u,%u",
2135                     hw_w, hw_h, hw_d, w, h)
2136         }
2137
2138         if (cam->vpp_flag & VPP_UYVY_TO_RGBX) {
2139                 w9968cf_vpp->uyvy_to_rgbx(pIn, fr->length, pOut, fmt, rgb);
2140                 fr->length = (w*h*d)/8;
2141                 _PSWAP(pIn, pOut)
2142                 DBG(6, "UYVY-16bit to %s conversion done", 
2143                     symbolic(v4l1_plist, fmt))
2144         }
2145
2146         if (pOut == fr->buffer)
2147                 memcpy(fr->buffer, cam->frame_vpp.buffer, fr->length);
2148
2149         return 0;
2150 }
2151
2152
2153
2154 /****************************************************************************
2155  * Image sensor control routines                                            *
2156  ****************************************************************************/
2157
2158 static int 
2159 w9968cf_sensor_set_control(struct w9968cf_device* cam, int cid, int val)
2160 {
2161         struct ovcamchip_control ctl;
2162         int err;
2163
2164         ctl.id = cid;
2165         ctl.value = val;
2166
2167         err = w9968cf_sensor_cmd(cam, OVCAMCHIP_CMD_S_CTRL, &ctl);
2168
2169         return err;
2170 }
2171
2172
2173 static int 
2174 w9968cf_sensor_get_control(struct w9968cf_device* cam, int cid, int* val)
2175 {
2176         struct ovcamchip_control ctl;
2177         int err;
2178
2179         ctl.id = cid;
2180
2181         err = w9968cf_sensor_cmd(cam, OVCAMCHIP_CMD_G_CTRL, &ctl);
2182         if (!err)
2183                 *val = ctl.value;
2184
2185         return err;
2186 }
2187
2188
2189 static int
2190 w9968cf_sensor_cmd(struct w9968cf_device* cam, unsigned int cmd, void* arg)
2191 {
2192         struct i2c_client* c = cam->sensor_client;
2193         int rc = 0;
2194
2195         if (!c || !c->driver || !c->driver->command)
2196                 return -EINVAL;
2197
2198         rc = c->driver->command(c, cmd, arg);
2199         /* The I2C driver returns -EPERM on non-supported controls */
2200         return (rc < 0 && rc != -EPERM) ? rc : 0;
2201 }
2202
2203
2204 /*--------------------------------------------------------------------------
2205   Update some settings of the image sensor.
2206   Returns: 0 on success, a negative number otherwise.
2207   --------------------------------------------------------------------------*/
2208 static int w9968cf_sensor_update_settings(struct w9968cf_device* cam)
2209 {
2210         int err = 0;
2211
2212         /* Auto brightness */
2213         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_AUTOBRIGHT, 
2214                                          cam->auto_brt);
2215         if (err)
2216                 return err;
2217
2218         /* Auto exposure */
2219         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_AUTOEXP, 
2220                                          cam->auto_exp);
2221         if (err)
2222                 return err;
2223
2224         /* Banding filter */
2225         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_BANDFILT, 
2226                                          cam->bandfilt);
2227         if (err)
2228                 return err;
2229
2230         /* Light frequency */
2231         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_FREQ,
2232                                          cam->lightfreq);
2233         if (err)
2234                 return err;
2235
2236         /* Back light */
2237         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_BACKLIGHT,
2238                                          cam->backlight);
2239         if (err)
2240                 return err;
2241
2242         /* Mirror */
2243         err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_MIRROR,
2244                                          cam->mirror);
2245         if (err)
2246                 return err;
2247
2248         return 0;
2249 }
2250
2251
2252 /*--------------------------------------------------------------------------
2253   Get some current picture settings from the image sensor and update the
2254   internal 'picture' structure of the camera.
2255   Returns: 0 on success, a negative number otherwise.
2256   --------------------------------------------------------------------------*/
2257 static int w9968cf_sensor_get_picture(struct w9968cf_device* cam)
2258 {
2259         int err, v;
2260
2261         err = w9968cf_sensor_get_control(cam, OVCAMCHIP_CID_CONT, &v);
2262         if (err)
2263                 return err;
2264         cam->picture.contrast = v;
2265
2266         err = w9968cf_sensor_get_control(cam, OVCAMCHIP_CID_BRIGHT, &v);
2267         if (err)
2268                 return err;
2269         cam->picture.brightness = v;
2270
2271         err = w9968cf_sensor_get_control(cam, OVCAMCHIP_CID_SAT, &v);
2272         if (err)
2273                 return err;
2274         cam->picture.colour = v;
2275
2276         err = w9968cf_sensor_get_control(cam, OVCAMCHIP_CID_HUE, &v);
2277         if (err)
2278                 return err;
2279         cam->picture.hue = v;
2280
2281         DBG(5, "Got picture settings from the image sensor")
2282
2283         PDBGG("Brightness, contrast, hue, colour, whiteness are "
2284               "%u,%u,%u,%u,%u", cam->picture.brightness,cam->picture.contrast,
2285               cam->picture.hue, cam->picture.colour, cam->picture.whiteness)
2286
2287         return 0;
2288 }
2289
2290
2291 /*--------------------------------------------------------------------------
2292   Update picture settings of the image sensor.
2293   Returns: 0 on success, a negative number otherwise.
2294   --------------------------------------------------------------------------*/
2295 static int
2296 w9968cf_sensor_update_picture(struct w9968cf_device* cam, 
2297                               struct video_picture pict)
2298 {
2299         int err = 0;
2300
2301         if ((!cam->sensor_initialized)
2302             || pict.contrast != cam->picture.contrast) {
2303                 err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_CONT,
2304                                                  pict.contrast);
2305                 if (err)
2306                         goto fail;
2307                 DBG(4, "Contrast changed from %u to %u",
2308                     cam->picture.contrast, pict.contrast)
2309                 cam->picture.contrast = pict.contrast;
2310         }
2311
2312         if (((!cam->sensor_initialized) || 
2313             pict.brightness != cam->picture.brightness) && (!cam->auto_brt)) {
2314                 err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_BRIGHT, 
2315                                                  pict.brightness);
2316                 if (err)
2317                         goto fail;
2318                 DBG(4, "Brightness changed from %u to %u",
2319                     cam->picture.brightness, pict.brightness)
2320                 cam->picture.brightness = pict.brightness;
2321         }
2322
2323         if ((!cam->sensor_initialized) || pict.colour != cam->picture.colour) {
2324                 err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_SAT, 
2325                                                  pict.colour);
2326                 if (err)
2327                         goto fail;
2328                 DBG(4, "Colour changed from %u to %u",
2329                     cam->picture.colour, pict.colour)
2330                 cam->picture.colour = pict.colour;
2331         }
2332
2333         if ((!cam->sensor_initialized) || pict.hue != cam->picture.hue) {
2334                 err = w9968cf_sensor_set_control(cam, OVCAMCHIP_CID_HUE, 
2335                                                  pict.hue);
2336                 if (err)
2337                         goto fail;
2338                 DBG(4, "Hue changed from %u to %u",
2339                     cam->picture.hue, pict.hue)
2340                 cam->picture.hue = pict.hue;
2341         }
2342
2343         return 0;
2344
2345 fail:
2346         DBG(4, "Failed to change sensor picture setting")
2347         return err;
2348 }
2349
2350
2351
2352 /****************************************************************************
2353  * Camera configuration                                                     *
2354  ****************************************************************************/
2355
2356 /*--------------------------------------------------------------------------
2357   This function is called when a supported image sensor is detected.
2358   Return 0 if the initialization succeeds, a negative number otherwise.
2359   --------------------------------------------------------------------------*/
2360 static int w9968cf_sensor_init(struct w9968cf_device* cam)
2361 {
2362         int err = 0;
2363
2364         if ((err = w9968cf_sensor_cmd(cam, OVCAMCHIP_CMD_INITIALIZE, 
2365                                       &cam->monochrome)))
2366                 goto error;
2367
2368         if ((err = w9968cf_sensor_cmd(cam, OVCAMCHIP_CMD_Q_SUBTYPE, 
2369                                       &cam->sensor)))
2370                 goto error;
2371
2372         /* NOTE: Make sure width and height are a multiple of 16 */
2373         switch (cam->sensor_client->addr) {
2374                 case OV6xx0_SID:
2375                         cam->maxwidth = 352;
2376                         cam->maxheight = 288;
2377                         cam->minwidth = 64;
2378                         cam->minheight = 48;
2379                         break;
2380                 case OV7xx0_SID:
2381                         cam->maxwidth = 640;
2382                         cam->maxheight = 480;
2383                         cam->minwidth = 64;
2384                         cam->minheight = 48;
2385                         break;
2386                 default:
2387                         DBG(1, "Not supported image sensor detected for %s",
2388                             symbolic(camlist, cam->id))
2389                         return -EINVAL;
2390         }
2391
2392         /* These values depend on the ones in the ovxxx0.c sources */
2393         switch (cam->sensor) {
2394                 case CC_OV7620:
2395                         cam->start_cropx = 287;
2396                         cam->start_cropy = 35;
2397                         /* Seems to work around a bug in the image sensor */
2398                         cam->vs_polarity = 1;
2399                         cam->hs_polarity = 1;
2400                         break;
2401                 default:
2402                         cam->start_cropx = 320;
2403                         cam->start_cropy = 35;
2404                         cam->vs_polarity = 1;
2405                         cam->hs_polarity = 0;
2406         }
2407
2408         if ((err = w9968cf_sensor_update_settings(cam)))
2409                 goto error;
2410
2411         if ((err = w9968cf_sensor_update_picture(cam, cam->picture)))
2412                 goto error;
2413
2414         cam->sensor_initialized = 1;
2415
2416         DBG(2, "%s image sensor initialized", symbolic(senlist, cam->sensor))
2417         return 0;
2418
2419 error:
2420         cam->sensor_initialized = 0;
2421         cam->sensor = CC_UNKNOWN;
2422         DBG(1, "Image sensor initialization failed for %s (/dev/video%d). "
2423                "Try to detach and attach this device again",
2424             symbolic(camlist, cam->id), cam->v4ldev->minor)
2425         return err;
2426 }
2427
2428
2429 /*--------------------------------------------------------------------------
2430   Fill some basic fields in the main device data structure.
2431   This function is called once on w9968cf_usb_probe() for each recognized 
2432   camera.
2433   --------------------------------------------------------------------------*/
2434 static void
2435 w9968cf_configure_camera(struct w9968cf_device* cam,
2436                          struct usb_device* udev,
2437                          enum w9968cf_model_id mod_id,
2438                          const unsigned short dev_nr)
2439 {
2440         init_MUTEX(&cam->fileop_sem);
2441         init_waitqueue_head(&cam->open);
2442         spin_lock_init(&cam->urb_lock);
2443         spin_lock_init(&cam->flist_lock);
2444
2445         cam->users = 0;
2446         cam->disconnected = 0;
2447         cam->id = mod_id;
2448         cam->sensor = CC_UNKNOWN;
2449         cam->sensor_initialized = 0;
2450
2451         /* Calculate the alternate setting number (from 1 to 16)
2452            according to the 'packet_size' module parameter */
2453         if (packet_size[dev_nr] < W9968CF_MIN_PACKET_SIZE)
2454                 packet_size[dev_nr] = W9968CF_MIN_PACKET_SIZE;
2455         for (cam->altsetting = 1;
2456              packet_size[dev_nr] < wMaxPacketSize[cam->altsetting-1];
2457              cam->altsetting++);
2458
2459         cam->max_buffers = (max_buffers[dev_nr] < 2 || 
2460                             max_buffers[dev_nr] > W9968CF_MAX_BUFFERS)
2461                            ? W9968CF_BUFFERS : (u8)max_buffers[dev_nr];
2462
2463         cam->double_buffer = (double_buffer[dev_nr] == 0 || 
2464                               double_buffer[dev_nr] == 1)
2465                              ? (u8)double_buffer[dev_nr]:W9968CF_DOUBLE_BUFFER;
2466
2467         cam->clamping = (clamping[dev_nr] == 0 || clamping[dev_nr] == 1)
2468                         ? (u8)clamping[dev_nr] : W9968CF_CLAMPING;
2469         
2470         cam->filter_type = (filter_type[dev_nr] == 0 ||
2471                             filter_type[dev_nr] == 1 ||
2472                             filter_type[dev_nr] == 2)
2473                            ? (u8)filter_type[dev_nr] : W9968CF_FILTER_TYPE;
2474
2475         cam->capture = 1;
2476
2477         cam->largeview = (largeview[dev_nr] == 0 || largeview[dev_nr] == 1)
2478                          ? (u8)largeview[dev_nr] : W9968CF_LARGEVIEW;
2479
2480         cam->decompression = (decompression[dev_nr] == 0 || 
2481                               decompression[dev_nr] == 1 ||
2482                               decompression[dev_nr] == 2)
2483                              ? (u8)decompression[dev_nr]:W9968CF_DECOMPRESSION;
2484
2485         cam->upscaling = (upscaling[dev_nr] == 0 || 
2486                           upscaling[dev_nr] == 1)
2487                          ? (u8)upscaling[dev_nr] : W9968CF_UPSCALING;
2488
2489         cam->auto_brt = (autobright[dev_nr] == 0 || autobright[dev_nr] == 1)
2490                         ? (u8)autobright[dev_nr] : W9968CF_AUTOBRIGHT;
2491
2492         cam->auto_exp = (autoexp[dev_nr] == 0 || autoexp[dev_nr] == 1)
2493                         ? (u8)autoexp[dev_nr] : W9968CF_AUTOEXP;
2494
2495         cam->lightfreq = (lightfreq[dev_nr] == 50 || lightfreq[dev_nr] == 60)
2496                          ? (u8)lightfreq[dev_nr] : W9968CF_LIGHTFREQ;
2497
2498         cam->bandfilt = (bandingfilter[dev_nr] == 0 || 
2499                          bandingfilter[dev_nr] == 1)
2500                         ? (u8)bandingfilter[dev_nr] : W9968CF_BANDINGFILTER;
2501
2502         cam->backlight = (backlight[dev_nr] == 0 || backlight[dev_nr] == 1)
2503                          ? (u8)backlight[dev_nr] : W9968CF_BACKLIGHT;
2504
2505         cam->clockdiv = (clockdiv[dev_nr] == -1 || clockdiv[dev_nr] >= 0)
2506                         ? (s8)clockdiv[dev_nr] : W9968CF_CLOCKDIV;
2507
2508         cam->mirror = (mirror[dev_nr] == 0 || mirror[dev_nr] == 1)
2509                       ? (u8)mirror[dev_nr] : W9968CF_MIRROR;
2510
2511         cam->monochrome = (monochrome[dev_nr] == 0 || monochrome[dev_nr] == 1)
2512                           ? monochrome[dev_nr] : W9968CF_MONOCHROME;
2513
2514         cam->picture.brightness = (u16)brightness[dev_nr];
2515         cam->picture.hue = (u16)hue[dev_nr];
2516         cam->picture.colour = (u16)colour[dev_nr];
2517         cam->picture.contrast = (u16)contrast[dev_nr];
2518         cam->picture.whiteness = (u16)whiteness[dev_nr];
2519         if (w9968cf_valid_palette((u16)force_palette[dev_nr])) {
2520                 cam->picture.palette = (u16)force_palette[dev_nr];
2521                 cam->force_palette = 1;
2522         } else {
2523                 cam->force_palette = 0;
2524                 if (cam->decompression == 0)
2525                         cam->picture.palette = W9968CF_PALETTE_DECOMP_OFF;
2526                 else if (cam->decompression == 1)
2527                         cam->picture.palette = W9968CF_PALETTE_DECOMP_FORCE;
2528                 else
2529                         cam->picture.palette = W9968CF_PALETTE_DECOMP_ON;
2530         }
2531         cam->picture.depth = w9968cf_valid_depth(cam->picture.palette);
2532
2533         cam->force_rgb = (force_rgb[dev_nr] == 0 || force_rgb[dev_nr] == 1)
2534                          ? (u8)force_rgb[dev_nr] : W9968CF_FORCE_RGB;
2535
2536         cam->window.x = 0;
2537         cam->window.y = 0;
2538         cam->window.width = W9968CF_WIDTH;
2539         cam->window.height = W9968CF_HEIGHT;
2540         cam->window.chromakey = 0;
2541         cam->window.clipcount = 0;
2542         cam->window.flags = 0;
2543
2544         DBG(3, "%s configured with settings #%u:",
2545             symbolic(camlist, cam->id), dev_nr)
2546         
2547         DBG(3, "- Data packet size for USB isochrnous transfer: %u bytes",
2548             wMaxPacketSize[cam->altsetting-1])
2549         
2550         DBG(3, "- Number of requested video frame buffers: %u",
2551             cam->max_buffers)
2552
2553         if (cam->double_buffer)
2554                 DBG(3, "- Hardware double buffering enabled")
2555         else 
2556                 DBG(3, "- Hardware double buffering disabled")
2557
2558         if (cam->filter_type == 0)
2559                 DBG(3, "- Video filtering disabled")
2560         else if (cam->filter_type == 1)
2561                 DBG(3, "- Video filtering enabled: type 1-2-1")
2562         else if (cam->filter_type == 2)
2563                 DBG(3, "- Video filtering enabled: type 2-3-6-3-2")
2564
2565         if (cam->clamping)
2566                 DBG(3, "- Video data clamping (CCIR-601 format) enabled")
2567         else
2568                 DBG(3, "- Video data clamping (CCIR-601 format) disabled")
2569
2570         if (cam->largeview)
2571                 DBG(3, "- Large view enabled")
2572         else
2573                 DBG(3, "- Large view disabled")
2574
2575         if ((cam->decompression) == 0 && (!cam->force_palette))
2576                 DBG(3, "- Decompression disabled")
2577         else if ((cam->decompression) == 1 && (!cam->force_palette))
2578                 DBG(3, "- Decompression forced")
2579         else if ((cam->decompression) == 2 && (!cam->force_palette))
2580                 DBG(3, "- Decompression allowed")
2581
2582         if (cam->upscaling)
2583                 DBG(3, "- Software image scaling enabled")
2584         else
2585                 DBG(3, "- Software image scaling disabled")
2586
2587         if (cam->force_palette)
2588                 DBG(3, "- Image palette forced to %s",
2589                     symbolic(v4l1_plist, cam->picture.palette))
2590
2591         if (cam->force_rgb)
2592                 DBG(3, "- RGB component ordering will be used instead of BGR")
2593
2594         if (cam->auto_brt)
2595                 DBG(3, "- Auto brightness enabled")
2596         else
2597                 DBG(3, "- Auto brightness disabled")
2598
2599         if (cam->auto_exp)
2600                 DBG(3, "- Auto exposure enabled")
2601         else
2602                 DBG(3, "- Auto exposure disabled")
2603
2604         if (cam->backlight)
2605                 DBG(3, "- Backlight exposure algorithm enabled")
2606         else
2607                 DBG(3, "- Backlight exposure algorithm disabled")
2608
2609         if (cam->mirror)
2610                 DBG(3, "- Mirror enabled")
2611         else
2612                 DBG(3, "- Mirror disabled")
2613
2614         if (cam->bandfilt)
2615                 DBG(3, "- Banding filter enabled")
2616         else
2617                 DBG(3, "- Banding filter disabled")
2618
2619         DBG(3, "- Power lighting frequency: %u", cam->lightfreq)
2620
2621         if (cam->clockdiv == -1)
2622                 DBG(3, "- Automatic clock divisor enabled")
2623         else
2624                 DBG(3, "- Clock divisor: %d", cam->clockdiv)
2625
2626         if (cam->monochrome)
2627                 DBG(3, "- Image sensor used as monochrome")
2628         else
2629                 DBG(3, "- Image sensor not used as monochrome")
2630 }
2631
2632
2633 /*--------------------------------------------------------------------------
2634   If the video post-processing module is not loaded, some parameters
2635   must be overridden.
2636   --------------------------------------------------------------------------*/
2637 static void w9968cf_adjust_configuration(struct w9968cf_device* cam)
2638 {
2639         if (!w9968cf_vpp) {
2640                 if (cam->decompression == 1) {
2641                         cam->decompression = 2;
2642                         DBG(2, "Video post-processing module not found: "
2643                                "'decompression' parameter forced to 2")
2644                 }
2645                 if (cam->upscaling) {
2646                         cam->upscaling = 0;
2647                         DBG(2, "Video post-processing module not found: "
2648                                "'upscaling' parameter forced to 0")
2649                 }
2650                 if (cam->picture.palette != VIDEO_PALETTE_UYVY) {
2651                         cam->force_palette = 0;
2652                         DBG(2, "Video post-processing module not found: "
2653                                "'force_palette' parameter forced to 0")
2654                 }
2655                 cam->picture.palette = VIDEO_PALETTE_UYVY;
2656                 cam->picture.depth = w9968cf_valid_depth(cam->picture.palette);
2657         }
2658 }
2659
2660
2661 /*--------------------------------------------------------------------------
2662   Release the resources used by the driver.
2663   This function is called on disconnect 
2664   (or on close if deallocation has been deferred)
2665   --------------------------------------------------------------------------*/
2666 static void w9968cf_release_resources(struct w9968cf_device* cam)
2667 {
2668         down(&w9968cf_devlist_sem);
2669
2670         DBG(2, "V4L device deregistered: /dev/video%d", cam->v4ldev->minor)
2671
2672         video_unregister_device(cam->v4ldev);
2673         list_del(&cam->v4llist);
2674         i2c_del_adapter(&cam->i2c_adapter);
2675         w9968cf_deallocate_memory(cam);
2676         kfree(cam->control_buffer);
2677         kfree(cam->data_buffer);
2678
2679         up(&w9968cf_devlist_sem);
2680 }
2681
2682
2683
2684 /****************************************************************************
2685  * Video4Linux interface                                                    *
2686  ****************************************************************************/
2687
2688 static int w9968cf_open(struct inode* inode, struct file* filp)
2689 {
2690         struct w9968cf_device* cam;
2691         int err;
2692
2693         /* This the only safe way to prevent race conditions with disconnect */
2694         if (!down_read_trylock(&w9968cf_disconnect))
2695                 return -ERESTARTSYS;
2696
2697         cam = (struct w9968cf_device*)video_get_drvdata(video_devdata(filp));
2698
2699         down(&cam->dev_sem);
2700
2701         if (cam->sensor == CC_UNKNOWN) {
2702                 DBG(2, "No supported image sensor has been detected by the "
2703                        "'ovcamchip' module for the %s (/dev/video%d). Make "
2704                        "sure it is loaded *before* (re)connecting the camera.",
2705                     symbolic(camlist, cam->id), cam->v4ldev->minor)
2706                 up(&cam->dev_sem);
2707                 up_read(&w9968cf_disconnect);
2708                 return -ENODEV;
2709         }
2710
2711         if (cam->users) {
2712                 DBG(2, "%s (/dev/video%d) has been already occupied by '%s'",
2713                     symbolic(camlist, cam->id),cam->v4ldev->minor,cam->command)
2714                 if ((filp->f_flags & O_NONBLOCK)||(filp->f_flags & O_NDELAY)) {
2715                         up(&cam->dev_sem);
2716                         up_read(&w9968cf_disconnect);
2717                         return -EWOULDBLOCK;
2718                 }
2719                 up(&cam->dev_sem);
2720                 err = wait_event_interruptible_exclusive(cam->open,
2721                                                          cam->disconnected ||
2722                                                          !cam->users);
2723                 if (err) {
2724                         up_read(&w9968cf_disconnect);
2725                         return err;
2726                 }
2727                 if (cam->disconnected) {
2728                         up_read(&w9968cf_disconnect);
2729                         return -ENODEV;
2730                 }
2731                 down(&cam->dev_sem);
2732         }
2733
2734         DBG(5, "Opening '%s', /dev/video%d ...",
2735             symbolic(camlist, cam->id), cam->v4ldev->minor)
2736
2737         cam->streaming = 0;
2738         cam->misconfigured = 0;
2739
2740         if (!w9968cf_vpp)
2741                 if ((err = w9968cf_vppmod_detect(cam)))
2742                         goto out;
2743
2744         if ((err = w9968cf_allocate_memory(cam)))
2745                 goto deallocate_memory;
2746
2747         if ((err = w9968cf_init_chip(cam)))
2748                 goto deallocate_memory;
2749
2750         if ((err = w9968cf_start_transfer(cam)))
2751                 goto deallocate_memory;
2752
2753         filp->private_data = cam;
2754
2755         cam->users++;
2756         strcpy(cam->command, current->comm);
2757
2758         init_waitqueue_head(&cam->wait_queue);
2759
2760         DBG(5, "Video device is open")
2761
2762         up(&cam->dev_sem);
2763         up_read(&w9968cf_disconnect);
2764
2765         return 0;
2766
2767 deallocate_memory:
2768         w9968cf_deallocate_memory(cam);
2769 out:
2770         DBG(2, "Failed to open the video device")
2771         up(&cam->dev_sem);
2772         up_read(&w9968cf_disconnect);
2773         return err;
2774 }
2775
2776
2777 static int w9968cf_release(struct inode* inode, struct file* filp)
2778 {
2779         struct w9968cf_device* cam;
2780
2781         cam = (struct w9968cf_device*)video_get_drvdata(video_devdata(filp));
2782
2783         down(&cam->dev_sem); /* prevent disconnect() to be called */
2784
2785         w9968cf_stop_transfer(cam);
2786
2787         w9968cf_vppmod_release(cam);
2788
2789         if (cam->disconnected) {
2790                 w9968cf_release_resources(cam);
2791                 up(&cam->dev_sem);
2792                 kfree(cam);
2793                 return 0;
2794         }
2795
2796         cam->users--;
2797         w9968cf_deallocate_memory(cam);
2798         wake_up_interruptible_nr(&cam->open, 1);
2799
2800         DBG(5, "Video device closed")
2801         up(&cam->dev_sem);
2802         return 0;
2803 }
2804
2805
2806 static ssize_t
2807 w9968cf_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
2808 {
2809         struct w9968cf_device* cam;
2810         struct w9968cf_frame_t* fr;
2811         int err = 0;
2812
2813         cam = (struct w9968cf_device*)video_get_drvdata(video_devdata(filp));
2814
2815         if (filp->f_flags & O_NONBLOCK)
2816                 return -EWOULDBLOCK;
2817
2818         if (down_interruptible(&cam->fileop_sem))
2819                 return -ERESTARTSYS;
2820
2821         if (cam->disconnected) {
2822                 DBG(2, "Device not present")
2823                 up(&cam->fileop_sem);
2824                 return -ENODEV;
2825         }
2826
2827         if (cam->misconfigured) {
2828                 DBG(2, "The camera is misconfigured. Close and open it again.")
2829                 up(&cam->fileop_sem);
2830                 return -EIO;
2831         }
2832
2833         if (!cam->frame[0].queued)
2834                 w9968cf_push_frame(cam, 0);
2835
2836         if (!cam->frame[1].queued)
2837                 w9968cf_push_frame(cam, 1);
2838
2839         err = wait_event_interruptible(cam->wait_queue,
2840                                        cam->frame[0].status == F_READY ||
2841                                        cam->frame[1].status == F_READY ||
2842                                        cam->disconnected);
2843         if (err) {
2844                 up(&cam->fileop_sem);
2845                 return err;
2846         }
2847         if (cam->disconnected) {
2848                 up(&cam->fileop_sem);
2849                 return -ENODEV;
2850         }
2851
2852         fr = (cam->frame[0].status == F_READY) ? &cam->frame[0]:&cam->frame[1];
2853
2854         if (w9968cf_vpp)
2855                 w9968cf_postprocess_frame(cam, fr);
2856
2857         if (count > fr->length)
2858                 count = fr->length;
2859
2860         if (copy_to_user(buf, fr->buffer, count)) {
2861                 fr->status = F_UNUSED;
2862                 up(&cam->fileop_sem);
2863                 return -EFAULT;
2864         }
2865         *f_pos += count;
2866
2867         fr->status = F_UNUSED;
2868
2869         DBG(5, "%zu bytes read", count)
2870
2871         up(&cam->fileop_sem);
2872         return count;
2873 }
2874
2875
2876 static int w9968cf_mmap(struct file* filp, struct vm_area_struct *vma)
2877 {
2878         struct w9968cf_device* cam = (struct w9968cf_device*)
2879                                      video_get_drvdata(video_devdata(filp));
2880         unsigned long vsize = vma->vm_end - vma->vm_start,
2881                       psize = cam->nbuffers * cam->frame[0].size,
2882                       start = vma->vm_start,
2883                       pos = (unsigned long)cam->frame[0].buffer,
2884                       page;
2885
2886         if (cam->disconnected) {
2887                 DBG(2, "Device not present")
2888                 return -ENODEV;
2889         }
2890
2891         if (cam->misconfigured) {
2892                 DBG(2, "The camera is misconfigured. Close and open it again")
2893                 return -EIO;
2894         }
2895
2896         PDBGG("mmapping %lu bytes...", vsize)
2897
2898         if (vsize > psize - (vma->vm_pgoff << PAGE_SHIFT))
2899                 return -EINVAL;
2900
2901         while (vsize > 0) {
2902                 page = vmalloc_to_pfn((void *)pos);
2903                 if (remap_pfn_range(vma, start, page + vma->vm_pgoff,
2904                                                 PAGE_SIZE, vma->vm_page_prot))
2905                         return -EAGAIN;
2906                 start += PAGE_SIZE;
2907                 pos += PAGE_SIZE;
2908                 vsize -= PAGE_SIZE;
2909         }
2910
2911         DBG(5, "mmap method successfully called")
2912         return 0;
2913 }
2914
2915
2916 static int
2917 w9968cf_ioctl(struct inode* inode, struct file* filp,
2918               unsigned int cmd, unsigned long arg)
2919 {
2920         struct w9968cf_device* cam;
2921         int err;
2922
2923         cam = (struct w9968cf_device*)video_get_drvdata(video_devdata(filp));
2924
2925         if (down_interruptible(&cam->fileop_sem))
2926                 return -ERESTARTSYS;
2927
2928         if (cam->disconnected) {
2929                 DBG(2, "Device not present")
2930                 up(&cam->fileop_sem);
2931                 return -ENODEV;
2932         }
2933
2934         if (cam->misconfigured) {
2935                 DBG(2, "The camera is misconfigured. Close and open it again.")
2936                 up(&cam->fileop_sem);
2937                 return -EIO;
2938         }
2939
2940         err = w9968cf_v4l_ioctl(inode, filp, cmd, (void __user *)arg);
2941
2942         up(&cam->fileop_sem);
2943         return err;
2944 }
2945
2946
2947 static int w9968cf_v4l_ioctl(struct inode* inode, struct file* filp,
2948                              unsigned int cmd, void __user * arg)
2949 {
2950         struct w9968cf_device* cam;
2951         const char* v4l1_ioctls[] = {
2952                 "?", "CGAP", "GCHAN", "SCHAN", "GTUNER", "STUNER", 
2953                 "GPICT", "SPICT", "CCAPTURE", "GWIN", "SWIN", "GFBUF",
2954                 "SFBUF", "KEY", "GFREQ", "SFREQ", "GAUDIO", "SAUDIO",
2955                 "SYNC", "MCAPTURE", "GMBUF", "GUNIT", "GCAPTURE", "SCAPTURE",
2956                 "SPLAYMODE", "SWRITEMODE", "GPLAYINFO", "SMICROCODE", 
2957                 "GVBIFMT", "SVBIFMT" 
2958         };
2959
2960         #define V4L1_IOCTL(cmd) \
2961                 ((_IOC_NR((cmd)) < ARRAY_SIZE(v4l1_ioctls)) ? \
2962                 v4l1_ioctls[_IOC_NR((cmd))] : "?")
2963
2964         cam = (struct w9968cf_device*)video_get_drvdata(video_devdata(filp));
2965
2966         switch (cmd) {
2967
2968         case VIDIOCGCAP: /* get video capability */
2969         {
2970                 struct video_capability cap = {
2971                         .type = VID_TYPE_CAPTURE | VID_TYPE_SCALES,
2972                         .channels = 1,
2973                         .audios = 0,
2974                         .minwidth = cam->minwidth,
2975                         .minheight = cam->minheight,
2976                 };
2977                 sprintf(cap.name, "W996[87]CF USB Camera #%d", 
2978                         cam->v4ldev->minor);
2979                 cap.maxwidth = (cam->upscaling && w9968cf_vpp)
2980                                ? max((u16)W9968CF_MAX_WIDTH, cam->maxwidth) 
2981                                  : cam->maxwidth;
2982                 cap.maxheight = (cam->upscaling && w9968cf_vpp)
2983                                 ? max((u16)W9968CF_MAX_HEIGHT, cam->maxheight)
2984                                   : cam->maxheight;
2985
2986                 if (copy_to_user(arg, &cap, sizeof(cap)))
2987                         return -EFAULT;
2988
2989                 DBG(5, "VIDIOCGCAP successfully called")
2990                 return 0;
2991         }
2992
2993         case VIDIOCGCHAN: /* get video channel informations */
2994         {
2995                 struct video_channel chan;
2996                 if (copy_from_user(&chan, arg, sizeof(chan)))
2997                         return -EFAULT;
2998
2999                 if (chan.channel != 0)
3000                         return -EINVAL;
3001
3002                 strcpy(chan.name, "Camera");
3003                 chan.tuners = 0;
3004                 chan.flags = 0;
3005                 chan.type = VIDEO_TYPE_CAMERA;
3006                 chan.norm = VIDEO_MODE_AUTO;
3007
3008                 if (copy_to_user(arg, &chan, sizeof(chan)))
3009                         return -EFAULT;
3010
3011                 DBG(5, "VIDIOCGCHAN successfully called")
3012                 return 0;
3013         }
3014
3015         case VIDIOCSCHAN: /* set active channel */
3016         {
3017                 struct video_channel chan;
3018
3019                 if (copy_from_user(&chan, arg, sizeof(chan)))
3020                         return -EFAULT;
3021
3022                 if (chan.channel != 0)
3023                         return -EINVAL;
3024
3025                 DBG(5, "VIDIOCSCHAN successfully called")
3026                 return 0;
3027         }
3028
3029         case VIDIOCGPICT: /* get image properties of the picture */
3030         {
3031                 if (w9968cf_sensor_get_picture(cam))
3032                         return -EIO;
3033
3034                 if (copy_to_user(arg, &cam->picture, sizeof(cam->picture)))
3035                         return -EFAULT;
3036
3037                 DBG(5, "VIDIOCGPICT successfully called")
3038                 return 0;
3039         }
3040
3041         case VIDIOCSPICT: /* change picture settings */
3042         {
3043                 struct video_picture pict;
3044                 int err = 0;
3045
3046                 if (copy_from_user(&pict, arg, sizeof(pict)))
3047                         return -EFAULT;
3048
3049                 if ( (cam->force_palette || !w9968cf_vpp) 
3050                      && pict.palette != cam->picture.palette ) {
3051                         DBG(4, "Palette %s rejected: only %s is allowed",
3052                             symbolic(v4l1_plist, pict.palette),
3053                             symbolic(v4l1_plist, cam->picture.palette))
3054                         return -EINVAL;
3055                 }
3056
3057                 if (!w9968cf_valid_palette(pict.palette)) {
3058                         DBG(4, "Palette %s not supported. VIDIOCSPICT failed",
3059                             symbolic(v4l1_plist, pict.palette))
3060                         return -EINVAL;
3061                 }
3062
3063                 if (!cam->force_palette) {
3064                    if (cam->decompression == 0) {
3065                       if (w9968cf_need_decompression(pict.palette)) {
3066                          DBG(4, "Decompression disabled: palette %s is not "
3067                                 "allowed. VIDIOCSPICT failed",
3068                              symbolic(v4l1_plist, pict.palette))
3069                          return -EINVAL;
3070                       }
3071                    } else if (cam->decompression == 1) {
3072                       if (!w9968cf_need_decompression(pict.palette)) {
3073                          DBG(4, "Decompression forced: palette %s is not "
3074                                 "allowed. VIDIOCSPICT failed",
3075                              symbolic(v4l1_plist, pict.palette))
3076                          return -EINVAL;
3077                       }
3078                    }
3079                 }
3080
3081                 if (pict.depth != w9968cf_valid_depth(pict.palette)) {
3082                         DBG(4, "Requested depth %u bpp is not valid for %s "
3083                                "palette: ignored and changed to %u bpp", 
3084                             pict.depth, symbolic(v4l1_plist, pict.palette),
3085                             w9968cf_valid_depth(pict.palette))
3086                         pict.depth = w9968cf_valid_depth(pict.palette);
3087                 }
3088
3089                 if (pict.palette != cam->picture.palette) {
3090                         if(*cam->requested_frame
3091                            || cam->frame_current->queued) {
3092                                 err = wait_event_interruptible
3093                                       ( cam->wait_queue,
3094                                         cam->disconnected ||
3095                                         (!*cam->requested_frame &&
3096                                          !cam->frame_current->queued) );
3097                                 if (err)
3098                                         return err;
3099                                 if (cam->disconnected)
3100                                         return -ENODEV;
3101                         }
3102
3103                         if (w9968cf_stop_transfer(cam))
3104                                 goto ioctl_fail;
3105
3106                         if (w9968cf_set_picture(cam, pict))
3107                                 goto ioctl_fail;
3108
3109                         if (w9968cf_start_transfer(cam))
3110                                 goto ioctl_fail;
3111
3112                 } else if (w9968cf_sensor_update_picture(cam, pict))
3113                         return -EIO;
3114
3115
3116                 DBG(5, "VIDIOCSPICT successfully called")
3117                 return 0;
3118         }
3119
3120         case VIDIOCSWIN: /* set capture area */
3121         {
3122                 struct video_window win;
3123                 int err = 0;
3124
3125                 if (copy_from_user(&win, arg, sizeof(win)))
3126                         return -EFAULT;
3127
3128                 DBG(6, "VIDIOCSWIN called: clipcount=%d, flags=%u, "
3129                        "x=%u, y=%u, %ux%u", win.clipcount, win.flags,
3130                     win.x, win.y, win.width, win.height)
3131
3132                 if (win.clipcount != 0 || win.flags != 0)
3133                         return -EINVAL;
3134
3135                 if ((err = w9968cf_adjust_window_size(cam, (u16*)&win.width,
3136                                                       (u16*)&win.height))) {
3137                         DBG(4, "Resolution not supported (%ux%u). "
3138                                "VIDIOCSWIN failed", win.width, win.height)
3139                         return err;
3140                 }
3141
3142                 if (win.x != cam->window.x ||
3143                     win.y != cam->window.y ||
3144                     win.width != cam->window.width ||
3145                     win.height != cam->window.height) {
3146                         if(*cam->requested_frame
3147                            || cam->frame_current->queued) {
3148                                 err = wait_event_interruptible
3149                                       ( cam->wait_queue,
3150                                         cam->disconnected ||
3151                                         (!*cam->requested_frame &&
3152                                          !cam->frame_current->queued) );
3153                                 if (err)
3154                                         return err;
3155                                 if (cam->disconnected)
3156                                         return -ENODEV;
3157                         }
3158
3159                         if (w9968cf_stop_transfer(cam))
3160                                 goto ioctl_fail;
3161
3162                         /* This _must_ be called before set_window() */
3163                         if (w9968cf_set_picture(cam, cam->picture))
3164                                 goto ioctl_fail;
3165
3166                         if (w9968cf_set_window(cam, win))
3167                                 goto ioctl_fail;
3168
3169                         if (w9968cf_start_transfer(cam))
3170                                 goto ioctl_fail;
3171                 }
3172
3173                 DBG(5, "VIDIOCSWIN successfully called. ")
3174                 return 0;
3175         }
3176
3177         case VIDIOCGWIN: /* get current window properties */
3178         {
3179                 if (copy_to_user(arg,&cam->window,sizeof(struct video_window)))
3180                         return -EFAULT;
3181
3182                 DBG(5, "VIDIOCGWIN successfully called")
3183                 return 0;
3184         }
3185
3186         case VIDIOCGMBUF: /* request for memory (mapped) buffer */
3187         {
3188                 struct video_mbuf mbuf;
3189                 u8 i;
3190
3191                 mbuf.size = cam->nbuffers * cam->frame[0].size;
3192                 mbuf.frames = cam->nbuffers;
3193                 for (i = 0; i < cam->nbuffers; i++)
3194                         mbuf.offsets[i] = (unsigned long)cam->frame[i].buffer -
3195                                           (unsigned long)cam->frame[0].buffer;
3196
3197                 if (copy_to_user(arg, &mbuf, sizeof(mbuf)))
3198                         return -EFAULT;
3199
3200                 DBG(5, "VIDIOCGMBUF successfully called")
3201                 return 0;
3202         }
3203
3204         case VIDIOCMCAPTURE: /* start the capture to a frame */
3205         {
3206                 struct video_mmap mmap;
3207                 struct w9968cf_frame_t* fr;
3208                 int err = 0;
3209
3210                 if (copy_from_user(&mmap, arg, sizeof(mmap)))
3211                         return -EFAULT;
3212
3213                 DBG(6, "VIDIOCMCAPTURE called: frame #%u, format=%s, %dx%d",
3214                     mmap.frame, symbolic(v4l1_plist, mmap.format), 
3215                     mmap.width, mmap.height)
3216
3217                 if (mmap.frame >= cam->nbuffers) {
3218                         DBG(4, "Invalid frame number (%u). "
3219                                "VIDIOCMCAPTURE failed", mmap.frame)
3220                         return -EINVAL;
3221                 }
3222
3223                 if (mmap.format!=cam->picture.palette && 
3224                     (cam->force_palette || !w9968cf_vpp)) {
3225                         DBG(4, "Palette %s rejected: only %s is allowed",
3226                             symbolic(v4l1_plist, mmap.format),
3227                             symbolic(v4l1_plist, cam->picture.palette))
3228                         return -EINVAL;
3229                 }
3230
3231                 if (!w9968cf_valid_palette(mmap.format)) {
3232                         DBG(4, "Palette %s not supported. "
3233                                "VIDIOCMCAPTURE failed", 
3234                             symbolic(v4l1_plist, mmap.format))
3235                         return -EINVAL;
3236                 }
3237
3238                 if (!cam->force_palette) {
3239                    if (cam->decompression == 0) {
3240                       if (w9968cf_need_decompression(mmap.format)) {
3241                          DBG(4, "Decompression disabled: palette %s is not "
3242                                 "allowed. VIDIOCSPICT failed",
3243                              symbolic(v4l1_plist, mmap.format))
3244                          return -EINVAL;
3245                       }
3246                    } else if (cam->decompression == 1) {
3247                       if (!w9968cf_need_decompression(mmap.format)) {
3248                          DBG(4, "Decompression forced: palette %s is not "
3249                                 "allowed. VIDIOCSPICT failed",
3250                              symbolic(v4l1_plist, mmap.format))
3251                          return -EINVAL;
3252                       }
3253                    }
3254                 }
3255
3256                 if ((err = w9968cf_adjust_window_size(cam, (u16*)&mmap.width, 
3257                                                       (u16*)&mmap.height))) {
3258                         DBG(4, "Resolution not supported (%dx%d). "
3259                                "VIDIOCMCAPTURE failed",
3260                             mmap.width, mmap.height)
3261                         return err;
3262                 }
3263
3264                 fr = &cam->frame[mmap.frame];
3265
3266                 if (mmap.width  != cam->window.width ||
3267                     mmap.height != cam->window.height ||
3268                     mmap.format != cam->picture.palette) {
3269
3270                         struct video_window win;
3271                         struct video_picture pict;
3272
3273                         if(*cam->requested_frame
3274                            || cam->frame_current->queued) {
3275                                 DBG(6, "VIDIOCMCAPTURE. Change settings for "
3276                                        "frame #%u: %dx%d, format %s. Wait...",
3277                                     mmap.frame, mmap.width, mmap.height,
3278                                     symbolic(v4l1_plist, mmap.format))
3279                                 err = wait_event_interruptible
3280                                       ( cam->wait_queue,
3281                                         cam->disconnected ||
3282                                         (!*cam->requested_frame &&
3283                                          !cam->frame_current->queued) );
3284                                 if (err)
3285                                         return err;
3286                                 if (cam->disconnected)
3287                                         return -ENODEV;
3288                         }
3289
3290                         memcpy(&win, &cam->window, sizeof(win));
3291                         memcpy(&pict, &cam->picture, sizeof(pict));
3292                         win.width = mmap.width;
3293                         win.height = mmap.height;
3294                         pict.palette = mmap.format;
3295
3296                         if (w9968cf_stop_transfer(cam))
3297                                 goto ioctl_fail;
3298
3299                         /* This before set_window */
3300                         if (w9968cf_set_picture(cam, pict)) 
3301                                 goto ioctl_fail;
3302
3303                         if (w9968cf_set_window(cam, win))
3304                                 goto ioctl_fail;
3305
3306                         if (w9968cf_start_transfer(cam))
3307                                 goto ioctl_fail;
3308
3309                 } else  if (fr->queued) {
3310
3311                         DBG(6, "Wait until frame #%u is free", mmap.frame)
3312                         
3313                         err = wait_event_interruptible(cam->wait_queue, 
3314                                                        cam->disconnected ||
3315                                                        (!fr->queued));
3316                         if (err)
3317                                 return err;
3318                         if (cam->disconnected)
3319                                 return -ENODEV;
3320                 }
3321
3322                 w9968cf_push_frame(cam, mmap.frame);
3323                 DBG(5, "VIDIOCMCAPTURE(%u): successfully called", mmap.frame)
3324                 return 0;
3325         }
3326
3327         case VIDIOCSYNC: /* wait until the capture of a frame is finished */
3328         {
3329                 unsigned int f_num;
3330                 struct w9968cf_frame_t* fr;
3331                 int err = 0;
3332
3333                 if (copy_from_user(&f_num, arg, sizeof(f_num)))
3334                         return -EFAULT;
3335
3336                 if (f_num >= cam->nbuffers) {
3337                         DBG(4, "Invalid frame number (%u). "
3338                                "VIDIOCMCAPTURE failed", f_num)
3339                         return -EINVAL;
3340                 }
3341
3342                 DBG(6, "VIDIOCSYNC called for frame #%u", f_num)
3343
3344                 fr = &cam->frame[f_num];
3345
3346                 switch (fr->status) {
3347                 case F_UNUSED:
3348                         if (!fr->queued) {
3349                                 DBG(4, "VIDIOSYNC: Frame #%u not requested!",
3350                                     f_num)
3351                                 return -EFAULT;
3352                         }
3353                 case F_ERROR:
3354                 case F_GRABBING:
3355                         err = wait_event_interruptible(cam->wait_queue, 
3356                                                        (fr->status == F_READY)
3357                                                        || cam->disconnected);
3358                         if (err)
3359                                 return err;
3360                         if (cam->disconnected)
3361                                 return -ENODEV;
3362                         break;
3363                 case F_READY:
3364                         break;
3365                 }
3366
3367                 if (w9968cf_vpp)
3368                         w9968cf_postprocess_frame(cam, fr);
3369
3370                 fr->status = F_UNUSED;
3371
3372                 DBG(5, "VIDIOCSYNC(%u) successfully called", f_num)
3373                 return 0;
3374         }
3375
3376         case VIDIOCGUNIT:/* report the unit numbers of the associated devices*/
3377         {
3378                 struct video_unit unit = {
3379                         .video = cam->v4ldev->minor,
3380                         .vbi = VIDEO_NO_UNIT,
3381                         .radio = VIDEO_NO_UNIT,
3382                         .audio = VIDEO_NO_UNIT,
3383                         .teletext = VIDEO_NO_UNIT,
3384                 };
3385
3386                 if (copy_to_user(arg, &unit, sizeof(unit)))
3387                         return -EFAULT;
3388
3389                 DBG(5, "VIDIOCGUNIT successfully called")
3390                 return 0;
3391         }
3392
3393         case VIDIOCKEY:
3394                 return 0;
3395
3396         case VIDIOCGFBUF:
3397         {
3398                 if (clear_user(arg, sizeof(struct video_buffer)))
3399                         return -EFAULT;
3400
3401                 DBG(5, "VIDIOCGFBUF successfully called")
3402                 return 0;
3403         }
3404
3405         case VIDIOCGTUNER:
3406         {
3407                 struct video_tuner tuner;
3408                 if (copy_from_user(&tuner, arg, sizeof(tuner)))
3409                         return -EFAULT;
3410
3411                 if (tuner.tuner != 0)
3412                         return -EINVAL;
3413
3414                 strcpy(tuner.name, "no_tuner");
3415                 tuner.rangelow = 0;
3416                 tuner.rangehigh = 0;
3417                 tuner.flags = VIDEO_TUNER_NORM;
3418                 tuner.mode = VIDEO_MODE_AUTO;
3419                 tuner.signal = 0xffff;
3420
3421                 if (copy_to_user(arg, &tuner, sizeof(tuner)))
3422                         return -EFAULT;
3423
3424                 DBG(5, "VIDIOCGTUNER successfully called")
3425                 return 0;
3426         }
3427
3428         case VIDIOCSTUNER:
3429         {
3430                 struct video_tuner tuner;
3431                 if (copy_from_user(&tuner, arg, sizeof(tuner)))
3432                         return -EFAULT;
3433
3434                 if (tuner.tuner != 0)
3435                         return -EINVAL;
3436
3437                 if (tuner.mode != VIDEO_MODE_AUTO)
3438                         return -EINVAL;
3439
3440                 DBG(5, "VIDIOCSTUNER successfully called")
3441                 return 0;
3442         }
3443
3444         case VIDIOCSFBUF:
3445         case VIDIOCCAPTURE:
3446         case VIDIOCGFREQ:
3447         case VIDIOCSFREQ:
3448         case VIDIOCGAUDIO:
3449         case VIDIOCSAUDIO:
3450         case VIDIOCSPLAYMODE:
3451         case VIDIOCSWRITEMODE:
3452         case VIDIOCGPLAYINFO:
3453         case VIDIOCSMICROCODE:
3454         case VIDIOCGVBIFMT:
3455         case VIDIOCSVBIFMT:
3456                 DBG(4, "Unsupported V4L1 IOCtl: VIDIOC%s "
3457                        "(type 0x%01X, "
3458                        "n. 0x%01X, "
3459                        "dir. 0x%01X, " 
3460                        "size 0x%02X)",
3461                     V4L1_IOCTL(cmd),
3462                     _IOC_TYPE(cmd),_IOC_NR(cmd),_IOC_DIR(cmd),_IOC_SIZE(cmd))
3463
3464                 return -EINVAL;
3465
3466         default:
3467                 DBG(4, "Invalid V4L1 IOCtl: VIDIOC%s "
3468                        "type 0x%01X, "
3469                        "n. 0x%01X, "
3470                        "dir. 0x%01X, "
3471                        "size 0x%02X",
3472                     V4L1_IOCTL(cmd),
3473                     _IOC_TYPE(cmd),_IOC_NR(cmd),_IOC_DIR(cmd),_IOC_SIZE(cmd))
3474
3475                 return -ENOIOCTLCMD;
3476
3477         } /* end of switch */
3478
3479 ioctl_fail:
3480         cam->misconfigured = 1;
3481         DBG(1, "VIDIOC%s failed because of hardware problems. "
3482                "To use the camera, close and open it again.", V4L1_IOCTL(cmd))
3483         return -EFAULT;
3484 }
3485
3486
3487 static struct file_operations w9968cf_fops = {
3488         .owner =   THIS_MODULE,
3489         .open =    w9968cf_open,
3490         .release = w9968cf_release,
3491         .read =    w9968cf_read,
3492         .ioctl =   w9968cf_ioctl,
3493         .mmap =    w9968cf_mmap,
3494         .llseek =  no_llseek,
3495 };
3496
3497
3498
3499 /****************************************************************************
3500  * USB probe and V4L registration, disconnect and id_table[] definition     *
3501  ****************************************************************************/
3502
3503 static int
3504 w9968cf_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
3505 {
3506         struct usb_device *udev = interface_to_usbdev(intf);
3507         struct w9968cf_device* cam;
3508         int err = 0;
3509         enum w9968cf_model_id mod_id;
3510         struct list_head* ptr;
3511         u8 sc = 0; /* number of simultaneous cameras */
3512         static unsigned short dev_nr = 0; /* we are handling device number n */
3513
3514         if (le16_to_cpu(udev->descriptor.idVendor)  == winbond_id_table[0].idVendor &&
3515             le16_to_cpu(udev->descriptor.idProduct) == winbond_id_table[0].idProduct)
3516                 mod_id = W9968CF_MOD_CLVBWGP; /* see camlist[] table */
3517         else if (le16_to_cpu(udev->descriptor.idVendor)  == winbond_id_table[1].idVendor &&
3518                  le16_to_cpu(udev->descriptor.idProduct) == winbond_id_table[1].idProduct)
3519                 mod_id = W9968CF_MOD_GENERIC; /* see camlist[] table */
3520         else
3521                 return -ENODEV;
3522
3523         cam = (struct w9968cf_device*)
3524                   kmalloc(sizeof(struct w9968cf_device), GFP_KERNEL);
3525         if (!cam)
3526                 return -ENOMEM;
3527
3528         memset(cam, 0, sizeof(*cam));
3529
3530         init_MUTEX(&cam->dev_sem);
3531         down(&cam->dev_sem);
3532
3533         cam->usbdev = udev;
3534         /* NOTE: a local copy is used to avoid possible race conditions */
3535         memcpy(&cam->dev, &udev->dev, sizeof(struct device));
3536
3537         DBG(2, "%s detected", symbolic(camlist, mod_id))
3538
3539         if (simcams > W9968CF_MAX_DEVICES)
3540                 simcams = W9968CF_SIMCAMS;
3541
3542         /* How many cameras are connected ? */
3543         down(&w9968cf_devlist_sem);
3544         list_for_each(ptr, &w9968cf_dev_list)
3545                 sc++;
3546         up(&w9968cf_devlist_sem);
3547
3548         if (sc >= simcams) {
3549                 DBG(2, "Device rejected: too many connected cameras "
3550                        "(max. %u)", simcams)
3551                 err = -EPERM;
3552                 goto fail;
3553         }
3554
3555
3556         /* Allocate 2 bytes of memory for camera control USB transfers */
3557         if (!(cam->control_buffer = kmalloc(2, GFP_KERNEL))) {
3558                 DBG(1,"Couldn't allocate memory for camera control transfers")
3559                 err = -ENOMEM;
3560                 goto fail;
3561         }
3562         memset(cam->control_buffer, 0, 2);
3563
3564         /* Allocate 8 bytes of memory for USB data transfers to the FSB */
3565         if (!(cam->data_buffer = kmalloc(8, GFP_KERNEL))) {
3566                 DBG(1, "Couldn't allocate memory for data "
3567                        "transfers to the FSB")
3568                 err = -ENOMEM;
3569                 goto fail;
3570         }
3571         memset(cam->data_buffer, 0, 8);
3572
3573         /* Register the V4L device */
3574         cam->v4ldev = video_device_alloc();
3575         if (!cam->v4ldev) {
3576                 DBG(1, "Could not allocate memory for a V4L structure")
3577                 err = -ENOMEM;
3578                 goto fail;
3579         }
3580
3581         strcpy(cam->v4ldev->name, symbolic(camlist, mod_id));
3582         cam->v4ldev->owner = THIS_MODULE;
3583         cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
3584         cam->v4ldev->hardware = VID_HARDWARE_W9968CF;
3585         cam->v4ldev->fops = &w9968cf_fops;
3586         cam->v4ldev->minor = video_nr[dev_nr];
3587         cam->v4ldev->release = video_device_release;
3588         video_set_drvdata(cam->v4ldev, cam);
3589         cam->v4ldev->dev = &cam->dev;
3590
3591         err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
3592                                     video_nr[dev_nr]);
3593         if (err) {
3594                 DBG(1, "V4L device registration failed")
3595                 if (err == -ENFILE && video_nr[dev_nr] == -1)
3596                         DBG(2, "Couldn't find a free /dev/videoX node")
3597                 video_nr[dev_nr] = -1;
3598                 dev_nr = (dev_nr < W9968CF_MAX_DEVICES-1) ? dev_nr+1 : 0;
3599                 goto fail;
3600         }
3601
3602         DBG(2, "V4L device registered as /dev/video%d", cam->v4ldev->minor)
3603
3604         /* Set some basic constants */
3605         w9968cf_configure_camera(cam, udev, mod_id, dev_nr);
3606
3607         /* Add a new entry into the list of V4L registered devices */
3608         down(&w9968cf_devlist_sem);
3609         list_add(&cam->v4llist, &w9968cf_dev_list);
3610         up(&w9968cf_devlist_sem);
3611         dev_nr = (dev_nr < W9968CF_MAX_DEVICES-1) ? dev_nr+1 : 0;
3612
3613         w9968cf_turn_on_led(cam);
3614
3615         w9968cf_i2c_init(cam);
3616
3617         usb_set_intfdata(intf, cam);
3618         up(&cam->dev_sem);
3619         return 0;
3620
3621 fail: /* Free unused memory */
3622         kfree(cam->control_buffer);
3623         kfree(cam->data_buffer);
3624         if (cam->v4ldev)
3625                 video_device_release(cam->v4ldev);
3626         up(&cam->dev_sem);
3627         kfree(cam);
3628         return err;
3629 }
3630
3631
3632 static void w9968cf_usb_disconnect(struct usb_interface* intf)
3633 {
3634         struct w9968cf_device* cam = 
3635            (struct w9968cf_device*)usb_get_intfdata(intf);
3636
3637         down_write(&w9968cf_disconnect);
3638
3639         if (cam) {
3640                 /* Prevent concurrent accesses to data */
3641                 down(&cam->dev_sem); 
3642
3643                 cam->disconnected = 1;
3644
3645                 DBG(2, "Disconnecting %s...", symbolic(camlist, cam->id))
3646
3647                 wake_up_interruptible_all(&cam->open);
3648
3649                 if (cam->users) {
3650                         DBG(2, "The device is open (/dev/video%d)! "
3651                                "Process name: %s. Deregistration and memory "
3652                                "deallocation are deferred on close.",
3653                             cam->v4ldev->minor, cam->command)
3654                         cam->misconfigured = 1;
3655                         w9968cf_stop_transfer(cam);
3656                         wake_up_interruptible(&cam->wait_queue);
3657                 } else
3658                         w9968cf_release_resources(cam);
3659
3660                 up(&cam->dev_sem);
3661
3662                 if (!cam->users)
3663                         kfree(cam);
3664         }
3665
3666         up_write(&w9968cf_disconnect);
3667 }
3668
3669
3670 static struct usb_driver w9968cf_usb_driver = {
3671         .name =       "w9968cf",
3672         .id_table =   winbond_id_table,
3673         .probe =      w9968cf_usb_probe,
3674         .disconnect = w9968cf_usb_disconnect,
3675 };
3676
3677
3678
3679 /****************************************************************************
3680  * Module init, exit and intermodule communication                          *
3681  ****************************************************************************/
3682
3683 static int w9968cf_vppmod_detect(struct w9968cf_device* cam)
3684 {
3685         if (!w9968cf_vpp)
3686                 if (vppmod_load)
3687                         request_module("w9968cf-vpp");
3688
3689         down(&w9968cf_vppmod_lock);
3690
3691         if (!w9968cf_vpp) {
3692                 DBG(4, "Video post-processing module not detected")
3693                 w9968cf_adjust_configuration(cam);
3694                 goto out;
3695         }
3696
3697         if (!try_module_get(w9968cf_vpp->owner)) {
3698                 DBG(1, "Couldn't increment the reference count of "
3699                        "the video post-processing module")
3700                 up(&w9968cf_vppmod_lock);
3701                 return -ENOSYS;
3702         }
3703
3704         w9968cf_vpp->busy++;
3705
3706         DBG(5, "Video post-processing module detected")
3707
3708 out:
3709         up(&w9968cf_vppmod_lock);
3710         return 0;
3711 }
3712
3713
3714 static void w9968cf_vppmod_release(struct w9968cf_device* cam)
3715 {
3716         down(&w9968cf_vppmod_lock);
3717
3718         if (w9968cf_vpp && w9968cf_vpp->busy) {
3719                 module_put(w9968cf_vpp->owner);
3720                 w9968cf_vpp->busy--;
3721                 wake_up(&w9968cf_vppmod_wait);
3722                 DBG(5, "Video post-processing module released")
3723         }
3724
3725         up(&w9968cf_vppmod_lock);
3726 }
3727
3728
3729 int w9968cf_vppmod_register(struct w9968cf_vpp_t* vpp)
3730 {
3731         down(&w9968cf_vppmod_lock);
3732
3733         if (w9968cf_vpp) {
3734                 KDBG(1, "Video post-processing module already registered")
3735                 up(&w9968cf_vppmod_lock);
3736                 return -EINVAL;
3737         }
3738
3739         w9968cf_vpp = vpp;
3740         w9968cf_vpp->busy = 0;
3741
3742         KDBG(2, "Video post-processing module registered")
3743         up(&w9968cf_vppmod_lock);
3744         return 0;
3745 }
3746
3747
3748 int w9968cf_vppmod_deregister(struct w9968cf_vpp_t* vpp)
3749 {
3750         down(&w9968cf_vppmod_lock);
3751
3752         if (!w9968cf_vpp) {
3753                 up(&w9968cf_vppmod_lock);
3754                 return -EINVAL;
3755         }
3756
3757         if (w9968cf_vpp != vpp) {
3758                 KDBG(1, "Only the owner can unregister the video "
3759                         "post-processing module")
3760                 up(&w9968cf_vppmod_lock);
3761                 return -EINVAL;
3762         }
3763
3764         if (w9968cf_vpp->busy) {
3765                 KDBG(2, "Video post-processing module busy. Wait for it to be "
3766                         "released...")
3767                 up(&w9968cf_vppmod_lock);
3768                 wait_event(w9968cf_vppmod_wait, !w9968cf_vpp->busy);
3769                 w9968cf_vpp = NULL;
3770                 goto out;
3771         }
3772
3773         w9968cf_vpp = NULL;
3774
3775         up(&w9968cf_vppmod_lock);
3776
3777 out:
3778         KDBG(2, "Video post-processing module unregistered")
3779         return 0;
3780 }
3781
3782
3783 static int __init w9968cf_module_init(void)
3784 {
3785         int err;
3786
3787         KDBG(2, W9968CF_MODULE_NAME" "W9968CF_MODULE_VERSION)
3788         KDBG(3, W9968CF_MODULE_AUTHOR)
3789
3790         if (ovmod_load)
3791                 request_module("ovcamchip");
3792
3793         if ((err = usb_register(&w9968cf_usb_driver)))
3794                 return err;
3795
3796         return 0;
3797 }
3798
3799
3800 static void __exit w9968cf_module_exit(void)
3801 {
3802         /* w9968cf_usb_disconnect() will be called */
3803         usb_deregister(&w9968cf_usb_driver);
3804
3805         KDBG(2, W9968CF_MODULE_NAME" deregistered")
3806 }
3807
3808
3809 module_init(w9968cf_module_init);
3810 module_exit(w9968cf_module_exit);
3811
3812
3813 EXPORT_SYMBOL(w9968cf_vppmod_register);
3814 EXPORT_SYMBOL(w9968cf_vppmod_deregister);