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