ed8935da58e0bf17a37c166002a2b89cd245d0dc
[firefly-linux-kernel-4.4.55.git] / 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                         for (i = 0; i < n; i++)
463                                 usb_free_urb(gspca_dev->urb[i]);
464                         return -ENOMEM;
465                 }
466                 urb->transfer_buffer = usb_buffer_alloc(gspca_dev->dev,
467                                                 bsize,
468                                                 GFP_KERNEL,
469                                                 &urb->transfer_dma);
470
471                 if (urb->transfer_buffer == NULL) {
472                         usb_free_urb(urb);
473                         destroy_urbs(gspca_dev);
474                         err("usb_buffer_urb failed");
475                         return -ENOMEM;
476                 }
477                 gspca_dev->urb[n] = urb;
478                 urb->dev = gspca_dev->dev;
479                 urb->context = gspca_dev;
480                 urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
481                                             ep->desc.bEndpointAddress);
482                 urb->transfer_flags = URB_ISO_ASAP
483                                         | URB_NO_TRANSFER_DMA_MAP;
484                 urb->interval = ep->desc.bInterval;
485                 urb->complete = isoc_irq;
486                 urb->number_of_packets = npkt;
487                 urb->transfer_buffer_length = bsize;
488                 for (i = 0; i < npkt; i++) {
489                         urb->iso_frame_desc[i].length = psize;
490                         urb->iso_frame_desc[i].offset = psize * i;
491                 }
492         }
493         return 0;
494 }
495
496 /*
497  * start the USB transfer
498  */
499 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
500 {
501         struct usb_host_endpoint *ep;
502         int n, ret;
503
504         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
505                 return -ERESTARTSYS;
506
507         /* set the higher alternate setting and
508          * loop until urb submit succeeds */
509         gspca_dev->alt = gspca_dev->nbalt;
510         for (;;) {
511                 PDEBUG(D_STREAM, "init transfer alt %d", gspca_dev->alt);
512                 ep = get_isoc_ep(gspca_dev);
513                 if (ep == NULL) {
514                         ret = -EIO;
515                         goto out;
516                 }
517                 ret = create_urbs(gspca_dev, ep);
518                 if (ret < 0)
519                         goto out;
520
521                 /* start the cam */
522                 gspca_dev->sd_desc->start(gspca_dev);
523                 gspca_dev->streaming = 1;
524                 atomic_set(&gspca_dev->nevent, 0);
525
526                 /* submit the URBs */
527                 for (n = 0; n < gspca_dev->nurbs; n++) {
528                         ret = usb_submit_urb(gspca_dev->urb[n], GFP_KERNEL);
529                         if (ret < 0) {
530                                 PDEBUG(D_ERR|D_STREAM,
531                                         "usb_submit_urb [%d] err %d", n, ret);
532                                 gspca_dev->streaming = 0;
533                                 destroy_urbs(gspca_dev);
534                                 if (ret == -ENOSPC)
535                                         break;  /* try the previous alt */
536                                 goto out;
537                         }
538                 }
539                 if (ret >= 0)
540                         break;
541         }
542 out:
543         mutex_unlock(&gspca_dev->usb_lock);
544         return ret;
545 }
546
547 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
548 {
549         int ret;
550
551         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
552         if (ret < 0)
553                 PDEBUG(D_ERR|D_STREAM, "set interface 0 err %d", ret);
554         return ret;
555 }
556
557 /* Note both the queue and the usb lock should be hold when calling this */
558 static void gspca_stream_off(struct gspca_dev *gspca_dev)
559 {
560         gspca_dev->streaming = 0;
561         atomic_set(&gspca_dev->nevent, 0);
562         if (gspca_dev->present) {
563                 if (gspca_dev->sd_desc->stopN)
564                         gspca_dev->sd_desc->stopN(gspca_dev);
565                 destroy_urbs(gspca_dev);
566                 gspca_set_alt0(gspca_dev);
567                 if (gspca_dev->sd_desc->stop0)
568                         gspca_dev->sd_desc->stop0(gspca_dev);
569                 PDEBUG(D_STREAM, "stream off OK");
570         }
571 }
572
573 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
574 {
575         int i;
576
577         i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
578         gspca_dev->curr_mode = i;
579         gspca_dev->width = gspca_dev->cam.cam_mode[i].width;
580         gspca_dev->height = gspca_dev->cam.cam_mode[i].height;
581         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixelformat;
582 }
583
584 static int wxh_to_mode(struct gspca_dev *gspca_dev,
585                         int width, int height)
586 {
587         int i;
588
589         for (i = gspca_dev->cam.nmodes; --i > 0; ) {
590                 if (width >= gspca_dev->cam.cam_mode[i].width
591                     && height >= gspca_dev->cam.cam_mode[i].height)
592                         break;
593         }
594         return i;
595 }
596
597 /*
598  * search a mode with the right pixel format
599  */
600 static int gspca_get_mode(struct gspca_dev *gspca_dev,
601                         int mode,
602                         int pixfmt)
603 {
604         int modeU, modeD;
605
606         modeU = modeD = mode;
607         while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
608                 if (--modeD >= 0) {
609                         if (gspca_dev->cam.cam_mode[modeD].pixelformat
610                                                                 == pixfmt)
611                                 return modeD;
612                 }
613                 if (++modeU < gspca_dev->cam.nmodes) {
614                         if (gspca_dev->cam.cam_mode[modeU].pixelformat
615                                                                 == pixfmt)
616                                 return modeU;
617                 }
618         }
619         return -EINVAL;
620 }
621
622 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
623                                 struct v4l2_fmtdesc *fmtdesc)
624 {
625         struct gspca_dev *gspca_dev = priv;
626         int i, j, index;
627         __u32 fmt_tb[8];
628
629         /* give an index to each format */
630         index = 0;
631         j = 0;
632         for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
633                 fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
634                 j = 0;
635                 for (;;) {
636                         if (fmt_tb[j] == fmt_tb[index])
637                                 break;
638                         j++;
639                 }
640                 if (j == index) {
641                         if (fmtdesc->index == index)
642                                 break;          /* new format */
643                         index++;
644                         if (index >= sizeof fmt_tb / sizeof fmt_tb[0])
645                                 return -EINVAL;
646                 }
647         }
648         if (i < 0)
649                 return -EINVAL;         /* no more format */
650
651         fmtdesc->pixelformat = fmt_tb[index];
652         if (gspca_is_compressed(fmt_tb[index]))
653                 fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
654         fmtdesc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
655         fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
656         fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
657         fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
658         fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
659         fmtdesc->description[4] = '\0';
660         return 0;
661 }
662
663 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
664                             struct v4l2_format *fmt)
665 {
666         struct gspca_dev *gspca_dev = priv;
667         int mode;
668
669         if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
670                 return -EINVAL;
671         mode = gspca_dev->curr_mode;
672         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
673                 sizeof fmt->fmt.pix);
674         return 0;
675 }
676
677 static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
678                         struct v4l2_format *fmt)
679 {
680         int w, h, mode, mode2;
681
682         if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
683                 return -EINVAL;
684         w = fmt->fmt.pix.width;
685         h = fmt->fmt.pix.height;
686
687 #ifdef GSPCA_DEBUG
688         if (gspca_debug & D_CONF)
689                 PDEBUG_MODE("try fmt cap", fmt->fmt.pix.pixelformat, w, h);
690 #endif
691         /* search the closest mode for width and height */
692         mode = wxh_to_mode(gspca_dev, w, h);
693
694         /* OK if right palette */
695         if (gspca_dev->cam.cam_mode[mode].pixelformat
696                                                 != fmt->fmt.pix.pixelformat) {
697
698                 /* else, search the closest mode with the same pixel format */
699                 mode2 = gspca_get_mode(gspca_dev, mode,
700                                         fmt->fmt.pix.pixelformat);
701                 if (mode2 >= 0)
702                         mode = mode2;
703 /*              else
704                         ;                * no chance, return this mode */
705         }
706         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
707                 sizeof fmt->fmt.pix);
708         return mode;                    /* used when s_fmt */
709 }
710
711 static int vidioc_try_fmt_vid_cap(struct file *file,
712                               void *priv,
713                               struct v4l2_format *fmt)
714 {
715         struct gspca_dev *gspca_dev = priv;
716         int ret;
717
718         ret = try_fmt_vid_cap(gspca_dev, fmt);
719         if (ret < 0)
720                 return ret;
721         return 0;
722 }
723
724 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
725                             struct v4l2_format *fmt)
726 {
727         struct gspca_dev *gspca_dev = priv;
728         int ret;
729
730         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
731                 return -ERESTARTSYS;
732
733         ret = try_fmt_vid_cap(gspca_dev, fmt);
734         if (ret < 0)
735                 goto out;
736
737         if (gspca_dev->nframes != 0
738             && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
739                 ret = -EINVAL;
740                 goto out;
741         }
742
743         if (ret == gspca_dev->curr_mode) {
744                 ret = 0;
745                 goto out;                       /* same mode */
746         }
747
748         if (gspca_dev->streaming) {
749                 ret = -EBUSY;
750                 goto out;
751         }
752         gspca_dev->width = fmt->fmt.pix.width;
753         gspca_dev->height = fmt->fmt.pix.height;
754         gspca_dev->pixfmt = fmt->fmt.pix.pixelformat;
755         gspca_dev->curr_mode = ret;
756
757         ret = 0;
758 out:
759         mutex_unlock(&gspca_dev->queue_lock);
760         return ret;
761 }
762
763 static int dev_open(struct inode *inode, struct file *file)
764 {
765         struct gspca_dev *gspca_dev;
766         int ret;
767
768         PDEBUG(D_STREAM, "%s open", current->comm);
769         gspca_dev = (struct gspca_dev *) video_devdata(file);
770         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
771                 return -ERESTARTSYS;
772         if (!gspca_dev->present) {
773                 ret = -ENODEV;
774                 goto out;
775         }
776
777         if (gspca_dev->users > 4) {     /* (arbitrary value) */
778                 ret = -EBUSY;
779                 goto out;
780         }
781         gspca_dev->users++;
782         file->private_data = gspca_dev;
783 #ifdef GSPCA_DEBUG
784         /* activate the v4l2 debug */
785         if (gspca_debug & D_V4L2)
786                 gspca_dev->vdev.debug |= 3;
787         else
788                 gspca_dev->vdev.debug &= ~3;
789 #endif
790         ret = 0;
791 out:
792         mutex_unlock(&gspca_dev->queue_lock);
793         if (ret != 0)
794                 PDEBUG(D_ERR|D_STREAM, "open failed err %d", ret);
795         else
796                 PDEBUG(D_STREAM, "open done");
797         return ret;
798 }
799
800 static int dev_close(struct inode *inode, struct file *file)
801 {
802         struct gspca_dev *gspca_dev = file->private_data;
803
804         PDEBUG(D_STREAM, "%s close", current->comm);
805         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
806                 return -ERESTARTSYS;
807         gspca_dev->users--;
808
809         /* if the file did the capture, free the streaming resources */
810         if (gspca_dev->capt_file == file) {
811                 if (gspca_dev->streaming) {
812                         mutex_lock(&gspca_dev->usb_lock);
813                         gspca_stream_off(gspca_dev);
814                         mutex_unlock(&gspca_dev->usb_lock);
815                 }
816                 frame_free(gspca_dev);
817                 gspca_dev->capt_file = NULL;
818                 gspca_dev->memory = GSPCA_MEMORY_NO;
819         }
820         file->private_data = NULL;
821         mutex_unlock(&gspca_dev->queue_lock);
822         PDEBUG(D_STREAM, "close done");
823         return 0;
824 }
825
826 static int vidioc_querycap(struct file *file, void  *priv,
827                            struct v4l2_capability *cap)
828 {
829         struct gspca_dev *gspca_dev = priv;
830
831         memset(cap, 0, sizeof *cap);
832         strncpy(cap->driver, gspca_dev->sd_desc->name, sizeof cap->driver);
833 /*      strncpy(cap->card, gspca_dev->cam.dev_name, sizeof cap->card); */
834         if (gspca_dev->dev->product != NULL) {
835                 strncpy(cap->card, gspca_dev->dev->product,
836                         sizeof cap->card);
837         } else {
838                 snprintf(cap->card, sizeof cap->card,
839                         "USB Camera (%04x:%04x)",
840                         le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
841                         le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
842         }
843         strncpy(cap->bus_info, gspca_dev->dev->bus->bus_name,
844                 sizeof cap->bus_info);
845         cap->version = DRIVER_VERSION_NUMBER;
846         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
847                           | V4L2_CAP_STREAMING
848                           | V4L2_CAP_READWRITE;
849         return 0;
850 }
851
852 static int vidioc_queryctrl(struct file *file, void *priv,
853                            struct v4l2_queryctrl *q_ctrl)
854 {
855         struct gspca_dev *gspca_dev = priv;
856         int i, ix;
857         u32 id;
858
859         ix = -1;
860         id = q_ctrl->id;
861         if (id & V4L2_CTRL_FLAG_NEXT_CTRL) {
862                 id &= V4L2_CTRL_ID_MASK;
863                 id++;
864                 for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
865                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id < id)
866                                 continue;
867                         if (ix < 0) {
868                                 ix = i;
869                                 continue;
870                         }
871                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id
872                                     > gspca_dev->sd_desc->ctrls[ix].qctrl.id)
873                                 continue;
874                         ix = i;
875                 }
876         }
877         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
878                 if (id == gspca_dev->sd_desc->ctrls[i].qctrl.id) {
879                         ix = i;
880                         break;
881                 }
882         }
883         if (ix < 0)
884                 return -EINVAL;
885         memcpy(q_ctrl, &gspca_dev->sd_desc->ctrls[ix].qctrl,
886                 sizeof *q_ctrl);
887         if (gspca_dev->ctrl_dis & (1 << ix))
888                 q_ctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
889         return 0;
890 }
891
892 static int vidioc_s_ctrl(struct file *file, void *priv,
893                          struct v4l2_control *ctrl)
894 {
895         struct gspca_dev *gspca_dev = priv;
896         const struct ctrl *ctrls;
897         int i, ret;
898
899         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
900              i < gspca_dev->sd_desc->nctrls;
901              i++, ctrls++) {
902                 if (ctrl->id != ctrls->qctrl.id)
903                         continue;
904                 if (gspca_dev->ctrl_dis & (1 << i))
905                         return -EINVAL;
906                 if (ctrl->value < ctrls->qctrl.minimum
907                     || ctrl->value > ctrls->qctrl.maximum)
908                         return -ERANGE;
909                 PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
910                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
911                         return -ERESTARTSYS;
912                 ret = ctrls->set(gspca_dev, ctrl->value);
913                 mutex_unlock(&gspca_dev->usb_lock);
914                 return ret;
915         }
916         return -EINVAL;
917 }
918
919 static int vidioc_g_ctrl(struct file *file, void *priv,
920                          struct v4l2_control *ctrl)
921 {
922         struct gspca_dev *gspca_dev = priv;
923
924         const struct ctrl *ctrls;
925         int i, ret;
926
927         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
928              i < gspca_dev->sd_desc->nctrls;
929              i++, ctrls++) {
930                 if (ctrl->id != ctrls->qctrl.id)
931                         continue;
932                 if (gspca_dev->ctrl_dis & (1 << i))
933                         return -EINVAL;
934                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
935                         return -ERESTARTSYS;
936                 ret = ctrls->get(gspca_dev, &ctrl->value);
937                 mutex_unlock(&gspca_dev->usb_lock);
938                 return ret;
939         }
940         return -EINVAL;
941 }
942
943 static int vidioc_querymenu(struct file *file, void *priv,
944                             struct v4l2_querymenu *qmenu)
945 {
946         struct gspca_dev *gspca_dev = priv;
947
948         if (!gspca_dev->sd_desc->querymenu)
949                 return -EINVAL;
950         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
951 }
952
953 static int vidioc_enum_input(struct file *file, void *priv,
954                                 struct v4l2_input *input)
955 {
956         struct gspca_dev *gspca_dev = priv;
957
958         if (input->index != 0)
959                 return -EINVAL;
960         memset(input, 0, sizeof *input);
961         input->type = V4L2_INPUT_TYPE_CAMERA;
962         strncpy(input->name, gspca_dev->sd_desc->name,
963                 sizeof input->name);
964         return 0;
965 }
966
967 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
968 {
969         *i = 0;
970         return 0;
971 }
972
973 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
974 {
975         if (i > 0)
976                 return -EINVAL;
977         return (0);
978 }
979
980 static int vidioc_reqbufs(struct file *file, void *priv,
981                           struct v4l2_requestbuffers *rb)
982 {
983         struct gspca_dev *gspca_dev = priv;
984         int i, ret = 0;
985
986         if (rb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
987                 return -EINVAL;
988         switch (rb->memory) {
989         case GSPCA_MEMORY_READ:                 /* (internal call) */
990         case V4L2_MEMORY_MMAP:
991         case V4L2_MEMORY_USERPTR:
992                 break;
993         default:
994                 return -EINVAL;
995         }
996         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
997                 return -ERESTARTSYS;
998
999         if (gspca_dev->memory != GSPCA_MEMORY_NO
1000             && gspca_dev->memory != rb->memory) {
1001                 ret = -EBUSY;
1002                 goto out;
1003         }
1004
1005         /* only one file may do the capture */
1006         if (gspca_dev->capt_file != NULL
1007             && gspca_dev->capt_file != file) {
1008                 ret = -EBUSY;
1009                 goto out;
1010         }
1011
1012         /* if allocated, the buffers must not be mapped */
1013         for (i = 0; i < gspca_dev->nframes; i++) {
1014                 if (gspca_dev->frame[i].vma_use_count) {
1015                         ret = -EBUSY;
1016                         goto out;
1017                 }
1018         }
1019
1020         /* stop streaming */
1021         if (gspca_dev->streaming) {
1022                 mutex_lock(&gspca_dev->usb_lock);
1023                 gspca_stream_off(gspca_dev);
1024                 mutex_unlock(&gspca_dev->usb_lock);
1025         }
1026
1027         /* free the previous allocated buffers, if any */
1028         if (gspca_dev->nframes != 0) {
1029                 frame_free(gspca_dev);
1030                 gspca_dev->capt_file = NULL;
1031         }
1032         if (rb->count == 0)                     /* unrequest */
1033                 goto out;
1034         gspca_dev->memory = rb->memory;
1035         ret = frame_alloc(gspca_dev, rb->count);
1036         if (ret == 0) {
1037                 rb->count = gspca_dev->nframes;
1038                 gspca_dev->capt_file = file;
1039         }
1040 out:
1041         mutex_unlock(&gspca_dev->queue_lock);
1042         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1043         return ret;
1044 }
1045
1046 static int vidioc_querybuf(struct file *file, void *priv,
1047                            struct v4l2_buffer *v4l2_buf)
1048 {
1049         struct gspca_dev *gspca_dev = priv;
1050         struct gspca_frame *frame;
1051
1052         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1053             || v4l2_buf->index < 0
1054             || v4l2_buf->index >= gspca_dev->nframes)
1055                 return -EINVAL;
1056
1057         frame = &gspca_dev->frame[v4l2_buf->index];
1058         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1059         return 0;
1060 }
1061
1062 static int vidioc_streamon(struct file *file, void *priv,
1063                            enum v4l2_buf_type buf_type)
1064 {
1065         struct gspca_dev *gspca_dev = priv;
1066         int ret;
1067
1068         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1069                 return -EINVAL;
1070         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1071                 return -ERESTARTSYS;
1072         if (!gspca_dev->present) {
1073                 ret = -ENODEV;
1074                 goto out;
1075         }
1076         if (gspca_dev->nframes == 0) {
1077                 ret = -EINVAL;
1078                 goto out;
1079         }
1080         if (!gspca_dev->streaming) {
1081                 ret = gspca_init_transfer(gspca_dev);
1082                 if (ret < 0)
1083                         goto out;
1084         }
1085 #ifdef GSPCA_DEBUG
1086         if (gspca_debug & D_STREAM) {
1087                 PDEBUG_MODE("stream on OK",
1088                         gspca_dev->pixfmt,
1089                         gspca_dev->width,
1090                         gspca_dev->height);
1091         }
1092 #endif
1093         ret = 0;
1094 out:
1095         mutex_unlock(&gspca_dev->queue_lock);
1096         return ret;
1097 }
1098
1099 static int vidioc_streamoff(struct file *file, void *priv,
1100                                 enum v4l2_buf_type buf_type)
1101 {
1102         struct gspca_dev *gspca_dev = priv;
1103         int i, ret;
1104
1105         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1106                 return -EINVAL;
1107         if (!gspca_dev->streaming)
1108                 return 0;
1109         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1110                 return -ERESTARTSYS;
1111
1112         /* stop streaming */
1113         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1114                 ret = -ERESTARTSYS;
1115                 goto out;
1116         }
1117         gspca_stream_off(gspca_dev);
1118         mutex_unlock(&gspca_dev->usb_lock);
1119
1120         /* empty the application queues */
1121         for (i = 0; i < gspca_dev->nframes; i++)
1122                 gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1123         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
1124         gspca_dev->last_packet_type = DISCARD_PACKET;
1125         gspca_dev->sequence = 0;
1126         atomic_set(&gspca_dev->nevent, 0);
1127         ret = 0;
1128 out:
1129         mutex_unlock(&gspca_dev->queue_lock);
1130         return ret;
1131 }
1132
1133 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1134                         struct v4l2_jpegcompression *jpegcomp)
1135 {
1136         struct gspca_dev *gspca_dev = priv;
1137         int ret;
1138
1139         if (!gspca_dev->sd_desc->get_jcomp)
1140                 return -EINVAL;
1141         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1142                 return -ERESTARTSYS;
1143         ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1144         mutex_unlock(&gspca_dev->usb_lock);
1145         return ret;
1146 }
1147
1148 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1149                         struct v4l2_jpegcompression *jpegcomp)
1150 {
1151         struct gspca_dev *gspca_dev = priv;
1152         int ret;
1153
1154         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1155                 return -ERESTARTSYS;
1156         if (!gspca_dev->sd_desc->set_jcomp)
1157                 return -EINVAL;
1158         ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1159         mutex_unlock(&gspca_dev->usb_lock);
1160         return ret;
1161 }
1162
1163 static int vidioc_g_parm(struct file *filp, void *priv,
1164                         struct v4l2_streamparm *parm)
1165 {
1166         struct gspca_dev *gspca_dev = priv;
1167
1168         memset(parm, 0, sizeof *parm);
1169         parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1170         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1171         return 0;
1172 }
1173
1174 static int vidioc_s_parm(struct file *filp, void *priv,
1175                         struct v4l2_streamparm *parm)
1176 {
1177         struct gspca_dev *gspca_dev = priv;
1178         int n;
1179
1180         n = parm->parm.capture.readbuffers;
1181         if (n == 0 || n > GSPCA_MAX_FRAMES)
1182                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1183         else
1184                 gspca_dev->nbufread = n;
1185         return 0;
1186 }
1187
1188 static int vidioc_s_std(struct file *filp, void *priv,
1189                         v4l2_std_id *parm)
1190 {
1191         return 0;
1192 }
1193
1194 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1195 static int vidiocgmbuf(struct file *file, void *priv,
1196                         struct video_mbuf *mbuf)
1197 {
1198         struct gspca_dev *gspca_dev = file->private_data;
1199         int i;
1200
1201         PDEBUG(D_STREAM, "cgmbuf");
1202         if (gspca_dev->nframes == 0) {
1203                 int ret;
1204
1205                 {
1206                         struct v4l2_format fmt;
1207
1208                         memset(&fmt, 0, sizeof fmt);
1209                         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1210                         i = gspca_dev->cam.nmodes - 1;  /* highest mode */
1211                         fmt.fmt.pix.width = gspca_dev->cam.cam_mode[i].width;
1212                         fmt.fmt.pix.height = gspca_dev->cam.cam_mode[i].height;
1213                         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_BGR24;
1214                         ret = vidioc_s_fmt_vid_cap(file, priv, &fmt);
1215                         if (ret != 0)
1216                                 return ret;
1217                 }
1218                 {
1219                         struct v4l2_requestbuffers rb;
1220
1221                         memset(&rb, 0, sizeof rb);
1222                         rb.count = 4;
1223                         rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1224                         rb.memory = V4L2_MEMORY_MMAP;
1225                         ret = vidioc_reqbufs(file, priv, &rb);
1226                         if (ret != 0)
1227                                 return ret;
1228                 }
1229         }
1230         mbuf->frames = gspca_dev->nframes;
1231         mbuf->size = gspca_dev->frsz * gspca_dev->nframes;
1232         for (i = 0; i < mbuf->frames; i++)
1233                 mbuf->offsets[i] = gspca_dev->frame[i].v4l2_buf.m.offset;
1234         return 0;
1235 }
1236 #endif
1237
1238 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1239 {
1240         struct gspca_dev *gspca_dev = file->private_data;
1241         struct gspca_frame *frame;
1242         struct page *page;
1243         unsigned long addr, start, size;
1244         int i, ret;
1245
1246         start = vma->vm_start;
1247         size = vma->vm_end - vma->vm_start;
1248         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1249
1250         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1251                 return -ERESTARTSYS;
1252         if (!gspca_dev->present) {
1253                 ret = -ENODEV;
1254                 goto out;
1255         }
1256         if (gspca_dev->capt_file != file) {
1257                 ret = -EINVAL;
1258                 goto out;
1259         }
1260
1261         frame = NULL;
1262         for (i = 0; i < gspca_dev->nframes; ++i) {
1263                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1264                         PDEBUG(D_STREAM, "mmap bad memory type");
1265                         break;
1266                 }
1267                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1268                                                 == vma->vm_pgoff) {
1269                         frame = &gspca_dev->frame[i];
1270                         break;
1271                 }
1272         }
1273         if (frame == NULL) {
1274                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1275                 ret = -EINVAL;
1276                 goto out;
1277         }
1278 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1279         /* v4l1 maps all the buffers */
1280         if (i != 0
1281             || size != frame->v4l2_buf.length * gspca_dev->nframes)
1282 #endif
1283             if (size != frame->v4l2_buf.length) {
1284                 PDEBUG(D_STREAM, "mmap bad size");
1285                 ret = -EINVAL;
1286                 goto out;
1287         }
1288
1289         /*
1290          * - VM_IO marks the area as being a mmaped region for I/O to a
1291          *   device. It also prevents the region from being core dumped.
1292          */
1293         vma->vm_flags |= VM_IO;
1294
1295         addr = (unsigned long) frame->data;
1296         while (size > 0) {
1297                 page = vmalloc_to_page((void *) addr);
1298                 ret = vm_insert_page(vma, start, page);
1299                 if (ret < 0)
1300                         goto out;
1301                 start += PAGE_SIZE;
1302                 addr += PAGE_SIZE;
1303                 size -= PAGE_SIZE;
1304         }
1305
1306         vma->vm_ops = &gspca_vm_ops;
1307         vma->vm_private_data = frame;
1308         gspca_vm_open(vma);
1309         ret = 0;
1310 out:
1311         mutex_unlock(&gspca_dev->queue_lock);
1312         return ret;
1313 }
1314
1315 /*
1316  * wait for a video frame
1317  *
1318  * If a frame is ready, its index is returned.
1319  */
1320 static int frame_wait(struct gspca_dev *gspca_dev,
1321                         int nonblock_ing)
1322 {
1323         struct gspca_frame *frame;
1324         int i, j, ret;
1325
1326         /* check if a frame is ready */
1327         i = gspca_dev->fr_o;
1328         j = gspca_dev->fr_queue[i];
1329         frame = &gspca_dev->frame[j];
1330         if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE) {
1331                 atomic_dec(&gspca_dev->nevent);
1332                 goto ok;
1333         }
1334         if (nonblock_ing)                       /* no frame yet */
1335                 return -EAGAIN;
1336
1337         /* wait till a frame is ready */
1338         for (;;) {
1339                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1340                                         atomic_read(&gspca_dev->nevent) > 0,
1341                                         msecs_to_jiffies(3000));
1342                 if (ret <= 0) {
1343                         if (ret < 0)
1344                                 return ret;     /* interrupt */
1345                         return -EIO;            /* timeout */
1346                 }
1347                 atomic_dec(&gspca_dev->nevent);
1348                 if (!gspca_dev->streaming || !gspca_dev->present)
1349                         return -EIO;
1350                 i = gspca_dev->fr_o;
1351                 j = gspca_dev->fr_queue[i];
1352                 frame = &gspca_dev->frame[j];
1353                 if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1354                         break;
1355         }
1356 ok:
1357         gspca_dev->fr_o = (i + 1) % gspca_dev->nframes;
1358         PDEBUG(D_FRAM, "frame wait q:%d i:%d o:%d",
1359                 gspca_dev->fr_q,
1360                 gspca_dev->fr_i,
1361                 gspca_dev->fr_o);
1362
1363         if (gspca_dev->sd_desc->dq_callback) {
1364                 mutex_lock(&gspca_dev->usb_lock);
1365                 gspca_dev->sd_desc->dq_callback(gspca_dev);
1366                 mutex_unlock(&gspca_dev->usb_lock);
1367         }
1368         return j;
1369 }
1370
1371 /*
1372  * dequeue a video buffer
1373  *
1374  * If nonblock_ing is false, block until a buffer is available.
1375  */
1376 static int vidioc_dqbuf(struct file *file, void *priv,
1377                         struct v4l2_buffer *v4l2_buf)
1378 {
1379         struct gspca_dev *gspca_dev = priv;
1380         struct gspca_frame *frame;
1381         int i, ret;
1382
1383         PDEBUG(D_FRAM, "dqbuf");
1384         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1385                 return -EINVAL;
1386         if (v4l2_buf->memory != gspca_dev->memory)
1387                 return -EINVAL;
1388
1389         /* if not streaming, be sure the application will not loop forever */
1390         if (!(file->f_flags & O_NONBLOCK)
1391             && !gspca_dev->streaming && gspca_dev->users == 1)
1392                 return -EINVAL;
1393
1394         /* only the capturing file may dequeue */
1395         if (gspca_dev->capt_file != file)
1396                 return -EINVAL;
1397
1398         /* only one dequeue / read at a time */
1399         if (mutex_lock_interruptible(&gspca_dev->read_lock))
1400                 return -ERESTARTSYS;
1401
1402         ret = frame_wait(gspca_dev, file->f_flags & O_NONBLOCK);
1403         if (ret < 0)
1404                 goto out;
1405         i = ret;                                /* frame index */
1406         frame = &gspca_dev->frame[i];
1407         if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1408                 if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1409                                  frame->data,
1410                                  frame->v4l2_buf.bytesused)) {
1411                         PDEBUG(D_ERR|D_STREAM,
1412                                 "dqbuf cp to user failed");
1413                         ret = -EFAULT;
1414                         goto out;
1415                 }
1416         }
1417         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1418         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1419         PDEBUG(D_FRAM, "dqbuf %d", i);
1420         ret = 0;
1421 out:
1422         mutex_unlock(&gspca_dev->read_lock);
1423         return ret;
1424 }
1425
1426 /*
1427  * queue a video buffer
1428  *
1429  * Attempting to queue a buffer that has already been
1430  * queued will return -EINVAL.
1431  */
1432 static int vidioc_qbuf(struct file *file, void *priv,
1433                         struct v4l2_buffer *v4l2_buf)
1434 {
1435         struct gspca_dev *gspca_dev = priv;
1436         struct gspca_frame *frame;
1437         int i, index, ret;
1438
1439         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1440         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1441                 return -EINVAL;
1442
1443         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1444                 return -ERESTARTSYS;
1445
1446         index = v4l2_buf->index;
1447         if ((unsigned) index >= gspca_dev->nframes) {
1448                 PDEBUG(D_FRAM,
1449                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
1450                 ret = -EINVAL;
1451                 goto out;
1452         }
1453         if (v4l2_buf->memory != gspca_dev->memory) {
1454                 PDEBUG(D_FRAM, "qbuf bad memory type");
1455                 ret = -EINVAL;
1456                 goto out;
1457         }
1458
1459         frame = &gspca_dev->frame[index];
1460         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1461                 PDEBUG(D_FRAM, "qbuf bad state");
1462                 ret = -EINVAL;
1463                 goto out;
1464         }
1465
1466         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1467 /*      frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE; */
1468
1469         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1470                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1471                 frame->v4l2_buf.length = v4l2_buf->length;
1472         }
1473
1474         /* put the buffer in the 'queued' queue */
1475         i = gspca_dev->fr_q;
1476         gspca_dev->fr_queue[i] = index;
1477         gspca_dev->fr_q = (i + 1) % gspca_dev->nframes;
1478         PDEBUG(D_FRAM, "qbuf q:%d i:%d o:%d",
1479                 gspca_dev->fr_q,
1480                 gspca_dev->fr_i,
1481                 gspca_dev->fr_o);
1482
1483         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1484         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1485         ret = 0;
1486 out:
1487         mutex_unlock(&gspca_dev->queue_lock);
1488         return ret;
1489 }
1490
1491 /*
1492  * allocate the resources for read()
1493  */
1494 static int read_alloc(struct gspca_dev *gspca_dev,
1495                         struct file *file)
1496 {
1497         struct v4l2_buffer v4l2_buf;
1498         int i, ret;
1499
1500         PDEBUG(D_STREAM, "read alloc");
1501         if (gspca_dev->nframes == 0) {
1502                 struct v4l2_requestbuffers rb;
1503
1504                 memset(&rb, 0, sizeof rb);
1505                 rb.count = gspca_dev->nbufread;
1506                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1507                 rb.memory = GSPCA_MEMORY_READ;
1508                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
1509                 if (ret != 0) {
1510                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1511                         return ret;
1512                 }
1513                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1514                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1515                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1516                 for (i = 0; i < gspca_dev->nbufread; i++) {
1517                         v4l2_buf.index = i;
1518                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1519                         if (ret != 0) {
1520                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1521                                 return ret;
1522                         }
1523                 }
1524                 gspca_dev->memory = GSPCA_MEMORY_READ;
1525         }
1526
1527         /* start streaming */
1528         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1529         if (ret != 0)
1530                 PDEBUG(D_STREAM, "read streamon err %d", ret);
1531         return ret;
1532 }
1533
1534 static unsigned int dev_poll(struct file *file, poll_table *wait)
1535 {
1536         struct gspca_dev *gspca_dev = file->private_data;
1537         int i, ret;
1538
1539         PDEBUG(D_FRAM, "poll");
1540
1541         poll_wait(file, &gspca_dev->wq, wait);
1542         if (!gspca_dev->present)
1543                 return POLLERR;
1544
1545         /* if reqbufs is not done, the user would use read() */
1546         if (gspca_dev->nframes == 0) {
1547                 if (gspca_dev->memory != GSPCA_MEMORY_NO)
1548                         return POLLERR;         /* not the 1st time */
1549                 ret = read_alloc(gspca_dev, file);
1550                 if (ret != 0)
1551                         return POLLERR;
1552         }
1553
1554         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
1555                 return POLLERR;
1556         if (!gspca_dev->present) {
1557                 ret = POLLERR;
1558                 goto out;
1559         }
1560
1561         /* check the next incoming buffer */
1562         i = gspca_dev->fr_o;
1563         i = gspca_dev->fr_queue[i];
1564         if (gspca_dev->frame[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1565                 ret = POLLIN | POLLRDNORM;      /* something to read */
1566         else
1567                 ret = 0;
1568 out:
1569         mutex_unlock(&gspca_dev->queue_lock);
1570         return ret;
1571 }
1572
1573 static ssize_t dev_read(struct file *file, char __user *data,
1574                     size_t count, loff_t *ppos)
1575 {
1576         struct gspca_dev *gspca_dev = file->private_data;
1577         struct gspca_frame *frame;
1578         struct v4l2_buffer v4l2_buf;
1579         struct timeval timestamp;
1580         int n, ret, ret2;
1581
1582         PDEBUG(D_FRAM, "read (%zd)", count);
1583         if (!gspca_dev->present)
1584                 return -ENODEV;
1585         switch (gspca_dev->memory) {
1586         case GSPCA_MEMORY_NO:                   /* first time */
1587                 ret = read_alloc(gspca_dev, file);
1588                 if (ret != 0)
1589                         return ret;
1590                 break;
1591         case GSPCA_MEMORY_READ:
1592                 if (gspca_dev->capt_file == file)
1593                         break;
1594                 /* fall thru */
1595         default:
1596                 return -EINVAL;
1597         }
1598
1599         /* get a frame */
1600         jiffies_to_timeval(get_jiffies_64(), &timestamp);
1601         timestamp.tv_sec--;
1602         n = 2;
1603         for (;;) {
1604                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1605                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1606                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1607                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1608                 if (ret != 0) {
1609                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1610                         return ret;
1611                 }
1612
1613                 /* if the process slept for more than 1 second,
1614                  * get anewer frame */
1615                 frame = &gspca_dev->frame[v4l2_buf.index];
1616                 if (--n < 0)
1617                         break;                  /* avoid infinite loop */
1618                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1619                         break;
1620                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1621                 if (ret != 0) {
1622                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
1623                         return ret;
1624                 }
1625         }
1626
1627         /* copy the frame */
1628         if (count > frame->v4l2_buf.bytesused)
1629                 count = frame->v4l2_buf.bytesused;
1630         ret = copy_to_user(data, frame->data, count);
1631         if (ret != 0) {
1632                 PDEBUG(D_ERR|D_STREAM,
1633                         "read cp to user lack %d / %zd", ret, count);
1634                 ret = -EFAULT;
1635                 goto out;
1636         }
1637         ret = count;
1638 out:
1639         /* in each case, requeue the buffer */
1640         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1641         if (ret2 != 0)
1642                 return ret2;
1643         return ret;
1644 }
1645
1646 static void dev_release(struct video_device *vfd)
1647 {
1648         /* nothing */
1649 }
1650
1651 static struct file_operations dev_fops = {
1652         .owner = THIS_MODULE,
1653         .open = dev_open,
1654         .release = dev_close,
1655         .read = dev_read,
1656         .mmap = dev_mmap,
1657         .ioctl = video_ioctl2,
1658 #ifdef CONFIG_COMPAT
1659         .compat_ioctl = v4l_compat_ioctl32,
1660 #endif
1661         .llseek = no_llseek,
1662         .poll   = dev_poll,
1663 };
1664
1665 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1666         .vidioc_querycap        = vidioc_querycap,
1667         .vidioc_dqbuf           = vidioc_dqbuf,
1668         .vidioc_qbuf            = vidioc_qbuf,
1669         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1670         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1671         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1672         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1673         .vidioc_streamon        = vidioc_streamon,
1674         .vidioc_queryctrl       = vidioc_queryctrl,
1675         .vidioc_g_ctrl          = vidioc_g_ctrl,
1676         .vidioc_s_ctrl          = vidioc_s_ctrl,
1677         .vidioc_querymenu       = vidioc_querymenu,
1678         .vidioc_enum_input      = vidioc_enum_input,
1679         .vidioc_g_input         = vidioc_g_input,
1680         .vidioc_s_input         = vidioc_s_input,
1681         .vidioc_reqbufs         = vidioc_reqbufs,
1682         .vidioc_querybuf        = vidioc_querybuf,
1683         .vidioc_streamoff       = vidioc_streamoff,
1684         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1685         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1686         .vidioc_g_parm          = vidioc_g_parm,
1687         .vidioc_s_parm          = vidioc_s_parm,
1688         .vidioc_s_std           = vidioc_s_std,
1689 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1690         .vidiocgmbuf          = vidiocgmbuf,
1691 #endif
1692 };
1693
1694 static struct video_device gspca_template = {
1695         .name = "gspca main driver",
1696         .fops = &dev_fops,
1697         .ioctl_ops = &dev_ioctl_ops,
1698         .release = dev_release,         /* mandatory */
1699         .minor = -1,
1700 };
1701
1702 /*
1703  * probe and create a new gspca device
1704  *
1705  * This function must be called by the sub-driver when it is
1706  * called for probing a new device.
1707  */
1708 int gspca_dev_probe(struct usb_interface *intf,
1709                 const struct usb_device_id *id,
1710                 const struct sd_desc *sd_desc,
1711                 int dev_size,
1712                 struct module *module)
1713 {
1714         struct usb_interface_descriptor *interface;
1715         struct gspca_dev *gspca_dev;
1716         struct usb_device *dev = interface_to_usbdev(intf);
1717         int ret;
1718
1719         PDEBUG(D_PROBE, "probing %04x:%04x", id->idVendor, id->idProduct);
1720
1721         /* we don't handle multi-config cameras */
1722         if (dev->descriptor.bNumConfigurations != 1)
1723                 return -ENODEV;
1724         interface = &intf->cur_altsetting->desc;
1725         if (interface->bInterfaceNumber > 0)
1726                 return -ENODEV;
1727
1728         /* create the device */
1729         if (dev_size < sizeof *gspca_dev)
1730                 dev_size = sizeof *gspca_dev;
1731         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
1732         if (gspca_dev == NULL) {
1733                 err("couldn't kzalloc gspca struct");
1734                 return -EIO;
1735         }
1736         gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
1737         if (!gspca_dev->usb_buf) {
1738                 err("out of memory");
1739                 ret = -EIO;
1740                 goto out;
1741         }
1742         gspca_dev->dev = dev;
1743         gspca_dev->iface = interface->bInterfaceNumber;
1744         gspca_dev->nbalt = intf->num_altsetting;
1745         gspca_dev->sd_desc = sd_desc;
1746 /*      gspca_dev->users = 0;                   (done by kzalloc) */
1747         gspca_dev->nbufread = 2;
1748
1749         /* configure the subdriver and initialize the USB device */
1750         ret = gspca_dev->sd_desc->config(gspca_dev, id);
1751         if (ret < 0)
1752                 goto out;
1753         ret = gspca_dev->sd_desc->init(gspca_dev);
1754         if (ret < 0)
1755                 goto out;
1756         ret = gspca_set_alt0(gspca_dev);
1757         if (ret < 0)
1758                 goto out;
1759         gspca_set_default_mode(gspca_dev);
1760
1761         mutex_init(&gspca_dev->usb_lock);
1762         mutex_init(&gspca_dev->read_lock);
1763         mutex_init(&gspca_dev->queue_lock);
1764         init_waitqueue_head(&gspca_dev->wq);
1765
1766         /* init video stuff */
1767         memcpy(&gspca_dev->vdev, &gspca_template, sizeof gspca_template);
1768         gspca_dev->vdev.parent = &dev->dev;
1769         memcpy(&gspca_dev->fops, &dev_fops, sizeof gspca_dev->fops);
1770         gspca_dev->vdev.fops = &gspca_dev->fops;
1771         gspca_dev->fops.owner = module;         /* module protection */
1772         gspca_dev->present = 1;
1773         ret = video_register_device(&gspca_dev->vdev,
1774                                   VFL_TYPE_GRABBER,
1775                                   video_nr);
1776         if (ret < 0) {
1777                 err("video_register_device err %d", ret);
1778                 goto out;
1779         }
1780
1781         usb_set_intfdata(intf, gspca_dev);
1782         PDEBUG(D_PROBE, "probe ok");
1783         return 0;
1784 out:
1785         kfree(gspca_dev->usb_buf);
1786         kfree(gspca_dev);
1787         return ret;
1788 }
1789 EXPORT_SYMBOL(gspca_dev_probe);
1790
1791 /*
1792  * USB disconnection
1793  *
1794  * This function must be called by the sub-driver
1795  * when the device disconnects, after the specific resources are freed.
1796  */
1797 void gspca_disconnect(struct usb_interface *intf)
1798 {
1799         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1800
1801         if (!gspca_dev)
1802                 return;
1803         gspca_dev->present = 0;
1804         mutex_lock(&gspca_dev->queue_lock);
1805         mutex_lock(&gspca_dev->usb_lock);
1806         gspca_dev->streaming = 0;
1807         destroy_urbs(gspca_dev);
1808         mutex_unlock(&gspca_dev->usb_lock);
1809         mutex_unlock(&gspca_dev->queue_lock);
1810         while (gspca_dev->users != 0) {         /* wait until fully closed */
1811                 atomic_inc(&gspca_dev->nevent);
1812                 wake_up_interruptible(&gspca_dev->wq);  /* wake processes */
1813                 schedule();
1814         }
1815 /* We don't want people trying to open up the device */
1816         video_unregister_device(&gspca_dev->vdev);
1817 /* Free the memory */
1818         kfree(gspca_dev->usb_buf);
1819         kfree(gspca_dev);
1820         PDEBUG(D_PROBE, "disconnect complete");
1821 }
1822 EXPORT_SYMBOL(gspca_disconnect);
1823
1824 #ifdef CONFIG_PM
1825 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
1826 {
1827         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1828
1829         if (!gspca_dev->streaming)
1830                 return 0;
1831         gspca_dev->frozen = 1;          /* avoid urb error messages */
1832         if (gspca_dev->sd_desc->stopN)
1833                 gspca_dev->sd_desc->stopN(gspca_dev);
1834         destroy_urbs(gspca_dev);
1835         gspca_set_alt0(gspca_dev);
1836         if (gspca_dev->sd_desc->stop0)
1837                 gspca_dev->sd_desc->stop0(gspca_dev);
1838         return 0;
1839 }
1840 EXPORT_SYMBOL(gspca_suspend);
1841
1842 int gspca_resume(struct usb_interface *intf)
1843 {
1844         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1845
1846         gspca_dev->frozen = 0;
1847         gspca_dev->sd_desc->init(gspca_dev);
1848         if (gspca_dev->streaming)
1849                 return gspca_init_transfer(gspca_dev);
1850         return 0;
1851 }
1852 EXPORT_SYMBOL(gspca_resume);
1853 #endif
1854 /* -- cam driver utility functions -- */
1855
1856 /* auto gain and exposure algorithm based on the knee algorithm described here:
1857    http://ytse.tricolour.net/docs/LowLightOptimization.html
1858
1859    Returns 0 if no changes were made, 1 if the gain and or exposure settings
1860    where changed. */
1861 int gspca_auto_gain_n_exposure(struct gspca_dev *gspca_dev, int avg_lum,
1862         int desired_avg_lum, int deadzone, int gain_knee, int exposure_knee)
1863 {
1864         int i, steps, gain, orig_gain, exposure, orig_exposure, autogain;
1865         const struct ctrl *gain_ctrl = NULL;
1866         const struct ctrl *exposure_ctrl = NULL;
1867         const struct ctrl *autogain_ctrl = NULL;
1868         int retval = 0;
1869
1870         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1871                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_GAIN)
1872                         gain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1873                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_EXPOSURE)
1874                         exposure_ctrl = &gspca_dev->sd_desc->ctrls[i];
1875                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_AUTOGAIN)
1876                         autogain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1877         }
1878         if (!gain_ctrl || !exposure_ctrl || !autogain_ctrl) {
1879                 PDEBUG(D_ERR, "Error: gspca_auto_gain_n_exposure called "
1880                         "on cam without (auto)gain/exposure");
1881                 return 0;
1882         }
1883
1884         if (gain_ctrl->get(gspca_dev, &gain) ||
1885                         exposure_ctrl->get(gspca_dev, &exposure) ||
1886                         autogain_ctrl->get(gspca_dev, &autogain) || !autogain)
1887                 return 0;
1888
1889         orig_gain = gain;
1890         orig_exposure = exposure;
1891
1892         /* If we are of a multiple of deadzone, do multiple steps to reach the
1893            desired lumination fast (with the risc of a slight overshoot) */
1894         steps = abs(desired_avg_lum - avg_lum) / deadzone;
1895
1896         PDEBUG(D_FRAM, "autogain: lum: %d, desired: %d, steps: %d\n",
1897                 avg_lum, desired_avg_lum, steps);
1898
1899         for (i = 0; i < steps; i++) {
1900                 if (avg_lum > desired_avg_lum) {
1901                         if (gain > gain_knee)
1902                                 gain--;
1903                         else if (exposure > exposure_knee)
1904                                 exposure--;
1905                         else if (gain > gain_ctrl->qctrl.default_value)
1906                                 gain--;
1907                         else if (exposure > exposure_ctrl->qctrl.minimum)
1908                                 exposure--;
1909                         else if (gain > gain_ctrl->qctrl.minimum)
1910                                 gain--;
1911                         else
1912                                 break;
1913                 } else {
1914                         if (gain < gain_ctrl->qctrl.default_value)
1915                                 gain++;
1916                         else if (exposure < exposure_knee)
1917                                 exposure++;
1918                         else if (gain < gain_knee)
1919                                 gain++;
1920                         else if (exposure < exposure_ctrl->qctrl.maximum)
1921                                 exposure++;
1922                         else if (gain < gain_ctrl->qctrl.maximum)
1923                                 gain++;
1924                         else
1925                                 break;
1926                 }
1927         }
1928
1929         if (gain != orig_gain) {
1930                 gain_ctrl->set(gspca_dev, gain);
1931                 retval = 1;
1932         }
1933         if (exposure != orig_exposure) {
1934                 exposure_ctrl->set(gspca_dev, exposure);
1935                 retval = 1;
1936         }
1937
1938         return retval;
1939 }
1940 EXPORT_SYMBOL(gspca_auto_gain_n_exposure);
1941
1942 /* -- module insert / remove -- */
1943 static int __init gspca_init(void)
1944 {
1945         info("main v%d.%d.%d registered",
1946                 (DRIVER_VERSION_NUMBER >> 16) & 0xff,
1947                 (DRIVER_VERSION_NUMBER >> 8) & 0xff,
1948                 DRIVER_VERSION_NUMBER & 0xff);
1949         return 0;
1950 }
1951 static void __exit gspca_exit(void)
1952 {
1953         info("main deregistered");
1954 }
1955
1956 module_init(gspca_init);
1957 module_exit(gspca_exit);
1958
1959 #ifdef GSPCA_DEBUG
1960 module_param_named(debug, gspca_debug, int, 0644);
1961 MODULE_PARM_DESC(debug,
1962                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
1963                 " 0x08:stream 0x10:frame 0x20:packet 0x40:USBin 0x80:USBout"
1964                 " 0x0100: v4l2");
1965 #endif