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