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