Merge branch 'for-linus' of master.kernel.org:/pub/scm/linux/kernel/git/dtor/input
[pandora-kernel.git] / drivers / media / video / sn9c102 / sn9c102_core.c
1 /***************************************************************************
2  * V4L2 driver for SN9C1xx PC Camera Controllers                           *
3  *                                                                         *
4  * Copyright (C) 2004-2007 by Luca Risolia <luca.risolia@studio.unibo.it>  *
5  *                                                                         *
6  * This program is free software; you can redistribute it and/or modify    *
7  * it under the terms of the GNU General Public License as published by    *
8  * the Free Software Foundation; either version 2 of the License, or       *
9  * (at your option) any later version.                                     *
10  *                                                                         *
11  * This program is distributed in the hope that it will be useful,         *
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
14  * GNU General Public License for more details.                            *
15  *                                                                         *
16  * You should have received a copy of the GNU General Public License       *
17  * along with this program; if not, write to the Free Software             *
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.               *
19  ***************************************************************************/
20
21 #include <linux/module.h>
22 #include <linux/init.h>
23 #include <linux/kernel.h>
24 #include <linux/param.h>
25 #include <linux/moduleparam.h>
26 #include <linux/errno.h>
27 #include <linux/slab.h>
28 #include <linux/device.h>
29 #include <linux/fs.h>
30 #include <linux/delay.h>
31 #include <linux/compiler.h>
32 #include <linux/ioctl.h>
33 #include <linux/poll.h>
34 #include <linux/stat.h>
35 #include <linux/mm.h>
36 #include <linux/vmalloc.h>
37 #include <linux/page-flags.h>
38 #include <linux/byteorder/generic.h>
39 #include <asm/page.h>
40 #include <asm/uaccess.h>
41
42 #include "sn9c102.h"
43
44 /*****************************************************************************/
45
46 #define SN9C102_MODULE_NAME     "V4L2 driver for SN9C1xx PC Camera Controllers"
47 #define SN9C102_MODULE_AUTHOR   "(C) 2004-2006 Luca Risolia"
48 #define SN9C102_AUTHOR_EMAIL    "<luca.risolia@studio.unibo.it>"
49 #define SN9C102_MODULE_LICENSE  "GPL"
50 #define SN9C102_MODULE_VERSION  "1:1.34"
51 #define SN9C102_MODULE_VERSION_CODE  KERNEL_VERSION(1, 1, 34)
52
53 /*****************************************************************************/
54
55 MODULE_DEVICE_TABLE(usb, sn9c102_id_table);
56
57 MODULE_AUTHOR(SN9C102_MODULE_AUTHOR " " SN9C102_AUTHOR_EMAIL);
58 MODULE_DESCRIPTION(SN9C102_MODULE_NAME);
59 MODULE_VERSION(SN9C102_MODULE_VERSION);
60 MODULE_LICENSE(SN9C102_MODULE_LICENSE);
61
62 static short video_nr[] = {[0 ... SN9C102_MAX_DEVICES-1] = -1};
63 module_param_array(video_nr, short, NULL, 0444);
64 MODULE_PARM_DESC(video_nr,
65                  "\n<-1|n[,...]> Specify V4L2 minor mode number."
66                  "\n -1 = use next available (default)"
67                  "\n  n = use minor number n (integer >= 0)"
68                  "\nYou can specify up to "__MODULE_STRING(SN9C102_MAX_DEVICES)
69                  " cameras this way."
70                  "\nFor example:"
71                  "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
72                  "\nthe second camera and use auto for the first"
73                  "\none and for every other camera."
74                  "\n");
75
76 static short force_munmap[] = {[0 ... SN9C102_MAX_DEVICES-1] =
77                                SN9C102_FORCE_MUNMAP};
78 module_param_array(force_munmap, bool, NULL, 0444);
79 MODULE_PARM_DESC(force_munmap,
80                  "\n<0|1[,...]> Force the application to unmap previously"
81                  "\nmapped buffer memory before calling any VIDIOC_S_CROP or"
82                  "\nVIDIOC_S_FMT ioctl's. Not all the applications support"
83                  "\nthis feature. This parameter is specific for each"
84                  "\ndetected camera."
85                  "\n 0 = do not force memory unmapping"
86                  "\n 1 = force memory unmapping (save memory)"
87                  "\nDefault value is "__MODULE_STRING(SN9C102_FORCE_MUNMAP)"."
88                  "\n");
89
90 static unsigned int frame_timeout[] = {[0 ... SN9C102_MAX_DEVICES-1] =
91                                        SN9C102_FRAME_TIMEOUT};
92 module_param_array(frame_timeout, uint, NULL, 0644);
93 MODULE_PARM_DESC(frame_timeout,
94                  "\n<0|n[,...]> Timeout for a video frame in seconds before"
95                  "\nreturning an I/O error; 0 for infinity."
96                  "\nThis parameter is specific for each detected camera."
97                  "\nDefault value is "__MODULE_STRING(SN9C102_FRAME_TIMEOUT)"."
98                  "\n");
99
100 #ifdef SN9C102_DEBUG
101 static unsigned short debug = SN9C102_DEBUG_LEVEL;
102 module_param(debug, ushort, 0644);
103 MODULE_PARM_DESC(debug,
104                  "\n<n> Debugging information level, from 0 to 3:"
105                  "\n0 = none (use carefully)"
106                  "\n1 = critical errors"
107                  "\n2 = significant informations"
108                  "\n3 = more verbose messages"
109                  "\nLevel 3 is useful for testing only, when only "
110                  "one device is used."
111                  "\nDefault value is "__MODULE_STRING(SN9C102_DEBUG_LEVEL)"."
112                  "\n");
113 #endif
114
115 /*****************************************************************************/
116
117 static u32
118 sn9c102_request_buffers(struct sn9c102_device* cam, u32 count,
119                         enum sn9c102_io_method io)
120 {
121         struct v4l2_pix_format* p = &(cam->sensor.pix_format);
122         struct v4l2_rect* r = &(cam->sensor.cropcap.bounds);
123         size_t imagesize = cam->module_param.force_munmap || io == IO_READ ?
124                                  (p->width * p->height * p->priv) / 8 :
125                                  (r->width * r->height * p->priv) / 8;
126         void* buff = NULL;
127         u32 i;
128
129         if (count > SN9C102_MAX_FRAMES)
130                 count = SN9C102_MAX_FRAMES;
131
132         if (cam->bridge == BRIDGE_SN9C105 || cam->bridge == BRIDGE_SN9C120)
133                 imagesize += 589 + 2; /* length of JPEG header + EOI marker */
134
135         cam->nbuffers = count;
136         while (cam->nbuffers > 0) {
137                 if ((buff = vmalloc_32_user(cam->nbuffers *
138                                             PAGE_ALIGN(imagesize))))
139                         break;
140                 cam->nbuffers--;
141         }
142
143         for (i = 0; i < cam->nbuffers; i++) {
144                 cam->frame[i].bufmem = buff + i*PAGE_ALIGN(imagesize);
145                 cam->frame[i].buf.index = i;
146                 cam->frame[i].buf.m.offset = i*PAGE_ALIGN(imagesize);
147                 cam->frame[i].buf.length = imagesize;
148                 cam->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
149                 cam->frame[i].buf.sequence = 0;
150                 cam->frame[i].buf.field = V4L2_FIELD_NONE;
151                 cam->frame[i].buf.memory = V4L2_MEMORY_MMAP;
152                 cam->frame[i].buf.flags = 0;
153         }
154
155         return cam->nbuffers;
156 }
157
158
159 static void sn9c102_release_buffers(struct sn9c102_device* cam)
160 {
161         if (cam->nbuffers) {
162                 vfree(cam->frame[0].bufmem);
163                 cam->nbuffers = 0;
164         }
165         cam->frame_current = NULL;
166 }
167
168
169 static void sn9c102_empty_framequeues(struct sn9c102_device* cam)
170 {
171         u32 i;
172
173         INIT_LIST_HEAD(&cam->inqueue);
174         INIT_LIST_HEAD(&cam->outqueue);
175
176         for (i = 0; i < SN9C102_MAX_FRAMES; i++) {
177                 cam->frame[i].state = F_UNUSED;
178                 cam->frame[i].buf.bytesused = 0;
179         }
180 }
181
182
183 static void sn9c102_requeue_outqueue(struct sn9c102_device* cam)
184 {
185         struct sn9c102_frame_t *i;
186
187         list_for_each_entry(i, &cam->outqueue, frame) {
188                 i->state = F_QUEUED;
189                 list_add(&i->frame, &cam->inqueue);
190         }
191
192         INIT_LIST_HEAD(&cam->outqueue);
193 }
194
195
196 static void sn9c102_queue_unusedframes(struct sn9c102_device* cam)
197 {
198         unsigned long lock_flags;
199         u32 i;
200
201         for (i = 0; i < cam->nbuffers; i++)
202                 if (cam->frame[i].state == F_UNUSED) {
203                         cam->frame[i].state = F_QUEUED;
204                         spin_lock_irqsave(&cam->queue_lock, lock_flags);
205                         list_add_tail(&cam->frame[i].frame, &cam->inqueue);
206                         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
207                 }
208 }
209
210 /*****************************************************************************/
211
212 int sn9c102_write_regs(struct sn9c102_device* cam, u8* buff, u16 index)
213 {
214         struct usb_device* udev = cam->usbdev;
215         int i, res;
216
217         if (index + sizeof(buff) >= ARRAY_SIZE(cam->reg))
218                 return -1;
219
220         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
221                               index, 0, buff, sizeof(buff),
222                               SN9C102_CTRL_TIMEOUT*sizeof(buff));
223         if (res < 0) {
224                 DBG(3, "Failed to write registers (index 0x%02X, error %d)",
225                     index, res);
226                 return -1;
227         }
228
229         for (i = 0; i < sizeof(buff); i++)
230                 cam->reg[index+i] = buff[i];
231
232         return 0;
233 }
234
235
236 int sn9c102_write_reg(struct sn9c102_device* cam, u8 value, u16 index)
237 {
238         struct usb_device* udev = cam->usbdev;
239         u8* buff = cam->control_buffer;
240         int res;
241
242         if (index >= ARRAY_SIZE(cam->reg))
243                 return -1;
244
245         *buff = value;
246
247         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
248                               index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
249         if (res < 0) {
250                 DBG(3, "Failed to write a register (value 0x%02X, index "
251                        "0x%02X, error %d)", value, index, res);
252                 return -1;
253         }
254
255         cam->reg[index] = value;
256
257         return 0;
258 }
259
260
261 /* NOTE: reading some registers always returns 0 */
262 static int sn9c102_read_reg(struct sn9c102_device* cam, u16 index)
263 {
264         struct usb_device* udev = cam->usbdev;
265         u8* buff = cam->control_buffer;
266         int res;
267
268         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
269                               index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
270         if (res < 0)
271                 DBG(3, "Failed to read a register (index 0x%02X, error %d)",
272                     index, res);
273
274         return (res >= 0) ? (int)(*buff) : -1;
275 }
276
277
278 int sn9c102_pread_reg(struct sn9c102_device* cam, u16 index)
279 {
280         if (index >= ARRAY_SIZE(cam->reg))
281                 return -1;
282
283         return cam->reg[index];
284 }
285
286
287 static int
288 sn9c102_i2c_wait(struct sn9c102_device* cam, struct sn9c102_sensor* sensor)
289 {
290         int i, r;
291
292         for (i = 1; i <= 5; i++) {
293                 r = sn9c102_read_reg(cam, 0x08);
294                 if (r < 0)
295                         return -EIO;
296                 if (r & 0x04)
297                         return 0;
298                 if (sensor->frequency & SN9C102_I2C_400KHZ)
299                         udelay(5*16);
300                 else
301                         udelay(16*16);
302         }
303         return -EBUSY;
304 }
305
306
307 static int
308 sn9c102_i2c_detect_read_error(struct sn9c102_device* cam,
309                               struct sn9c102_sensor* sensor)
310 {
311         int r , err = 0;
312
313         r = sn9c102_read_reg(cam, 0x08);
314         if (r < 0)
315                 err += r;
316
317         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102) {
318                 if (!(r & 0x08))
319                         err += -1;
320         } else {
321                 if (r & 0x08)
322                         err += -1;
323         }
324
325         return err ? -EIO : 0;
326 }
327
328
329 static int
330 sn9c102_i2c_detect_write_error(struct sn9c102_device* cam,
331                                struct sn9c102_sensor* sensor)
332 {
333         int r;
334         r = sn9c102_read_reg(cam, 0x08);
335         return (r < 0 || (r >= 0 && (r & 0x08))) ? -EIO : 0;
336 }
337
338
339 int
340 sn9c102_i2c_try_raw_read(struct sn9c102_device* cam,
341                          struct sn9c102_sensor* sensor, u8 data0, u8 data1,
342                          u8 n, u8 buffer[])
343 {
344         struct usb_device* udev = cam->usbdev;
345         u8* data = cam->control_buffer;
346         int err = 0, res;
347
348         /* Write cycle */
349         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
350                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) | 0x10;
351         data[1] = data0; /* I2C slave id */
352         data[2] = data1; /* address */
353         data[7] = 0x10;
354         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
355                               0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
356         if (res < 0)
357                 err += res;
358
359         err += sn9c102_i2c_wait(cam, sensor);
360
361         /* Read cycle - n bytes */
362         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
363                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) |
364                   (n << 4) | 0x02;
365         data[1] = data0;
366         data[7] = 0x10;
367         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
368                               0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
369         if (res < 0)
370                 err += res;
371
372         err += sn9c102_i2c_wait(cam, sensor);
373
374         /* The first read byte will be placed in data[4] */
375         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
376                               0x0a, 0, data, 5, SN9C102_CTRL_TIMEOUT);
377         if (res < 0)
378                 err += res;
379
380         err += sn9c102_i2c_detect_read_error(cam, sensor);
381
382         PDBGG("I2C read: address 0x%02X, first read byte: 0x%02X", data1,
383               data[4]);
384
385         if (err) {
386                 DBG(3, "I2C read failed for %s image sensor", sensor->name);
387                 return -1;
388         }
389
390         if (buffer)
391                 memcpy(buffer, data, sizeof(buffer));
392
393         return (int)data[4];
394 }
395
396
397 int
398 sn9c102_i2c_try_raw_write(struct sn9c102_device* cam,
399                           struct sn9c102_sensor* sensor, u8 n, u8 data0,
400                           u8 data1, u8 data2, u8 data3, u8 data4, u8 data5)
401 {
402         struct usb_device* udev = cam->usbdev;
403         u8* data = cam->control_buffer;
404         int err = 0, res;
405
406         /* Write cycle. It usually is address + value */
407         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
408                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0)
409                   | ((n - 1) << 4);
410         data[1] = data0;
411         data[2] = data1;
412         data[3] = data2;
413         data[4] = data3;
414         data[5] = data4;
415         data[6] = data5;
416         data[7] = 0x17;
417         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
418                               0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
419         if (res < 0)
420                 err += res;
421
422         err += sn9c102_i2c_wait(cam, sensor);
423         err += sn9c102_i2c_detect_write_error(cam, sensor);
424
425         if (err)
426                 DBG(3, "I2C write failed for %s image sensor", sensor->name);
427
428         PDBGG("I2C raw write: %u bytes, data0 = 0x%02X, data1 = 0x%02X, "
429               "data2 = 0x%02X, data3 = 0x%02X, data4 = 0x%02X, data5 = 0x%02X",
430               n, data0, data1, data2, data3, data4, data5);
431
432         return err ? -1 : 0;
433 }
434
435
436 int
437 sn9c102_i2c_try_read(struct sn9c102_device* cam,
438                      struct sn9c102_sensor* sensor, u8 address)
439 {
440         return sn9c102_i2c_try_raw_read(cam, sensor, sensor->i2c_slave_id,
441                                         address, 1, NULL);
442 }
443
444
445 int
446 sn9c102_i2c_try_write(struct sn9c102_device* cam,
447                       struct sn9c102_sensor* sensor, u8 address, u8 value)
448 {
449         return sn9c102_i2c_try_raw_write(cam, sensor, 3,
450                                          sensor->i2c_slave_id, address,
451                                          value, 0, 0, 0);
452 }
453
454
455 int sn9c102_i2c_read(struct sn9c102_device* cam, u8 address)
456 {
457         return sn9c102_i2c_try_read(cam, &cam->sensor, address);
458 }
459
460
461 int sn9c102_i2c_write(struct sn9c102_device* cam, u8 address, u8 value)
462 {
463         return sn9c102_i2c_try_write(cam, &cam->sensor, address, value);
464 }
465
466 /*****************************************************************************/
467
468 static size_t sn9c102_sof_length(struct sn9c102_device* cam)
469 {
470         switch (cam->bridge) {
471         case BRIDGE_SN9C101:
472         case BRIDGE_SN9C102:
473                 return 12;
474         case BRIDGE_SN9C103:
475                 return 18;
476         case BRIDGE_SN9C105:
477         case BRIDGE_SN9C120:
478                 return 62;
479         }
480
481         return 0;
482 }
483
484
485 static void*
486 sn9c102_find_sof_header(struct sn9c102_device* cam, void* mem, size_t len)
487 {
488         char sof_header[6] = {0xff, 0xff, 0x00, 0xc4, 0xc4, 0x96};
489         size_t soflen = 0, i;
490
491         soflen = sn9c102_sof_length(cam);
492
493         for (i = 0; (len >= soflen) && (i <= len - soflen); i++)
494                 if (!memcmp(mem + i, sof_header, sizeof(sof_header))) {
495                         memcpy(cam->sof_header, mem + i,
496                                sizeof(sn9c102_sof_header_t));
497                                 /* Skip the header */
498                                 return mem + i + soflen;
499                         }
500
501         return NULL;
502 }
503
504
505 static void*
506 sn9c102_find_eof_header(struct sn9c102_device* cam, void* mem, size_t len)
507 {
508         char eof_header[4][4] = {
509                 {0x00, 0x00, 0x00, 0x00},
510                 {0x40, 0x00, 0x00, 0x00},
511                 {0x80, 0x00, 0x00, 0x00},
512                 {0xc0, 0x00, 0x00, 0x00},
513         };
514         size_t i, j;
515
516         if (cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X ||
517             cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
518                 return NULL; /* EOF header does not exist in compressed data */
519
520         for (i = 0; (len >= 4) && (i <= len - 4); i++)
521                 for (j = 0; j < ARRAY_SIZE(eof_header); j++)
522                         if (!memcmp(mem + i, eof_header[j], 4))
523                                 return mem + i;
524
525         return NULL;
526 }
527
528
529 static void
530 sn9c102_write_jpegheader(struct sn9c102_device* cam, struct sn9c102_frame_t* f)
531 {
532         static u8 jpeg_header[589] = {
533                 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x06, 0x04, 0x05,
534                 0x06, 0x05, 0x04, 0x06, 0x06, 0x05, 0x06, 0x07, 0x07, 0x06,
535                 0x08, 0x0a, 0x10, 0x0a, 0x0a, 0x09, 0x09, 0x0a, 0x14, 0x0e,
536                 0x0f, 0x0c, 0x10, 0x17, 0x14, 0x18, 0x18, 0x17, 0x14, 0x16,
537                 0x16, 0x1a, 0x1d, 0x25, 0x1f, 0x1a, 0x1b, 0x23, 0x1c, 0x16,
538                 0x16, 0x20, 0x2c, 0x20, 0x23, 0x26, 0x27, 0x29, 0x2a, 0x29,
539                 0x19, 0x1f, 0x2d, 0x30, 0x2d, 0x28, 0x30, 0x25, 0x28, 0x29,
540                 0x28, 0x01, 0x07, 0x07, 0x07, 0x0a, 0x08, 0x0a, 0x13, 0x0a,
541                 0x0a, 0x13, 0x28, 0x1a, 0x16, 0x1a, 0x28, 0x28, 0x28, 0x28,
542                 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
543                 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
544                 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
545                 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
546                 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0xff, 0xc4, 0x01, 0xa2,
547                 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
548                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,
549                 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01,
550                 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
551                 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03,
552                 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00,
553                 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04,
554                 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04,
555                 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61,
556                 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23,
557                 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62,
558                 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25,
559                 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38,
560                 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
561                 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64,
562                 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76,
563                 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
564                 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
565                 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
566                 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2,
567                 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3,
568                 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3,
569                 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3,
570                 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02,
571                 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04,
572                 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04,
573                 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
574                 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1,
575                 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
576                 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19,
577                 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
578                 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
579                 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64,
580                 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76,
581                 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
582                 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
583                 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9,
584                 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
585                 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
586                 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3,
587                 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
588                 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc0, 0x00, 0x11,
589                 0x08, 0x01, 0xe0, 0x02, 0x80, 0x03, 0x01, 0x21, 0x00, 0x02,
590                 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xda, 0x00, 0x0c, 0x03,
591                 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00
592         };
593         u8 *pos = f->bufmem;
594
595         memcpy(pos, jpeg_header, sizeof(jpeg_header));
596         *(pos + 6) = 0x00;
597         *(pos + 7 + 64) = 0x01;
598         if (cam->compression.quality == 0) {
599                 memcpy(pos + 7, SN9C102_Y_QTABLE0, 64);
600                 memcpy(pos + 8 + 64, SN9C102_UV_QTABLE0, 64);
601         } else if (cam->compression.quality == 1) {
602                 memcpy(pos + 7, SN9C102_Y_QTABLE1, 64);
603                 memcpy(pos + 8 + 64, SN9C102_UV_QTABLE1, 64);
604         }
605         *(pos + 564) = cam->sensor.pix_format.width & 0xFF;
606         *(pos + 563) = (cam->sensor.pix_format.width >> 8) & 0xFF;
607         *(pos + 562) = cam->sensor.pix_format.height & 0xFF;
608         *(pos + 561) = (cam->sensor.pix_format.height >> 8) & 0xFF;
609         *(pos + 567) = 0x21;
610
611         f->buf.bytesused += sizeof(jpeg_header);
612 }
613
614
615 static void
616 sn9c102_write_eoimarker(struct sn9c102_device* cam, struct sn9c102_frame_t* f)
617 {
618         static const u8 eoi_marker[2] = {0xff, 0xd9};
619
620         memcpy(f->bufmem + f->buf.bytesused, eoi_marker, sizeof(eoi_marker));
621         f->buf.bytesused += sizeof(eoi_marker);
622 }
623
624
625 static void sn9c102_urb_complete(struct urb *urb)
626 {
627         struct sn9c102_device* cam = urb->context;
628         struct sn9c102_frame_t** f;
629         size_t imagesize, soflen;
630         u8 i;
631         int err = 0;
632
633         if (urb->status == -ENOENT)
634                 return;
635
636         f = &cam->frame_current;
637
638         if (cam->stream == STREAM_INTERRUPT) {
639                 cam->stream = STREAM_OFF;
640                 if ((*f))
641                         (*f)->state = F_QUEUED;
642                 DBG(3, "Stream interrupted by application");
643                 wake_up(&cam->wait_stream);
644         }
645
646         if (cam->state & DEV_DISCONNECTED)
647                 return;
648
649         if (cam->state & DEV_MISCONFIGURED) {
650                 wake_up_interruptible(&cam->wait_frame);
651                 return;
652         }
653
654         if (cam->stream == STREAM_OFF || list_empty(&cam->inqueue))
655                 goto resubmit_urb;
656
657         if (!(*f))
658                 (*f) = list_entry(cam->inqueue.next, struct sn9c102_frame_t,
659                                   frame);
660
661         imagesize = (cam->sensor.pix_format.width *
662                      cam->sensor.pix_format.height *
663                      cam->sensor.pix_format.priv) / 8;
664         if (cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
665                 imagesize += 589; /* length of jpeg header */
666         soflen = sn9c102_sof_length(cam);
667
668         for (i = 0; i < urb->number_of_packets; i++) {
669                 unsigned int img, len, status;
670                 void *pos, *sof, *eof;
671
672                 len = urb->iso_frame_desc[i].actual_length;
673                 status = urb->iso_frame_desc[i].status;
674                 pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;
675
676                 if (status) {
677                         DBG(3, "Error in isochronous frame");
678                         (*f)->state = F_ERROR;
679                         continue;
680                 }
681
682                 PDBGG("Isochrnous frame: length %u, #%u i", len, i);
683
684 redo:
685                 sof = sn9c102_find_sof_header(cam, pos, len);
686                 if (likely(!sof)) {
687                         eof = sn9c102_find_eof_header(cam, pos, len);
688                         if ((*f)->state == F_GRABBING) {
689 end_of_frame:
690                                 img = len;
691
692                                 if (eof)
693                                         img = (eof > pos) ? eof - pos - 1 : 0;
694
695                                 if ((*f)->buf.bytesused+img > imagesize) {
696                                         u32 b;
697                                         b = (*f)->buf.bytesused + img -
698                                             imagesize;
699                                         img = imagesize - (*f)->buf.bytesused;
700                                         DBG(3, "Expected EOF not found: "
701                                                "video frame cut");
702                                         if (eof)
703                                                 DBG(3, "Exceeded limit: +%u "
704                                                        "bytes", (unsigned)(b));
705                                 }
706
707                                 memcpy((*f)->bufmem + (*f)->buf.bytesused, pos,
708                                        img);
709
710                                 if ((*f)->buf.bytesused == 0)
711                                         do_gettimeofday(&(*f)->buf.timestamp);
712
713                                 (*f)->buf.bytesused += img;
714
715                                 if ((*f)->buf.bytesused == imagesize ||
716                                     ((cam->sensor.pix_format.pixelformat ==
717                                       V4L2_PIX_FMT_SN9C10X ||
718                                       cam->sensor.pix_format.pixelformat ==
719                                       V4L2_PIX_FMT_JPEG) && eof)) {
720                                         u32 b;
721
722                                         if (cam->sensor.pix_format.pixelformat
723                                             == V4L2_PIX_FMT_JPEG)
724                                                 sn9c102_write_eoimarker(cam,
725                                                                         (*f));
726
727                                         b = (*f)->buf.bytesused;
728                                         (*f)->state = F_DONE;
729                                         (*f)->buf.sequence= ++cam->frame_count;
730
731                                         spin_lock(&cam->queue_lock);
732                                         list_move_tail(&(*f)->frame,
733                                                        &cam->outqueue);
734                                         if (!list_empty(&cam->inqueue))
735                                                 (*f) = list_entry(
736                                                         cam->inqueue.next,
737                                                         struct sn9c102_frame_t,
738                                                         frame );
739                                         else
740                                                 (*f) = NULL;
741                                         spin_unlock(&cam->queue_lock);
742
743                                         memcpy(cam->sysfs.frame_header,
744                                                cam->sof_header, soflen);
745
746                                         DBG(3, "Video frame captured: %lu "
747                                                "bytes", (unsigned long)(b));
748
749                                         if (!(*f))
750                                                 goto resubmit_urb;
751
752                                 } else if (eof) {
753                                         (*f)->state = F_ERROR;
754                                         DBG(3, "Not expected EOF after %lu "
755                                                "bytes of image data",
756                                             (unsigned long)
757                                             ((*f)->buf.bytesused));
758                                 }
759
760                                 if (sof) /* (1) */
761                                         goto start_of_frame;
762
763                         } else if (eof) {
764                                 DBG(3, "EOF without SOF");
765                                 continue;
766
767                         } else {
768                                 PDBGG("Ignoring pointless isochronous frame");
769                                 continue;
770                         }
771
772                 } else if ((*f)->state == F_QUEUED || (*f)->state == F_ERROR) {
773 start_of_frame:
774                         (*f)->state = F_GRABBING;
775                         (*f)->buf.bytesused = 0;
776                         len -= (sof - pos);
777                         pos = sof;
778                         if (cam->sensor.pix_format.pixelformat ==
779                             V4L2_PIX_FMT_JPEG)
780                                 sn9c102_write_jpegheader(cam, (*f));
781                         DBG(3, "SOF detected: new video frame");
782                         if (len)
783                                 goto redo;
784
785                 } else if ((*f)->state == F_GRABBING) {
786                         eof = sn9c102_find_eof_header(cam, pos, len);
787                         if (eof && eof < sof)
788                                 goto end_of_frame; /* (1) */
789                         else {
790                                 if (cam->sensor.pix_format.pixelformat ==
791                                     V4L2_PIX_FMT_SN9C10X ||
792                                     cam->sensor.pix_format.pixelformat ==
793                                     V4L2_PIX_FMT_JPEG) {
794                                         eof = sof - soflen;
795                                         goto end_of_frame;
796                                 } else {
797                                         DBG(3, "SOF before expected EOF after "
798                                                "%lu bytes of image data",
799                                             (unsigned long)
800                                             ((*f)->buf.bytesused));
801                                         goto start_of_frame;
802                                 }
803                         }
804                 }
805         }
806
807 resubmit_urb:
808         urb->dev = cam->usbdev;
809         err = usb_submit_urb(urb, GFP_ATOMIC);
810         if (err < 0 && err != -EPERM) {
811                 cam->state |= DEV_MISCONFIGURED;
812                 DBG(1, "usb_submit_urb() failed");
813         }
814
815         wake_up_interruptible(&cam->wait_frame);
816 }
817
818
819 static int sn9c102_start_transfer(struct sn9c102_device* cam)
820 {
821         struct usb_device *udev = cam->usbdev;
822         struct urb* urb;
823         struct usb_host_interface* altsetting = usb_altnum_to_altsetting(
824                                                     usb_ifnum_to_if(udev, 0),
825                                                     SN9C102_ALTERNATE_SETTING);
826         const unsigned int psz = le16_to_cpu(altsetting->
827                                              endpoint[0].desc.wMaxPacketSize);
828         s8 i, j;
829         int err = 0;
830
831         for (i = 0; i < SN9C102_URBS; i++) {
832                 cam->transfer_buffer[i] = kzalloc(SN9C102_ISO_PACKETS * psz,
833                                                   GFP_KERNEL);
834                 if (!cam->transfer_buffer[i]) {
835                         err = -ENOMEM;
836                         DBG(1, "Not enough memory");
837                         goto free_buffers;
838                 }
839         }
840
841         for (i = 0; i < SN9C102_URBS; i++) {
842                 urb = usb_alloc_urb(SN9C102_ISO_PACKETS, GFP_KERNEL);
843                 cam->urb[i] = urb;
844                 if (!urb) {
845                         err = -ENOMEM;
846                         DBG(1, "usb_alloc_urb() failed");
847                         goto free_urbs;
848                 }
849                 urb->dev = udev;
850                 urb->context = cam;
851                 urb->pipe = usb_rcvisocpipe(udev, 1);
852                 urb->transfer_flags = URB_ISO_ASAP;
853                 urb->number_of_packets = SN9C102_ISO_PACKETS;
854                 urb->complete = sn9c102_urb_complete;
855                 urb->transfer_buffer = cam->transfer_buffer[i];
856                 urb->transfer_buffer_length = psz * SN9C102_ISO_PACKETS;
857                 urb->interval = 1;
858                 for (j = 0; j < SN9C102_ISO_PACKETS; j++) {
859                         urb->iso_frame_desc[j].offset = psz * j;
860                         urb->iso_frame_desc[j].length = psz;
861                 }
862         }
863
864         /* Enable video */
865         if (!(cam->reg[0x01] & 0x04)) {
866                 err = sn9c102_write_reg(cam, cam->reg[0x01] | 0x04, 0x01);
867                 if (err) {
868                         err = -EIO;
869                         DBG(1, "I/O hardware error");
870                         goto free_urbs;
871                 }
872         }
873
874         err = usb_set_interface(udev, 0, SN9C102_ALTERNATE_SETTING);
875         if (err) {
876                 DBG(1, "usb_set_interface() failed");
877                 goto free_urbs;
878         }
879
880         cam->frame_current = NULL;
881
882         for (i = 0; i < SN9C102_URBS; i++) {
883                 err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
884                 if (err) {
885                         for (j = i-1; j >= 0; j--)
886                                 usb_kill_urb(cam->urb[j]);
887                         DBG(1, "usb_submit_urb() failed, error %d", err);
888                         goto free_urbs;
889                 }
890         }
891
892         return 0;
893
894 free_urbs:
895         for (i = 0; (i < SN9C102_URBS) && cam->urb[i]; i++)
896                 usb_free_urb(cam->urb[i]);
897
898 free_buffers:
899         for (i = 0; (i < SN9C102_URBS) && cam->transfer_buffer[i]; i++)
900                 kfree(cam->transfer_buffer[i]);
901
902         return err;
903 }
904
905
906 static int sn9c102_stop_transfer(struct sn9c102_device* cam)
907 {
908         struct usb_device *udev = cam->usbdev;
909         s8 i;
910         int err = 0;
911
912         if (cam->state & DEV_DISCONNECTED)
913                 return 0;
914
915         for (i = SN9C102_URBS-1; i >= 0; i--) {
916                 usb_kill_urb(cam->urb[i]);
917                 usb_free_urb(cam->urb[i]);
918                 kfree(cam->transfer_buffer[i]);
919         }
920
921         err = usb_set_interface(udev, 0, 0); /* 0 Mb/s */
922         if (err)
923                 DBG(3, "usb_set_interface() failed");
924
925         return err;
926 }
927
928
929 static int sn9c102_stream_interrupt(struct sn9c102_device* cam)
930 {
931         long timeout;
932
933         cam->stream = STREAM_INTERRUPT;
934         timeout = wait_event_timeout(cam->wait_stream,
935                                      (cam->stream == STREAM_OFF) ||
936                                      (cam->state & DEV_DISCONNECTED),
937                                      SN9C102_URB_TIMEOUT);
938         if (cam->state & DEV_DISCONNECTED)
939                 return -ENODEV;
940         else if (cam->stream != STREAM_OFF) {
941                 cam->state |= DEV_MISCONFIGURED;
942                 DBG(1, "URB timeout reached. The camera is misconfigured. "
943                        "To use it, close and open /dev/video%d again.",
944                     cam->v4ldev->minor);
945                 return -EIO;
946         }
947
948         return 0;
949 }
950
951 /*****************************************************************************/
952
953 #ifdef CONFIG_VIDEO_ADV_DEBUG
954 static u16 sn9c102_strtou16(const char* buff, size_t len, ssize_t* count)
955 {
956         char str[7];
957         char* endp;
958         unsigned long val;
959
960         if (len < 6) {
961                 strncpy(str, buff, len);
962                 str[len+1] = '\0';
963         } else {
964                 strncpy(str, buff, 4);
965                 str[6] = '\0';
966         }
967
968         val = simple_strtoul(str, &endp, 0);
969
970         *count = 0;
971         if (val <= 0xffff)
972                 *count = (ssize_t)(endp - str);
973         if ((*count) && (len == *count+1) && (buff[*count] == '\n'))
974                 *count += 1;
975
976         return (u16)val;
977 }
978
979 /*
980    NOTE 1: being inside one of the following methods implies that the v4l
981            device exists for sure (see kobjects and reference counters)
982    NOTE 2: buffers are PAGE_SIZE long
983 */
984
985 static ssize_t sn9c102_show_reg(struct class_device* cd, char* buf)
986 {
987         struct sn9c102_device* cam;
988         ssize_t count;
989
990         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
991                 return -ERESTARTSYS;
992
993         cam = video_get_drvdata(container_of(cd, struct video_device,
994                                              class_dev));
995         if (!cam) {
996                 mutex_unlock(&sn9c102_sysfs_lock);
997                 return -ENODEV;
998         }
999
1000         count = sprintf(buf, "%u\n", cam->sysfs.reg);
1001
1002         mutex_unlock(&sn9c102_sysfs_lock);
1003
1004         return count;
1005 }
1006
1007
1008 static ssize_t
1009 sn9c102_store_reg(struct class_device* cd, const char* buf, size_t len)
1010 {
1011         struct sn9c102_device* cam;
1012         u16 index;
1013         ssize_t count;
1014
1015         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1016                 return -ERESTARTSYS;
1017
1018         cam = video_get_drvdata(container_of(cd, struct video_device,
1019                                              class_dev));
1020         if (!cam) {
1021                 mutex_unlock(&sn9c102_sysfs_lock);
1022                 return -ENODEV;
1023         }
1024
1025         index = sn9c102_strtou16(buf, len, &count);
1026         if (index >= ARRAY_SIZE(cam->reg) || !count) {
1027                 mutex_unlock(&sn9c102_sysfs_lock);
1028                 return -EINVAL;
1029         }
1030
1031         cam->sysfs.reg = index;
1032
1033         DBG(2, "Moved SN9C1XX register index to 0x%02X", cam->sysfs.reg);
1034         DBG(3, "Written bytes: %zd", count);
1035
1036         mutex_unlock(&sn9c102_sysfs_lock);
1037
1038         return count;
1039 }
1040
1041
1042 static ssize_t sn9c102_show_val(struct class_device* cd, char* buf)
1043 {
1044         struct sn9c102_device* cam;
1045         ssize_t count;
1046         int val;
1047
1048         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1049                 return -ERESTARTSYS;
1050
1051         cam = video_get_drvdata(container_of(cd, struct video_device,
1052                                              class_dev));
1053         if (!cam) {
1054                 mutex_unlock(&sn9c102_sysfs_lock);
1055                 return -ENODEV;
1056         }
1057
1058         if ((val = sn9c102_read_reg(cam, cam->sysfs.reg)) < 0) {
1059                 mutex_unlock(&sn9c102_sysfs_lock);
1060                 return -EIO;
1061         }
1062
1063         count = sprintf(buf, "%d\n", val);
1064
1065         DBG(3, "Read bytes: %zd", count);
1066
1067         mutex_unlock(&sn9c102_sysfs_lock);
1068
1069         return count;
1070 }
1071
1072
1073 static ssize_t
1074 sn9c102_store_val(struct class_device* cd, const char* buf, size_t len)
1075 {
1076         struct sn9c102_device* cam;
1077         u16 value;
1078         ssize_t count;
1079         int err;
1080
1081         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1082                 return -ERESTARTSYS;
1083
1084         cam = video_get_drvdata(container_of(cd, struct video_device,
1085                                              class_dev));
1086         if (!cam) {
1087                 mutex_unlock(&sn9c102_sysfs_lock);
1088                 return -ENODEV;
1089         }
1090
1091         value = sn9c102_strtou16(buf, len, &count);
1092         if (!count) {
1093                 mutex_unlock(&sn9c102_sysfs_lock);
1094                 return -EINVAL;
1095         }
1096
1097         err = sn9c102_write_reg(cam, value, cam->sysfs.reg);
1098         if (err) {
1099                 mutex_unlock(&sn9c102_sysfs_lock);
1100                 return -EIO;
1101         }
1102
1103         DBG(2, "Written SN9C1XX reg. 0x%02X, val. 0x%02X",
1104             cam->sysfs.reg, value);
1105         DBG(3, "Written bytes: %zd", count);
1106
1107         mutex_unlock(&sn9c102_sysfs_lock);
1108
1109         return count;
1110 }
1111
1112
1113 static ssize_t sn9c102_show_i2c_reg(struct class_device* cd, char* buf)
1114 {
1115         struct sn9c102_device* cam;
1116         ssize_t count;
1117
1118         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1119                 return -ERESTARTSYS;
1120
1121         cam = video_get_drvdata(container_of(cd, struct video_device,
1122                                              class_dev));
1123         if (!cam) {
1124                 mutex_unlock(&sn9c102_sysfs_lock);
1125                 return -ENODEV;
1126         }
1127
1128         count = sprintf(buf, "%u\n", cam->sysfs.i2c_reg);
1129
1130         DBG(3, "Read bytes: %zd", count);
1131
1132         mutex_unlock(&sn9c102_sysfs_lock);
1133
1134         return count;
1135 }
1136
1137
1138 static ssize_t
1139 sn9c102_store_i2c_reg(struct class_device* cd, const char* buf, size_t len)
1140 {
1141         struct sn9c102_device* cam;
1142         u16 index;
1143         ssize_t count;
1144
1145         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1146                 return -ERESTARTSYS;
1147
1148         cam = video_get_drvdata(container_of(cd, struct video_device,
1149                                              class_dev));
1150         if (!cam) {
1151                 mutex_unlock(&sn9c102_sysfs_lock);
1152                 return -ENODEV;
1153         }
1154
1155         index = sn9c102_strtou16(buf, len, &count);
1156         if (!count) {
1157                 mutex_unlock(&sn9c102_sysfs_lock);
1158                 return -EINVAL;
1159         }
1160
1161         cam->sysfs.i2c_reg = index;
1162
1163         DBG(2, "Moved sensor register index to 0x%02X", cam->sysfs.i2c_reg);
1164         DBG(3, "Written bytes: %zd", count);
1165
1166         mutex_unlock(&sn9c102_sysfs_lock);
1167
1168         return count;
1169 }
1170
1171
1172 static ssize_t sn9c102_show_i2c_val(struct class_device* cd, char* buf)
1173 {
1174         struct sn9c102_device* cam;
1175         ssize_t count;
1176         int val;
1177
1178         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1179                 return -ERESTARTSYS;
1180
1181         cam = video_get_drvdata(container_of(cd, struct video_device,
1182                                              class_dev));
1183         if (!cam) {
1184                 mutex_unlock(&sn9c102_sysfs_lock);
1185                 return -ENODEV;
1186         }
1187
1188         if (!(cam->sensor.sysfs_ops & SN9C102_I2C_READ)) {
1189                 mutex_unlock(&sn9c102_sysfs_lock);
1190                 return -ENOSYS;
1191         }
1192
1193         if ((val = sn9c102_i2c_read(cam, cam->sysfs.i2c_reg)) < 0) {
1194                 mutex_unlock(&sn9c102_sysfs_lock);
1195                 return -EIO;
1196         }
1197
1198         count = sprintf(buf, "%d\n", val);
1199
1200         DBG(3, "Read bytes: %zd", count);
1201
1202         mutex_unlock(&sn9c102_sysfs_lock);
1203
1204         return count;
1205 }
1206
1207
1208 static ssize_t
1209 sn9c102_store_i2c_val(struct class_device* cd, const char* buf, size_t len)
1210 {
1211         struct sn9c102_device* cam;
1212         u16 value;
1213         ssize_t count;
1214         int err;
1215
1216         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1217                 return -ERESTARTSYS;
1218
1219         cam = video_get_drvdata(container_of(cd, struct video_device,
1220                                              class_dev));
1221         if (!cam) {
1222                 mutex_unlock(&sn9c102_sysfs_lock);
1223                 return -ENODEV;
1224         }
1225
1226         if (!(cam->sensor.sysfs_ops & SN9C102_I2C_WRITE)) {
1227                 mutex_unlock(&sn9c102_sysfs_lock);
1228                 return -ENOSYS;
1229         }
1230
1231         value = sn9c102_strtou16(buf, len, &count);
1232         if (!count) {
1233                 mutex_unlock(&sn9c102_sysfs_lock);
1234                 return -EINVAL;
1235         }
1236
1237         err = sn9c102_i2c_write(cam, cam->sysfs.i2c_reg, value);
1238         if (err) {
1239                 mutex_unlock(&sn9c102_sysfs_lock);
1240                 return -EIO;
1241         }
1242
1243         DBG(2, "Written sensor reg. 0x%02X, val. 0x%02X",
1244             cam->sysfs.i2c_reg, value);
1245         DBG(3, "Written bytes: %zd", count);
1246
1247         mutex_unlock(&sn9c102_sysfs_lock);
1248
1249         return count;
1250 }
1251
1252
1253 static ssize_t
1254 sn9c102_store_green(struct class_device* cd, const char* buf, size_t len)
1255 {
1256         struct sn9c102_device* cam;
1257         enum sn9c102_bridge bridge;
1258         ssize_t res = 0;
1259         u16 value;
1260         ssize_t count;
1261
1262         if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1263                 return -ERESTARTSYS;
1264
1265         cam = video_get_drvdata(container_of(cd, struct video_device,
1266                                              class_dev));
1267         if (!cam) {
1268                 mutex_unlock(&sn9c102_sysfs_lock);
1269                 return -ENODEV;
1270         }
1271
1272         bridge = cam->bridge;
1273
1274         mutex_unlock(&sn9c102_sysfs_lock);
1275
1276         value = sn9c102_strtou16(buf, len, &count);
1277         if (!count)
1278                 return -EINVAL;
1279
1280         switch (bridge) {
1281         case BRIDGE_SN9C101:
1282         case BRIDGE_SN9C102:
1283                 if (value > 0x0f)
1284                         return -EINVAL;
1285                 if ((res = sn9c102_store_reg(cd, "0x11", 4)) >= 0)
1286                         res = sn9c102_store_val(cd, buf, len);
1287                 break;
1288         case BRIDGE_SN9C103:
1289         case BRIDGE_SN9C105:
1290         case BRIDGE_SN9C120:
1291                 if (value > 0x7f)
1292                         return -EINVAL;
1293                 if ((res = sn9c102_store_reg(cd, "0x07", 4)) >= 0)
1294                         res = sn9c102_store_val(cd, buf, len);
1295                 break;
1296         }
1297
1298         return res;
1299 }
1300
1301
1302 static ssize_t
1303 sn9c102_store_blue(struct class_device* cd, const char* buf, size_t len)
1304 {
1305         ssize_t res = 0;
1306         u16 value;
1307         ssize_t count;
1308
1309         value = sn9c102_strtou16(buf, len, &count);
1310         if (!count || value > 0x7f)
1311                 return -EINVAL;
1312
1313         if ((res = sn9c102_store_reg(cd, "0x06", 4)) >= 0)
1314                 res = sn9c102_store_val(cd, buf, len);
1315
1316         return res;
1317 }
1318
1319
1320 static ssize_t
1321 sn9c102_store_red(struct class_device* cd, const char* buf, size_t len)
1322 {
1323         ssize_t res = 0;
1324         u16 value;
1325         ssize_t count;
1326
1327         value = sn9c102_strtou16(buf, len, &count);
1328         if (!count || value > 0x7f)
1329                 return -EINVAL;
1330
1331         if ((res = sn9c102_store_reg(cd, "0x05", 4)) >= 0)
1332                 res = sn9c102_store_val(cd, buf, len);
1333
1334         return res;
1335 }
1336
1337
1338 static ssize_t sn9c102_show_frame_header(struct class_device* cd, char* buf)
1339 {
1340         struct sn9c102_device* cam;
1341         ssize_t count;
1342
1343         cam = video_get_drvdata(container_of(cd, struct video_device,
1344                                              class_dev));
1345         if (!cam)
1346                 return -ENODEV;
1347
1348         count = sizeof(cam->sysfs.frame_header);
1349         memcpy(buf, cam->sysfs.frame_header, count);
1350
1351         DBG(3, "Frame header, read bytes: %zd", count);
1352
1353         return count;
1354 }
1355
1356
1357 static CLASS_DEVICE_ATTR(reg, S_IRUGO | S_IWUSR,
1358                          sn9c102_show_reg, sn9c102_store_reg);
1359 static CLASS_DEVICE_ATTR(val, S_IRUGO | S_IWUSR,
1360                          sn9c102_show_val, sn9c102_store_val);
1361 static CLASS_DEVICE_ATTR(i2c_reg, S_IRUGO | S_IWUSR,
1362                          sn9c102_show_i2c_reg, sn9c102_store_i2c_reg);
1363 static CLASS_DEVICE_ATTR(i2c_val, S_IRUGO | S_IWUSR,
1364                          sn9c102_show_i2c_val, sn9c102_store_i2c_val);
1365 static CLASS_DEVICE_ATTR(green, S_IWUGO, NULL, sn9c102_store_green);
1366 static CLASS_DEVICE_ATTR(blue, S_IWUGO, NULL, sn9c102_store_blue);
1367 static CLASS_DEVICE_ATTR(red, S_IWUGO, NULL, sn9c102_store_red);
1368 static CLASS_DEVICE_ATTR(frame_header, S_IRUGO,
1369                          sn9c102_show_frame_header, NULL);
1370
1371
1372 static int sn9c102_create_sysfs(struct sn9c102_device* cam)
1373 {
1374         struct video_device *v4ldev = cam->v4ldev;
1375         int err = 0;
1376
1377         if ((err = video_device_create_file(v4ldev, &class_device_attr_reg)))
1378                 goto err_out;
1379         if ((err = video_device_create_file(v4ldev, &class_device_attr_val)))
1380                 goto err_reg;
1381         if ((err = video_device_create_file(v4ldev,
1382                                             &class_device_attr_frame_header)))
1383                 goto err_val;
1384
1385         if (cam->sensor.sysfs_ops) {
1386                 if ((err = video_device_create_file(v4ldev,
1387                                                   &class_device_attr_i2c_reg)))
1388                         goto err_frame_header;
1389                 if ((err = video_device_create_file(v4ldev,
1390                                                   &class_device_attr_i2c_val)))
1391                         goto err_i2c_reg;
1392         }
1393
1394         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102) {
1395                 if ((err = video_device_create_file(v4ldev,
1396                                                     &class_device_attr_green)))
1397                         goto err_i2c_val;
1398         } else {
1399                 if ((err = video_device_create_file(v4ldev,
1400                                                     &class_device_attr_blue)))
1401                         goto err_i2c_val;
1402                 if ((err = video_device_create_file(v4ldev,
1403                                                     &class_device_attr_red)))
1404                         goto err_blue;
1405         }
1406
1407         return 0;
1408
1409 err_blue:
1410         video_device_remove_file(v4ldev, &class_device_attr_blue);
1411 err_i2c_val:
1412         if (cam->sensor.sysfs_ops)
1413                 video_device_remove_file(v4ldev, &class_device_attr_i2c_val);
1414 err_i2c_reg:
1415         if (cam->sensor.sysfs_ops)
1416                 video_device_remove_file(v4ldev, &class_device_attr_i2c_reg);
1417 err_frame_header:
1418         video_device_remove_file(v4ldev, &class_device_attr_frame_header);
1419 err_val:
1420         video_device_remove_file(v4ldev, &class_device_attr_val);
1421 err_reg:
1422         video_device_remove_file(v4ldev, &class_device_attr_reg);
1423 err_out:
1424         return err;
1425 }
1426 #endif /* CONFIG_VIDEO_ADV_DEBUG */
1427
1428 /*****************************************************************************/
1429
1430 static int
1431 sn9c102_set_pix_format(struct sn9c102_device* cam, struct v4l2_pix_format* pix)
1432 {
1433         int err = 0;
1434
1435         if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X ||
1436             pix->pixelformat == V4L2_PIX_FMT_JPEG) {
1437                 switch (cam->bridge) {
1438                 case BRIDGE_SN9C101:
1439                 case BRIDGE_SN9C102:
1440                 case BRIDGE_SN9C103:
1441                         err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x80,
1442                                                  0x18);
1443                         break;
1444                 case BRIDGE_SN9C105:
1445                 case BRIDGE_SN9C120:
1446                         err += sn9c102_write_reg(cam, cam->reg[0x18] & 0x7f,
1447                                                  0x18);
1448                         break;
1449                 }
1450         } else {
1451                 switch (cam->bridge) {
1452                 case BRIDGE_SN9C101:
1453                 case BRIDGE_SN9C102:
1454                 case BRIDGE_SN9C103:
1455                         err += sn9c102_write_reg(cam, cam->reg[0x18] & 0x7f,
1456                                                  0x18);
1457                         break;
1458                 case BRIDGE_SN9C105:
1459                 case BRIDGE_SN9C120:
1460                         err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x80,
1461                                                  0x18);
1462                         break;
1463                 }
1464         }
1465
1466         return err ? -EIO : 0;
1467 }
1468
1469
1470 static int
1471 sn9c102_set_compression(struct sn9c102_device* cam,
1472                         struct v4l2_jpegcompression* compression)
1473 {
1474         int i, err = 0;
1475
1476         switch (cam->bridge) {
1477         case BRIDGE_SN9C101:
1478         case BRIDGE_SN9C102:
1479         case BRIDGE_SN9C103:
1480         if (compression->quality == 0)
1481                         err += sn9c102_write_reg(cam, cam->reg[0x17] | 0x01,
1482                                                  0x17);
1483         else if (compression->quality == 1)
1484                         err += sn9c102_write_reg(cam, cam->reg[0x17] & 0xfe,
1485                                                  0x17);
1486                 break;
1487         case BRIDGE_SN9C105:
1488         case BRIDGE_SN9C120:
1489                 if (compression->quality == 0) {
1490                         for (i = 0; i <= 63; i++) {
1491                                 err += sn9c102_write_reg(cam,
1492                                                          SN9C102_Y_QTABLE0[i],
1493                                                          0x100 + i);
1494                                 err += sn9c102_write_reg(cam,
1495                                                          SN9C102_UV_QTABLE0[i],
1496                                                          0x140 + i);
1497                         }
1498                         err += sn9c102_write_reg(cam, cam->reg[0x18] & 0xbf,
1499                                                  0x18);
1500                 } else if (compression->quality == 1) {
1501                         for (i = 0; i <= 63; i++) {
1502                                 err += sn9c102_write_reg(cam,
1503                                                          SN9C102_Y_QTABLE1[i],
1504                                                          0x100 + i);
1505                                 err += sn9c102_write_reg(cam,
1506                                                          SN9C102_UV_QTABLE1[i],
1507                                                          0x140 + i);
1508                         }
1509                         err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x40,
1510                                                  0x18);
1511                 }
1512                 break;
1513         }
1514
1515         return err ? -EIO : 0;
1516 }
1517
1518
1519 static int sn9c102_set_scale(struct sn9c102_device* cam, u8 scale)
1520 {
1521         u8 r = 0;
1522         int err = 0;
1523
1524         if (scale == 1)
1525                 r = cam->reg[0x18] & 0xcf;
1526         else if (scale == 2) {
1527                 r = cam->reg[0x18] & 0xcf;
1528                 r |= 0x10;
1529         } else if (scale == 4)
1530                 r = cam->reg[0x18] | 0x20;
1531
1532         err += sn9c102_write_reg(cam, r, 0x18);
1533         if (err)
1534                 return -EIO;
1535
1536         PDBGG("Scaling factor: %u", scale);
1537
1538         return 0;
1539 }
1540
1541
1542 static int sn9c102_set_crop(struct sn9c102_device* cam, struct v4l2_rect* rect)
1543 {
1544         struct sn9c102_sensor* s = &cam->sensor;
1545         u8 h_start = (u8)(rect->left - s->cropcap.bounds.left),
1546            v_start = (u8)(rect->top - s->cropcap.bounds.top),
1547            h_size = (u8)(rect->width / 16),
1548            v_size = (u8)(rect->height / 16);
1549         int err = 0;
1550
1551         err += sn9c102_write_reg(cam, h_start, 0x12);
1552         err += sn9c102_write_reg(cam, v_start, 0x13);
1553         err += sn9c102_write_reg(cam, h_size, 0x15);
1554         err += sn9c102_write_reg(cam, v_size, 0x16);
1555         if (err)
1556                 return -EIO;
1557
1558         PDBGG("h_start, v_start, h_size, v_size, ho_size, vo_size "
1559               "%u %u %u %u", h_start, v_start, h_size, v_size);
1560
1561         return 0;
1562 }
1563
1564
1565 static int sn9c102_init(struct sn9c102_device* cam)
1566 {
1567         struct sn9c102_sensor* s = &cam->sensor;
1568         struct v4l2_control ctrl;
1569         struct v4l2_queryctrl *qctrl;
1570         struct v4l2_rect* rect;
1571         u8 i = 0;
1572         int err = 0;
1573
1574         if (!(cam->state & DEV_INITIALIZED)) {
1575                 init_waitqueue_head(&cam->open);
1576                 qctrl = s->qctrl;
1577                 rect = &(s->cropcap.defrect);
1578         } else { /* use current values */
1579                 qctrl = s->_qctrl;
1580                 rect = &(s->_rect);
1581         }
1582
1583         err += sn9c102_set_scale(cam, rect->width / s->pix_format.width);
1584         err += sn9c102_set_crop(cam, rect);
1585         if (err)
1586                 return err;
1587
1588         if (s->init) {
1589                 err = s->init(cam);
1590                 if (err) {
1591                         DBG(3, "Sensor initialization failed");
1592                         return err;
1593                 }
1594         }
1595
1596         if (!(cam->state & DEV_INITIALIZED))
1597                 if (cam->bridge == BRIDGE_SN9C101 ||
1598                     cam->bridge == BRIDGE_SN9C102 ||
1599                     cam->bridge == BRIDGE_SN9C103) {
1600                         cam->compression.quality =  cam->reg[0x17] & 0x01 ?
1601                                                     0 : 1;
1602                 } else {
1603                         cam->compression.quality =  cam->reg[0x18] & 0x40 ?
1604                                                     0 : 1;
1605                         err += sn9c102_set_compression(cam, &cam->compression);
1606                 }
1607         else
1608                 err += sn9c102_set_compression(cam, &cam->compression);
1609         err += sn9c102_set_pix_format(cam, &s->pix_format);
1610         if (s->set_pix_format)
1611                 err += s->set_pix_format(cam, &s->pix_format);
1612         if (err)
1613                 return err;
1614
1615         if (s->pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X ||
1616             s->pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
1617                 DBG(3, "Compressed video format is active, quality %d",
1618                     cam->compression.quality);
1619         else
1620                 DBG(3, "Uncompressed video format is active");
1621
1622         if (s->set_crop)
1623                 if ((err = s->set_crop(cam, rect))) {
1624                         DBG(3, "set_crop() failed");
1625                         return err;
1626                 }
1627
1628         if (s->set_ctrl) {
1629                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1630                         if (s->qctrl[i].id != 0 &&
1631                             !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
1632                                 ctrl.id = s->qctrl[i].id;
1633                                 ctrl.value = qctrl[i].default_value;
1634                                 err = s->set_ctrl(cam, &ctrl);
1635                                 if (err) {
1636                                         DBG(3, "Set %s control failed",
1637                                             s->qctrl[i].name);
1638                                         return err;
1639                                 }
1640                                 DBG(3, "Image sensor supports '%s' control",
1641                                     s->qctrl[i].name);
1642                         }
1643         }
1644
1645         if (!(cam->state & DEV_INITIALIZED)) {
1646                 mutex_init(&cam->fileop_mutex);
1647                 spin_lock_init(&cam->queue_lock);
1648                 init_waitqueue_head(&cam->wait_frame);
1649                 init_waitqueue_head(&cam->wait_stream);
1650                 cam->nreadbuffers = 2;
1651                 memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
1652                 memcpy(&(s->_rect), &(s->cropcap.defrect),
1653                        sizeof(struct v4l2_rect));
1654                 cam->state |= DEV_INITIALIZED;
1655         }
1656
1657         DBG(2, "Initialization succeeded");
1658         return 0;
1659 }
1660
1661
1662 static void sn9c102_release_resources(struct sn9c102_device* cam)
1663 {
1664         mutex_lock(&sn9c102_sysfs_lock);
1665
1666         DBG(2, "V4L2 device /dev/video%d deregistered", cam->v4ldev->minor);
1667         video_set_drvdata(cam->v4ldev, NULL);
1668         video_unregister_device(cam->v4ldev);
1669
1670         mutex_unlock(&sn9c102_sysfs_lock);
1671
1672         kfree(cam->control_buffer);
1673 }
1674
1675 /*****************************************************************************/
1676
1677 static int sn9c102_open(struct inode* inode, struct file* filp)
1678 {
1679         struct sn9c102_device* cam;
1680         int err = 0;
1681
1682         /*
1683            This is the only safe way to prevent race conditions with
1684            disconnect
1685         */
1686         if (!down_read_trylock(&sn9c102_disconnect))
1687                 return -ERESTARTSYS;
1688
1689         cam = video_get_drvdata(video_devdata(filp));
1690
1691         if (mutex_lock_interruptible(&cam->dev_mutex)) {
1692                 up_read(&sn9c102_disconnect);
1693                 return -ERESTARTSYS;
1694         }
1695
1696         if (cam->users) {
1697                 DBG(2, "Device /dev/video%d is busy...", cam->v4ldev->minor);
1698                 DBG(3, "Simultaneous opens are not supported");
1699                 if ((filp->f_flags & O_NONBLOCK) ||
1700                     (filp->f_flags & O_NDELAY)) {
1701                         err = -EWOULDBLOCK;
1702                         goto out;
1703                 }
1704                 mutex_unlock(&cam->dev_mutex);
1705                 err = wait_event_interruptible_exclusive(cam->open,
1706                                                   cam->state & DEV_DISCONNECTED
1707                                                          || !cam->users);
1708                 if (err) {
1709                         up_read(&sn9c102_disconnect);
1710                         return err;
1711                 }
1712                 if (cam->state & DEV_DISCONNECTED) {
1713                         up_read(&sn9c102_disconnect);
1714                         return -ENODEV;
1715                 }
1716                 mutex_lock(&cam->dev_mutex);
1717         }
1718
1719
1720         if (cam->state & DEV_MISCONFIGURED) {
1721                 err = sn9c102_init(cam);
1722                 if (err) {
1723                         DBG(1, "Initialization failed again. "
1724                                "I will retry on next open().");
1725                         goto out;
1726                 }
1727                 cam->state &= ~DEV_MISCONFIGURED;
1728         }
1729
1730         if ((err = sn9c102_start_transfer(cam)))
1731                 goto out;
1732
1733         filp->private_data = cam;
1734         cam->users++;
1735         cam->io = IO_NONE;
1736         cam->stream = STREAM_OFF;
1737         cam->nbuffers = 0;
1738         cam->frame_count = 0;
1739         sn9c102_empty_framequeues(cam);
1740
1741         DBG(3, "Video device /dev/video%d is open", cam->v4ldev->minor);
1742
1743 out:
1744         mutex_unlock(&cam->dev_mutex);
1745         up_read(&sn9c102_disconnect);
1746         return err;
1747 }
1748
1749
1750 static int sn9c102_release(struct inode* inode, struct file* filp)
1751 {
1752         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1753
1754         mutex_lock(&cam->dev_mutex); /* prevent disconnect() to be called */
1755
1756         sn9c102_stop_transfer(cam);
1757
1758         sn9c102_release_buffers(cam);
1759
1760         if (cam->state & DEV_DISCONNECTED) {
1761                 sn9c102_release_resources(cam);
1762                 usb_put_dev(cam->usbdev);
1763                 mutex_unlock(&cam->dev_mutex);
1764                 kfree(cam);
1765                 return 0;
1766         }
1767
1768         cam->users--;
1769         wake_up_interruptible_nr(&cam->open, 1);
1770
1771         DBG(3, "Video device /dev/video%d closed", cam->v4ldev->minor);
1772
1773         mutex_unlock(&cam->dev_mutex);
1774
1775         return 0;
1776 }
1777
1778
1779 static ssize_t
1780 sn9c102_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
1781 {
1782         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1783         struct sn9c102_frame_t* f, * i;
1784         unsigned long lock_flags;
1785         long timeout;
1786         int err = 0;
1787
1788         if (mutex_lock_interruptible(&cam->fileop_mutex))
1789                 return -ERESTARTSYS;
1790
1791         if (cam->state & DEV_DISCONNECTED) {
1792                 DBG(1, "Device not present");
1793                 mutex_unlock(&cam->fileop_mutex);
1794                 return -ENODEV;
1795         }
1796
1797         if (cam->state & DEV_MISCONFIGURED) {
1798                 DBG(1, "The camera is misconfigured. Close and open it "
1799                        "again.");
1800                 mutex_unlock(&cam->fileop_mutex);
1801                 return -EIO;
1802         }
1803
1804         if (cam->io == IO_MMAP) {
1805                 DBG(3, "Close and open the device again to choose "
1806                        "the read method");
1807                 mutex_unlock(&cam->fileop_mutex);
1808                 return -EINVAL;
1809         }
1810
1811         if (cam->io == IO_NONE) {
1812                 if (!sn9c102_request_buffers(cam,cam->nreadbuffers, IO_READ)) {
1813                         DBG(1, "read() failed, not enough memory");
1814                         mutex_unlock(&cam->fileop_mutex);
1815                         return -ENOMEM;
1816                 }
1817                 cam->io = IO_READ;
1818                 cam->stream = STREAM_ON;
1819         }
1820
1821         if (list_empty(&cam->inqueue)) {
1822                 if (!list_empty(&cam->outqueue))
1823                         sn9c102_empty_framequeues(cam);
1824                 sn9c102_queue_unusedframes(cam);
1825         }
1826
1827         if (!count) {
1828                 mutex_unlock(&cam->fileop_mutex);
1829                 return 0;
1830         }
1831
1832         if (list_empty(&cam->outqueue)) {
1833                 if (filp->f_flags & O_NONBLOCK) {
1834                         mutex_unlock(&cam->fileop_mutex);
1835                         return -EAGAIN;
1836                 }
1837                 if (!cam->module_param.frame_timeout) {
1838                         err = wait_event_interruptible
1839                               ( cam->wait_frame,
1840                                 (!list_empty(&cam->outqueue)) ||
1841                                 (cam->state & DEV_DISCONNECTED) ||
1842                                 (cam->state & DEV_MISCONFIGURED) );
1843                         if (err) {
1844                                 mutex_unlock(&cam->fileop_mutex);
1845                                 return err;
1846                         }
1847                 } else {
1848                 timeout = wait_event_interruptible_timeout
1849                           ( cam->wait_frame,
1850                             (!list_empty(&cam->outqueue)) ||
1851                             (cam->state & DEV_DISCONNECTED) ||
1852                             (cam->state & DEV_MISCONFIGURED),
1853                             cam->module_param.frame_timeout *
1854                             1000 * msecs_to_jiffies(1) );
1855                 if (timeout < 0) {
1856                         mutex_unlock(&cam->fileop_mutex);
1857                         return timeout;
1858                         } else if (timeout == 0 &&
1859                                    !(cam->state & DEV_DISCONNECTED)) {
1860                                 DBG(1, "Video frame timeout elapsed");
1861                                 mutex_unlock(&cam->fileop_mutex);
1862                                 return -EIO;
1863                         }
1864                 }
1865                 if (cam->state & DEV_DISCONNECTED) {
1866                         mutex_unlock(&cam->fileop_mutex);
1867                         return -ENODEV;
1868                 }
1869                 if (cam->state & DEV_MISCONFIGURED) {
1870                         mutex_unlock(&cam->fileop_mutex);
1871                         return -EIO;
1872                 }
1873         }
1874
1875         f = list_entry(cam->outqueue.prev, struct sn9c102_frame_t, frame);
1876
1877         if (count > f->buf.bytesused)
1878                 count = f->buf.bytesused;
1879
1880         if (copy_to_user(buf, f->bufmem, count)) {
1881                 err = -EFAULT;
1882                 goto exit;
1883         }
1884         *f_pos += count;
1885
1886 exit:
1887         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1888         list_for_each_entry(i, &cam->outqueue, frame)
1889                 i->state = F_UNUSED;
1890         INIT_LIST_HEAD(&cam->outqueue);
1891         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1892
1893         sn9c102_queue_unusedframes(cam);
1894
1895         PDBGG("Frame #%lu, bytes read: %zu",
1896               (unsigned long)f->buf.index, count);
1897
1898         mutex_unlock(&cam->fileop_mutex);
1899
1900         return count;
1901 }
1902
1903
1904 static unsigned int sn9c102_poll(struct file *filp, poll_table *wait)
1905 {
1906         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1907         struct sn9c102_frame_t* f;
1908         unsigned long lock_flags;
1909         unsigned int mask = 0;
1910
1911         if (mutex_lock_interruptible(&cam->fileop_mutex))
1912                 return POLLERR;
1913
1914         if (cam->state & DEV_DISCONNECTED) {
1915                 DBG(1, "Device not present");
1916                 goto error;
1917         }
1918
1919         if (cam->state & DEV_MISCONFIGURED) {
1920                 DBG(1, "The camera is misconfigured. Close and open it "
1921                        "again.");
1922                 goto error;
1923         }
1924
1925         if (cam->io == IO_NONE) {
1926                 if (!sn9c102_request_buffers(cam, cam->nreadbuffers,
1927                                              IO_READ)) {
1928                         DBG(1, "poll() failed, not enough memory");
1929                         goto error;
1930                 }
1931                 cam->io = IO_READ;
1932                 cam->stream = STREAM_ON;
1933         }
1934
1935         if (cam->io == IO_READ) {
1936                 spin_lock_irqsave(&cam->queue_lock, lock_flags);
1937                 list_for_each_entry(f, &cam->outqueue, frame)
1938                         f->state = F_UNUSED;
1939                 INIT_LIST_HEAD(&cam->outqueue);
1940                 spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1941                 sn9c102_queue_unusedframes(cam);
1942         }
1943
1944         poll_wait(filp, &cam->wait_frame, wait);
1945
1946         if (!list_empty(&cam->outqueue))
1947                 mask |= POLLIN | POLLRDNORM;
1948
1949         mutex_unlock(&cam->fileop_mutex);
1950
1951         return mask;
1952
1953 error:
1954         mutex_unlock(&cam->fileop_mutex);
1955         return POLLERR;
1956 }
1957
1958
1959 static void sn9c102_vm_open(struct vm_area_struct* vma)
1960 {
1961         struct sn9c102_frame_t* f = vma->vm_private_data;
1962         f->vma_use_count++;
1963 }
1964
1965
1966 static void sn9c102_vm_close(struct vm_area_struct* vma)
1967 {
1968         /* NOTE: buffers are not freed here */
1969         struct sn9c102_frame_t* f = vma->vm_private_data;
1970         f->vma_use_count--;
1971 }
1972
1973
1974 static struct vm_operations_struct sn9c102_vm_ops = {
1975         .open = sn9c102_vm_open,
1976         .close = sn9c102_vm_close,
1977 };
1978
1979
1980 static int sn9c102_mmap(struct file* filp, struct vm_area_struct *vma)
1981 {
1982         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1983         unsigned long size = vma->vm_end - vma->vm_start,
1984                       start = vma->vm_start;
1985         void *pos;
1986         u32 i;
1987
1988         if (mutex_lock_interruptible(&cam->fileop_mutex))
1989                 return -ERESTARTSYS;
1990
1991         if (cam->state & DEV_DISCONNECTED) {
1992                 DBG(1, "Device not present");
1993                 mutex_unlock(&cam->fileop_mutex);
1994                 return -ENODEV;
1995         }
1996
1997         if (cam->state & DEV_MISCONFIGURED) {
1998                 DBG(1, "The camera is misconfigured. Close and open it "
1999                        "again.");
2000                 mutex_unlock(&cam->fileop_mutex);
2001                 return -EIO;
2002         }
2003
2004         if (cam->io != IO_MMAP || !(vma->vm_flags & VM_WRITE) ||
2005             size != PAGE_ALIGN(cam->frame[0].buf.length)) {
2006                 mutex_unlock(&cam->fileop_mutex);
2007                 return -EINVAL;
2008         }
2009
2010         for (i = 0; i < cam->nbuffers; i++) {
2011                 if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
2012                         break;
2013         }
2014         if (i == cam->nbuffers) {
2015                 mutex_unlock(&cam->fileop_mutex);
2016                 return -EINVAL;
2017         }
2018
2019         vma->vm_flags |= VM_IO;
2020         vma->vm_flags |= VM_RESERVED;
2021
2022         pos = cam->frame[i].bufmem;
2023         while (size > 0) { /* size is page-aligned */
2024                 if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
2025                         mutex_unlock(&cam->fileop_mutex);
2026                         return -EAGAIN;
2027                 }
2028                 start += PAGE_SIZE;
2029                 pos += PAGE_SIZE;
2030                 size -= PAGE_SIZE;
2031         }
2032
2033         vma->vm_ops = &sn9c102_vm_ops;
2034         vma->vm_private_data = &cam->frame[i];
2035
2036         sn9c102_vm_open(vma);
2037
2038         mutex_unlock(&cam->fileop_mutex);
2039
2040         return 0;
2041 }
2042
2043 /*****************************************************************************/
2044
2045 static int
2046 sn9c102_vidioc_querycap(struct sn9c102_device* cam, void __user * arg)
2047 {
2048         struct v4l2_capability cap = {
2049                 .driver = "sn9c102",
2050                 .version = SN9C102_MODULE_VERSION_CODE,
2051                 .capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
2052                                 V4L2_CAP_STREAMING,
2053         };
2054
2055         strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
2056         if (usb_make_path(cam->usbdev, cap.bus_info, sizeof(cap.bus_info)) < 0)
2057                 strlcpy(cap.bus_info, cam->usbdev->dev.bus_id,
2058                         sizeof(cap.bus_info));
2059
2060         if (copy_to_user(arg, &cap, sizeof(cap)))
2061                 return -EFAULT;
2062
2063         return 0;
2064 }
2065
2066
2067 static int
2068 sn9c102_vidioc_enuminput(struct sn9c102_device* cam, void __user * arg)
2069 {
2070         struct v4l2_input i;
2071
2072         if (copy_from_user(&i, arg, sizeof(i)))
2073                 return -EFAULT;
2074
2075         if (i.index)
2076                 return -EINVAL;
2077
2078         memset(&i, 0, sizeof(i));
2079         strcpy(i.name, "Camera");
2080         i.type = V4L2_INPUT_TYPE_CAMERA;
2081
2082         if (copy_to_user(arg, &i, sizeof(i)))
2083                 return -EFAULT;
2084
2085         return 0;
2086 }
2087
2088
2089 static int
2090 sn9c102_vidioc_g_input(struct sn9c102_device* cam, void __user * arg)
2091 {
2092         int index = 0;
2093
2094         if (copy_to_user(arg, &index, sizeof(index)))
2095                 return -EFAULT;
2096
2097         return 0;
2098 }
2099
2100
2101 static int
2102 sn9c102_vidioc_s_input(struct sn9c102_device* cam, void __user * arg)
2103 {
2104         int index;
2105
2106         if (copy_from_user(&index, arg, sizeof(index)))
2107                 return -EFAULT;
2108
2109         if (index != 0)
2110                 return -EINVAL;
2111
2112         return 0;
2113 }
2114
2115
2116 static int
2117 sn9c102_vidioc_query_ctrl(struct sn9c102_device* cam, void __user * arg)
2118 {
2119         struct sn9c102_sensor* s = &cam->sensor;
2120         struct v4l2_queryctrl qc;
2121         u8 i;
2122
2123         if (copy_from_user(&qc, arg, sizeof(qc)))
2124                 return -EFAULT;
2125
2126         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
2127                 if (qc.id && qc.id == s->qctrl[i].id) {
2128                         memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
2129                         if (copy_to_user(arg, &qc, sizeof(qc)))
2130                                 return -EFAULT;
2131                         return 0;
2132                 }
2133
2134         return -EINVAL;
2135 }
2136
2137
2138 static int
2139 sn9c102_vidioc_g_ctrl(struct sn9c102_device* cam, void __user * arg)
2140 {
2141         struct sn9c102_sensor* s = &cam->sensor;
2142         struct v4l2_control ctrl;
2143         int err = 0;
2144         u8 i;
2145
2146         if (!s->get_ctrl && !s->set_ctrl)
2147                 return -EINVAL;
2148
2149         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
2150                 return -EFAULT;
2151
2152         if (!s->get_ctrl) {
2153                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
2154                         if (ctrl.id && ctrl.id == s->qctrl[i].id) {
2155                                 ctrl.value = s->_qctrl[i].default_value;
2156                                 goto exit;
2157                         }
2158                 return -EINVAL;
2159         } else
2160                 err = s->get_ctrl(cam, &ctrl);
2161
2162 exit:
2163         if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
2164                 return -EFAULT;
2165
2166         PDBGG("VIDIOC_G_CTRL: id %lu, value %lu",
2167               (unsigned long)ctrl.id, (unsigned long)ctrl.value);
2168
2169         return err;
2170 }
2171
2172
2173 static int
2174 sn9c102_vidioc_s_ctrl(struct sn9c102_device* cam, void __user * arg)
2175 {
2176         struct sn9c102_sensor* s = &cam->sensor;
2177         struct v4l2_control ctrl;
2178         u8 i;
2179         int err = 0;
2180
2181         if (!s->set_ctrl)
2182                 return -EINVAL;
2183
2184         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
2185                 return -EFAULT;
2186
2187         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
2188                 if (ctrl.id == s->qctrl[i].id) {
2189                         if (s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)
2190                                 return -EINVAL;
2191                         if (ctrl.value < s->qctrl[i].minimum ||
2192                             ctrl.value > s->qctrl[i].maximum)
2193                                 return -ERANGE;
2194                         ctrl.value -= ctrl.value % s->qctrl[i].step;
2195                         break;
2196                 }
2197
2198         if ((err = s->set_ctrl(cam, &ctrl)))
2199                 return err;
2200
2201         s->_qctrl[i].default_value = ctrl.value;
2202
2203         PDBGG("VIDIOC_S_CTRL: id %lu, value %lu",
2204               (unsigned long)ctrl.id, (unsigned long)ctrl.value);
2205
2206         return 0;
2207 }
2208
2209
2210 static int
2211 sn9c102_vidioc_cropcap(struct sn9c102_device* cam, void __user * arg)
2212 {
2213         struct v4l2_cropcap* cc = &(cam->sensor.cropcap);
2214
2215         cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2216         cc->pixelaspect.numerator = 1;
2217         cc->pixelaspect.denominator = 1;
2218
2219         if (copy_to_user(arg, cc, sizeof(*cc)))
2220                 return -EFAULT;
2221
2222         return 0;
2223 }
2224
2225
2226 static int
2227 sn9c102_vidioc_g_crop(struct sn9c102_device* cam, void __user * arg)
2228 {
2229         struct sn9c102_sensor* s = &cam->sensor;
2230         struct v4l2_crop crop = {
2231                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2232         };
2233
2234         memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));
2235
2236         if (copy_to_user(arg, &crop, sizeof(crop)))
2237                 return -EFAULT;
2238
2239         return 0;
2240 }
2241
2242
2243 static int
2244 sn9c102_vidioc_s_crop(struct sn9c102_device* cam, void __user * arg)
2245 {
2246         struct sn9c102_sensor* s = &cam->sensor;
2247         struct v4l2_crop crop;
2248         struct v4l2_rect* rect;
2249         struct v4l2_rect* bounds = &(s->cropcap.bounds);
2250         struct v4l2_pix_format* pix_format = &(s->pix_format);
2251         u8 scale;
2252         const enum sn9c102_stream_state stream = cam->stream;
2253         const u32 nbuffers = cam->nbuffers;
2254         u32 i;
2255         int err = 0;
2256
2257         if (copy_from_user(&crop, arg, sizeof(crop)))
2258                 return -EFAULT;
2259
2260         rect = &(crop.c);
2261
2262         if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2263                 return -EINVAL;
2264
2265         if (cam->module_param.force_munmap)
2266                 for (i = 0; i < cam->nbuffers; i++)
2267                         if (cam->frame[i].vma_use_count) {
2268                                 DBG(3, "VIDIOC_S_CROP failed. "
2269                                        "Unmap the buffers first.");
2270                                 return -EINVAL;
2271                         }
2272
2273         /* Preserve R,G or B origin */
2274         rect->left = (s->_rect.left & 1L) ? rect->left | 1L : rect->left & ~1L;
2275         rect->top = (s->_rect.top & 1L) ? rect->top | 1L : rect->top & ~1L;
2276
2277         if (rect->width < 16)
2278                 rect->width = 16;
2279         if (rect->height < 16)
2280                 rect->height = 16;
2281         if (rect->width > bounds->width)
2282                 rect->width = bounds->width;
2283         if (rect->height > bounds->height)
2284                 rect->height = bounds->height;
2285         if (rect->left < bounds->left)
2286                 rect->left = bounds->left;
2287         if (rect->top < bounds->top)
2288                 rect->top = bounds->top;
2289         if (rect->left + rect->width > bounds->left + bounds->width)
2290                 rect->left = bounds->left+bounds->width - rect->width;
2291         if (rect->top + rect->height > bounds->top + bounds->height)
2292                 rect->top = bounds->top+bounds->height - rect->height;
2293
2294         rect->width &= ~15L;
2295         rect->height &= ~15L;
2296
2297         if (SN9C102_PRESERVE_IMGSCALE) {
2298                 /* Calculate the actual scaling factor */
2299                 u32 a, b;
2300                 a = rect->width * rect->height;
2301                 b = pix_format->width * pix_format->height;
2302                 scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2303         } else
2304                 scale = 1;
2305
2306         if (cam->stream == STREAM_ON)
2307                 if ((err = sn9c102_stream_interrupt(cam)))
2308                         return err;
2309
2310         if (copy_to_user(arg, &crop, sizeof(crop))) {
2311                 cam->stream = stream;
2312                 return -EFAULT;
2313         }
2314
2315         if (cam->module_param.force_munmap || cam->io == IO_READ)
2316                 sn9c102_release_buffers(cam);
2317
2318         err = sn9c102_set_crop(cam, rect);
2319         if (s->set_crop)
2320                 err += s->set_crop(cam, rect);
2321         err += sn9c102_set_scale(cam, scale);
2322
2323         if (err) { /* atomic, no rollback in ioctl() */
2324                 cam->state |= DEV_MISCONFIGURED;
2325                 DBG(1, "VIDIOC_S_CROP failed because of hardware problems. To "
2326                        "use the camera, close and open /dev/video%d again.",
2327                     cam->v4ldev->minor);
2328                 return -EIO;
2329         }
2330
2331         s->pix_format.width = rect->width/scale;
2332         s->pix_format.height = rect->height/scale;
2333         memcpy(&(s->_rect), rect, sizeof(*rect));
2334
2335         if ((cam->module_param.force_munmap || cam->io == IO_READ) &&
2336             nbuffers != sn9c102_request_buffers(cam, nbuffers, cam->io)) {
2337                 cam->state |= DEV_MISCONFIGURED;
2338                 DBG(1, "VIDIOC_S_CROP failed because of not enough memory. To "
2339                        "use the camera, close and open /dev/video%d again.",
2340                     cam->v4ldev->minor);
2341                 return -ENOMEM;
2342         }
2343
2344         if (cam->io == IO_READ)
2345                 sn9c102_empty_framequeues(cam);
2346         else if (cam->module_param.force_munmap)
2347                 sn9c102_requeue_outqueue(cam);
2348
2349         cam->stream = stream;
2350
2351         return 0;
2352 }
2353
2354
2355 static int
2356 sn9c102_vidioc_enum_framesizes(struct sn9c102_device* cam, void __user * arg)
2357 {
2358         struct v4l2_frmsizeenum frmsize;
2359
2360         if (copy_from_user(&frmsize, arg, sizeof(frmsize)))
2361                 return -EFAULT;
2362
2363         if (frmsize.index != 0)
2364                 return -EINVAL;
2365
2366         switch (cam->bridge) {
2367         case BRIDGE_SN9C101:
2368         case BRIDGE_SN9C102:
2369         case BRIDGE_SN9C103:
2370                 if (frmsize.pixel_format != V4L2_PIX_FMT_SN9C10X &&
2371                     frmsize.pixel_format != V4L2_PIX_FMT_SBGGR8)
2372                         return -EINVAL;
2373         case BRIDGE_SN9C105:
2374         case BRIDGE_SN9C120:
2375                 if (frmsize.pixel_format != V4L2_PIX_FMT_JPEG &&
2376                     frmsize.pixel_format != V4L2_PIX_FMT_SBGGR8)
2377                         return -EINVAL;
2378         }
2379
2380         frmsize.type = V4L2_FRMSIZE_TYPE_STEPWISE;
2381         frmsize.stepwise.min_width = frmsize.stepwise.step_width = 16;
2382         frmsize.stepwise.min_height = frmsize.stepwise.step_height = 16;
2383         frmsize.stepwise.max_width = cam->sensor.cropcap.bounds.width;
2384         frmsize.stepwise.max_height = cam->sensor.cropcap.bounds.height;
2385         memset(&frmsize.reserved, 0, sizeof(frmsize.reserved));
2386
2387         if (copy_to_user(arg, &frmsize, sizeof(frmsize)))
2388                 return -EFAULT;
2389
2390         return 0;
2391 }
2392
2393
2394 static int
2395 sn9c102_vidioc_enum_fmt(struct sn9c102_device* cam, void __user * arg)
2396 {
2397         struct v4l2_fmtdesc fmtd;
2398
2399         if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
2400                 return -EFAULT;
2401
2402         if (fmtd.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2403                 return -EINVAL;
2404
2405         if (fmtd.index == 0) {
2406                 strcpy(fmtd.description, "bayer rgb");
2407                 fmtd.pixelformat = V4L2_PIX_FMT_SBGGR8;
2408         } else if (fmtd.index == 1) {
2409                 switch (cam->bridge) {
2410                 case BRIDGE_SN9C101:
2411                 case BRIDGE_SN9C102:
2412                 case BRIDGE_SN9C103:
2413                 strcpy(fmtd.description, "compressed");
2414                 fmtd.pixelformat = V4L2_PIX_FMT_SN9C10X;
2415                         break;
2416                 case BRIDGE_SN9C105:
2417                 case BRIDGE_SN9C120:
2418                         strcpy(fmtd.description, "JPEG");
2419                         fmtd.pixelformat = V4L2_PIX_FMT_JPEG;
2420                         break;
2421                 }
2422                 fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
2423         } else
2424                 return -EINVAL;
2425
2426         fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2427         memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));
2428
2429         if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
2430                 return -EFAULT;
2431
2432         return 0;
2433 }
2434
2435
2436 static int
2437 sn9c102_vidioc_g_fmt(struct sn9c102_device* cam, void __user * arg)
2438 {
2439         struct v4l2_format format;
2440         struct v4l2_pix_format* pfmt = &(cam->sensor.pix_format);
2441
2442         if (copy_from_user(&format, arg, sizeof(format)))
2443                 return -EFAULT;
2444
2445         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2446                 return -EINVAL;
2447
2448         pfmt->bytesperline = (pfmt->pixelformat==V4L2_PIX_FMT_SN9C10X ||
2449                               pfmt->pixelformat==V4L2_PIX_FMT_JPEG)
2450                              ? 0 : (pfmt->width * pfmt->priv) / 8;
2451         pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
2452         pfmt->field = V4L2_FIELD_NONE;
2453         memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));
2454
2455         if (copy_to_user(arg, &format, sizeof(format)))
2456                 return -EFAULT;
2457
2458         return 0;
2459 }
2460
2461
2462 static int
2463 sn9c102_vidioc_try_s_fmt(struct sn9c102_device* cam, unsigned int cmd,
2464                          void __user * arg)
2465 {
2466         struct sn9c102_sensor* s = &cam->sensor;
2467         struct v4l2_format format;
2468         struct v4l2_pix_format* pix;
2469         struct v4l2_pix_format* pfmt = &(s->pix_format);
2470         struct v4l2_rect* bounds = &(s->cropcap.bounds);
2471         struct v4l2_rect rect;
2472         u8 scale;
2473         const enum sn9c102_stream_state stream = cam->stream;
2474         const u32 nbuffers = cam->nbuffers;
2475         u32 i;
2476         int err = 0;
2477
2478         if (copy_from_user(&format, arg, sizeof(format)))
2479                 return -EFAULT;
2480
2481         pix = &(format.fmt.pix);
2482
2483         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2484                 return -EINVAL;
2485
2486         memcpy(&rect, &(s->_rect), sizeof(rect));
2487
2488         { /* calculate the actual scaling factor */
2489                 u32 a, b;
2490                 a = rect.width * rect.height;
2491                 b = pix->width * pix->height;
2492                 scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2493         }
2494
2495         rect.width = scale * pix->width;
2496         rect.height = scale * pix->height;
2497
2498         if (rect.width < 16)
2499                 rect.width = 16;
2500         if (rect.height < 16)
2501                 rect.height = 16;
2502         if (rect.width > bounds->left + bounds->width - rect.left)
2503                 rect.width = bounds->left + bounds->width - rect.left;
2504         if (rect.height > bounds->top + bounds->height - rect.top)
2505                 rect.height = bounds->top + bounds->height - rect.top;
2506
2507         rect.width &= ~15L;
2508         rect.height &= ~15L;
2509
2510         { /* adjust the scaling factor */
2511                 u32 a, b;
2512                 a = rect.width * rect.height;
2513                 b = pix->width * pix->height;
2514                 scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2515         }
2516
2517         pix->width = rect.width / scale;
2518         pix->height = rect.height / scale;
2519
2520         switch (cam->bridge) {
2521         case BRIDGE_SN9C101:
2522         case BRIDGE_SN9C102:
2523         case BRIDGE_SN9C103:
2524         if (pix->pixelformat != V4L2_PIX_FMT_SN9C10X &&
2525             pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
2526                 pix->pixelformat = pfmt->pixelformat;
2527                 break;
2528         case BRIDGE_SN9C105:
2529         case BRIDGE_SN9C120:
2530                 if (pix->pixelformat != V4L2_PIX_FMT_JPEG &&
2531                     pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
2532                         pix->pixelformat = pfmt->pixelformat;
2533                 break;
2534         }
2535         pix->priv = pfmt->priv; /* bpp */
2536         pix->colorspace = pfmt->colorspace;
2537         pix->bytesperline = (pix->pixelformat == V4L2_PIX_FMT_SN9C10X ||
2538                              pix->pixelformat == V4L2_PIX_FMT_JPEG)
2539                             ? 0 : (pix->width * pix->priv) / 8;
2540         pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
2541         pix->field = V4L2_FIELD_NONE;
2542
2543         if (cmd == VIDIOC_TRY_FMT) {
2544                 if (copy_to_user(arg, &format, sizeof(format)))
2545                         return -EFAULT;
2546                 return 0;
2547         }
2548
2549         if (cam->module_param.force_munmap)
2550                 for (i = 0; i < cam->nbuffers; i++)
2551                         if (cam->frame[i].vma_use_count) {
2552                                 DBG(3, "VIDIOC_S_FMT failed. Unmap the "
2553                                        "buffers first.");
2554                                 return -EINVAL;
2555                         }
2556
2557         if (cam->stream == STREAM_ON)
2558                 if ((err = sn9c102_stream_interrupt(cam)))
2559                         return err;
2560
2561         if (copy_to_user(arg, &format, sizeof(format))) {
2562                 cam->stream = stream;
2563                 return -EFAULT;
2564         }
2565
2566         if (cam->module_param.force_munmap  || cam->io == IO_READ)
2567                 sn9c102_release_buffers(cam);
2568
2569         err += sn9c102_set_pix_format(cam, pix);
2570         err += sn9c102_set_crop(cam, &rect);
2571         if (s->set_pix_format)
2572                 err += s->set_pix_format(cam, pix);
2573         if (s->set_crop)
2574                 err += s->set_crop(cam, &rect);
2575         err += sn9c102_set_scale(cam, scale);
2576
2577         if (err) { /* atomic, no rollback in ioctl() */
2578                 cam->state |= DEV_MISCONFIGURED;
2579                 DBG(1, "VIDIOC_S_FMT failed because of hardware problems. To "
2580                        "use the camera, close and open /dev/video%d again.",
2581                     cam->v4ldev->minor);
2582                 return -EIO;
2583         }
2584
2585         memcpy(pfmt, pix, sizeof(*pix));
2586         memcpy(&(s->_rect), &rect, sizeof(rect));
2587
2588         if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
2589             nbuffers != sn9c102_request_buffers(cam, nbuffers, cam->io)) {
2590                 cam->state |= DEV_MISCONFIGURED;
2591                 DBG(1, "VIDIOC_S_FMT failed because of not enough memory. To "
2592                        "use the camera, close and open /dev/video%d again.",
2593                     cam->v4ldev->minor);
2594                 return -ENOMEM;
2595         }
2596
2597         if (cam->io == IO_READ)
2598                 sn9c102_empty_framequeues(cam);
2599         else if (cam->module_param.force_munmap)
2600                 sn9c102_requeue_outqueue(cam);
2601
2602         cam->stream = stream;
2603
2604         return 0;
2605 }
2606
2607
2608 static int
2609 sn9c102_vidioc_g_jpegcomp(struct sn9c102_device* cam, void __user * arg)
2610 {
2611         if (copy_to_user(arg, &cam->compression, sizeof(cam->compression)))
2612                 return -EFAULT;
2613
2614         return 0;
2615 }
2616
2617
2618 static int
2619 sn9c102_vidioc_s_jpegcomp(struct sn9c102_device* cam, void __user * arg)
2620 {
2621         struct v4l2_jpegcompression jc;
2622         const enum sn9c102_stream_state stream = cam->stream;
2623         int err = 0;
2624
2625         if (copy_from_user(&jc, arg, sizeof(jc)))
2626                 return -EFAULT;
2627
2628         if (jc.quality != 0 && jc.quality != 1)
2629                 return -EINVAL;
2630
2631         if (cam->stream == STREAM_ON)
2632                 if ((err = sn9c102_stream_interrupt(cam)))
2633                         return err;
2634
2635         err += sn9c102_set_compression(cam, &jc);
2636         if (err) { /* atomic, no rollback in ioctl() */
2637                 cam->state |= DEV_MISCONFIGURED;
2638                 DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware "
2639                        "problems. To use the camera, close and open "
2640                        "/dev/video%d again.", cam->v4ldev->minor);
2641                 return -EIO;
2642         }
2643
2644         cam->compression.quality = jc.quality;
2645
2646         cam->stream = stream;
2647
2648         return 0;
2649 }
2650
2651
2652 static int
2653 sn9c102_vidioc_reqbufs(struct sn9c102_device* cam, void __user * arg)
2654 {
2655         struct v4l2_requestbuffers rb;
2656         u32 i;
2657         int err;
2658
2659         if (copy_from_user(&rb, arg, sizeof(rb)))
2660                 return -EFAULT;
2661
2662         if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2663             rb.memory != V4L2_MEMORY_MMAP)
2664                 return -EINVAL;
2665
2666         if (cam->io == IO_READ) {
2667                 DBG(3, "Close and open the device again to choose the mmap "
2668                        "I/O method");
2669                 return -EINVAL;
2670         }
2671
2672         for (i = 0; i < cam->nbuffers; i++)
2673                 if (cam->frame[i].vma_use_count) {
2674                         DBG(3, "VIDIOC_REQBUFS failed. Previous buffers are "
2675                                "still mapped.");
2676                         return -EINVAL;
2677                 }
2678
2679         if (cam->stream == STREAM_ON)
2680                 if ((err = sn9c102_stream_interrupt(cam)))
2681                         return err;
2682
2683         sn9c102_empty_framequeues(cam);
2684
2685         sn9c102_release_buffers(cam);
2686         if (rb.count)
2687                 rb.count = sn9c102_request_buffers(cam, rb.count, IO_MMAP);
2688
2689         if (copy_to_user(arg, &rb, sizeof(rb))) {
2690                 sn9c102_release_buffers(cam);
2691                 cam->io = IO_NONE;
2692                 return -EFAULT;
2693         }
2694
2695         cam->io = rb.count ? IO_MMAP : IO_NONE;
2696
2697         return 0;
2698 }
2699
2700
2701 static int
2702 sn9c102_vidioc_querybuf(struct sn9c102_device* cam, void __user * arg)
2703 {
2704         struct v4l2_buffer b;
2705
2706         if (copy_from_user(&b, arg, sizeof(b)))
2707                 return -EFAULT;
2708
2709         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2710             b.index >= cam->nbuffers || cam->io != IO_MMAP)
2711                 return -EINVAL;
2712
2713         memcpy(&b, &cam->frame[b.index].buf, sizeof(b));
2714
2715         if (cam->frame[b.index].vma_use_count)
2716                 b.flags |= V4L2_BUF_FLAG_MAPPED;
2717
2718         if (cam->frame[b.index].state == F_DONE)
2719                 b.flags |= V4L2_BUF_FLAG_DONE;
2720         else if (cam->frame[b.index].state != F_UNUSED)
2721                 b.flags |= V4L2_BUF_FLAG_QUEUED;
2722
2723         if (copy_to_user(arg, &b, sizeof(b)))
2724                 return -EFAULT;
2725
2726         return 0;
2727 }
2728
2729
2730 static int
2731 sn9c102_vidioc_qbuf(struct sn9c102_device* cam, void __user * arg)
2732 {
2733         struct v4l2_buffer b;
2734         unsigned long lock_flags;
2735
2736         if (copy_from_user(&b, arg, sizeof(b)))
2737                 return -EFAULT;
2738
2739         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2740             b.index >= cam->nbuffers || cam->io != IO_MMAP)
2741                 return -EINVAL;
2742
2743         if (cam->frame[b.index].state != F_UNUSED)
2744                 return -EINVAL;
2745
2746         cam->frame[b.index].state = F_QUEUED;
2747
2748         spin_lock_irqsave(&cam->queue_lock, lock_flags);
2749         list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
2750         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2751
2752         PDBGG("Frame #%lu queued", (unsigned long)b.index);
2753
2754         return 0;
2755 }
2756
2757
2758 static int
2759 sn9c102_vidioc_dqbuf(struct sn9c102_device* cam, struct file* filp,
2760                      void __user * arg)
2761 {
2762         struct v4l2_buffer b;
2763         struct sn9c102_frame_t *f;
2764         unsigned long lock_flags;
2765         long timeout;
2766         int err = 0;
2767
2768         if (copy_from_user(&b, arg, sizeof(b)))
2769                 return -EFAULT;
2770
2771         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2772                 return -EINVAL;
2773
2774         if (list_empty(&cam->outqueue)) {
2775                 if (cam->stream == STREAM_OFF)
2776                         return -EINVAL;
2777                 if (filp->f_flags & O_NONBLOCK)
2778                         return -EAGAIN;
2779                 if (!cam->module_param.frame_timeout) {
2780                         err = wait_event_interruptible
2781                               ( cam->wait_frame,
2782                                 (!list_empty(&cam->outqueue)) ||
2783                                 (cam->state & DEV_DISCONNECTED) ||
2784                                 (cam->state & DEV_MISCONFIGURED) );
2785                         if (err)
2786                                 return err;
2787                 } else {
2788                 timeout = wait_event_interruptible_timeout
2789                           ( cam->wait_frame,
2790                             (!list_empty(&cam->outqueue)) ||
2791                             (cam->state & DEV_DISCONNECTED) ||
2792                             (cam->state & DEV_MISCONFIGURED),
2793                             cam->module_param.frame_timeout *
2794                             1000 * msecs_to_jiffies(1) );
2795                 if (timeout < 0)
2796                         return timeout;
2797                         else if (timeout == 0 &&
2798                                  !(cam->state & DEV_DISCONNECTED)) {
2799                                 DBG(1, "Video frame timeout elapsed");
2800                                 return -EIO;
2801                         }
2802                 }
2803                 if (cam->state & DEV_DISCONNECTED)
2804                         return -ENODEV;
2805                 if (cam->state & DEV_MISCONFIGURED)
2806                         return -EIO;
2807         }
2808
2809         spin_lock_irqsave(&cam->queue_lock, lock_flags);
2810         f = list_entry(cam->outqueue.next, struct sn9c102_frame_t, frame);
2811         list_del(cam->outqueue.next);
2812         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2813
2814         f->state = F_UNUSED;
2815
2816         memcpy(&b, &f->buf, sizeof(b));
2817         if (f->vma_use_count)
2818                 b.flags |= V4L2_BUF_FLAG_MAPPED;
2819
2820         if (copy_to_user(arg, &b, sizeof(b)))
2821                 return -EFAULT;
2822
2823         PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index);
2824
2825         return 0;
2826 }
2827
2828
2829 static int
2830 sn9c102_vidioc_streamon(struct sn9c102_device* cam, void __user * arg)
2831 {
2832         int type;
2833
2834         if (copy_from_user(&type, arg, sizeof(type)))
2835                 return -EFAULT;
2836
2837         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2838                 return -EINVAL;
2839
2840         if (list_empty(&cam->inqueue))
2841                 return -EINVAL;
2842
2843         cam->stream = STREAM_ON;
2844
2845         DBG(3, "Stream on");
2846
2847         return 0;
2848 }
2849
2850
2851 static int
2852 sn9c102_vidioc_streamoff(struct sn9c102_device* cam, void __user * arg)
2853 {
2854         int type, err;
2855
2856         if (copy_from_user(&type, arg, sizeof(type)))
2857                 return -EFAULT;
2858
2859         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2860                 return -EINVAL;
2861
2862         if (cam->stream == STREAM_ON)
2863                 if ((err = sn9c102_stream_interrupt(cam)))
2864                         return err;
2865
2866         sn9c102_empty_framequeues(cam);
2867
2868         DBG(3, "Stream off");
2869
2870         return 0;
2871 }
2872
2873
2874 static int
2875 sn9c102_vidioc_g_parm(struct sn9c102_device* cam, void __user * arg)
2876 {
2877         struct v4l2_streamparm sp;
2878
2879         if (copy_from_user(&sp, arg, sizeof(sp)))
2880                 return -EFAULT;
2881
2882         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2883                 return -EINVAL;
2884
2885         sp.parm.capture.extendedmode = 0;
2886         sp.parm.capture.readbuffers = cam->nreadbuffers;
2887
2888         if (copy_to_user(arg, &sp, sizeof(sp)))
2889                 return -EFAULT;
2890
2891         return 0;
2892 }
2893
2894
2895 static int
2896 sn9c102_vidioc_s_parm(struct sn9c102_device* cam, void __user * arg)
2897 {
2898         struct v4l2_streamparm sp;
2899
2900         if (copy_from_user(&sp, arg, sizeof(sp)))
2901                 return -EFAULT;
2902
2903         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2904                 return -EINVAL;
2905
2906         sp.parm.capture.extendedmode = 0;
2907
2908         if (sp.parm.capture.readbuffers == 0)
2909                 sp.parm.capture.readbuffers = cam->nreadbuffers;
2910
2911         if (sp.parm.capture.readbuffers > SN9C102_MAX_FRAMES)
2912                 sp.parm.capture.readbuffers = SN9C102_MAX_FRAMES;
2913
2914         if (copy_to_user(arg, &sp, sizeof(sp)))
2915                 return -EFAULT;
2916
2917         cam->nreadbuffers = sp.parm.capture.readbuffers;
2918
2919         return 0;
2920 }
2921
2922
2923 static int
2924 sn9c102_vidioc_enumaudio(struct sn9c102_device* cam, void __user * arg)
2925 {
2926         struct v4l2_audio audio;
2927
2928         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
2929                 return -EINVAL;
2930
2931         if (copy_from_user(&audio, arg, sizeof(audio)))
2932                 return -EFAULT;
2933
2934         if (audio.index != 0)
2935                 return -EINVAL;
2936
2937         strcpy(audio.name, "Microphone");
2938         audio.capability = 0;
2939         audio.mode = 0;
2940
2941         if (copy_to_user(arg, &audio, sizeof(audio)))
2942                 return -EFAULT;
2943
2944         return 0;
2945 }
2946
2947
2948 static int
2949 sn9c102_vidioc_g_audio(struct sn9c102_device* cam, void __user * arg)
2950 {
2951         struct v4l2_audio audio;
2952
2953         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
2954                 return -EINVAL;
2955
2956         if (copy_from_user(&audio, arg, sizeof(audio)))
2957                 return -EFAULT;
2958
2959         memset(&audio, 0, sizeof(audio));
2960         strcpy(audio.name, "Microphone");
2961
2962         if (copy_to_user(arg, &audio, sizeof(audio)))
2963                 return -EFAULT;
2964
2965         return 0;
2966 }
2967
2968
2969 static int
2970 sn9c102_vidioc_s_audio(struct sn9c102_device* cam, void __user * arg)
2971 {
2972         struct v4l2_audio audio;
2973
2974         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
2975                 return -EINVAL;
2976
2977         if (copy_from_user(&audio, arg, sizeof(audio)))
2978                 return -EFAULT;
2979
2980         if (audio.index != 0)
2981                 return -EINVAL;
2982
2983         return 0;
2984 }
2985
2986
2987 static int sn9c102_ioctl_v4l2(struct inode* inode, struct file* filp,
2988                               unsigned int cmd, void __user * arg)
2989 {
2990         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
2991
2992         switch (cmd) {
2993
2994         case VIDIOC_QUERYCAP:
2995                 return sn9c102_vidioc_querycap(cam, arg);
2996
2997         case VIDIOC_ENUMINPUT:
2998                 return sn9c102_vidioc_enuminput(cam, arg);
2999
3000         case VIDIOC_G_INPUT:
3001                 return sn9c102_vidioc_g_input(cam, arg);
3002
3003         case VIDIOC_S_INPUT:
3004                 return sn9c102_vidioc_s_input(cam, arg);
3005
3006         case VIDIOC_QUERYCTRL:
3007                 return sn9c102_vidioc_query_ctrl(cam, arg);
3008
3009         case VIDIOC_G_CTRL:
3010                 return sn9c102_vidioc_g_ctrl(cam, arg);
3011
3012         case VIDIOC_S_CTRL:
3013                 return sn9c102_vidioc_s_ctrl(cam, arg);
3014
3015         case VIDIOC_CROPCAP:
3016                 return sn9c102_vidioc_cropcap(cam, arg);
3017
3018         case VIDIOC_G_CROP:
3019                 return sn9c102_vidioc_g_crop(cam, arg);
3020
3021         case VIDIOC_S_CROP:
3022                 return sn9c102_vidioc_s_crop(cam, arg);
3023
3024         case VIDIOC_ENUM_FRAMESIZES:
3025                 return sn9c102_vidioc_enum_framesizes(cam, arg);
3026
3027         case VIDIOC_ENUM_FMT:
3028                 return sn9c102_vidioc_enum_fmt(cam, arg);
3029
3030         case VIDIOC_G_FMT:
3031                 return sn9c102_vidioc_g_fmt(cam, arg);
3032
3033         case VIDIOC_TRY_FMT:
3034         case VIDIOC_S_FMT:
3035                 return sn9c102_vidioc_try_s_fmt(cam, cmd, arg);
3036
3037         case VIDIOC_G_JPEGCOMP:
3038                 return sn9c102_vidioc_g_jpegcomp(cam, arg);
3039
3040         case VIDIOC_S_JPEGCOMP:
3041                 return sn9c102_vidioc_s_jpegcomp(cam, arg);
3042
3043         case VIDIOC_REQBUFS:
3044                 return sn9c102_vidioc_reqbufs(cam, arg);
3045
3046         case VIDIOC_QUERYBUF:
3047                 return sn9c102_vidioc_querybuf(cam, arg);
3048
3049         case VIDIOC_QBUF:
3050                 return sn9c102_vidioc_qbuf(cam, arg);
3051
3052         case VIDIOC_DQBUF:
3053                 return sn9c102_vidioc_dqbuf(cam, filp, arg);
3054
3055         case VIDIOC_STREAMON:
3056                 return sn9c102_vidioc_streamon(cam, arg);
3057
3058         case VIDIOC_STREAMOFF:
3059                 return sn9c102_vidioc_streamoff(cam, arg);
3060
3061         case VIDIOC_G_PARM:
3062                 return sn9c102_vidioc_g_parm(cam, arg);
3063
3064         case VIDIOC_S_PARM:
3065                 return sn9c102_vidioc_s_parm(cam, arg);
3066
3067         case VIDIOC_ENUMAUDIO:
3068                 return sn9c102_vidioc_enumaudio(cam, arg);
3069
3070         case VIDIOC_G_AUDIO:
3071                 return sn9c102_vidioc_g_audio(cam, arg);
3072
3073         case VIDIOC_S_AUDIO:
3074                 return sn9c102_vidioc_s_audio(cam, arg);
3075
3076         case VIDIOC_G_STD:
3077         case VIDIOC_S_STD:
3078         case VIDIOC_QUERYSTD:
3079         case VIDIOC_ENUMSTD:
3080         case VIDIOC_QUERYMENU:
3081         case VIDIOC_ENUM_FRAMEINTERVALS:
3082                 return -EINVAL;
3083
3084         default:
3085                 return -EINVAL;
3086
3087         }
3088 }
3089
3090
3091 static int sn9c102_ioctl(struct inode* inode, struct file* filp,
3092                          unsigned int cmd, unsigned long arg)
3093 {
3094         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
3095         int err = 0;
3096
3097         if (mutex_lock_interruptible(&cam->fileop_mutex))
3098                 return -ERESTARTSYS;
3099
3100         if (cam->state & DEV_DISCONNECTED) {
3101                 DBG(1, "Device not present");
3102                 mutex_unlock(&cam->fileop_mutex);
3103                 return -ENODEV;
3104         }
3105
3106         if (cam->state & DEV_MISCONFIGURED) {
3107                 DBG(1, "The camera is misconfigured. Close and open it "
3108                        "again.");
3109                 mutex_unlock(&cam->fileop_mutex);
3110                 return -EIO;
3111         }
3112
3113         V4LDBG(3, "sn9c102", cmd);
3114
3115         err = sn9c102_ioctl_v4l2(inode, filp, cmd, (void __user *)arg);
3116
3117         mutex_unlock(&cam->fileop_mutex);
3118
3119         return err;
3120 }
3121
3122 /*****************************************************************************/
3123
3124 static const struct file_operations sn9c102_fops = {
3125         .owner = THIS_MODULE,
3126         .open =    sn9c102_open,
3127         .release = sn9c102_release,
3128         .ioctl =   sn9c102_ioctl,
3129         .compat_ioctl = v4l_compat_ioctl32,
3130         .read =    sn9c102_read,
3131         .poll =    sn9c102_poll,
3132         .mmap =    sn9c102_mmap,
3133         .llseek =  no_llseek,
3134 };
3135
3136 /*****************************************************************************/
3137
3138 /* It exists a single interface only. We do not need to validate anything. */
3139 static int
3140 sn9c102_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
3141 {
3142         struct usb_device *udev = interface_to_usbdev(intf);
3143         struct sn9c102_device* cam;
3144         static unsigned int dev_nr = 0;
3145         unsigned int i;
3146         int err = 0, r;
3147
3148         if (!(cam = kzalloc(sizeof(struct sn9c102_device), GFP_KERNEL)))
3149                 return -ENOMEM;
3150
3151         cam->usbdev = udev;
3152
3153         if (!(cam->control_buffer = kzalloc(8, GFP_KERNEL))) {
3154                 DBG(1, "kzalloc() failed");
3155                 err = -ENOMEM;
3156                 goto fail;
3157         }
3158
3159         if (!(cam->v4ldev = video_device_alloc())) {
3160                 DBG(1, "video_device_alloc() failed");
3161                 err = -ENOMEM;
3162                 goto fail;
3163         }
3164
3165         mutex_init(&cam->dev_mutex);
3166
3167         r = sn9c102_read_reg(cam, 0x00);
3168         if (r < 0 || (r != 0x10 && r != 0x11 && r != 0x12)) {
3169                 DBG(1, "Sorry, this is not a SN9C1xx based camera "
3170                        "(vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3171                 err = -ENODEV;
3172                 goto fail;
3173         }
3174
3175         cam->bridge = id->driver_info;
3176         switch (cam->bridge) {
3177         case BRIDGE_SN9C101:
3178         case BRIDGE_SN9C102:
3179                 DBG(2, "SN9C10[12] PC Camera Controller detected "
3180                        "(vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3181                 break;
3182         case BRIDGE_SN9C103:
3183                 DBG(2, "SN9C103 PC Camera Controller detected "
3184                        "(vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3185                 break;
3186         case BRIDGE_SN9C105:
3187                 DBG(2, "SN9C105 PC Camera Controller detected "
3188                        "(vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3189                 break;
3190         case BRIDGE_SN9C120:
3191                 DBG(2, "SN9C120 PC Camera Controller detected "
3192                        "(vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3193                 break;
3194         }
3195
3196         for  (i = 0; sn9c102_sensor_table[i]; i++) {
3197                 err = sn9c102_sensor_table[i](cam);
3198                 if (!err)
3199                         break;
3200         }
3201
3202         if (!err) {
3203                 DBG(2, "%s image sensor detected", cam->sensor.name);
3204                 DBG(3, "Support for %s maintained by %s",
3205                     cam->sensor.name, cam->sensor.maintainer);
3206         } else {
3207                 DBG(1, "No supported image sensor detected");
3208                 err = -ENODEV;
3209                 goto fail;
3210         }
3211
3212         if (!(cam->bridge & cam->sensor.supported_bridge)) {
3213                 DBG(1, "Bridge not supported");
3214                 err = -ENODEV;
3215                 goto fail;
3216         }
3217
3218         if (sn9c102_init(cam)) {
3219                 DBG(1, "Initialization failed. I will retry on open().");
3220                 cam->state |= DEV_MISCONFIGURED;
3221         }
3222
3223         strcpy(cam->v4ldev->name, "SN9C1xx PC Camera");
3224         cam->v4ldev->owner = THIS_MODULE;
3225         cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
3226         cam->v4ldev->hardware = 0;
3227         cam->v4ldev->fops = &sn9c102_fops;
3228         cam->v4ldev->minor = video_nr[dev_nr];
3229         cam->v4ldev->release = video_device_release;
3230         video_set_drvdata(cam->v4ldev, cam);
3231
3232         mutex_lock(&cam->dev_mutex);
3233
3234         err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
3235                                     video_nr[dev_nr]);
3236         if (err) {
3237                 DBG(1, "V4L2 device registration failed");
3238                 if (err == -ENFILE && video_nr[dev_nr] == -1)
3239                         DBG(1, "Free /dev/videoX node not found");
3240                 video_nr[dev_nr] = -1;
3241                 dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
3242                 mutex_unlock(&cam->dev_mutex);
3243                 goto fail;
3244         }
3245
3246         DBG(2, "V4L2 device registered as /dev/video%d", cam->v4ldev->minor);
3247
3248         cam->module_param.force_munmap = force_munmap[dev_nr];
3249         cam->module_param.frame_timeout = frame_timeout[dev_nr];
3250
3251         dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
3252
3253 #ifdef CONFIG_VIDEO_ADV_DEBUG
3254         err = sn9c102_create_sysfs(cam);
3255         if (!err)
3256                 DBG(2, "Optional device control through 'sysfs' "
3257                        "interface ready");
3258         else
3259                 DBG(2, "Failed to create optional 'sysfs' interface for "
3260                        "device controlling. Error #%d", err);
3261 #else
3262         DBG(2, "Optional device control through 'sysfs' interface disabled");
3263 #endif
3264
3265         usb_set_intfdata(intf, cam);
3266
3267         mutex_unlock(&cam->dev_mutex);
3268
3269         return 0;
3270
3271 fail:
3272         if (cam) {
3273                 kfree(cam->control_buffer);
3274                 if (cam->v4ldev)
3275                         video_device_release(cam->v4ldev);
3276                 kfree(cam);
3277         }
3278         return err;
3279 }
3280
3281
3282 static void sn9c102_usb_disconnect(struct usb_interface* intf)
3283 {
3284         struct sn9c102_device* cam = usb_get_intfdata(intf);
3285
3286         if (!cam)
3287                 return;
3288
3289         down_write(&sn9c102_disconnect);
3290
3291         mutex_lock(&cam->dev_mutex);
3292
3293         DBG(2, "Disconnecting %s...", cam->v4ldev->name);
3294
3295         wake_up_interruptible_all(&cam->open);
3296
3297         if (cam->users) {
3298                 DBG(2, "Device /dev/video%d is open! Deregistration and "
3299                        "memory deallocation are deferred on close.",
3300                     cam->v4ldev->minor);
3301                 cam->state |= DEV_MISCONFIGURED;
3302                 sn9c102_stop_transfer(cam);
3303                 cam->state |= DEV_DISCONNECTED;
3304                 wake_up_interruptible(&cam->wait_frame);
3305                 wake_up(&cam->wait_stream);
3306                 usb_get_dev(cam->usbdev);
3307         } else {
3308                 cam->state |= DEV_DISCONNECTED;
3309                 sn9c102_release_resources(cam);
3310         }
3311
3312         mutex_unlock(&cam->dev_mutex);
3313
3314         if (!cam->users)
3315                 kfree(cam);
3316
3317         up_write(&sn9c102_disconnect);
3318 }
3319
3320
3321 static struct usb_driver sn9c102_usb_driver = {
3322         .name =       "sn9c102",
3323         .id_table =   sn9c102_id_table,
3324         .probe =      sn9c102_usb_probe,
3325         .disconnect = sn9c102_usb_disconnect,
3326 };
3327
3328 /*****************************************************************************/
3329
3330 static int __init sn9c102_module_init(void)
3331 {
3332         int err = 0;
3333
3334         KDBG(2, SN9C102_MODULE_NAME " v" SN9C102_MODULE_VERSION);
3335         KDBG(3, SN9C102_MODULE_AUTHOR);
3336
3337         if ((err = usb_register(&sn9c102_usb_driver)))
3338                 KDBG(1, "usb_register() failed");
3339
3340         return err;
3341 }
3342
3343
3344 static void __exit sn9c102_module_exit(void)
3345 {
3346         usb_deregister(&sn9c102_usb_driver);
3347 }
3348
3349
3350 module_init(sn9c102_module_init);
3351 module_exit(sn9c102_module_exit);