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