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