V4L/DVB (9087): gspca: Image transfer by bulk uses altsetting 0 with any buffer size.
[safe/jmp/linux-2.6] / drivers / media / video / gspca / gspca.c
1 /*
2  * Main USB camera driver
3  *
4  * V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #define MODULE_NAME "gspca"
22
23 #include <linux/init.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/sched.h>
27 #include <linux/slab.h>
28 #include <linux/mm.h>
29 #include <linux/string.h>
30 #include <linux/pagemap.h>
31 #include <linux/io.h>
32 #include <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                                     int 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 /*      size = PAGE_ALIGN(size);        (already done) */
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 /*      strncpy(cap->card, gspca_dev->cam.dev_name, sizeof cap->card); */
941         if (gspca_dev->dev->product != NULL) {
942                 strncpy(cap->card, gspca_dev->dev->product,
943                         sizeof cap->card);
944         } else {
945                 snprintf(cap->card, sizeof cap->card,
946                         "USB Camera (%04x:%04x)",
947                         le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
948                         le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
949         }
950         strncpy(cap->bus_info, gspca_dev->dev->bus->bus_name,
951                 sizeof cap->bus_info);
952         cap->version = DRIVER_VERSION_NUMBER;
953         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
954                           | V4L2_CAP_STREAMING
955                           | V4L2_CAP_READWRITE;
956         return 0;
957 }
958
959 static int vidioc_queryctrl(struct file *file, void *priv,
960                            struct v4l2_queryctrl *q_ctrl)
961 {
962         struct gspca_dev *gspca_dev = priv;
963         int i, ix;
964         u32 id;
965
966         ix = -1;
967         id = q_ctrl->id;
968         if (id & V4L2_CTRL_FLAG_NEXT_CTRL) {
969                 id &= V4L2_CTRL_ID_MASK;
970                 id++;
971                 for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
972                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id < id)
973                                 continue;
974                         if (ix < 0) {
975                                 ix = i;
976                                 continue;
977                         }
978                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id
979                                     > gspca_dev->sd_desc->ctrls[ix].qctrl.id)
980                                 continue;
981                         ix = i;
982                 }
983         }
984         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
985                 if (id == gspca_dev->sd_desc->ctrls[i].qctrl.id) {
986                         ix = i;
987                         break;
988                 }
989         }
990         if (ix < 0)
991                 return -EINVAL;
992         memcpy(q_ctrl, &gspca_dev->sd_desc->ctrls[ix].qctrl,
993                 sizeof *q_ctrl);
994         if (gspca_dev->ctrl_dis & (1 << ix))
995                 q_ctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
996         return 0;
997 }
998
999 static int vidioc_s_ctrl(struct file *file, void *priv,
1000                          struct v4l2_control *ctrl)
1001 {
1002         struct gspca_dev *gspca_dev = priv;
1003         const struct ctrl *ctrls;
1004         int i, ret;
1005
1006         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1007              i < gspca_dev->sd_desc->nctrls;
1008              i++, ctrls++) {
1009                 if (ctrl->id != ctrls->qctrl.id)
1010                         continue;
1011                 if (gspca_dev->ctrl_dis & (1 << i))
1012                         return -EINVAL;
1013                 if (ctrl->value < ctrls->qctrl.minimum
1014                     || ctrl->value > ctrls->qctrl.maximum)
1015                         return -ERANGE;
1016                 PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
1017                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1018                         return -ERESTARTSYS;
1019                 ret = ctrls->set(gspca_dev, ctrl->value);
1020                 mutex_unlock(&gspca_dev->usb_lock);
1021                 return ret;
1022         }
1023         return -EINVAL;
1024 }
1025
1026 static int vidioc_g_ctrl(struct file *file, void *priv,
1027                          struct v4l2_control *ctrl)
1028 {
1029         struct gspca_dev *gspca_dev = priv;
1030
1031         const struct ctrl *ctrls;
1032         int i, ret;
1033
1034         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1035              i < gspca_dev->sd_desc->nctrls;
1036              i++, ctrls++) {
1037                 if (ctrl->id != ctrls->qctrl.id)
1038                         continue;
1039                 if (gspca_dev->ctrl_dis & (1 << i))
1040                         return -EINVAL;
1041                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1042                         return -ERESTARTSYS;
1043                 ret = ctrls->get(gspca_dev, &ctrl->value);
1044                 mutex_unlock(&gspca_dev->usb_lock);
1045                 return ret;
1046         }
1047         return -EINVAL;
1048 }
1049
1050 static int vidioc_querymenu(struct file *file, void *priv,
1051                             struct v4l2_querymenu *qmenu)
1052 {
1053         struct gspca_dev *gspca_dev = priv;
1054
1055         if (!gspca_dev->sd_desc->querymenu)
1056                 return -EINVAL;
1057         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
1058 }
1059
1060 static int vidioc_enum_input(struct file *file, void *priv,
1061                                 struct v4l2_input *input)
1062 {
1063         struct gspca_dev *gspca_dev = priv;
1064
1065         if (input->index != 0)
1066                 return -EINVAL;
1067         memset(input, 0, sizeof *input);
1068         input->type = V4L2_INPUT_TYPE_CAMERA;
1069         strncpy(input->name, gspca_dev->sd_desc->name,
1070                 sizeof input->name);
1071         return 0;
1072 }
1073
1074 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1075 {
1076         *i = 0;
1077         return 0;
1078 }
1079
1080 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1081 {
1082         if (i > 0)
1083                 return -EINVAL;
1084         return (0);
1085 }
1086
1087 static int vidioc_reqbufs(struct file *file, void *priv,
1088                           struct v4l2_requestbuffers *rb)
1089 {
1090         struct gspca_dev *gspca_dev = priv;
1091         int i, ret = 0;
1092
1093         if (rb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1094                 return -EINVAL;
1095         switch (rb->memory) {
1096         case GSPCA_MEMORY_READ:                 /* (internal call) */
1097         case V4L2_MEMORY_MMAP:
1098         case V4L2_MEMORY_USERPTR:
1099                 break;
1100         default:
1101                 return -EINVAL;
1102         }
1103         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1104                 return -ERESTARTSYS;
1105
1106         if (gspca_dev->memory != GSPCA_MEMORY_NO
1107             && gspca_dev->memory != rb->memory) {
1108                 ret = -EBUSY;
1109                 goto out;
1110         }
1111
1112         /* only one file may do the capture */
1113         if (gspca_dev->capt_file != NULL
1114             && gspca_dev->capt_file != file) {
1115                 ret = -EBUSY;
1116                 goto out;
1117         }
1118
1119         /* if allocated, the buffers must not be mapped */
1120         for (i = 0; i < gspca_dev->nframes; i++) {
1121                 if (gspca_dev->frame[i].vma_use_count) {
1122                         ret = -EBUSY;
1123                         goto out;
1124                 }
1125         }
1126
1127         /* stop streaming */
1128         if (gspca_dev->streaming) {
1129                 mutex_lock(&gspca_dev->usb_lock);
1130                 gspca_stream_off(gspca_dev);
1131                 mutex_unlock(&gspca_dev->usb_lock);
1132         }
1133
1134         /* free the previous allocated buffers, if any */
1135         if (gspca_dev->nframes != 0) {
1136                 frame_free(gspca_dev);
1137                 gspca_dev->capt_file = NULL;
1138         }
1139         if (rb->count == 0)                     /* unrequest */
1140                 goto out;
1141         gspca_dev->memory = rb->memory;
1142         ret = frame_alloc(gspca_dev, rb->count);
1143         if (ret == 0) {
1144                 rb->count = gspca_dev->nframes;
1145                 gspca_dev->capt_file = file;
1146         }
1147 out:
1148         mutex_unlock(&gspca_dev->queue_lock);
1149         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1150         return ret;
1151 }
1152
1153 static int vidioc_querybuf(struct file *file, void *priv,
1154                            struct v4l2_buffer *v4l2_buf)
1155 {
1156         struct gspca_dev *gspca_dev = priv;
1157         struct gspca_frame *frame;
1158
1159         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1160             || v4l2_buf->index < 0
1161             || v4l2_buf->index >= gspca_dev->nframes)
1162                 return -EINVAL;
1163
1164         frame = &gspca_dev->frame[v4l2_buf->index];
1165         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1166         return 0;
1167 }
1168
1169 static int vidioc_streamon(struct file *file, void *priv,
1170                            enum v4l2_buf_type buf_type)
1171 {
1172         struct gspca_dev *gspca_dev = priv;
1173         int ret;
1174
1175         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1176                 return -EINVAL;
1177         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1178                 return -ERESTARTSYS;
1179         if (!gspca_dev->present) {
1180                 ret = -ENODEV;
1181                 goto out;
1182         }
1183         if (gspca_dev->nframes == 0) {
1184                 ret = -EINVAL;
1185                 goto out;
1186         }
1187         if (!gspca_dev->streaming) {
1188                 ret = gspca_init_transfer(gspca_dev);
1189                 if (ret < 0)
1190                         goto out;
1191         }
1192 #ifdef GSPCA_DEBUG
1193         if (gspca_debug & D_STREAM) {
1194                 PDEBUG_MODE("stream on OK",
1195                         gspca_dev->pixfmt,
1196                         gspca_dev->width,
1197                         gspca_dev->height);
1198         }
1199 #endif
1200         ret = 0;
1201 out:
1202         mutex_unlock(&gspca_dev->queue_lock);
1203         return ret;
1204 }
1205
1206 static int vidioc_streamoff(struct file *file, void *priv,
1207                                 enum v4l2_buf_type buf_type)
1208 {
1209         struct gspca_dev *gspca_dev = priv;
1210         int i, ret;
1211
1212         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1213                 return -EINVAL;
1214         if (!gspca_dev->streaming)
1215                 return 0;
1216         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1217                 return -ERESTARTSYS;
1218
1219         /* stop streaming */
1220         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1221                 ret = -ERESTARTSYS;
1222                 goto out;
1223         }
1224         gspca_stream_off(gspca_dev);
1225         mutex_unlock(&gspca_dev->usb_lock);
1226
1227         /* empty the application queues */
1228         for (i = 0; i < gspca_dev->nframes; i++)
1229                 gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1230         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
1231         gspca_dev->last_packet_type = DISCARD_PACKET;
1232         gspca_dev->sequence = 0;
1233         atomic_set(&gspca_dev->nevent, 0);
1234         ret = 0;
1235 out:
1236         mutex_unlock(&gspca_dev->queue_lock);
1237         return ret;
1238 }
1239
1240 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1241                         struct v4l2_jpegcompression *jpegcomp)
1242 {
1243         struct gspca_dev *gspca_dev = priv;
1244         int ret;
1245
1246         if (!gspca_dev->sd_desc->get_jcomp)
1247                 return -EINVAL;
1248         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1249                 return -ERESTARTSYS;
1250         ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1251         mutex_unlock(&gspca_dev->usb_lock);
1252         return ret;
1253 }
1254
1255 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1256                         struct v4l2_jpegcompression *jpegcomp)
1257 {
1258         struct gspca_dev *gspca_dev = priv;
1259         int ret;
1260
1261         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1262                 return -ERESTARTSYS;
1263         if (!gspca_dev->sd_desc->set_jcomp)
1264                 return -EINVAL;
1265         ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1266         mutex_unlock(&gspca_dev->usb_lock);
1267         return ret;
1268 }
1269
1270 static int vidioc_g_parm(struct file *filp, void *priv,
1271                         struct v4l2_streamparm *parm)
1272 {
1273         struct gspca_dev *gspca_dev = priv;
1274
1275         memset(parm, 0, sizeof *parm);
1276         parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1277         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1278         return 0;
1279 }
1280
1281 static int vidioc_s_parm(struct file *filp, void *priv,
1282                         struct v4l2_streamparm *parm)
1283 {
1284         struct gspca_dev *gspca_dev = priv;
1285         int n;
1286
1287         n = parm->parm.capture.readbuffers;
1288         if (n == 0 || n > GSPCA_MAX_FRAMES)
1289                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1290         else
1291                 gspca_dev->nbufread = n;
1292         return 0;
1293 }
1294
1295 static int vidioc_s_std(struct file *filp, void *priv,
1296                         v4l2_std_id *parm)
1297 {
1298         return 0;
1299 }
1300
1301 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1302 static int vidiocgmbuf(struct file *file, void *priv,
1303                         struct video_mbuf *mbuf)
1304 {
1305         struct gspca_dev *gspca_dev = file->private_data;
1306         int i;
1307
1308         PDEBUG(D_STREAM, "cgmbuf");
1309         if (gspca_dev->nframes == 0) {
1310                 int ret;
1311
1312                 {
1313                         struct v4l2_format fmt;
1314
1315                         memset(&fmt, 0, sizeof fmt);
1316                         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1317                         i = gspca_dev->cam.nmodes - 1;  /* highest mode */
1318                         fmt.fmt.pix.width = gspca_dev->cam.cam_mode[i].width;
1319                         fmt.fmt.pix.height = gspca_dev->cam.cam_mode[i].height;
1320                         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_BGR24;
1321                         ret = vidioc_s_fmt_vid_cap(file, priv, &fmt);
1322                         if (ret != 0)
1323                                 return ret;
1324                 }
1325                 {
1326                         struct v4l2_requestbuffers rb;
1327
1328                         memset(&rb, 0, sizeof rb);
1329                         rb.count = 4;
1330                         rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1331                         rb.memory = V4L2_MEMORY_MMAP;
1332                         ret = vidioc_reqbufs(file, priv, &rb);
1333                         if (ret != 0)
1334                                 return ret;
1335                 }
1336         }
1337         mbuf->frames = gspca_dev->nframes;
1338         mbuf->size = gspca_dev->frsz * gspca_dev->nframes;
1339         for (i = 0; i < mbuf->frames; i++)
1340                 mbuf->offsets[i] = gspca_dev->frame[i].v4l2_buf.m.offset;
1341         return 0;
1342 }
1343 #endif
1344
1345 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1346 {
1347         struct gspca_dev *gspca_dev = file->private_data;
1348         struct gspca_frame *frame;
1349         struct page *page;
1350         unsigned long addr, start, size;
1351         int i, ret;
1352
1353         start = vma->vm_start;
1354         size = vma->vm_end - vma->vm_start;
1355         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1356
1357         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1358                 return -ERESTARTSYS;
1359         if (!gspca_dev->present) {
1360                 ret = -ENODEV;
1361                 goto out;
1362         }
1363         if (gspca_dev->capt_file != file) {
1364                 ret = -EINVAL;
1365                 goto out;
1366         }
1367
1368         frame = NULL;
1369         for (i = 0; i < gspca_dev->nframes; ++i) {
1370                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1371                         PDEBUG(D_STREAM, "mmap bad memory type");
1372                         break;
1373                 }
1374                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1375                                                 == vma->vm_pgoff) {
1376                         frame = &gspca_dev->frame[i];
1377                         break;
1378                 }
1379         }
1380         if (frame == NULL) {
1381                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1382                 ret = -EINVAL;
1383                 goto out;
1384         }
1385 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1386         /* v4l1 maps all the buffers */
1387         if (i != 0
1388             || size != frame->v4l2_buf.length * gspca_dev->nframes)
1389 #endif
1390             if (size != frame->v4l2_buf.length) {
1391                 PDEBUG(D_STREAM, "mmap bad size");
1392                 ret = -EINVAL;
1393                 goto out;
1394         }
1395
1396         /*
1397          * - VM_IO marks the area as being a mmaped region for I/O to a
1398          *   device. It also prevents the region from being core dumped.
1399          */
1400         vma->vm_flags |= VM_IO;
1401
1402         addr = (unsigned long) frame->data;
1403         while (size > 0) {
1404                 page = vmalloc_to_page((void *) addr);
1405                 ret = vm_insert_page(vma, start, page);
1406                 if (ret < 0)
1407                         goto out;
1408                 start += PAGE_SIZE;
1409                 addr += PAGE_SIZE;
1410                 size -= PAGE_SIZE;
1411         }
1412
1413         vma->vm_ops = &gspca_vm_ops;
1414         vma->vm_private_data = frame;
1415         gspca_vm_open(vma);
1416         ret = 0;
1417 out:
1418         mutex_unlock(&gspca_dev->queue_lock);
1419         return ret;
1420 }
1421
1422 /*
1423  * wait for a video frame
1424  *
1425  * If a frame is ready, its index is returned.
1426  */
1427 static int frame_wait(struct gspca_dev *gspca_dev,
1428                         int nonblock_ing)
1429 {
1430         struct gspca_frame *frame;
1431         int i, j, ret;
1432
1433         /* check if a frame is ready */
1434         i = gspca_dev->fr_o;
1435         j = gspca_dev->fr_queue[i];
1436         frame = &gspca_dev->frame[j];
1437         if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE) {
1438                 atomic_dec(&gspca_dev->nevent);
1439                 goto ok;
1440         }
1441         if (nonblock_ing)                       /* no frame yet */
1442                 return -EAGAIN;
1443
1444         /* wait till a frame is ready */
1445         for (;;) {
1446                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1447                                         atomic_read(&gspca_dev->nevent) > 0,
1448                                         msecs_to_jiffies(3000));
1449                 if (ret <= 0) {
1450                         if (ret < 0)
1451                                 return ret;     /* interrupt */
1452                         return -EIO;            /* timeout */
1453                 }
1454                 atomic_dec(&gspca_dev->nevent);
1455                 if (!gspca_dev->streaming || !gspca_dev->present)
1456                         return -EIO;
1457                 i = gspca_dev->fr_o;
1458                 j = gspca_dev->fr_queue[i];
1459                 frame = &gspca_dev->frame[j];
1460                 if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1461                         break;
1462         }
1463 ok:
1464         gspca_dev->fr_o = (i + 1) % gspca_dev->nframes;
1465         PDEBUG(D_FRAM, "frame wait q:%d i:%d o:%d",
1466                 gspca_dev->fr_q,
1467                 gspca_dev->fr_i,
1468                 gspca_dev->fr_o);
1469
1470         if (gspca_dev->sd_desc->dq_callback) {
1471                 mutex_lock(&gspca_dev->usb_lock);
1472                 gspca_dev->sd_desc->dq_callback(gspca_dev);
1473                 mutex_unlock(&gspca_dev->usb_lock);
1474         }
1475         return j;
1476 }
1477
1478 /*
1479  * dequeue a video buffer
1480  *
1481  * If nonblock_ing is false, block until a buffer is available.
1482  */
1483 static int vidioc_dqbuf(struct file *file, void *priv,
1484                         struct v4l2_buffer *v4l2_buf)
1485 {
1486         struct gspca_dev *gspca_dev = priv;
1487         struct gspca_frame *frame;
1488         int i, ret;
1489
1490         PDEBUG(D_FRAM, "dqbuf");
1491         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1492                 return -EINVAL;
1493         if (v4l2_buf->memory != gspca_dev->memory)
1494                 return -EINVAL;
1495
1496         /* if not streaming, be sure the application will not loop forever */
1497         if (!(file->f_flags & O_NONBLOCK)
1498             && !gspca_dev->streaming && gspca_dev->users == 1)
1499                 return -EINVAL;
1500
1501         /* only the capturing file may dequeue */
1502         if (gspca_dev->capt_file != file)
1503                 return -EINVAL;
1504
1505         /* only one dequeue / read at a time */
1506         if (mutex_lock_interruptible(&gspca_dev->read_lock))
1507                 return -ERESTARTSYS;
1508
1509         ret = frame_wait(gspca_dev, file->f_flags & O_NONBLOCK);
1510         if (ret < 0)
1511                 goto out;
1512         i = ret;                                /* frame index */
1513         frame = &gspca_dev->frame[i];
1514         if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1515                 if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1516                                  frame->data,
1517                                  frame->v4l2_buf.bytesused)) {
1518                         PDEBUG(D_ERR|D_STREAM,
1519                                 "dqbuf cp to user failed");
1520                         ret = -EFAULT;
1521                         goto out;
1522                 }
1523         }
1524         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1525         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1526         PDEBUG(D_FRAM, "dqbuf %d", i);
1527         ret = 0;
1528 out:
1529         mutex_unlock(&gspca_dev->read_lock);
1530         return ret;
1531 }
1532
1533 /*
1534  * queue a video buffer
1535  *
1536  * Attempting to queue a buffer that has already been
1537  * queued will return -EINVAL.
1538  */
1539 static int vidioc_qbuf(struct file *file, void *priv,
1540                         struct v4l2_buffer *v4l2_buf)
1541 {
1542         struct gspca_dev *gspca_dev = priv;
1543         struct gspca_frame *frame;
1544         int i, index, ret;
1545
1546         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1547         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1548                 return -EINVAL;
1549
1550         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1551                 return -ERESTARTSYS;
1552
1553         index = v4l2_buf->index;
1554         if ((unsigned) index >= gspca_dev->nframes) {
1555                 PDEBUG(D_FRAM,
1556                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
1557                 ret = -EINVAL;
1558                 goto out;
1559         }
1560         if (v4l2_buf->memory != gspca_dev->memory) {
1561                 PDEBUG(D_FRAM, "qbuf bad memory type");
1562                 ret = -EINVAL;
1563                 goto out;
1564         }
1565
1566         frame = &gspca_dev->frame[index];
1567         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1568                 PDEBUG(D_FRAM, "qbuf bad state");
1569                 ret = -EINVAL;
1570                 goto out;
1571         }
1572
1573         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1574 /*      frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE; */
1575
1576         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1577                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1578                 frame->v4l2_buf.length = v4l2_buf->length;
1579         }
1580
1581         /* put the buffer in the 'queued' queue */
1582         i = gspca_dev->fr_q;
1583         gspca_dev->fr_queue[i] = index;
1584         gspca_dev->fr_q = (i + 1) % gspca_dev->nframes;
1585         PDEBUG(D_FRAM, "qbuf q:%d i:%d o:%d",
1586                 gspca_dev->fr_q,
1587                 gspca_dev->fr_i,
1588                 gspca_dev->fr_o);
1589
1590         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1591         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1592         ret = 0;
1593 out:
1594         mutex_unlock(&gspca_dev->queue_lock);
1595         return ret;
1596 }
1597
1598 /*
1599  * allocate the resources for read()
1600  */
1601 static int read_alloc(struct gspca_dev *gspca_dev,
1602                         struct file *file)
1603 {
1604         struct v4l2_buffer v4l2_buf;
1605         int i, ret;
1606
1607         PDEBUG(D_STREAM, "read alloc");
1608         if (gspca_dev->nframes == 0) {
1609                 struct v4l2_requestbuffers rb;
1610
1611                 memset(&rb, 0, sizeof rb);
1612                 rb.count = gspca_dev->nbufread;
1613                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1614                 rb.memory = GSPCA_MEMORY_READ;
1615                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
1616                 if (ret != 0) {
1617                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1618                         return ret;
1619                 }
1620                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1621                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1622                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1623                 for (i = 0; i < gspca_dev->nbufread; i++) {
1624                         v4l2_buf.index = i;
1625                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1626                         if (ret != 0) {
1627                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1628                                 return ret;
1629                         }
1630                 }
1631                 gspca_dev->memory = GSPCA_MEMORY_READ;
1632         }
1633
1634         /* start streaming */
1635         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1636         if (ret != 0)
1637                 PDEBUG(D_STREAM, "read streamon err %d", ret);
1638         return ret;
1639 }
1640
1641 static unsigned int dev_poll(struct file *file, poll_table *wait)
1642 {
1643         struct gspca_dev *gspca_dev = file->private_data;
1644         int i, ret;
1645
1646         PDEBUG(D_FRAM, "poll");
1647
1648         poll_wait(file, &gspca_dev->wq, wait);
1649         if (!gspca_dev->present)
1650                 return POLLERR;
1651
1652         /* if reqbufs is not done, the user would use read() */
1653         if (gspca_dev->nframes == 0) {
1654                 if (gspca_dev->memory != GSPCA_MEMORY_NO)
1655                         return POLLERR;         /* not the 1st time */
1656                 ret = read_alloc(gspca_dev, file);
1657                 if (ret != 0)
1658                         return POLLERR;
1659         }
1660
1661         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
1662                 return POLLERR;
1663         if (!gspca_dev->present) {
1664                 ret = POLLERR;
1665                 goto out;
1666         }
1667
1668         /* check the next incoming buffer */
1669         i = gspca_dev->fr_o;
1670         i = gspca_dev->fr_queue[i];
1671         if (gspca_dev->frame[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1672                 ret = POLLIN | POLLRDNORM;      /* something to read */
1673         else
1674                 ret = 0;
1675 out:
1676         mutex_unlock(&gspca_dev->queue_lock);
1677         return ret;
1678 }
1679
1680 static ssize_t dev_read(struct file *file, char __user *data,
1681                     size_t count, loff_t *ppos)
1682 {
1683         struct gspca_dev *gspca_dev = file->private_data;
1684         struct gspca_frame *frame;
1685         struct v4l2_buffer v4l2_buf;
1686         struct timeval timestamp;
1687         int n, ret, ret2;
1688
1689         PDEBUG(D_FRAM, "read (%zd)", count);
1690         if (!gspca_dev->present)
1691                 return -ENODEV;
1692         switch (gspca_dev->memory) {
1693         case GSPCA_MEMORY_NO:                   /* first time */
1694                 ret = read_alloc(gspca_dev, file);
1695                 if (ret != 0)
1696                         return ret;
1697                 break;
1698         case GSPCA_MEMORY_READ:
1699                 if (gspca_dev->capt_file == file)
1700                         break;
1701                 /* fall thru */
1702         default:
1703                 return -EINVAL;
1704         }
1705
1706         /* get a frame */
1707         jiffies_to_timeval(get_jiffies_64(), &timestamp);
1708         timestamp.tv_sec--;
1709         n = 2;
1710         for (;;) {
1711                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1712                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1713                 v4l2_buf.memory = GSPCA_MEMORY_READ;
1714                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1715                 if (ret != 0) {
1716                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1717                         return ret;
1718                 }
1719
1720                 /* if the process slept for more than 1 second,
1721                  * get a newer frame */
1722                 frame = &gspca_dev->frame[v4l2_buf.index];
1723                 if (--n < 0)
1724                         break;                  /* avoid infinite loop */
1725                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1726                         break;
1727                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1728                 if (ret != 0) {
1729                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
1730                         return ret;
1731                 }
1732         }
1733
1734         /* copy the frame */
1735         if (count > frame->v4l2_buf.bytesused)
1736                 count = frame->v4l2_buf.bytesused;
1737         ret = copy_to_user(data, frame->data, count);
1738         if (ret != 0) {
1739                 PDEBUG(D_ERR|D_STREAM,
1740                         "read cp to user lack %d / %zd", ret, count);
1741                 ret = -EFAULT;
1742                 goto out;
1743         }
1744         ret = count;
1745 out:
1746         /* in each case, requeue the buffer */
1747         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1748         if (ret2 != 0)
1749                 return ret2;
1750         return ret;
1751 }
1752
1753 static void dev_release(struct video_device *vfd)
1754 {
1755         /* nothing */
1756 }
1757
1758 static struct file_operations dev_fops = {
1759         .owner = THIS_MODULE,
1760         .open = dev_open,
1761         .release = dev_close,
1762         .read = dev_read,
1763         .mmap = dev_mmap,
1764         .ioctl = video_ioctl2,
1765 #ifdef CONFIG_COMPAT
1766         .compat_ioctl = v4l_compat_ioctl32,
1767 #endif
1768         .llseek = no_llseek,
1769         .poll   = dev_poll,
1770 };
1771
1772 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1773         .vidioc_querycap        = vidioc_querycap,
1774         .vidioc_dqbuf           = vidioc_dqbuf,
1775         .vidioc_qbuf            = vidioc_qbuf,
1776         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1777         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1778         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1779         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1780         .vidioc_streamon        = vidioc_streamon,
1781         .vidioc_queryctrl       = vidioc_queryctrl,
1782         .vidioc_g_ctrl          = vidioc_g_ctrl,
1783         .vidioc_s_ctrl          = vidioc_s_ctrl,
1784         .vidioc_querymenu       = vidioc_querymenu,
1785         .vidioc_enum_input      = vidioc_enum_input,
1786         .vidioc_g_input         = vidioc_g_input,
1787         .vidioc_s_input         = vidioc_s_input,
1788         .vidioc_reqbufs         = vidioc_reqbufs,
1789         .vidioc_querybuf        = vidioc_querybuf,
1790         .vidioc_streamoff       = vidioc_streamoff,
1791         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1792         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1793         .vidioc_g_parm          = vidioc_g_parm,
1794         .vidioc_s_parm          = vidioc_s_parm,
1795         .vidioc_s_std           = vidioc_s_std,
1796 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1797         .vidiocgmbuf          = vidiocgmbuf,
1798 #endif
1799 };
1800
1801 static struct video_device gspca_template = {
1802         .name = "gspca main driver",
1803         .fops = &dev_fops,
1804         .ioctl_ops = &dev_ioctl_ops,
1805         .release = dev_release,         /* mandatory */
1806         .minor = -1,
1807 };
1808
1809 /*
1810  * probe and create a new gspca device
1811  *
1812  * This function must be called by the sub-driver when it is
1813  * called for probing a new device.
1814  */
1815 int gspca_dev_probe(struct usb_interface *intf,
1816                 const struct usb_device_id *id,
1817                 const struct sd_desc *sd_desc,
1818                 int dev_size,
1819                 struct module *module)
1820 {
1821         struct usb_interface_descriptor *interface;
1822         struct gspca_dev *gspca_dev;
1823         struct usb_device *dev = interface_to_usbdev(intf);
1824         int ret;
1825
1826         PDEBUG(D_PROBE, "probing %04x:%04x", id->idVendor, id->idProduct);
1827
1828         /* we don't handle multi-config cameras */
1829         if (dev->descriptor.bNumConfigurations != 1)
1830                 return -ENODEV;
1831         interface = &intf->cur_altsetting->desc;
1832         if (interface->bInterfaceNumber > 0)
1833                 return -ENODEV;
1834
1835         /* create the device */
1836         if (dev_size < sizeof *gspca_dev)
1837                 dev_size = sizeof *gspca_dev;
1838         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
1839         if (gspca_dev == NULL) {
1840                 err("couldn't kzalloc gspca struct");
1841                 return -EIO;
1842         }
1843         kref_init(&gspca_dev->kref);
1844         gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
1845         if (!gspca_dev->usb_buf) {
1846                 err("out of memory");
1847                 ret = -EIO;
1848                 goto out;
1849         }
1850         gspca_dev->dev = dev;
1851         gspca_dev->iface = interface->bInterfaceNumber;
1852         gspca_dev->nbalt = intf->num_altsetting;
1853         gspca_dev->sd_desc = sd_desc;
1854 /*      gspca_dev->users = 0;                   (done by kzalloc) */
1855         gspca_dev->nbufread = 2;
1856
1857         /* configure the subdriver and initialize the USB device */
1858         ret = gspca_dev->sd_desc->config(gspca_dev, id);
1859         if (ret < 0)
1860                 goto out;
1861         ret = gspca_dev->sd_desc->init(gspca_dev);
1862         if (ret < 0)
1863                 goto out;
1864         ret = gspca_set_alt0(gspca_dev);
1865         if (ret < 0)
1866                 goto out;
1867         gspca_set_default_mode(gspca_dev);
1868
1869         mutex_init(&gspca_dev->usb_lock);
1870         mutex_init(&gspca_dev->read_lock);
1871         mutex_init(&gspca_dev->queue_lock);
1872         init_waitqueue_head(&gspca_dev->wq);
1873
1874         /* init video stuff */
1875         memcpy(&gspca_dev->vdev, &gspca_template, sizeof gspca_template);
1876         gspca_dev->vdev.parent = &dev->dev;
1877         memcpy(&gspca_dev->fops, &dev_fops, sizeof gspca_dev->fops);
1878         gspca_dev->vdev.fops = &gspca_dev->fops;
1879         gspca_dev->fops.owner = module;         /* module protection */
1880         gspca_dev->present = 1;
1881         ret = video_register_device(&gspca_dev->vdev,
1882                                   VFL_TYPE_GRABBER,
1883                                   video_nr);
1884         if (ret < 0) {
1885                 err("video_register_device err %d", ret);
1886                 goto out;
1887         }
1888
1889         usb_set_intfdata(intf, gspca_dev);
1890         PDEBUG(D_PROBE, "probe ok");
1891         return 0;
1892 out:
1893         kref_put(&gspca_dev->kref, gspca_delete);
1894         return ret;
1895 }
1896 EXPORT_SYMBOL(gspca_dev_probe);
1897
1898 /*
1899  * USB disconnection
1900  *
1901  * This function must be called by the sub-driver
1902  * when the device disconnects, after the specific resources are freed.
1903  */
1904 void gspca_disconnect(struct usb_interface *intf)
1905 {
1906         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1907
1908         usb_set_intfdata(intf, NULL);
1909
1910         gspca_dev->present = 0;
1911         mutex_lock(&gspca_dev->queue_lock);
1912         mutex_lock(&gspca_dev->usb_lock);
1913         gspca_dev->streaming = 0;
1914         destroy_urbs(gspca_dev);
1915         mutex_unlock(&gspca_dev->usb_lock);
1916         mutex_unlock(&gspca_dev->queue_lock);
1917
1918 /* We don't want people trying to open up the device */
1919         video_unregister_device(&gspca_dev->vdev);
1920
1921         kref_put(&gspca_dev->kref, gspca_delete);
1922
1923         PDEBUG(D_PROBE, "disconnect complete");
1924 }
1925 EXPORT_SYMBOL(gspca_disconnect);
1926
1927 #ifdef CONFIG_PM
1928 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
1929 {
1930         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1931
1932         if (!gspca_dev->streaming)
1933                 return 0;
1934         gspca_dev->frozen = 1;          /* avoid urb error messages */
1935         if (gspca_dev->sd_desc->stopN)
1936                 gspca_dev->sd_desc->stopN(gspca_dev);
1937         destroy_urbs(gspca_dev);
1938         gspca_set_alt0(gspca_dev);
1939         if (gspca_dev->sd_desc->stop0)
1940                 gspca_dev->sd_desc->stop0(gspca_dev);
1941         return 0;
1942 }
1943 EXPORT_SYMBOL(gspca_suspend);
1944
1945 int gspca_resume(struct usb_interface *intf)
1946 {
1947         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
1948
1949         gspca_dev->frozen = 0;
1950         gspca_dev->sd_desc->init(gspca_dev);
1951         if (gspca_dev->streaming)
1952                 return gspca_init_transfer(gspca_dev);
1953         return 0;
1954 }
1955 EXPORT_SYMBOL(gspca_resume);
1956 #endif
1957 /* -- cam driver utility functions -- */
1958
1959 /* auto gain and exposure algorithm based on the knee algorithm described here:
1960    http://ytse.tricolour.net/docs/LowLightOptimization.html
1961
1962    Returns 0 if no changes were made, 1 if the gain and or exposure settings
1963    where changed. */
1964 int gspca_auto_gain_n_exposure(struct gspca_dev *gspca_dev, int avg_lum,
1965         int desired_avg_lum, int deadzone, int gain_knee, int exposure_knee)
1966 {
1967         int i, steps, gain, orig_gain, exposure, orig_exposure, autogain;
1968         const struct ctrl *gain_ctrl = NULL;
1969         const struct ctrl *exposure_ctrl = NULL;
1970         const struct ctrl *autogain_ctrl = NULL;
1971         int retval = 0;
1972
1973         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1974                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_GAIN)
1975                         gain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1976                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_EXPOSURE)
1977                         exposure_ctrl = &gspca_dev->sd_desc->ctrls[i];
1978                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_AUTOGAIN)
1979                         autogain_ctrl = &gspca_dev->sd_desc->ctrls[i];
1980         }
1981         if (!gain_ctrl || !exposure_ctrl || !autogain_ctrl) {
1982                 PDEBUG(D_ERR, "Error: gspca_auto_gain_n_exposure called "
1983                         "on cam without (auto)gain/exposure");
1984                 return 0;
1985         }
1986
1987         if (gain_ctrl->get(gspca_dev, &gain) ||
1988                         exposure_ctrl->get(gspca_dev, &exposure) ||
1989                         autogain_ctrl->get(gspca_dev, &autogain) || !autogain)
1990                 return 0;
1991
1992         orig_gain = gain;
1993         orig_exposure = exposure;
1994
1995         /* If we are of a multiple of deadzone, do multiple steps to reach the
1996            desired lumination fast (with the risc of a slight overshoot) */
1997         steps = abs(desired_avg_lum - avg_lum) / deadzone;
1998
1999         PDEBUG(D_FRAM, "autogain: lum: %d, desired: %d, steps: %d\n",
2000                 avg_lum, desired_avg_lum, steps);
2001
2002         for (i = 0; i < steps; i++) {
2003                 if (avg_lum > desired_avg_lum) {
2004                         if (gain > gain_knee)
2005                                 gain--;
2006                         else if (exposure > exposure_knee)
2007                                 exposure--;
2008                         else if (gain > gain_ctrl->qctrl.default_value)
2009                                 gain--;
2010                         else if (exposure > exposure_ctrl->qctrl.minimum)
2011                                 exposure--;
2012                         else if (gain > gain_ctrl->qctrl.minimum)
2013                                 gain--;
2014                         else
2015                                 break;
2016                 } else {
2017                         if (gain < gain_ctrl->qctrl.default_value)
2018                                 gain++;
2019                         else if (exposure < exposure_knee)
2020                                 exposure++;
2021                         else if (gain < gain_knee)
2022                                 gain++;
2023                         else if (exposure < exposure_ctrl->qctrl.maximum)
2024                                 exposure++;
2025                         else if (gain < gain_ctrl->qctrl.maximum)
2026                                 gain++;
2027                         else
2028                                 break;
2029                 }
2030         }
2031
2032         if (gain != orig_gain) {
2033                 gain_ctrl->set(gspca_dev, gain);
2034                 retval = 1;
2035         }
2036         if (exposure != orig_exposure) {
2037                 exposure_ctrl->set(gspca_dev, exposure);
2038                 retval = 1;
2039         }
2040
2041         return retval;
2042 }
2043 EXPORT_SYMBOL(gspca_auto_gain_n_exposure);
2044
2045 /* -- module insert / remove -- */
2046 static int __init gspca_init(void)
2047 {
2048         info("main v%d.%d.%d registered",
2049                 (DRIVER_VERSION_NUMBER >> 16) & 0xff,
2050                 (DRIVER_VERSION_NUMBER >> 8) & 0xff,
2051                 DRIVER_VERSION_NUMBER & 0xff);
2052         return 0;
2053 }
2054 static void __exit gspca_exit(void)
2055 {
2056         info("main deregistered");
2057 }
2058
2059 module_init(gspca_init);
2060 module_exit(gspca_exit);
2061
2062 #ifdef GSPCA_DEBUG
2063 module_param_named(debug, gspca_debug, int, 0644);
2064 MODULE_PARM_DESC(debug,
2065                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
2066                 " 0x08:stream 0x10:frame 0x20:packet 0x40:USBin 0x80:USBout"
2067                 " 0x0100: v4l2");
2068 #endif