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