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