Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-2.6
[linux-2.6] / drivers / usb / media / sn9c102_core.c
1 /***************************************************************************
2  * V4L2 driver for SN9C10x PC Camera Controllers                           *
3  *                                                                         *
4  * Copyright (C) 2004-2005 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/string.h>
29 #include <linux/device.h>
30 #include <linux/fs.h>
31 #include <linux/delay.h>
32 #include <linux/stddef.h>
33 #include <linux/compiler.h>
34 #include <linux/ioctl.h>
35 #include <linux/poll.h>
36 #include <linux/stat.h>
37 #include <linux/mm.h>
38 #include <linux/vmalloc.h>
39 #include <linux/page-flags.h>
40 #include <linux/byteorder/generic.h>
41 #include <asm/page.h>
42 #include <asm/uaccess.h>
43
44 #include "sn9c102.h"
45
46 /*****************************************************************************/
47
48 MODULE_DEVICE_TABLE(usb, sn9c102_id_table);
49
50 MODULE_AUTHOR(SN9C102_MODULE_AUTHOR " " SN9C102_AUTHOR_EMAIL);
51 MODULE_DESCRIPTION(SN9C102_MODULE_NAME);
52 MODULE_VERSION(SN9C102_MODULE_VERSION);
53 MODULE_LICENSE(SN9C102_MODULE_LICENSE);
54
55 static short video_nr[] = {[0 ... SN9C102_MAX_DEVICES-1] = -1};
56 module_param_array(video_nr, short, NULL, 0444);
57 MODULE_PARM_DESC(video_nr,
58                  "\n<-1|n[,...]> Specify V4L2 minor mode number."
59                  "\n -1 = use next available (default)"
60                  "\n  n = use minor number n (integer >= 0)"
61                  "\nYou can specify up to "__MODULE_STRING(SN9C102_MAX_DEVICES)
62                  " cameras this way."
63                  "\nFor example:"
64                  "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
65                  "\nthe second camera and use auto for the first"
66                  "\none and for every other camera."
67                  "\n");
68
69 static short force_munmap[] = {[0 ... SN9C102_MAX_DEVICES-1] = 
70                                SN9C102_FORCE_MUNMAP};
71 module_param_array(force_munmap, bool, NULL, 0444);
72 MODULE_PARM_DESC(force_munmap,
73                  "\n<0|1[,...]> Force the application to unmap previously "
74                  "\nmapped buffer memory before calling any VIDIOC_S_CROP or "
75                  "\nVIDIOC_S_FMT ioctl's. Not all the applications support "
76                  "\nthis feature. This parameter is specific for each "
77                  "\ndetected camera."
78                  "\n 0 = do not force memory unmapping"
79                  "\n 1 = force memory unmapping (save memory)"
80                  "\nDefault value is "__MODULE_STRING(SN9C102_FORCE_MUNMAP)"."
81                  "\n");
82
83 #ifdef SN9C102_DEBUG
84 static unsigned short debug = SN9C102_DEBUG_LEVEL;
85 module_param(debug, ushort, 0644);
86 MODULE_PARM_DESC(debug,
87                  "\n<n> Debugging information level, from 0 to 3:"
88                  "\n0 = none (use carefully)"
89                  "\n1 = critical errors"
90                  "\n2 = significant informations"
91                  "\n3 = more verbose messages"
92                  "\nLevel 3 is useful for testing only, when only "
93                  "one device is used."
94                  "\nDefault value is "__MODULE_STRING(SN9C102_DEBUG_LEVEL)"."
95                  "\n");
96 #endif
97
98 /*****************************************************************************/
99
100 static sn9c102_sof_header_t sn9c102_sof_header[] = {
101         {0xff, 0xff, 0x00, 0xc4, 0xc4, 0x96, 0x00},
102         {0xff, 0xff, 0x00, 0xc4, 0xc4, 0x96, 0x01},
103 };
104
105
106 static sn9c102_eof_header_t sn9c102_eof_header[] = {
107         {0x00, 0x00, 0x00, 0x00},
108         {0x40, 0x00, 0x00, 0x00},
109         {0x80, 0x00, 0x00, 0x00},
110         {0xc0, 0x00, 0x00, 0x00},
111 };
112
113 /*****************************************************************************/
114
115 static void* rvmalloc(size_t size)
116 {
117         void* mem;
118         unsigned long adr;
119
120         size = PAGE_ALIGN(size);
121
122         mem = vmalloc_32((unsigned long)size);
123         if (!mem)
124                 return NULL;
125
126         memset(mem, 0, size);
127
128         adr = (unsigned long)mem;
129         while (size > 0) {
130                 SetPageReserved(vmalloc_to_page((void *)adr));
131                 adr += PAGE_SIZE;
132                 size -= PAGE_SIZE;
133         }
134
135         return mem;
136 }
137
138
139 static void rvfree(void* mem, size_t size)
140 {
141         unsigned long adr;
142
143         if (!mem)
144                 return;
145
146         size = PAGE_ALIGN(size);
147
148         adr = (unsigned long)mem;
149         while (size > 0) {
150                 ClearPageReserved(vmalloc_to_page((void *)adr));
151                 adr += PAGE_SIZE;
152                 size -= PAGE_SIZE;
153         }
154
155         vfree(mem);
156 }
157
158
159 static u32 
160 sn9c102_request_buffers(struct sn9c102_device* cam, u32 count, 
161                         enum sn9c102_io_method io)
162 {
163         struct v4l2_pix_format* p = &(cam->sensor->pix_format);
164         struct v4l2_rect* r = &(cam->sensor->cropcap.bounds);
165         const size_t imagesize = cam->module_param.force_munmap ||
166                                  io == IO_READ ?
167                                  (p->width * p->height * p->priv) / 8 :
168                                  (r->width * r->height * p->priv) / 8;
169         void* buff = NULL;
170         u32 i;
171
172         if (count > SN9C102_MAX_FRAMES)
173                 count = SN9C102_MAX_FRAMES;
174
175         cam->nbuffers = count;
176         while (cam->nbuffers > 0) {
177                 if ((buff = rvmalloc(cam->nbuffers * PAGE_ALIGN(imagesize))))
178                         break;
179                 cam->nbuffers--;
180         }
181
182         for (i = 0; i < cam->nbuffers; i++) {
183                 cam->frame[i].bufmem = buff + i*PAGE_ALIGN(imagesize);
184                 cam->frame[i].buf.index = i;
185                 cam->frame[i].buf.m.offset = i*PAGE_ALIGN(imagesize);
186                 cam->frame[i].buf.length = imagesize;
187                 cam->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
188                 cam->frame[i].buf.sequence = 0;
189                 cam->frame[i].buf.field = V4L2_FIELD_NONE;
190                 cam->frame[i].buf.memory = V4L2_MEMORY_MMAP;
191                 cam->frame[i].buf.flags = 0;
192         }
193
194         return cam->nbuffers;
195 }
196
197
198 static void sn9c102_release_buffers(struct sn9c102_device* cam)
199 {
200         if (cam->nbuffers) {
201                 rvfree(cam->frame[0].bufmem,
202                        cam->nbuffers * PAGE_ALIGN(cam->frame[0].buf.length));
203                 cam->nbuffers = 0;
204         }
205 }
206
207
208 static void sn9c102_empty_framequeues(struct sn9c102_device* cam)
209 {
210         u32 i;
211
212         INIT_LIST_HEAD(&cam->inqueue);
213         INIT_LIST_HEAD(&cam->outqueue);
214
215         for (i = 0; i < SN9C102_MAX_FRAMES; i++) {
216                 cam->frame[i].state = F_UNUSED;
217                 cam->frame[i].buf.bytesused = 0;
218         }
219 }
220
221
222 static void sn9c102_queue_unusedframes(struct sn9c102_device* cam)
223 {
224         unsigned long lock_flags;
225         u32 i;
226
227         for (i = 0; i < cam->nbuffers; i++)
228                 if (cam->frame[i].state == F_UNUSED) {
229                         cam->frame[i].state = F_QUEUED;
230                         spin_lock_irqsave(&cam->queue_lock, lock_flags);
231                         list_add_tail(&cam->frame[i].frame, &cam->inqueue);
232                         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
233                 }
234 }
235
236 /*****************************************************************************/
237
238 int sn9c102_write_reg(struct sn9c102_device* cam, u8 value, u16 index)
239 {
240         struct usb_device* udev = cam->usbdev;
241         u8* buff = cam->control_buffer;
242         int res;
243
244         *buff = value;
245
246         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
247                               index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
248         if (res < 0) {
249                 DBG(3, "Failed to write a register (value 0x%02X, index "
250                        "0x%02X, error %d)", value, index, res)
251                 return -1;
252         }
253
254         cam->reg[index] = value;
255
256         return 0;
257 }
258
259
260 /* NOTE: reading some registers always returns 0 */
261 static int sn9c102_read_reg(struct sn9c102_device* cam, u16 index)
262 {
263         struct usb_device* udev = cam->usbdev;
264         u8* buff = cam->control_buffer;
265         int res;
266
267         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
268                               index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
269         if (res < 0)
270                 DBG(3, "Failed to read a register (index 0x%02X, error %d)",
271                     index, res)
272
273         return (res >= 0) ? (int)(*buff) : -1;
274 }
275
276
277 int sn9c102_pread_reg(struct sn9c102_device* cam, u16 index)
278 {
279         if (index > 0x1f)
280                 return -EINVAL;
281
282         return cam->reg[index];
283 }
284
285
286 static int
287 sn9c102_i2c_wait(struct sn9c102_device* cam, struct sn9c102_sensor* sensor)
288 {
289         int i, r;
290
291         for (i = 1; i <= 5; i++) {
292                 r = sn9c102_read_reg(cam, 0x08);
293                 if (r < 0)
294                         return -EIO;
295                 if (r & 0x04)
296                         return 0;
297                 if (sensor->frequency & SN9C102_I2C_400KHZ)
298                         udelay(5*16);
299                 else
300                         udelay(16*16);
301         }
302         return -EBUSY;
303 }
304
305
306 static int
307 sn9c102_i2c_detect_read_error(struct sn9c102_device* cam, 
308                               struct sn9c102_sensor* sensor)
309 {
310         int r;
311         r = sn9c102_read_reg(cam, 0x08);
312         return (r < 0 || (r >= 0 && !(r & 0x08))) ? -EIO : 0;
313 }
314
315
316 static int
317 sn9c102_i2c_detect_write_error(struct sn9c102_device* cam, 
318                                struct sn9c102_sensor* sensor)
319 {
320         int r;
321         r = sn9c102_read_reg(cam, 0x08);
322         return (r < 0 || (r >= 0 && (r & 0x08))) ? -EIO : 0;
323 }
324
325
326 int 
327 sn9c102_i2c_try_raw_read(struct sn9c102_device* cam,
328                          struct sn9c102_sensor* sensor, u8 data0, u8 data1,
329                          u8 n, u8 buffer[])
330 {
331         struct usb_device* udev = cam->usbdev;
332         u8* data = cam->control_buffer;
333         int err = 0, res;
334
335         /* Write cycle */
336         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
337                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) | 0x10;
338         data[1] = data0; /* I2C slave id */
339         data[2] = data1; /* address */
340         data[7] = 0x10;
341         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
342                               0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
343         if (res < 0)
344                 err += res;
345
346         err += sn9c102_i2c_wait(cam, sensor);
347
348         /* Read cycle - n bytes */
349         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
350                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) |
351                   (n << 4) | 0x02;
352         data[1] = data0;
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         /* The first read byte will be placed in data[4] */
362         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
363                               0x0a, 0, data, 5, SN9C102_CTRL_TIMEOUT);
364         if (res < 0)
365                 err += res;
366
367         err += sn9c102_i2c_detect_read_error(cam, sensor);
368
369         PDBGG("I2C read: address 0x%02X, first read byte: 0x%02X", data1,
370               data[4])
371
372         if (err) {
373                 DBG(3, "I2C read failed for %s image sensor", sensor->name)
374                 return -1;
375         }
376
377         if (buffer)
378                 memcpy(buffer, data, sizeof(buffer));
379
380         return (int)data[4];
381 }
382
383
384 int 
385 sn9c102_i2c_try_raw_write(struct sn9c102_device* cam,
386                           struct sn9c102_sensor* sensor, u8 n, u8 data0,
387                           u8 data1, u8 data2, u8 data3, u8 data4, u8 data5)
388 {
389         struct usb_device* udev = cam->usbdev;
390         u8* data = cam->control_buffer;
391         int err = 0, res;
392
393         /* Write cycle. It usually is address + value */
394         data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
395                   ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0)
396                   | ((n - 1) << 4);
397         data[1] = data0;
398         data[2] = data1;
399         data[3] = data2;
400         data[4] = data3;
401         data[5] = data4;
402         data[6] = data5;
403         data[7] = 0x14;
404         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
405                               0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
406         if (res < 0)
407                 err += res;
408
409         err += sn9c102_i2c_wait(cam, sensor);
410         err += sn9c102_i2c_detect_write_error(cam, sensor);
411
412         if (err)
413                 DBG(3, "I2C write failed for %s image sensor", sensor->name)
414
415         PDBGG("I2C raw write: %u bytes, data0 = 0x%02X, data1 = 0x%02X, "
416               "data2 = 0x%02X, data3 = 0x%02X, data4 = 0x%02X, data5 = 0x%02X",
417               n, data0, data1, data2, data3, data4, data5)
418
419         return err ? -1 : 0;
420 }
421
422
423 int
424 sn9c102_i2c_try_read(struct sn9c102_device* cam,
425                      struct sn9c102_sensor* sensor, u8 address)
426 {
427         return sn9c102_i2c_try_raw_read(cam, sensor, sensor->i2c_slave_id,
428                                         address, 1, NULL);
429 }
430
431
432 int
433 sn9c102_i2c_try_write(struct sn9c102_device* cam,
434                       struct sn9c102_sensor* sensor, u8 address, u8 value)
435 {
436         return sn9c102_i2c_try_raw_write(cam, sensor, 3, 
437                                          sensor->i2c_slave_id, address,
438                                          value, 0, 0, 0);
439 }
440
441
442 int sn9c102_i2c_read(struct sn9c102_device* cam, u8 address)
443 {
444         if (!cam->sensor)
445                 return -1;
446
447         return sn9c102_i2c_try_read(cam, cam->sensor, address);
448 }
449
450
451 int sn9c102_i2c_write(struct sn9c102_device* cam, u8 address, u8 value)
452 {
453         if (!cam->sensor)
454                 return -1;
455
456         return sn9c102_i2c_try_write(cam, cam->sensor, address, value);
457 }
458
459 /*****************************************************************************/
460
461 static void*
462 sn9c102_find_sof_header(struct sn9c102_device* cam, void* mem, size_t len)
463 {
464         size_t soflen = sizeof(sn9c102_sof_header_t), i;
465         u8 j, n = sizeof(sn9c102_sof_header) / soflen;
466
467         for (i = 0; (len >= soflen) && (i <= len - soflen); i++)
468                 for (j = 0; j < n; j++)
469                         /* It's enough to compare 7 bytes */
470                         if (!memcmp(mem + i, sn9c102_sof_header[j], 7)) {
471                                 memcpy(cam->sof_header, mem + i, soflen);
472                                 /* Skip the header */
473                                 return mem + i + soflen;
474                         }
475
476         return NULL;
477 }
478
479
480 static void*
481 sn9c102_find_eof_header(struct sn9c102_device* cam, void* mem, size_t len)
482 {
483         size_t eoflen = sizeof(sn9c102_eof_header_t), i;
484         unsigned j, n = sizeof(sn9c102_eof_header) / eoflen;
485
486         if (cam->sensor->pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X)
487                 return NULL; /* EOF header does not exist in compressed data */
488
489         for (i = 0; (len >= eoflen) && (i <= len - eoflen); i++)
490                 for (j = 0; j < n; j++)
491                         if (!memcmp(mem + i, sn9c102_eof_header[j], eoflen))
492                                 return mem + i;
493
494         return NULL;
495 }
496
497
498 static void sn9c102_urb_complete(struct urb *urb, struct pt_regs* regs)
499 {
500         struct sn9c102_device* cam = urb->context;
501         struct sn9c102_frame_t** f;
502         size_t imagesize;
503         unsigned long lock_flags;
504         u8 i;
505         int err = 0;
506
507         if (urb->status == -ENOENT)
508                 return;
509
510         f = &cam->frame_current;
511
512         if (cam->stream == STREAM_INTERRUPT) {
513                 cam->stream = STREAM_OFF;
514                 if ((*f))
515                         (*f)->state = F_QUEUED;
516                 DBG(3, "Stream interrupted")
517                 wake_up_interruptible(&cam->wait_stream);
518         }
519
520         if (cam->state & DEV_DISCONNECTED)
521                 return;
522
523         if (cam->state & DEV_MISCONFIGURED) {
524                 wake_up_interruptible(&cam->wait_frame);
525                 return;
526         }
527
528         if (cam->stream == STREAM_OFF || list_empty(&cam->inqueue))
529                 goto resubmit_urb;
530
531         if (!(*f))
532                 (*f) = list_entry(cam->inqueue.next, struct sn9c102_frame_t,
533                                   frame);
534
535         imagesize = (cam->sensor->pix_format.width *
536                      cam->sensor->pix_format.height *
537                      cam->sensor->pix_format.priv) / 8;
538
539         for (i = 0; i < urb->number_of_packets; i++) {
540                 unsigned int img, len, status;
541                 void *pos, *sof, *eof;
542
543                 len = urb->iso_frame_desc[i].actual_length;
544                 status = urb->iso_frame_desc[i].status;
545                 pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;
546
547                 if (status) {
548                         DBG(3, "Error in isochronous frame")
549                         (*f)->state = F_ERROR;
550                         continue;
551                 }
552
553                 PDBGG("Isochrnous frame: length %u, #%u i", len, i)
554
555                 /*
556                    NOTE: It is probably correct to assume that SOF and EOF
557                          headers do not occur between two consecutive packets,
558                          but who knows..Whatever is the truth, this assumption
559                          doesn't introduce bugs.
560                 */
561
562 redo:
563                 sof = sn9c102_find_sof_header(cam, pos, len);
564                 if (!sof) {
565                         eof = sn9c102_find_eof_header(cam, pos, len);
566                         if ((*f)->state == F_GRABBING) {
567 end_of_frame:
568                                 img = len;
569
570                                 if (eof)
571                                         img = (eof > pos) ? eof - pos - 1 : 0;
572
573                                 if ((*f)->buf.bytesused+img > imagesize) {
574                                         u32 b = (*f)->buf.bytesused + img -
575                                                 imagesize;
576                                         img = imagesize - (*f)->buf.bytesused;
577                                         DBG(3, "Expected EOF not found: "
578                                                "video frame cut")
579                                         if (eof)
580                                                 DBG(3, "Exceeded limit: +%u "
581                                                        "bytes", (unsigned)(b))
582                                 }
583
584                                 memcpy((*f)->bufmem + (*f)->buf.bytesused, pos,
585                                        img);
586
587                                 if ((*f)->buf.bytesused == 0)
588                                         do_gettimeofday(&(*f)->buf.timestamp);
589
590                                 (*f)->buf.bytesused += img;
591
592                                 if ((*f)->buf.bytesused == imagesize ||
593                                     (cam->sensor->pix_format.pixelformat ==
594                                                 V4L2_PIX_FMT_SN9C10X && eof)) {
595                                         u32 b = (*f)->buf.bytesused;
596                                         (*f)->state = F_DONE;
597                                         (*f)->buf.sequence= ++cam->frame_count;
598                                         spin_lock_irqsave(&cam->queue_lock,
599                                                           lock_flags);
600                                         list_move_tail(&(*f)->frame,
601                                                        &cam->outqueue);
602                                         if (!list_empty(&cam->inqueue))
603                                                 (*f) = list_entry(
604                                                         cam->inqueue.next,
605                                                         struct sn9c102_frame_t,
606                                                         frame );
607                                         else
608                                                 (*f) = NULL;
609                                         spin_unlock_irqrestore(&cam->queue_lock
610                                                                , lock_flags);
611                                         memcpy(cam->sysfs.frame_header,
612                                                cam->sof_header,
613                                                sizeof(sn9c102_sof_header_t));
614                                         DBG(3, "Video frame captured: "
615                                                "%lu bytes", (unsigned long)(b))
616
617                                         if (!(*f))
618                                                 goto resubmit_urb;
619
620                                 } else if (eof) {
621                                         (*f)->state = F_ERROR;
622                                         DBG(3, "Not expected EOF after %lu "
623                                                "bytes of image data", 
624                                           (unsigned long)((*f)->buf.bytesused))
625                                 }
626
627                                 if (sof) /* (1) */
628                                         goto start_of_frame;
629
630                         } else if (eof) {
631                                 DBG(3, "EOF without SOF")
632                                 continue;
633
634                         } else {
635                                 PDBGG("Ignoring pointless isochronous frame")
636                                 continue;
637                         }
638
639                 } else if ((*f)->state == F_QUEUED || (*f)->state == F_ERROR) {
640 start_of_frame:
641                         (*f)->state = F_GRABBING;
642                         (*f)->buf.bytesused = 0;
643                         len -= (sof - pos);
644                         pos = sof;
645                         DBG(3, "SOF detected: new video frame")
646                         if (len)
647                                 goto redo;
648
649                 } else if ((*f)->state == F_GRABBING) {
650                         eof = sn9c102_find_eof_header(cam, pos, len);
651                         if (eof && eof < sof)
652                                 goto end_of_frame; /* (1) */
653                         else {
654                                 if (cam->sensor->pix_format.pixelformat ==
655                                     V4L2_PIX_FMT_SN9C10X) {
656                                         eof = sof-sizeof(sn9c102_sof_header_t);
657                                         goto end_of_frame;
658                                 } else {
659                                         DBG(3, "SOF before expected EOF after "
660                                                "%lu bytes of image data", 
661                                           (unsigned long)((*f)->buf.bytesused))
662                                         goto start_of_frame;
663                                 }
664                         }
665                 }
666         }
667
668 resubmit_urb:
669         urb->dev = cam->usbdev;
670         err = usb_submit_urb(urb, GFP_ATOMIC);
671         if (err < 0 && err != -EPERM) {
672                 cam->state |= DEV_MISCONFIGURED;
673                 DBG(1, "usb_submit_urb() failed")
674         }
675
676         wake_up_interruptible(&cam->wait_frame);
677 }
678
679
680 static int sn9c102_start_transfer(struct sn9c102_device* cam)
681 {
682         struct usb_device *udev = cam->usbdev;
683         struct urb* urb;
684         const unsigned int wMaxPacketSize[] = {0, 128, 256, 384, 512,
685                                                680, 800, 900, 1023};
686         const unsigned int psz = wMaxPacketSize[SN9C102_ALTERNATE_SETTING];
687         s8 i, j;
688         int err = 0;
689
690         for (i = 0; i < SN9C102_URBS; i++) {
691                 cam->transfer_buffer[i] = kmalloc(SN9C102_ISO_PACKETS * psz,
692                                                   GFP_KERNEL);
693                 if (!cam->transfer_buffer[i]) {
694                         err = -ENOMEM;
695                         DBG(1, "Not enough memory")
696                         goto free_buffers;
697                 }
698         }
699
700         for (i = 0; i < SN9C102_URBS; i++) {
701                 urb = usb_alloc_urb(SN9C102_ISO_PACKETS, GFP_KERNEL);
702                 cam->urb[i] = urb;
703                 if (!urb) {
704                         err = -ENOMEM;
705                         DBG(1, "usb_alloc_urb() failed")
706                         goto free_urbs;
707                 }
708                 urb->dev = udev;
709                 urb->context = cam;
710                 urb->pipe = usb_rcvisocpipe(udev, 1);
711                 urb->transfer_flags = URB_ISO_ASAP;
712                 urb->number_of_packets = SN9C102_ISO_PACKETS;
713                 urb->complete = sn9c102_urb_complete;
714                 urb->transfer_buffer = cam->transfer_buffer[i];
715                 urb->transfer_buffer_length = psz * SN9C102_ISO_PACKETS;
716                 urb->interval = 1;
717                 for (j = 0; j < SN9C102_ISO_PACKETS; j++) {
718                         urb->iso_frame_desc[j].offset = psz * j;
719                         urb->iso_frame_desc[j].length = psz;
720                 }
721         }
722
723         /* Enable video */
724         if (!(cam->reg[0x01] & 0x04)) {
725                 err = sn9c102_write_reg(cam, cam->reg[0x01] | 0x04, 0x01);
726                 if (err) {
727                         err = -EIO;
728                         DBG(1, "I/O hardware error")
729                         goto free_urbs;
730                 }
731         }
732
733         err = usb_set_interface(udev, 0, SN9C102_ALTERNATE_SETTING);
734         if (err) {
735                 DBG(1, "usb_set_interface() failed")
736                 goto free_urbs;
737         }
738
739         cam->frame_current = NULL;
740
741         for (i = 0; i < SN9C102_URBS; i++) {
742                 err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
743                 if (err) {
744                         for (j = i-1; j >= 0; j--)
745                                 usb_kill_urb(cam->urb[j]);
746                         DBG(1, "usb_submit_urb() failed, error %d", err)
747                         goto free_urbs;
748                 }
749         }
750
751         return 0;
752
753 free_urbs:
754         for (i = 0; (i < SN9C102_URBS) &&  cam->urb[i]; i++)
755                 usb_free_urb(cam->urb[i]);
756
757 free_buffers:
758         for (i = 0; (i < SN9C102_URBS) && cam->transfer_buffer[i]; i++)
759                 kfree(cam->transfer_buffer[i]);
760
761         return err;
762 }
763
764
765 static int sn9c102_stop_transfer(struct sn9c102_device* cam)
766 {
767         struct usb_device *udev = cam->usbdev;
768         s8 i;
769         int err = 0;
770
771         if (cam->state & DEV_DISCONNECTED)
772                 return 0;
773
774         for (i = SN9C102_URBS-1; i >= 0; i--) {
775                 usb_kill_urb(cam->urb[i]);
776                 usb_free_urb(cam->urb[i]);
777                 kfree(cam->transfer_buffer[i]);
778         }
779
780         err = usb_set_interface(udev, 0, 0); /* 0 Mb/s */
781         if (err)
782                 DBG(3, "usb_set_interface() failed")
783
784         return err;
785 }
786
787
788 static int sn9c102_stream_interrupt(struct sn9c102_device* cam)
789 {
790         int err = 0;
791
792         cam->stream = STREAM_INTERRUPT;
793         err = wait_event_timeout(cam->wait_stream,
794                                  (cam->stream == STREAM_OFF) ||
795                                  (cam->state & DEV_DISCONNECTED),
796                                  SN9C102_URB_TIMEOUT);
797         if (cam->state & DEV_DISCONNECTED)
798                 return -ENODEV;
799         else if (err) {
800                 cam->state |= DEV_MISCONFIGURED;
801                 DBG(1, "The camera is misconfigured. To use it, close and "
802                        "open /dev/video%d again.", cam->v4ldev->minor)
803                 return err;
804         }
805
806         return 0;
807 }
808
809 /*****************************************************************************/
810
811 static u8 sn9c102_strtou8(const char* buff, size_t len, ssize_t* count)
812 {
813         char str[5];
814         char* endp;
815         unsigned long val;
816
817         if (len < 4) {
818                 strncpy(str, buff, len);
819                 str[len+1] = '\0';
820         } else {
821                 strncpy(str, buff, 4);
822                 str[4] = '\0';
823         }
824
825         val = simple_strtoul(str, &endp, 0);
826
827         *count = 0;
828         if (val <= 0xff)
829                 *count = (ssize_t)(endp - str);
830         if ((*count) && (len == *count+1) && (buff[*count] == '\n'))
831                 *count += 1;
832
833         return (u8)val;
834 }
835
836 /*
837    NOTE 1: being inside one of the following methods implies that the v4l
838            device exists for sure (see kobjects and reference counters)
839    NOTE 2: buffers are PAGE_SIZE long
840 */
841
842 static ssize_t sn9c102_show_reg(struct class_device* cd, char* buf)
843 {
844         struct sn9c102_device* cam;
845         ssize_t count;
846
847         if (down_interruptible(&sn9c102_sysfs_lock))
848                 return -ERESTARTSYS;
849
850         cam = video_get_drvdata(to_video_device(cd));
851         if (!cam) {
852                 up(&sn9c102_sysfs_lock);
853                 return -ENODEV;
854         }
855
856         count = sprintf(buf, "%u\n", cam->sysfs.reg);
857
858         up(&sn9c102_sysfs_lock);
859
860         return count;
861
862
863
864 static ssize_t 
865 sn9c102_store_reg(struct class_device* cd, const char* buf, size_t len)
866 {
867         struct sn9c102_device* cam;
868         u8 index;
869         ssize_t count;
870
871         if (down_interruptible(&sn9c102_sysfs_lock))
872                 return -ERESTARTSYS;
873
874         cam = video_get_drvdata(to_video_device(cd));
875         if (!cam) {
876                 up(&sn9c102_sysfs_lock);
877                 return -ENODEV;
878         }
879
880         index = sn9c102_strtou8(buf, len, &count);
881         if (index > 0x1f || !count) {
882                 up(&sn9c102_sysfs_lock);
883                 return -EINVAL;
884         }
885
886         cam->sysfs.reg = index;
887
888         DBG(2, "Moved SN9C10X register index to 0x%02X", cam->sysfs.reg)
889         DBG(3, "Written bytes: %zd", count)
890
891         up(&sn9c102_sysfs_lock);
892
893         return count;
894 }
895
896
897 static ssize_t sn9c102_show_val(struct class_device* cd, char* buf)
898 {
899         struct sn9c102_device* cam;
900         ssize_t count;
901         int val;
902
903         if (down_interruptible(&sn9c102_sysfs_lock))
904                 return -ERESTARTSYS;
905
906         cam = video_get_drvdata(to_video_device(cd));
907         if (!cam) {
908                 up(&sn9c102_sysfs_lock);
909                 return -ENODEV;
910         }
911
912         if ((val = sn9c102_read_reg(cam, cam->sysfs.reg)) < 0) {
913                 up(&sn9c102_sysfs_lock);
914                 return -EIO;
915         }
916
917         count = sprintf(buf, "%d\n", val);
918
919         DBG(3, "Read bytes: %zd", count)
920
921         up(&sn9c102_sysfs_lock);
922
923         return count;
924
925
926
927 static ssize_t
928 sn9c102_store_val(struct class_device* cd, const char* buf, size_t len)
929 {
930         struct sn9c102_device* cam;
931         u8 value;
932         ssize_t count;
933         int err;
934
935         if (down_interruptible(&sn9c102_sysfs_lock))
936                 return -ERESTARTSYS;
937
938         cam = video_get_drvdata(to_video_device(cd));
939         if (!cam) {
940                 up(&sn9c102_sysfs_lock);
941                 return -ENODEV;
942         }
943
944         value = sn9c102_strtou8(buf, len, &count);
945         if (!count) {
946                 up(&sn9c102_sysfs_lock);
947                 return -EINVAL;
948         }
949
950         err = sn9c102_write_reg(cam, value, cam->sysfs.reg);
951         if (err) {
952                 up(&sn9c102_sysfs_lock);
953                 return -EIO;
954         }
955
956         DBG(2, "Written SN9C10X reg. 0x%02X, val. 0x%02X",
957             cam->sysfs.reg, value)
958         DBG(3, "Written bytes: %zd", count)
959
960         up(&sn9c102_sysfs_lock);
961
962         return count;
963 }
964
965
966 static ssize_t sn9c102_show_i2c_reg(struct class_device* cd, char* buf)
967 {
968         struct sn9c102_device* cam;
969         ssize_t count;
970
971         if (down_interruptible(&sn9c102_sysfs_lock))
972                 return -ERESTARTSYS;
973
974         cam = video_get_drvdata(to_video_device(cd));
975         if (!cam) {
976                 up(&sn9c102_sysfs_lock);
977                 return -ENODEV;
978         }
979
980         count = sprintf(buf, "%u\n", cam->sysfs.i2c_reg);
981
982         DBG(3, "Read bytes: %zd", count)
983
984         up(&sn9c102_sysfs_lock);
985
986         return count;
987 }
988
989
990 static ssize_t 
991 sn9c102_store_i2c_reg(struct class_device* cd, const char* buf, size_t len)
992 {
993         struct sn9c102_device* cam;
994         u8 index;
995         ssize_t count;
996
997         if (down_interruptible(&sn9c102_sysfs_lock))
998                 return -ERESTARTSYS;
999
1000         cam = video_get_drvdata(to_video_device(cd));
1001         if (!cam) {
1002                 up(&sn9c102_sysfs_lock);
1003                 return -ENODEV;
1004         }
1005
1006         index = sn9c102_strtou8(buf, len, &count);
1007         if (!count) {
1008                 up(&sn9c102_sysfs_lock);
1009                 return -EINVAL;
1010         }
1011
1012         cam->sysfs.i2c_reg = index;
1013
1014         DBG(2, "Moved sensor register index to 0x%02X", cam->sysfs.i2c_reg)
1015         DBG(3, "Written bytes: %zd", count)
1016
1017         up(&sn9c102_sysfs_lock);
1018
1019         return count;
1020 }
1021
1022
1023 static ssize_t sn9c102_show_i2c_val(struct class_device* cd, char* buf)
1024 {
1025         struct sn9c102_device* cam;
1026         ssize_t count;
1027         int val;
1028
1029         if (down_interruptible(&sn9c102_sysfs_lock))
1030                 return -ERESTARTSYS;
1031
1032         cam = video_get_drvdata(to_video_device(cd));
1033         if (!cam) {
1034                 up(&sn9c102_sysfs_lock);
1035                 return -ENODEV;
1036         }
1037
1038         if (!(cam->sensor->sysfs_ops & SN9C102_I2C_READ)) {
1039                 up(&sn9c102_sysfs_lock);
1040                 return -ENOSYS;
1041         }
1042
1043         if ((val = sn9c102_i2c_read(cam, cam->sysfs.i2c_reg)) < 0) {
1044                 up(&sn9c102_sysfs_lock);
1045                 return -EIO;
1046         }
1047
1048         count = sprintf(buf, "%d\n", val);
1049
1050         DBG(3, "Read bytes: %zd", count)
1051
1052         up(&sn9c102_sysfs_lock);
1053
1054         return count;
1055
1056
1057
1058 static ssize_t
1059 sn9c102_store_i2c_val(struct class_device* cd, const char* buf, size_t len)
1060 {
1061         struct sn9c102_device* cam;
1062         u8 value;
1063         ssize_t count;
1064         int err;
1065
1066         if (down_interruptible(&sn9c102_sysfs_lock))
1067                 return -ERESTARTSYS;
1068
1069         cam = video_get_drvdata(to_video_device(cd));
1070         if (!cam) {
1071                 up(&sn9c102_sysfs_lock);
1072                 return -ENODEV;
1073         }
1074
1075         if (!(cam->sensor->sysfs_ops & SN9C102_I2C_WRITE)) {
1076                 up(&sn9c102_sysfs_lock);
1077                 return -ENOSYS;
1078         }
1079
1080         value = sn9c102_strtou8(buf, len, &count);
1081         if (!count) {
1082                 up(&sn9c102_sysfs_lock);
1083                 return -EINVAL;
1084         }
1085
1086         err = sn9c102_i2c_write(cam, cam->sysfs.i2c_reg, value);
1087         if (err) {
1088                 up(&sn9c102_sysfs_lock);
1089                 return -EIO;
1090         }
1091
1092         DBG(2, "Written sensor reg. 0x%02X, val. 0x%02X",
1093             cam->sysfs.i2c_reg, value)
1094         DBG(3, "Written bytes: %zd", count)
1095
1096         up(&sn9c102_sysfs_lock);
1097
1098         return count;
1099 }
1100
1101
1102 static ssize_t
1103 sn9c102_store_green(struct class_device* cd, const char* buf, size_t len)
1104 {
1105         struct sn9c102_device* cam;
1106         enum sn9c102_bridge bridge;
1107         ssize_t res = 0;
1108         u8 value;
1109         ssize_t count;
1110
1111         if (down_interruptible(&sn9c102_sysfs_lock))
1112                 return -ERESTARTSYS;
1113
1114         cam = video_get_drvdata(to_video_device(cd));
1115         if (!cam) {
1116                 up(&sn9c102_sysfs_lock);
1117                 return -ENODEV;
1118         }
1119
1120         bridge = cam->bridge;
1121
1122         up(&sn9c102_sysfs_lock);
1123
1124         value = sn9c102_strtou8(buf, len, &count);
1125         if (!count)
1126                 return -EINVAL;
1127
1128         switch (bridge) {
1129         case BRIDGE_SN9C101:
1130         case BRIDGE_SN9C102:
1131                 if (value > 0x0f)
1132                         return -EINVAL;
1133                 if ((res = sn9c102_store_reg(cd, "0x11", 4)) >= 0)
1134                         res = sn9c102_store_val(cd, buf, len);
1135                 break;
1136         case BRIDGE_SN9C103:
1137                 if (value > 0x7f)
1138                         return -EINVAL;
1139                 if ((res = sn9c102_store_reg(cd, "0x04", 4)) >= 0)
1140                         res = sn9c102_store_val(cd, buf, len);
1141                 break;
1142         }
1143
1144         return res;
1145 }
1146
1147
1148 static ssize_t
1149 sn9c102_store_blue(struct class_device* cd, const char* buf, size_t len)
1150 {
1151         ssize_t res = 0;
1152         u8 value;
1153         ssize_t count;
1154
1155         value = sn9c102_strtou8(buf, len, &count);
1156         if (!count || value > 0x7f)
1157                 return -EINVAL;
1158
1159         if ((res = sn9c102_store_reg(cd, "0x06", 4)) >= 0)
1160                 res = sn9c102_store_val(cd, buf, len);
1161
1162         return res;
1163 }
1164
1165
1166 static ssize_t
1167 sn9c102_store_red(struct class_device* cd, const char* buf, size_t len)
1168 {
1169         ssize_t res = 0;
1170         u8 value;
1171         ssize_t count;
1172
1173         value = sn9c102_strtou8(buf, len, &count);
1174         if (!count || value > 0x7f)
1175                 return -EINVAL;
1176
1177         if ((res = sn9c102_store_reg(cd, "0x05", 4)) >= 0)
1178                 res = sn9c102_store_val(cd, buf, len);
1179
1180         return res;
1181 }
1182
1183
1184 static ssize_t sn9c102_show_frame_header(struct class_device* cd, char* buf)
1185 {
1186         struct sn9c102_device* cam;
1187         ssize_t count;
1188
1189         cam = video_get_drvdata(to_video_device(cd));
1190         if (!cam)
1191                 return -ENODEV;
1192
1193         count = sizeof(cam->sysfs.frame_header);
1194         memcpy(buf, cam->sysfs.frame_header, count);
1195
1196         DBG(3, "Frame header, read bytes: %zd", count)
1197
1198         return count;
1199
1200
1201
1202 static CLASS_DEVICE_ATTR(reg, S_IRUGO | S_IWUSR,
1203                          sn9c102_show_reg, sn9c102_store_reg);
1204 static CLASS_DEVICE_ATTR(val, S_IRUGO | S_IWUSR,
1205                          sn9c102_show_val, sn9c102_store_val);
1206 static CLASS_DEVICE_ATTR(i2c_reg, S_IRUGO | S_IWUSR,
1207                          sn9c102_show_i2c_reg, sn9c102_store_i2c_reg);
1208 static CLASS_DEVICE_ATTR(i2c_val, S_IRUGO | S_IWUSR,
1209                          sn9c102_show_i2c_val, sn9c102_store_i2c_val);
1210 static CLASS_DEVICE_ATTR(green, S_IWUGO, NULL, sn9c102_store_green);
1211 static CLASS_DEVICE_ATTR(blue, S_IWUGO, NULL, sn9c102_store_blue);
1212 static CLASS_DEVICE_ATTR(red, S_IWUGO, NULL, sn9c102_store_red);
1213 static CLASS_DEVICE_ATTR(frame_header, S_IRUGO,
1214                          sn9c102_show_frame_header, NULL);
1215
1216
1217 static void sn9c102_create_sysfs(struct sn9c102_device* cam)
1218 {
1219         struct video_device *v4ldev = cam->v4ldev;
1220
1221         video_device_create_file(v4ldev, &class_device_attr_reg);
1222         video_device_create_file(v4ldev, &class_device_attr_val);
1223         video_device_create_file(v4ldev, &class_device_attr_frame_header);
1224         if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
1225                 video_device_create_file(v4ldev, &class_device_attr_green);
1226         else if (cam->bridge == BRIDGE_SN9C103) {
1227                 video_device_create_file(v4ldev, &class_device_attr_blue);
1228                 video_device_create_file(v4ldev, &class_device_attr_red);
1229         }
1230         if (cam->sensor->sysfs_ops) {
1231                 video_device_create_file(v4ldev, &class_device_attr_i2c_reg);
1232                 video_device_create_file(v4ldev, &class_device_attr_i2c_val);
1233         }
1234 }
1235
1236 /*****************************************************************************/
1237
1238 static int
1239 sn9c102_set_pix_format(struct sn9c102_device* cam, struct v4l2_pix_format* pix)
1240 {
1241         int err = 0;
1242
1243         if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X)
1244                 err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x80, 0x18);
1245         else
1246                 err += sn9c102_write_reg(cam, cam->reg[0x18] & 0x7f, 0x18);
1247
1248         return err ? -EIO : 0;
1249 }
1250
1251
1252 static int
1253 sn9c102_set_compression(struct sn9c102_device* cam,
1254                         struct v4l2_jpegcompression* compression)
1255 {
1256         int err = 0;
1257
1258         if (compression->quality == 0)
1259                 err += sn9c102_write_reg(cam, cam->reg[0x17] | 0x01, 0x17);
1260         else if (compression->quality == 1)
1261                 err += sn9c102_write_reg(cam, cam->reg[0x17] & 0xfe, 0x17);
1262
1263         return err ? -EIO : 0;
1264 }
1265
1266
1267 static int sn9c102_set_scale(struct sn9c102_device* cam, u8 scale)
1268 {
1269         u8 r = 0;
1270         int err = 0;
1271
1272         if (scale == 1)
1273                 r = cam->reg[0x18] & 0xcf;
1274         else if (scale == 2) {
1275                 r = cam->reg[0x18] & 0xcf;
1276                 r |= 0x10;
1277         } else if (scale == 4)
1278                 r = cam->reg[0x18] | 0x20;
1279
1280         err += sn9c102_write_reg(cam, r, 0x18);
1281         if (err)
1282                 return -EIO;
1283
1284         PDBGG("Scaling factor: %u", scale)
1285
1286         return 0;
1287 }
1288
1289
1290 static int sn9c102_set_crop(struct sn9c102_device* cam, struct v4l2_rect* rect)
1291 {
1292         struct sn9c102_sensor* s = cam->sensor;
1293         u8 h_start = (u8)(rect->left - s->cropcap.bounds.left),
1294            v_start = (u8)(rect->top - s->cropcap.bounds.top),
1295            h_size = (u8)(rect->width / 16),
1296            v_size = (u8)(rect->height / 16);
1297         int err = 0;
1298
1299         err += sn9c102_write_reg(cam, h_start, 0x12);
1300         err += sn9c102_write_reg(cam, v_start, 0x13);
1301         err += sn9c102_write_reg(cam, h_size, 0x15);
1302         err += sn9c102_write_reg(cam, v_size, 0x16);
1303         if (err)
1304                 return -EIO;
1305
1306         PDBGG("h_start, v_start, h_size, v_size, ho_size, vo_size "
1307               "%u %u %u %u", h_start, v_start, h_size, v_size)
1308
1309         return 0;
1310 }
1311
1312
1313 static int sn9c102_init(struct sn9c102_device* cam)
1314 {
1315         struct sn9c102_sensor* s = cam->sensor;
1316         struct v4l2_control ctrl;
1317         struct v4l2_queryctrl *qctrl;
1318         struct v4l2_rect* rect;
1319         u8 i = 0;
1320         int err = 0;
1321
1322         if (!(cam->state & DEV_INITIALIZED)) {
1323                 init_waitqueue_head(&cam->open);
1324                 qctrl = s->qctrl;
1325                 rect = &(s->cropcap.defrect);
1326         } else { /* use current values */
1327                 qctrl = s->_qctrl;
1328                 rect = &(s->_rect);
1329         }
1330
1331         err += sn9c102_set_scale(cam, rect->width / s->pix_format.width);
1332         err += sn9c102_set_crop(cam, rect);
1333         if (err)
1334                 return err;
1335
1336         if (s->init) {
1337                 err = s->init(cam);
1338                 if (err) {
1339                         DBG(3, "Sensor initialization failed")
1340                         return err;
1341                 }
1342         }
1343
1344         if (!(cam->state & DEV_INITIALIZED))
1345                 cam->compression.quality =  cam->reg[0x17] & 0x01 ? 0 : 1;
1346         else
1347                 err += sn9c102_set_compression(cam, &cam->compression);
1348         err += sn9c102_set_pix_format(cam, &s->pix_format);
1349         if (s->set_pix_format)
1350                 err += s->set_pix_format(cam, &s->pix_format);
1351         if (err)
1352                 return err;
1353
1354         if (s->pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X)
1355                 DBG(3, "Compressed video format is active, quality %d",
1356                     cam->compression.quality)
1357         else
1358                 DBG(3, "Uncompressed video format is active")
1359
1360         if (s->set_crop)
1361                 if ((err = s->set_crop(cam, rect))) {
1362                         DBG(3, "set_crop() failed")
1363                         return err;
1364                 }
1365
1366         if (s->set_ctrl) {
1367                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1368                         if (s->qctrl[i].id != 0 &&
1369                             !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
1370                                 ctrl.id = s->qctrl[i].id;
1371                                 ctrl.value = qctrl[i].default_value;
1372                                 err = s->set_ctrl(cam, &ctrl);
1373                                 if (err) {
1374                                         DBG(3, "Set %s control failed",
1375                                             s->qctrl[i].name)
1376                                         return err;
1377                                 }
1378                                 DBG(3, "Image sensor supports '%s' control",
1379                                     s->qctrl[i].name)
1380                         }
1381         }
1382
1383         if (!(cam->state & DEV_INITIALIZED)) {
1384                 init_MUTEX(&cam->fileop_sem);
1385                 spin_lock_init(&cam->queue_lock);
1386                 init_waitqueue_head(&cam->wait_frame);
1387                 init_waitqueue_head(&cam->wait_stream);
1388                 cam->nreadbuffers = 2;
1389                 memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
1390                 memcpy(&(s->_rect), &(s->cropcap.defrect),
1391                        sizeof(struct v4l2_rect));
1392                 cam->state |= DEV_INITIALIZED;
1393         }
1394
1395         DBG(2, "Initialization succeeded")
1396         return 0;
1397 }
1398
1399
1400 static void sn9c102_release_resources(struct sn9c102_device* cam)
1401 {
1402         down(&sn9c102_sysfs_lock);
1403
1404         DBG(2, "V4L2 device /dev/video%d deregistered", cam->v4ldev->minor)
1405         video_set_drvdata(cam->v4ldev, NULL);
1406         video_unregister_device(cam->v4ldev);
1407
1408         up(&sn9c102_sysfs_lock);
1409
1410         kfree(cam->control_buffer);
1411 }
1412
1413 /*****************************************************************************/
1414
1415 static int sn9c102_open(struct inode* inode, struct file* filp)
1416 {
1417         struct sn9c102_device* cam;
1418         int err = 0;
1419
1420         /*
1421            This is the only safe way to prevent race conditions with
1422            disconnect
1423         */
1424         if (!down_read_trylock(&sn9c102_disconnect))
1425                 return -ERESTARTSYS;
1426
1427         cam = video_get_drvdata(video_devdata(filp));
1428
1429         if (down_interruptible(&cam->dev_sem)) {
1430                 up_read(&sn9c102_disconnect);
1431                 return -ERESTARTSYS;
1432         }
1433
1434         if (cam->users) {
1435                 DBG(2, "Device /dev/video%d is busy...", cam->v4ldev->minor)
1436                 if ((filp->f_flags & O_NONBLOCK) ||
1437                     (filp->f_flags & O_NDELAY)) {
1438                         err = -EWOULDBLOCK;
1439                         goto out;
1440                 }
1441                 up(&cam->dev_sem);
1442                 err = wait_event_interruptible_exclusive(cam->open,
1443                                                   cam->state & DEV_DISCONNECTED
1444                                                          || !cam->users);
1445                 if (err) {
1446                         up_read(&sn9c102_disconnect);
1447                         return err;
1448                 }
1449                 if (cam->state & DEV_DISCONNECTED) {
1450                         up_read(&sn9c102_disconnect);
1451                         return -ENODEV;
1452                 }
1453                 down(&cam->dev_sem);
1454         }
1455
1456
1457         if (cam->state & DEV_MISCONFIGURED) {
1458                 err = sn9c102_init(cam);
1459                 if (err) {
1460                         DBG(1, "Initialization failed again. "
1461                                "I will retry on next open().")
1462                         goto out;
1463                 }
1464                 cam->state &= ~DEV_MISCONFIGURED;
1465         }
1466
1467         if ((err = sn9c102_start_transfer(cam)))
1468                 goto out;
1469
1470         filp->private_data = cam;
1471         cam->users++;
1472         cam->io = IO_NONE;
1473         cam->stream = STREAM_OFF;
1474         cam->nbuffers = 0;
1475         cam->frame_count = 0;
1476         sn9c102_empty_framequeues(cam);
1477
1478         DBG(3, "Video device /dev/video%d is open", cam->v4ldev->minor)
1479
1480 out:
1481         up(&cam->dev_sem);
1482         up_read(&sn9c102_disconnect);
1483         return err;
1484 }
1485
1486
1487 static int sn9c102_release(struct inode* inode, struct file* filp)
1488 {
1489         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1490
1491         down(&cam->dev_sem); /* prevent disconnect() to be called */
1492
1493         sn9c102_stop_transfer(cam);
1494
1495         sn9c102_release_buffers(cam);
1496
1497         if (cam->state & DEV_DISCONNECTED) {
1498                 sn9c102_release_resources(cam);
1499                 up(&cam->dev_sem);
1500                 kfree(cam);
1501                 return 0;
1502         }
1503
1504         cam->users--;
1505         wake_up_interruptible_nr(&cam->open, 1);
1506
1507         DBG(3, "Video device /dev/video%d closed", cam->v4ldev->minor)
1508
1509         up(&cam->dev_sem);
1510
1511         return 0;
1512 }
1513
1514
1515 static ssize_t
1516 sn9c102_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
1517 {
1518         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1519         struct sn9c102_frame_t* f, * i;
1520         unsigned long lock_flags;
1521         int err = 0;
1522
1523         if (down_interruptible(&cam->fileop_sem))
1524                 return -ERESTARTSYS;
1525
1526         if (cam->state & DEV_DISCONNECTED) {
1527                 DBG(1, "Device not present")
1528                 up(&cam->fileop_sem);
1529                 return -ENODEV;
1530         }
1531
1532         if (cam->state & DEV_MISCONFIGURED) {
1533                 DBG(1, "The camera is misconfigured. Close and open it again.")
1534                 up(&cam->fileop_sem);
1535                 return -EIO;
1536         }
1537
1538         if (cam->io == IO_MMAP) {
1539                 DBG(3, "Close and open the device again to choose "
1540                        "the read method")
1541                 up(&cam->fileop_sem);
1542                 return -EINVAL;
1543         }
1544
1545         if (cam->io == IO_NONE) {
1546                 if (!sn9c102_request_buffers(cam,cam->nreadbuffers, IO_READ)) {
1547                         DBG(1, "read() failed, not enough memory")
1548                         up(&cam->fileop_sem);
1549                         return -ENOMEM;
1550                 }
1551                 cam->io = IO_READ;
1552                 cam->stream = STREAM_ON;
1553                 sn9c102_queue_unusedframes(cam);
1554         }
1555
1556         if (!count) {
1557                 up(&cam->fileop_sem);
1558                 return 0;
1559         }
1560
1561         if (list_empty(&cam->outqueue)) {
1562                 if (filp->f_flags & O_NONBLOCK) {
1563                         up(&cam->fileop_sem);
1564                         return -EAGAIN;
1565                 }
1566                 err = wait_event_interruptible
1567                       ( cam->wait_frame, 
1568                         (!list_empty(&cam->outqueue)) ||
1569                         (cam->state & DEV_DISCONNECTED) ||
1570                         (cam->state & DEV_MISCONFIGURED) );
1571                 if (err) {
1572                         up(&cam->fileop_sem);
1573                         return err;
1574                 }
1575                 if (cam->state & DEV_DISCONNECTED) {
1576                         up(&cam->fileop_sem);
1577                         return -ENODEV;
1578                 }
1579                 if (cam->state & DEV_MISCONFIGURED) {
1580                         up(&cam->fileop_sem);
1581                         return -EIO;
1582                 }
1583         }
1584
1585         f = list_entry(cam->outqueue.prev, struct sn9c102_frame_t, frame);
1586
1587         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1588         list_for_each_entry(i, &cam->outqueue, frame)
1589                 i->state = F_UNUSED;
1590         INIT_LIST_HEAD(&cam->outqueue);
1591         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1592
1593         sn9c102_queue_unusedframes(cam);
1594
1595         if (count > f->buf.bytesused)
1596                 count = f->buf.bytesused;
1597
1598         if (copy_to_user(buf, f->bufmem, count)) {
1599                 up(&cam->fileop_sem);
1600                 return -EFAULT;
1601         }
1602         *f_pos += count;
1603
1604         PDBGG("Frame #%lu, bytes read: %zu", (unsigned long)f->buf.index,count)
1605
1606         up(&cam->fileop_sem);
1607
1608         return count;
1609 }
1610
1611
1612 static unsigned int sn9c102_poll(struct file *filp, poll_table *wait)
1613 {
1614         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1615         unsigned int mask = 0;
1616
1617         if (down_interruptible(&cam->fileop_sem))
1618                 return POLLERR;
1619
1620         if (cam->state & DEV_DISCONNECTED) {
1621                 DBG(1, "Device not present")
1622                 goto error;
1623         }
1624
1625         if (cam->state & DEV_MISCONFIGURED) {
1626                 DBG(1, "The camera is misconfigured. Close and open it again.")
1627                 goto error;
1628         }
1629
1630         if (cam->io == IO_NONE) {
1631                 if (!sn9c102_request_buffers(cam, cam->nreadbuffers,
1632                                              IO_READ)) {
1633                         DBG(1, "poll() failed, not enough memory")
1634                         goto error;
1635                 }
1636                 cam->io = IO_READ;
1637                 cam->stream = STREAM_ON;
1638         }
1639
1640         if (cam->io == IO_READ)
1641                 sn9c102_queue_unusedframes(cam);
1642
1643         poll_wait(filp, &cam->wait_frame, wait);
1644
1645         if (!list_empty(&cam->outqueue))
1646                 mask |= POLLIN | POLLRDNORM;
1647
1648         up(&cam->fileop_sem);
1649
1650         return mask;
1651
1652 error:
1653         up(&cam->fileop_sem);
1654         return POLLERR;
1655 }
1656
1657
1658 static void sn9c102_vm_open(struct vm_area_struct* vma)
1659 {
1660         struct sn9c102_frame_t* f = vma->vm_private_data;
1661         f->vma_use_count++;
1662 }
1663
1664
1665 static void sn9c102_vm_close(struct vm_area_struct* vma)
1666 {
1667         /* NOTE: buffers are not freed here */
1668         struct sn9c102_frame_t* f = vma->vm_private_data;
1669         f->vma_use_count--;
1670 }
1671
1672
1673 static struct vm_operations_struct sn9c102_vm_ops = {
1674         .open = sn9c102_vm_open,
1675         .close = sn9c102_vm_close,
1676 };
1677
1678
1679 static int sn9c102_mmap(struct file* filp, struct vm_area_struct *vma)
1680 {
1681         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1682         unsigned long size = vma->vm_end - vma->vm_start,
1683                       start = vma->vm_start,
1684                       pos,
1685                       page;
1686         u32 i;
1687
1688         if (down_interruptible(&cam->fileop_sem))
1689                 return -ERESTARTSYS;
1690
1691         if (cam->state & DEV_DISCONNECTED) {
1692                 DBG(1, "Device not present")
1693                 up(&cam->fileop_sem);
1694                 return -ENODEV;
1695         }
1696
1697         if (cam->state & DEV_MISCONFIGURED) {
1698                 DBG(1, "The camera is misconfigured. Close and open it again.")
1699                 up(&cam->fileop_sem);
1700                 return -EIO;
1701         }
1702
1703         if (cam->io != IO_MMAP || !(vma->vm_flags & VM_WRITE) ||
1704             size != PAGE_ALIGN(cam->frame[0].buf.length)) {
1705                 up(&cam->fileop_sem);
1706                 return -EINVAL;
1707         }
1708
1709         for (i = 0; i < cam->nbuffers; i++) {
1710                 if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
1711                         break;
1712         }
1713         if (i == cam->nbuffers) {
1714                 up(&cam->fileop_sem);
1715                 return -EINVAL;
1716         }
1717
1718         /* VM_IO is eventually going to replace PageReserved altogether */
1719         vma->vm_flags |= VM_IO;
1720         vma->vm_flags |= VM_RESERVED; /* avoid to swap out this VMA */
1721
1722         pos = (unsigned long)cam->frame[i].bufmem;
1723         while (size > 0) { /* size is page-aligned */
1724                 page = vmalloc_to_pfn((void *)pos);
1725                 if (remap_pfn_range(vma, start, page, PAGE_SIZE,
1726                                     vma->vm_page_prot)) {
1727                         up(&cam->fileop_sem);
1728                         return -EAGAIN;
1729                 }
1730                 start += PAGE_SIZE;
1731                 pos += PAGE_SIZE;
1732                 size -= PAGE_SIZE;
1733         }
1734
1735         vma->vm_ops = &sn9c102_vm_ops;
1736         vma->vm_private_data = &cam->frame[i];
1737
1738         sn9c102_vm_open(vma);
1739
1740         up(&cam->fileop_sem);
1741
1742         return 0;
1743 }
1744
1745
1746 static int sn9c102_ioctl_v4l2(struct inode* inode, struct file* filp,
1747                               unsigned int cmd, void __user * arg)
1748 {
1749         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
1750
1751         switch (cmd) {
1752
1753         case VIDIOC_QUERYCAP:
1754         {
1755                 struct v4l2_capability cap = {
1756                         .driver = "sn9c102",
1757                         .version = SN9C102_MODULE_VERSION_CODE,
1758                         .capabilities = V4L2_CAP_VIDEO_CAPTURE | 
1759                                         V4L2_CAP_READWRITE |
1760                                         V4L2_CAP_STREAMING,
1761                 };
1762
1763                 strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
1764                 if (usb_make_path(cam->usbdev, cap.bus_info,
1765                     sizeof(cap.bus_info)) < 0)
1766                         strlcpy(cap.bus_info, cam->dev.bus_id,
1767                                 sizeof(cap.bus_info));
1768
1769                 if (copy_to_user(arg, &cap, sizeof(cap)))
1770                         return -EFAULT;
1771
1772                 return 0;
1773         }
1774
1775         case VIDIOC_ENUMINPUT:
1776         {
1777                 struct v4l2_input i;
1778
1779                 if (copy_from_user(&i, arg, sizeof(i)))
1780                         return -EFAULT;
1781
1782                 if (i.index)
1783                         return -EINVAL;
1784
1785                 memset(&i, 0, sizeof(i));
1786                 strcpy(i.name, "USB");
1787
1788                 if (copy_to_user(arg, &i, sizeof(i)))
1789                         return -EFAULT;
1790
1791                 return 0;
1792         }
1793
1794         case VIDIOC_G_INPUT:
1795         case VIDIOC_S_INPUT:
1796         {
1797                 int index;
1798
1799                 if (copy_from_user(&index, arg, sizeof(index)))
1800                         return -EFAULT;
1801
1802                 if (index != 0)
1803                         return -EINVAL;
1804
1805                 return 0;
1806         }
1807
1808         case VIDIOC_QUERYCTRL:
1809         {
1810                 struct sn9c102_sensor* s = cam->sensor;
1811                 struct v4l2_queryctrl qc;
1812                 u8 i;
1813
1814                 if (copy_from_user(&qc, arg, sizeof(qc)))
1815                         return -EFAULT;
1816
1817                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1818                         if (qc.id && qc.id == s->qctrl[i].id) {
1819                                 memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
1820                                 if (copy_to_user(arg, &qc, sizeof(qc)))
1821                                         return -EFAULT;
1822                                 return 0;
1823                         }
1824
1825                 return -EINVAL;
1826         }
1827
1828         case VIDIOC_G_CTRL:
1829         {
1830                 struct sn9c102_sensor* s = cam->sensor;
1831                 struct v4l2_control ctrl;
1832                 int err = 0;
1833
1834                 if (!s->get_ctrl)
1835                         return -EINVAL;
1836
1837                 if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1838                         return -EFAULT;
1839
1840                 err = s->get_ctrl(cam, &ctrl);
1841
1842                 if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
1843                         return -EFAULT;
1844
1845                 return err;
1846         }
1847
1848         case VIDIOC_S_CTRL_OLD:
1849         case VIDIOC_S_CTRL:
1850         {
1851                 struct sn9c102_sensor* s = cam->sensor;
1852                 struct v4l2_control ctrl;
1853                 u8 i;
1854                 int err = 0;
1855
1856                 if (!s->set_ctrl)
1857                         return -EINVAL;
1858
1859                 if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1860                         return -EFAULT;
1861
1862                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1863                         if (ctrl.id == s->qctrl[i].id) {
1864                                 if (ctrl.value < s->qctrl[i].minimum ||
1865                                     ctrl.value > s->qctrl[i].maximum)
1866                                         return -ERANGE;
1867                                 ctrl.value -= ctrl.value % s->qctrl[i].step;
1868                                 break;
1869                         }
1870
1871                 if ((err = s->set_ctrl(cam, &ctrl)))
1872                         return err;
1873
1874                 s->_qctrl[i].default_value = ctrl.value;
1875
1876                 PDBGG("VIDIOC_S_CTRL: id %lu, value %lu",
1877                       (unsigned long)ctrl.id, (unsigned long)ctrl.value)
1878
1879                 return 0;
1880         }
1881
1882         case VIDIOC_CROPCAP:
1883         {
1884                 struct v4l2_cropcap* cc = &(cam->sensor->cropcap);
1885
1886                 cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1887                 cc->pixelaspect.numerator = 1;
1888                 cc->pixelaspect.denominator = 1;
1889
1890                 if (copy_to_user(arg, cc, sizeof(*cc)))
1891                         return -EFAULT;
1892
1893                 return 0;
1894         }
1895
1896         case VIDIOC_G_CROP:
1897         {
1898                 struct sn9c102_sensor* s = cam->sensor;
1899                 struct v4l2_crop crop = {
1900                         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1901                 };
1902
1903                 memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));
1904
1905                 if (copy_to_user(arg, &crop, sizeof(crop)))
1906                         return -EFAULT;
1907
1908                 return 0;
1909         }
1910
1911         case VIDIOC_S_CROP:
1912         {
1913                 struct sn9c102_sensor* s = cam->sensor;
1914                 struct v4l2_crop crop;
1915                 struct v4l2_rect* rect;
1916                 struct v4l2_rect* bounds = &(s->cropcap.bounds);
1917                 struct v4l2_pix_format* pix_format = &(s->pix_format);
1918                 u8 scale;
1919                 const enum sn9c102_stream_state stream = cam->stream;
1920                 const u32 nbuffers = cam->nbuffers;
1921                 u32 i;
1922                 int err = 0;
1923
1924                 if (copy_from_user(&crop, arg, sizeof(crop)))
1925                         return -EFAULT;
1926
1927                 rect = &(crop.c);
1928
1929                 if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1930                         return -EINVAL;
1931
1932                 if (cam->module_param.force_munmap)
1933                         for (i = 0; i < cam->nbuffers; i++)
1934                                 if (cam->frame[i].vma_use_count) {
1935                                         DBG(3, "VIDIOC_S_CROP failed. "
1936                                                "Unmap the buffers first.")
1937                                         return -EINVAL;
1938                                 }
1939
1940                 /* Preserve R,G or B origin */
1941                 rect->left = (s->_rect.left & 1L) ?
1942                              rect->left | 1L : rect->left & ~1L;
1943                 rect->top = (s->_rect.top & 1L) ?
1944                             rect->top | 1L : rect->top & ~1L;
1945
1946                 if (rect->width < 16)
1947                         rect->width = 16;
1948                 if (rect->height < 16)
1949                         rect->height = 16;
1950                 if (rect->width > bounds->width)
1951                         rect->width = bounds->width;
1952                 if (rect->height > bounds->height)
1953                         rect->height = bounds->height;
1954                 if (rect->left < bounds->left)
1955                         rect->left = bounds->left;
1956                 if (rect->top < bounds->top)
1957                         rect->top = bounds->top;
1958                 if (rect->left + rect->width > bounds->left + bounds->width)
1959                         rect->left = bounds->left+bounds->width - rect->width;
1960                 if (rect->top + rect->height > bounds->top + bounds->height)
1961                         rect->top = bounds->top+bounds->height - rect->height;
1962
1963                 rect->width &= ~15L;
1964                 rect->height &= ~15L;
1965
1966                 if (SN9C102_PRESERVE_IMGSCALE) {
1967                         /* Calculate the actual scaling factor */
1968                         u32 a, b;
1969                         a = rect->width * rect->height;
1970                         b = pix_format->width * pix_format->height;
1971                         scale = b ? (u8)((a / b) < 4 ? 1 :
1972                                         ((a / b) < 16 ? 2 : 4)) : 1;
1973                 } else
1974                         scale = 1;
1975
1976                 if (cam->stream == STREAM_ON)
1977                         if ((err = sn9c102_stream_interrupt(cam)))
1978                                 return err;
1979
1980                 if (copy_to_user(arg, &crop, sizeof(crop))) {
1981                         cam->stream = stream;
1982                         return -EFAULT;
1983                 }
1984
1985                 if (cam->module_param.force_munmap || cam->io == IO_READ)
1986                         sn9c102_release_buffers(cam);
1987
1988                 err = sn9c102_set_crop(cam, rect);
1989                 if (s->set_crop)
1990                         err += s->set_crop(cam, rect);
1991                 err += sn9c102_set_scale(cam, scale);
1992
1993                 if (err) { /* atomic, no rollback in ioctl() */
1994                         cam->state |= DEV_MISCONFIGURED;
1995                         DBG(1, "VIDIOC_S_CROP failed because of hardware "
1996                                "problems. To use the camera, close and open "
1997                                "/dev/video%d again.", cam->v4ldev->minor)
1998                         return -EIO;
1999                 }
2000
2001                 s->pix_format.width = rect->width/scale;
2002                 s->pix_format.height = rect->height/scale;
2003                 memcpy(&(s->_rect), rect, sizeof(*rect));
2004
2005                 if ((cam->module_param.force_munmap || cam->io == IO_READ) &&
2006                     nbuffers != sn9c102_request_buffers(cam, nbuffers,
2007                                                         cam->io)) {
2008                         cam->state |= DEV_MISCONFIGURED;
2009                         DBG(1, "VIDIOC_S_CROP failed because of not enough "
2010                                "memory. To use the camera, close and open "
2011                                "/dev/video%d again.", cam->v4ldev->minor)
2012                         return -ENOMEM;
2013                 }
2014
2015                 cam->stream = stream;
2016
2017                 return 0;
2018         }
2019
2020         case VIDIOC_ENUM_FMT:
2021         {
2022                 struct v4l2_fmtdesc fmtd;
2023
2024                 if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
2025                         return -EFAULT;
2026
2027                 if (fmtd.index == 0) {
2028                         strcpy(fmtd.description, "bayer rgb");
2029                         fmtd.pixelformat = V4L2_PIX_FMT_SBGGR8;
2030                 } else if (fmtd.index == 1) {
2031                         strcpy(fmtd.description, "compressed");
2032                         fmtd.pixelformat = V4L2_PIX_FMT_SN9C10X;
2033                         fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
2034                 } else
2035                         return -EINVAL;
2036
2037                 fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2038                 memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));
2039
2040                 if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
2041                         return -EFAULT;
2042
2043                 return 0;
2044         }
2045
2046         case VIDIOC_G_FMT:
2047         {
2048                 struct v4l2_format format;
2049                 struct v4l2_pix_format* pfmt = &(cam->sensor->pix_format);
2050
2051                 if (copy_from_user(&format, arg, sizeof(format)))
2052                         return -EFAULT;
2053
2054                 if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2055                         return -EINVAL;
2056
2057                 pfmt->bytesperline = (pfmt->pixelformat==V4L2_PIX_FMT_SN9C10X)
2058                                      ? 0 : (pfmt->width * pfmt->priv) / 8;
2059                 pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
2060                 pfmt->field = V4L2_FIELD_NONE;
2061                 memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));
2062
2063                 if (copy_to_user(arg, &format, sizeof(format)))
2064                         return -EFAULT;
2065
2066                 return 0;
2067         }
2068
2069         case VIDIOC_TRY_FMT:
2070         case VIDIOC_S_FMT:
2071         {
2072                 struct sn9c102_sensor* s = cam->sensor;
2073                 struct v4l2_format format;
2074                 struct v4l2_pix_format* pix;
2075                 struct v4l2_pix_format* pfmt = &(s->pix_format);
2076                 struct v4l2_rect* bounds = &(s->cropcap.bounds);
2077                 struct v4l2_rect rect;
2078                 u8 scale;
2079                 const enum sn9c102_stream_state stream = cam->stream;
2080                 const u32 nbuffers = cam->nbuffers;
2081                 u32 i;
2082                 int err = 0;
2083
2084                 if (copy_from_user(&format, arg, sizeof(format)))
2085                         return -EFAULT;
2086
2087                 pix = &(format.fmt.pix);
2088
2089                 if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2090                         return -EINVAL;
2091
2092                 memcpy(&rect, &(s->_rect), sizeof(rect));
2093
2094                 { /* calculate the actual scaling factor */
2095                         u32 a, b;
2096                         a = rect.width * rect.height;
2097                         b = pix->width * pix->height;
2098                         scale = b ? (u8)((a / b) < 4 ? 1 :
2099                                         ((a / b) < 16 ? 2 : 4)) : 1;
2100                 }
2101
2102                 rect.width = scale * pix->width;
2103                 rect.height = scale * pix->height;
2104
2105                 if (rect.width < 16)
2106                         rect.width = 16;
2107                 if (rect.height < 16)
2108                         rect.height = 16;
2109                 if (rect.width > bounds->left + bounds->width - rect.left)
2110                         rect.width = bounds->left + bounds->width - rect.left;
2111                 if (rect.height > bounds->top + bounds->height - rect.top)
2112                         rect.height = bounds->top + bounds->height - rect.top;
2113
2114                 rect.width &= ~15L;
2115                 rect.height &= ~15L;
2116
2117                 { /* adjust the scaling factor */
2118                         u32 a, b;
2119                         a = rect.width * rect.height;
2120                         b = pix->width * pix->height;
2121                         scale = b ? (u8)((a / b) < 4 ? 1 :
2122                                         ((a / b) < 16 ? 2 : 4)) : 1;
2123                 }
2124
2125                 pix->width = rect.width / scale;
2126                 pix->height = rect.height / scale;
2127
2128                 if (pix->pixelformat != V4L2_PIX_FMT_SN9C10X &&
2129                     pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
2130                         pix->pixelformat = pfmt->pixelformat;
2131                 pix->priv = pfmt->priv; /* bpp */
2132                 pix->colorspace = pfmt->colorspace;
2133                 pix->bytesperline = (pix->pixelformat == V4L2_PIX_FMT_SN9C10X)
2134                                     ? 0 : (pix->width * pix->priv) / 8;
2135                 pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
2136                 pix->field = V4L2_FIELD_NONE;
2137
2138                 if (cmd == VIDIOC_TRY_FMT) {
2139                         if (copy_to_user(arg, &format, sizeof(format)))
2140                                 return -EFAULT;
2141                         return 0;
2142                 }
2143
2144                 if (cam->module_param.force_munmap)
2145                         for (i = 0; i < cam->nbuffers; i++)
2146                                 if (cam->frame[i].vma_use_count) {
2147                                         DBG(3, "VIDIOC_S_FMT failed. "
2148                                                "Unmap the buffers first.")
2149                                         return -EINVAL;
2150                                 }
2151
2152                 if (cam->stream == STREAM_ON)
2153                         if ((err = sn9c102_stream_interrupt(cam)))
2154                                 return err;
2155
2156                 if (copy_to_user(arg, &format, sizeof(format))) {
2157                         cam->stream = stream;
2158                         return -EFAULT;
2159                 }
2160
2161                 if (cam->module_param.force_munmap  || cam->io == IO_READ)
2162                         sn9c102_release_buffers(cam);
2163
2164                 err += sn9c102_set_pix_format(cam, pix);
2165                 err += sn9c102_set_crop(cam, &rect);
2166                 if (s->set_pix_format)
2167                         err += s->set_pix_format(cam, pix);
2168                 if (s->set_crop)
2169                         err += s->set_crop(cam, &rect);
2170                 err += sn9c102_set_scale(cam, scale);
2171
2172                 if (err) { /* atomic, no rollback in ioctl() */
2173                         cam->state |= DEV_MISCONFIGURED;
2174                         DBG(1, "VIDIOC_S_FMT failed because of hardware "
2175                                "problems. To use the camera, close and open "
2176                                "/dev/video%d again.", cam->v4ldev->minor)
2177                         return -EIO;
2178                 }
2179
2180                 memcpy(pfmt, pix, sizeof(*pix));
2181                 memcpy(&(s->_rect), &rect, sizeof(rect));
2182
2183                 if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
2184                     nbuffers != sn9c102_request_buffers(cam, nbuffers,
2185                                                         cam->io)) {
2186                         cam->state |= DEV_MISCONFIGURED;
2187                         DBG(1, "VIDIOC_S_FMT failed because of not enough "
2188                                "memory. To use the camera, close and open "
2189                                "/dev/video%d again.", cam->v4ldev->minor)
2190                         return -ENOMEM;
2191                 }
2192
2193                 cam->stream = stream;
2194
2195                 return 0;
2196         }
2197
2198         case VIDIOC_G_JPEGCOMP:
2199         {
2200                 if (copy_to_user(arg, &cam->compression,
2201                                  sizeof(cam->compression)))
2202                         return -EFAULT;
2203
2204                 return 0;
2205         }
2206
2207         case VIDIOC_S_JPEGCOMP:
2208         {
2209                 struct v4l2_jpegcompression jc;
2210                 const enum sn9c102_stream_state stream = cam->stream;
2211                 int err = 0;
2212
2213                 if (copy_from_user(&jc, arg, sizeof(jc)))
2214                         return -EFAULT;
2215
2216                 if (jc.quality != 0 && jc.quality != 1)
2217                         return -EINVAL;
2218
2219                 if (cam->stream == STREAM_ON)
2220                         if ((err = sn9c102_stream_interrupt(cam)))
2221                                 return err;
2222
2223                 err += sn9c102_set_compression(cam, &jc);
2224                 if (err) { /* atomic, no rollback in ioctl() */
2225                         cam->state |= DEV_MISCONFIGURED;
2226                         DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware "
2227                                "problems. To use the camera, close and open "
2228                                "/dev/video%d again.", cam->v4ldev->minor)
2229                         return -EIO;
2230                 }
2231
2232                 cam->compression.quality = jc.quality;
2233
2234                 cam->stream = stream;
2235
2236                 return 0;
2237         }
2238
2239         case VIDIOC_REQBUFS:
2240         {
2241                 struct v4l2_requestbuffers rb;
2242                 u32 i;
2243                 int err;
2244
2245                 if (copy_from_user(&rb, arg, sizeof(rb)))
2246                         return -EFAULT;
2247
2248                 if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2249                     rb.memory != V4L2_MEMORY_MMAP)
2250                         return -EINVAL;
2251
2252                 if (cam->io == IO_READ) {
2253                         DBG(3, "Close and open the device again to choose "
2254                                "the mmap I/O method")
2255                         return -EINVAL;
2256                 }
2257
2258                 for (i = 0; i < cam->nbuffers; i++)
2259                         if (cam->frame[i].vma_use_count) {
2260                                 DBG(3, "VIDIOC_REQBUFS failed. "
2261                                        "Previous buffers are still mapped.")
2262                                 return -EINVAL;
2263                         }
2264
2265                 if (cam->stream == STREAM_ON)
2266                         if ((err = sn9c102_stream_interrupt(cam)))
2267                                 return err;
2268
2269                 sn9c102_empty_framequeues(cam);
2270
2271                 sn9c102_release_buffers(cam);
2272                 if (rb.count)
2273                         rb.count = sn9c102_request_buffers(cam, rb.count,
2274                                                            IO_MMAP);
2275
2276                 if (copy_to_user(arg, &rb, sizeof(rb))) {
2277                         sn9c102_release_buffers(cam);
2278                         cam->io = IO_NONE;
2279                         return -EFAULT;
2280                 }
2281
2282                 cam->io = rb.count ? IO_MMAP : IO_NONE;
2283
2284                 return 0;
2285         }
2286
2287         case VIDIOC_QUERYBUF:
2288         {
2289                 struct v4l2_buffer b;
2290
2291                 if (copy_from_user(&b, arg, sizeof(b)))
2292                         return -EFAULT;
2293
2294                 if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2295                     b.index >= cam->nbuffers || cam->io != IO_MMAP)
2296                         return -EINVAL;
2297
2298                 memcpy(&b, &cam->frame[b.index].buf, sizeof(b));
2299
2300                 if (cam->frame[b.index].vma_use_count)
2301                         b.flags |= V4L2_BUF_FLAG_MAPPED;
2302
2303                 if (cam->frame[b.index].state == F_DONE)
2304                         b.flags |= V4L2_BUF_FLAG_DONE;
2305                 else if (cam->frame[b.index].state != F_UNUSED)
2306                         b.flags |= V4L2_BUF_FLAG_QUEUED;
2307
2308                 if (copy_to_user(arg, &b, sizeof(b)))
2309                         return -EFAULT;
2310
2311                 return 0;
2312         }
2313
2314         case VIDIOC_QBUF:
2315         {
2316                 struct v4l2_buffer b;
2317                 unsigned long lock_flags;
2318
2319                 if (copy_from_user(&b, arg, sizeof(b)))
2320                         return -EFAULT;
2321
2322                 if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2323                     b.index >= cam->nbuffers || cam->io != IO_MMAP)
2324                         return -EINVAL;
2325
2326                 if (cam->frame[b.index].state != F_UNUSED)
2327                         return -EINVAL;
2328
2329                 cam->frame[b.index].state = F_QUEUED;
2330
2331                 spin_lock_irqsave(&cam->queue_lock, lock_flags);
2332                 list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
2333                 spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2334
2335                 PDBGG("Frame #%lu queued", (unsigned long)b.index)
2336
2337                 return 0;
2338         }
2339
2340         case VIDIOC_DQBUF:
2341         {
2342                 struct v4l2_buffer b;
2343                 struct sn9c102_frame_t *f;
2344                 unsigned long lock_flags;
2345                 int err = 0;
2346
2347                 if (copy_from_user(&b, arg, sizeof(b)))
2348                         return -EFAULT;
2349
2350                 if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io!= IO_MMAP)
2351                         return -EINVAL;
2352
2353                 if (list_empty(&cam->outqueue)) {
2354                         if (cam->stream == STREAM_OFF)
2355                                 return -EINVAL;
2356                         if (filp->f_flags & O_NONBLOCK)
2357                                 return -EAGAIN;
2358                         err = wait_event_interruptible
2359                               ( cam->wait_frame, 
2360                                 (!list_empty(&cam->outqueue)) ||
2361                                 (cam->state & DEV_DISCONNECTED) ||
2362                                 (cam->state & DEV_MISCONFIGURED) );
2363                         if (err)
2364                                 return err;
2365                         if (cam->state & DEV_DISCONNECTED)
2366                                 return -ENODEV;
2367                         if (cam->state & DEV_MISCONFIGURED)
2368                                 return -EIO;
2369                 }
2370
2371                 spin_lock_irqsave(&cam->queue_lock, lock_flags);
2372                 f = list_entry(cam->outqueue.next, struct sn9c102_frame_t,
2373                                frame);
2374                 list_del(cam->outqueue.next);
2375                 spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2376
2377                 f->state = F_UNUSED;
2378
2379                 memcpy(&b, &f->buf, sizeof(b));
2380                 if (f->vma_use_count)
2381                         b.flags |= V4L2_BUF_FLAG_MAPPED;
2382
2383                 if (copy_to_user(arg, &b, sizeof(b)))
2384                         return -EFAULT;
2385
2386                 PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index)
2387
2388                 return 0;
2389         }
2390
2391         case VIDIOC_STREAMON:
2392         {
2393                 int type;
2394
2395                 if (copy_from_user(&type, arg, sizeof(type)))
2396                         return -EFAULT;
2397
2398                 if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2399                         return -EINVAL;
2400
2401                 if (list_empty(&cam->inqueue))
2402                         return -EINVAL;
2403
2404                 cam->stream = STREAM_ON;
2405
2406                 DBG(3, "Stream on")
2407
2408                 return 0;
2409         }
2410
2411         case VIDIOC_STREAMOFF:
2412         {
2413                 int type, err;
2414
2415                 if (copy_from_user(&type, arg, sizeof(type)))
2416                         return -EFAULT;
2417
2418                 if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2419                         return -EINVAL;
2420
2421                 if (cam->stream == STREAM_ON)
2422                         if ((err = sn9c102_stream_interrupt(cam)))
2423                                 return err;
2424
2425                 sn9c102_empty_framequeues(cam);
2426
2427                 DBG(3, "Stream off")
2428
2429                 return 0;
2430         }
2431
2432         case VIDIOC_G_PARM:
2433         {
2434                 struct v4l2_streamparm sp;
2435
2436                 if (copy_from_user(&sp, arg, sizeof(sp)))
2437                         return -EFAULT;
2438
2439                 if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2440                         return -EINVAL;
2441
2442                 sp.parm.capture.extendedmode = 0;
2443                 sp.parm.capture.readbuffers = cam->nreadbuffers;
2444
2445                 if (copy_to_user(arg, &sp, sizeof(sp)))
2446                         return -EFAULT;
2447
2448                 return 0;
2449         }
2450
2451         case VIDIOC_S_PARM_OLD:
2452         case VIDIOC_S_PARM:
2453         {
2454                 struct v4l2_streamparm sp;
2455
2456                 if (copy_from_user(&sp, arg, sizeof(sp)))
2457                         return -EFAULT;
2458
2459                 if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2460                         return -EINVAL;
2461
2462                 sp.parm.capture.extendedmode = 0;
2463
2464                 if (sp.parm.capture.readbuffers == 0)
2465                         sp.parm.capture.readbuffers = cam->nreadbuffers;
2466
2467                 if (sp.parm.capture.readbuffers > SN9C102_MAX_FRAMES)
2468                         sp.parm.capture.readbuffers = SN9C102_MAX_FRAMES;
2469
2470                 if (copy_to_user(arg, &sp, sizeof(sp)))
2471                         return -EFAULT;
2472
2473                 cam->nreadbuffers = sp.parm.capture.readbuffers;
2474
2475                 return 0;
2476         }
2477
2478         case VIDIOC_G_STD:
2479         case VIDIOC_S_STD:
2480         case VIDIOC_QUERYSTD:
2481         case VIDIOC_ENUMSTD:
2482         case VIDIOC_QUERYMENU:
2483                 return -EINVAL;
2484
2485         default:
2486                 return -EINVAL;
2487
2488         }
2489 }
2490
2491
2492 static int sn9c102_ioctl(struct inode* inode, struct file* filp,
2493                          unsigned int cmd, unsigned long arg)
2494 {
2495         struct sn9c102_device* cam = video_get_drvdata(video_devdata(filp));
2496         int err = 0;
2497
2498         if (down_interruptible(&cam->fileop_sem))
2499                 return -ERESTARTSYS;
2500
2501         if (cam->state & DEV_DISCONNECTED) {
2502                 DBG(1, "Device not present")
2503                 up(&cam->fileop_sem);
2504                 return -ENODEV;
2505         }
2506
2507         if (cam->state & DEV_MISCONFIGURED) {
2508                 DBG(1, "The camera is misconfigured. Close and open it again.")
2509                 up(&cam->fileop_sem);
2510                 return -EIO;
2511         }
2512
2513         err = sn9c102_ioctl_v4l2(inode, filp, cmd, (void __user *)arg);
2514
2515         up(&cam->fileop_sem);
2516
2517         return err;
2518 }
2519
2520
2521 static struct file_operations sn9c102_fops = {
2522         .owner =   THIS_MODULE,
2523         .open =    sn9c102_open,
2524         .release = sn9c102_release,
2525         .ioctl =   sn9c102_ioctl,
2526         .read =    sn9c102_read,
2527         .poll =    sn9c102_poll,
2528         .mmap =    sn9c102_mmap,
2529         .llseek =  no_llseek,
2530 };
2531
2532 /*****************************************************************************/
2533
2534 /* It exists a single interface only. We do not need to validate anything. */
2535 static int
2536 sn9c102_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
2537 {
2538         struct usb_device *udev = interface_to_usbdev(intf);
2539         struct sn9c102_device* cam;
2540         static unsigned int dev_nr = 0;
2541         unsigned int i, n;
2542         int err = 0, r;
2543
2544         n = ARRAY_SIZE(sn9c102_id_table);
2545         for (i = 0; i < n-1; i++)
2546                 if (le16_to_cpu(udev->descriptor.idVendor) == 
2547                     sn9c102_id_table[i].idVendor &&
2548                     le16_to_cpu(udev->descriptor.idProduct) ==
2549                     sn9c102_id_table[i].idProduct)
2550                         break;
2551         if (i == n-1)
2552                 return -ENODEV;
2553
2554         if (!(cam = kmalloc(sizeof(struct sn9c102_device), GFP_KERNEL)))
2555                 return -ENOMEM;
2556         memset(cam, 0, sizeof(*cam));
2557
2558         cam->usbdev = udev;
2559
2560         memcpy(&cam->dev, &udev->dev, sizeof(struct device));
2561
2562         if (!(cam->control_buffer = kmalloc(8, GFP_KERNEL))) {
2563                 DBG(1, "kmalloc() failed")
2564                 err = -ENOMEM;
2565                 goto fail;
2566         }
2567         memset(cam->control_buffer, 0, 8);
2568
2569         if (!(cam->v4ldev = video_device_alloc())) {
2570                 DBG(1, "video_device_alloc() failed")
2571                 err = -ENOMEM;
2572                 goto fail;
2573         }
2574
2575         init_MUTEX(&cam->dev_sem);
2576
2577         r = sn9c102_read_reg(cam, 0x00);
2578         if (r < 0 || r != 0x10) {
2579                 DBG(1, "Sorry, this is not a SN9C10x based camera "
2580                        "(vid/pid 0x%04X/0x%04X)",
2581                     sn9c102_id_table[i].idVendor,sn9c102_id_table[i].idProduct)
2582                 err = -ENODEV;
2583                 goto fail;
2584         }
2585
2586         cam->bridge = (sn9c102_id_table[i].idProduct & 0xffc0) == 0x6080 ?
2587                       BRIDGE_SN9C103 : BRIDGE_SN9C102;
2588         switch (cam->bridge) {
2589         case BRIDGE_SN9C101:
2590         case BRIDGE_SN9C102:
2591                 DBG(2, "SN9C10[12] PC Camera Controller detected "
2592                        "(vid/pid 0x%04X/0x%04X)", sn9c102_id_table[i].idVendor,
2593                     sn9c102_id_table[i].idProduct)
2594                 break;
2595         case BRIDGE_SN9C103:
2596                 DBG(2, "SN9C103 PC Camera Controller detected "
2597                        "(vid/pid 0x%04X/0x%04X)", sn9c102_id_table[i].idVendor,
2598                     sn9c102_id_table[i].idProduct)
2599                 break;
2600         }
2601
2602         for  (i = 0; sn9c102_sensor_table[i]; i++) {
2603                 err = sn9c102_sensor_table[i](cam);
2604                 if (!err)
2605                         break;
2606         }
2607
2608         if (!err && cam->sensor) {
2609                 DBG(2, "%s image sensor detected", cam->sensor->name)
2610                 DBG(3, "Support for %s maintained by %s",
2611                     cam->sensor->name, cam->sensor->maintainer)
2612         } else {
2613                 DBG(1, "No supported image sensor detected")
2614                 err = -ENODEV;
2615                 goto fail;
2616         }
2617
2618         if (sn9c102_init(cam)) {
2619                 DBG(1, "Initialization failed. I will retry on open().")
2620                 cam->state |= DEV_MISCONFIGURED;
2621         }
2622
2623         strcpy(cam->v4ldev->name, "SN9C10x PC Camera");
2624         cam->v4ldev->owner = THIS_MODULE;
2625         cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
2626         cam->v4ldev->hardware = VID_HARDWARE_SN9C102;
2627         cam->v4ldev->fops = &sn9c102_fops;
2628         cam->v4ldev->minor = video_nr[dev_nr];
2629         cam->v4ldev->release = video_device_release;
2630         video_set_drvdata(cam->v4ldev, cam);
2631
2632         down(&cam->dev_sem);
2633
2634         err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
2635                                     video_nr[dev_nr]);
2636         if (err) {
2637                 DBG(1, "V4L2 device registration failed")
2638                 if (err == -ENFILE && video_nr[dev_nr] == -1)
2639                         DBG(1, "Free /dev/videoX node not found")
2640                 video_nr[dev_nr] = -1;
2641                 dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
2642                 up(&cam->dev_sem);
2643                 goto fail;
2644         }
2645
2646         DBG(2, "V4L2 device registered as /dev/video%d", cam->v4ldev->minor)
2647
2648         cam->module_param.force_munmap = force_munmap[dev_nr];
2649
2650         dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
2651
2652         sn9c102_create_sysfs(cam);
2653         DBG(2, "Optional device control through 'sysfs' interface ready")
2654
2655         usb_set_intfdata(intf, cam);
2656
2657         up(&cam->dev_sem);
2658
2659         return 0;
2660
2661 fail:
2662         if (cam) {
2663                 kfree(cam->control_buffer);
2664                 if (cam->v4ldev)
2665                         video_device_release(cam->v4ldev);
2666                 kfree(cam);
2667         }
2668         return err;
2669 }
2670
2671
2672 static void sn9c102_usb_disconnect(struct usb_interface* intf)
2673 {
2674         struct sn9c102_device* cam = usb_get_intfdata(intf);
2675
2676         if (!cam)
2677                 return;
2678
2679         down_write(&sn9c102_disconnect);
2680
2681         down(&cam->dev_sem); 
2682
2683         DBG(2, "Disconnecting %s...", cam->v4ldev->name)
2684
2685         wake_up_interruptible_all(&cam->open);
2686
2687         if (cam->users) {
2688                 DBG(2, "Device /dev/video%d is open! Deregistration and "
2689                        "memory deallocation are deferred on close.",
2690                     cam->v4ldev->minor)
2691                 cam->state |= DEV_MISCONFIGURED;
2692                 sn9c102_stop_transfer(cam);
2693                 cam->state |= DEV_DISCONNECTED;
2694                 wake_up_interruptible(&cam->wait_frame);
2695                 wake_up_interruptible(&cam->wait_stream);
2696         } else {
2697                 cam->state |= DEV_DISCONNECTED;
2698                 sn9c102_release_resources(cam);
2699         }
2700
2701         up(&cam->dev_sem);
2702
2703         if (!cam->users)
2704                 kfree(cam);
2705
2706         up_write(&sn9c102_disconnect);
2707 }
2708
2709
2710 static struct usb_driver sn9c102_usb_driver = {
2711         .name =       "sn9c102",
2712         .id_table =   sn9c102_id_table,
2713         .probe =      sn9c102_usb_probe,
2714         .disconnect = sn9c102_usb_disconnect,
2715 };
2716
2717 /*****************************************************************************/
2718
2719 static int __init sn9c102_module_init(void)
2720 {
2721         int err = 0;
2722
2723         KDBG(2, SN9C102_MODULE_NAME " v" SN9C102_MODULE_VERSION)
2724         KDBG(3, SN9C102_MODULE_AUTHOR)
2725
2726         if ((err = usb_register(&sn9c102_usb_driver)))
2727                 KDBG(1, "usb_register() failed")
2728
2729         return err;
2730 }
2731
2732
2733 static void __exit sn9c102_module_exit(void)
2734 {
2735         usb_deregister(&sn9c102_usb_driver);
2736 }
2737
2738
2739 module_init(sn9c102_module_init);
2740 module_exit(sn9c102_module_exit);