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