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