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