]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/video/gspca/gspca.c
[media] gspca: Allow subdrivers to use the control framework
[karo-tx-linux.git] / drivers / media / video / gspca / gspca.c
1 /*
2  * Main USB camera driver
3  *
4  * Copyright (C) 2008-2011 Jean-François Moine <http://moinejf.free.fr>
5  *
6  * Camera button input handling by Márton Németh
7  * Copyright (C) 2009-2010 Márton Németh <nm127@freemail.hu>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by the
11  * Free Software Foundation; either version 2 of the License, or (at your
12  * option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17  * for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
25
26 #define GSPCA_VERSION   "2.14.0"
27
28 #include <linux/init.h>
29 #include <linux/fs.h>
30 #include <linux/vmalloc.h>
31 #include <linux/sched.h>
32 #include <linux/slab.h>
33 #include <linux/mm.h>
34 #include <linux/string.h>
35 #include <linux/pagemap.h>
36 #include <linux/io.h>
37 #include <asm/page.h>
38 #include <linux/uaccess.h>
39 #include <linux/ktime.h>
40 #include <media/v4l2-ioctl.h>
41 #include <media/v4l2-ctrls.h>
42
43 #include "gspca.h"
44
45 #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
46 #include <linux/input.h>
47 #include <linux/usb/input.h>
48 #endif
49
50 /* global values */
51 #define DEF_NURBS 3             /* default number of URBs */
52 #if DEF_NURBS > MAX_NURBS
53 #error "DEF_NURBS too big"
54 #endif
55
56 MODULE_AUTHOR("Jean-François Moine <http://moinejf.free.fr>");
57 MODULE_DESCRIPTION("GSPCA USB Camera Driver");
58 MODULE_LICENSE("GPL");
59 MODULE_VERSION(GSPCA_VERSION);
60
61 #ifdef GSPCA_DEBUG
62 int gspca_debug = D_ERR | D_PROBE;
63 EXPORT_SYMBOL(gspca_debug);
64
65 static void PDEBUG_MODE(char *txt, __u32 pixfmt, int w, int h)
66 {
67         if ((pixfmt >> 24) >= '0' && (pixfmt >> 24) <= 'z') {
68                 PDEBUG(D_CONF|D_STREAM, "%s %c%c%c%c %dx%d",
69                         txt,
70                         pixfmt & 0xff,
71                         (pixfmt >> 8) & 0xff,
72                         (pixfmt >> 16) & 0xff,
73                         pixfmt >> 24,
74                         w, h);
75         } else {
76                 PDEBUG(D_CONF|D_STREAM, "%s 0x%08x %dx%d",
77                         txt,
78                         pixfmt,
79                         w, h);
80         }
81 }
82 #else
83 #define PDEBUG_MODE(txt, pixfmt, w, h)
84 #endif
85
86 /* specific memory types - !! should be different from V4L2_MEMORY_xxx */
87 #define GSPCA_MEMORY_NO 0       /* V4L2_MEMORY_xxx starts from 1 */
88 #define GSPCA_MEMORY_READ 7
89
90 #define BUF_ALL_FLAGS (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE)
91
92 /*
93  * VMA operations.
94  */
95 static void gspca_vm_open(struct vm_area_struct *vma)
96 {
97         struct gspca_frame *frame = vma->vm_private_data;
98
99         frame->vma_use_count++;
100         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
101 }
102
103 static void gspca_vm_close(struct vm_area_struct *vma)
104 {
105         struct gspca_frame *frame = vma->vm_private_data;
106
107         if (--frame->vma_use_count <= 0)
108                 frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_MAPPED;
109 }
110
111 static const struct vm_operations_struct gspca_vm_ops = {
112         .open           = gspca_vm_open,
113         .close          = gspca_vm_close,
114 };
115
116 /*
117  * Input and interrupt endpoint handling functions
118  */
119 #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
120 static void int_irq(struct urb *urb)
121 {
122         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
123         int ret;
124
125         ret = urb->status;
126         switch (ret) {
127         case 0:
128                 if (gspca_dev->sd_desc->int_pkt_scan(gspca_dev,
129                     urb->transfer_buffer, urb->actual_length) < 0) {
130                         PDEBUG(D_ERR, "Unknown packet received");
131                 }
132                 break;
133
134         case -ENOENT:
135         case -ECONNRESET:
136         case -ENODEV:
137         case -ESHUTDOWN:
138                 /* Stop is requested either by software or hardware is gone,
139                  * keep the ret value non-zero and don't resubmit later.
140                  */
141                 break;
142
143         default:
144                 PDEBUG(D_ERR, "URB error %i, resubmitting", urb->status);
145                 urb->status = 0;
146                 ret = 0;
147         }
148
149         if (ret == 0) {
150                 ret = usb_submit_urb(urb, GFP_ATOMIC);
151                 if (ret < 0)
152                         pr_err("Resubmit URB failed with error %i\n", ret);
153         }
154 }
155
156 static int gspca_input_connect(struct gspca_dev *dev)
157 {
158         struct input_dev *input_dev;
159         int err = 0;
160
161         dev->input_dev = NULL;
162         if (dev->sd_desc->int_pkt_scan || dev->sd_desc->other_input)  {
163                 input_dev = input_allocate_device();
164                 if (!input_dev)
165                         return -ENOMEM;
166
167                 usb_make_path(dev->dev, dev->phys, sizeof(dev->phys));
168                 strlcat(dev->phys, "/input0", sizeof(dev->phys));
169
170                 input_dev->name = dev->sd_desc->name;
171                 input_dev->phys = dev->phys;
172
173                 usb_to_input_id(dev->dev, &input_dev->id);
174
175                 input_dev->evbit[0] = BIT_MASK(EV_KEY);
176                 input_dev->keybit[BIT_WORD(KEY_CAMERA)] = BIT_MASK(KEY_CAMERA);
177                 input_dev->dev.parent = &dev->dev->dev;
178
179                 err = input_register_device(input_dev);
180                 if (err) {
181                         pr_err("Input device registration failed with error %i\n",
182                                err);
183                         input_dev->dev.parent = NULL;
184                         input_free_device(input_dev);
185                 } else {
186                         dev->input_dev = input_dev;
187                 }
188         }
189
190         return err;
191 }
192
193 static int alloc_and_submit_int_urb(struct gspca_dev *gspca_dev,
194                           struct usb_endpoint_descriptor *ep)
195 {
196         unsigned int buffer_len;
197         int interval;
198         struct urb *urb;
199         struct usb_device *dev;
200         void *buffer = NULL;
201         int ret = -EINVAL;
202
203         buffer_len = le16_to_cpu(ep->wMaxPacketSize);
204         interval = ep->bInterval;
205         PDEBUG(D_CONF, "found int in endpoint: 0x%x, "
206                 "buffer_len=%u, interval=%u",
207                 ep->bEndpointAddress, buffer_len, interval);
208
209         dev = gspca_dev->dev;
210
211         urb = usb_alloc_urb(0, GFP_KERNEL);
212         if (!urb) {
213                 ret = -ENOMEM;
214                 goto error;
215         }
216
217         buffer = usb_alloc_coherent(dev, buffer_len,
218                                 GFP_KERNEL, &urb->transfer_dma);
219         if (!buffer) {
220                 ret = -ENOMEM;
221                 goto error_buffer;
222         }
223         usb_fill_int_urb(urb, dev,
224                 usb_rcvintpipe(dev, ep->bEndpointAddress),
225                 buffer, buffer_len,
226                 int_irq, (void *)gspca_dev, interval);
227         urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
228         ret = usb_submit_urb(urb, GFP_KERNEL);
229         if (ret < 0) {
230                 PDEBUG(D_ERR, "submit int URB failed with error %i", ret);
231                 goto error_submit;
232         }
233         gspca_dev->int_urb = urb;
234         return ret;
235
236 error_submit:
237         usb_free_coherent(dev,
238                           urb->transfer_buffer_length,
239                           urb->transfer_buffer,
240                           urb->transfer_dma);
241 error_buffer:
242         usb_free_urb(urb);
243 error:
244         return ret;
245 }
246
247 static void gspca_input_create_urb(struct gspca_dev *gspca_dev)
248 {
249         struct usb_interface *intf;
250         struct usb_host_interface *intf_desc;
251         struct usb_endpoint_descriptor *ep;
252         int i;
253
254         if (gspca_dev->sd_desc->int_pkt_scan)  {
255                 intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
256                 intf_desc = intf->cur_altsetting;
257                 for (i = 0; i < intf_desc->desc.bNumEndpoints; i++) {
258                         ep = &intf_desc->endpoint[i].desc;
259                         if (usb_endpoint_dir_in(ep) &&
260                             usb_endpoint_xfer_int(ep)) {
261
262                                 alloc_and_submit_int_urb(gspca_dev, ep);
263                                 break;
264                         }
265                 }
266         }
267 }
268
269 static void gspca_input_destroy_urb(struct gspca_dev *gspca_dev)
270 {
271         struct urb *urb;
272
273         urb = gspca_dev->int_urb;
274         if (urb) {
275                 gspca_dev->int_urb = NULL;
276                 usb_kill_urb(urb);
277                 usb_free_coherent(gspca_dev->dev,
278                                   urb->transfer_buffer_length,
279                                   urb->transfer_buffer,
280                                   urb->transfer_dma);
281                 usb_free_urb(urb);
282         }
283 }
284 #else
285 static inline void gspca_input_destroy_urb(struct gspca_dev *gspca_dev)
286 {
287 }
288
289 static inline void gspca_input_create_urb(struct gspca_dev *gspca_dev)
290 {
291 }
292
293 static inline int gspca_input_connect(struct gspca_dev *dev)
294 {
295         return 0;
296 }
297 #endif
298
299 /*
300  * fill a video frame from an URB and resubmit
301  */
302 static void fill_frame(struct gspca_dev *gspca_dev,
303                         struct urb *urb)
304 {
305         u8 *data;               /* address of data in the iso message */
306         int i, len, st;
307         cam_pkt_op pkt_scan;
308
309         if (urb->status != 0) {
310                 if (urb->status == -ESHUTDOWN)
311                         return;         /* disconnection */
312 #ifdef CONFIG_PM
313                 if (gspca_dev->frozen)
314                         return;
315 #endif
316                 PDEBUG(D_ERR|D_PACK, "urb status: %d", urb->status);
317                 urb->status = 0;
318                 goto resubmit;
319         }
320         pkt_scan = gspca_dev->sd_desc->pkt_scan;
321         for (i = 0; i < urb->number_of_packets; i++) {
322                 len = urb->iso_frame_desc[i].actual_length;
323
324                 /* check the packet status and length */
325                 st = urb->iso_frame_desc[i].status;
326                 if (st) {
327                         pr_err("ISOC data error: [%d] len=%d, status=%d\n",
328                                i, len, st);
329                         gspca_dev->last_packet_type = DISCARD_PACKET;
330                         continue;
331                 }
332                 if (len == 0) {
333                         if (gspca_dev->empty_packet == 0)
334                                 gspca_dev->empty_packet = 1;
335                         continue;
336                 }
337
338                 /* let the packet be analyzed by the subdriver */
339                 PDEBUG(D_PACK, "packet [%d] o:%d l:%d",
340                         i, urb->iso_frame_desc[i].offset, len);
341                 data = (u8 *) urb->transfer_buffer
342                                         + urb->iso_frame_desc[i].offset;
343                 pkt_scan(gspca_dev, data, len);
344         }
345
346 resubmit:
347         /* resubmit the URB */
348         st = usb_submit_urb(urb, GFP_ATOMIC);
349         if (st < 0)
350                 pr_err("usb_submit_urb() ret %d\n", st);
351 }
352
353 /*
354  * ISOC message interrupt from the USB device
355  *
356  * Analyse each packet and call the subdriver for copy to the frame buffer.
357  */
358 static void isoc_irq(struct urb *urb)
359 {
360         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
361
362         PDEBUG(D_PACK, "isoc irq");
363         if (!gspca_dev->streaming)
364                 return;
365         fill_frame(gspca_dev, urb);
366 }
367
368 /*
369  * bulk message interrupt from the USB device
370  */
371 static void bulk_irq(struct urb *urb)
372 {
373         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
374         int st;
375
376         PDEBUG(D_PACK, "bulk irq");
377         if (!gspca_dev->streaming)
378                 return;
379         switch (urb->status) {
380         case 0:
381                 break;
382         case -ESHUTDOWN:
383                 return;         /* disconnection */
384         default:
385 #ifdef CONFIG_PM
386                 if (gspca_dev->frozen)
387                         return;
388 #endif
389                 PDEBUG(D_ERR|D_PACK, "urb status: %d", urb->status);
390                 urb->status = 0;
391                 goto resubmit;
392         }
393
394         PDEBUG(D_PACK, "packet l:%d", urb->actual_length);
395         gspca_dev->sd_desc->pkt_scan(gspca_dev,
396                                 urb->transfer_buffer,
397                                 urb->actual_length);
398
399 resubmit:
400         /* resubmit the URB */
401         if (gspca_dev->cam.bulk_nurbs != 0) {
402                 st = usb_submit_urb(urb, GFP_ATOMIC);
403                 if (st < 0)
404                         pr_err("usb_submit_urb() ret %d\n", st);
405         }
406 }
407
408 /*
409  * add data to the current frame
410  *
411  * This function is called by the subdrivers at interrupt level.
412  *
413  * To build a frame, these ones must add
414  *      - one FIRST_PACKET
415  *      - 0 or many INTER_PACKETs
416  *      - one LAST_PACKET
417  * DISCARD_PACKET invalidates the whole frame.
418  */
419 void gspca_frame_add(struct gspca_dev *gspca_dev,
420                         enum gspca_packet_type packet_type,
421                         const u8 *data,
422                         int len)
423 {
424         struct gspca_frame *frame;
425         int i, j;
426
427         PDEBUG(D_PACK, "add t:%d l:%d", packet_type, len);
428
429         if (packet_type == FIRST_PACKET) {
430                 i = atomic_read(&gspca_dev->fr_i);
431
432                 /* if there are no queued buffer, discard the whole frame */
433                 if (i == atomic_read(&gspca_dev->fr_q)) {
434                         gspca_dev->last_packet_type = DISCARD_PACKET;
435                         gspca_dev->sequence++;
436                         return;
437                 }
438                 j = gspca_dev->fr_queue[i];
439                 frame = &gspca_dev->frame[j];
440                 frame->v4l2_buf.timestamp = ktime_to_timeval(ktime_get());
441                 frame->v4l2_buf.sequence = gspca_dev->sequence++;
442                 gspca_dev->image = frame->data;
443                 gspca_dev->image_len = 0;
444         } else {
445                 switch (gspca_dev->last_packet_type) {
446                 case DISCARD_PACKET:
447                         if (packet_type == LAST_PACKET) {
448                                 gspca_dev->last_packet_type = packet_type;
449                                 gspca_dev->image = NULL;
450                                 gspca_dev->image_len = 0;
451                         }
452                         return;
453                 case LAST_PACKET:
454                         return;
455                 }
456         }
457
458         /* append the packet to the frame buffer */
459         if (len > 0) {
460                 if (gspca_dev->image_len + len > gspca_dev->frsz) {
461                         PDEBUG(D_ERR|D_PACK, "frame overflow %d > %d",
462                                 gspca_dev->image_len + len,
463                                 gspca_dev->frsz);
464                         packet_type = DISCARD_PACKET;
465                 } else {
466 /* !! image is NULL only when last pkt is LAST or DISCARD
467                         if (gspca_dev->image == NULL) {
468                                 pr_err("gspca_frame_add() image == NULL\n");
469                                 return;
470                         }
471  */
472                         memcpy(gspca_dev->image + gspca_dev->image_len,
473                                 data, len);
474                         gspca_dev->image_len += len;
475                 }
476         }
477         gspca_dev->last_packet_type = packet_type;
478
479         /* if last packet, invalidate packet concatenation until
480          * next first packet, wake up the application and advance
481          * in the queue */
482         if (packet_type == LAST_PACKET) {
483                 i = atomic_read(&gspca_dev->fr_i);
484                 j = gspca_dev->fr_queue[i];
485                 frame = &gspca_dev->frame[j];
486                 frame->v4l2_buf.bytesused = gspca_dev->image_len;
487                 frame->v4l2_buf.flags = (frame->v4l2_buf.flags
488                                          | V4L2_BUF_FLAG_DONE)
489                                         & ~V4L2_BUF_FLAG_QUEUED;
490                 i = (i + 1) % GSPCA_MAX_FRAMES;
491                 atomic_set(&gspca_dev->fr_i, i);
492                 wake_up_interruptible(&gspca_dev->wq);  /* event = new frame */
493                 PDEBUG(D_FRAM, "frame complete len:%d",
494                         frame->v4l2_buf.bytesused);
495                 gspca_dev->image = NULL;
496                 gspca_dev->image_len = 0;
497         }
498 }
499 EXPORT_SYMBOL(gspca_frame_add);
500
501 static int frame_alloc(struct gspca_dev *gspca_dev, struct file *file,
502                         enum v4l2_memory memory, unsigned int count)
503 {
504         struct gspca_frame *frame;
505         unsigned int frsz;
506         int i;
507
508         i = gspca_dev->curr_mode;
509         frsz = gspca_dev->cam.cam_mode[i].sizeimage;
510         PDEBUG(D_STREAM, "frame alloc frsz: %d", frsz);
511         frsz = PAGE_ALIGN(frsz);
512         if (count >= GSPCA_MAX_FRAMES)
513                 count = GSPCA_MAX_FRAMES - 1;
514         gspca_dev->frbuf = vmalloc_32(frsz * count);
515         if (!gspca_dev->frbuf) {
516                 pr_err("frame alloc failed\n");
517                 return -ENOMEM;
518         }
519         gspca_dev->capt_file = file;
520         gspca_dev->memory = memory;
521         gspca_dev->frsz = frsz;
522         gspca_dev->nframes = count;
523         for (i = 0; i < count; i++) {
524                 frame = &gspca_dev->frame[i];
525                 frame->v4l2_buf.index = i;
526                 frame->v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
527                 frame->v4l2_buf.flags = 0;
528                 frame->v4l2_buf.field = V4L2_FIELD_NONE;
529                 frame->v4l2_buf.length = frsz;
530                 frame->v4l2_buf.memory = memory;
531                 frame->v4l2_buf.sequence = 0;
532                 frame->data = gspca_dev->frbuf + i * frsz;
533                 frame->v4l2_buf.m.offset = i * frsz;
534         }
535         atomic_set(&gspca_dev->fr_q, 0);
536         atomic_set(&gspca_dev->fr_i, 0);
537         gspca_dev->fr_o = 0;
538         return 0;
539 }
540
541 static void frame_free(struct gspca_dev *gspca_dev)
542 {
543         int i;
544
545         PDEBUG(D_STREAM, "frame free");
546         if (gspca_dev->frbuf != NULL) {
547                 vfree(gspca_dev->frbuf);
548                 gspca_dev->frbuf = NULL;
549                 for (i = 0; i < gspca_dev->nframes; i++)
550                         gspca_dev->frame[i].data = NULL;
551         }
552         gspca_dev->nframes = 0;
553         gspca_dev->frsz = 0;
554         gspca_dev->capt_file = NULL;
555         gspca_dev->memory = GSPCA_MEMORY_NO;
556 }
557
558 static void destroy_urbs(struct gspca_dev *gspca_dev)
559 {
560         struct urb *urb;
561         unsigned int i;
562
563         PDEBUG(D_STREAM, "kill transfer");
564         for (i = 0; i < MAX_NURBS; i++) {
565                 urb = gspca_dev->urb[i];
566                 if (urb == NULL)
567                         break;
568
569                 gspca_dev->urb[i] = NULL;
570                 usb_kill_urb(urb);
571                 if (urb->transfer_buffer != NULL)
572                         usb_free_coherent(gspca_dev->dev,
573                                           urb->transfer_buffer_length,
574                                           urb->transfer_buffer,
575                                           urb->transfer_dma);
576                 usb_free_urb(urb);
577         }
578 }
579
580 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
581 {
582         int ret;
583
584         if (gspca_dev->alt == 0)
585                 return 0;
586         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
587         if (ret < 0)
588                 pr_err("set alt 0 err %d\n", ret);
589         return ret;
590 }
591
592 /* Note: both the queue and the usb locks should be held when calling this */
593 static void gspca_stream_off(struct gspca_dev *gspca_dev)
594 {
595         gspca_dev->streaming = 0;
596         if (gspca_dev->present) {
597                 if (gspca_dev->sd_desc->stopN)
598                         gspca_dev->sd_desc->stopN(gspca_dev);
599                 destroy_urbs(gspca_dev);
600                 gspca_input_destroy_urb(gspca_dev);
601                 gspca_set_alt0(gspca_dev);
602                 gspca_input_create_urb(gspca_dev);
603         }
604
605         /* always call stop0 to free the subdriver's resources */
606         if (gspca_dev->sd_desc->stop0)
607                 gspca_dev->sd_desc->stop0(gspca_dev);
608         PDEBUG(D_STREAM, "stream off OK");
609 }
610
611 /*
612  * look for an input transfer endpoint in an alternate setting
613  */
614 static struct usb_host_endpoint *alt_xfer(struct usb_host_interface *alt,
615                                           int xfer)
616 {
617         struct usb_host_endpoint *ep;
618         int i, attr;
619
620         for (i = 0; i < alt->desc.bNumEndpoints; i++) {
621                 ep = &alt->endpoint[i];
622                 attr = ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
623                 if (attr == xfer
624                     && ep->desc.wMaxPacketSize != 0
625                     && usb_endpoint_dir_in(&ep->desc))
626                         return ep;
627         }
628         return NULL;
629 }
630
631 /* compute the minimum bandwidth for the current transfer */
632 static u32 which_bandwidth(struct gspca_dev *gspca_dev)
633 {
634         u32 bandwidth;
635         int i;
636
637         /* get the (max) image size */
638         i = gspca_dev->curr_mode;
639         bandwidth = gspca_dev->cam.cam_mode[i].sizeimage;
640
641         /* if the image is compressed, estimate its mean size */
642         if (!gspca_dev->cam.needs_full_bandwidth &&
643             bandwidth < gspca_dev->cam.cam_mode[i].width *
644                                 gspca_dev->cam.cam_mode[i].height)
645                 bandwidth = bandwidth * 3 / 8;  /* 0.375 */
646
647         /* estimate the frame rate */
648         if (gspca_dev->sd_desc->get_streamparm) {
649                 struct v4l2_streamparm parm;
650
651                 gspca_dev->sd_desc->get_streamparm(gspca_dev, &parm);
652                 bandwidth *= parm.parm.capture.timeperframe.denominator;
653                 bandwidth /= parm.parm.capture.timeperframe.numerator;
654         } else {
655
656                 /* don't hope more than 15 fps with USB 1.1 and
657                  * image resolution >= 640x480 */
658                 if (gspca_dev->width >= 640
659                  && gspca_dev->dev->speed == USB_SPEED_FULL)
660                         bandwidth *= 15;                /* 15 fps */
661                 else
662                         bandwidth *= 30;                /* 30 fps */
663         }
664
665         PDEBUG(D_STREAM, "min bandwidth: %d", bandwidth);
666         return bandwidth;
667 }
668
669 /* endpoint table */
670 #define MAX_ALT 16
671 struct ep_tb_s {
672         u32 alt;
673         u32 bandwidth;
674 };
675
676 /*
677  * build the table of the endpoints
678  * and compute the minimum bandwidth for the image transfer
679  */
680 static int build_isoc_ep_tb(struct gspca_dev *gspca_dev,
681                         struct usb_interface *intf,
682                         struct ep_tb_s *ep_tb)
683 {
684         struct usb_host_endpoint *ep;
685         int i, j, nbalt, psize, found;
686         u32 bandwidth, last_bw;
687
688         nbalt = intf->num_altsetting;
689         if (nbalt > MAX_ALT)
690                 nbalt = MAX_ALT;        /* fixme: should warn */
691
692         /* build the endpoint table */
693         i = 0;
694         last_bw = 0;
695         for (;;) {
696                 ep_tb->bandwidth = 2000 * 2000 * 120;
697                 found = 0;
698                 for (j = 0; j < nbalt; j++) {
699                         ep = alt_xfer(&intf->altsetting[j],
700                                       USB_ENDPOINT_XFER_ISOC);
701                         if (ep == NULL)
702                                 continue;
703                         if (ep->desc.bInterval == 0) {
704                                 pr_err("alt %d iso endp with 0 interval\n", j);
705                                 continue;
706                         }
707                         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
708                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
709                         bandwidth = psize * 1000;
710                         if (gspca_dev->dev->speed == USB_SPEED_HIGH
711                          || gspca_dev->dev->speed == USB_SPEED_SUPER)
712                                 bandwidth *= 8;
713                         bandwidth /= 1 << (ep->desc.bInterval - 1);
714                         if (bandwidth <= last_bw)
715                                 continue;
716                         if (bandwidth < ep_tb->bandwidth) {
717                                 ep_tb->bandwidth = bandwidth;
718                                 ep_tb->alt = j;
719                                 found = 1;
720                         }
721                 }
722                 if (!found)
723                         break;
724                 PDEBUG(D_STREAM, "alt %d bandwidth %d",
725                                 ep_tb->alt, ep_tb->bandwidth);
726                 last_bw = ep_tb->bandwidth;
727                 i++;
728                 ep_tb++;
729         }
730
731         /*
732          * If the camera:
733          * has a usb audio class interface (a built in usb mic); and
734          * is a usb 1 full speed device; and
735          * uses the max full speed iso bandwidth; and
736          * and has more than 1 alt setting
737          * then skip the highest alt setting to spare bandwidth for the mic
738          */
739         if (gspca_dev->audio &&
740                         gspca_dev->dev->speed == USB_SPEED_FULL &&
741                         last_bw >= 1000000 &&
742                         i > 1) {
743                 PDEBUG(D_STREAM, "dev has usb audio, skipping highest alt");
744                 i--;
745                 ep_tb--;
746         }
747
748         /* get the requested bandwidth and start at the highest atlsetting */
749         bandwidth = which_bandwidth(gspca_dev);
750         ep_tb--;
751         while (i > 1) {
752                 ep_tb--;
753                 if (ep_tb->bandwidth < bandwidth)
754                         break;
755                 i--;
756         }
757         return i;
758 }
759
760 /*
761  * create the URBs for image transfer
762  */
763 static int create_urbs(struct gspca_dev *gspca_dev,
764                         struct usb_host_endpoint *ep)
765 {
766         struct urb *urb;
767         int n, nurbs, i, psize, npkt, bsize;
768
769         /* calculate the packet size and the number of packets */
770         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
771
772         if (!gspca_dev->cam.bulk) {             /* isoc */
773
774                 /* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
775                 if (gspca_dev->pkt_size == 0)
776                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
777                 else
778                         psize = gspca_dev->pkt_size;
779                 npkt = gspca_dev->cam.npkt;
780                 if (npkt == 0)
781                         npkt = 32;              /* default value */
782                 bsize = psize * npkt;
783                 PDEBUG(D_STREAM,
784                         "isoc %d pkts size %d = bsize:%d",
785                         npkt, psize, bsize);
786                 nurbs = DEF_NURBS;
787         } else {                                /* bulk */
788                 npkt = 0;
789                 bsize = gspca_dev->cam.bulk_size;
790                 if (bsize == 0)
791                         bsize = psize;
792                 PDEBUG(D_STREAM, "bulk bsize:%d", bsize);
793                 if (gspca_dev->cam.bulk_nurbs != 0)
794                         nurbs = gspca_dev->cam.bulk_nurbs;
795                 else
796                         nurbs = 1;
797         }
798
799         for (n = 0; n < nurbs; n++) {
800                 urb = usb_alloc_urb(npkt, GFP_KERNEL);
801                 if (!urb) {
802                         pr_err("usb_alloc_urb failed\n");
803                         return -ENOMEM;
804                 }
805                 gspca_dev->urb[n] = urb;
806                 urb->transfer_buffer = usb_alloc_coherent(gspca_dev->dev,
807                                                 bsize,
808                                                 GFP_KERNEL,
809                                                 &urb->transfer_dma);
810
811                 if (urb->transfer_buffer == NULL) {
812                         pr_err("usb_alloc_coherent failed\n");
813                         return -ENOMEM;
814                 }
815                 urb->dev = gspca_dev->dev;
816                 urb->context = gspca_dev;
817                 urb->transfer_buffer_length = bsize;
818                 if (npkt != 0) {                /* ISOC */
819                         urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
820                                                     ep->desc.bEndpointAddress);
821                         urb->transfer_flags = URB_ISO_ASAP
822                                         | URB_NO_TRANSFER_DMA_MAP;
823                         urb->interval = 1 << (ep->desc.bInterval - 1);
824                         urb->complete = isoc_irq;
825                         urb->number_of_packets = npkt;
826                         for (i = 0; i < npkt; i++) {
827                                 urb->iso_frame_desc[i].length = psize;
828                                 urb->iso_frame_desc[i].offset = psize * i;
829                         }
830                 } else {                /* bulk */
831                         urb->pipe = usb_rcvbulkpipe(gspca_dev->dev,
832                                                 ep->desc.bEndpointAddress);
833                         urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
834                         urb->complete = bulk_irq;
835                 }
836         }
837         return 0;
838 }
839
840 /*
841  * start the USB transfer
842  */
843 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
844 {
845         struct usb_interface *intf;
846         struct usb_host_endpoint *ep;
847         struct urb *urb;
848         struct ep_tb_s ep_tb[MAX_ALT];
849         int n, ret, xfer, alt, alt_idx;
850
851         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
852                 return -ERESTARTSYS;
853
854         if (!gspca_dev->present) {
855                 ret = -ENODEV;
856                 goto unlock;
857         }
858
859         /* reset the streaming variables */
860         gspca_dev->image = NULL;
861         gspca_dev->image_len = 0;
862         gspca_dev->last_packet_type = DISCARD_PACKET;
863         gspca_dev->sequence = 0;
864
865         gspca_dev->usb_err = 0;
866
867         /* do the specific subdriver stuff before endpoint selection */
868         intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
869         gspca_dev->alt = gspca_dev->cam.bulk ? intf->num_altsetting : 0;
870         if (gspca_dev->sd_desc->isoc_init) {
871                 ret = gspca_dev->sd_desc->isoc_init(gspca_dev);
872                 if (ret < 0)
873                         goto unlock;
874         }
875         xfer = gspca_dev->cam.bulk ? USB_ENDPOINT_XFER_BULK
876                                    : USB_ENDPOINT_XFER_ISOC;
877
878         /* if bulk or the subdriver forced an altsetting, get the endpoint */
879         if (gspca_dev->alt != 0) {
880                 gspca_dev->alt--;       /* (previous version compatibility) */
881                 ep = alt_xfer(&intf->altsetting[gspca_dev->alt], xfer);
882                 if (ep == NULL) {
883                         pr_err("bad altsetting %d\n", gspca_dev->alt);
884                         ret = -EIO;
885                         goto out;
886                 }
887                 ep_tb[0].alt = gspca_dev->alt;
888                 alt_idx = 1;
889         } else {
890
891         /* else, compute the minimum bandwidth
892          * and build the endpoint table */
893                 alt_idx = build_isoc_ep_tb(gspca_dev, intf, ep_tb);
894                 if (alt_idx <= 0) {
895                         pr_err("no transfer endpoint found\n");
896                         ret = -EIO;
897                         goto unlock;
898                 }
899         }
900
901         /* set the highest alternate setting and
902          * loop until urb submit succeeds */
903         gspca_input_destroy_urb(gspca_dev);
904
905         gspca_dev->alt = ep_tb[--alt_idx].alt;
906         alt = -1;
907         for (;;) {
908                 if (alt != gspca_dev->alt) {
909                         alt = gspca_dev->alt;
910                         if (intf->num_altsetting > 1) {
911                                 ret = usb_set_interface(gspca_dev->dev,
912                                                         gspca_dev->iface,
913                                                         alt);
914                                 if (ret < 0) {
915                                         if (ret == -ENOSPC)
916                                                 goto retry; /*fixme: ugly*/
917                                         pr_err("set alt %d err %d\n", alt, ret);
918                                         goto out;
919                                 }
920                         }
921                 }
922                 if (!gspca_dev->cam.no_urb_create) {
923                         PDEBUG(D_STREAM, "init transfer alt %d", alt);
924                         ret = create_urbs(gspca_dev,
925                                 alt_xfer(&intf->altsetting[alt], xfer));
926                         if (ret < 0) {
927                                 destroy_urbs(gspca_dev);
928                                 goto out;
929                         }
930                 }
931
932                 /* clear the bulk endpoint */
933                 if (gspca_dev->cam.bulk)
934                         usb_clear_halt(gspca_dev->dev,
935                                         gspca_dev->urb[0]->pipe);
936
937                 /* start the cam */
938                 ret = gspca_dev->sd_desc->start(gspca_dev);
939                 if (ret < 0) {
940                         destroy_urbs(gspca_dev);
941                         goto out;
942                 }
943                 gspca_dev->streaming = 1;
944
945                 /* some bulk transfers are started by the subdriver */
946                 if (gspca_dev->cam.bulk && gspca_dev->cam.bulk_nurbs == 0)
947                         break;
948
949                 /* submit the URBs */
950                 for (n = 0; n < MAX_NURBS; n++) {
951                         urb = gspca_dev->urb[n];
952                         if (urb == NULL)
953                                 break;
954                         ret = usb_submit_urb(urb, GFP_KERNEL);
955                         if (ret < 0)
956                                 break;
957                 }
958                 if (ret >= 0)
959                         break;                  /* transfer is started */
960
961                 /* something when wrong
962                  * stop the webcam and free the transfer resources */
963                 gspca_stream_off(gspca_dev);
964                 if (ret != -ENOSPC) {
965                         pr_err("usb_submit_urb alt %d err %d\n",
966                                gspca_dev->alt, ret);
967                         goto out;
968                 }
969
970                 /* the bandwidth is not wide enough
971                  * negotiate or try a lower alternate setting */
972 retry:
973                 PDEBUG(D_ERR|D_STREAM,
974                         "alt %d - bandwidth not wide enough - trying again",
975                         alt);
976                 msleep(20);     /* wait for kill complete */
977                 if (gspca_dev->sd_desc->isoc_nego) {
978                         ret = gspca_dev->sd_desc->isoc_nego(gspca_dev);
979                         if (ret < 0)
980                                 goto out;
981                 } else {
982                         if (alt_idx <= 0) {
983                                 pr_err("no transfer endpoint found\n");
984                                 ret = -EIO;
985                                 goto out;
986                         }
987                         gspca_dev->alt = ep_tb[--alt_idx].alt;
988                 }
989         }
990 out:
991         gspca_input_create_urb(gspca_dev);
992 unlock:
993         mutex_unlock(&gspca_dev->usb_lock);
994         return ret;
995 }
996
997 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
998 {
999         struct gspca_ctrl *ctrl;
1000         int i;
1001
1002         i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
1003         gspca_dev->curr_mode = i;
1004         gspca_dev->width = gspca_dev->cam.cam_mode[i].width;
1005         gspca_dev->height = gspca_dev->cam.cam_mode[i].height;
1006         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixelformat;
1007
1008         /* set the current control values to their default values
1009          * which may have changed in sd_init() */
1010         /* does nothing if ctrl_handler == NULL */
1011         v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
1012         ctrl = gspca_dev->cam.ctrls;
1013         if (ctrl != NULL) {
1014                 for (i = 0;
1015                      i < gspca_dev->sd_desc->nctrls;
1016                      i++, ctrl++)
1017                         ctrl->val = ctrl->def;
1018         }
1019 }
1020
1021 static int wxh_to_mode(struct gspca_dev *gspca_dev,
1022                         int width, int height)
1023 {
1024         int i;
1025
1026         for (i = gspca_dev->cam.nmodes; --i > 0; ) {
1027                 if (width >= gspca_dev->cam.cam_mode[i].width
1028                     && height >= gspca_dev->cam.cam_mode[i].height)
1029                         break;
1030         }
1031         return i;
1032 }
1033
1034 /*
1035  * search a mode with the right pixel format
1036  */
1037 static int gspca_get_mode(struct gspca_dev *gspca_dev,
1038                         int mode,
1039                         int pixfmt)
1040 {
1041         int modeU, modeD;
1042
1043         modeU = modeD = mode;
1044         while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
1045                 if (--modeD >= 0) {
1046                         if (gspca_dev->cam.cam_mode[modeD].pixelformat
1047                                                                 == pixfmt)
1048                                 return modeD;
1049                 }
1050                 if (++modeU < gspca_dev->cam.nmodes) {
1051                         if (gspca_dev->cam.cam_mode[modeU].pixelformat
1052                                                                 == pixfmt)
1053                                 return modeU;
1054                 }
1055         }
1056         return -EINVAL;
1057 }
1058
1059 #ifdef CONFIG_VIDEO_ADV_DEBUG
1060 static int vidioc_g_register(struct file *file, void *priv,
1061                         struct v4l2_dbg_register *reg)
1062 {
1063         int ret;
1064         struct gspca_dev *gspca_dev = priv;
1065
1066         if (!gspca_dev->sd_desc->get_chip_ident)
1067                 return -EINVAL;
1068
1069         if (!gspca_dev->sd_desc->get_register)
1070                 return -EINVAL;
1071
1072         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1073                 return -ERESTARTSYS;
1074         gspca_dev->usb_err = 0;
1075         if (gspca_dev->present)
1076                 ret = gspca_dev->sd_desc->get_register(gspca_dev, reg);
1077         else
1078                 ret = -ENODEV;
1079         mutex_unlock(&gspca_dev->usb_lock);
1080
1081         return ret;
1082 }
1083
1084 static int vidioc_s_register(struct file *file, void *priv,
1085                         struct v4l2_dbg_register *reg)
1086 {
1087         int ret;
1088         struct gspca_dev *gspca_dev = priv;
1089
1090         if (!gspca_dev->sd_desc->get_chip_ident)
1091                 return -EINVAL;
1092
1093         if (!gspca_dev->sd_desc->set_register)
1094                 return -EINVAL;
1095
1096         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1097                 return -ERESTARTSYS;
1098         gspca_dev->usb_err = 0;
1099         if (gspca_dev->present)
1100                 ret = gspca_dev->sd_desc->set_register(gspca_dev, reg);
1101         else
1102                 ret = -ENODEV;
1103         mutex_unlock(&gspca_dev->usb_lock);
1104
1105         return ret;
1106 }
1107 #endif
1108
1109 static int vidioc_g_chip_ident(struct file *file, void *priv,
1110                         struct v4l2_dbg_chip_ident *chip)
1111 {
1112         int ret;
1113         struct gspca_dev *gspca_dev = priv;
1114
1115         if (!gspca_dev->sd_desc->get_chip_ident)
1116                 return -EINVAL;
1117
1118         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1119                 return -ERESTARTSYS;
1120         gspca_dev->usb_err = 0;
1121         if (gspca_dev->present)
1122                 ret = gspca_dev->sd_desc->get_chip_ident(gspca_dev, chip);
1123         else
1124                 ret = -ENODEV;
1125         mutex_unlock(&gspca_dev->usb_lock);
1126
1127         return ret;
1128 }
1129
1130 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1131                                 struct v4l2_fmtdesc *fmtdesc)
1132 {
1133         struct gspca_dev *gspca_dev = priv;
1134         int i, j, index;
1135         __u32 fmt_tb[8];
1136
1137         /* give an index to each format */
1138         index = 0;
1139         j = 0;
1140         for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
1141                 fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
1142                 j = 0;
1143                 for (;;) {
1144                         if (fmt_tb[j] == fmt_tb[index])
1145                                 break;
1146                         j++;
1147                 }
1148                 if (j == index) {
1149                         if (fmtdesc->index == index)
1150                                 break;          /* new format */
1151                         index++;
1152                         if (index >= ARRAY_SIZE(fmt_tb))
1153                                 return -EINVAL;
1154                 }
1155         }
1156         if (i < 0)
1157                 return -EINVAL;         /* no more format */
1158
1159         fmtdesc->pixelformat = fmt_tb[index];
1160         if (gspca_dev->cam.cam_mode[i].sizeimage <
1161                         gspca_dev->cam.cam_mode[i].width *
1162                                 gspca_dev->cam.cam_mode[i].height)
1163                 fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1164         fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
1165         fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
1166         fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
1167         fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
1168         fmtdesc->description[4] = '\0';
1169         return 0;
1170 }
1171
1172 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1173                             struct v4l2_format *fmt)
1174 {
1175         struct gspca_dev *gspca_dev = priv;
1176         int mode;
1177
1178         mode = gspca_dev->curr_mode;
1179         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
1180                 sizeof fmt->fmt.pix);
1181         return 0;
1182 }
1183
1184 static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
1185                         struct v4l2_format *fmt)
1186 {
1187         int w, h, mode, mode2;
1188
1189         w = fmt->fmt.pix.width;
1190         h = fmt->fmt.pix.height;
1191
1192 #ifdef GSPCA_DEBUG
1193         if (gspca_debug & D_CONF)
1194                 PDEBUG_MODE("try fmt cap", fmt->fmt.pix.pixelformat, w, h);
1195 #endif
1196         /* search the closest mode for width and height */
1197         mode = wxh_to_mode(gspca_dev, w, h);
1198
1199         /* OK if right palette */
1200         if (gspca_dev->cam.cam_mode[mode].pixelformat
1201                                                 != fmt->fmt.pix.pixelformat) {
1202
1203                 /* else, search the closest mode with the same pixel format */
1204                 mode2 = gspca_get_mode(gspca_dev, mode,
1205                                         fmt->fmt.pix.pixelformat);
1206                 if (mode2 >= 0)
1207                         mode = mode2;
1208 /*              else
1209                         ;                * no chance, return this mode */
1210         }
1211         memcpy(&fmt->fmt.pix, &gspca_dev->cam.cam_mode[mode],
1212                 sizeof fmt->fmt.pix);
1213         return mode;                    /* used when s_fmt */
1214 }
1215
1216 static int vidioc_try_fmt_vid_cap(struct file *file,
1217                               void *priv,
1218                               struct v4l2_format *fmt)
1219 {
1220         struct gspca_dev *gspca_dev = priv;
1221         int ret;
1222
1223         ret = try_fmt_vid_cap(gspca_dev, fmt);
1224         if (ret < 0)
1225                 return ret;
1226         return 0;
1227 }
1228
1229 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1230                             struct v4l2_format *fmt)
1231 {
1232         struct gspca_dev *gspca_dev = priv;
1233         int ret;
1234
1235         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1236                 return -ERESTARTSYS;
1237
1238         ret = try_fmt_vid_cap(gspca_dev, fmt);
1239         if (ret < 0)
1240                 goto out;
1241
1242         if (gspca_dev->nframes != 0
1243             && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
1244                 ret = -EINVAL;
1245                 goto out;
1246         }
1247
1248         if (ret == gspca_dev->curr_mode) {
1249                 ret = 0;
1250                 goto out;                       /* same mode */
1251         }
1252
1253         if (gspca_dev->streaming) {
1254                 ret = -EBUSY;
1255                 goto out;
1256         }
1257         gspca_dev->width = fmt->fmt.pix.width;
1258         gspca_dev->height = fmt->fmt.pix.height;
1259         gspca_dev->pixfmt = fmt->fmt.pix.pixelformat;
1260         gspca_dev->curr_mode = ret;
1261
1262         ret = 0;
1263 out:
1264         mutex_unlock(&gspca_dev->queue_lock);
1265         return ret;
1266 }
1267
1268 static int vidioc_enum_framesizes(struct file *file, void *priv,
1269                                   struct v4l2_frmsizeenum *fsize)
1270 {
1271         struct gspca_dev *gspca_dev = priv;
1272         int i;
1273         __u32 index = 0;
1274
1275         for (i = 0; i < gspca_dev->cam.nmodes; i++) {
1276                 if (fsize->pixel_format !=
1277                                 gspca_dev->cam.cam_mode[i].pixelformat)
1278                         continue;
1279
1280                 if (fsize->index == index) {
1281                         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1282                         fsize->discrete.width =
1283                                 gspca_dev->cam.cam_mode[i].width;
1284                         fsize->discrete.height =
1285                                 gspca_dev->cam.cam_mode[i].height;
1286                         return 0;
1287                 }
1288                 index++;
1289         }
1290
1291         return -EINVAL;
1292 }
1293
1294 static int vidioc_enum_frameintervals(struct file *filp, void *priv,
1295                                       struct v4l2_frmivalenum *fival)
1296 {
1297         struct gspca_dev *gspca_dev = priv;
1298         int mode = wxh_to_mode(gspca_dev, fival->width, fival->height);
1299         __u32 i;
1300
1301         if (gspca_dev->cam.mode_framerates == NULL ||
1302                         gspca_dev->cam.mode_framerates[mode].nrates == 0)
1303                 return -EINVAL;
1304
1305         if (fival->pixel_format !=
1306                         gspca_dev->cam.cam_mode[mode].pixelformat)
1307                 return -EINVAL;
1308
1309         for (i = 0; i < gspca_dev->cam.mode_framerates[mode].nrates; i++) {
1310                 if (fival->index == i) {
1311                         fival->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1312                         fival->discrete.numerator = 1;
1313                         fival->discrete.denominator =
1314                                 gspca_dev->cam.mode_framerates[mode].rates[i];
1315                         return 0;
1316                 }
1317         }
1318
1319         return -EINVAL;
1320 }
1321
1322 static void gspca_release(struct video_device *vfd)
1323 {
1324         struct gspca_dev *gspca_dev = container_of(vfd, struct gspca_dev, vdev);
1325
1326         PDEBUG(D_PROBE, "%s released",
1327                 video_device_node_name(&gspca_dev->vdev));
1328
1329         v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
1330         kfree(gspca_dev->usb_buf);
1331         kfree(gspca_dev);
1332 }
1333
1334 static int dev_open(struct file *file)
1335 {
1336         struct gspca_dev *gspca_dev;
1337
1338         PDEBUG(D_STREAM, "[%s] open", current->comm);
1339         gspca_dev = (struct gspca_dev *) video_devdata(file);
1340         if (!gspca_dev->present)
1341                 return -ENODEV;
1342
1343         /* protect the subdriver against rmmod */
1344         if (!try_module_get(gspca_dev->module))
1345                 return -ENODEV;
1346
1347         file->private_data = gspca_dev;
1348 #ifdef GSPCA_DEBUG
1349         /* activate the v4l2 debug */
1350         if (gspca_debug & D_V4L2)
1351                 gspca_dev->vdev.debug |= V4L2_DEBUG_IOCTL
1352                                         | V4L2_DEBUG_IOCTL_ARG;
1353         else
1354                 gspca_dev->vdev.debug &= ~(V4L2_DEBUG_IOCTL
1355                                         | V4L2_DEBUG_IOCTL_ARG);
1356 #endif
1357         return 0;
1358 }
1359
1360 static int dev_close(struct file *file)
1361 {
1362         struct gspca_dev *gspca_dev = file->private_data;
1363
1364         PDEBUG(D_STREAM, "[%s] close", current->comm);
1365         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1366                 return -ERESTARTSYS;
1367
1368         /* if the file did the capture, free the streaming resources */
1369         if (gspca_dev->capt_file == file) {
1370                 if (gspca_dev->streaming) {
1371                         mutex_lock(&gspca_dev->usb_lock);
1372                         gspca_dev->usb_err = 0;
1373                         gspca_stream_off(gspca_dev);
1374                         mutex_unlock(&gspca_dev->usb_lock);
1375                 }
1376                 frame_free(gspca_dev);
1377         }
1378         file->private_data = NULL;
1379         module_put(gspca_dev->module);
1380         mutex_unlock(&gspca_dev->queue_lock);
1381
1382         PDEBUG(D_STREAM, "close done");
1383
1384         return 0;
1385 }
1386
1387 static int vidioc_querycap(struct file *file, void  *priv,
1388                            struct v4l2_capability *cap)
1389 {
1390         struct gspca_dev *gspca_dev = priv;
1391         int ret;
1392
1393         /* protect the access to the usb device */
1394         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1395                 return -ERESTARTSYS;
1396         if (!gspca_dev->present) {
1397                 ret = -ENODEV;
1398                 goto out;
1399         }
1400         strlcpy((char *) cap->driver, gspca_dev->sd_desc->name,
1401                         sizeof cap->driver);
1402         if (gspca_dev->dev->product != NULL) {
1403                 strlcpy((char *) cap->card, gspca_dev->dev->product,
1404                         sizeof cap->card);
1405         } else {
1406                 snprintf((char *) cap->card, sizeof cap->card,
1407                         "USB Camera (%04x:%04x)",
1408                         le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
1409                         le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
1410         }
1411         usb_make_path(gspca_dev->dev, (char *) cap->bus_info,
1412                         sizeof(cap->bus_info));
1413         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
1414                           | V4L2_CAP_STREAMING
1415                           | V4L2_CAP_READWRITE;
1416         ret = 0;
1417 out:
1418         mutex_unlock(&gspca_dev->usb_lock);
1419         return ret;
1420 }
1421
1422 static int get_ctrl(struct gspca_dev *gspca_dev,
1423                                    int id)
1424 {
1425         const struct ctrl *ctrls;
1426         int i;
1427
1428         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1429              i < gspca_dev->sd_desc->nctrls;
1430              i++, ctrls++) {
1431                 if (gspca_dev->ctrl_dis & (1 << i))
1432                         continue;
1433                 if (id == ctrls->qctrl.id)
1434                         return i;
1435         }
1436         return -1;
1437 }
1438
1439 static int vidioc_queryctrl(struct file *file, void *priv,
1440                            struct v4l2_queryctrl *q_ctrl)
1441 {
1442         struct gspca_dev *gspca_dev = priv;
1443         const struct ctrl *ctrls;
1444         struct gspca_ctrl *gspca_ctrl;
1445         int i, idx;
1446         u32 id;
1447
1448         id = q_ctrl->id;
1449         if (id & V4L2_CTRL_FLAG_NEXT_CTRL) {
1450                 id &= V4L2_CTRL_ID_MASK;
1451                 id++;
1452                 idx = -1;
1453                 for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1454                         if (gspca_dev->ctrl_dis & (1 << i))
1455                                 continue;
1456                         if (gspca_dev->sd_desc->ctrls[i].qctrl.id < id)
1457                                 continue;
1458                         if (idx >= 0
1459                          && gspca_dev->sd_desc->ctrls[i].qctrl.id
1460                                     > gspca_dev->sd_desc->ctrls[idx].qctrl.id)
1461                                 continue;
1462                         idx = i;
1463                 }
1464         } else {
1465                 idx = get_ctrl(gspca_dev, id);
1466         }
1467         if (idx < 0)
1468                 return -EINVAL;
1469         ctrls = &gspca_dev->sd_desc->ctrls[idx];
1470         memcpy(q_ctrl, &ctrls->qctrl, sizeof *q_ctrl);
1471         if (gspca_dev->cam.ctrls != NULL) {
1472                 gspca_ctrl = &gspca_dev->cam.ctrls[idx];
1473                 q_ctrl->default_value = gspca_ctrl->def;
1474                 q_ctrl->minimum = gspca_ctrl->min;
1475                 q_ctrl->maximum = gspca_ctrl->max;
1476         }
1477         if (gspca_dev->ctrl_inac & (1 << idx))
1478                 q_ctrl->flags |= V4L2_CTRL_FLAG_INACTIVE;
1479         return 0;
1480 }
1481
1482 static int vidioc_s_ctrl(struct file *file, void *priv,
1483                          struct v4l2_control *ctrl)
1484 {
1485         struct gspca_dev *gspca_dev = priv;
1486         const struct ctrl *ctrls;
1487         struct gspca_ctrl *gspca_ctrl;
1488         int idx, ret;
1489
1490         idx = get_ctrl(gspca_dev, ctrl->id);
1491         if (idx < 0)
1492                 return -EINVAL;
1493         if (gspca_dev->ctrl_inac & (1 << idx))
1494                 return -EINVAL;
1495         ctrls = &gspca_dev->sd_desc->ctrls[idx];
1496         if (gspca_dev->cam.ctrls != NULL) {
1497                 gspca_ctrl = &gspca_dev->cam.ctrls[idx];
1498                 if (ctrl->value < gspca_ctrl->min
1499                     || ctrl->value > gspca_ctrl->max)
1500                         return -ERANGE;
1501         } else {
1502                 gspca_ctrl = NULL;
1503                 if (ctrl->value < ctrls->qctrl.minimum
1504                     || ctrl->value > ctrls->qctrl.maximum)
1505                         return -ERANGE;
1506         }
1507         PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
1508         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1509                 return -ERESTARTSYS;
1510         if (!gspca_dev->present) {
1511                 ret = -ENODEV;
1512                 goto out;
1513         }
1514         gspca_dev->usb_err = 0;
1515         if (ctrls->set != NULL) {
1516                 ret = ctrls->set(gspca_dev, ctrl->value);
1517                 goto out;
1518         }
1519         if (gspca_ctrl != NULL) {
1520                 gspca_ctrl->val = ctrl->value;
1521                 if (ctrls->set_control != NULL
1522                  && gspca_dev->streaming)
1523                         ctrls->set_control(gspca_dev);
1524         }
1525         ret = gspca_dev->usb_err;
1526 out:
1527         mutex_unlock(&gspca_dev->usb_lock);
1528         return ret;
1529 }
1530
1531 static int vidioc_g_ctrl(struct file *file, void *priv,
1532                          struct v4l2_control *ctrl)
1533 {
1534         struct gspca_dev *gspca_dev = priv;
1535         const struct ctrl *ctrls;
1536         int idx, ret;
1537
1538         idx = get_ctrl(gspca_dev, ctrl->id);
1539         if (idx < 0)
1540                 return -EINVAL;
1541         ctrls = &gspca_dev->sd_desc->ctrls[idx];
1542
1543         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1544                 return -ERESTARTSYS;
1545         if (!gspca_dev->present) {
1546                 ret = -ENODEV;
1547                 goto out;
1548         }
1549         gspca_dev->usb_err = 0;
1550         if (ctrls->get != NULL) {
1551                 ret = ctrls->get(gspca_dev, &ctrl->value);
1552                 goto out;
1553         }
1554         if (gspca_dev->cam.ctrls != NULL)
1555                 ctrl->value = gspca_dev->cam.ctrls[idx].val;
1556         ret = 0;
1557 out:
1558         mutex_unlock(&gspca_dev->usb_lock);
1559         return ret;
1560 }
1561
1562 static int vidioc_querymenu(struct file *file, void *priv,
1563                             struct v4l2_querymenu *qmenu)
1564 {
1565         struct gspca_dev *gspca_dev = priv;
1566
1567         if (!gspca_dev->sd_desc->querymenu)
1568                 return -EINVAL;
1569         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
1570 }
1571
1572 static int vidioc_enum_input(struct file *file, void *priv,
1573                                 struct v4l2_input *input)
1574 {
1575         struct gspca_dev *gspca_dev = priv;
1576
1577         if (input->index != 0)
1578                 return -EINVAL;
1579         input->type = V4L2_INPUT_TYPE_CAMERA;
1580         input->status = gspca_dev->cam.input_flags;
1581         strlcpy(input->name, gspca_dev->sd_desc->name,
1582                 sizeof input->name);
1583         return 0;
1584 }
1585
1586 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1587 {
1588         *i = 0;
1589         return 0;
1590 }
1591
1592 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1593 {
1594         if (i > 0)
1595                 return -EINVAL;
1596         return (0);
1597 }
1598
1599 static int vidioc_reqbufs(struct file *file, void *priv,
1600                           struct v4l2_requestbuffers *rb)
1601 {
1602         struct gspca_dev *gspca_dev = priv;
1603         int i, ret = 0, streaming;
1604
1605         i = rb->memory;                 /* (avoid compilation warning) */
1606         switch (i) {
1607         case GSPCA_MEMORY_READ:                 /* (internal call) */
1608         case V4L2_MEMORY_MMAP:
1609         case V4L2_MEMORY_USERPTR:
1610                 break;
1611         default:
1612                 return -EINVAL;
1613         }
1614         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1615                 return -ERESTARTSYS;
1616
1617         if (gspca_dev->memory != GSPCA_MEMORY_NO
1618             && gspca_dev->memory != GSPCA_MEMORY_READ
1619             && gspca_dev->memory != rb->memory) {
1620                 ret = -EBUSY;
1621                 goto out;
1622         }
1623
1624         /* only one file may do the capture */
1625         if (gspca_dev->capt_file != NULL
1626             && gspca_dev->capt_file != file) {
1627                 ret = -EBUSY;
1628                 goto out;
1629         }
1630
1631         /* if allocated, the buffers must not be mapped */
1632         for (i = 0; i < gspca_dev->nframes; i++) {
1633                 if (gspca_dev->frame[i].vma_use_count) {
1634                         ret = -EBUSY;
1635                         goto out;
1636                 }
1637         }
1638
1639         /* stop streaming */
1640         streaming = gspca_dev->streaming;
1641         if (streaming) {
1642                 mutex_lock(&gspca_dev->usb_lock);
1643                 gspca_dev->usb_err = 0;
1644                 gspca_stream_off(gspca_dev);
1645                 mutex_unlock(&gspca_dev->usb_lock);
1646
1647                 /* Don't restart the stream when switching from read
1648                  * to mmap mode */
1649                 if (gspca_dev->memory == GSPCA_MEMORY_READ)
1650                         streaming = 0;
1651         }
1652
1653         /* free the previous allocated buffers, if any */
1654         if (gspca_dev->nframes != 0)
1655                 frame_free(gspca_dev);
1656         if (rb->count == 0)                     /* unrequest */
1657                 goto out;
1658         ret = frame_alloc(gspca_dev, file, rb->memory, rb->count);
1659         if (ret == 0) {
1660                 rb->count = gspca_dev->nframes;
1661                 if (streaming)
1662                         ret = gspca_init_transfer(gspca_dev);
1663         }
1664 out:
1665         mutex_unlock(&gspca_dev->queue_lock);
1666         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1667         return ret;
1668 }
1669
1670 static int vidioc_querybuf(struct file *file, void *priv,
1671                            struct v4l2_buffer *v4l2_buf)
1672 {
1673         struct gspca_dev *gspca_dev = priv;
1674         struct gspca_frame *frame;
1675
1676         if (v4l2_buf->index < 0
1677             || v4l2_buf->index >= gspca_dev->nframes)
1678                 return -EINVAL;
1679
1680         frame = &gspca_dev->frame[v4l2_buf->index];
1681         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1682         return 0;
1683 }
1684
1685 static int vidioc_streamon(struct file *file, void *priv,
1686                            enum v4l2_buf_type buf_type)
1687 {
1688         struct gspca_dev *gspca_dev = priv;
1689         int ret;
1690
1691         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1692                 return -EINVAL;
1693         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1694                 return -ERESTARTSYS;
1695
1696         /* check the capture file */
1697         if (gspca_dev->capt_file != file) {
1698                 ret = -EBUSY;
1699                 goto out;
1700         }
1701
1702         if (gspca_dev->nframes == 0
1703             || !(gspca_dev->frame[0].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)) {
1704                 ret = -EINVAL;
1705                 goto out;
1706         }
1707         if (!gspca_dev->streaming) {
1708                 ret = gspca_init_transfer(gspca_dev);
1709                 if (ret < 0)
1710                         goto out;
1711         }
1712 #ifdef GSPCA_DEBUG
1713         if (gspca_debug & D_STREAM) {
1714                 PDEBUG_MODE("stream on OK",
1715                         gspca_dev->pixfmt,
1716                         gspca_dev->width,
1717                         gspca_dev->height);
1718         }
1719 #endif
1720         ret = 0;
1721 out:
1722         mutex_unlock(&gspca_dev->queue_lock);
1723         return ret;
1724 }
1725
1726 static int vidioc_streamoff(struct file *file, void *priv,
1727                                 enum v4l2_buf_type buf_type)
1728 {
1729         struct gspca_dev *gspca_dev = priv;
1730         int ret;
1731
1732         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1733                 return -EINVAL;
1734
1735         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1736                 return -ERESTARTSYS;
1737
1738         if (!gspca_dev->streaming) {
1739                 ret = 0;
1740                 goto out;
1741         }
1742
1743         /* check the capture file */
1744         if (gspca_dev->capt_file != file) {
1745                 ret = -EBUSY;
1746                 goto out;
1747         }
1748
1749         /* stop streaming */
1750         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1751                 ret = -ERESTARTSYS;
1752                 goto out;
1753         }
1754         gspca_dev->usb_err = 0;
1755         gspca_stream_off(gspca_dev);
1756         mutex_unlock(&gspca_dev->usb_lock);
1757         /* In case another thread is waiting in dqbuf */
1758         wake_up_interruptible(&gspca_dev->wq);
1759
1760         /* empty the transfer queues */
1761         atomic_set(&gspca_dev->fr_q, 0);
1762         atomic_set(&gspca_dev->fr_i, 0);
1763         gspca_dev->fr_o = 0;
1764         ret = 0;
1765 out:
1766         mutex_unlock(&gspca_dev->queue_lock);
1767         return ret;
1768 }
1769
1770 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1771                         struct v4l2_jpegcompression *jpegcomp)
1772 {
1773         struct gspca_dev *gspca_dev = priv;
1774         int ret;
1775
1776         if (!gspca_dev->sd_desc->get_jcomp)
1777                 return -EINVAL;
1778         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1779                 return -ERESTARTSYS;
1780         gspca_dev->usb_err = 0;
1781         if (gspca_dev->present)
1782                 ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1783         else
1784                 ret = -ENODEV;
1785         mutex_unlock(&gspca_dev->usb_lock);
1786         return ret;
1787 }
1788
1789 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1790                         struct v4l2_jpegcompression *jpegcomp)
1791 {
1792         struct gspca_dev *gspca_dev = priv;
1793         int ret;
1794
1795         if (!gspca_dev->sd_desc->set_jcomp)
1796                 return -EINVAL;
1797         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1798                 return -ERESTARTSYS;
1799         gspca_dev->usb_err = 0;
1800         if (gspca_dev->present)
1801                 ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1802         else
1803                 ret = -ENODEV;
1804         mutex_unlock(&gspca_dev->usb_lock);
1805         return ret;
1806 }
1807
1808 static int vidioc_g_parm(struct file *filp, void *priv,
1809                         struct v4l2_streamparm *parm)
1810 {
1811         struct gspca_dev *gspca_dev = priv;
1812
1813         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1814
1815         if (gspca_dev->sd_desc->get_streamparm) {
1816                 int ret;
1817
1818                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1819                         return -ERESTARTSYS;
1820                 if (gspca_dev->present) {
1821                         gspca_dev->usb_err = 0;
1822                         gspca_dev->sd_desc->get_streamparm(gspca_dev, parm);
1823                         ret = gspca_dev->usb_err;
1824                 } else {
1825                         ret = -ENODEV;
1826                 }
1827                 mutex_unlock(&gspca_dev->usb_lock);
1828                 return ret;
1829         }
1830
1831         return 0;
1832 }
1833
1834 static int vidioc_s_parm(struct file *filp, void *priv,
1835                         struct v4l2_streamparm *parm)
1836 {
1837         struct gspca_dev *gspca_dev = priv;
1838         int n;
1839
1840         n = parm->parm.capture.readbuffers;
1841         if (n == 0 || n >= GSPCA_MAX_FRAMES)
1842                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1843         else
1844                 gspca_dev->nbufread = n;
1845
1846         if (gspca_dev->sd_desc->set_streamparm) {
1847                 int ret;
1848
1849                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1850                         return -ERESTARTSYS;
1851                 if (gspca_dev->present) {
1852                         gspca_dev->usb_err = 0;
1853                         gspca_dev->sd_desc->set_streamparm(gspca_dev, parm);
1854                         ret = gspca_dev->usb_err;
1855                 } else {
1856                         ret = -ENODEV;
1857                 }
1858                 mutex_unlock(&gspca_dev->usb_lock);
1859                 return ret;
1860         }
1861
1862         return 0;
1863 }
1864
1865 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1866 {
1867         struct gspca_dev *gspca_dev = file->private_data;
1868         struct gspca_frame *frame;
1869         struct page *page;
1870         unsigned long addr, start, size;
1871         int i, ret;
1872
1873         start = vma->vm_start;
1874         size = vma->vm_end - vma->vm_start;
1875         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1876
1877         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1878                 return -ERESTARTSYS;
1879         if (!gspca_dev->present) {
1880                 ret = -ENODEV;
1881                 goto out;
1882         }
1883         if (gspca_dev->capt_file != file) {
1884                 ret = -EINVAL;
1885                 goto out;
1886         }
1887
1888         frame = NULL;
1889         for (i = 0; i < gspca_dev->nframes; ++i) {
1890                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1891                         PDEBUG(D_STREAM, "mmap bad memory type");
1892                         break;
1893                 }
1894                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1895                                                 == vma->vm_pgoff) {
1896                         frame = &gspca_dev->frame[i];
1897                         break;
1898                 }
1899         }
1900         if (frame == NULL) {
1901                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1902                 ret = -EINVAL;
1903                 goto out;
1904         }
1905         if (size != frame->v4l2_buf.length) {
1906                 PDEBUG(D_STREAM, "mmap bad size");
1907                 ret = -EINVAL;
1908                 goto out;
1909         }
1910
1911         /*
1912          * - VM_IO marks the area as being a mmaped region for I/O to a
1913          *   device. It also prevents the region from being core dumped.
1914          */
1915         vma->vm_flags |= VM_IO;
1916
1917         addr = (unsigned long) frame->data;
1918         while (size > 0) {
1919                 page = vmalloc_to_page((void *) addr);
1920                 ret = vm_insert_page(vma, start, page);
1921                 if (ret < 0)
1922                         goto out;
1923                 start += PAGE_SIZE;
1924                 addr += PAGE_SIZE;
1925                 size -= PAGE_SIZE;
1926         }
1927
1928         vma->vm_ops = &gspca_vm_ops;
1929         vma->vm_private_data = frame;
1930         gspca_vm_open(vma);
1931         ret = 0;
1932 out:
1933         mutex_unlock(&gspca_dev->queue_lock);
1934         return ret;
1935 }
1936
1937 static int frame_ready_nolock(struct gspca_dev *gspca_dev, struct file *file,
1938                                 enum v4l2_memory memory)
1939 {
1940         if (!gspca_dev->present)
1941                 return -ENODEV;
1942         if (gspca_dev->capt_file != file || gspca_dev->memory != memory ||
1943                         !gspca_dev->streaming)
1944                 return -EINVAL;
1945
1946         /* check if a frame is ready */
1947         return gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i);
1948 }
1949
1950 static int frame_ready(struct gspca_dev *gspca_dev, struct file *file,
1951                         enum v4l2_memory memory)
1952 {
1953         int ret;
1954
1955         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1956                 return -ERESTARTSYS;
1957         ret = frame_ready_nolock(gspca_dev, file, memory);
1958         mutex_unlock(&gspca_dev->queue_lock);
1959         return ret;
1960 }
1961
1962 /*
1963  * dequeue a video buffer
1964  *
1965  * If nonblock_ing is false, block until a buffer is available.
1966  */
1967 static int vidioc_dqbuf(struct file *file, void *priv,
1968                         struct v4l2_buffer *v4l2_buf)
1969 {
1970         struct gspca_dev *gspca_dev = priv;
1971         struct gspca_frame *frame;
1972         int i, j, ret;
1973
1974         PDEBUG(D_FRAM, "dqbuf");
1975
1976         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1977                 return -ERESTARTSYS;
1978
1979         for (;;) {
1980                 ret = frame_ready_nolock(gspca_dev, file, v4l2_buf->memory);
1981                 if (ret < 0)
1982                         goto out;
1983                 if (ret > 0)
1984                         break;
1985
1986                 mutex_unlock(&gspca_dev->queue_lock);
1987
1988                 if (file->f_flags & O_NONBLOCK)
1989                         return -EAGAIN;
1990
1991                 /* wait till a frame is ready */
1992                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1993                         frame_ready(gspca_dev, file, v4l2_buf->memory),
1994                         msecs_to_jiffies(3000));
1995                 if (ret < 0)
1996                         return ret;
1997                 if (ret == 0)
1998                         return -EIO;
1999
2000                 if (mutex_lock_interruptible(&gspca_dev->queue_lock))
2001                         return -ERESTARTSYS;
2002         }
2003
2004         i = gspca_dev->fr_o;
2005         j = gspca_dev->fr_queue[i];
2006         frame = &gspca_dev->frame[j];
2007
2008         gspca_dev->fr_o = (i + 1) % GSPCA_MAX_FRAMES;
2009
2010         if (gspca_dev->sd_desc->dq_callback) {
2011                 mutex_lock(&gspca_dev->usb_lock);
2012                 gspca_dev->usb_err = 0;
2013                 if (gspca_dev->present)
2014                         gspca_dev->sd_desc->dq_callback(gspca_dev);
2015                 mutex_unlock(&gspca_dev->usb_lock);
2016         }
2017
2018         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
2019         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
2020         PDEBUG(D_FRAM, "dqbuf %d", j);
2021         ret = 0;
2022
2023         if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
2024                 if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
2025                                  frame->data,
2026                                  frame->v4l2_buf.bytesused)) {
2027                         PDEBUG(D_ERR|D_STREAM,
2028                                 "dqbuf cp to user failed");
2029                         ret = -EFAULT;
2030                 }
2031         }
2032 out:
2033         mutex_unlock(&gspca_dev->queue_lock);
2034         return ret;
2035 }
2036
2037 /*
2038  * queue a video buffer
2039  *
2040  * Attempting to queue a buffer that has already been
2041  * queued will return -EINVAL.
2042  */
2043 static int vidioc_qbuf(struct file *file, void *priv,
2044                         struct v4l2_buffer *v4l2_buf)
2045 {
2046         struct gspca_dev *gspca_dev = priv;
2047         struct gspca_frame *frame;
2048         int i, index, ret;
2049
2050         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
2051
2052         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
2053                 return -ERESTARTSYS;
2054
2055         index = v4l2_buf->index;
2056         if ((unsigned) index >= gspca_dev->nframes) {
2057                 PDEBUG(D_FRAM,
2058                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
2059                 ret = -EINVAL;
2060                 goto out;
2061         }
2062         if (v4l2_buf->memory != gspca_dev->memory) {
2063                 PDEBUG(D_FRAM, "qbuf bad memory type");
2064                 ret = -EINVAL;
2065                 goto out;
2066         }
2067
2068         frame = &gspca_dev->frame[index];
2069         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
2070                 PDEBUG(D_FRAM, "qbuf bad state");
2071                 ret = -EINVAL;
2072                 goto out;
2073         }
2074
2075         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
2076
2077         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
2078                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
2079                 frame->v4l2_buf.length = v4l2_buf->length;
2080         }
2081
2082         /* put the buffer in the 'queued' queue */
2083         i = atomic_read(&gspca_dev->fr_q);
2084         gspca_dev->fr_queue[i] = index;
2085         atomic_set(&gspca_dev->fr_q, (i + 1) % GSPCA_MAX_FRAMES);
2086
2087         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
2088         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
2089         ret = 0;
2090 out:
2091         mutex_unlock(&gspca_dev->queue_lock);
2092         return ret;
2093 }
2094
2095 /*
2096  * allocate the resources for read()
2097  */
2098 static int read_alloc(struct gspca_dev *gspca_dev,
2099                         struct file *file)
2100 {
2101         struct v4l2_buffer v4l2_buf;
2102         int i, ret;
2103
2104         PDEBUG(D_STREAM, "read alloc");
2105         if (gspca_dev->nframes == 0) {
2106                 struct v4l2_requestbuffers rb;
2107
2108                 memset(&rb, 0, sizeof rb);
2109                 rb.count = gspca_dev->nbufread;
2110                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2111                 rb.memory = GSPCA_MEMORY_READ;
2112                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
2113                 if (ret != 0) {
2114                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
2115                         return ret;
2116                 }
2117                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
2118                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2119                 v4l2_buf.memory = GSPCA_MEMORY_READ;
2120                 for (i = 0; i < gspca_dev->nbufread; i++) {
2121                         v4l2_buf.index = i;
2122                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2123                         if (ret != 0) {
2124                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
2125                                 return ret;
2126                         }
2127                 }
2128                 gspca_dev->memory = GSPCA_MEMORY_READ;
2129         }
2130
2131         /* start streaming */
2132         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
2133         if (ret != 0)
2134                 PDEBUG(D_STREAM, "read streamon err %d", ret);
2135         return ret;
2136 }
2137
2138 static unsigned int dev_poll(struct file *file, poll_table *wait)
2139 {
2140         struct gspca_dev *gspca_dev = file->private_data;
2141         int ret;
2142
2143         PDEBUG(D_FRAM, "poll");
2144
2145         poll_wait(file, &gspca_dev->wq, wait);
2146
2147         /* if reqbufs is not done, the user would use read() */
2148         if (gspca_dev->memory == GSPCA_MEMORY_NO) {
2149                 ret = read_alloc(gspca_dev, file);
2150                 if (ret != 0)
2151                         return POLLERR;
2152         }
2153
2154         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
2155                 return POLLERR;
2156
2157         /* check if an image has been received */
2158         if (gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i))
2159                 ret = POLLIN | POLLRDNORM;      /* yes */
2160         else
2161                 ret = 0;
2162         mutex_unlock(&gspca_dev->queue_lock);
2163         if (!gspca_dev->present)
2164                 return POLLHUP;
2165         return ret;
2166 }
2167
2168 static ssize_t dev_read(struct file *file, char __user *data,
2169                     size_t count, loff_t *ppos)
2170 {
2171         struct gspca_dev *gspca_dev = file->private_data;
2172         struct gspca_frame *frame;
2173         struct v4l2_buffer v4l2_buf;
2174         struct timeval timestamp;
2175         int n, ret, ret2;
2176
2177         PDEBUG(D_FRAM, "read (%zd)", count);
2178         if (!gspca_dev->present)
2179                 return -ENODEV;
2180         if (gspca_dev->memory == GSPCA_MEMORY_NO) { /* first time ? */
2181                 ret = read_alloc(gspca_dev, file);
2182                 if (ret != 0)
2183                         return ret;
2184         }
2185
2186         /* get a frame */
2187         timestamp = ktime_to_timeval(ktime_get());
2188         timestamp.tv_sec--;
2189         n = 2;
2190         for (;;) {
2191                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
2192                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2193                 v4l2_buf.memory = GSPCA_MEMORY_READ;
2194                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
2195                 if (ret != 0) {
2196                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
2197                         return ret;
2198                 }
2199
2200                 /* if the process slept for more than 1 second,
2201                  * get a newer frame */
2202                 frame = &gspca_dev->frame[v4l2_buf.index];
2203                 if (--n < 0)
2204                         break;                  /* avoid infinite loop */
2205                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
2206                         break;
2207                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2208                 if (ret != 0) {
2209                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
2210                         return ret;
2211                 }
2212         }
2213
2214         /* copy the frame */
2215         if (count > frame->v4l2_buf.bytesused)
2216                 count = frame->v4l2_buf.bytesused;
2217         ret = copy_to_user(data, frame->data, count);
2218         if (ret != 0) {
2219                 PDEBUG(D_ERR|D_STREAM,
2220                         "read cp to user lack %d / %zd", ret, count);
2221                 ret = -EFAULT;
2222                 goto out;
2223         }
2224         ret = count;
2225 out:
2226         /* in each case, requeue the buffer */
2227         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2228         if (ret2 != 0)
2229                 return ret2;
2230         return ret;
2231 }
2232
2233 static struct v4l2_file_operations dev_fops = {
2234         .owner = THIS_MODULE,
2235         .open = dev_open,
2236         .release = dev_close,
2237         .read = dev_read,
2238         .mmap = dev_mmap,
2239         .unlocked_ioctl = video_ioctl2,
2240         .poll   = dev_poll,
2241 };
2242
2243 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
2244         .vidioc_querycap        = vidioc_querycap,
2245         .vidioc_dqbuf           = vidioc_dqbuf,
2246         .vidioc_qbuf            = vidioc_qbuf,
2247         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
2248         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
2249         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
2250         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
2251         .vidioc_streamon        = vidioc_streamon,
2252         .vidioc_queryctrl       = vidioc_queryctrl,
2253         .vidioc_g_ctrl          = vidioc_g_ctrl,
2254         .vidioc_s_ctrl          = vidioc_s_ctrl,
2255         .vidioc_querymenu       = vidioc_querymenu,
2256         .vidioc_enum_input      = vidioc_enum_input,
2257         .vidioc_g_input         = vidioc_g_input,
2258         .vidioc_s_input         = vidioc_s_input,
2259         .vidioc_reqbufs         = vidioc_reqbufs,
2260         .vidioc_querybuf        = vidioc_querybuf,
2261         .vidioc_streamoff       = vidioc_streamoff,
2262         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
2263         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
2264         .vidioc_g_parm          = vidioc_g_parm,
2265         .vidioc_s_parm          = vidioc_s_parm,
2266         .vidioc_enum_framesizes = vidioc_enum_framesizes,
2267         .vidioc_enum_frameintervals = vidioc_enum_frameintervals,
2268 #ifdef CONFIG_VIDEO_ADV_DEBUG
2269         .vidioc_g_register      = vidioc_g_register,
2270         .vidioc_s_register      = vidioc_s_register,
2271 #endif
2272         .vidioc_g_chip_ident    = vidioc_g_chip_ident,
2273 };
2274
2275 static const struct video_device gspca_template = {
2276         .name = "gspca main driver",
2277         .fops = &dev_fops,
2278         .ioctl_ops = &dev_ioctl_ops,
2279         .release = gspca_release,
2280 };
2281
2282 /* initialize the controls */
2283 static void ctrls_init(struct gspca_dev *gspca_dev)
2284 {
2285         struct gspca_ctrl *ctrl;
2286         int i;
2287
2288         for (i = 0, ctrl = gspca_dev->cam.ctrls;
2289              i < gspca_dev->sd_desc->nctrls;
2290              i++, ctrl++) {
2291                 ctrl->def = gspca_dev->sd_desc->ctrls[i].qctrl.default_value;
2292                 ctrl->val = ctrl->def;
2293                 ctrl->min = gspca_dev->sd_desc->ctrls[i].qctrl.minimum;
2294                 ctrl->max = gspca_dev->sd_desc->ctrls[i].qctrl.maximum;
2295         }
2296 }
2297
2298 /*
2299  * probe and create a new gspca device
2300  *
2301  * This function must be called by the sub-driver when it is
2302  * called for probing a new device.
2303  */
2304 int gspca_dev_probe2(struct usb_interface *intf,
2305                 const struct usb_device_id *id,
2306                 const struct sd_desc *sd_desc,
2307                 int dev_size,
2308                 struct module *module)
2309 {
2310         struct gspca_dev *gspca_dev;
2311         struct usb_device *dev = interface_to_usbdev(intf);
2312         int ret;
2313
2314         pr_info("%s-" GSPCA_VERSION " probing %04x:%04x\n",
2315                 sd_desc->name, id->idVendor, id->idProduct);
2316
2317         /* create the device */
2318         if (dev_size < sizeof *gspca_dev)
2319                 dev_size = sizeof *gspca_dev;
2320         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
2321         if (!gspca_dev) {
2322                 pr_err("couldn't kzalloc gspca struct\n");
2323                 return -ENOMEM;
2324         }
2325         gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
2326         if (!gspca_dev->usb_buf) {
2327                 pr_err("out of memory\n");
2328                 ret = -ENOMEM;
2329                 goto out;
2330         }
2331         gspca_dev->dev = dev;
2332         gspca_dev->iface = intf->cur_altsetting->desc.bInterfaceNumber;
2333
2334         /* check if any audio device */
2335         if (dev->actconfig->desc.bNumInterfaces != 1) {
2336                 int i;
2337                 struct usb_interface *intf2;
2338
2339                 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
2340                         intf2 = dev->actconfig->interface[i];
2341                         if (intf2 != NULL
2342                          && intf2->altsetting != NULL
2343                          && intf2->altsetting->desc.bInterfaceClass ==
2344                                          USB_CLASS_AUDIO) {
2345                                 gspca_dev->audio = 1;
2346                                 break;
2347                         }
2348                 }
2349         }
2350
2351         gspca_dev->sd_desc = sd_desc;
2352         gspca_dev->nbufread = 2;
2353         gspca_dev->empty_packet = -1;   /* don't check the empty packets */
2354         gspca_dev->vdev = gspca_template;
2355         gspca_dev->vdev.parent = &intf->dev;
2356         gspca_dev->module = module;
2357         gspca_dev->present = 1;
2358
2359         mutex_init(&gspca_dev->usb_lock);
2360         mutex_init(&gspca_dev->queue_lock);
2361         init_waitqueue_head(&gspca_dev->wq);
2362
2363         /* configure the subdriver and initialize the USB device */
2364         ret = sd_desc->config(gspca_dev, id);
2365         if (ret < 0)
2366                 goto out;
2367         if (gspca_dev->cam.ctrls != NULL)
2368                 ctrls_init(gspca_dev);
2369         ret = sd_desc->init(gspca_dev);
2370         if (ret < 0)
2371                 goto out;
2372         if (sd_desc->init_controls)
2373                 ret = sd_desc->init_controls(gspca_dev);
2374         if (ret < 0)
2375                 goto out;
2376         gspca_set_default_mode(gspca_dev);
2377
2378         ret = gspca_input_connect(gspca_dev);
2379         if (ret)
2380                 goto out;
2381
2382         /* init video stuff */
2383         ret = video_register_device(&gspca_dev->vdev,
2384                                   VFL_TYPE_GRABBER,
2385                                   -1);
2386         if (ret < 0) {
2387                 pr_err("video_register_device err %d\n", ret);
2388                 goto out;
2389         }
2390
2391         usb_set_intfdata(intf, gspca_dev);
2392         PDEBUG(D_PROBE, "%s created", video_device_node_name(&gspca_dev->vdev));
2393
2394         gspca_input_create_urb(gspca_dev);
2395
2396         return 0;
2397 out:
2398 #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
2399         if (gspca_dev->input_dev)
2400                 input_unregister_device(gspca_dev->input_dev);
2401 #endif
2402         v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
2403         kfree(gspca_dev->usb_buf);
2404         kfree(gspca_dev);
2405         return ret;
2406 }
2407 EXPORT_SYMBOL(gspca_dev_probe2);
2408
2409 /* same function as the previous one, but check the interface */
2410 int gspca_dev_probe(struct usb_interface *intf,
2411                 const struct usb_device_id *id,
2412                 const struct sd_desc *sd_desc,
2413                 int dev_size,
2414                 struct module *module)
2415 {
2416         struct usb_device *dev = interface_to_usbdev(intf);
2417
2418         /* we don't handle multi-config cameras */
2419         if (dev->descriptor.bNumConfigurations != 1) {
2420                 pr_err("%04x:%04x too many config\n",
2421                        id->idVendor, id->idProduct);
2422                 return -ENODEV;
2423         }
2424
2425         /* the USB video interface must be the first one */
2426         if (dev->actconfig->desc.bNumInterfaces != 1
2427          && intf->cur_altsetting->desc.bInterfaceNumber != 0)
2428                 return -ENODEV;
2429
2430         return gspca_dev_probe2(intf, id, sd_desc, dev_size, module);
2431 }
2432 EXPORT_SYMBOL(gspca_dev_probe);
2433
2434 /*
2435  * USB disconnection
2436  *
2437  * This function must be called by the sub-driver
2438  * when the device disconnects, after the specific resources are freed.
2439  */
2440 void gspca_disconnect(struct usb_interface *intf)
2441 {
2442         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2443 #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
2444         struct input_dev *input_dev;
2445 #endif
2446
2447         PDEBUG(D_PROBE, "%s disconnect",
2448                 video_device_node_name(&gspca_dev->vdev));
2449         mutex_lock(&gspca_dev->usb_lock);
2450
2451         gspca_dev->present = 0;
2452         wake_up_interruptible(&gspca_dev->wq);
2453
2454         destroy_urbs(gspca_dev);
2455
2456 #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
2457         gspca_input_destroy_urb(gspca_dev);
2458         input_dev = gspca_dev->input_dev;
2459         if (input_dev) {
2460                 gspca_dev->input_dev = NULL;
2461                 input_unregister_device(input_dev);
2462         }
2463 #endif
2464
2465         /* the device is freed at exit of this function */
2466         gspca_dev->dev = NULL;
2467         mutex_unlock(&gspca_dev->usb_lock);
2468
2469         usb_set_intfdata(intf, NULL);
2470
2471         /* release the device */
2472         /* (this will call gspca_release() immediately or on last close) */
2473         video_unregister_device(&gspca_dev->vdev);
2474
2475 /*      PDEBUG(D_PROBE, "disconnect complete"); */
2476 }
2477 EXPORT_SYMBOL(gspca_disconnect);
2478
2479 #ifdef CONFIG_PM
2480 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
2481 {
2482         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2483
2484         if (!gspca_dev->streaming)
2485                 return 0;
2486         gspca_dev->frozen = 1;          /* avoid urb error messages */
2487         if (gspca_dev->sd_desc->stopN)
2488                 gspca_dev->sd_desc->stopN(gspca_dev);
2489         destroy_urbs(gspca_dev);
2490         gspca_input_destroy_urb(gspca_dev);
2491         gspca_set_alt0(gspca_dev);
2492         if (gspca_dev->sd_desc->stop0)
2493                 gspca_dev->sd_desc->stop0(gspca_dev);
2494         return 0;
2495 }
2496 EXPORT_SYMBOL(gspca_suspend);
2497
2498 int gspca_resume(struct usb_interface *intf)
2499 {
2500         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2501         int streaming;
2502
2503         gspca_dev->frozen = 0;
2504         gspca_dev->sd_desc->init(gspca_dev);
2505         gspca_input_create_urb(gspca_dev);
2506         /*
2507          * Most subdrivers send all ctrl values on sd_start and thus
2508          * only write to the device registers on s_ctrl when streaming ->
2509          * Clear streaming to avoid setting all ctrls twice.
2510          */
2511         streaming = gspca_dev->streaming;
2512         gspca_dev->streaming = 0;
2513         v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
2514         if (streaming)
2515                 return gspca_init_transfer(gspca_dev);
2516         return 0;
2517 }
2518 EXPORT_SYMBOL(gspca_resume);
2519 #endif
2520 /* -- cam driver utility functions -- */
2521
2522 /* auto gain and exposure algorithm based on the knee algorithm described here:
2523    http://ytse.tricolour.net/docs/LowLightOptimization.html
2524
2525    Returns 0 if no changes were made, 1 if the gain and or exposure settings
2526    where changed. */
2527 int gspca_auto_gain_n_exposure(struct gspca_dev *gspca_dev, int avg_lum,
2528         int desired_avg_lum, int deadzone, int gain_knee, int exposure_knee)
2529 {
2530         int i, steps, gain, orig_gain, exposure, orig_exposure, autogain;
2531         const struct ctrl *gain_ctrl = NULL;
2532         const struct ctrl *exposure_ctrl = NULL;
2533         const struct ctrl *autogain_ctrl = NULL;
2534         int retval = 0;
2535
2536         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
2537                 if (gspca_dev->ctrl_dis & (1 << i))
2538                         continue;
2539                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_GAIN)
2540                         gain_ctrl = &gspca_dev->sd_desc->ctrls[i];
2541                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_EXPOSURE)
2542                         exposure_ctrl = &gspca_dev->sd_desc->ctrls[i];
2543                 if (gspca_dev->sd_desc->ctrls[i].qctrl.id == V4L2_CID_AUTOGAIN)
2544                         autogain_ctrl = &gspca_dev->sd_desc->ctrls[i];
2545         }
2546         if (!gain_ctrl || !exposure_ctrl || !autogain_ctrl) {
2547                 PDEBUG(D_ERR, "Error: gspca_auto_gain_n_exposure called "
2548                         "on cam without (auto)gain/exposure");
2549                 return 0;
2550         }
2551
2552         if (gain_ctrl->get(gspca_dev, &gain) ||
2553                         exposure_ctrl->get(gspca_dev, &exposure) ||
2554                         autogain_ctrl->get(gspca_dev, &autogain) || !autogain)
2555                 return 0;
2556
2557         orig_gain = gain;
2558         orig_exposure = exposure;
2559
2560         /* If we are of a multiple of deadzone, do multiple steps to reach the
2561            desired lumination fast (with the risc of a slight overshoot) */
2562         steps = abs(desired_avg_lum - avg_lum) / deadzone;
2563
2564         PDEBUG(D_FRAM, "autogain: lum: %d, desired: %d, steps: %d",
2565                 avg_lum, desired_avg_lum, steps);
2566
2567         for (i = 0; i < steps; i++) {
2568                 if (avg_lum > desired_avg_lum) {
2569                         if (gain > gain_knee)
2570                                 gain--;
2571                         else if (exposure > exposure_knee)
2572                                 exposure--;
2573                         else if (gain > gain_ctrl->qctrl.default_value)
2574                                 gain--;
2575                         else if (exposure > exposure_ctrl->qctrl.minimum)
2576                                 exposure--;
2577                         else if (gain > gain_ctrl->qctrl.minimum)
2578                                 gain--;
2579                         else
2580                                 break;
2581                 } else {
2582                         if (gain < gain_ctrl->qctrl.default_value)
2583                                 gain++;
2584                         else if (exposure < exposure_knee)
2585                                 exposure++;
2586                         else if (gain < gain_knee)
2587                                 gain++;
2588                         else if (exposure < exposure_ctrl->qctrl.maximum)
2589                                 exposure++;
2590                         else if (gain < gain_ctrl->qctrl.maximum)
2591                                 gain++;
2592                         else
2593                                 break;
2594                 }
2595         }
2596
2597         if (gain != orig_gain) {
2598                 gain_ctrl->set(gspca_dev, gain);
2599                 retval = 1;
2600         }
2601         if (exposure != orig_exposure) {
2602                 exposure_ctrl->set(gspca_dev, exposure);
2603                 retval = 1;
2604         }
2605
2606         return retval;
2607 }
2608 EXPORT_SYMBOL(gspca_auto_gain_n_exposure);
2609
2610 /* -- module insert / remove -- */
2611 static int __init gspca_init(void)
2612 {
2613         pr_info("v" GSPCA_VERSION " registered\n");
2614         return 0;
2615 }
2616 static void __exit gspca_exit(void)
2617 {
2618 }
2619
2620 module_init(gspca_init);
2621 module_exit(gspca_exit);
2622
2623 #ifdef GSPCA_DEBUG
2624 module_param_named(debug, gspca_debug, int, 0644);
2625 MODULE_PARM_DESC(debug,
2626                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
2627                 " 0x08:stream 0x10:frame 0x20:packet"
2628                 " 0x0100: v4l2");
2629 #endif