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