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