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