V4L/DVB (8156): Many bug fixes, zc3xx added.
[linux-2.6] / drivers / media / video / gspca / gspca.c
1 /*
2  * Main USB camera driver
3  *
4  * V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #define MODULE_NAME "gspca"
22
23 #include <linux/init.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/sched.h>
27 #include <linux/slab.h>
28 #include <linux/mm.h>
29 #include <linux/string.h>
30 #include <linux/pagemap.h>
31 #include <asm/io.h>
32 #include <asm/page.h>
33 #include <asm/uaccess.h>
34 #include <linux/jiffies.h>
35
36 #include "gspca.h"
37
38 /* option */
39 #define GSPCA_HLP 0
40
41 /* global values */
42 #define DEF_NURBS 2             /* default number of URBs (mmap) */
43
44 MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>");
45 MODULE_DESCRIPTION("GSPCA USB Camera Driver");
46 MODULE_LICENSE("GPL");
47
48 #define DRIVER_VERSION_NUMBER   KERNEL_VERSION(0, 2, 15)
49 static const char version[] = "0.2.15";
50
51 static int video_nr = -1;
52
53 static int comp_fac = 30;       /* Buffer size ratio when compressed in % */
54
55 #ifdef GSPCA_DEBUG
56 int gspca_debug = D_ERR | D_PROBE;
57 EXPORT_SYMBOL(gspca_debug);
58
59 static void PDEBUG_MODE(char *txt, __u32 pixfmt, int w, int h)
60 {
61         if ((pixfmt >> 24) >= '0' && (pixfmt >> 24) <= 'z') {
62                 PDEBUG(D_CONF|D_STREAM, "%s %c%c%c%c %dx%d",
63                         txt,
64                         pixfmt & 0xff,
65                         (pixfmt >> 8) & 0xff,
66                         (pixfmt >> 16) & 0xff,
67                         pixfmt >> 24,
68                         w, h);
69         } else {
70                 PDEBUG(D_CONF|D_STREAM, "%s 0x%08x %dx%d",
71                         txt,
72                         pixfmt,
73                         w, h);
74         }
75 }
76 #else
77 #define PDEBUG_MODE(txt, pixfmt, w, h)
78 #endif
79
80 /* specific memory types - !! should different from V4L2_MEMORY_xxx */
81 #define GSPCA_MEMORY_NO 0       /* V4L2_MEMORY_xxx starts from 1 */
82 #define GSPCA_MEMORY_READ 7
83
84 #ifndef GSPCA_HLP
85 #define BUF_ALL_FLAGS (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE)
86 #else
87 #define GSPCA_BUF_FLAG_DECODE   0x1000  /* internal buffer flag */
88 #define BUF_ALL_FLAGS (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE \
89                         | GSPCA_BUF_FLAG_DECODE)
90
91 static int autostart = 4;
92 module_param(autostart, int, 0644);
93 MODULE_PARM_DESC(autostart,
94                 "Automatically start the helper process");
95
96 /* try to start the helper process */
97 static void start_hlp(void)
98 {
99         int ret;
100         static char *argv[] = {"gspca_hlp", NULL};
101         static char *env[] = {NULL};
102
103         if (autostart <= 0) {
104                 if (autostart < 0)
105                         PDEBUG(D_ERR|D_PROBE, "Too many helper restart");
106                 return;
107         }
108         autostart--;
109         if (autostart == 0)
110                 autostart = -1;
111         ret = call_usermodehelper("/sbin/gspca_hlp", argv, env,
112                                 UMH_WAIT_EXEC);
113         if (ret != 0)
114                 PDEBUG(D_ERR|D_PROBE,
115                         "/sbin/gspca_hlp start failed %d", ret);
116 }
117
118 /* /dev/gspca_hlp stuff */
119 #include <linux/miscdevice.h>
120 #include "gspca_hlp.h"
121
122 /* !! possible decodings defined in decoder.c */
123 static __u32 bayer_to_tb[] = {
124         V4L2_PIX_FMT_SBGGR8,
125         V4L2_PIX_FMT_YUYV,
126         V4L2_PIX_FMT_YUV420,
127         V4L2_PIX_FMT_RGB24,
128         V4L2_PIX_FMT_BGR24,
129         V4L2_PIX_FMT_RGB565,
130 };
131 static __u32 jpeg_to_tb[] = {
132         V4L2_PIX_FMT_JPEG,
133         V4L2_PIX_FMT_YUYV,
134         V4L2_PIX_FMT_YUV420,
135         V4L2_PIX_FMT_RGB24,
136         V4L2_PIX_FMT_BGR24,
137         V4L2_PIX_FMT_RGB565,
138 };
139
140 /* /dev/gspca_hlp device */
141 struct hlp_dev {
142         struct gspca_dev *gspca_dev;    /* associated device */
143         struct gspca_frame *frame;      /* frame being decoded */
144         __u32 pixfmt;                   /* webcam pixel format */
145         atomic_t nevent;                /* nb of frames ready to decode */
146         wait_queue_head_t wq;           /* wait queue */
147         char fr_d;                      /* next frame to decode */
148 } *hlp;
149
150 static int hlp_open(struct inode *inode, struct file *file)
151 {
152         struct hlp_dev *hlp_dev;
153
154         PDEBUG(D_CONF, "hlp open");
155         if (hlp != 0)
156                 return -EBUSY;
157         hlp_dev = kzalloc(sizeof *hlp_dev, GFP_KERNEL);
158         if (hlp_dev == NULL) {
159                 err("couldn't kzalloc hlp struct");
160                 return -EIO;
161         }
162         init_waitqueue_head(&hlp_dev->wq);
163         file->private_data = hlp_dev;
164         hlp = hlp_dev;
165         return 0;
166 }
167
168 static int hlp_close(struct inode *inode, struct file *file)
169 {
170         struct gspca_dev *gspca_dev;
171         int mode;
172
173         PDEBUG(D_CONF, "hlp close");
174         file->private_data = NULL;
175
176         /* stop decoding */
177         gspca_dev = hlp->gspca_dev;
178         if (gspca_dev != 0) {
179                 mode = gspca_dev->curr_mode;
180                 gspca_dev->pixfmt = gspca_dev->cam.cam_mode[mode].pixfmt;
181         }
182
183         /* destroy the helper structure */
184         kfree(hlp);
185         hlp = 0;
186
187         /* try to restart the helper process */
188         start_hlp();
189         return 0;
190 }
191
192 static ssize_t hlp_read(struct file *file, char __user *buf,
193                     size_t cnt, loff_t *ppos)
194 {
195         struct hlp_dev *hlp_dev = file->private_data;
196         struct gspca_dev *gspca_dev;
197         struct gspca_frame *frame;
198         struct gspca_hlp_read_hd head;
199         int i, j, len, ret;
200
201         PDEBUG(D_FRAM, "hlp read (%d)", cnt);
202
203         /* check / wait till a frame is ready */
204         for (;;) {
205                 gspca_dev = hlp_dev->gspca_dev;
206                 if (gspca_dev != 0 && gspca_dev->streaming) {
207                         i = hlp_dev->fr_d;      /* frame to decode */
208                         j = gspca_dev->fr_queue[i];
209                         frame = &gspca_dev->frame[j];
210                         if (frame->v4l2_buf.flags & GSPCA_BUF_FLAG_DECODE)
211                                 break;
212                 }
213                 ret = wait_event_interruptible(hlp_dev->wq,
214                                         atomic_read(&hlp_dev->nevent) > 0);
215                 if (ret < 0) {                  /* helper process is killed */
216                         autostart = 0;          /* don't restart it */
217                         return ret;
218                 }
219         }
220         atomic_dec(&hlp_dev->nevent);
221         hlp_dev->fr_d = (i + 1) % gspca_dev->nframes;
222         PDEBUG(D_FRAM, "hlp read q:%d i:%d d:%d o:%d",
223                 gspca_dev->fr_q,
224                 gspca_dev->fr_i,
225                 hlp_dev->fr_d,
226                 gspca_dev->fr_o);
227
228         hlp_dev->frame = frame;         /* memorize the current frame */
229         len = frame->v4l2_buf.bytesused;
230         if (cnt < sizeof head - sizeof head.data + len)
231 /*fixme: special errno?*/
232                 return -EINVAL;
233         head.pixfmt_out = gspca_dev->pixfmt;
234         head.pixfmt_in = hlp_dev->pixfmt;
235         head.width = gspca_dev->width;
236         head.height = gspca_dev->height;
237         copy_to_user(buf, &head, sizeof head);
238         copy_to_user(buf + sizeof head - sizeof head.data,
239                         frame->data, len);
240         return sizeof head - sizeof head.data + len;
241 }
242
243 static ssize_t hlp_write(struct file *file,
244                         const char __user *buf,
245                         size_t cnt, loff_t *ppos)
246 {
247         struct hlp_dev *hlp_dev = file->private_data;
248         struct gspca_dev *gspca_dev;
249         struct gspca_frame *frame;
250
251         PDEBUG(D_FRAM, "hlp write (%d)", cnt);
252         gspca_dev = hlp_dev->gspca_dev;
253         if (gspca_dev == 0)
254                 return cnt;
255         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
256                 return -ERESTARTSYS;
257         if (!gspca_dev->streaming)
258                 goto out;
259         frame = hlp_dev->frame;
260         hlp_dev->frame = 0;
261         if (frame == 0)
262                 goto out;
263         if (cnt > frame->v4l2_buf.length) {
264                 PDEBUG(D_ERR|D_FRAM, "bad frame size %d - %d",
265                         cnt, frame->v4l2_buf.length);
266                 cnt = -EINVAL;
267                 goto out;
268         }
269         copy_from_user(frame->data, buf, cnt);
270         frame->v4l2_buf.bytesused = cnt;
271         frame->v4l2_buf.flags &= ~(V4L2_BUF_FLAG_QUEUED
272                                   | GSPCA_BUF_FLAG_DECODE);
273         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_DONE;
274         mutex_unlock(&gspca_dev->queue_lock);
275         atomic_inc(&gspca_dev->nevent);
276         wake_up_interruptible(&gspca_dev->wq);  /* event = new frame */
277         PDEBUG(D_FRAM, "hlp write q:%d i:%d d:%d o:%d",
278                 gspca_dev->fr_q,
279                 gspca_dev->fr_i,
280                 hlp_dev->fr_d,
281                 gspca_dev->fr_o);
282         return cnt;
283 out:
284         mutex_unlock(&gspca_dev->queue_lock);
285         return cnt;
286 }
287
288 static struct file_operations hlp_fops = {
289         .owner = THIS_MODULE,
290         .open = hlp_open,
291         .release = hlp_close,
292         .read = hlp_read,
293         .write = hlp_write,
294         .llseek = no_llseek
295 };
296 static struct miscdevice hlp_device = {
297         .minor = MISC_DYNAMIC_MINOR,
298         .name = "gspca_hlp",
299         .fops = &hlp_fops,
300 };
301 #endif
302
303 /*
304  * VMA operations.
305  */
306 static void gspca_vm_open(struct vm_area_struct *vma)
307 {
308         struct gspca_frame *frame = vma->vm_private_data;
309
310         frame->vma_use_count++;
311         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
312 }
313
314 static void gspca_vm_close(struct vm_area_struct *vma)
315 {
316         struct gspca_frame *frame = vma->vm_private_data;
317
318         if (--frame->vma_use_count <= 0)
319                 frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_MAPPED;
320 }
321
322 static struct vm_operations_struct gspca_vm_ops = {
323         .open           = gspca_vm_open,
324         .close          = gspca_vm_close,
325 };
326
327 /*
328  * fill a video frame from an URB and resubmit
329  */
330 static void fill_frame(struct gspca_dev *gspca_dev,
331                         struct urb *urb)
332 {
333         struct gspca_frame *frame;
334         unsigned char *data;    /* address of data in the iso message */
335         int i, j, len, st;
336         cam_pkt_op pkt_scan;
337
338         pkt_scan = gspca_dev->sd_desc->pkt_scan;
339         for (i = 0; i < urb->number_of_packets; i++) {
340
341                 /* check the availability of the frame buffer */
342                 j = gspca_dev->fr_i;
343                 j = gspca_dev->fr_queue[j];
344                 frame = &gspca_dev->frame[j];
345                 if ((frame->v4l2_buf.flags & BUF_ALL_FLAGS)
346                                         != V4L2_BUF_FLAG_QUEUED) {
347                         gspca_dev->last_packet_type = DISCARD_PACKET;
348                         break;
349                 }
350
351                 /* check the packet status and length */
352                 len = urb->iso_frame_desc[i].actual_length;
353                 st = urb->iso_frame_desc[i].status;
354                 if (st) {
355                         PDEBUG(D_ERR, "ISOC data error: [%d] len=%d, status=%d",
356                                 i, len, st);
357                         gspca_dev->last_packet_type = DISCARD_PACKET;
358                         continue;
359                 }
360                 if (len == 0)
361                         continue;
362
363                 /* let the packet be analyzed by the subdriver */
364                 PDEBUG(D_PACK, "packet [%d] o:%d l:%d",
365                         i, urb->iso_frame_desc[i].offset, len);
366                 data = (unsigned char *) urb->transfer_buffer
367                                         + urb->iso_frame_desc[i].offset;
368                 pkt_scan(gspca_dev, frame, data, len);
369         }
370
371         /* resubmit the URB */
372 /*fixme: don't do that when userptr and too many URBs sent*/
373         urb->status = 0;
374         st = usb_submit_urb(urb, GFP_ATOMIC);
375         if (st < 0)
376                 PDEBUG(D_ERR|D_PACK, "usb_submit_urb() ret %d", st);
377 }
378
379 /*
380  * ISOC message interrupt from the USB device
381  *
382  * Analyse each packet and call the subdriver for copy
383  * to the frame buffer.
384  *
385  * There are 2 functions:
386  *      - the first one (isoc_irq_mmap) is used when the application
387  *        buffers are mapped. The frame detection and copy is done
388  *        at interrupt level.
389  *      - the second one (isoc_irq_user) is used when the application
390  *        buffers are in user space (userptr). The frame detection
391  *        and copy is done by the application.
392  */
393 static void isoc_irq_mmap(struct urb *urb)
394 {
395         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
396
397         PDEBUG(D_PACK, "isoc irq mmap");
398         if (!gspca_dev->streaming)
399                 return;
400         fill_frame(gspca_dev, urb);
401 }
402
403 static void isoc_irq_user(struct urb *urb)
404 {
405         struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
406         int i;
407
408         PDEBUG(D_PACK, "isoc irq user");
409         if (!gspca_dev->streaming)
410                 return;
411
412         i = gspca_dev->urb_in % gspca_dev->nurbs;
413         if (urb != gspca_dev->urb[i]) {
414                 PDEBUG(D_ERR|D_PACK, "urb out of sequence");
415                 return;                 /* should never occur */
416         }
417
418         gspca_dev->urb_in++;
419         atomic_inc(&gspca_dev->nevent);         /* new event */
420         wake_up_interruptible(&gspca_dev->wq);
421 /*fixme: submit a new URBs until urb_in == urb_out (% nurbs)*/
422 }
423
424 /*
425  * treat the isoc messages
426  *
427  * This routine is called by the application (case userptr).
428  */
429 static void isoc_transfer(struct gspca_dev *gspca_dev)
430 {
431         struct urb *urb;
432         int i;
433
434         for (;;) {
435                 i = gspca_dev->urb_out;
436                 PDEBUG(D_PACK, "isoc transf i:%d o:%d", gspca_dev->urb_in, i);
437                 if (i == gspca_dev->urb_in)     /* isoc message to read */
438                         break;                  /* no (more) message */
439                 atomic_dec(&gspca_dev->nevent);
440 /*PDEBUG(D_PACK, "isoc_trf nevent: %d", atomic_read(&gspca_dev->nevent));*/
441                 gspca_dev->urb_out = i + 1;     /* message treated */
442                 urb = gspca_dev->urb[i % gspca_dev->nurbs];
443                 fill_frame(gspca_dev, urb);
444         }
445 }
446
447 /*
448  * add data to the current frame
449  *
450  * This function is called by the subdrivers at interrupt level
451  * or user level.
452  * To build a frame, these ones must add
453  *      - one FIRST_PACKET
454  *      - 0 or many INTER_PACKETs
455  *      - one LAST_PACKET
456  * DISCARD_PACKET invalidates the whole frame.
457  * On LAST_PACKET, a new frame is returned.
458  */
459 struct gspca_frame *gspca_frame_add(struct gspca_dev *gspca_dev,
460                                     int packet_type,
461                                     struct gspca_frame *frame,
462                                     unsigned char *data,
463                                     int len)
464 {
465         int i, j;
466
467         PDEBUG(D_PACK, "add t:%d l:%d", packet_type, len);
468
469         /* when start of a new frame, if the current frame buffer
470          * is not queued, discard the whole frame */
471         if (packet_type == FIRST_PACKET) {
472                 if ((frame->v4l2_buf.flags & BUF_ALL_FLAGS)
473                                                 != V4L2_BUF_FLAG_QUEUED) {
474                         gspca_dev->last_packet_type = DISCARD_PACKET;
475                         return frame;
476                 }
477                 frame->data_end = frame->data;
478                 jiffies_to_timeval(get_jiffies_64(),
479                                    &frame->v4l2_buf.timestamp);
480                 frame->v4l2_buf.sequence = ++gspca_dev->sequence;
481         } else if (gspca_dev->last_packet_type == DISCARD_PACKET) {
482                 return frame;
483         }
484
485         /* append the packet to the frame buffer */
486         if (len > 0) {
487                 if (frame->data_end - frame->data + len
488                                                  > frame->v4l2_buf.length) {
489                         PDEBUG(D_ERR|D_PACK, "frame overflow %d > %d",
490                                 frame->data_end - frame->data + len,
491                                 frame->v4l2_buf.length);
492                         packet_type = DISCARD_PACKET;
493                 } else {
494                         if (frame->v4l2_buf.memory != V4L2_MEMORY_USERPTR)
495                                 memcpy(frame->data_end, data, len);
496                         else
497                                 copy_to_user(frame->data_end, data, len);
498                         frame->data_end += len;
499                 }
500         }
501         gspca_dev->last_packet_type = packet_type;
502
503         /* if last packet, wake the application and advance in the queue */
504         if (packet_type == LAST_PACKET) {
505                 frame->v4l2_buf.bytesused = frame->data_end - frame->data;
506 #ifndef GSPCA_HLP
507                 frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_QUEUED;
508                 frame->v4l2_buf.flags |= V4L2_BUF_FLAG_DONE;
509                 atomic_inc(&gspca_dev->nevent);
510                 wake_up_interruptible(&gspca_dev->wq);  /* event = new frame */
511 #else /*GSPCA_HLP*/
512                 if (hlp != 0 && hlp->gspca_dev == gspca_dev) {
513                         frame->v4l2_buf.flags |= GSPCA_BUF_FLAG_DECODE;
514                         atomic_inc(&hlp->nevent);
515                         wake_up_interruptible(&hlp->wq);
516                 } else {
517                         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_QUEUED;
518                         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_DONE;
519                         atomic_inc(&gspca_dev->nevent);
520                         wake_up_interruptible(&gspca_dev->wq);  /* new frame */
521                 }
522 #endif /*GSPCA_HLP*/
523                 i = (gspca_dev->fr_i + 1) % gspca_dev->nframes;
524                 gspca_dev->fr_i = i;
525                 PDEBUG(D_FRAM, "frame complete len:%d q:%d i:%d o:%d",
526                         frame->v4l2_buf.bytesused,
527                         gspca_dev->fr_q,
528                         i,
529                         gspca_dev->fr_o);
530                 j = gspca_dev->fr_queue[i];
531                 frame = &gspca_dev->frame[j];
532         }
533         return frame;
534 }
535 EXPORT_SYMBOL(gspca_frame_add);
536
537 static int gspca_is_compressed(__u32 format)
538 {
539         switch (format) {
540         case V4L2_PIX_FMT_MJPEG:
541         case V4L2_PIX_FMT_JPEG:
542                 return 1;
543         }
544         return 0;
545 }
546
547 static void *rvmalloc(unsigned long size)
548 {
549         void *mem;
550         unsigned long adr;
551
552 /*      size = PAGE_ALIGN(size);        (already done) */
553         mem = vmalloc_32(size);
554         if (mem != 0) {
555                 memset(mem, 0, size);
556                 adr = (unsigned long) mem;
557                 while ((long) size > 0) {
558                         SetPageReserved(vmalloc_to_page((void *) adr));
559                         adr += PAGE_SIZE;
560                         size -= PAGE_SIZE;
561                 }
562         }
563         return mem;
564 }
565
566 static void rvfree(void *mem, unsigned long size)
567 {
568         unsigned long adr;
569
570         if (!mem)
571                 return;
572         adr = (unsigned long) mem;
573         while ((long) size > 0) {
574                 ClearPageReserved(vmalloc_to_page((void *) adr));
575                 adr += PAGE_SIZE;
576                 size -= PAGE_SIZE;
577         }
578         vfree(mem);
579 }
580
581 static __u32 get_v4l2_depth(__u32 pixfmt)
582 {
583         switch (pixfmt) {
584         case V4L2_PIX_FMT_BGR32:
585         case V4L2_PIX_FMT_RGB32:
586                 return 32;
587         case V4L2_PIX_FMT_RGB24:        /* 'RGB3' */
588         case V4L2_PIX_FMT_BGR24:
589                 return 24;
590         case V4L2_PIX_FMT_RGB565:       /* 'RGBP' */
591         case V4L2_PIX_FMT_YUYV:         /* 'YUYV' packed 4.2.2 */
592         case V4L2_PIX_FMT_YYUV:         /* 'YYUV' */
593                 return 16;
594         case V4L2_PIX_FMT_YUV420:       /* 'YU12' planar 4.2.0 */
595                 return 12;
596         case V4L2_PIX_FMT_MJPEG:
597         case V4L2_PIX_FMT_JPEG:
598         case V4L2_PIX_FMT_SBGGR8:       /* 'BA81' Bayer */
599                 return 8;
600         }
601         PDEBUG(D_ERR|D_CONF, "Unknown pixel format %c%c%c%c",
602                 pixfmt & 0xff,
603                 (pixfmt >> 8) & 0xff,
604                 (pixfmt >> 16) & 0xff,
605                 pixfmt >> 24);
606         return -EINVAL;
607 }
608
609 static int gspca_get_buff_size(struct gspca_dev *gspca_dev)
610 {
611         unsigned int size;
612
613         size = gspca_dev->width * gspca_dev->height
614                                 * get_v4l2_depth(gspca_dev->pixfmt) / 8;
615         if (!size)
616                 return -ENOMEM;
617         return size;
618 }
619
620 static int frame_alloc(struct gspca_dev *gspca_dev,
621                         unsigned int count)
622 {
623         struct gspca_frame *frame;
624         unsigned int frsz;
625         int i;
626
627         frsz = gspca_get_buff_size(gspca_dev);
628         if (frsz < 0)
629                 return frsz;
630         PDEBUG(D_STREAM, "frame alloc frsz: %d", frsz);
631         if (count > GSPCA_MAX_FRAMES)
632                 count = GSPCA_MAX_FRAMES;
633         /* if compressed (JPEG), reduce the buffer size */
634         if (gspca_is_compressed(gspca_dev->pixfmt))
635                 frsz = (frsz * comp_fac) / 100 + 600;   /* plus JPEG header */
636         frsz = PAGE_ALIGN(frsz);
637         PDEBUG(D_STREAM, "new fr_sz: %d", frsz);
638         gspca_dev->frsz = frsz;
639         if (gspca_dev->memory == V4L2_MEMORY_MMAP) {
640                 gspca_dev->frbuf = rvmalloc(frsz * count);
641                 if (!gspca_dev->frbuf) {
642                         err("frame alloc failed");
643                         return -ENOMEM;
644                 }
645         }
646         gspca_dev->nframes = count;
647         for (i = 0; i < count; i++) {
648                 frame = &gspca_dev->frame[i];
649                 frame->v4l2_buf.index = i;
650                 frame->v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
651                 frame->v4l2_buf.flags = 0;
652                 frame->v4l2_buf.field = V4L2_FIELD_NONE;
653                 frame->v4l2_buf.length = frsz;
654                 frame->v4l2_buf.memory = gspca_dev->memory;
655                 frame->v4l2_buf.sequence = 0;
656                 if (gspca_dev->memory == V4L2_MEMORY_MMAP) {
657                         frame->data = frame->data_end =
658                                         gspca_dev->frbuf + i * frsz;
659                         frame->v4l2_buf.m.offset = i * frsz;
660                 }
661         }
662         gspca_dev->fr_i = gspca_dev->fr_o = gspca_dev->fr_q = 0;
663 #ifdef GSPCA_HLP
664         {
665                 struct hlp_dev *hlp_dev;
666
667                 hlp_dev = hlp;
668                 if (hlp != 0 && hlp_dev->gspca_dev == gspca_dev) {
669                         hlp_dev->fr_d = 0;
670                         atomic_set(&hlp_dev->nevent, 0);
671                 }
672         }
673 #endif /*GSPCA_HLP*/
674         gspca_dev->last_packet_type = DISCARD_PACKET;
675         gspca_dev->sequence = 0;
676         atomic_set(&gspca_dev->nevent, 0);
677         return 0;
678 }
679
680 static void frame_free(struct gspca_dev *gspca_dev)
681 {
682         int i;
683
684         PDEBUG(D_STREAM, "frame free");
685         if (gspca_dev->frbuf != 0) {
686                 rvfree(gspca_dev->frbuf,
687                         gspca_dev->nframes * gspca_dev->frsz);
688                 gspca_dev->frbuf = NULL;
689                 for (i = 0; i < gspca_dev->nframes; i++)
690                         gspca_dev->frame[i].data = NULL;
691         }
692         gspca_dev->nframes = 0;
693 }
694
695 static void destroy_urbs(struct gspca_dev *gspca_dev)
696 {
697         struct urb *urb;
698         unsigned int i;
699
700         PDEBUG(D_STREAM, "kill transfer");
701         for (i = 0; i < MAX_NURBS; ++i) {
702                 urb = gspca_dev->urb[i];
703                 if (urb == NULL)
704                         break;
705
706                 gspca_dev->urb[i] = NULL;
707                 usb_kill_urb(urb);
708                 if (urb->transfer_buffer != 0)
709                         usb_buffer_free(gspca_dev->dev,
710                                         urb->transfer_buffer_length,
711                                         urb->transfer_buffer,
712                                         urb->transfer_dma);
713                 usb_free_urb(urb);
714         }
715 }
716
717 /*
718  * search an input isochronous endpoint in an alternate setting
719  */
720 static struct usb_host_endpoint *alt_isoc(struct usb_host_interface *alt,
721                                           __u8 epaddr)
722 {
723         struct usb_host_endpoint *ep;
724         int i, attr;
725
726         epaddr |= USB_DIR_IN;
727         for (i = 0; i < alt->desc.bNumEndpoints; i++) {
728                 ep = &alt->endpoint[i];
729                 if (ep->desc.bEndpointAddress == epaddr) {
730                         attr = ep->desc.bmAttributes
731                                                 & USB_ENDPOINT_XFERTYPE_MASK;
732                         if (attr == USB_ENDPOINT_XFER_ISOC)
733                                 return ep;
734                         break;
735                 }
736         }
737         return NULL;
738 }
739
740 /*
741  * search an input isochronous endpoint
742  *
743  * The endpoint is defined by the subdriver.
744  * Use only the first isoc (some Zoran - 0x0572:0x0001 - have two such ep).
745  * This routine may be called many times when the bandwidth is too small
746  * (the bandwidth is checked on urb submit).
747  */
748 struct usb_host_endpoint *get_isoc_ep(struct gspca_dev *gspca_dev)
749 {
750         struct usb_interface *intf;
751         struct usb_host_endpoint *ep;
752         int i, ret;
753
754         intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
755         i = gspca_dev->alt;                     /* previous alt setting */
756         while (--i > 0) {                       /* alt 0 is unusable */
757                 ep = alt_isoc(&intf->altsetting[i], gspca_dev->cam.epaddr);
758                 if (ep)
759                         break;
760         }
761         if (i <= 0) {
762                 err("no ISOC endpoint found");
763                 return NULL;
764         }
765         PDEBUG(D_STREAM, "use ISOC alt %d ep 0x%02x",
766                         i, ep->desc.bEndpointAddress);
767         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, i);
768         if (ret < 0) {
769                 err("set interface err %d", ret);
770                 return NULL;
771         }
772         gspca_dev->alt = i;             /* memorize the current alt setting */
773         return ep;
774 }
775
776 /*
777  * create the isochronous URBs
778  */
779 static int create_urbs(struct gspca_dev *gspca_dev,
780                         struct usb_host_endpoint *ep)
781 {
782         struct urb *urb;
783         int n, nurbs, i, psize, npkt, bsize;
784         usb_complete_t usb_complete;
785
786         /* calculate the packet size and the number of packets */
787         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
788
789         /* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
790         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
791         npkt = ISO_MAX_SIZE / psize;
792         if (npkt > ISO_MAX_PKT)
793                 npkt = ISO_MAX_PKT;
794         bsize = psize * npkt;
795         PDEBUG(D_STREAM,
796                 "isoc %d pkts size %d (bsize:%d)", npkt, psize, bsize);
797 /*fixme:change for userptr*/
798 /*fixme:don't submit all URBs when userptr*/
799         gspca_dev->nurbs = nurbs = DEF_NURBS;
800         if (gspca_dev->memory == V4L2_MEMORY_MMAP)
801                 usb_complete = isoc_irq_mmap;
802         else
803                 usb_complete = isoc_irq_user;
804         for (n = 0; n < nurbs; n++) {
805                 urb = usb_alloc_urb(npkt, GFP_KERNEL);
806                 if (!urb) {
807                         err("usb_alloc_urb failed");
808                         return -ENOMEM;
809                 }
810                 urb->transfer_buffer = usb_buffer_alloc(gspca_dev->dev,
811                                                 bsize,
812                                                 GFP_KERNEL,
813                                                 &urb->transfer_dma);
814
815                 if (urb->transfer_buffer == NULL) {
816                         usb_free_urb(urb);
817                         destroy_urbs(gspca_dev);
818                         err("usb_buffer_urb failed");
819                         return -ENOMEM;
820                 }
821                 gspca_dev->urb[n] = urb;
822                 urb->dev = gspca_dev->dev;
823                 urb->context = gspca_dev;
824                 urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
825                                             ep->desc.bEndpointAddress);
826                 urb->transfer_flags = URB_ISO_ASAP
827                                         | URB_NO_TRANSFER_DMA_MAP;
828                 urb->interval = ep->desc.bInterval;
829                 urb->complete = usb_complete;
830                 urb->number_of_packets = npkt;
831                 urb->transfer_buffer_length = bsize;
832                 for (i = 0; i < npkt; i++) {
833                         urb->iso_frame_desc[i].length = psize;
834                         urb->iso_frame_desc[i].offset = psize * i;
835                 }
836         }
837         gspca_dev->urb_in = gspca_dev->urb_out = 0;
838         return 0;
839 }
840
841 /*
842  * start the USB transfer
843  */
844 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
845 {
846         struct usb_host_endpoint *ep;
847         int n, ret;
848
849         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
850                 return -ERESTARTSYS;
851
852         /* set the higher alternate setting and
853          * loop until urb submit succeeds */
854         gspca_dev->alt = gspca_dev->nbalt;
855         for (;;) {
856                 PDEBUG(D_STREAM, "init transfer alt %d", gspca_dev->alt);
857                 ep = get_isoc_ep(gspca_dev);
858                 if (ep == NULL) {
859                         ret = -EIO;
860                         goto out;
861                 }
862                 ret = create_urbs(gspca_dev, ep);
863                 if (ret < 0)
864                         goto out;
865
866                 /* start the cam */
867                 gspca_dev->sd_desc->start(gspca_dev);
868                 gspca_dev->streaming = 1;
869                 atomic_set(&gspca_dev->nevent, 0);
870
871                 /* submit the URBs */
872                 for (n = 0; n < gspca_dev->nurbs; n++) {
873                         ret = usb_submit_urb(gspca_dev->urb[n], GFP_KERNEL);
874                         if (ret < 0) {
875                                 PDEBUG(D_ERR|D_STREAM,
876                                         "usb_submit_urb [%d] err %d", n, ret);
877                                 gspca_dev->streaming = 0;
878                                 destroy_urbs(gspca_dev);
879                                 if (ret == -ENOSPC)
880                                         break;  /* try the previous alt */
881                                 goto out;
882                         }
883                 }
884                 if (ret >= 0)
885                         break;
886         }
887 out:
888         mutex_unlock(&gspca_dev->usb_lock);
889         return ret;
890 }
891
892 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
893 {
894         int ret;
895
896         ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
897         if (ret < 0)
898                 PDEBUG(D_ERR|D_STREAM, "set interface 0 err %d", ret);
899         return ret;
900 }
901
902 /* Note both the queue and the usb lock should be hold when calling this */
903 static void gspca_stream_off(struct gspca_dev *gspca_dev)
904 {
905         gspca_dev->streaming = 0;
906         atomic_set(&gspca_dev->nevent, 0);
907 #ifdef GSPCA_HLP
908         {
909                 struct hlp_dev *hlp_dev;
910
911                 hlp_dev = hlp;
912                 if (hlp_dev != 0
913                     && hlp_dev->gspca_dev == gspca_dev)
914                         atomic_set(&hlp_dev->nevent, 0);
915         }
916 #endif
917         if (gspca_dev->present) {
918                 gspca_dev->sd_desc->stopN(gspca_dev);
919                 destroy_urbs(gspca_dev);
920                 gspca_set_alt0(gspca_dev);
921                 gspca_dev->sd_desc->stop0(gspca_dev);
922                 PDEBUG(D_STREAM, "stream off OK");
923         } else {
924                 destroy_urbs(gspca_dev);
925                 atomic_inc(&gspca_dev->nevent);
926                 wake_up_interruptible(&gspca_dev->wq);
927                 PDEBUG(D_ERR|D_STREAM, "stream off no device ??");
928         }
929 }
930
931 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
932 {
933         int i;
934
935         i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
936         gspca_dev->curr_mode = i;
937         gspca_dev->width = gspca_dev->cam.cam_mode[i].width;
938         gspca_dev->height = gspca_dev->cam.cam_mode[i].height;
939         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixfmt;
940 }
941
942 static int wxh_to_mode(struct gspca_dev *gspca_dev,
943                         int width, int height)
944 {
945         int i;
946
947         for (i = gspca_dev->cam.nmodes; --i > 0; ) {
948                 if (width >= gspca_dev->cam.cam_mode[i].width
949                     && height >= gspca_dev->cam.cam_mode[i].height)
950                         break;
951         }
952         return i;
953 }
954
955 /*
956  * search a mode with the right pixel format
957  */
958 static int gspca_get_mode(struct gspca_dev *gspca_dev,
959                         int mode,
960                         int pixfmt)
961 {
962         int modeU, modeD;
963
964         modeU = modeD = mode;
965         while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
966                 if (--modeD >= 0) {
967                         if (gspca_dev->cam.cam_mode[modeD].pixfmt == pixfmt)
968                                 return modeD;
969                 }
970                 if (++modeU < gspca_dev->cam.nmodes) {
971                         if (gspca_dev->cam.cam_mode[modeU].pixfmt == pixfmt)
972                                 return modeU;
973                 }
974         }
975         return -EINVAL;
976 }
977
978 static int vidioc_enum_fmt_cap(struct file *file, void  *priv,
979                                 struct v4l2_fmtdesc *fmtdesc)
980 {
981         struct gspca_dev *gspca_dev = priv;
982         int i;
983 #ifndef GSPCA_HLP
984         int j, index;
985         __u32 fmt_tb[8];
986 #endif
987
988         PDEBUG(D_CONF, "enum fmt cap");
989
990 #ifndef GSPCA_HLP
991         /* give an index to each format */
992         index = 0;
993         j = 0;
994         for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
995                 fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixfmt;
996                 j = 0;
997                 for (;;) {
998                         if (fmt_tb[j] == fmt_tb[index])
999                                 break;
1000                         j++;
1001                 }
1002                 if (j == index) {
1003                         if (fmtdesc->index == index)
1004                                 break;          /* new format */
1005                         index++;
1006                         if (index >= sizeof fmt_tb / sizeof fmt_tb[0])
1007                                 return -EINVAL;
1008                 }
1009         }
1010         if (i < 0)
1011                 return -EINVAL;         /* no more format */
1012
1013         fmtdesc->pixelformat = fmt_tb[index];
1014         if (gspca_is_compressed(fmt_tb[index]))
1015                 fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1016 #else /*GSPCA_HLP*/
1017         /* !! code tied to the decoding functions in decoder.c */
1018         i = gspca_dev->cam.nmodes - 1;
1019         if (fmtdesc->index == 0) {      /* (assume one format per subdriver) */
1020                 fmtdesc->pixelformat = gspca_dev->cam.cam_mode[i].pixfmt;
1021                 if (gspca_is_compressed(fmtdesc->pixelformat))
1022                         fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1023         } else {
1024                 if (hlp == 0
1025                     || (hlp->gspca_dev != 0
1026                         && hlp->gspca_dev != gspca_dev))
1027                         return -EINVAL;
1028                 switch (gspca_dev->cam.cam_mode[i].pixfmt) {
1029                 case V4L2_PIX_FMT_JPEG:
1030                         if (fmtdesc->index >= sizeof jpeg_to_tb
1031                                                  / sizeof jpeg_to_tb[0])
1032                                 return -EINVAL;
1033                         fmtdesc->pixelformat = jpeg_to_tb[fmtdesc->index];
1034                         break;
1035                 case V4L2_PIX_FMT_SBGGR8:
1036                         if (fmtdesc->index >= sizeof bayer_to_tb
1037                                                  / sizeof bayer_to_tb[0])
1038                                 return -EINVAL;
1039                         fmtdesc->pixelformat = bayer_to_tb[fmtdesc->index];
1040                         break;
1041                 default:
1042                         return -EINVAL;
1043                 }
1044         }
1045 #endif /*GSPCA_HLP*/
1046         fmtdesc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1047         fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
1048         fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
1049         fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
1050         fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
1051         fmtdesc->description[4] = '\0';
1052         return 0;
1053 }
1054
1055 static int vidioc_g_fmt_cap(struct file *file, void *priv,
1056                             struct v4l2_format *fmt)
1057 {
1058         struct gspca_dev *gspca_dev = priv;
1059
1060 #ifdef GSPCA_HLP
1061         int i;
1062
1063         /* if the pixel format is not the one of the device and
1064          * if the helper is inactive or busy, restore */
1065         i = gspca_dev->curr_mode;
1066         if (gspca_dev->pixfmt != gspca_dev->cam.cam_mode[i].pixfmt) {
1067                 struct hlp_dev *hlp_dev;
1068
1069                 hlp_dev = hlp;
1070                 if (hlp_dev == 0 || hlp_dev->gspca_dev != gspca_dev)
1071                         gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i].pixfmt;
1072         }
1073 #endif /*GSPCA_HLP*/
1074
1075         fmt->fmt.pix.width = gspca_dev->width;
1076         fmt->fmt.pix.height = gspca_dev->height;
1077         fmt->fmt.pix.pixelformat = gspca_dev->pixfmt;
1078 #ifdef GSPCA_DEBUG
1079         if (gspca_debug & D_CONF) {
1080                 PDEBUG_MODE("get fmt cap",
1081                         fmt->fmt.pix.pixelformat,
1082                         fmt->fmt.pix.width,
1083                         fmt->fmt.pix.height);
1084         }
1085 #endif
1086         fmt->fmt.pix.field = V4L2_FIELD_NONE;
1087         fmt->fmt.pix.bytesperline = get_v4l2_depth(fmt->fmt.pix.pixelformat)
1088                                         * fmt->fmt.pix.width / 8;
1089         fmt->fmt.pix.sizeimage = fmt->fmt.pix.bytesperline
1090                                         * fmt->fmt.pix.height;
1091 /* (should be in the subdriver) */
1092         fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
1093         fmt->fmt.pix.priv = 0;
1094         return 0;
1095 }
1096
1097 static int try_fmt_cap(struct gspca_dev *gspca_dev,
1098                         struct v4l2_format *fmt)
1099 {
1100         int w, h, mode, mode2, frsz;
1101
1102         w = fmt->fmt.pix.width;
1103         h = fmt->fmt.pix.height;
1104
1105         /* (luvcview problem) */
1106         if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG)
1107                 fmt->fmt.pix.pixelformat = V4L2_PIX_FMT_JPEG;
1108 #ifdef GSPCA_DEBUG
1109         if (gspca_debug & D_CONF)
1110                 PDEBUG_MODE("try fmt cap", fmt->fmt.pix.pixelformat, w, h);
1111 #endif
1112         /* search the closest mode for width and height */
1113         mode = wxh_to_mode(gspca_dev, w, h);
1114
1115         /* OK if right palette */
1116         if (gspca_dev->cam.cam_mode[mode].pixfmt != fmt->fmt.pix.pixelformat) {
1117
1118                 /* else, search the closest mode with the same pixel format */
1119                 mode2 = gspca_get_mode(gspca_dev, mode,
1120                                         fmt->fmt.pix.pixelformat);
1121                 if (mode2 >= 0) {
1122                         mode = mode2;
1123                 } else {
1124                         __u32 pixfmt;
1125
1126                         pixfmt = gspca_dev->cam.cam_mode[mode].pixfmt;
1127 #ifndef GSPCA_HLP
1128
1129                         /* no chance, return this mode */
1130                         fmt->fmt.pix.pixelformat = pixfmt;
1131 #else /*GSPCA_HLP*/
1132                         if (hlp != 0
1133                             && (hlp->gspca_dev == 0
1134                                 || hlp->gspca_dev == gspca_dev)
1135 /* decoding works for JPEG and Bayer only */
1136                             && (pixfmt == V4L2_PIX_FMT_JPEG
1137                                 || pixfmt == V4L2_PIX_FMT_SBGGR8)) {
1138                                 switch (fmt->fmt.pix.pixelformat) {
1139                                 case V4L2_PIX_FMT_YUYV:         /* 'YUYV' */
1140                                 case V4L2_PIX_FMT_BGR24:        /* 'BGR3' */
1141                                 case V4L2_PIX_FMT_RGB24:        /* 'RGB3' */
1142                                 case V4L2_PIX_FMT_YUV420:       /* 'YU12' */
1143                                 case V4L2_PIX_FMT_RGB565:       /* 'RGBP' */
1144                                         break;
1145                                 default: {
1146                                         /* return any of the supported fmt's */
1147                                         __u8 u;
1148
1149                                         u = get_jiffies_64();
1150                                         u %= sizeof bayer_to_tb
1151                                                 / sizeof bayer_to_tb[0] - 1;
1152                                         fmt->fmt.pix.pixelformat =
1153                                                         bayer_to_tb[u + 1];
1154                                         break;
1155                                     }
1156                                 }
1157                         } else {
1158                                 fmt->fmt.pix.pixelformat = pixfmt;
1159                         }
1160 #endif /*GSPCA_HLP*/
1161 #ifdef GSPCA_DEBUG
1162                         if (gspca_debug & D_CONF) {
1163                                 PDEBUG_MODE("new format",
1164                                         fmt->fmt.pix.pixelformat,
1165                                         gspca_dev->cam.cam_mode[mode].width,
1166                                         gspca_dev->cam.cam_mode[mode].height);
1167                         }
1168 #endif
1169                 }
1170         }
1171         fmt->fmt.pix.width = gspca_dev->cam.cam_mode[mode].width;
1172         fmt->fmt.pix.height = gspca_dev->cam.cam_mode[mode].height;
1173         fmt->fmt.pix.bytesperline = get_v4l2_depth(fmt->fmt.pix.pixelformat)
1174                                         * fmt->fmt.pix.width / 8;
1175         frsz = fmt->fmt.pix.bytesperline * fmt->fmt.pix.height;
1176         if (gspca_is_compressed(fmt->fmt.pix.pixelformat))
1177                 frsz = (frsz * comp_fac) / 100;
1178         fmt->fmt.pix.sizeimage = frsz;
1179         return mode;                    /* used when s_fmt */
1180 }
1181
1182 static int vidioc_try_fmt_cap(struct file *file,
1183                               void *priv,
1184                               struct v4l2_format *fmt)
1185 {
1186         struct gspca_dev *gspca_dev = priv;
1187         int ret;
1188
1189         ret = try_fmt_cap(gspca_dev, fmt);
1190         if (ret < 0)
1191                 return ret;
1192         return 0;
1193 }
1194
1195 static int vidioc_s_fmt_cap(struct file *file, void *priv,
1196                             struct v4l2_format *fmt)
1197 {
1198         struct gspca_dev *gspca_dev = priv;
1199         int ret;
1200
1201 #ifdef GSPCA_DEBUG
1202         if (gspca_debug & D_CONF) {
1203                 PDEBUG_MODE("set fmt cap",
1204                         fmt->fmt.pix.pixelformat,
1205                         fmt->fmt.pix.width, fmt->fmt.pix.height);
1206         }
1207 #endif
1208         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1209                 return -ERESTARTSYS;
1210
1211         ret = try_fmt_cap(gspca_dev, fmt);
1212         if (ret < 0)
1213                 goto out;
1214
1215         if (gspca_dev->nframes != 0
1216             && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
1217                 ret = -EINVAL;
1218                 goto out;
1219         }
1220
1221 #ifndef GSPCA_HLP
1222         if (ret == gspca_dev->curr_mode)
1223                 goto out;                       /* same mode */
1224 #else /*GSPCA_HLP*/
1225         if (ret == gspca_dev->curr_mode
1226             && gspca_dev->pixfmt == fmt->fmt.pix.pixelformat)
1227                 goto out;                       /* same mode */
1228 #endif /*GSPCA_HLP*/
1229
1230         if (gspca_dev->streaming) {
1231                 ret = -EBUSY;
1232                 goto out;
1233         }
1234         gspca_dev->width = fmt->fmt.pix.width;
1235         gspca_dev->height = fmt->fmt.pix.height;
1236         gspca_dev->pixfmt = fmt->fmt.pix.pixelformat;
1237         gspca_dev->curr_mode = ret;
1238
1239 #ifdef GSPCA_HLP
1240         /* if frame decoding is required */
1241         if (gspca_dev->pixfmt != gspca_dev->cam.cam_mode[ret].pixfmt) {
1242                 struct hlp_dev *hlp_dev;
1243
1244                 hlp_dev = hlp;
1245                 if (hlp_dev == 0
1246                     || (hlp_dev->gspca_dev != 0
1247                         && hlp_dev->gspca_dev != gspca_dev)) { /* helper busy */
1248                         fmt->fmt.pix.pixelformat =
1249                                 gspca_dev->pixfmt =
1250                                         gspca_dev->cam.cam_mode[ret].pixfmt;
1251                 } else {                                /* helper active */
1252                         hlp_dev->gspca_dev = gspca_dev;
1253                         hlp_dev->pixfmt = gspca_dev->cam.cam_mode[ret].pixfmt;
1254                         hlp_dev->fr_d = gspca_dev->fr_i;
1255                 }
1256         } else if (hlp != 0 && hlp->gspca_dev == gspca_dev)
1257                 hlp->gspca_dev = 0;
1258 #endif /*GSPCA_HLP*/
1259         ret = 0;
1260 out:
1261         mutex_unlock(&gspca_dev->queue_lock);
1262         return ret;
1263 }
1264
1265 static int dev_open(struct inode *inode, struct file *file)
1266 {
1267         struct gspca_dev *gspca_dev;
1268         int ret;
1269
1270         PDEBUG(D_STREAM, "%s open", current->comm);
1271         gspca_dev = (struct gspca_dev *) video_devdata(file);
1272         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1273                 return -ERESTARTSYS;
1274         if (!gspca_dev->present) {
1275                 ret = -ENODEV;
1276                 goto out;
1277         }
1278
1279         /* if not done yet, initialize the sensor */
1280         if (gspca_dev->users == 0) {
1281                 if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1282                         ret = -ERESTARTSYS;
1283                         goto out;
1284                 }
1285                 ret = gspca_dev->sd_desc->open(gspca_dev);
1286                 mutex_unlock(&gspca_dev->usb_lock);
1287                 if (ret != 0) {
1288                         PDEBUG(D_ERR|D_CONF, "init device failed %d", ret);
1289                         goto out;
1290                 }
1291         } else if (gspca_dev->users > 4) {      /* (arbitrary value) */
1292                 ret = -EBUSY;
1293                 goto out;
1294         }
1295         gspca_dev->users++;
1296         file->private_data = gspca_dev;
1297 #ifdef GSPCA_DEBUG
1298         /* activate the v4l2 debug */
1299         if (gspca_debug & D_V4L2)
1300                 gspca_dev->vdev.debug |= 3;
1301         else
1302                 gspca_dev->vdev.debug &= ~3;
1303 #endif
1304 out:
1305         mutex_unlock(&gspca_dev->queue_lock);
1306         if (ret != 0)
1307                 PDEBUG(D_ERR|D_STREAM, "open failed err %d", ret);
1308         else
1309                 PDEBUG(D_STREAM, "open done");
1310         return ret;
1311 }
1312
1313 static int dev_close(struct inode *inode, struct file *file)
1314 {
1315         struct gspca_dev *gspca_dev = file->private_data;
1316
1317         PDEBUG(D_STREAM, "%s close", current->comm);
1318         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1319                 return -ERESTARTSYS;
1320         gspca_dev->users--;
1321
1322         /* if the file did capture, free the streaming resources */
1323         if (gspca_dev->capt_file == file) {
1324                 mutex_lock(&gspca_dev->usb_lock);
1325                 if (gspca_dev->streaming)
1326                         gspca_stream_off(gspca_dev);
1327                 gspca_dev->sd_desc->close(gspca_dev);
1328                 mutex_unlock(&gspca_dev->usb_lock);
1329                 frame_free(gspca_dev);
1330                 gspca_dev->capt_file = 0;
1331                 gspca_dev->memory = GSPCA_MEMORY_NO;
1332 #ifdef GSPCA_HLP
1333                 {
1334                         struct hlp_dev *hlp_dev;
1335                         int mode;
1336
1337                         hlp_dev = hlp;
1338                         if (hlp_dev != 0
1339                             && hlp_dev->gspca_dev == gspca_dev) {
1340                                 hlp_dev->gspca_dev = 0;
1341                                 hlp_dev->frame = 0;
1342                                 mode = gspca_dev->curr_mode;
1343                                 gspca_dev->pixfmt =
1344                                         gspca_dev->cam.cam_mode[mode].pixfmt;
1345                         }
1346                 }
1347 #endif /*GSPCA_HLP*/
1348         }
1349         file->private_data = NULL;
1350         mutex_unlock(&gspca_dev->queue_lock);
1351         PDEBUG(D_STREAM, "close done");
1352         return 0;
1353 }
1354
1355 static int vidioc_querycap(struct file *file, void  *priv,
1356                            struct v4l2_capability *cap)
1357 {
1358         struct gspca_dev *gspca_dev = priv;
1359
1360         PDEBUG(D_CONF, "querycap");
1361         memset(cap, 0, sizeof *cap);
1362         strncpy(cap->driver, gspca_dev->sd_desc->name, sizeof cap->driver);
1363         strncpy(cap->card, gspca_dev->cam.dev_name, sizeof cap->card);
1364         strncpy(cap->bus_info, gspca_dev->dev->bus->bus_name,
1365                 sizeof cap->bus_info);
1366         cap->version = DRIVER_VERSION_NUMBER;
1367         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
1368                           | V4L2_CAP_STREAMING
1369                           | V4L2_CAP_READWRITE;
1370         return 0;
1371 }
1372
1373 static int vidioc_queryctrl(struct file *file, void *priv,
1374                            struct v4l2_queryctrl *q_ctrl)
1375 {
1376         struct gspca_dev *gspca_dev = priv;
1377         int i;
1378
1379         PDEBUG(D_CONF, "queryctrl");
1380         for (i = 0; i < gspca_dev->sd_desc->nctrls; i++) {
1381                 if (q_ctrl->id == gspca_dev->sd_desc->ctrls[i].qctrl.id) {
1382                         memcpy(q_ctrl,
1383                                 &gspca_dev->sd_desc->ctrls[i].qctrl,
1384                                 sizeof *q_ctrl);
1385                         return 0;
1386                 }
1387         }
1388         if (q_ctrl->id >= V4L2_CID_BASE
1389             && q_ctrl->id <= V4L2_CID_LASTP1) {
1390                 q_ctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
1391                 return 0;
1392         }
1393         return -EINVAL;
1394 }
1395
1396 static int vidioc_s_ctrl(struct file *file, void *priv,
1397                          struct v4l2_control *ctrl)
1398 {
1399         struct gspca_dev *gspca_dev = priv;
1400         struct ctrl *ctrls;
1401         int i, ret;
1402
1403         PDEBUG(D_CONF, "set ctrl");
1404         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1405              i < gspca_dev->sd_desc->nctrls;
1406              i++, ctrls++) {
1407                 if (ctrl->id != ctrls->qctrl.id)
1408                         continue;
1409                 if (ctrl->value < ctrls->qctrl.minimum
1410                     && ctrl->value > ctrls->qctrl.maximum)
1411                         return -ERANGE;
1412                 PDEBUG(D_CONF, "set ctrl [%08x] = %d", ctrl->id, ctrl->value);
1413                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1414                         return -ERESTARTSYS;
1415                 ret = ctrls->set(gspca_dev, ctrl->value);
1416                 mutex_unlock(&gspca_dev->usb_lock);
1417                 return ret;
1418         }
1419         return -EINVAL;
1420 }
1421
1422 static int vidioc_g_ctrl(struct file *file, void *priv,
1423                          struct v4l2_control *ctrl)
1424 {
1425         struct gspca_dev *gspca_dev = priv;
1426
1427         struct ctrl *ctrls;
1428         int i, ret;
1429
1430         for (i = 0, ctrls = gspca_dev->sd_desc->ctrls;
1431              i < gspca_dev->sd_desc->nctrls;
1432              i++, ctrls++) {
1433                 if (ctrl->id != ctrls->qctrl.id)
1434                         continue;
1435                 if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1436                         return -ERESTARTSYS;
1437                 ret = ctrls->get(gspca_dev, &ctrl->value);
1438                 mutex_unlock(&gspca_dev->usb_lock);
1439                 return ret;
1440         }
1441         return -EINVAL;
1442 }
1443
1444 static int vidioc_querymenu(struct file *file, void *priv,
1445                             struct v4l2_querymenu *qmenu)
1446 {
1447         struct gspca_dev *gspca_dev = priv;
1448
1449         if (!gspca_dev->sd_desc->querymenu)
1450                 return -EINVAL;
1451         return gspca_dev->sd_desc->querymenu(gspca_dev, qmenu);
1452 }
1453
1454 static int vidioc_enum_input(struct file *file, void *priv,
1455                                 struct v4l2_input *input)
1456 {
1457         struct gspca_dev *gspca_dev = priv;
1458
1459         if (input->index != 0)
1460                 return -EINVAL;
1461         memset(input, 0, sizeof *input);
1462         input->type = V4L2_INPUT_TYPE_CAMERA;
1463         strncpy(input->name, gspca_dev->sd_desc->name,
1464                 sizeof input->name);
1465         return 0;
1466 }
1467
1468 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1469 {
1470         *i = 0;
1471         return 0;
1472 }
1473
1474 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1475 {
1476         if (i > 0)
1477                 return -EINVAL;
1478         return (0);
1479 }
1480
1481 static int vidioc_reqbufs(struct file *file, void *priv,
1482                           struct v4l2_requestbuffers *rb)
1483 {
1484         struct gspca_dev *gspca_dev = priv;
1485         int i, ret = 0;
1486
1487         PDEBUG(D_STREAM, "reqbufs %d", rb->count);
1488         if (rb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1489                 return -EINVAL;
1490         switch (rb->memory) {
1491         case V4L2_MEMORY_MMAP:
1492                 break;
1493         case V4L2_MEMORY_USERPTR:
1494 #ifdef GSPCA_HLP
1495                 if (hlp == 0 || hlp->gspca_dev != gspca_dev)
1496                         break;
1497 #endif
1498                 return -EINVAL;
1499         default:
1500                 return -EINVAL;
1501         }
1502         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1503                 return -ERESTARTSYS;
1504
1505         for (i = 0; i < gspca_dev->nframes; i++) {
1506                 if (gspca_dev->frame[i].vma_use_count) {
1507                         ret = -EBUSY;
1508                         goto out;
1509                 }
1510         }
1511
1512         /* only one file may do capture */
1513         if ((gspca_dev->capt_file != 0 && gspca_dev->capt_file != file)
1514             || gspca_dev->streaming) {
1515                 ret = -EBUSY;
1516                 goto out;
1517         }
1518
1519         if (rb->count == 0) { /* unrequest? */
1520                 frame_free(gspca_dev);
1521                 gspca_dev->capt_file = 0;
1522         } else {
1523                 gspca_dev->memory = rb->memory;
1524                 ret = frame_alloc(gspca_dev, rb->count);
1525                 if (ret == 0) {
1526                         rb->count = gspca_dev->nframes;
1527                         gspca_dev->capt_file = file;
1528                 }
1529         }
1530 out:
1531         mutex_unlock(&gspca_dev->queue_lock);
1532         PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1533         return ret;
1534 }
1535
1536 static int vidioc_querybuf(struct file *file, void *priv,
1537                            struct v4l2_buffer *v4l2_buf)
1538 {
1539         struct gspca_dev *gspca_dev = priv;
1540         struct gspca_frame *frame;
1541
1542         PDEBUG(D_STREAM, "querybuf");
1543         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1544             || v4l2_buf->index < 0
1545             || v4l2_buf->index >= gspca_dev->nframes)
1546                 return -EINVAL;
1547
1548         frame = &gspca_dev->frame[v4l2_buf->index];
1549         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1550         return 0;
1551 }
1552
1553 static int vidioc_streamon(struct file *file, void *priv,
1554                            enum v4l2_buf_type buf_type)
1555 {
1556         struct gspca_dev *gspca_dev = priv;
1557         int ret;
1558
1559         PDEBUG(D_STREAM, "stream on");
1560         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1561                 return -EINVAL;
1562         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1563                 return -ERESTARTSYS;
1564         if (!gspca_dev->present) {
1565                 ret = -ENODEV;
1566                 goto out;
1567         }
1568         if (gspca_dev->nframes == 0) {
1569                 ret = -EINVAL;
1570                 goto out;
1571         }
1572         if (gspca_dev->capt_file != file) {
1573                 ret = -EINVAL;
1574                 goto out;
1575         }
1576         if (!gspca_dev->streaming) {
1577                 ret = gspca_init_transfer(gspca_dev);
1578                 if (ret < 0)
1579                         goto out;
1580         }
1581 #ifdef GSPCA_DEBUG
1582         if (gspca_debug & D_STREAM) {
1583                 PDEBUG_MODE("stream on OK",
1584                         gspca_dev->pixfmt,
1585                         gspca_dev->width,
1586                         gspca_dev->height);
1587         }
1588 #endif
1589         ret = 0;
1590 out:
1591         mutex_unlock(&gspca_dev->queue_lock);
1592         return ret;
1593 }
1594
1595 static int vidioc_streamoff(struct file *file, void *priv,
1596                                 enum v4l2_buf_type buf_type)
1597 {
1598         struct gspca_dev *gspca_dev = priv;
1599         int ret;
1600
1601         PDEBUG(D_STREAM, "stream off");
1602         if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1603                 return -EINVAL;
1604         if (!gspca_dev->streaming)
1605                 return 0;
1606         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1607                 return -ERESTARTSYS;
1608         if (mutex_lock_interruptible(&gspca_dev->usb_lock)) {
1609                 ret = -ERESTARTSYS;
1610                 goto out;
1611         }
1612         if (gspca_dev->capt_file != file) {
1613                 ret = -EINVAL;
1614                 goto out2;
1615         }
1616         gspca_stream_off(gspca_dev);
1617         ret = 0;
1618 out2:
1619         mutex_unlock(&gspca_dev->usb_lock);
1620 out:
1621         mutex_unlock(&gspca_dev->queue_lock);
1622         return ret;
1623 }
1624
1625 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1626                         struct v4l2_jpegcompression *jpegcomp)
1627 {
1628         struct gspca_dev *gspca_dev = priv;
1629         int ret;
1630
1631         if (!gspca_dev->sd_desc->get_jcomp)
1632                 return -EINVAL;
1633         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1634                 return -ERESTARTSYS;
1635         ret = gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1636         mutex_unlock(&gspca_dev->usb_lock);
1637         return ret;
1638 }
1639
1640 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1641                         struct v4l2_jpegcompression *jpegcomp)
1642 {
1643         struct gspca_dev *gspca_dev = priv;
1644         int ret;
1645
1646         if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1647                 return -ERESTARTSYS;
1648         if (!gspca_dev->sd_desc->set_jcomp)
1649                 return -EINVAL;
1650         ret = gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1651         mutex_unlock(&gspca_dev->usb_lock);
1652         return ret;
1653 }
1654
1655 static int vidioc_g_parm(struct file *filp, void *priv,
1656                         struct v4l2_streamparm *parm)
1657 {
1658         struct gspca_dev *gspca_dev = priv;
1659
1660         memset(parm, 0, sizeof parm);
1661         parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1662         parm->parm.capture.readbuffers = gspca_dev->nbufread;
1663         return 0;
1664 }
1665
1666 static int vidioc_s_parm(struct file *filp, void *priv,
1667                         struct v4l2_streamparm *parm)
1668 {
1669         struct gspca_dev *gspca_dev = priv;
1670         int n;
1671
1672         n = parm->parm.capture.readbuffers;
1673         if (n == 0 || n > GSPCA_MAX_FRAMES)
1674                 parm->parm.capture.readbuffers = gspca_dev->nbufread;
1675         else
1676                 gspca_dev->nbufread = n;
1677         return 0;
1678 }
1679
1680 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1681 static int vidiocgmbuf(struct file *file, void *priv,
1682                         struct video_mbuf *mbuf)
1683 {
1684         struct gspca_dev *gspca_dev = file->private_data;
1685         int i;
1686
1687         PDEBUG(D_STREAM, "cgmbuf");
1688         if (gspca_dev->nframes == 0) {
1689                 struct v4l2_requestbuffers rb;
1690                 int ret;
1691                 __u32 pixfmt;
1692                 short width, height;
1693
1694                 /* as the final format is not yet defined, allocate
1695                    buffers with the max size */
1696                 pixfmt = gspca_dev->pixfmt;
1697                 width = gspca_dev->width;
1698                 height = gspca_dev->height;
1699                 gspca_dev->pixfmt = V4L2_PIX_FMT_BGR32;
1700                 gspca_dev->width = 640;
1701                 gspca_dev->height = 480;
1702                 memset(&rb, 0, sizeof rb);
1703                 rb.count = 4;
1704                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1705                 rb.memory = V4L2_MEMORY_MMAP;
1706                 ret = vidioc_reqbufs(file, priv, &rb);
1707                 gspca_dev->pixfmt = pixfmt;
1708                 gspca_dev->width = width;
1709                 gspca_dev->height = height;
1710                 if (ret != 0)
1711                         return ret;
1712         }
1713         mbuf->frames = gspca_dev->nframes;
1714         mbuf->size = gspca_dev->frsz * gspca_dev->nframes;
1715         for (i = 0; i < mbuf->frames; i++)
1716                 mbuf->offsets[i] = gspca_dev->frame[i].v4l2_buf.m.offset;
1717         return 0;
1718 }
1719 #endif
1720
1721 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1722 {
1723         struct gspca_dev *gspca_dev = file->private_data;
1724         struct gspca_frame *frame = 0;
1725         struct page *page;
1726         unsigned long addr, start, size;
1727         int i, ret;
1728 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1729         int compat = 0;
1730 #endif
1731
1732         start = vma->vm_start;
1733         size = vma->vm_end - vma->vm_start;
1734         PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1735
1736         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1737                 return -ERESTARTSYS;
1738         if (!gspca_dev->present) {
1739                 ret = -ENODEV;
1740                 goto out;
1741         }
1742         if (gspca_dev->capt_file != file) {
1743                 ret = -EINVAL;
1744                 goto out;
1745         }
1746
1747         for (i = 0; i < gspca_dev->nframes; ++i) {
1748                 if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1749                         PDEBUG(D_STREAM, "mmap bad memory type");
1750                         break;
1751                 }
1752                 if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1753                                                 == vma->vm_pgoff) {
1754                         frame = &gspca_dev->frame[i];
1755                         break;
1756                 }
1757         }
1758         if (frame == 0) {
1759                 PDEBUG(D_STREAM, "mmap no frame buffer found");
1760                 ret = -EINVAL;
1761                 goto out;
1762         }
1763 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1764         if (i == 0 && size == frame->v4l2_buf.length * gspca_dev->nframes)
1765                 compat = 1;
1766         else
1767 #endif
1768         if (size != frame->v4l2_buf.length) {
1769                 PDEBUG(D_STREAM, "mmap bad size");
1770                 ret = -EINVAL;
1771                 goto out;
1772         }
1773
1774         /*
1775          * - VM_IO marks the area as being a mmaped region for I/O to a
1776          *   device. It also prevents the region from being core dumped.
1777          */
1778         vma->vm_flags |= VM_IO;
1779
1780         addr = (unsigned long) frame->data;
1781         while (size > 0) {
1782                 page = vmalloc_to_page((void *) addr);
1783                 ret = vm_insert_page(vma, start, page);
1784                 if (ret < 0)
1785                         goto out;
1786                 start += PAGE_SIZE;
1787                 addr += PAGE_SIZE;
1788                 size -= PAGE_SIZE;
1789         }
1790
1791         vma->vm_ops = &gspca_vm_ops;
1792         vma->vm_private_data = frame;
1793         gspca_vm_open(vma);
1794 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1795         if (compat) {
1796 /*fixme: ugly*/
1797                 for (i = 1; i < gspca_dev->nframes; ++i)
1798                         gspca_dev->frame[i].v4l2_buf.flags |=
1799                                                 V4L2_BUF_FLAG_MAPPED;
1800         }
1801 #endif
1802         ret = 0;
1803 out:
1804         mutex_unlock(&gspca_dev->queue_lock);
1805         return ret;
1806 }
1807
1808 /*
1809  * wait for a video frame
1810  *
1811  * If a frame is ready, its index is returned.
1812  */
1813 static int frame_wait(struct gspca_dev *gspca_dev,
1814                         int nonblock_ing)
1815 {
1816         struct gspca_frame *frame;
1817         int i, j, ret;
1818
1819         /* if userptr, treat the awaiting URBs */
1820         if (gspca_dev->memory == V4L2_MEMORY_USERPTR)
1821                 isoc_transfer(gspca_dev);
1822
1823         /* check if a frame is ready */
1824         i = gspca_dev->fr_o;
1825         j = gspca_dev->fr_queue[i];
1826         frame = &gspca_dev->frame[j];
1827         if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1828                 goto ok;
1829         if (nonblock_ing)                       /* no frame yet */
1830                 return -EAGAIN;
1831
1832         /* wait till a frame is ready */
1833         for (;;) {
1834                 ret = wait_event_interruptible_timeout(gspca_dev->wq,
1835                                         atomic_read(&gspca_dev->nevent) > 0,
1836                                         msecs_to_jiffies(3000));
1837                 if (ret <= 0) {
1838                         if (ret < 0)
1839                                 return ret;
1840                         return -EIO;
1841                 }
1842                 if (!gspca_dev->streaming || !gspca_dev->present)
1843                         return -EIO;
1844                 if (gspca_dev->memory == V4L2_MEMORY_USERPTR)
1845                         isoc_transfer(gspca_dev);
1846                 i = gspca_dev->fr_o;
1847                 j = gspca_dev->fr_queue[i];
1848                 frame = &gspca_dev->frame[j];
1849                 if (frame->v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1850                         break;
1851         }
1852 ok:
1853         atomic_dec(&gspca_dev->nevent);
1854         gspca_dev->fr_o = (i + 1) % gspca_dev->nframes;
1855         PDEBUG(D_FRAM, "frame wait q:%d i:%d o:%d",
1856                 gspca_dev->fr_q,
1857                 gspca_dev->fr_i,
1858                 gspca_dev->fr_o);
1859
1860         if (gspca_dev->sd_desc->dq_callback)
1861                 gspca_dev->sd_desc->dq_callback(gspca_dev);
1862
1863         return j;
1864 }
1865
1866 /*
1867  * dequeue a video buffer
1868  *
1869  * If nonblock_ing is false, block until a buffer is available.
1870  */
1871 static int vidioc_dqbuf(struct file *file, void *priv,
1872                         struct v4l2_buffer *v4l2_buf)
1873 {
1874         struct gspca_dev *gspca_dev = priv;
1875         struct gspca_frame *frame;
1876         int i, ret;
1877
1878         PDEBUG(D_FRAM, "dqbuf");
1879         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
1880             || (v4l2_buf->memory != V4L2_MEMORY_MMAP
1881                 && v4l2_buf->memory != V4L2_MEMORY_USERPTR))
1882                 return -EINVAL;
1883         if (!gspca_dev->streaming)
1884                 return -EINVAL;
1885         if (gspca_dev->capt_file != file) {
1886                 ret = -EINVAL;
1887                 goto out;
1888         }
1889
1890         /* only one read */
1891         if (mutex_lock_interruptible(&gspca_dev->read_lock))
1892                 return -ERESTARTSYS;
1893
1894         ret = frame_wait(gspca_dev, file->f_flags & O_NONBLOCK);
1895         if (ret < 0)
1896                 goto out;
1897         i = ret;                                /* frame index */
1898         frame = &gspca_dev->frame[i];
1899         frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1900         memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1901         PDEBUG(D_FRAM, "dqbuf %d", i);
1902         ret = 0;
1903 out:
1904         mutex_unlock(&gspca_dev->read_lock);
1905         return ret;
1906 }
1907
1908 /*
1909  * queue a video buffer
1910  *
1911  * Attempting to queue a buffer that has already been
1912  * queued will return -EINVAL.
1913  */
1914 static int vidioc_qbuf(struct file *file, void *priv,
1915                         struct v4l2_buffer *v4l2_buf)
1916 {
1917         struct gspca_dev *gspca_dev = priv;
1918         struct gspca_frame *frame;
1919         int i, index, ret;
1920
1921         PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1922         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1923                 return -EINVAL;
1924
1925         index = v4l2_buf->index;
1926         if ((unsigned) index >= gspca_dev->nframes) {
1927                 PDEBUG(D_FRAM,
1928                         "qbuf idx %d >= %d", index, gspca_dev->nframes);
1929                 return -EINVAL;
1930         }
1931         frame = &gspca_dev->frame[index];
1932
1933         if (v4l2_buf->memory != frame->v4l2_buf.memory) {
1934                 PDEBUG(D_FRAM, "qbuf bad memory type");
1935                 return -EINVAL;
1936         }
1937         if (gspca_dev->capt_file != file)
1938                 return -EINVAL;
1939
1940         if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1941                 return -ERESTARTSYS;
1942
1943         if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1944                 PDEBUG(D_FRAM, "qbuf bad state");
1945                 ret = -EINVAL;
1946                 goto out;
1947         }
1948
1949         frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1950 /*      frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE; */
1951
1952         if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1953                 frame->data = frame->data_end =
1954                                 (unsigned char *) v4l2_buf->m.userptr;
1955                 frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1956                 frame->v4l2_buf.length = v4l2_buf->length;
1957         }
1958
1959         /* put the buffer in the 'queued' queue */
1960         i = gspca_dev->fr_q;
1961         gspca_dev->fr_queue[i] = index;
1962         gspca_dev->fr_q = (i + 1) % gspca_dev->nframes;
1963         PDEBUG(D_FRAM, "qbuf q:%d i:%d o:%d",
1964                 gspca_dev->fr_q,
1965                 gspca_dev->fr_i,
1966                 gspca_dev->fr_o);
1967
1968         v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1969         v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1970         ret = 0;
1971 out:
1972         mutex_unlock(&gspca_dev->queue_lock);
1973         return ret;
1974 }
1975
1976 /*
1977  * allocate the resources for read()
1978  */
1979 static int read_alloc(struct gspca_dev *gspca_dev,
1980                         struct file *file)
1981 {
1982         struct v4l2_buffer v4l2_buf;
1983         int i, ret;
1984
1985         PDEBUG(D_STREAM, "read alloc");
1986         if (gspca_dev->nframes == 0) {
1987                 struct v4l2_requestbuffers rb;
1988
1989                 memset(&rb, 0, sizeof rb);
1990                 rb.count = gspca_dev->nbufread;
1991                 rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1992                 rb.memory = V4L2_MEMORY_MMAP;
1993                 ret = vidioc_reqbufs(file, gspca_dev, &rb);
1994                 if (ret != 0) {
1995                         PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1996                         return ret;
1997                 }
1998                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
1999                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2000                 v4l2_buf.memory = V4L2_MEMORY_MMAP;
2001                 for (i = 0; i < gspca_dev->nbufread; i++) {
2002                         v4l2_buf.index = i;
2003 /*fixme: ugly!*/
2004                         gspca_dev->frame[i].v4l2_buf.flags |=
2005                                                         V4L2_BUF_FLAG_MAPPED;
2006                         ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2007                         if (ret != 0) {
2008                                 PDEBUG(D_STREAM, "read qbuf err: %d", ret);
2009                                 return ret;
2010                         }
2011                 }
2012                 gspca_dev->memory = GSPCA_MEMORY_READ;
2013         }
2014
2015         /* start streaming */
2016         ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
2017         if (ret != 0)
2018                 PDEBUG(D_STREAM, "read streamon err %d", ret);
2019         return ret;
2020 }
2021
2022 static unsigned int dev_poll(struct file *file, poll_table *wait)
2023 {
2024         struct gspca_dev *gspca_dev = file->private_data;
2025         int i, ret;
2026
2027         PDEBUG(D_FRAM, "poll");
2028
2029         poll_wait(file, &gspca_dev->wq, wait);
2030         if (!gspca_dev->present)
2031                 return POLLERR;
2032
2033         /* if not streaming, the user would use read() */
2034         if (!gspca_dev->streaming) {
2035                 if (gspca_dev->memory != GSPCA_MEMORY_NO) {
2036                         ret = POLLERR;          /* not the 1st time */
2037                         goto out;
2038                 }
2039                 ret = read_alloc(gspca_dev, file);
2040                 if (ret != 0) {
2041                         ret = POLLERR;
2042                         goto out;
2043                 }
2044         }
2045
2046         if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0)
2047                 return POLLERR;
2048         if (!gspca_dev->present) {
2049                 ret = POLLERR;
2050                 goto out;
2051         }
2052
2053         /* if not mmap, treat the awaiting URBs */
2054         if (gspca_dev->memory == V4L2_MEMORY_USERPTR
2055             && gspca_dev->capt_file == file)
2056                 isoc_transfer(gspca_dev);
2057
2058         i = gspca_dev->fr_o;
2059         i = gspca_dev->fr_queue[i];
2060         if (gspca_dev->frame[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
2061                 ret = POLLIN | POLLRDNORM;      /* something to read */
2062         else
2063                 ret = 0;
2064 out:
2065         mutex_unlock(&gspca_dev->queue_lock);
2066         return ret;
2067 }
2068
2069 static ssize_t dev_read(struct file *file, char __user *data,
2070                     size_t count, loff_t *ppos)
2071 {
2072         struct gspca_dev *gspca_dev = file->private_data;
2073         struct gspca_frame *frame;
2074         struct v4l2_buffer v4l2_buf;
2075         struct timeval timestamp;
2076         int i, ret, ret2;
2077
2078         PDEBUG(D_FRAM, "read (%d)", count);
2079         if (!gspca_dev->present)
2080                 return -ENODEV;
2081         switch (gspca_dev->memory) {
2082         case GSPCA_MEMORY_NO:                   /* first time */
2083                 ret = read_alloc(gspca_dev, file);
2084                 if (ret != 0)
2085                         return ret;
2086                 break;
2087         case GSPCA_MEMORY_READ:
2088                 if (gspca_dev->capt_file != file)
2089                         return -EINVAL;
2090                 break;
2091         default:
2092                 return -EINVAL;
2093         }
2094
2095         /* get a frame */
2096         jiffies_to_timeval(get_jiffies_64(), &timestamp);
2097         timestamp.tv_sec--;
2098         for (i = 0; i < 2; i++) {
2099                 memset(&v4l2_buf, 0, sizeof v4l2_buf);
2100                 v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2101                 v4l2_buf.memory = V4L2_MEMORY_MMAP;
2102                 ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
2103                 if (ret != 0) {
2104                         PDEBUG(D_STREAM, "read dqbuf err %d", ret);
2105                         return ret;
2106                 }
2107
2108                 /* if the process slept for more than 1 second,
2109                  * get a brand new frame */
2110                 frame = &gspca_dev->frame[v4l2_buf.index];
2111                 if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
2112                         break;
2113                 ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2114                 if (ret != 0) {
2115                         PDEBUG(D_STREAM, "read qbuf err %d", ret);
2116                         return ret;
2117                 }
2118         }
2119
2120         /* copy the frame */
2121         if (count < frame->v4l2_buf.bytesused) {
2122                 PDEBUG(D_STREAM, "read bad count: %d < %d",
2123                         count, frame->v4l2_buf.bytesused);
2124 /*fixme: special errno?*/
2125                 ret = -EINVAL;
2126                 goto out;
2127         }
2128         count = frame->v4l2_buf.bytesused;
2129         ret = copy_to_user(data, frame->data, count);
2130         if (ret != 0) {
2131                 PDEBUG(D_ERR|D_STREAM,
2132                         "read cp to user lack %d / %d", ret, count);
2133                 ret = -EFAULT;
2134                 goto out;
2135         }
2136         ret = count;
2137 out:
2138         /* in each case, requeue the buffer */
2139         ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
2140         if (ret2 != 0)
2141                 return ret2;
2142         return ret;
2143 }
2144
2145 static void dev_release(struct video_device *vfd)
2146 {
2147         /* nothing */
2148 }
2149
2150 static struct file_operations dev_fops = {
2151         .owner = THIS_MODULE,
2152         .open = dev_open,
2153         .release = dev_close,
2154         .read = dev_read,
2155         .mmap = dev_mmap,
2156         .ioctl = video_ioctl2,
2157         .llseek = no_llseek,
2158         .poll   = dev_poll,
2159 };
2160
2161 static struct video_device gspca_template = {
2162         .name = "gspca main driver",
2163         .type = VID_TYPE_CAPTURE,
2164         .fops = &dev_fops,
2165         .release = dev_release,         /* mandatory */
2166         .minor = -1,
2167         .vidioc_querycap        = vidioc_querycap,
2168         .vidioc_dqbuf           = vidioc_dqbuf,
2169         .vidioc_qbuf            = vidioc_qbuf,
2170         .vidioc_enum_fmt_cap    = vidioc_enum_fmt_cap,
2171         .vidioc_try_fmt_cap     = vidioc_try_fmt_cap,
2172         .vidioc_g_fmt_cap       = vidioc_g_fmt_cap,
2173         .vidioc_s_fmt_cap       = vidioc_s_fmt_cap,
2174         .vidioc_streamon        = vidioc_streamon,
2175         .vidioc_queryctrl       = vidioc_queryctrl,
2176         .vidioc_g_ctrl          = vidioc_g_ctrl,
2177         .vidioc_s_ctrl          = vidioc_s_ctrl,
2178         .vidioc_querymenu       = vidioc_querymenu,
2179         .vidioc_enum_input      = vidioc_enum_input,
2180         .vidioc_g_input         = vidioc_g_input,
2181         .vidioc_s_input         = vidioc_s_input,
2182         .vidioc_reqbufs         = vidioc_reqbufs,
2183         .vidioc_querybuf        = vidioc_querybuf,
2184         .vidioc_streamoff       = vidioc_streamoff,
2185         .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
2186         .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
2187         .vidioc_g_parm          = vidioc_g_parm,
2188         .vidioc_s_parm          = vidioc_s_parm,
2189 #ifdef CONFIG_VIDEO_V4L1_COMPAT
2190         .vidiocgmbuf          = vidiocgmbuf,
2191 #endif
2192 };
2193
2194 /*
2195  * probe and create a new gspca device
2196  *
2197  * This function must be called by the sub-driver when it is
2198  * called for probing a new device.
2199  */
2200 int gspca_dev_probe(struct usb_interface *intf,
2201                 const struct usb_device_id *id,
2202                 const struct sd_desc *sd_desc,
2203                 int dev_size,
2204                 struct module *module)
2205 {
2206         struct usb_interface_descriptor *interface;
2207         struct gspca_dev *gspca_dev;
2208         struct usb_device *dev = interface_to_usbdev(intf);
2209         int ret;
2210         __u16 vendor;
2211         __u16 product;
2212
2213         vendor = id->idVendor;
2214         product = id->idProduct;
2215         PDEBUG(D_PROBE, "probing %04x:%04x", vendor, product);
2216
2217         /* we don't handle multi-config cameras */
2218         if (dev->descriptor.bNumConfigurations != 1)
2219                 return -ENODEV;
2220         interface = &intf->cur_altsetting->desc;
2221         if (interface->bInterfaceNumber > 0)
2222                 return -ENODEV;
2223
2224         /* create the device */
2225         if (dev_size < sizeof *gspca_dev)
2226                 dev_size = sizeof *gspca_dev;
2227         gspca_dev = kzalloc(dev_size, GFP_KERNEL);
2228         if (gspca_dev == NULL) {
2229                 err("couldn't kzalloc gspca struct");
2230                 return -EIO;
2231         }
2232         gspca_dev->dev = dev;
2233         gspca_dev->iface = interface->bInterfaceNumber;
2234         gspca_dev->nbalt = intf->num_altsetting;
2235         gspca_dev->sd_desc = sd_desc;
2236 /*      gspca_dev->users = 0;                   (done by kzalloc) */
2237         gspca_dev->nbufread = 2;
2238
2239         /* configure the subdriver */
2240         ret = gspca_dev->sd_desc->config(gspca_dev, id);
2241         if (ret < 0)
2242                 goto out;
2243         ret = gspca_set_alt0(gspca_dev);
2244         if (ret < 0)
2245                 goto out;
2246         gspca_set_default_mode(gspca_dev);
2247
2248         mutex_init(&gspca_dev->usb_lock);
2249         mutex_init(&gspca_dev->read_lock);
2250         mutex_init(&gspca_dev->queue_lock);
2251         init_waitqueue_head(&gspca_dev->wq);
2252
2253         /* init video stuff */
2254         memcpy(&gspca_dev->vdev, &gspca_template, sizeof gspca_template);
2255         gspca_dev->vdev.dev = &dev->dev;
2256         memcpy(&gspca_dev->fops, &dev_fops, sizeof gspca_dev->fops);
2257         gspca_dev->vdev.fops = &gspca_dev->fops;
2258         gspca_dev->fops.owner = module;         /* module protection */
2259         ret = video_register_device(&gspca_dev->vdev,
2260                                   VFL_TYPE_GRABBER,
2261                                   video_nr);
2262         if (ret < 0) {
2263                 err("video_register_device err %d", ret);
2264                 goto out;
2265         }
2266
2267         gspca_dev->present = 1;
2268         usb_set_intfdata(intf, gspca_dev);
2269         PDEBUG(D_PROBE, "probe ok");
2270         return 0;
2271 out:
2272         kfree(gspca_dev);
2273         return ret;
2274 }
2275 EXPORT_SYMBOL(gspca_dev_probe);
2276
2277 /*
2278  * USB disconnection
2279  *
2280  * This function must be called by the sub-driver
2281  * when the device disconnects, after the specific resources are freed.
2282  */
2283 void gspca_disconnect(struct usb_interface *intf)
2284 {
2285         struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2286
2287         if (!gspca_dev)
2288                 return;
2289         gspca_dev->present = 0;
2290         mutex_lock(&gspca_dev->queue_lock);
2291         mutex_lock(&gspca_dev->usb_lock);
2292         gspca_dev->streaming = 0;
2293         destroy_urbs(gspca_dev);
2294         mutex_unlock(&gspca_dev->usb_lock);
2295         mutex_unlock(&gspca_dev->queue_lock);
2296         while (gspca_dev->users != 0) {         /* wait until fully closed */
2297                 atomic_inc(&gspca_dev->nevent);
2298                 wake_up_interruptible(&gspca_dev->wq);  /* wake processes */
2299                 schedule();
2300         }
2301 /* We don't want people trying to open up the device */
2302         video_unregister_device(&gspca_dev->vdev);
2303 /* Free the memory */
2304         kfree(gspca_dev);
2305         PDEBUG(D_PROBE, "disconnect complete");
2306 }
2307 EXPORT_SYMBOL(gspca_disconnect);
2308
2309 /* -- module insert / remove -- */
2310 static int __init gspca_init(void)
2311 {
2312 #ifdef GSPCA_HLP
2313         int ret;
2314
2315         /* create /dev/gspca_hlp */
2316         ret = misc_register(&hlp_device);
2317         if (ret < 0)
2318                 err("misc_register err %d", ret);
2319         start_hlp();            /* try to start the helper process */
2320 #endif
2321         info("main v%s registered", version);
2322         return 0;
2323 }
2324 static void __exit gspca_exit(void)
2325 {
2326 #ifdef GSPCA_HLP
2327         misc_deregister(&hlp_device);
2328 #endif
2329         info("main deregistered");
2330 }
2331
2332 module_init(gspca_init);
2333 module_exit(gspca_exit);
2334
2335 module_param_named(debug, gspca_debug, int, 0644);
2336 MODULE_PARM_DESC(debug,
2337                 "Debug (bit) 0x01:error 0x02:probe 0x04:config"
2338                 " 0x08:stream 0x10:frame 0x20:packet 0x40:USBin 0x80:USBout"
2339                 " 0x0100: v4l2");
2340
2341 module_param(comp_fac, int, 0644);
2342 MODULE_PARM_DESC(comp_fac,
2343                 "Buffer size ratio when compressed in percent");