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