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