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