V4L/DVB (8815): gspca: Fix problems with disabled controls.
[safe/jmp/linux-2.6] / drivers / media / video / gspca / gspca.c
1 /*
2  * Main USB camera driver
3  *
4  * V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * 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 Foundation,
18  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #define MODULE_NAME "gspca"
22
23 #include <linux/init.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/sched.h>
27 #include <linux/slab.h>
28 #include <linux/mm.h>
29 #include <linux/string.h>
30 #include <linux/pagemap.h>
31 #include <linux/io.h>
32 #include <asm/page.h>
33 #include <linux/uaccess.h>
34 #include <linux/jiffies.h>
35 #include <media/v4l2-ioctl.h>
36
37 #include "gspca.h"
38
39 /* global values */
40 #define DEF_NURBS 2             /* default number of URBs */
41
42 MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>");
43 MODULE_DESCRIPTION("GSPCA USB Camera Driver");
44 MODULE_LICENSE("GPL");
45
46 #define DRIVER_VERSION_NUMBER   KERNEL_VERSION(2, 2, 0)
47
48 static int video_nr = -1;
49
50 #ifdef GSPCA_DEBUG
51 int gspca_debug = D_ERR | D_PROBE;
52 EXPORT_SYMBOL(gspca_debug);
53
54 static void PDEBUG_MODE(char *txt, __u32 pixfmt, int w, int h)
55 {
56         if ((pixfmt >> 24) >= '0' && (pixfmt >> 24) <= 'z') {
57                 PDEBUG(D_CONF|D_STREAM, "%s %c%c%c%c %dx%d",
58                         txt,
59                         pixfmt & 0xff,
60                         (pixfmt >> 8) & 0xff,
61                         (pixfmt >> 16) & 0xff,
62                         pixfmt >> 24,
63                         w, h);
64         } else {
65                 PDEBUG(D_CONF|D_STREAM, "%s 0x%08x %dx%d",
66                         txt,
67                         pixfmt,
68                         w, h);
69         }
70 }
71 #else
72 #define PDEBUG_MODE(txt, pixfmt, w, h)
73 #endif
74
75 /* specific memory types - !! should different from V4L2_MEMORY_xxx */
76 #define GSPCA_MEMORY_NO 0       /* V4L2_MEMORY_xxx starts from 1 */
77 #define GSPCA_MEMORY_READ 7
78
79 #define BUF_ALL_FLAGS (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE)
80
81 /*
82  * VMA operations.
83  */
84 static void gspca_vm_open(struct vm_area_struct *vma)
85 {
86         struct gspca_frame *frame = vma->vm_private_data;
87
88         frame->vma_use_count++;
89         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
90 }
91
92 static void gspca_vm_close(struct vm_area_struct *vma)
93 {
94         struct gspca_frame *frame = vma->vm_private_data;
95
96         if (--frame->vma_use_count <= 0)
97                 frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_MAPPED;
98 }
99
100 static struct vm_operations_struct gspca_vm_ops = {
101         .open           = gspca_vm_open,
102         .close          = gspca_vm_close,
103 };
104
105 /*
106  * fill a video frame from an URB and resubmit
107  */
108 static void fill_frame(struct gspca_dev *gspca_dev,
109                         struct urb *urb)
110 {
111         struct gspca_frame *frame;
112         __u8 *data;             /* address of data in the iso message */
113         int i, j, len, st;
114         cam_pkt_op pkt_scan;
115
116         if (urb->status != 0) {
117 #ifdef CONFIG_PM
118                 if (!gspca_dev->frozen)
119 #endif
120                         PDEBUG(D_ERR|D_PACK, "urb status: %d", urb->status);
121                 return;         /* disconnection ? */
122         }
123         pkt_scan = gspca_dev->sd_desc->pkt_scan;
124         for (i = 0; i < urb->number_of_packets; i++) {
125
126                 /* check the availability of the frame buffer */
127                 j = gspca_dev->fr_i;
128                 j = gspca_dev->fr_queue[j];
129                 frame = &gspca_dev->frame[j];
130                 if ((frame->v4l2_buf.flags & BUF_ALL_FLAGS)
131                                         != V4L2_BUF_FLAG_QUEUED) {
132                         gspca_dev->last_packet_type = DISCARD_PACKET;
133                         break;
134                 }
135
136                 /* check the packet status and length */
137                 len = urb->iso_frame_desc[i].actual_length;
138                 if (len == 0)
139                         continue;
140                 st = urb->iso_frame_desc[i].status;
141                 if (st) {
142                         PDEBUG(D_ERR,
143                                 "ISOC data error: [%d] len=%d, status=%d",
144                                 i, len, st);
145                         gspca_dev->last_packet_type = DISCARD_PACKET;
146                         continue;
147                 }
148
149                 /* let the packet be analyzed by the subdriver */
150                 PDEBUG(D_PACK, "packet [%d] o:%d l:%d",
151                         i, urb->iso_frame_desc[i].offset, len);
152                 data = (__u8 *) urb->transfer_buffer
153                                         + urb->iso_frame_desc[i].offset;
154                 pkt_scan(gspca_dev, frame, data, len);
155         }
156
157         /* resubmit the URB */
158         urb->status = 0;
159         st = usb_submit_urb(urb, GFP_ATOMIC);
160         if (st < 0)
161                 PDEBUG(D_ERR|D_PACK, "usb_submit_urb() ret %d", st);
162 }
163
164 /*
165  * ISOC message interrupt from the USB device
166  *
167  * Analyse each packet and call the subdriver for copy to the frame buffer.
168  */
169 static void isoc_irq(struct urb *urb
170 )
171 {
172         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
173
174         PDEBUG(D_PACK, "isoc irq");
175         if (!gspca_dev->streaming)
176                 return;
177         fill_frame(gspca_dev, urb);
178 }
179
180 /*
181  * add data to the current frame
182  *
183  * This function is called by the subdrivers at interrupt level.
184  *
185  * To build a frame, these ones must add
186  *      - one FIRST_PACKET
187  *      - 0 or many INTER_PACKETs
188  *      - one LAST_PACKET
189  * DISCARD_PACKET invalidates the whole frame.
190  * On LAST_PACKET, a new frame is returned.
191  */
192 struct gspca_frame *gspca_frame_add(struct gspca_dev *gspca_dev,
193                                     int packet_type,
194                                     struct gspca_frame *frame,
195                                     const __u8 *data,
196                                     int len)
197 {
198         int i, j;
199
200         PDEBUG(D_PACK, "add t:%d l:%d", packet_type, len);
201
202         /* when start of a new frame, if the current frame buffer
203          * is not queued, discard the whole frame */
204         if (packet_type == FIRST_PACKET) {
205                 if ((frame->v4l2_buf.flags & BUF_ALL_FLAGS)
206                                                 != V4L2_BUF_FLAG_QUEUED) {
207                         gspca_dev->last_packet_type = DISCARD_PACKET;
208                         return frame;
209                 }
210                 frame->data_end = frame->data;
211                 jiffies_to_timeval(get_jiffies_64(),
212                                    &frame->v4l2_buf.timestamp);
213                 frame->v4l2_buf.sequence = ++gspca_dev->sequence;
214         } else if (gspca_dev->last_packet_type == DISCARD_PACKET) {
215                 if (packet_type == LAST_PACKET)
216                         gspca_dev->last_packet_type = packet_type;
217                 return frame;
218         }
219
220         /* append the packet to the frame buffer */
221         if (len > 0) {
222                 if (frame->data_end - frame->data + len
223                                                  > frame->v4l2_buf.length) {
224                         PDEBUG(D_ERR|D_PACK, "frame overflow %zd > %d",
225                                 frame->data_end - frame->data + len,
226                                 frame->v4l2_buf.length);
227                         packet_type = DISCARD_PACKET;
228                 } else {
229                         memcpy(frame->data_end, data, len);
230                         frame->data_end += len;
231                 }
232         }
233         gspca_dev->last_packet_type = packet_type;
234
235         /* if last packet, wake the application and advance in the queue */
236         if (packet_type == LAST_PACKET) {
237                 frame->v4l2_buf.bytesused = frame->data_end - frame->data;
238                 frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_QUEUED;
239                 frame->v4l2_buf.flags |= V4L2_BUF_FLAG_DONE;
240                 atomic_inc(&gspca_dev->nevent);
241                 wake_up_interruptible(&gspca_dev->wq);  /* event = new frame */
242                 i = (gspca_dev->fr_i + 1) % gspca_dev->nframes;
243                 gspca_dev->fr_i = i;
244                 PDEBUG(D_FRAM, "frame complete len:%d q:%d i:%d o:%d",
245                         frame->v4l2_buf.bytesused,
246                         gspca_dev->fr_q,
247                         i,
248                         gspca_dev->fr_o);
249                 j = gspca_dev->fr_queue[i];
250                 frame = &gspca_dev->frame[j];
251         }
252         return frame;
253 }
254 EXPORT_SYMBOL(gspca_frame_add);
255
256 static int gspca_is_compressed(__u32 format)
257 {
258         switch (format) {
259         case V4L2_PIX_FMT_MJPEG:
260         case V4L2_PIX_FMT_JPEG:
261         case V4L2_PIX_FMT_SPCA561:
262         case V4L2_PIX_FMT_PAC207:
263                 return 1;
264         }
265         return 0;
266 }
267
268 static void *rvmalloc(unsigned long size)
269 {
270         void *mem;
271         unsigned long adr;
272
273 /*      size = PAGE_ALIGN(size);        (already done) */
274         mem = vmalloc_32(size);
275         if (mem != NULL) {
276                 adr = (unsigned long) mem;
277                 while ((long) size > 0) {
278                         SetPageReserved(vmalloc_to_page((void *) adr));
279                         adr += PAGE_SIZE;
280                         size -= PAGE_SIZE;
281                 }
282         }
283         return mem;
284 }
285
286 static void rvfree(void *mem, long size)
287 {
288         unsigned long adr;
289
290         adr = (unsigned long) mem;
291         while (size > 0) {
292                 ClearPageReserved(vmalloc_to_page((void *) adr));
293                 adr += PAGE_SIZE;
294                 size -= PAGE_SIZE;
295         }
296         vfree(mem);
297 }
298
299 static int frame_alloc(struct gspca_dev *gspca_dev,
300                         unsigned int count)
301 {
302         struct gspca_frame *frame;
303         unsigned int frsz;
304         int i;
305
306         i = gspca_dev->curr_mode;
307         frsz = gspca_dev->cam.cam_mode[i].sizeimage;
308         PDEBUG(D_STREAM, "frame alloc frsz: %d", frsz);
309         frsz = PAGE_ALIGN(frsz);
310         gspca_dev->frsz = frsz;
311         if (count > GSPCA_MAX_FRAMES)
312                 count = GSPCA_MAX_FRAMES;
313         gspca_dev->frbuf = rvmalloc(frsz * count);
314         if (!gspca_dev->frbuf) {
315                 err("frame alloc failed");
316                 return -ENOMEM;
317         }
318         gspca_dev->nframes = count;
319         for (i = 0; i < count; i++) {
320                 frame = &gspca_dev->frame[i];
321                 frame->v4l2_buf.index = i;
322                 frame->v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
323                 frame->v4l2_buf.flags = 0;
324                 frame->v4l2_buf.field = V4L2_FIELD_NONE;
325                 frame->v4l2_buf.length = frsz;
326                 frame->v4l2_buf.memory = gspca_dev->memory;
327                 frame->v4l2_buf.sequence = 0;
328                 frame->data = frame->data_end =
329                                         gspca_dev->frbuf + i * frsz;
330                 frame->v4l2_buf.m.offset = i * frsz;
331         }
332         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
333         gspca_dev->last_packet_type = DISCARD_PACKET;
334         gspca_dev->sequence = 0;
335         atomic_set(&gspca_dev->nevent, 0);
336         return 0;
337 }
338
339 static void frame_free(struct gspca_dev *gspca_dev)
340 {
341         int i;
342
343         PDEBUG(D_STREAM, "frame free");
344         if (gspca_dev->frbuf != NULL) {
345                 rvfree(gspca_dev->frbuf,
346                         gspca_dev->nframes * gspca_dev->frsz);
347                 gspca_dev->frbuf = NULL;
348                 for (i = 0; i < gspca_dev->nframes; i++)
349                         gspca_dev->frame[i].data = NULL;
350         }
351         gspca_dev->nframes = 0;
352 }
353
354 static void destroy_urbs(struct gspca_dev *gspca_dev)
355 {
356         struct urb *urb;
357         unsigned int i;
358
359         PDEBUG(D_STREAM, "kill transfer");
360         for (i = 0; i < MAX_NURBS; ++i) {
361                 urb = gspca_dev->urb[i];
362                 if (urb == NULL)
363                         break;
364
365                 gspca_dev->urb[i] = NULL;
366                 usb_kill_urb(urb);
367                 if (urb->transfer_buffer != NULL)
368                         usb_buffer_free(gspca_dev->dev,
369                                         urb->transfer_buffer_length,
370                                         urb->transfer_buffer,
371                                         urb->transfer_dma);
372                 usb_free_urb(urb);
373         }
374 }
375
376 /*
377  * search an input isochronous endpoint in an alternate setting
378  */
379 static struct usb_host_endpoint *alt_isoc(struct usb_host_interface *alt,
380                                           __u8 epaddr)
381 {
382         struct usb_host_endpoint *ep;
383         int i, attr;
384
385         epaddr |= USB_DIR_IN;
386         for (i = 0; i < alt->desc.bNumEndpoints; i++) {
387                 ep = &alt->endpoint[i];
388                 if (ep->desc.bEndpointAddress == epaddr) {
389                         attr = ep->desc.bmAttributes
390                                                 & USB_ENDPOINT_XFERTYPE_MASK;
391                         if (attr == USB_ENDPOINT_XFER_ISOC)
392                                 return ep;
393                         break;
394                 }
395         }
396         return NULL;
397 }
398
399 /*
400  * search an input isochronous endpoint
401  *
402  * The endpoint is defined by the subdriver.
403  * Use only the first isoc (some Zoran - 0x0572:0x0001 - have two such ep).
404  * This routine may be called many times when the bandwidth is too small
405  * (the bandwidth is checked on urb submit).
406  */
407 static struct usb_host_endpoint *get_isoc_ep(struct gspca_dev *gspca_dev)
408 {
409         struct usb_interface *intf;
410         struct usb_host_endpoint *ep;
411         int i, ret;
412
413         intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
414         ep = NULL;
415         i = gspca_dev->alt;                     /* previous alt setting */
416         while (--i > 0) {                       /* alt 0 is unusable */
417                 ep = alt_isoc(&intf->altsetting[i], gspca_dev->cam.epaddr);
418                 if (ep)
419                         break;
420         }
421         if (ep == NULL) {
422                 err("no ISOC endpoint found");
423                 return NULL;
424         }
425         PDEBUG(D_STREAM, "use ISOC alt %d ep 0x%02x",
426                         i, ep->desc.bEndpointAddress);
427         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, i);
428         if (ret < 0) {
429                 err("set interface err %d", ret);
430                 return NULL;
431         }
432         gspca_dev->alt = i;             /* memorize the current alt setting */
433         return ep;
434 }
435
436 /*
437  * create the isochronous URBs
438  */
439 static int create_urbs(struct gspca_dev *gspca_dev,
440                         struct usb_host_endpoint *ep)
441 {
442         struct urb *urb;
443         int n, nurbs, i, psize, npkt, bsize;
444
445         /* calculate the packet size and the number of packets */
446         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
447
448         /* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
449         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
450         npkt = ISO_MAX_SIZE / psize;
451         if (npkt > ISO_MAX_PKT)
452                 npkt = ISO_MAX_PKT;
453         bsize = psize * npkt;
454         PDEBUG(D_STREAM,
455                 "isoc %d pkts size %d (bsize:%d)", npkt, psize, bsize);
456         nurbs = DEF_NURBS;
457         gspca_dev->nurbs = nurbs;
458         for (n = 0; n < nurbs; n++) {
459                 urb = usb_alloc_urb(npkt, GFP_KERNEL);
460                 if (!urb) {
461                         err("usb_alloc_urb failed");
462                         return -ENOMEM;
463                 }
464                 urb->transfer_buffer = usb_buffer_alloc(gspca_dev->dev,
465                                                 bsize,
466                                                 GFP_KERNEL,
467                                                 &urb->transfer_dma);
468
469                 if (urb->transfer_buffer == NULL) {
470                         usb_free_urb(urb);
471                         destroy_urbs(gspca_dev);
472                         err("usb_buffer_urb failed");
473                         return -ENOMEM;
474                 }
475                 gspca_dev->urb[n] = urb;
476                 urb->dev = gspca_dev->dev;
477                 urb->context = gspca_dev;
478                 urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
479                                             ep->desc.bEndpointAddress);
480                 urb->transfer_flags = URB_ISO_ASAP
481                                         | URB_NO_TRANSFER_DMA_MAP;
482                 urb->interval = ep->desc.bInterval;
483                 urb->complete = isoc_irq;
484                 urb->number_of_packets = npkt;
485                 urb->transfer_buffer_length = bsize;
486                 for (i = 0; i < npkt; i++) {
487                         urb->iso_frame_desc[i].length = psize;
488                         urb->iso_frame_desc[i].offset = psize * i;
489                 }
490         }
491         return 0;
492 }
493
494 /*
495  * start the USB transfer
496  */
497 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
498 {
499         struct usb_host_endpoint *ep;
500         int n, ret;
501
502         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
503                 return -ERESTARTSYS;
504
505         /* set the higher alternate setting and
506          * loop until urb submit succeeds */
507         gspca_dev->alt = gspca_dev->nbalt;
508         for (;;) {
509                 PDEBUG(D_STREAM, "init transfer alt %d", gspca_dev->alt);
510                 ep = get_isoc_ep(gspca_dev);
511                 if (ep == NULL) {
512                         ret = -EIO;
513                         goto out;
514                 }
515                 ret = create_urbs(gspca_dev, ep);
516                 if (ret < 0)
517                         goto out;
518
519                 /* start the cam */
520                 gspca_dev->sd_desc->start(gspca_dev);
521                 gspca_dev->streaming = 1;
522                 atomic_set(&gspca_dev->nevent, 0);
523
524                 /* submit the URBs */
525                 for (n = 0; n < gspca_dev->nurbs; n++) {
526                         ret = usb_submit_urb(gspca_dev->urb[n], GFP_KERNEL);
527                         if (ret < 0) {
528                                 PDEBUG(D_ERR|D_STREAM,
529                                         "usb_submit_urb [%d] err %d", n, ret);
530                                 gspca_dev->streaming = 0;
531                                 destroy_urbs(gspca_dev);
532                                 if (ret == -ENOSPC)
533                                         break;  /* try the previous alt */
534                                 goto out;
535                         }
536                 }
537                 if (ret >= 0)
538                         break;
539         }
540 out:
541         mutex_unlock(&gspca_dev->usb_lock);
542         return ret;
543 }
544
545 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
546 {
547         int ret;
548
549         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
550         if (ret < 0)
551                 PDEBUG(D_ERR|D_STREAM, "set interface 0 err %d", ret);
552         return ret;
553 }
554
555 /* Note both the queue and the usb lock should be hold when calling this */
556 static void gspca_stream_off(struct gspca_dev *gspca_dev)
557 {
558         gspca_dev->streaming = 0;
559         atomic_set(&gspca_dev->nevent, 0);
560         if (gspca_dev->present) {
561                 gspca_dev->sd_desc->stopN(gspca_dev);
562                 destroy_urbs(gspca_dev);
563                 gspca_set_alt0(gspca_dev);
564                 gspca_dev->sd_desc->stop0(gspca_dev);
565                 PDEBUG(D_STREAM, "stream off OK");
566         }
567 }
568
569 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
570 {
571         int i;
572
573         i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
574         gspca_dev->curr_mode = i;
575         gspca_dev->width = gspca_dev->cam.cam_mode[i].width;
576         gspca_dev->height = gspca_dev->cam.cam_mode[i].height;
577         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixelformat;
578 }
579
580 static int wxh_to_mode(struct gspca_dev *gspca_dev,
581                         int width, int height)
582 {
583         int i;
584
585         for (i = gspca_dev->cam.nmodes; --i > 0; ) {
586                 if (width >= gspca_dev->cam.cam_mode[i].width
587                     && height >= gspca_dev->cam.cam_mode[i].height)
588                         break;
589         }
590         return i;
591 }
592
593 /*
594  * search a mode with the right pixel format
595  */
596 static int gspca_get_mode(struct gspca_dev *gspca_dev,
597                         int mode,
598                         int pixfmt)
599 {
600         int modeU, modeD;
601
602         modeU = modeD = mode;
603         while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
604                 if (--modeD >= 0) {
605                         if (gspca_dev->cam.cam_mode[modeD].pixelformat
606                                                                 == pixfmt)
607                                 return modeD;
608                 }
609                 if (++modeU < gspca_dev->cam.nmodes) {
610                         if (gspca_dev->cam.cam_mode[modeU].pixelformat
611                                                                 == pixfmt)
612                                 return modeU;
613                 }
614         }
615         return -EINVAL;
616 }
617
618 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
619                                 struct v4l2_fmtdesc *fmtdesc)
620 {
621         struct gspca_dev *gspca_dev = priv;
622         int i, j, index;
623         __u32 fmt_tb[8];
624
625         /* give an index to each format */
626         index = 0;
627         j = 0;
628         for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
629                 fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
630                 j = 0;
631                 for (;;) {
632                         if (fmt_tb[j] == fmt_tb[index])
633                                 break;
634                         j++;
635                 }
636                 if (j == index) {
637                         if (fmtdesc->index == index)
638                                 break;          /* new format */
639                         index++;
640                         if (index >= sizeof fmt_tb / sizeof fmt_tb[0])
641                                 return -EINVAL;
642                 }
643         }
644         if (i < 0)
645                 return -EINVAL;         /* no more format */
646
647         fmtdesc->pixelformat = fmt_tb[index];
648         if (gspca_is_compressed(fmt_tb[index]))
649                 fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
650         fmtdesc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
651         fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
652         fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
653         fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
654         fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
655         fmtdesc->description[4] = '\0';
656         return 0;
657 }
658
659 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
660                             struct v4l2_format *fmt)
661 {
662         struct gspca_dev *gspca_dev = priv;
663         int mode;
664
665         if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
666                 return -EINVAL;
667         mode = gspca_dev->curr_mode;
668         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
669                 sizeof fmt->fmt.pix);
670         return 0;
671 }
672
673 static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
674                         struct v4l2_format *fmt)
675 {
676         int w, h, mode, mode2;
677
678         if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
679                 return -EINVAL;
680         w = fmt->fmt.pix.width;
681         h = fmt->fmt.pix.height;
682
683 #ifdef GSPCA_DEBUG
684         if (gspca_debug & D_CONF)
685                 PDEBUG_MODE("try fmt cap", fmt->fmt.pix.pixelformat, w, h);
686 #endif
687         /* search the closest mode for width and height */
688         mode = wxh_to_mode(gspca_dev, w, h);
689
690         /* OK if right palette */
691         if (gspca_dev->cam.cam_mode[mode].pixelformat
692                                                 != fmt->fmt.pix.pixelformat) {
693
694                 /* else, search the closest mode with the same pixel format */
695                 mode2 = gspca_get_mode(gspca_dev, mode,
696                                         fmt->fmt.pix.pixelformat);
697                 if (mode2 >= 0)
698                         mode = mode2;
699 /*              else
700                         ;                * no chance, return this mode */
701         }
702         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
703                 sizeof fmt->fmt.pix);
704         return mode;                    /* used when s_fmt */
705 }
706
707 static int vidioc_try_fmt_vid_cap(struct file *file,
708                               void *priv,
709                               struct v4l2_format *fmt)
710 {
711         struct gspca_dev *gspca_dev = priv;
712         int ret;
713
714         ret = try_fmt_vid_cap(gspca_dev, fmt);
715         if (ret < 0)
716                 return ret;
717         return 0;
718 }
719
720 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
721                             struct v4l2_format *fmt)
722 {
723         struct gspca_dev *gspca_dev = priv;
724         int ret;
725
726         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
727                 return -ERESTARTSYS;
728
729         ret = try_fmt_vid_cap(gspca_dev, fmt);
730         if (ret < 0)
731                 goto out;
732
733         if (gspca_dev->nframes != 0
734             && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
735                 ret = -EINVAL;
736                 goto out;
737         }
738
739         if (ret == gspca_dev->curr_mode) {
740                 ret = 0;
741                 goto out;                       /* same mode */
742         }
743
744         if (gspca_dev->streaming) {
745                 ret = -EBUSY;
746                 goto out;
747         }
748         gspca_dev->width = fmt->fmt.pix.width;
749         gspca_dev->height = fmt->fmt.pix.height;
750         gspca_dev->pixfmt = fmt->fmt.pix.pixelformat;
751         gspca_dev->curr_mode = ret;
752
753         ret = 0;
754 out:
755         mutex_unlock(&gspca_dev->queue_lock);
756         return ret;
757 }
758
759 static int dev_open(struct inode *inode, struct file *file)
760 {
761         struct gspca_dev *gspca_dev;
762         int ret;
763
764         PDEBUG(D_STREAM, "%s open", current->comm);
765         gspca_dev = (struct gspca_dev *) video_devdata(file);
766         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
767                 return -ERESTARTSYS;
768         if (!gspca_dev->present) {
769                 ret = -ENODEV;
770                 goto out;
771         }
772
773         /* if not done yet, initialize the sensor */
774         if (gspca_dev->users == 0) {
775                 if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
776                         ret = -ERESTARTSYS;
777                         goto out;
778                 }
779                 ret = gspca_dev->sd_desc->open(gspca_dev);
780                 mutex_unlock(&gspca_dev->usb_lock);
781                 if (ret != 0) {
782                         PDEBUG(D_ERR|D_CONF, "init device failed %d", ret);
783                         goto out;
784                 }
785         } else if (gspca_dev->users > 4) {      /* (arbitrary value) */
786                 ret = -EBUSY;
787                 goto out;
788         }
789         gspca_dev->users++;
790         file->private_data = gspca_dev;
791 #ifdef GSPCA_DEBUG
792         /* activate the v4l2 debug */
793         if (gspca_debug & D_V4L2)
794                 gspca_dev->vdev.debug |= 3;
795         else
796                 gspca_dev->vdev.debug &= ~3;
797 #endif
798 out:
799         mutex_unlock(&gspca_dev->queue_lock);
800         if (ret != 0)
801                 PDEBUG(D_ERR|D_STREAM, "open failed err %d", ret);
802         else
803                 PDEBUG(D_STREAM, "open done");
804         return ret;
805 }
806
807 static int dev_close(struct inode *inode, struct file *file)
808 {
809         struct gspca_dev *gspca_dev = file->private_data;
810
811         PDEBUG(D_STREAM, "%s close", current->comm);
812         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
813                 return -ERESTARTSYS;
814         gspca_dev->users--;
815
816         /* if the file did the capture, free the streaming resources */
817         if (gspca_dev->capt_file == file) {
818                 mutex_lock(&gspca_dev->usb_lock);
819                 if (gspca_dev->streaming)
820                         gspca_stream_off(gspca_dev);
821                 gspca_dev->sd_desc->close(gspca_dev);
822                 mutex_unlock(&gspca_dev->usb_lock);
823                 frame_free(gspca_dev);
824                 gspca_dev->capt_file = NULL;
825                 gspca_dev->memory = GSPCA_MEMORY_NO;
826         }
827         file->private_data = NULL;
828         mutex_unlock(&gspca_dev->queue_lock);
829         PDEBUG(D_STREAM, "close done");
830         return 0;
831 }
832
833 static int vidioc_querycap(struct file *file, void  *priv,
834                            struct v4l2_capability *cap)
835 {
836         struct gspca_dev *gspca_dev = priv;
837
838         memset(cap, 0, sizeof *cap);
839         strncpy(cap->driver, gspca_dev->sd_desc->name, sizeof cap->driver);
840 /*      strncpy(cap->card, gspca_dev->cam.dev_name, sizeof cap->card); */
841         if (gspca_dev->dev->product != NULL) {
842                 strncpy(cap->card, gspca_dev->dev->product,
843                         sizeof cap->card);
844         } else {
845                 snprintf(cap->card, sizeof cap->card,
846                         "USB Camera (%04x:%04x)",
847                         le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
848                         le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
849         }
850         strncpy(cap->bus_info, gspca_dev->dev->bus->bus_name,
851                 sizeof cap->bus_info);
852         cap->version = DRIVER_VERSION_NUMBER;
853         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
854                           | V4L2_CAP_STREAMING
855                           | V4L2_CAP_READWRITE;
856         return 0;
857 }
858
859 static int vidioc_queryctrl(struct file *file, void *priv,
860                            struct v4l2_queryctrl *q_ctrl)
861 {
862         struct gspca_dev *gspca_dev = priv;
863         int i, ix;
864         u32 id;
865
866         ix = -1;
867         id = q_ctrl->id;
868         if (id & V4L2_CTRL_FLAG_NEXT_CTRL) {
869                 id &= V4L2_CTRL_ID_MASK;
870                 id++;
871                 for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
872                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id < id)
873                                 continue;
874                         if (ix < 0) {
875                                 ix = i;
876                                 continue;
877                         }
878                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id
879                                     > gspca_dev->sd_desc->ctrls[ix].qctrl.id)
880                                 continue;
881                         ix = i;
882                 }
883         }
884         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
885                 if (id == gspca_dev->sd_desc->ctrls[i].qctrl.id) {
886                         ix = i;
887                         break;
888                 }
889         }
890         if (ix < 0)
891                 return -EINVAL;
892         memcpy(q_ctrl, &gspca_dev->sd_desc->ctrls[ix].qctrl,
893                 sizeof *q_ctrl);
894         if (gspca_dev->ctrl_dis & (1 << ix))
895                 q_ctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
896         return 0;
897 }
898
899 static int vidioc_s_ctrl(struct file *file, void *priv,
900                          struct v4l2_control *ctrl)
901 {
902         struct gspca_dev *gspca_dev = priv;
903         const struct ctrl *ctrls;
904         int i, ret;
905
906         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
907              i < gspca_dev->sd_desc->nctrls;
908              i++, ctrls++) {
909                 if (ctrl->id != ctrls->qctrl.id)
910                         continue;
911                 if (gspca_dev->ctrl_dis & (1 << i))
912                         return -EINVAL;
913                 if (ctrl->value < ctrls->qctrl.minimum
914                     || ctrl->value > ctrls->qctrl.maximum)
915                         return -ERANGE;
916                 PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
917                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
918                         return -ERESTARTSYS;
919                 ret = ctrls->set(gspca_dev, ctrl->value);
920                 mutex_unlock(&gspca_dev->usb_lock);
921                 return ret;
922         }
923         return -EINVAL;
924 }
925
926 static int vidioc_g_ctrl(struct file *file, void *priv,
927                          struct v4l2_control *ctrl)
928 {
929         struct gspca_dev *gspca_dev = priv;
930
931         const struct ctrl *ctrls;
932         int i, ret;
933
934         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
935              i < gspca_dev->sd_desc->nctrls;
936              i++, ctrls++) {
937                 if (ctrl->id != ctrls->qctrl.id)
938                         continue;
939                 if (gspca_dev->ctrl_dis & (1 << i))
940                         return -EINVAL;
941                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
942                         return -ERESTARTSYS;
943                 ret = ctrls->get(gspca_dev, &ctrl->value);
944                 mutex_unlock(&gspca_dev->usb_lock);
945                 return ret;
946         }
947         return -EINVAL;
948 }
949
950 static int vidioc_querymenu(struct file *file, void *priv,
951                             struct v4l2_querymenu *qmenu)
952 {
953         struct gspca_dev *gspca_dev = priv;
954
955         if (!gspca_dev->sd_desc->querymenu)
956                 return -EINVAL;
957         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
958 }
959
960 static int vidioc_enum_input(struct file *file, void *priv,
961                                 struct v4l2_input *input)
962 {
963         struct gspca_dev *gspca_dev = priv;
964
965         if (input->index != 0)
966                 return -EINVAL;
967         memset(input, 0, sizeof *input);
968         input->type = V4L2_INPUT_TYPE_CAMERA;
969         strncpy(input->name, gspca_dev->sd_desc->name,
970                 sizeof input->name);
971         return 0;
972 }
973
974 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
975 {
976         *i = 0;
977         return 0;
978 }
979
980 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
981 {
982         if (i > 0)
983                 return -EINVAL;
984         return (0);
985 }
986
987 static int vidioc_reqbufs(struct file *file, void *priv,
988                           struct v4l2_requestbuffers *rb)
989 {
990         struct gspca_dev *gspca_dev = priv;
991         int i, ret = 0;
992
993         if (rb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
994                 return -EINVAL;
995         switch (rb->memory) {
996         case GSPCA_MEMORY_READ:                 /* (internal call) */
997         case V4L2_MEMORY_MMAP:
998         case V4L2_MEMORY_USERPTR:
999                 break;
1000         default:
1001                 return -EINVAL;
1002         }
1003         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1004                 return -ERESTARTSYS;
1005
1006         if (gspca_dev->memory != GSPCA_MEMORY_NO
1007             && gspca_dev->memory != rb->memory) {
1008                 ret = -EBUSY;
1009                 goto out;
1010         }
1011
1012         /* only one file may do the capture */
1013         if (gspca_dev->capt_file != NULL
1014             && gspca_dev->capt_file != file) {
1015                 ret = -EBUSY;
1016                 goto out;
1017         }
1018
1019         /* if allocated, the buffers must not be mapped */
1020         for (i = 0; i < gspca_dev->nframes; i++) {
1021                 if (gspca_dev->frame[i].vma_use_count) {
1022                         ret = -EBUSY;
1023                         goto out;
1024                 }
1025         }
1026
1027         /* stop streaming */
1028         if (gspca_dev->streaming) {
1029                 mutex_lock(&gspca_dev->usb_lock);
1030                 gspca_stream_off(gspca_dev);
1031                 mutex_unlock(&gspca_dev->usb_lock);
1032         }
1033
1034         /* free the previous allocated buffers, if any */
1035         if (gspca_dev->nframes != 0) {
1036                 frame_free(gspca_dev);
1037                 gspca_dev->capt_file = NULL;
1038         }
1039         if (rb->count == 0)                     /* unrequest */
1040                 goto out;
1041         gspca_dev->memory = rb->memory;
1042         ret = frame_alloc(gspca_dev, rb->count);
1043         if (ret == 0) {
1044                 rb->count = gspca_dev->nframes;
1045                 gspca_dev->capt_file = file;
1046         }
1047 out:
1048         mutex_unlock(&gspca_dev->queue_lock);
1049         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1050         return ret;
1051 }
1052
1053 static int vidioc_querybuf(struct file *file, void *priv,
1054                            struct v4l2_buffer *v4l2_buf)
1055 {
1056         struct gspca_dev *gspca_dev = priv;
1057         struct gspca_frame *frame;
1058
1059         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1060             || v4l2_buf->index < 0
1061             || v4l2_buf->index >= gspca_dev->nframes)
1062                 return -EINVAL;
1063
1064         frame = &gspca_dev->frame[v4l2_buf->index];
1065         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1066         return 0;
1067 }
1068
1069 static int vidioc_streamon(struct file *file, void *priv,
1070                            enum v4l2_buf_type buf_type)
1071 {
1072         struct gspca_dev *gspca_dev = priv;
1073         int ret;
1074
1075         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1076                 return -EINVAL;
1077         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1078                 return -ERESTARTSYS;
1079         if (!gspca_dev->present) {
1080                 ret = -ENODEV;
1081                 goto out;
1082         }
1083         if (gspca_dev->nframes == 0) {
1084                 ret = -EINVAL;
1085                 goto out;
1086         }
1087         if (!gspca_dev->streaming) {
1088                 ret = gspca_init_transfer(gspca_dev);
1089                 if (ret < 0)
1090                         goto out;
1091         }
1092 #ifdef GSPCA_DEBUG
1093         if (gspca_debug & D_STREAM) {
1094                 PDEBUG_MODE("stream on OK",
1095                         gspca_dev->pixfmt,
1096                         gspca_dev->width,
1097                         gspca_dev->height);
1098         }
1099 #endif
1100         ret = 0;
1101 out:
1102         mutex_unlock(&gspca_dev->queue_lock);
1103         return ret;
1104 }
1105
1106 static int vidioc_streamoff(struct file *file, void *priv,
1107                                 enum v4l2_buf_type buf_type)
1108 {
1109         struct gspca_dev *gspca_dev = priv;
1110         int i, ret;
1111
1112         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1113                 return -EINVAL;
1114         if (!gspca_dev->streaming)
1115                 return 0;
1116         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1117                 return -ERESTARTSYS;
1118
1119         /* stop streaming */
1120         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1121                 ret = -ERESTARTSYS;
1122                 goto out;
1123         }
1124         gspca_stream_off(gspca_dev);
1125         mutex_unlock(&gspca_dev->usb_lock);
1126
1127         /* empty the application queues */
1128         for (i = 0; i < gspca_dev->nframes; i++)
1129                 gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1130         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
1131         gspca_dev->last_packet_type = DISCARD_PACKET;
1132         gspca_dev->sequence = 0;
1133         atomic_set(&gspca_dev->nevent, 0);
1134         ret = 0;
1135 out:
1136         mutex_unlock(&gspca_dev->queue_lock);
1137         return ret;
1138 }
1139
1140 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1141                         struct v4l2_jpegcompression *jpegcomp)
1142 {
1143         struct gspca_dev *gspca_dev = priv;
1144         int ret;
1145
1146         if (!gspca_dev->sd_desc->get_jcomp)
1147                 return -EINVAL;
1148         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1149                 return -ERESTARTSYS;
1150         ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1151         mutex_unlock(&gspca_dev->usb_lock);
1152         return ret;
1153 }
1154
1155 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1156                         struct v4l2_jpegcompression *jpegcomp)
1157 {
1158         struct gspca_dev *gspca_dev = priv;
1159         int ret;
1160
1161         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1162                 return -ERESTARTSYS;
1163         if (!gspca_dev->sd_desc->set_jcomp)
1164                 return -EINVAL;
1165         ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1166         mutex_unlock(&gspca_dev->usb_lock);
1167         return ret;
1168 }
1169
1170 static int vidioc_g_parm(struct file *filp, void *priv,
1171                         struct v4l2_streamparm *parm)
1172 {
1173         struct gspca_dev *gspca_dev = priv;
1174
1175         memset(parm, 0, sizeof *parm);
1176         parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1177         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1178         return 0;
1179 }
1180
1181 static int vidioc_s_parm(struct file *filp, void *priv,
1182                         struct v4l2_streamparm *parm)
1183 {
1184         struct gspca_dev *gspca_dev = priv;
1185         int n;
1186
1187         n = parm->parm.capture.readbuffers;
1188         if (n == 0 || n > GSPCA_MAX_FRAMES)
1189                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1190         else
1191                 gspca_dev->nbufread = n;
1192         return 0;
1193 }
1194
1195 static int vidioc_s_std(struct file *filp, void *priv,
1196                         v4l2_std_id *parm)
1197 {
1198         return 0;
1199 }
1200
1201 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1202 static int vidiocgmbuf(struct file *file, void *priv,
1203                         struct video_mbuf *mbuf)
1204 {
1205         struct gspca_dev *gspca_dev = file->private_data;
1206         int i;
1207
1208         PDEBUG(D_STREAM, "cgmbuf");
1209         if (gspca_dev->nframes == 0) {
1210                 int ret;
1211
1212                 {
1213                         struct v4l2_format fmt;
1214
1215                         memset(&fmt, 0, sizeof fmt);
1216                         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1217                         i = gspca_dev->cam.nmodes - 1;  /* highest mode */
1218                         fmt.fmt.pix.width = gspca_dev->cam.cam_mode[i].width;
1219                         fmt.fmt.pix.height = gspca_dev->cam.cam_mode[i].height;
1220                         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_BGR24;
1221                         ret = vidioc_s_fmt_vid_cap(file, priv, &fmt);
1222                         if (ret != 0)
1223                                 return ret;
1224                 }
1225                 {
1226                         struct v4l2_requestbuffers rb;
1227
1228                         memset(&rb, 0, sizeof rb);
1229                         rb.count = 4;
1230                         rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1231                         rb.memory = V4L2_MEMORY_MMAP;
1232                         ret = vidioc_reqbufs(file, priv, &rb);
1233                         if (ret != 0)
1234                                 return ret;
1235                 }
1236         }
1237         mbuf->frames = gspca_dev->nframes;
1238         mbuf->size = gspca_dev->frsz * gspca_dev->nframes;
1239         for (i = 0; i < mbuf->frames; i++)
1240                 mbuf->offsets[i] = gspca_dev->frame[i].v4l2_buf.m.offset;
1241         return 0;
1242 }
1243 #endif
1244
1245 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1246 {
1247         struct gspca_dev *gspca_dev = file->private_data;
1248         struct gspca_frame *frame;
1249         struct page *page;
1250         unsigned long addr, start, size;
1251         int i, ret;
1252
1253         start = vma->vm_start;
1254         size = vma->vm_end - vma->vm_start;
1255         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1256
1257         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1258                 return -ERESTARTSYS;
1259         if (!gspca_dev->present) {
1260                 ret = -ENODEV;
1261                 goto out;
1262         }
1263         if (gspca_dev->capt_file != file) {
1264                 ret = -EINVAL;
1265                 goto out;
1266         }
1267
1268         frame = NULL;
1269         for (i = 0; i < gspca_dev->nframes; ++i) {
1270                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1271                         PDEBUG(D_STREAM, "mmap bad memory type");
1272                         break;
1273                 }
1274                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1275                                                 == vma->vm_pgoff) {
1276                         frame = &gspca_dev->frame[i];
1277                         break;
1278                 }
1279         }
1280         if (frame == NULL) {
1281                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1282                 ret = -EINVAL;
1283                 goto out;
1284         }
1285 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1286         /* v4l1 maps all the buffers */
1287         if (i != 0
1288             || size != frame->v4l2_buf.length * gspca_dev->nframes)
1289 #endif
1290             if (size != frame->v4l2_buf.length) {
1291                 PDEBUG(D_STREAM, "mmap bad size");
1292                 ret = -EINVAL;
1293                 goto out;
1294         }
1295
1296         /*
1297          * - VM_IO marks the area as being a mmaped region for I/O to a
1298          *   device. It also prevents the region from being core dumped.
1299          */
1300         vma->vm_flags |= VM_IO;
1301
1302         addr = (unsigned long) frame->data;
1303         while (size > 0) {
1304                 page = vmalloc_to_page((void *) addr);
1305                 ret = vm_insert_page(vma, start, page);
1306                 if (ret < 0)
1307                         goto out;
1308                 start += PAGE_SIZE;
1309                 addr += PAGE_SIZE;
1310                 size -= PAGE_SIZE;
1311         }
1312
1313         vma->vm_ops = &gspca_vm_ops;
1314         vma->vm_private_data = frame;
1315         gspca_vm_open(vma);
1316         ret = 0;
1317 out:
1318         mutex_unlock(&gspca_dev->queue_lock);
1319         return ret;
1320 }
1321
1322 /*
1323  * wait for a video frame
1324  *
1325  * If a frame is ready, its index is returned.
1326  */
1327 static int frame_wait(struct gspca_dev *gspca_dev,
1328                         int nonblock_ing)
1329 {
1330         struct gspca_frame *frame;
1331         int i, j, ret;
1332
1333         /* check if a frame is ready */
1334         i = gspca_dev->fr_o;
1335         j = gspca_dev->fr_queue[i];
1336         frame = &gspca_dev->frame[j];
1337         if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE) {
1338                 atomic_dec(&gspca_dev->nevent);
1339                 goto ok;
1340         }
1341         if (nonblock_ing)                       /* no frame yet */
1342                 return -EAGAIN;
1343
1344         /* wait till a frame is ready */
1345         for (;;) {
1346                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1347                                         atomic_read(&gspca_dev->nevent) > 0,
1348                                         msecs_to_jiffies(3000));
1349                 if (ret <= 0) {
1350                         if (ret < 0)
1351                                 return ret;     /* interrupt */
1352                         return -EIO;            /* timeout */
1353                 }
1354                 atomic_dec(&gspca_dev->nevent);
1355                 if (!gspca_dev->streaming || !gspca_dev->present)
1356                         return -EIO;
1357                 i = gspca_dev->fr_o;
1358                 j = gspca_dev->fr_queue[i];
1359                 frame = &gspca_dev->frame[j];
1360                 if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1361                         break;
1362         }
1363 ok:
1364         gspca_dev->fr_o = (i + 1) % gspca_dev->nframes;
1365         PDEBUG(D_FRAM, "frame wait q:%d i:%d o:%d",
1366                 gspca_dev->fr_q,
1367                 gspca_dev->fr_i,
1368                 gspca_dev->fr_o);
1369
1370         if (gspca_dev->sd_desc->dq_callback) {
1371                 mutex_lock(&gspca_dev->usb_lock);
1372                 gspca_dev->sd_desc->dq_callback(gspca_dev);
1373                 mutex_unlock(&gspca_dev->usb_lock);
1374         }
1375         return j;
1376 }
1377
1378 /*
1379  * dequeue a video buffer
1380  *
1381  * If nonblock_ing is false, block until a buffer is available.
1382  */
1383 static int vidioc_dqbuf(struct file *file, void *priv,
1384                         struct v4l2_buffer *v4l2_buf)
1385 {
1386         struct gspca_dev *gspca_dev = priv;
1387         struct gspca_frame *frame;
1388         int i, ret;
1389
1390         PDEBUG(D_FRAM, "dqbuf");
1391         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1392                 return -EINVAL;
1393         if (v4l2_buf->memory != gspca_dev->memory)
1394                 return -EINVAL;
1395
1396         /* if not streaming, be sure the application will not loop forever */
1397         if (!(file->f_flags & O_NONBLOCK)
1398             && !gspca_dev->streaming && gspca_dev->users == 1)
1399                 return -EINVAL;
1400
1401         /* only the capturing file may dequeue */
1402         if (gspca_dev->capt_file != file)
1403                 return -EINVAL;
1404
1405         /* only one dequeue / read at a time */
1406         if (mutex_lock_interruptible(&gspca_dev->read_lock))
1407                 return -ERESTARTSYS;
1408
1409         ret = frame_wait(gspca_dev, file->f_flags & O_NONBLOCK);
1410         if (ret < 0)
1411                 goto out;
1412         i = ret;                                /* frame index */
1413         frame = &gspca_dev->frame[i];
1414         if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1415                 if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1416                                  frame->data,
1417                                  frame->v4l2_buf.bytesused)) {
1418                         PDEBUG(D_ERR|D_STREAM,
1419                                 "dqbuf cp to user failed");
1420                         ret = -EFAULT;
1421                         goto out;
1422                 }
1423         }
1424         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1425         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1426         PDEBUG(D_FRAM, "dqbuf %d", i);
1427         ret = 0;
1428 out:
1429         mutex_unlock(&gspca_dev->read_lock);
1430         return ret;
1431 }
1432
1433 /*
1434  * queue a video buffer
1435  *
1436  * Attempting to queue a buffer that has already been
1437  * queued will return -EINVAL.
1438  */
1439 static int vidioc_qbuf(struct file *file, void *priv,
1440                         struct v4l2_buffer *v4l2_buf)
1441 {
1442         struct gspca_dev *gspca_dev = priv;
1443         struct gspca_frame *frame;
1444         int i, index, ret;
1445
1446         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1447         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1448                 return -EINVAL;
1449
1450         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1451                 return -ERESTARTSYS;
1452
1453         index = v4l2_buf->index;
1454         if ((unsigned) index >= gspca_dev->nframes) {
1455                 PDEBUG(D_FRAM,
1456                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
1457                 ret = -EINVAL;
1458                 goto out;
1459         }
1460         if (v4l2_buf->memory != gspca_dev->memory) {
1461                 PDEBUG(D_FRAM, "qbuf bad memory type");
1462                 ret = -EINVAL;
1463                 goto out;
1464         }
1465
1466         frame = &gspca_dev->frame[index];
1467         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1468                 PDEBUG(D_FRAM, "qbuf bad state");
1469                 ret = -EINVAL;
1470                 goto out;
1471         }
1472
1473         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1474 /*      frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE; */
1475
1476         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1477                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1478                 frame->v4l2_buf.length = v4l2_buf->length;
1479         }
1480
1481         /* put the buffer in the 'queued' queue */
1482         i = gspca_dev->fr_q;
1483         gspca_dev->fr_queue[i] = index;
1484         gspca_dev->fr_q = (i + 1) % gspca_dev->nframes;
1485         PDEBUG(D_FRAM, "qbuf q:%d i:%d o:%d",
1486                 gspca_dev->fr_q,
1487                 gspca_dev->fr_i,
1488                 gspca_dev->fr_o);
1489
1490         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1491         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1492         ret = 0;
1493 out:
1494         mutex_unlock(&gspca_dev->queue_lock);
1495         return ret;
1496 }
1497
1498 /*
1499  * allocate the resources for read()
1500  */
1501 static int read_alloc(struct gspca_dev *gspca_dev,
1502                         struct file *file)
1503 {
1504         struct v4l2_buffer v4l2_buf;
1505         int i, ret;
1506
1507         PDEBUG(D_STREAM, "read alloc");
1508         if (gspca_dev->nframes == 0) {
1509                 struct v4l2_requestbuffers rb;
1510
1511                 memset(&rb, 0, sizeof rb);
1512                 rb.count = gspca_dev->nbufread;
1513                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1514                 rb.memory = GSPCA_MEMORY_READ;
1515                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
1516                 if (ret != 0) {
1517                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1518                         return ret;
1519                 }
1520                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1521                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1522                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1523                 for (i = 0; i < gspca_dev->nbufread; i++) {
1524                         v4l2_buf.index = i;
1525                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1526                         if (ret != 0) {
1527                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1528                                 return ret;
1529                         }
1530                 }
1531                 gspca_dev->memory = GSPCA_MEMORY_READ;
1532         }
1533
1534         /* start streaming */
1535         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1536         if (ret != 0)
1537                 PDEBUG(D_STREAM, "read streamon err %d", ret);
1538         return ret;
1539 }
1540
1541 static unsigned int dev_poll(struct file *file, poll_table *wait)
1542 {
1543         struct gspca_dev *gspca_dev = file->private_data;
1544         int i, ret;
1545
1546         PDEBUG(D_FRAM, "poll");
1547
1548         poll_wait(file, &gspca_dev->wq, wait);
1549         if (!gspca_dev->present)
1550                 return POLLERR;
1551
1552         /* if reqbufs is not done, the user would use read() */
1553         if (gspca_dev->nframes == 0) {
1554                 if (gspca_dev->memory != GSPCA_MEMORY_NO)
1555                         return POLLERR;         /* not the 1st time */
1556                 ret = read_alloc(gspca_dev, file);
1557                 if (ret != 0)
1558                         return POLLERR;
1559         }
1560
1561         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
1562                 return POLLERR;
1563         if (!gspca_dev->present) {
1564                 ret = POLLERR;
1565                 goto out;
1566         }
1567
1568         /* check the next incoming buffer */
1569         i = gspca_dev->fr_o;
1570         i = gspca_dev->fr_queue[i];
1571         if (gspca_dev->frame[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1572                 ret = POLLIN | POLLRDNORM;      /* something to read */
1573         else
1574                 ret = 0;
1575 out:
1576         mutex_unlock(&gspca_dev->queue_lock);
1577         return ret;
1578 }
1579
1580 static ssize_t dev_read(struct file *file, char __user *data,
1581                     size_t count, loff_t *ppos)
1582 {
1583         struct gspca_dev *gspca_dev = file->private_data;
1584         struct gspca_frame *frame;
1585         struct v4l2_buffer v4l2_buf;
1586         struct timeval timestamp;
1587         int n, ret, ret2;
1588
1589         PDEBUG(D_FRAM, "read (%zd)", count);
1590         if (!gspca_dev->present)
1591                 return -ENODEV;
1592         switch (gspca_dev->memory) {
1593         case GSPCA_MEMORY_NO:                   /* first time */
1594                 ret = read_alloc(gspca_dev, file);
1595                 if (ret != 0)
1596                         return ret;
1597                 break;
1598         case GSPCA_MEMORY_READ:
1599                 if (gspca_dev->capt_file == file)
1600                         break;
1601                 /* fall thru */
1602         default:
1603                 return -EINVAL;
1604         }
1605
1606         /* get a frame */
1607         jiffies_to_timeval(get_jiffies_64(), &timestamp);
1608         timestamp.tv_sec--;
1609         n = 2;
1610         for (;;) {
1611                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1612                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1613                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1614                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1615                 if (ret != 0) {
1616                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1617                         return ret;
1618                 }
1619
1620                 /* if the process slept for more than 1 second,
1621                  * get anewer frame */
1622                 frame = &gspca_dev->frame[v4l2_buf.index];
1623                 if (--n < 0)
1624                         break;                  /* avoid infinite loop */
1625                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1626                         break;
1627                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1628                 if (ret != 0) {
1629                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
1630                         return ret;
1631                 }
1632         }
1633
1634         /* copy the frame */
1635         if (count > frame->v4l2_buf.bytesused)
1636                 count = frame->v4l2_buf.bytesused;
1637         ret = copy_to_user(data, frame->data, count);
1638         if (ret != 0) {
1639                 PDEBUG(D_ERR|D_STREAM,
1640                         "read cp to user lack %d / %zd", ret, count);
1641                 ret = -EFAULT;
1642                 goto out;
1643         }
1644         ret = count;
1645 out:
1646         /* in each case, requeue the buffer */
1647         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1648         if (ret2 != 0)
1649                 return ret2;
1650         return ret;
1651 }
1652
1653 static void dev_release(struct video_device *vfd)
1654 {
1655         /* nothing */
1656 }
1657
1658 static struct file_operations dev_fops = {
1659         .owner = THIS_MODULE,
1660         .open = dev_open,
1661         .release = dev_close,
1662         .read = dev_read,
1663         .mmap = dev_mmap,
1664         .ioctl = video_ioctl2,
1665 #ifdef CONFIG_COMPAT
1666         .compat_ioctl = v4l_compat_ioctl32,
1667 #endif
1668         .llseek = no_llseek,
1669         .poll   = dev_poll,
1670 };
1671
1672 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1673         .vidioc_querycap        = vidioc_querycap,
1674         .vidioc_dqbuf           = vidioc_dqbuf,
1675         .vidioc_qbuf            = vidioc_qbuf,
1676         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1677         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1678         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1679         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1680         .vidioc_streamon        = vidioc_streamon,
1681         .vidioc_queryctrl       = vidioc_queryctrl,
1682         .vidioc_g_ctrl          = vidioc_g_ctrl,
1683         .vidioc_s_ctrl          = vidioc_s_ctrl,
1684         .vidioc_querymenu       = vidioc_querymenu,
1685         .vidioc_enum_input      = vidioc_enum_input,
1686         .vidioc_g_input         = vidioc_g_input,
1687         .vidioc_s_input         = vidioc_s_input,
1688         .vidioc_reqbufs         = vidioc_reqbufs,
1689         .vidioc_querybuf        = vidioc_querybuf,
1690         .vidioc_streamoff       = vidioc_streamoff,
1691         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1692         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1693         .vidioc_g_parm          = vidioc_g_parm,
1694         .vidioc_s_parm          = vidioc_s_parm,
1695         .vidioc_s_std           = vidioc_s_std,
1696 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1697         .vidiocgmbuf          = vidiocgmbuf,
1698 #endif
1699 };
1700
1701 static struct video_device gspca_template = {
1702         .name = "gspca main driver",
1703         .fops = &dev_fops,
1704         .ioctl_ops = &dev_ioctl_ops,
1705         .release = dev_release,         /* mandatory */
1706         .minor = -1,
1707 };
1708
1709 /*
1710  * probe and create a new gspca device
1711  *
1712  * This function must be called by the sub-driver when it is
1713  * called for probing a new device.
1714  */
1715 int gspca_dev_probe(struct usb_interface *intf,
1716                 const struct usb_device_id *id,
1717                 const struct sd_desc *sd_desc,
1718                 int dev_size,
1719                 struct module *module)
1720 {
1721         struct usb_interface_descriptor *interface;
1722         struct gspca_dev *gspca_dev;
1723         struct usb_device *dev = interface_to_usbdev(intf);
1724         int ret;
1725
1726         PDEBUG(D_PROBE, "probing %04x:%04x", id->idVendor, id->idProduct);
1727
1728         /* we don't handle multi-config cameras */
1729         if (dev->descriptor.bNumConfigurations != 1)
1730                 return -ENODEV;
1731         interface = &intf->cur_altsetting->desc;
1732         if (interface->bInterfaceNumber > 0)
1733                 return -ENODEV;
1734
1735         /* create the device */
1736         if (dev_size < sizeof *gspca_dev)
1737                 dev_size = sizeof *gspca_dev;
1738         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
1739         if (gspca_dev == NULL) {
1740                 err("couldn't kzalloc gspca struct");
1741                 return -EIO;
1742         }
1743         gspca_dev->dev = dev;
1744         gspca_dev->iface = interface->bInterfaceNumber;
1745         gspca_dev->nbalt = intf->num_altsetting;
1746         gspca_dev->sd_desc = sd_desc;
1747 /*      gspca_dev->users = 0;                   (done by kzalloc) */
1748         gspca_dev->nbufread = 2;
1749
1750         /* configure the subdriver */
1751         ret = gspca_dev->sd_desc->config(gspca_dev, id);
1752         if (ret < 0)
1753                 goto out;
1754         ret = gspca_set_alt0(gspca_dev);
1755         if (ret < 0)
1756                 goto out;
1757         gspca_set_default_mode(gspca_dev);
1758
1759         mutex_init(&gspca_dev->usb_lock);
1760         mutex_init(&gspca_dev->read_lock);
1761         mutex_init(&gspca_dev->queue_lock);
1762         init_waitqueue_head(&gspca_dev->wq);
1763
1764         /* init video stuff */
1765         memcpy(&gspca_dev->vdev, &gspca_template, sizeof gspca_template);
1766         gspca_dev->vdev.parent = &dev->dev;
1767         memcpy(&gspca_dev->fops, &dev_fops, sizeof gspca_dev->fops);
1768         gspca_dev->vdev.fops = &gspca_dev->fops;
1769         gspca_dev->fops.owner = module;         /* module protection */
1770         gspca_dev->present = 1;
1771         ret = video_register_device(&gspca_dev->vdev,
1772                                   VFL_TYPE_GRABBER,
1773                                   video_nr);
1774         if (ret < 0) {
1775                 err("video_register_device err %d", ret);
1776                 goto out;
1777         }
1778
1779         usb_set_intfdata(intf, gspca_dev);
1780         PDEBUG(D_PROBE, "probe ok");
1781         return 0;
1782 out:
1783         kfree(gspca_dev);
1784         return ret;
1785 }
1786 EXPORT_SYMBOL(gspca_dev_probe);
1787
1788 /*
1789  * USB disconnection
1790  *
1791  * This function must be called by the sub-driver
1792  * when the device disconnects, after the specific resources are freed.
1793  */
1794 void gspca_disconnect(struct usb_interface *intf)
1795 {
1796         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1797
1798         if (!gspca_dev)
1799                 return;
1800         gspca_dev->present = 0;
1801         mutex_lock(&gspca_dev->queue_lock);
1802         mutex_lock(&gspca_dev->usb_lock);
1803         gspca_dev->streaming = 0;
1804         destroy_urbs(gspca_dev);
1805         mutex_unlock(&gspca_dev->usb_lock);
1806         mutex_unlock(&gspca_dev->queue_lock);
1807         while (gspca_dev->users != 0) {         /* wait until fully closed */
1808                 atomic_inc(&gspca_dev->nevent);
1809                 wake_up_interruptible(&gspca_dev->wq);  /* wake processes */
1810                 schedule();
1811         }
1812 /* We don't want people trying to open up the device */
1813         video_unregister_device(&gspca_dev->vdev);
1814 /* Free the memory */
1815         kfree(gspca_dev);
1816         PDEBUG(D_PROBE, "disconnect complete");
1817 }
1818 EXPORT_SYMBOL(gspca_disconnect);
1819
1820 #ifdef CONFIG_PM
1821 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
1822 {
1823         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1824
1825         if (!gspca_dev->streaming)
1826                 return 0;
1827         gspca_dev->frozen = 1;          /* avoid urb error messages */
1828         gspca_dev->sd_desc->stopN(gspca_dev);
1829         destroy_urbs(gspca_dev);
1830         gspca_set_alt0(gspca_dev);
1831         gspca_dev->sd_desc->stop0(gspca_dev);
1832         return 0;
1833 }
1834 EXPORT_SYMBOL(gspca_suspend);
1835
1836 int gspca_resume(struct usb_interface *intf)
1837 {
1838         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1839
1840         gspca_dev->frozen = 0;
1841         if (!gspca_dev->streaming)
1842                 return 0;
1843         return gspca_init_transfer(gspca_dev);
1844 }
1845 EXPORT_SYMBOL(gspca_resume);
1846 #endif
1847 /* -- cam driver utility functions -- */
1848
1849 /* auto gain and exposure algorithm based on the knee algorithm described here:
1850    http://ytse.tricolour.net/docs/LowLightOptimization.html
1851
1852    Returns 0 if no changes were made, 1 if the gain and or exposure settings
1853    where changed. */
1854 int gspca_auto_gain_n_exposure(struct gspca_dev *gspca_dev, int avg_lum,
1855         int desired_avg_lum, int deadzone, int gain_knee, int exposure_knee)
1856 {
1857         int i, steps, gain, orig_gain, exposure, orig_exposure, autogain;
1858         const struct ctrl *gain_ctrl = NULL;
1859         const struct ctrl *exposure_ctrl = NULL;
1860         const struct ctrl *autogain_ctrl = NULL;
1861         int retval = 0;
1862
1863         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1864                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_GAIN)
1865                         gain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1866                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_EXPOSURE)
1867                         exposure_ctrl = &gspca_dev->sd_desc->ctrls[i];
1868                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_AUTOGAIN)
1869                         autogain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1870         }
1871         if (!gain_ctrl || !exposure_ctrl || !autogain_ctrl) {
1872                 PDEBUG(D_ERR, "Error: gspca_auto_gain_n_exposure called "
1873                         "on cam without (auto)gain/exposure");
1874                 return 0;
1875         }
1876
1877         if (gain_ctrl->get(gspca_dev, &gain) ||
1878                         exposure_ctrl->get(gspca_dev, &exposure) ||
1879                         autogain_ctrl->get(gspca_dev, &autogain) || !autogain)
1880                 return 0;
1881
1882         orig_gain = gain;
1883         orig_exposure = exposure;
1884
1885         /* If we are of a multiple of deadzone, do multiple steps to reach the
1886            desired lumination fast (with the risc of a slight overshoot) */
1887         steps = abs(desired_avg_lum - avg_lum) / deadzone;
1888
1889         PDEBUG(D_FRAM, "autogain: lum: %d, desired: %d, steps: %d\n",
1890                 avg_lum, desired_avg_lum, steps);
1891
1892         for (i = 0; i < steps; i++) {
1893                 if (avg_lum > desired_avg_lum) {
1894                         if (gain > gain_knee)
1895                                 gain--;
1896                         else if (exposure > exposure_knee)
1897                                 exposure--;
1898                         else if (gain > gain_ctrl->qctrl.default_value)
1899                                 gain--;
1900                         else if (exposure > exposure_ctrl->qctrl.minimum)
1901                                 exposure--;
1902                         else if (gain > gain_ctrl->qctrl.minimum)
1903                                 gain--;
1904                         else
1905                                 break;
1906                 } else {
1907                         if (gain < gain_ctrl->qctrl.default_value)
1908                                 gain++;
1909                         else if (exposure < exposure_knee)
1910                                 exposure++;
1911                         else if (gain < gain_knee)
1912                                 gain++;
1913                         else if (exposure < exposure_ctrl->qctrl.maximum)
1914                                 exposure++;
1915                         else if (gain < gain_ctrl->qctrl.maximum)
1916                                 gain++;
1917                         else
1918                                 break;
1919                 }
1920         }
1921
1922         if (gain != orig_gain) {
1923                 gain_ctrl->set(gspca_dev, gain);
1924                 retval = 1;
1925         }
1926         if (exposure != orig_exposure) {
1927                 exposure_ctrl->set(gspca_dev, exposure);
1928                 retval = 1;
1929         }
1930
1931         return retval;
1932 }
1933 EXPORT_SYMBOL(gspca_auto_gain_n_exposure);
1934
1935 /* -- module insert / remove -- */
1936 static int __init gspca_init(void)
1937 {
1938         info("main v%d.%d.%d registered",
1939                 (DRIVER_VERSION_NUMBER >> 16) & 0xff,
1940                 (DRIVER_VERSION_NUMBER >> 8) & 0xff,
1941                 DRIVER_VERSION_NUMBER & 0xff);
1942         return 0;
1943 }
1944 static void __exit gspca_exit(void)
1945 {
1946         info("main deregistered");
1947 }
1948
1949 module_init(gspca_init);
1950 module_exit(gspca_exit);
1951
1952 #ifdef GSPCA_DEBUG
1953 module_param_named(debug, gspca_debug, int, 0644);
1954 MODULE_PARM_DESC(debug,
1955                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
1956                 " 0x08:stream 0x10:frame 0x20:packet 0x40:USBin 0x80:USBout"
1957                 " 0x0100: v4l2");
1958 #endif