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