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