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