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