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