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