]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/media/video/gspca/gspca.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/rusty/linux-2.6-cpumask
[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 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, 5, 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                                           __u8 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                         return ep;
454         }
455         return NULL;
456 }
457
458 /*
459  * look for an input (isoc or bulk) endpoint
460  *
461  * The endpoint is defined by the subdriver.
462  * Use only the first isoc (some Zoran - 0x0572:0x0001 - have two such ep).
463  * This routine may be called many times when the bandwidth is too small
464  * (the bandwidth is checked on urb submit).
465  */
466 static struct usb_host_endpoint *get_ep(struct gspca_dev *gspca_dev)
467 {
468         struct usb_interface *intf;
469         struct usb_host_endpoint *ep;
470         int i, ret;
471
472         intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
473         ep = NULL;
474         i = gspca_dev->alt;                     /* previous alt setting */
475
476         /* try isoc */
477         while (--i >= 0) {
478                 ep = alt_xfer(&intf->altsetting[i],
479                                 USB_ENDPOINT_XFER_ISOC);
480                 if (ep)
481                         break;
482         }
483
484         /* if no isoc, try bulk (alt 0 only) */
485         if (ep == NULL) {
486                 ep = alt_xfer(&intf->altsetting[0],
487                                 USB_ENDPOINT_XFER_BULK);
488                 if (ep == NULL) {
489                         err("no transfer endpoint found");
490                         return NULL;
491                 }
492                 i = 0;
493                 gspca_dev->bulk = 1;
494         }
495         PDEBUG(D_STREAM, "use alt %d ep 0x%02x",
496                         i, ep->desc.bEndpointAddress);
497         if (i > 0) {
498                 ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, i);
499                 if (ret < 0) {
500                         err("set interface err %d", ret);
501                         return NULL;
502                 }
503         }
504         gspca_dev->alt = i;             /* memorize the current alt setting */
505         return ep;
506 }
507
508 /*
509  * create the URBs for image transfer
510  */
511 static int create_urbs(struct gspca_dev *gspca_dev,
512                         struct usb_host_endpoint *ep)
513 {
514         struct urb *urb;
515         int n, nurbs, i, psize, npkt, bsize;
516
517         /* calculate the packet size and the number of packets */
518         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
519
520         if (!gspca_dev->bulk) {                 /* isoc */
521
522                 /* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
523                 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
524                 npkt = ISO_MAX_SIZE / psize;
525                 if (npkt > ISO_MAX_PKT)
526                         npkt = ISO_MAX_PKT;
527                 bsize = psize * npkt;
528                 PDEBUG(D_STREAM,
529                         "isoc %d pkts size %d = bsize:%d",
530                         npkt, psize, bsize);
531                 nurbs = DEF_NURBS;
532         } else {                                /* bulk */
533                 npkt = 0;
534                 bsize = gspca_dev->cam.bulk_size;
535                 if (bsize == 0)
536                         bsize = psize;
537                 PDEBUG(D_STREAM, "bulk bsize:%d", bsize);
538                 if (gspca_dev->cam.bulk_nurbs != 0)
539                         nurbs = gspca_dev->cam.bulk_nurbs;
540                 else
541                         nurbs = 1;
542         }
543
544         gspca_dev->nurbs = nurbs;
545         for (n = 0; n < nurbs; n++) {
546                 urb = usb_alloc_urb(npkt, GFP_KERNEL);
547                 if (!urb) {
548                         err("usb_alloc_urb failed");
549                         destroy_urbs(gspca_dev);
550                         return -ENOMEM;
551                 }
552                 urb->transfer_buffer = usb_buffer_alloc(gspca_dev->dev,
553                                                 bsize,
554                                                 GFP_KERNEL,
555                                                 &urb->transfer_dma);
556
557                 if (urb->transfer_buffer == NULL) {
558                         usb_free_urb(urb);
559                         err("usb_buffer_urb failed");
560                         destroy_urbs(gspca_dev);
561                         return -ENOMEM;
562                 }
563                 gspca_dev->urb[n] = urb;
564                 urb->dev = gspca_dev->dev;
565                 urb->context = gspca_dev;
566                 urb->transfer_buffer_length = bsize;
567                 if (npkt != 0) {                /* ISOC */
568                         urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
569                                                     ep->desc.bEndpointAddress);
570                         urb->transfer_flags = URB_ISO_ASAP
571                                         | URB_NO_TRANSFER_DMA_MAP;
572                         urb->interval = ep->desc.bInterval;
573                         urb->complete = isoc_irq;
574                         urb->number_of_packets = npkt;
575                         for (i = 0; i < npkt; i++) {
576                                 urb->iso_frame_desc[i].length = psize;
577                                 urb->iso_frame_desc[i].offset = psize * i;
578                         }
579                 } else {                /* bulk */
580                         urb->pipe = usb_rcvbulkpipe(gspca_dev->dev,
581                                                 ep->desc.bEndpointAddress),
582                         urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
583                         urb->complete = bulk_irq;
584                 }
585         }
586         return 0;
587 }
588
589 /*
590  * start the USB transfer
591  */
592 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
593 {
594         struct usb_host_endpoint *ep;
595         int n, ret;
596
597         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
598                 return -ERESTARTSYS;
599
600         if (!gspca_dev->present) {
601                 ret = -ENODEV;
602                 goto out;
603         }
604
605         /* set the higher alternate setting and
606          * loop until urb submit succeeds */
607         gspca_dev->alt = gspca_dev->nbalt;
608         for (;;) {
609                 PDEBUG(D_STREAM, "init transfer alt %d", gspca_dev->alt);
610                 ep = get_ep(gspca_dev);
611                 if (ep == NULL) {
612                         ret = -EIO;
613                         goto out;
614                 }
615                 ret = create_urbs(gspca_dev, ep);
616                 if (ret < 0)
617                         goto out;
618
619                 /* clear the bulk endpoint */
620                 if (gspca_dev->bulk)
621                         usb_clear_halt(gspca_dev->dev,
622                                         gspca_dev->urb[0]->pipe);
623
624                 /* start the cam */
625                 ret = gspca_dev->sd_desc->start(gspca_dev);
626                 if (ret < 0) {
627                         destroy_urbs(gspca_dev);
628                         goto out;
629                 }
630                 gspca_dev->streaming = 1;
631
632                 /* some bulk transfers are started by the subdriver */
633                 if (gspca_dev->bulk && gspca_dev->cam.bulk_nurbs == 0)
634                         break;
635
636                 /* submit the URBs */
637                 for (n = 0; n < gspca_dev->nurbs; n++) {
638                         ret = usb_submit_urb(gspca_dev->urb[n], GFP_KERNEL);
639                         if (ret < 0) {
640                                 PDEBUG(D_ERR|D_STREAM,
641                                         "usb_submit_urb [%d] err %d", n, ret);
642                                 gspca_dev->streaming = 0;
643                                 destroy_urbs(gspca_dev);
644                                 if (ret == -ENOSPC) {
645                                         msleep(20);     /* wait for kill
646                                                          * complete */
647                                         break;  /* try the previous alt */
648                                 }
649                                 goto out;
650                         }
651                 }
652                 if (ret >= 0)
653                         break;
654         }
655 out:
656         mutex_unlock(&gspca_dev->usb_lock);
657         return ret;
658 }
659
660 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
661 {
662         int ret;
663
664         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
665         if (ret < 0)
666                 PDEBUG(D_ERR|D_STREAM, "set alt 0 err %d", ret);
667         return ret;
668 }
669
670 /* Note: both the queue and the usb locks should be held when calling this */
671 static void gspca_stream_off(struct gspca_dev *gspca_dev)
672 {
673         gspca_dev->streaming = 0;
674         if (gspca_dev->present) {
675                 if (gspca_dev->sd_desc->stopN)
676                         gspca_dev->sd_desc->stopN(gspca_dev);
677                 destroy_urbs(gspca_dev);
678                 gspca_set_alt0(gspca_dev);
679         }
680
681         /* always call stop0 to free the subdriver's resources */
682         if (gspca_dev->sd_desc->stop0)
683                 gspca_dev->sd_desc->stop0(gspca_dev);
684         PDEBUG(D_STREAM, "stream off OK");
685 }
686
687 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
688 {
689         int i;
690
691         i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
692         gspca_dev->curr_mode = i;
693         gspca_dev->width = gspca_dev->cam.cam_mode[i].width;
694         gspca_dev->height = gspca_dev->cam.cam_mode[i].height;
695         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixelformat;
696 }
697
698 static int wxh_to_mode(struct gspca_dev *gspca_dev,
699                         int width, int height)
700 {
701         int i;
702
703         for (i = gspca_dev->cam.nmodes; --i > 0; ) {
704                 if (width >= gspca_dev->cam.cam_mode[i].width
705                     && height >= gspca_dev->cam.cam_mode[i].height)
706                         break;
707         }
708         return i;
709 }
710
711 /*
712  * search a mode with the right pixel format
713  */
714 static int gspca_get_mode(struct gspca_dev *gspca_dev,
715                         int mode,
716                         int pixfmt)
717 {
718         int modeU, modeD;
719
720         modeU = modeD = mode;
721         while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
722                 if (--modeD >= 0) {
723                         if (gspca_dev->cam.cam_mode[modeD].pixelformat
724                                                                 == pixfmt)
725                                 return modeD;
726                 }
727                 if (++modeU < gspca_dev->cam.nmodes) {
728                         if (gspca_dev->cam.cam_mode[modeU].pixelformat
729                                                                 == pixfmt)
730                                 return modeU;
731                 }
732         }
733         return -EINVAL;
734 }
735
736 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
737                                 struct v4l2_fmtdesc *fmtdesc)
738 {
739         struct gspca_dev *gspca_dev = priv;
740         int i, j, index;
741         __u32 fmt_tb[8];
742
743         /* give an index to each format */
744         index = 0;
745         j = 0;
746         for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
747                 fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
748                 j = 0;
749                 for (;;) {
750                         if (fmt_tb[j] == fmt_tb[index])
751                                 break;
752                         j++;
753                 }
754                 if (j == index) {
755                         if (fmtdesc->index == index)
756                                 break;          /* new format */
757                         index++;
758                         if (index >= ARRAY_SIZE(fmt_tb))
759                                 return -EINVAL;
760                 }
761         }
762         if (i < 0)
763                 return -EINVAL;         /* no more format */
764
765         fmtdesc->pixelformat = fmt_tb[index];
766         if (gspca_is_compressed(fmt_tb[index]))
767                 fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
768         fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
769         fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
770         fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
771         fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
772         fmtdesc->description[4] = '\0';
773         return 0;
774 }
775
776 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
777                             struct v4l2_format *fmt)
778 {
779         struct gspca_dev *gspca_dev = priv;
780         int mode;
781
782         mode = gspca_dev->curr_mode;
783         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
784                 sizeof fmt->fmt.pix);
785         return 0;
786 }
787
788 static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
789                         struct v4l2_format *fmt)
790 {
791         int w, h, mode, mode2;
792
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 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 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         int ret;
963
964         /* protect the access to the usb device */
965         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
966                 return -ERESTARTSYS;
967         if (!gspca_dev->present) {
968                 ret = -ENODEV;
969                 goto out;
970         }
971         strncpy(cap->driver, gspca_dev->sd_desc->name, sizeof cap->driver);
972         if (gspca_dev->dev->product != NULL) {
973                 strncpy(cap->card, gspca_dev->dev->product,
974                         sizeof cap->card);
975         } else {
976                 snprintf(cap->card, sizeof cap->card,
977                         "USB Camera (%04x:%04x)",
978                         le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
979                         le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
980         }
981         usb_make_path(gspca_dev->dev, cap->bus_info, sizeof(cap->bus_info));
982         cap->version = DRIVER_VERSION_NUMBER;
983         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
984                           | V4L2_CAP_STREAMING
985                           | V4L2_CAP_READWRITE;
986         ret = 0;
987 out:
988         mutex_unlock(&gspca_dev->usb_lock);
989         return ret;
990 }
991
992 static int vidioc_queryctrl(struct file *file, void *priv,
993                            struct v4l2_queryctrl *q_ctrl)
994 {
995         struct gspca_dev *gspca_dev = priv;
996         int i, ix;
997         u32 id;
998
999         ix = -1;
1000         id = q_ctrl->id;
1001         if (id & V4L2_CTRL_FLAG_NEXT_CTRL) {
1002                 id &= V4L2_CTRL_ID_MASK;
1003                 id++;
1004                 for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1005                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id < id)
1006                                 continue;
1007                         if (ix < 0) {
1008                                 ix = i;
1009                                 continue;
1010                         }
1011                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id
1012                                     > gspca_dev->sd_desc->ctrls[ix].qctrl.id)
1013                                 continue;
1014                         ix = i;
1015                 }
1016         }
1017         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1018                 if (id == gspca_dev->sd_desc->ctrls[i].qctrl.id) {
1019                         ix = i;
1020                         break;
1021                 }
1022         }
1023         if (ix < 0)
1024                 return -EINVAL;
1025         memcpy(q_ctrl, &gspca_dev->sd_desc->ctrls[ix].qctrl,
1026                 sizeof *q_ctrl);
1027         if (gspca_dev->ctrl_dis & (1 << ix))
1028                 q_ctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
1029         return 0;
1030 }
1031
1032 static int vidioc_s_ctrl(struct file *file, void *priv,
1033                          struct v4l2_control *ctrl)
1034 {
1035         struct gspca_dev *gspca_dev = priv;
1036         const struct ctrl *ctrls;
1037         int i, ret;
1038
1039         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1040              i < gspca_dev->sd_desc->nctrls;
1041              i++, ctrls++) {
1042                 if (ctrl->id != ctrls->qctrl.id)
1043                         continue;
1044                 if (gspca_dev->ctrl_dis & (1 << i))
1045                         return -EINVAL;
1046                 if (ctrl->value < ctrls->qctrl.minimum
1047                     || ctrl->value > ctrls->qctrl.maximum)
1048                         return -ERANGE;
1049                 PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
1050                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1051                         return -ERESTARTSYS;
1052                 if (gspca_dev->present)
1053                         ret = ctrls->set(gspca_dev, ctrl->value);
1054                 else
1055                         ret = -ENODEV;
1056                 mutex_unlock(&gspca_dev->usb_lock);
1057                 return ret;
1058         }
1059         return -EINVAL;
1060 }
1061
1062 static int vidioc_g_ctrl(struct file *file, void *priv,
1063                          struct v4l2_control *ctrl)
1064 {
1065         struct gspca_dev *gspca_dev = priv;
1066
1067         const struct ctrl *ctrls;
1068         int i, ret;
1069
1070         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1071              i < gspca_dev->sd_desc->nctrls;
1072              i++, ctrls++) {
1073                 if (ctrl->id != ctrls->qctrl.id)
1074                         continue;
1075                 if (gspca_dev->ctrl_dis & (1 << i))
1076                         return -EINVAL;
1077                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1078                         return -ERESTARTSYS;
1079                 if (gspca_dev->present)
1080                         ret = ctrls->get(gspca_dev, &ctrl->value);
1081                 else
1082                         ret = -ENODEV;
1083                 mutex_unlock(&gspca_dev->usb_lock);
1084                 return ret;
1085         }
1086         return -EINVAL;
1087 }
1088
1089 /*fixme: have an audio flag in gspca_dev?*/
1090 static int vidioc_s_audio(struct file *file, void *priv,
1091                          struct v4l2_audio *audio)
1092 {
1093         if (audio->index != 0)
1094                 return -EINVAL;
1095         return 0;
1096 }
1097
1098 static int vidioc_g_audio(struct file *file, void *priv,
1099                          struct v4l2_audio *audio)
1100 {
1101         strcpy(audio->name, "Microphone");
1102         return 0;
1103 }
1104
1105 static int vidioc_enumaudio(struct file *file, void *priv,
1106                          struct v4l2_audio *audio)
1107 {
1108         if (audio->index != 0)
1109                 return -EINVAL;
1110
1111         strcpy(audio->name, "Microphone");
1112         audio->capability = 0;
1113         audio->mode = 0;
1114         return 0;
1115 }
1116
1117 static int vidioc_querymenu(struct file *file, void *priv,
1118                             struct v4l2_querymenu *qmenu)
1119 {
1120         struct gspca_dev *gspca_dev = priv;
1121
1122         if (!gspca_dev->sd_desc->querymenu)
1123                 return -EINVAL;
1124         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
1125 }
1126
1127 static int vidioc_enum_input(struct file *file, void *priv,
1128                                 struct v4l2_input *input)
1129 {
1130         struct gspca_dev *gspca_dev = priv;
1131
1132         if (input->index != 0)
1133                 return -EINVAL;
1134         input->type = V4L2_INPUT_TYPE_CAMERA;
1135         strncpy(input->name, gspca_dev->sd_desc->name,
1136                 sizeof input->name);
1137         return 0;
1138 }
1139
1140 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1141 {
1142         *i = 0;
1143         return 0;
1144 }
1145
1146 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1147 {
1148         if (i > 0)
1149                 return -EINVAL;
1150         return (0);
1151 }
1152
1153 static int vidioc_reqbufs(struct file *file, void *priv,
1154                           struct v4l2_requestbuffers *rb)
1155 {
1156         struct gspca_dev *gspca_dev = priv;
1157         int i, ret = 0;
1158
1159         switch (rb->memory) {
1160         case GSPCA_MEMORY_READ:                 /* (internal call) */
1161         case V4L2_MEMORY_MMAP:
1162         case V4L2_MEMORY_USERPTR:
1163                 break;
1164         default:
1165                 return -EINVAL;
1166         }
1167         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1168                 return -ERESTARTSYS;
1169
1170         if (gspca_dev->memory != GSPCA_MEMORY_NO
1171             && gspca_dev->memory != rb->memory) {
1172                 ret = -EBUSY;
1173                 goto out;
1174         }
1175
1176         /* only one file may do the capture */
1177         if (gspca_dev->capt_file != NULL
1178             && gspca_dev->capt_file != file) {
1179                 ret = -EBUSY;
1180                 goto out;
1181         }
1182
1183         /* if allocated, the buffers must not be mapped */
1184         for (i = 0; i < gspca_dev->nframes; i++) {
1185                 if (gspca_dev->frame[i].vma_use_count) {
1186                         ret = -EBUSY;
1187                         goto out;
1188                 }
1189         }
1190
1191         /* stop streaming */
1192         if (gspca_dev->streaming) {
1193                 mutex_lock(&gspca_dev->usb_lock);
1194                 gspca_stream_off(gspca_dev);
1195                 mutex_unlock(&gspca_dev->usb_lock);
1196         }
1197
1198         /* free the previous allocated buffers, if any */
1199         if (gspca_dev->nframes != 0) {
1200                 frame_free(gspca_dev);
1201                 gspca_dev->capt_file = NULL;
1202         }
1203         if (rb->count == 0)                     /* unrequest */
1204                 goto out;
1205         gspca_dev->memory = rb->memory;
1206         ret = frame_alloc(gspca_dev, rb->count);
1207         if (ret == 0) {
1208                 rb->count = gspca_dev->nframes;
1209                 gspca_dev->capt_file = file;
1210         }
1211 out:
1212         mutex_unlock(&gspca_dev->queue_lock);
1213         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1214         return ret;
1215 }
1216
1217 static int vidioc_querybuf(struct file *file, void *priv,
1218                            struct v4l2_buffer *v4l2_buf)
1219 {
1220         struct gspca_dev *gspca_dev = priv;
1221         struct gspca_frame *frame;
1222
1223         if (v4l2_buf->index < 0
1224             || v4l2_buf->index >= gspca_dev->nframes)
1225                 return -EINVAL;
1226
1227         frame = &gspca_dev->frame[v4l2_buf->index];
1228         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1229         return 0;
1230 }
1231
1232 static int vidioc_streamon(struct file *file, void *priv,
1233                            enum v4l2_buf_type buf_type)
1234 {
1235         struct gspca_dev *gspca_dev = priv;
1236         int ret;
1237
1238         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1239                 return -EINVAL;
1240         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1241                 return -ERESTARTSYS;
1242
1243         if (gspca_dev->nframes == 0
1244             || !(gspca_dev->frame[0].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)) {
1245                 ret = -EINVAL;
1246                 goto out;
1247         }
1248         if (!gspca_dev->streaming) {
1249                 ret = gspca_init_transfer(gspca_dev);
1250                 if (ret < 0)
1251                         goto out;
1252         }
1253 #ifdef GSPCA_DEBUG
1254         if (gspca_debug & D_STREAM) {
1255                 PDEBUG_MODE("stream on OK",
1256                         gspca_dev->pixfmt,
1257                         gspca_dev->width,
1258                         gspca_dev->height);
1259         }
1260 #endif
1261         ret = 0;
1262 out:
1263         mutex_unlock(&gspca_dev->queue_lock);
1264         return ret;
1265 }
1266
1267 static int vidioc_streamoff(struct file *file, void *priv,
1268                                 enum v4l2_buf_type buf_type)
1269 {
1270         struct gspca_dev *gspca_dev = priv;
1271         int i, ret;
1272
1273         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1274                 return -EINVAL;
1275         if (!gspca_dev->streaming)
1276                 return 0;
1277         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1278                 return -ERESTARTSYS;
1279
1280         /* stop streaming */
1281         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1282                 ret = -ERESTARTSYS;
1283                 goto out;
1284         }
1285         gspca_stream_off(gspca_dev);
1286         mutex_unlock(&gspca_dev->usb_lock);
1287
1288         /* empty the application queues */
1289         for (i = 0; i < gspca_dev->nframes; i++)
1290                 gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1291         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
1292         gspca_dev->last_packet_type = DISCARD_PACKET;
1293         gspca_dev->sequence = 0;
1294         ret = 0;
1295 out:
1296         mutex_unlock(&gspca_dev->queue_lock);
1297         return ret;
1298 }
1299
1300 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1301                         struct v4l2_jpegcompression *jpegcomp)
1302 {
1303         struct gspca_dev *gspca_dev = priv;
1304         int ret;
1305
1306         if (!gspca_dev->sd_desc->get_jcomp)
1307                 return -EINVAL;
1308         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1309                 return -ERESTARTSYS;
1310         if (gspca_dev->present)
1311                 ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1312         else
1313                 ret = -ENODEV;
1314         mutex_unlock(&gspca_dev->usb_lock);
1315         return ret;
1316 }
1317
1318 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1319                         struct v4l2_jpegcompression *jpegcomp)
1320 {
1321         struct gspca_dev *gspca_dev = priv;
1322         int ret;
1323
1324         if (!gspca_dev->sd_desc->set_jcomp)
1325                 return -EINVAL;
1326         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1327                 return -ERESTARTSYS;
1328         if (gspca_dev->present)
1329                 ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1330         else
1331                 ret = -ENODEV;
1332         mutex_unlock(&gspca_dev->usb_lock);
1333         return ret;
1334 }
1335
1336 static int vidioc_g_parm(struct file *filp, void *priv,
1337                         struct v4l2_streamparm *parm)
1338 {
1339         struct gspca_dev *gspca_dev = priv;
1340
1341         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1342
1343         if (gspca_dev->sd_desc->get_streamparm) {
1344                 int ret;
1345
1346                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1347                         return -ERESTARTSYS;
1348                 if (gspca_dev->present)
1349                         ret = gspca_dev->sd_desc->get_streamparm(gspca_dev,
1350                                                                  parm);
1351                 else
1352                         ret = -ENODEV;
1353                 mutex_unlock(&gspca_dev->usb_lock);
1354                 return ret;
1355         }
1356
1357         return 0;
1358 }
1359
1360 static int vidioc_s_parm(struct file *filp, void *priv,
1361                         struct v4l2_streamparm *parm)
1362 {
1363         struct gspca_dev *gspca_dev = priv;
1364         int n;
1365
1366         n = parm->parm.capture.readbuffers;
1367         if (n == 0 || n > GSPCA_MAX_FRAMES)
1368                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1369         else
1370                 gspca_dev->nbufread = n;
1371
1372         if (gspca_dev->sd_desc->set_streamparm) {
1373                 int ret;
1374
1375                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1376                         return -ERESTARTSYS;
1377                 if (gspca_dev->present)
1378                         ret = gspca_dev->sd_desc->set_streamparm(gspca_dev,
1379                                                                  parm);
1380                 else
1381                         ret = -ENODEV;
1382                 mutex_unlock(&gspca_dev->usb_lock);
1383                 return ret;
1384         }
1385
1386         return 0;
1387 }
1388
1389 static int vidioc_s_std(struct file *filp, void *priv,
1390                         v4l2_std_id *parm)
1391 {
1392         return 0;
1393 }
1394
1395 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1396 static int vidiocgmbuf(struct file *file, void *priv,
1397                         struct video_mbuf *mbuf)
1398 {
1399         struct gspca_dev *gspca_dev = file->private_data;
1400         int i;
1401
1402         PDEBUG(D_STREAM, "cgmbuf");
1403         if (gspca_dev->nframes == 0) {
1404                 int ret;
1405
1406                 {
1407                         struct v4l2_format fmt;
1408
1409                         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1410                         i = gspca_dev->cam.nmodes - 1;  /* highest mode */
1411                         fmt.fmt.pix.width = gspca_dev->cam.cam_mode[i].width;
1412                         fmt.fmt.pix.height = gspca_dev->cam.cam_mode[i].height;
1413                         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_BGR24;
1414                         ret = vidioc_s_fmt_vid_cap(file, priv, &fmt);
1415                         if (ret != 0)
1416                                 return ret;
1417                 }
1418                 {
1419                         struct v4l2_requestbuffers rb;
1420
1421                         memset(&rb, 0, sizeof rb);
1422                         rb.count = 4;
1423                         rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1424                         rb.memory = V4L2_MEMORY_MMAP;
1425                         ret = vidioc_reqbufs(file, priv, &rb);
1426                         if (ret != 0)
1427                                 return ret;
1428                 }
1429         }
1430         mbuf->frames = gspca_dev->nframes;
1431         mbuf->size = gspca_dev->frsz * gspca_dev->nframes;
1432         for (i = 0; i < mbuf->frames; i++)
1433                 mbuf->offsets[i] = gspca_dev->frame[i].v4l2_buf.m.offset;
1434         return 0;
1435 }
1436 #endif
1437
1438 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1439 {
1440         struct gspca_dev *gspca_dev = file->private_data;
1441         struct gspca_frame *frame;
1442         struct page *page;
1443         unsigned long addr, start, size;
1444         int i, ret;
1445
1446         start = vma->vm_start;
1447         size = vma->vm_end - vma->vm_start;
1448         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1449
1450         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1451                 return -ERESTARTSYS;
1452         if (!gspca_dev->present) {
1453                 ret = -ENODEV;
1454                 goto out;
1455         }
1456         if (gspca_dev->capt_file != file) {
1457                 ret = -EINVAL;
1458                 goto out;
1459         }
1460
1461         frame = NULL;
1462         for (i = 0; i < gspca_dev->nframes; ++i) {
1463                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1464                         PDEBUG(D_STREAM, "mmap bad memory type");
1465                         break;
1466                 }
1467                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1468                                                 == vma->vm_pgoff) {
1469                         frame = &gspca_dev->frame[i];
1470                         break;
1471                 }
1472         }
1473         if (frame == NULL) {
1474                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1475                 ret = -EINVAL;
1476                 goto out;
1477         }
1478 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1479         /* v4l1 maps all the buffers */
1480         if (i != 0
1481             || size != frame->v4l2_buf.length * gspca_dev->nframes)
1482 #endif
1483             if (size != frame->v4l2_buf.length) {
1484                 PDEBUG(D_STREAM, "mmap bad size");
1485                 ret = -EINVAL;
1486                 goto out;
1487         }
1488
1489         /*
1490          * - VM_IO marks the area as being a mmaped region for I/O to a
1491          *   device. It also prevents the region from being core dumped.
1492          */
1493         vma->vm_flags |= VM_IO;
1494
1495         addr = (unsigned long) frame->data;
1496         while (size > 0) {
1497                 page = vmalloc_to_page((void *) addr);
1498                 ret = vm_insert_page(vma, start, page);
1499                 if (ret < 0)
1500                         goto out;
1501                 start += PAGE_SIZE;
1502                 addr += PAGE_SIZE;
1503                 size -= PAGE_SIZE;
1504         }
1505
1506         vma->vm_ops = &gspca_vm_ops;
1507         vma->vm_private_data = frame;
1508         gspca_vm_open(vma);
1509         ret = 0;
1510 out:
1511         mutex_unlock(&gspca_dev->queue_lock);
1512         return ret;
1513 }
1514
1515 /*
1516  * wait for a video frame
1517  *
1518  * If a frame is ready, its index is returned.
1519  */
1520 static int frame_wait(struct gspca_dev *gspca_dev,
1521                         int nonblock_ing)
1522 {
1523         struct gspca_frame *frame;
1524         int i, j, ret;
1525
1526         /* check if a frame is ready */
1527         i = gspca_dev->fr_o;
1528         j = gspca_dev->fr_queue[i];
1529         frame = &gspca_dev->frame[j];
1530
1531         if (!(frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)) {
1532                 if (nonblock_ing)
1533                         return -EAGAIN;
1534
1535                 /* wait till a frame is ready */
1536                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1537                         (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE) ||
1538                         !gspca_dev->streaming || !gspca_dev->present,
1539                         msecs_to_jiffies(3000));
1540                 if (ret < 0)
1541                         return ret;
1542                 if (ret == 0 || !gspca_dev->streaming || !gspca_dev->present)
1543                         return -EIO;
1544         }
1545
1546         gspca_dev->fr_o = (i + 1) % gspca_dev->nframes;
1547         PDEBUG(D_FRAM, "frame wait q:%d i:%d o:%d",
1548                 gspca_dev->fr_q,
1549                 gspca_dev->fr_i,
1550                 gspca_dev->fr_o);
1551
1552         if (gspca_dev->sd_desc->dq_callback) {
1553                 mutex_lock(&gspca_dev->usb_lock);
1554                 if (gspca_dev->present)
1555                         gspca_dev->sd_desc->dq_callback(gspca_dev);
1556                 mutex_unlock(&gspca_dev->usb_lock);
1557         }
1558         return j;
1559 }
1560
1561 /*
1562  * dequeue a video buffer
1563  *
1564  * If nonblock_ing is false, block until a buffer is available.
1565  */
1566 static int vidioc_dqbuf(struct file *file, void *priv,
1567                         struct v4l2_buffer *v4l2_buf)
1568 {
1569         struct gspca_dev *gspca_dev = priv;
1570         struct gspca_frame *frame;
1571         int i, ret;
1572
1573         PDEBUG(D_FRAM, "dqbuf");
1574         if (v4l2_buf->memory != gspca_dev->memory)
1575                 return -EINVAL;
1576
1577         if (!gspca_dev->present)
1578                 return -ENODEV;
1579
1580         /* if not streaming, be sure the application will not loop forever */
1581         if (!(file->f_flags & O_NONBLOCK)
1582             && !gspca_dev->streaming && gspca_dev->users == 1)
1583                 return -EINVAL;
1584
1585         /* only the capturing file may dequeue */
1586         if (gspca_dev->capt_file != file)
1587                 return -EINVAL;
1588
1589         /* only one dequeue / read at a time */
1590         if (mutex_lock_interruptible(&gspca_dev->read_lock))
1591                 return -ERESTARTSYS;
1592
1593         ret = frame_wait(gspca_dev, file->f_flags & O_NONBLOCK);
1594         if (ret < 0)
1595                 goto out;
1596         i = ret;                                /* frame index */
1597         frame = &gspca_dev->frame[i];
1598         if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1599                 if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1600                                  frame->data,
1601                                  frame->v4l2_buf.bytesused)) {
1602                         PDEBUG(D_ERR|D_STREAM,
1603                                 "dqbuf cp to user failed");
1604                         ret = -EFAULT;
1605                         goto out;
1606                 }
1607         }
1608         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1609         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1610         PDEBUG(D_FRAM, "dqbuf %d", i);
1611         ret = 0;
1612 out:
1613         mutex_unlock(&gspca_dev->read_lock);
1614         return ret;
1615 }
1616
1617 /*
1618  * queue a video buffer
1619  *
1620  * Attempting to queue a buffer that has already been
1621  * queued will return -EINVAL.
1622  */
1623 static int vidioc_qbuf(struct file *file, void *priv,
1624                         struct v4l2_buffer *v4l2_buf)
1625 {
1626         struct gspca_dev *gspca_dev = priv;
1627         struct gspca_frame *frame;
1628         int i, index, ret;
1629
1630         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1631
1632         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1633                 return -ERESTARTSYS;
1634
1635         index = v4l2_buf->index;
1636         if ((unsigned) index >= gspca_dev->nframes) {
1637                 PDEBUG(D_FRAM,
1638                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
1639                 ret = -EINVAL;
1640                 goto out;
1641         }
1642         if (v4l2_buf->memory != gspca_dev->memory) {
1643                 PDEBUG(D_FRAM, "qbuf bad memory type");
1644                 ret = -EINVAL;
1645                 goto out;
1646         }
1647
1648         frame = &gspca_dev->frame[index];
1649         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1650                 PDEBUG(D_FRAM, "qbuf bad state");
1651                 ret = -EINVAL;
1652                 goto out;
1653         }
1654
1655         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1656
1657         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1658                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1659                 frame->v4l2_buf.length = v4l2_buf->length;
1660         }
1661
1662         /* put the buffer in the 'queued' queue */
1663         i = gspca_dev->fr_q;
1664         gspca_dev->fr_queue[i] = index;
1665         gspca_dev->fr_q = (i + 1) % gspca_dev->nframes;
1666         PDEBUG(D_FRAM, "qbuf q:%d i:%d o:%d",
1667                 gspca_dev->fr_q,
1668                 gspca_dev->fr_i,
1669                 gspca_dev->fr_o);
1670
1671         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1672         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1673         ret = 0;
1674 out:
1675         mutex_unlock(&gspca_dev->queue_lock);
1676         return ret;
1677 }
1678
1679 /*
1680  * allocate the resources for read()
1681  */
1682 static int read_alloc(struct gspca_dev *gspca_dev,
1683                         struct file *file)
1684 {
1685         struct v4l2_buffer v4l2_buf;
1686         int i, ret;
1687
1688         PDEBUG(D_STREAM, "read alloc");
1689         if (gspca_dev->nframes == 0) {
1690                 struct v4l2_requestbuffers rb;
1691
1692                 memset(&rb, 0, sizeof rb);
1693                 rb.count = gspca_dev->nbufread;
1694                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1695                 rb.memory = GSPCA_MEMORY_READ;
1696                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
1697                 if (ret != 0) {
1698                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1699                         return ret;
1700                 }
1701                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1702                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1703                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1704                 for (i = 0; i < gspca_dev->nbufread; i++) {
1705                         v4l2_buf.index = i;
1706                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1707                         if (ret != 0) {
1708                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1709                                 return ret;
1710                         }
1711                 }
1712                 gspca_dev->memory = GSPCA_MEMORY_READ;
1713         }
1714
1715         /* start streaming */
1716         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1717         if (ret != 0)
1718                 PDEBUG(D_STREAM, "read streamon err %d", ret);
1719         return ret;
1720 }
1721
1722 static unsigned int dev_poll(struct file *file, poll_table *wait)
1723 {
1724         struct gspca_dev *gspca_dev = file->private_data;
1725         int i, ret;
1726
1727         PDEBUG(D_FRAM, "poll");
1728
1729         poll_wait(file, &gspca_dev->wq, wait);
1730
1731         /* if reqbufs is not done, the user would use read() */
1732         if (gspca_dev->nframes == 0) {
1733                 if (gspca_dev->memory != GSPCA_MEMORY_NO)
1734                         return POLLERR;         /* not the 1st time */
1735                 ret = read_alloc(gspca_dev, file);
1736                 if (ret != 0)
1737                         return POLLERR;
1738         }
1739
1740         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
1741                 return POLLERR;
1742
1743         /* check the next incoming buffer */
1744         i = gspca_dev->fr_o;
1745         i = gspca_dev->fr_queue[i];
1746         if (gspca_dev->frame[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1747                 ret = POLLIN | POLLRDNORM;      /* something to read */
1748         else
1749                 ret = 0;
1750         mutex_unlock(&gspca_dev->queue_lock);
1751         if (!gspca_dev->present)
1752                 return POLLHUP;
1753         return ret;
1754 }
1755
1756 static ssize_t dev_read(struct file *file, char __user *data,
1757                     size_t count, loff_t *ppos)
1758 {
1759         struct gspca_dev *gspca_dev = file->private_data;
1760         struct gspca_frame *frame;
1761         struct v4l2_buffer v4l2_buf;
1762         struct timeval timestamp;
1763         int n, ret, ret2;
1764
1765         PDEBUG(D_FRAM, "read (%zd)", count);
1766         if (!gspca_dev->present)
1767                 return -ENODEV;
1768         switch (gspca_dev->memory) {
1769         case GSPCA_MEMORY_NO:                   /* first time */
1770                 ret = read_alloc(gspca_dev, file);
1771                 if (ret != 0)
1772                         return ret;
1773                 break;
1774         case GSPCA_MEMORY_READ:
1775                 if (gspca_dev->capt_file == file)
1776                         break;
1777                 /* fall thru */
1778         default:
1779                 return -EINVAL;
1780         }
1781
1782         /* get a frame */
1783         jiffies_to_timeval(get_jiffies_64(), &timestamp);
1784         timestamp.tv_sec--;
1785         n = 2;
1786         for (;;) {
1787                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1788                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1789                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1790                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1791                 if (ret != 0) {
1792                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1793                         return ret;
1794                 }
1795
1796                 /* if the process slept for more than 1 second,
1797                  * get a newer frame */
1798                 frame = &gspca_dev->frame[v4l2_buf.index];
1799                 if (--n < 0)
1800                         break;                  /* avoid infinite loop */
1801                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1802                         break;
1803                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1804                 if (ret != 0) {
1805                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
1806                         return ret;
1807                 }
1808         }
1809
1810         /* copy the frame */
1811         if (count > frame->v4l2_buf.bytesused)
1812                 count = frame->v4l2_buf.bytesused;
1813         ret = copy_to_user(data, frame->data, count);
1814         if (ret != 0) {
1815                 PDEBUG(D_ERR|D_STREAM,
1816                         "read cp to user lack %d / %zd", ret, count);
1817                 ret = -EFAULT;
1818                 goto out;
1819         }
1820         ret = count;
1821 out:
1822         /* in each case, requeue the buffer */
1823         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1824         if (ret2 != 0)
1825                 return ret2;
1826         return ret;
1827 }
1828
1829 static struct v4l2_file_operations dev_fops = {
1830         .owner = THIS_MODULE,
1831         .open = dev_open,
1832         .release = dev_close,
1833         .read = dev_read,
1834         .mmap = dev_mmap,
1835         .unlocked_ioctl = video_ioctl2,
1836         .poll   = dev_poll,
1837 };
1838
1839 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1840         .vidioc_querycap        = vidioc_querycap,
1841         .vidioc_dqbuf           = vidioc_dqbuf,
1842         .vidioc_qbuf            = vidioc_qbuf,
1843         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1844         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1845         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1846         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1847         .vidioc_streamon        = vidioc_streamon,
1848         .vidioc_queryctrl       = vidioc_queryctrl,
1849         .vidioc_g_ctrl          = vidioc_g_ctrl,
1850         .vidioc_s_ctrl          = vidioc_s_ctrl,
1851         .vidioc_g_audio         = vidioc_g_audio,
1852         .vidioc_s_audio         = vidioc_s_audio,
1853         .vidioc_enumaudio       = vidioc_enumaudio,
1854         .vidioc_querymenu       = vidioc_querymenu,
1855         .vidioc_enum_input      = vidioc_enum_input,
1856         .vidioc_g_input         = vidioc_g_input,
1857         .vidioc_s_input         = vidioc_s_input,
1858         .vidioc_reqbufs         = vidioc_reqbufs,
1859         .vidioc_querybuf        = vidioc_querybuf,
1860         .vidioc_streamoff       = vidioc_streamoff,
1861         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1862         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1863         .vidioc_g_parm          = vidioc_g_parm,
1864         .vidioc_s_parm          = vidioc_s_parm,
1865         .vidioc_s_std           = vidioc_s_std,
1866 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1867         .vidiocgmbuf          = vidiocgmbuf,
1868 #endif
1869 };
1870
1871 static struct video_device gspca_template = {
1872         .name = "gspca main driver",
1873         .fops = &dev_fops,
1874         .ioctl_ops = &dev_ioctl_ops,
1875         .release = gspca_release,
1876         .minor = -1,
1877 };
1878
1879 /*
1880  * probe and create a new gspca device
1881  *
1882  * This function must be called by the sub-driver when it is
1883  * called for probing a new device.
1884  */
1885 int gspca_dev_probe(struct usb_interface *intf,
1886                 const struct usb_device_id *id,
1887                 const struct sd_desc *sd_desc,
1888                 int dev_size,
1889                 struct module *module)
1890 {
1891         struct usb_interface_descriptor *interface;
1892         struct gspca_dev *gspca_dev;
1893         struct usb_device *dev = interface_to_usbdev(intf);
1894         int ret;
1895
1896         PDEBUG(D_PROBE, "probing %04x:%04x", id->idVendor, id->idProduct);
1897
1898         /* we don't handle multi-config cameras */
1899         if (dev->descriptor.bNumConfigurations != 1)
1900                 return -ENODEV;
1901         interface = &intf->cur_altsetting->desc;
1902         if (interface->bInterfaceNumber > 0)
1903                 return -ENODEV;
1904
1905         /* create the device */
1906         if (dev_size < sizeof *gspca_dev)
1907                 dev_size = sizeof *gspca_dev;
1908         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
1909         if (!gspca_dev) {
1910                 err("couldn't kzalloc gspca struct");
1911                 return -ENOMEM;
1912         }
1913         gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
1914         if (!gspca_dev->usb_buf) {
1915                 err("out of memory");
1916                 ret = -ENOMEM;
1917                 goto out;
1918         }
1919         gspca_dev->dev = dev;
1920         gspca_dev->iface = interface->bInterfaceNumber;
1921         gspca_dev->nbalt = intf->num_altsetting;
1922         gspca_dev->sd_desc = sd_desc;
1923         gspca_dev->nbufread = 2;
1924         gspca_dev->empty_packet = -1;   /* don't check the empty packets */
1925
1926         /* configure the subdriver and initialize the USB device */
1927         ret = sd_desc->config(gspca_dev, id);
1928         if (ret < 0)
1929                 goto out;
1930         ret = sd_desc->init(gspca_dev);
1931         if (ret < 0)
1932                 goto out;
1933         ret = gspca_set_alt0(gspca_dev);
1934         if (ret < 0)
1935                 goto out;
1936         gspca_set_default_mode(gspca_dev);
1937
1938         mutex_init(&gspca_dev->usb_lock);
1939         mutex_init(&gspca_dev->read_lock);
1940         mutex_init(&gspca_dev->queue_lock);
1941         init_waitqueue_head(&gspca_dev->wq);
1942
1943         /* init video stuff */
1944         memcpy(&gspca_dev->vdev, &gspca_template, sizeof gspca_template);
1945         gspca_dev->vdev.parent = &dev->dev;
1946         gspca_dev->module = module;
1947         gspca_dev->present = 1;
1948         ret = video_register_device(&gspca_dev->vdev,
1949                                   VFL_TYPE_GRABBER,
1950                                   -1);
1951         if (ret < 0) {
1952                 err("video_register_device err %d", ret);
1953                 goto out;
1954         }
1955
1956         usb_set_intfdata(intf, gspca_dev);
1957         PDEBUG(D_PROBE, "probe ok");
1958         return 0;
1959 out:
1960         kfree(gspca_dev->usb_buf);
1961         kfree(gspca_dev);
1962         return ret;
1963 }
1964 EXPORT_SYMBOL(gspca_dev_probe);
1965
1966 /*
1967  * USB disconnection
1968  *
1969  * This function must be called by the sub-driver
1970  * when the device disconnects, after the specific resources are freed.
1971  */
1972 void gspca_disconnect(struct usb_interface *intf)
1973 {
1974         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1975
1976         mutex_lock(&gspca_dev->usb_lock);
1977         gspca_dev->present = 0;
1978
1979         if (gspca_dev->streaming) {
1980                 destroy_urbs(gspca_dev);
1981                 wake_up_interruptible(&gspca_dev->wq);
1982         }
1983
1984         /* the device is freed at exit of this function */
1985         gspca_dev->dev = NULL;
1986         mutex_unlock(&gspca_dev->usb_lock);
1987
1988         usb_set_intfdata(intf, NULL);
1989
1990         /* release the device */
1991         /* (this will call gspca_release() immediatly or on last close) */
1992         video_unregister_device(&gspca_dev->vdev);
1993
1994         PDEBUG(D_PROBE, "disconnect complete");
1995 }
1996 EXPORT_SYMBOL(gspca_disconnect);
1997
1998 #ifdef CONFIG_PM
1999 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
2000 {
2001         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2002
2003         if (!gspca_dev->streaming)
2004                 return 0;
2005         gspca_dev->frozen = 1;          /* avoid urb error messages */
2006         if (gspca_dev->sd_desc->stopN)
2007                 gspca_dev->sd_desc->stopN(gspca_dev);
2008         destroy_urbs(gspca_dev);
2009         gspca_set_alt0(gspca_dev);
2010         if (gspca_dev->sd_desc->stop0)
2011                 gspca_dev->sd_desc->stop0(gspca_dev);
2012         return 0;
2013 }
2014 EXPORT_SYMBOL(gspca_suspend);
2015
2016 int gspca_resume(struct usb_interface *intf)
2017 {
2018         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2019
2020         gspca_dev->frozen = 0;
2021         gspca_dev->sd_desc->init(gspca_dev);
2022         if (gspca_dev->streaming)
2023                 return gspca_init_transfer(gspca_dev);
2024         return 0;
2025 }
2026 EXPORT_SYMBOL(gspca_resume);
2027 #endif
2028 /* -- cam driver utility functions -- */
2029
2030 /* auto gain and exposure algorithm based on the knee algorithm described here:
2031    http://ytse.tricolour.net/docs/LowLightOptimization.html
2032
2033    Returns 0 if no changes were made, 1 if the gain and or exposure settings
2034    where changed. */
2035 int gspca_auto_gain_n_exposure(struct gspca_dev *gspca_dev, int avg_lum,
2036         int desired_avg_lum, int deadzone, int gain_knee, int exposure_knee)
2037 {
2038         int i, steps, gain, orig_gain, exposure, orig_exposure, autogain;
2039         const struct ctrl *gain_ctrl = NULL;
2040         const struct ctrl *exposure_ctrl = NULL;
2041         const struct ctrl *autogain_ctrl = NULL;
2042         int retval = 0;
2043
2044         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
2045                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_GAIN)
2046                         gain_ctrl = &gspca_dev->sd_desc->ctrls[i];
2047                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_EXPOSURE)
2048                         exposure_ctrl = &gspca_dev->sd_desc->ctrls[i];
2049                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_AUTOGAIN)
2050                         autogain_ctrl = &gspca_dev->sd_desc->ctrls[i];
2051         }
2052         if (!gain_ctrl || !exposure_ctrl || !autogain_ctrl) {
2053                 PDEBUG(D_ERR, "Error: gspca_auto_gain_n_exposure called "
2054                         "on cam without (auto)gain/exposure");
2055                 return 0;
2056         }
2057
2058         if (gain_ctrl->get(gspca_dev, &gain) ||
2059                         exposure_ctrl->get(gspca_dev, &exposure) ||
2060                         autogain_ctrl->get(gspca_dev, &autogain) || !autogain)
2061                 return 0;
2062
2063         orig_gain = gain;
2064         orig_exposure = exposure;
2065
2066         /* If we are of a multiple of deadzone, do multiple steps to reach the
2067            desired lumination fast (with the risc of a slight overshoot) */
2068         steps = abs(desired_avg_lum - avg_lum) / deadzone;
2069
2070         PDEBUG(D_FRAM, "autogain: lum: %d, desired: %d, steps: %d",
2071                 avg_lum, desired_avg_lum, steps);
2072
2073         for (i = 0; i < steps; i++) {
2074                 if (avg_lum > desired_avg_lum) {
2075                         if (gain > gain_knee)
2076                                 gain--;
2077                         else if (exposure > exposure_knee)
2078                                 exposure--;
2079                         else if (gain > gain_ctrl->qctrl.default_value)
2080                                 gain--;
2081                         else if (exposure > exposure_ctrl->qctrl.minimum)
2082                                 exposure--;
2083                         else if (gain > gain_ctrl->qctrl.minimum)
2084                                 gain--;
2085                         else
2086                                 break;
2087                 } else {
2088                         if (gain < gain_ctrl->qctrl.default_value)
2089                                 gain++;
2090                         else if (exposure < exposure_knee)
2091                                 exposure++;
2092                         else if (gain < gain_knee)
2093                                 gain++;
2094                         else if (exposure < exposure_ctrl->qctrl.maximum)
2095                                 exposure++;
2096                         else if (gain < gain_ctrl->qctrl.maximum)
2097                                 gain++;
2098                         else
2099                                 break;
2100                 }
2101         }
2102
2103         if (gain != orig_gain) {
2104                 gain_ctrl->set(gspca_dev, gain);
2105                 retval = 1;
2106         }
2107         if (exposure != orig_exposure) {
2108                 exposure_ctrl->set(gspca_dev, exposure);
2109                 retval = 1;
2110         }
2111
2112         return retval;
2113 }
2114 EXPORT_SYMBOL(gspca_auto_gain_n_exposure);
2115
2116 /* -- module insert / remove -- */
2117 static int __init gspca_init(void)
2118 {
2119         info("main v%d.%d.%d registered",
2120                 (DRIVER_VERSION_NUMBER >> 16) & 0xff,
2121                 (DRIVER_VERSION_NUMBER >> 8) & 0xff,
2122                 DRIVER_VERSION_NUMBER & 0xff);
2123         return 0;
2124 }
2125 static void __exit gspca_exit(void)
2126 {
2127         info("main deregistered");
2128 }
2129
2130 module_init(gspca_init);
2131 module_exit(gspca_exit);
2132
2133 #ifdef GSPCA_DEBUG
2134 module_param_named(debug, gspca_debug, int, 0644);
2135 MODULE_PARM_DESC(debug,
2136                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
2137                 " 0x08:stream 0x10:frame 0x20:packet 0x40:USBin 0x80:USBout"
2138                 " 0x0100: v4l2");
2139 #endif