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