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