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