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