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