xref: /openbmc/linux/drivers/media/usb/gspca/gspca.c (revision 77a87824)
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 		v4l2_get_timestamp(&frame->v4l2_buf.timestamp);
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 	frsz = gspca_dev->pixfmt.sizeimage;
508 	PDEBUG(D_STREAM, "frame alloc frsz: %d", frsz);
509 	frsz = PAGE_ALIGN(frsz);
510 	if (count >= GSPCA_MAX_FRAMES)
511 		count = GSPCA_MAX_FRAMES - 1;
512 	gspca_dev->frbuf = vmalloc_32(frsz * count);
513 	if (!gspca_dev->frbuf) {
514 		pr_err("frame alloc failed\n");
515 		return -ENOMEM;
516 	}
517 	gspca_dev->capt_file = file;
518 	gspca_dev->memory = memory;
519 	gspca_dev->frsz = frsz;
520 	gspca_dev->nframes = count;
521 	for (i = 0; i < count; i++) {
522 		frame = &gspca_dev->frame[i];
523 		frame->v4l2_buf.index = i;
524 		frame->v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
525 		frame->v4l2_buf.flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
526 		frame->v4l2_buf.field = V4L2_FIELD_NONE;
527 		frame->v4l2_buf.length = frsz;
528 		frame->v4l2_buf.memory = memory;
529 		frame->v4l2_buf.sequence = 0;
530 		frame->data = gspca_dev->frbuf + i * frsz;
531 		frame->v4l2_buf.m.offset = i * frsz;
532 	}
533 	atomic_set(&gspca_dev->fr_q, 0);
534 	atomic_set(&gspca_dev->fr_i, 0);
535 	gspca_dev->fr_o = 0;
536 	return 0;
537 }
538 
539 static void frame_free(struct gspca_dev *gspca_dev)
540 {
541 	int i;
542 
543 	PDEBUG(D_STREAM, "frame free");
544 	if (gspca_dev->frbuf != NULL) {
545 		vfree(gspca_dev->frbuf);
546 		gspca_dev->frbuf = NULL;
547 		for (i = 0; i < gspca_dev->nframes; i++)
548 			gspca_dev->frame[i].data = NULL;
549 	}
550 	gspca_dev->nframes = 0;
551 	gspca_dev->frsz = 0;
552 	gspca_dev->capt_file = NULL;
553 	gspca_dev->memory = GSPCA_MEMORY_NO;
554 }
555 
556 static void destroy_urbs(struct gspca_dev *gspca_dev)
557 {
558 	struct urb *urb;
559 	unsigned int i;
560 
561 	PDEBUG(D_STREAM, "kill transfer");
562 	for (i = 0; i < MAX_NURBS; i++) {
563 		urb = gspca_dev->urb[i];
564 		if (urb == NULL)
565 			break;
566 
567 		gspca_dev->urb[i] = NULL;
568 		usb_kill_urb(urb);
569 		usb_free_coherent(gspca_dev->dev,
570 				  urb->transfer_buffer_length,
571 				  urb->transfer_buffer,
572 				  urb->transfer_dma);
573 		usb_free_urb(urb);
574 	}
575 }
576 
577 static int gspca_set_alt0(struct gspca_dev *gspca_dev)
578 {
579 	int ret;
580 
581 	if (gspca_dev->alt == 0)
582 		return 0;
583 	ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
584 	if (ret < 0)
585 		pr_err("set alt 0 err %d\n", ret);
586 	return ret;
587 }
588 
589 /* Note: both the queue and the usb locks should be held when calling this */
590 static void gspca_stream_off(struct gspca_dev *gspca_dev)
591 {
592 	gspca_dev->streaming = 0;
593 	gspca_dev->usb_err = 0;
594 	if (gspca_dev->sd_desc->stopN)
595 		gspca_dev->sd_desc->stopN(gspca_dev);
596 	destroy_urbs(gspca_dev);
597 	gspca_input_destroy_urb(gspca_dev);
598 	gspca_set_alt0(gspca_dev);
599 	gspca_input_create_urb(gspca_dev);
600 	if (gspca_dev->sd_desc->stop0)
601 		gspca_dev->sd_desc->stop0(gspca_dev);
602 	PDEBUG(D_STREAM, "stream off OK");
603 }
604 
605 /*
606  * look for an input transfer endpoint in an alternate setting.
607  *
608  * If xfer_ep is invalid, return the first valid ep found, otherwise
609  * look for exactly the ep with address equal to xfer_ep.
610  */
611 static struct usb_host_endpoint *alt_xfer(struct usb_host_interface *alt,
612 					  int xfer, int xfer_ep)
613 {
614 	struct usb_host_endpoint *ep;
615 	int i, attr;
616 
617 	for (i = 0; i < alt->desc.bNumEndpoints; i++) {
618 		ep = &alt->endpoint[i];
619 		attr = ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
620 		if (attr == xfer
621 		    && ep->desc.wMaxPacketSize != 0
622 		    && usb_endpoint_dir_in(&ep->desc)
623 		    && (xfer_ep < 0 || ep->desc.bEndpointAddress == xfer_ep))
624 			return ep;
625 	}
626 	return NULL;
627 }
628 
629 /* compute the minimum bandwidth for the current transfer */
630 static u32 which_bandwidth(struct gspca_dev *gspca_dev)
631 {
632 	u32 bandwidth;
633 
634 	/* get the (max) image size */
635 	bandwidth = gspca_dev->pixfmt.sizeimage;
636 
637 	/* if the image is compressed, estimate its mean size */
638 	if (!gspca_dev->cam.needs_full_bandwidth &&
639 	    bandwidth < gspca_dev->pixfmt.width *
640 				gspca_dev->pixfmt.height)
641 		bandwidth = bandwidth * 3 / 8;	/* 0.375 */
642 
643 	/* estimate the frame rate */
644 	if (gspca_dev->sd_desc->get_streamparm) {
645 		struct v4l2_streamparm parm;
646 
647 		gspca_dev->sd_desc->get_streamparm(gspca_dev, &parm);
648 		bandwidth *= parm.parm.capture.timeperframe.denominator;
649 		bandwidth /= parm.parm.capture.timeperframe.numerator;
650 	} else {
651 
652 		/* don't hope more than 15 fps with USB 1.1 and
653 		 * image resolution >= 640x480 */
654 		if (gspca_dev->pixfmt.width >= 640
655 		 && gspca_dev->dev->speed == USB_SPEED_FULL)
656 			bandwidth *= 15;		/* 15 fps */
657 		else
658 			bandwidth *= 30;		/* 30 fps */
659 	}
660 
661 	PDEBUG(D_STREAM, "min bandwidth: %d", bandwidth);
662 	return bandwidth;
663 }
664 
665 /* endpoint table */
666 #define MAX_ALT 16
667 struct ep_tb_s {
668 	u32 alt;
669 	u32 bandwidth;
670 };
671 
672 /*
673  * build the table of the endpoints
674  * and compute the minimum bandwidth for the image transfer
675  */
676 static int build_isoc_ep_tb(struct gspca_dev *gspca_dev,
677 			struct usb_interface *intf,
678 			struct ep_tb_s *ep_tb)
679 {
680 	struct usb_host_endpoint *ep;
681 	int i, j, nbalt, psize, found;
682 	u32 bandwidth, last_bw;
683 
684 	nbalt = intf->num_altsetting;
685 	if (nbalt > MAX_ALT)
686 		nbalt = MAX_ALT;	/* fixme: should warn */
687 
688 	/* build the endpoint table */
689 	i = 0;
690 	last_bw = 0;
691 	for (;;) {
692 		ep_tb->bandwidth = 2000 * 2000 * 120;
693 		found = 0;
694 		for (j = 0; j < nbalt; j++) {
695 			ep = alt_xfer(&intf->altsetting[j],
696 				      USB_ENDPOINT_XFER_ISOC,
697 				      gspca_dev->xfer_ep);
698 			if (ep == NULL)
699 				continue;
700 			if (ep->desc.bInterval == 0) {
701 				pr_err("alt %d iso endp with 0 interval\n", j);
702 				continue;
703 			}
704 			psize = le16_to_cpu(ep->desc.wMaxPacketSize);
705 			psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
706 			bandwidth = psize * 1000;
707 			if (gspca_dev->dev->speed == USB_SPEED_HIGH
708 			 || gspca_dev->dev->speed >= USB_SPEED_SUPER)
709 				bandwidth *= 8;
710 			bandwidth /= 1 << (ep->desc.bInterval - 1);
711 			if (bandwidth <= last_bw)
712 				continue;
713 			if (bandwidth < ep_tb->bandwidth) {
714 				ep_tb->bandwidth = bandwidth;
715 				ep_tb->alt = j;
716 				found = 1;
717 			}
718 		}
719 		if (!found)
720 			break;
721 		PDEBUG(D_STREAM, "alt %d bandwidth %d",
722 				ep_tb->alt, ep_tb->bandwidth);
723 		last_bw = ep_tb->bandwidth;
724 		i++;
725 		ep_tb++;
726 	}
727 
728 	/*
729 	 * If the camera:
730 	 * has a usb audio class interface (a built in usb mic); and
731 	 * is a usb 1 full speed device; and
732 	 * uses the max full speed iso bandwidth; and
733 	 * and has more than 1 alt setting
734 	 * then skip the highest alt setting to spare bandwidth for the mic
735 	 */
736 	if (gspca_dev->audio &&
737 			gspca_dev->dev->speed == USB_SPEED_FULL &&
738 			last_bw >= 1000000 &&
739 			i > 1) {
740 		PDEBUG(D_STREAM, "dev has usb audio, skipping highest alt");
741 		i--;
742 		ep_tb--;
743 	}
744 
745 	/* get the requested bandwidth and start at the highest atlsetting */
746 	bandwidth = which_bandwidth(gspca_dev);
747 	ep_tb--;
748 	while (i > 1) {
749 		ep_tb--;
750 		if (ep_tb->bandwidth < bandwidth)
751 			break;
752 		i--;
753 	}
754 	return i;
755 }
756 
757 /*
758  * create the URBs for image transfer
759  */
760 static int create_urbs(struct gspca_dev *gspca_dev,
761 			struct usb_host_endpoint *ep)
762 {
763 	struct urb *urb;
764 	int n, nurbs, i, psize, npkt, bsize;
765 
766 	/* calculate the packet size and the number of packets */
767 	psize = le16_to_cpu(ep->desc.wMaxPacketSize);
768 
769 	if (!gspca_dev->cam.bulk) {		/* isoc */
770 
771 		/* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
772 		if (gspca_dev->pkt_size == 0)
773 			psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
774 		else
775 			psize = gspca_dev->pkt_size;
776 		npkt = gspca_dev->cam.npkt;
777 		if (npkt == 0)
778 			npkt = 32;		/* default value */
779 		bsize = psize * npkt;
780 		PDEBUG(D_STREAM,
781 			"isoc %d pkts size %d = bsize:%d",
782 			npkt, psize, bsize);
783 		nurbs = DEF_NURBS;
784 	} else {				/* bulk */
785 		npkt = 0;
786 		bsize = gspca_dev->cam.bulk_size;
787 		if (bsize == 0)
788 			bsize = psize;
789 		PDEBUG(D_STREAM, "bulk bsize:%d", bsize);
790 		if (gspca_dev->cam.bulk_nurbs != 0)
791 			nurbs = gspca_dev->cam.bulk_nurbs;
792 		else
793 			nurbs = 1;
794 	}
795 
796 	for (n = 0; n < nurbs; n++) {
797 		urb = usb_alloc_urb(npkt, GFP_KERNEL);
798 		if (!urb) {
799 			pr_err("usb_alloc_urb failed\n");
800 			return -ENOMEM;
801 		}
802 		gspca_dev->urb[n] = urb;
803 		urb->transfer_buffer = usb_alloc_coherent(gspca_dev->dev,
804 						bsize,
805 						GFP_KERNEL,
806 						&urb->transfer_dma);
807 
808 		if (urb->transfer_buffer == NULL) {
809 			pr_err("usb_alloc_coherent failed\n");
810 			return -ENOMEM;
811 		}
812 		urb->dev = gspca_dev->dev;
813 		urb->context = gspca_dev;
814 		urb->transfer_buffer_length = bsize;
815 		if (npkt != 0) {		/* ISOC */
816 			urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
817 						    ep->desc.bEndpointAddress);
818 			urb->transfer_flags = URB_ISO_ASAP
819 					| URB_NO_TRANSFER_DMA_MAP;
820 			urb->interval = 1 << (ep->desc.bInterval - 1);
821 			urb->complete = isoc_irq;
822 			urb->number_of_packets = npkt;
823 			for (i = 0; i < npkt; i++) {
824 				urb->iso_frame_desc[i].length = psize;
825 				urb->iso_frame_desc[i].offset = psize * i;
826 			}
827 		} else {		/* bulk */
828 			urb->pipe = usb_rcvbulkpipe(gspca_dev->dev,
829 						ep->desc.bEndpointAddress);
830 			urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
831 			urb->complete = bulk_irq;
832 		}
833 	}
834 	return 0;
835 }
836 
837 /*
838  * start the USB transfer
839  */
840 static int gspca_init_transfer(struct gspca_dev *gspca_dev)
841 {
842 	struct usb_interface *intf;
843 	struct usb_host_endpoint *ep;
844 	struct urb *urb;
845 	struct ep_tb_s ep_tb[MAX_ALT];
846 	int n, ret, xfer, alt, alt_idx;
847 
848 	/* reset the streaming variables */
849 	gspca_dev->image = NULL;
850 	gspca_dev->image_len = 0;
851 	gspca_dev->last_packet_type = DISCARD_PACKET;
852 	gspca_dev->sequence = 0;
853 
854 	gspca_dev->usb_err = 0;
855 
856 	/* do the specific subdriver stuff before endpoint selection */
857 	intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
858 	gspca_dev->alt = gspca_dev->cam.bulk ? intf->num_altsetting : 0;
859 	if (gspca_dev->sd_desc->isoc_init) {
860 		ret = gspca_dev->sd_desc->isoc_init(gspca_dev);
861 		if (ret < 0)
862 			return ret;
863 	}
864 	xfer = gspca_dev->cam.bulk ? USB_ENDPOINT_XFER_BULK
865 				   : USB_ENDPOINT_XFER_ISOC;
866 
867 	/* if bulk or the subdriver forced an altsetting, get the endpoint */
868 	if (gspca_dev->alt != 0) {
869 		gspca_dev->alt--;	/* (previous version compatibility) */
870 		ep = alt_xfer(&intf->altsetting[gspca_dev->alt], xfer,
871 			      gspca_dev->xfer_ep);
872 		if (ep == NULL) {
873 			pr_err("bad altsetting %d\n", gspca_dev->alt);
874 			return -EIO;
875 		}
876 		ep_tb[0].alt = gspca_dev->alt;
877 		alt_idx = 1;
878 	} else {
879 		/* else, compute the minimum bandwidth
880 		 * and build the endpoint table */
881 		alt_idx = build_isoc_ep_tb(gspca_dev, intf, ep_tb);
882 		if (alt_idx <= 0) {
883 			pr_err("no transfer endpoint found\n");
884 			return -EIO;
885 		}
886 	}
887 
888 	/* set the highest alternate setting and
889 	 * loop until urb submit succeeds */
890 	gspca_input_destroy_urb(gspca_dev);
891 
892 	gspca_dev->alt = ep_tb[--alt_idx].alt;
893 	alt = -1;
894 	for (;;) {
895 		if (alt != gspca_dev->alt) {
896 			alt = gspca_dev->alt;
897 			if (intf->num_altsetting > 1) {
898 				ret = usb_set_interface(gspca_dev->dev,
899 							gspca_dev->iface,
900 							alt);
901 				if (ret < 0) {
902 					if (ret == -ENOSPC)
903 						goto retry; /*fixme: ugly*/
904 					pr_err("set alt %d err %d\n", alt, ret);
905 					goto out;
906 				}
907 			}
908 		}
909 		if (!gspca_dev->cam.no_urb_create) {
910 			PDEBUG(D_STREAM, "init transfer alt %d", alt);
911 			ret = create_urbs(gspca_dev,
912 				alt_xfer(&intf->altsetting[alt], xfer,
913 					 gspca_dev->xfer_ep));
914 			if (ret < 0) {
915 				destroy_urbs(gspca_dev);
916 				goto out;
917 			}
918 		}
919 
920 		/* clear the bulk endpoint */
921 		if (gspca_dev->cam.bulk)
922 			usb_clear_halt(gspca_dev->dev,
923 					gspca_dev->urb[0]->pipe);
924 
925 		/* start the cam */
926 		ret = gspca_dev->sd_desc->start(gspca_dev);
927 		if (ret < 0) {
928 			destroy_urbs(gspca_dev);
929 			goto out;
930 		}
931 		gspca_dev->streaming = 1;
932 		v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
933 
934 		/* some bulk transfers are started by the subdriver */
935 		if (gspca_dev->cam.bulk && gspca_dev->cam.bulk_nurbs == 0)
936 			break;
937 
938 		/* submit the URBs */
939 		for (n = 0; n < MAX_NURBS; n++) {
940 			urb = gspca_dev->urb[n];
941 			if (urb == NULL)
942 				break;
943 			ret = usb_submit_urb(urb, GFP_KERNEL);
944 			if (ret < 0)
945 				break;
946 		}
947 		if (ret >= 0)
948 			break;			/* transfer is started */
949 
950 		/* something when wrong
951 		 * stop the webcam and free the transfer resources */
952 		gspca_stream_off(gspca_dev);
953 		if (ret != -ENOSPC) {
954 			pr_err("usb_submit_urb alt %d err %d\n",
955 			       gspca_dev->alt, ret);
956 			goto out;
957 		}
958 
959 		/* the bandwidth is not wide enough
960 		 * negotiate or try a lower alternate setting */
961 retry:
962 		PERR("alt %d - bandwidth not wide enough, trying again", alt);
963 		msleep(20);	/* wait for kill complete */
964 		if (gspca_dev->sd_desc->isoc_nego) {
965 			ret = gspca_dev->sd_desc->isoc_nego(gspca_dev);
966 			if (ret < 0)
967 				goto out;
968 		} else {
969 			if (alt_idx <= 0) {
970 				pr_err("no transfer endpoint found\n");
971 				ret = -EIO;
972 				goto out;
973 			}
974 			gspca_dev->alt = ep_tb[--alt_idx].alt;
975 		}
976 	}
977 out:
978 	gspca_input_create_urb(gspca_dev);
979 	return ret;
980 }
981 
982 static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
983 {
984 	int i;
985 
986 	i = gspca_dev->cam.nmodes - 1;	/* take the highest mode */
987 	gspca_dev->curr_mode = i;
988 	gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i];
989 
990 	/* does nothing if ctrl_handler == NULL */
991 	v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
992 }
993 
994 static int wxh_to_mode(struct gspca_dev *gspca_dev,
995 			int width, int height)
996 {
997 	int i;
998 
999 	for (i = 0; i < gspca_dev->cam.nmodes; i++) {
1000 		if (width == gspca_dev->cam.cam_mode[i].width
1001 		    && height == gspca_dev->cam.cam_mode[i].height)
1002 			return i;
1003 	}
1004 	return -EINVAL;
1005 }
1006 
1007 static int wxh_to_nearest_mode(struct gspca_dev *gspca_dev,
1008 			int width, int height)
1009 {
1010 	int i;
1011 
1012 	for (i = gspca_dev->cam.nmodes; --i > 0; ) {
1013 		if (width >= gspca_dev->cam.cam_mode[i].width
1014 		    && height >= gspca_dev->cam.cam_mode[i].height)
1015 			break;
1016 	}
1017 	return i;
1018 }
1019 
1020 /*
1021  * search a mode with the right pixel format
1022  */
1023 static int gspca_get_mode(struct gspca_dev *gspca_dev,
1024 			int mode,
1025 			int pixfmt)
1026 {
1027 	int modeU, modeD;
1028 
1029 	modeU = modeD = mode;
1030 	while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
1031 		if (--modeD >= 0) {
1032 			if (gspca_dev->cam.cam_mode[modeD].pixelformat
1033 								== pixfmt)
1034 				return modeD;
1035 		}
1036 		if (++modeU < gspca_dev->cam.nmodes) {
1037 			if (gspca_dev->cam.cam_mode[modeU].pixelformat
1038 								== pixfmt)
1039 				return modeU;
1040 		}
1041 	}
1042 	return -EINVAL;
1043 }
1044 
1045 #ifdef CONFIG_VIDEO_ADV_DEBUG
1046 static int vidioc_g_chip_info(struct file *file, void *priv,
1047 				struct v4l2_dbg_chip_info *chip)
1048 {
1049 	struct gspca_dev *gspca_dev = video_drvdata(file);
1050 
1051 	gspca_dev->usb_err = 0;
1052 	if (gspca_dev->sd_desc->get_chip_info)
1053 		return gspca_dev->sd_desc->get_chip_info(gspca_dev, chip);
1054 	return chip->match.addr ? -EINVAL : 0;
1055 }
1056 
1057 static int vidioc_g_register(struct file *file, void *priv,
1058 		struct v4l2_dbg_register *reg)
1059 {
1060 	struct gspca_dev *gspca_dev = video_drvdata(file);
1061 
1062 	gspca_dev->usb_err = 0;
1063 	return gspca_dev->sd_desc->get_register(gspca_dev, reg);
1064 }
1065 
1066 static int vidioc_s_register(struct file *file, void *priv,
1067 		const struct v4l2_dbg_register *reg)
1068 {
1069 	struct gspca_dev *gspca_dev = video_drvdata(file);
1070 
1071 	gspca_dev->usb_err = 0;
1072 	return gspca_dev->sd_desc->set_register(gspca_dev, reg);
1073 }
1074 #endif
1075 
1076 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1077 				struct v4l2_fmtdesc *fmtdesc)
1078 {
1079 	struct gspca_dev *gspca_dev = video_drvdata(file);
1080 	int i, j, index;
1081 	__u32 fmt_tb[8];
1082 
1083 	/* give an index to each format */
1084 	index = 0;
1085 	j = 0;
1086 	for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
1087 		fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
1088 		j = 0;
1089 		for (;;) {
1090 			if (fmt_tb[j] == fmt_tb[index])
1091 				break;
1092 			j++;
1093 		}
1094 		if (j == index) {
1095 			if (fmtdesc->index == index)
1096 				break;		/* new format */
1097 			index++;
1098 			if (index >= ARRAY_SIZE(fmt_tb))
1099 				return -EINVAL;
1100 		}
1101 	}
1102 	if (i < 0)
1103 		return -EINVAL;		/* no more format */
1104 
1105 	fmtdesc->pixelformat = fmt_tb[index];
1106 	if (gspca_dev->cam.cam_mode[i].sizeimage <
1107 			gspca_dev->cam.cam_mode[i].width *
1108 				gspca_dev->cam.cam_mode[i].height)
1109 		fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1110 	fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
1111 	fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
1112 	fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
1113 	fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
1114 	fmtdesc->description[4] = '\0';
1115 	return 0;
1116 }
1117 
1118 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1119 			    struct v4l2_format *fmt)
1120 {
1121 	struct gspca_dev *gspca_dev = video_drvdata(file);
1122 
1123 	fmt->fmt.pix = gspca_dev->pixfmt;
1124 	/* some drivers use priv internally, zero it before giving it back to
1125 	   the core */
1126 	fmt->fmt.pix.priv = 0;
1127 	return 0;
1128 }
1129 
1130 static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
1131 			struct v4l2_format *fmt)
1132 {
1133 	int w, h, mode, mode2;
1134 
1135 	w = fmt->fmt.pix.width;
1136 	h = fmt->fmt.pix.height;
1137 
1138 	PDEBUG_MODE(gspca_dev, D_CONF, "try fmt cap",
1139 		    fmt->fmt.pix.pixelformat, w, h);
1140 
1141 	/* search the nearest mode for width and height */
1142 	mode = wxh_to_nearest_mode(gspca_dev, w, h);
1143 
1144 	/* OK if right palette */
1145 	if (gspca_dev->cam.cam_mode[mode].pixelformat
1146 						!= fmt->fmt.pix.pixelformat) {
1147 
1148 		/* else, search the closest mode with the same pixel format */
1149 		mode2 = gspca_get_mode(gspca_dev, mode,
1150 					fmt->fmt.pix.pixelformat);
1151 		if (mode2 >= 0)
1152 			mode = mode2;
1153 	}
1154 	fmt->fmt.pix = gspca_dev->cam.cam_mode[mode];
1155 	if (gspca_dev->sd_desc->try_fmt) {
1156 		/* pass original resolution to subdriver try_fmt */
1157 		fmt->fmt.pix.width = w;
1158 		fmt->fmt.pix.height = h;
1159 		gspca_dev->sd_desc->try_fmt(gspca_dev, fmt);
1160 	}
1161 	/* some drivers use priv internally, zero it before giving it back to
1162 	   the core */
1163 	fmt->fmt.pix.priv = 0;
1164 	return mode;			/* used when s_fmt */
1165 }
1166 
1167 static int vidioc_try_fmt_vid_cap(struct file *file,
1168 			      void *priv,
1169 			      struct v4l2_format *fmt)
1170 {
1171 	struct gspca_dev *gspca_dev = video_drvdata(file);
1172 	int ret;
1173 
1174 	ret = try_fmt_vid_cap(gspca_dev, fmt);
1175 	if (ret < 0)
1176 		return ret;
1177 	return 0;
1178 }
1179 
1180 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1181 			    struct v4l2_format *fmt)
1182 {
1183 	struct gspca_dev *gspca_dev = video_drvdata(file);
1184 	int ret;
1185 
1186 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1187 		return -ERESTARTSYS;
1188 
1189 	ret = try_fmt_vid_cap(gspca_dev, fmt);
1190 	if (ret < 0)
1191 		goto out;
1192 
1193 	if (gspca_dev->nframes != 0
1194 	    && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
1195 		ret = -EINVAL;
1196 		goto out;
1197 	}
1198 
1199 	if (gspca_dev->streaming) {
1200 		ret = -EBUSY;
1201 		goto out;
1202 	}
1203 	gspca_dev->curr_mode = ret;
1204 	if (gspca_dev->sd_desc->try_fmt)
1205 		/* subdriver try_fmt can modify format parameters */
1206 		gspca_dev->pixfmt = fmt->fmt.pix;
1207 	else
1208 		gspca_dev->pixfmt = gspca_dev->cam.cam_mode[ret];
1209 
1210 	ret = 0;
1211 out:
1212 	mutex_unlock(&gspca_dev->queue_lock);
1213 	return ret;
1214 }
1215 
1216 static int vidioc_enum_framesizes(struct file *file, void *priv,
1217 				  struct v4l2_frmsizeenum *fsize)
1218 {
1219 	struct gspca_dev *gspca_dev = video_drvdata(file);
1220 	int i;
1221 	__u32 index = 0;
1222 
1223 	if (gspca_dev->sd_desc->enum_framesizes)
1224 		return gspca_dev->sd_desc->enum_framesizes(gspca_dev, fsize);
1225 
1226 	for (i = 0; i < gspca_dev->cam.nmodes; i++) {
1227 		if (fsize->pixel_format !=
1228 				gspca_dev->cam.cam_mode[i].pixelformat)
1229 			continue;
1230 
1231 		if (fsize->index == index) {
1232 			fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1233 			fsize->discrete.width =
1234 				gspca_dev->cam.cam_mode[i].width;
1235 			fsize->discrete.height =
1236 				gspca_dev->cam.cam_mode[i].height;
1237 			return 0;
1238 		}
1239 		index++;
1240 	}
1241 
1242 	return -EINVAL;
1243 }
1244 
1245 static int vidioc_enum_frameintervals(struct file *filp, void *priv,
1246 				      struct v4l2_frmivalenum *fival)
1247 {
1248 	struct gspca_dev *gspca_dev = video_drvdata(filp);
1249 	int mode;
1250 	__u32 i;
1251 
1252 	mode = wxh_to_mode(gspca_dev, fival->width, fival->height);
1253 	if (mode < 0)
1254 		return -EINVAL;
1255 
1256 	if (gspca_dev->cam.mode_framerates == NULL ||
1257 			gspca_dev->cam.mode_framerates[mode].nrates == 0)
1258 		return -EINVAL;
1259 
1260 	if (fival->pixel_format !=
1261 			gspca_dev->cam.cam_mode[mode].pixelformat)
1262 		return -EINVAL;
1263 
1264 	for (i = 0; i < gspca_dev->cam.mode_framerates[mode].nrates; i++) {
1265 		if (fival->index == i) {
1266 			fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1267 			fival->discrete.numerator = 1;
1268 			fival->discrete.denominator =
1269 				gspca_dev->cam.mode_framerates[mode].rates[i];
1270 			return 0;
1271 		}
1272 	}
1273 
1274 	return -EINVAL;
1275 }
1276 
1277 static void gspca_release(struct v4l2_device *v4l2_device)
1278 {
1279 	struct gspca_dev *gspca_dev =
1280 		container_of(v4l2_device, struct gspca_dev, v4l2_dev);
1281 
1282 	v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
1283 	v4l2_device_unregister(&gspca_dev->v4l2_dev);
1284 	kfree(gspca_dev->usb_buf);
1285 	kfree(gspca_dev);
1286 }
1287 
1288 static int dev_open(struct file *file)
1289 {
1290 	struct gspca_dev *gspca_dev = video_drvdata(file);
1291 	int ret;
1292 
1293 	PDEBUG(D_STREAM, "[%s] open", current->comm);
1294 
1295 	/* protect the subdriver against rmmod */
1296 	if (!try_module_get(gspca_dev->module))
1297 		return -ENODEV;
1298 
1299 	ret = v4l2_fh_open(file);
1300 	if (ret)
1301 		module_put(gspca_dev->module);
1302 	return ret;
1303 }
1304 
1305 static int dev_close(struct file *file)
1306 {
1307 	struct gspca_dev *gspca_dev = video_drvdata(file);
1308 
1309 	PDEBUG(D_STREAM, "[%s] close", current->comm);
1310 
1311 	/* Needed for gspca_stream_off, always lock before queue_lock! */
1312 	if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1313 		return -ERESTARTSYS;
1314 
1315 	if (mutex_lock_interruptible(&gspca_dev->queue_lock)) {
1316 		mutex_unlock(&gspca_dev->usb_lock);
1317 		return -ERESTARTSYS;
1318 	}
1319 
1320 	/* if the file did the capture, free the streaming resources */
1321 	if (gspca_dev->capt_file == file) {
1322 		if (gspca_dev->streaming)
1323 			gspca_stream_off(gspca_dev);
1324 		frame_free(gspca_dev);
1325 	}
1326 	module_put(gspca_dev->module);
1327 	mutex_unlock(&gspca_dev->queue_lock);
1328 	mutex_unlock(&gspca_dev->usb_lock);
1329 
1330 	PDEBUG(D_STREAM, "close done");
1331 
1332 	return v4l2_fh_release(file);
1333 }
1334 
1335 static int vidioc_querycap(struct file *file, void  *priv,
1336 			   struct v4l2_capability *cap)
1337 {
1338 	struct gspca_dev *gspca_dev = video_drvdata(file);
1339 
1340 	strlcpy((char *) cap->driver, gspca_dev->sd_desc->name,
1341 			sizeof cap->driver);
1342 	if (gspca_dev->dev->product != NULL) {
1343 		strlcpy((char *) cap->card, gspca_dev->dev->product,
1344 			sizeof cap->card);
1345 	} else {
1346 		snprintf((char *) cap->card, sizeof cap->card,
1347 			"USB Camera (%04x:%04x)",
1348 			le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
1349 			le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
1350 	}
1351 	usb_make_path(gspca_dev->dev, (char *) cap->bus_info,
1352 			sizeof(cap->bus_info));
1353 	cap->device_caps = V4L2_CAP_VIDEO_CAPTURE
1354 			  | V4L2_CAP_STREAMING
1355 			  | V4L2_CAP_READWRITE;
1356 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
1357 	return 0;
1358 }
1359 
1360 static int vidioc_enum_input(struct file *file, void *priv,
1361 				struct v4l2_input *input)
1362 {
1363 	struct gspca_dev *gspca_dev = video_drvdata(file);
1364 
1365 	if (input->index != 0)
1366 		return -EINVAL;
1367 	input->type = V4L2_INPUT_TYPE_CAMERA;
1368 	input->status = gspca_dev->cam.input_flags;
1369 	strlcpy(input->name, gspca_dev->sd_desc->name,
1370 		sizeof input->name);
1371 	return 0;
1372 }
1373 
1374 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1375 {
1376 	*i = 0;
1377 	return 0;
1378 }
1379 
1380 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1381 {
1382 	if (i > 0)
1383 		return -EINVAL;
1384 	return (0);
1385 }
1386 
1387 static int vidioc_reqbufs(struct file *file, void *priv,
1388 			  struct v4l2_requestbuffers *rb)
1389 {
1390 	struct gspca_dev *gspca_dev = video_drvdata(file);
1391 	int i, ret = 0, streaming;
1392 
1393 	i = rb->memory;			/* (avoid compilation warning) */
1394 	switch (i) {
1395 	case GSPCA_MEMORY_READ:			/* (internal call) */
1396 	case V4L2_MEMORY_MMAP:
1397 	case V4L2_MEMORY_USERPTR:
1398 		break;
1399 	default:
1400 		return -EINVAL;
1401 	}
1402 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1403 		return -ERESTARTSYS;
1404 
1405 	if (gspca_dev->memory != GSPCA_MEMORY_NO
1406 	    && gspca_dev->memory != GSPCA_MEMORY_READ
1407 	    && gspca_dev->memory != rb->memory) {
1408 		ret = -EBUSY;
1409 		goto out;
1410 	}
1411 
1412 	/* only one file may do the capture */
1413 	if (gspca_dev->capt_file != NULL
1414 	    && gspca_dev->capt_file != file) {
1415 		ret = -EBUSY;
1416 		goto out;
1417 	}
1418 
1419 	/* if allocated, the buffers must not be mapped */
1420 	for (i = 0; i < gspca_dev->nframes; i++) {
1421 		if (gspca_dev->frame[i].vma_use_count) {
1422 			ret = -EBUSY;
1423 			goto out;
1424 		}
1425 	}
1426 
1427 	/* stop streaming */
1428 	streaming = gspca_dev->streaming;
1429 	if (streaming) {
1430 		gspca_stream_off(gspca_dev);
1431 
1432 		/* Don't restart the stream when switching from read
1433 		 * to mmap mode */
1434 		if (gspca_dev->memory == GSPCA_MEMORY_READ)
1435 			streaming = 0;
1436 	}
1437 
1438 	/* free the previous allocated buffers, if any */
1439 	if (gspca_dev->nframes != 0)
1440 		frame_free(gspca_dev);
1441 	if (rb->count == 0)			/* unrequest */
1442 		goto out;
1443 	ret = frame_alloc(gspca_dev, file, rb->memory, rb->count);
1444 	if (ret == 0) {
1445 		rb->count = gspca_dev->nframes;
1446 		if (streaming)
1447 			ret = gspca_init_transfer(gspca_dev);
1448 	}
1449 out:
1450 	mutex_unlock(&gspca_dev->queue_lock);
1451 	PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1452 	return ret;
1453 }
1454 
1455 static int vidioc_querybuf(struct file *file, void *priv,
1456 			   struct v4l2_buffer *v4l2_buf)
1457 {
1458 	struct gspca_dev *gspca_dev = video_drvdata(file);
1459 	struct gspca_frame *frame;
1460 
1461 	if (v4l2_buf->index >= gspca_dev->nframes)
1462 		return -EINVAL;
1463 
1464 	frame = &gspca_dev->frame[v4l2_buf->index];
1465 	memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1466 	return 0;
1467 }
1468 
1469 static int vidioc_streamon(struct file *file, void *priv,
1470 			   enum v4l2_buf_type buf_type)
1471 {
1472 	struct gspca_dev *gspca_dev = video_drvdata(file);
1473 	int ret;
1474 
1475 	if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1476 		return -EINVAL;
1477 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1478 		return -ERESTARTSYS;
1479 
1480 	/* check the capture file */
1481 	if (gspca_dev->capt_file != file) {
1482 		ret = -EBUSY;
1483 		goto out;
1484 	}
1485 
1486 	if (gspca_dev->nframes == 0
1487 	    || !(gspca_dev->frame[0].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)) {
1488 		ret = -EINVAL;
1489 		goto out;
1490 	}
1491 	if (!gspca_dev->streaming) {
1492 		ret = gspca_init_transfer(gspca_dev);
1493 		if (ret < 0)
1494 			goto out;
1495 	}
1496 	PDEBUG_MODE(gspca_dev, D_STREAM, "stream on OK",
1497 		    gspca_dev->pixfmt.pixelformat,
1498 		    gspca_dev->pixfmt.width, gspca_dev->pixfmt.height);
1499 	ret = 0;
1500 out:
1501 	mutex_unlock(&gspca_dev->queue_lock);
1502 	return ret;
1503 }
1504 
1505 static int vidioc_streamoff(struct file *file, void *priv,
1506 				enum v4l2_buf_type buf_type)
1507 {
1508 	struct gspca_dev *gspca_dev = video_drvdata(file);
1509 	int i, ret;
1510 
1511 	if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1512 		return -EINVAL;
1513 
1514 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1515 		return -ERESTARTSYS;
1516 
1517 	if (!gspca_dev->streaming) {
1518 		ret = 0;
1519 		goto out;
1520 	}
1521 
1522 	/* check the capture file */
1523 	if (gspca_dev->capt_file != file) {
1524 		ret = -EBUSY;
1525 		goto out;
1526 	}
1527 
1528 	/* stop streaming */
1529 	gspca_stream_off(gspca_dev);
1530 	/* In case another thread is waiting in dqbuf */
1531 	wake_up_interruptible(&gspca_dev->wq);
1532 
1533 	/* empty the transfer queues */
1534 	for (i = 0; i < gspca_dev->nframes; i++)
1535 		gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1536 	atomic_set(&gspca_dev->fr_q, 0);
1537 	atomic_set(&gspca_dev->fr_i, 0);
1538 	gspca_dev->fr_o = 0;
1539 	ret = 0;
1540 out:
1541 	mutex_unlock(&gspca_dev->queue_lock);
1542 	return ret;
1543 }
1544 
1545 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1546 			struct v4l2_jpegcompression *jpegcomp)
1547 {
1548 	struct gspca_dev *gspca_dev = video_drvdata(file);
1549 
1550 	gspca_dev->usb_err = 0;
1551 	return gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1552 }
1553 
1554 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1555 			const struct v4l2_jpegcompression *jpegcomp)
1556 {
1557 	struct gspca_dev *gspca_dev = video_drvdata(file);
1558 
1559 	gspca_dev->usb_err = 0;
1560 	return gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1561 }
1562 
1563 static int vidioc_g_parm(struct file *filp, void *priv,
1564 			struct v4l2_streamparm *parm)
1565 {
1566 	struct gspca_dev *gspca_dev = video_drvdata(filp);
1567 
1568 	parm->parm.capture.readbuffers = gspca_dev->nbufread;
1569 
1570 	if (gspca_dev->sd_desc->get_streamparm) {
1571 		gspca_dev->usb_err = 0;
1572 		gspca_dev->sd_desc->get_streamparm(gspca_dev, parm);
1573 		return gspca_dev->usb_err;
1574 	}
1575 	return 0;
1576 }
1577 
1578 static int vidioc_s_parm(struct file *filp, void *priv,
1579 			struct v4l2_streamparm *parm)
1580 {
1581 	struct gspca_dev *gspca_dev = video_drvdata(filp);
1582 	unsigned int n;
1583 
1584 	n = parm->parm.capture.readbuffers;
1585 	if (n == 0 || n >= GSPCA_MAX_FRAMES)
1586 		parm->parm.capture.readbuffers = gspca_dev->nbufread;
1587 	else
1588 		gspca_dev->nbufread = n;
1589 
1590 	if (gspca_dev->sd_desc->set_streamparm) {
1591 		gspca_dev->usb_err = 0;
1592 		gspca_dev->sd_desc->set_streamparm(gspca_dev, parm);
1593 		return gspca_dev->usb_err;
1594 	}
1595 
1596 	return 0;
1597 }
1598 
1599 static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1600 {
1601 	struct gspca_dev *gspca_dev = video_drvdata(file);
1602 	struct gspca_frame *frame;
1603 	struct page *page;
1604 	unsigned long addr, start, size;
1605 	int i, ret;
1606 
1607 	start = vma->vm_start;
1608 	size = vma->vm_end - vma->vm_start;
1609 	PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1610 
1611 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1612 		return -ERESTARTSYS;
1613 	if (gspca_dev->capt_file != file) {
1614 		ret = -EINVAL;
1615 		goto out;
1616 	}
1617 
1618 	frame = NULL;
1619 	for (i = 0; i < gspca_dev->nframes; ++i) {
1620 		if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1621 			PDEBUG(D_STREAM, "mmap bad memory type");
1622 			break;
1623 		}
1624 		if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1625 						== vma->vm_pgoff) {
1626 			frame = &gspca_dev->frame[i];
1627 			break;
1628 		}
1629 	}
1630 	if (frame == NULL) {
1631 		PDEBUG(D_STREAM, "mmap no frame buffer found");
1632 		ret = -EINVAL;
1633 		goto out;
1634 	}
1635 	if (size != frame->v4l2_buf.length) {
1636 		PDEBUG(D_STREAM, "mmap bad size");
1637 		ret = -EINVAL;
1638 		goto out;
1639 	}
1640 
1641 	/*
1642 	 * - VM_IO marks the area as being a mmaped region for I/O to a
1643 	 *   device. It also prevents the region from being core dumped.
1644 	 */
1645 	vma->vm_flags |= VM_IO;
1646 
1647 	addr = (unsigned long) frame->data;
1648 	while (size > 0) {
1649 		page = vmalloc_to_page((void *) addr);
1650 		ret = vm_insert_page(vma, start, page);
1651 		if (ret < 0)
1652 			goto out;
1653 		start += PAGE_SIZE;
1654 		addr += PAGE_SIZE;
1655 		size -= PAGE_SIZE;
1656 	}
1657 
1658 	vma->vm_ops = &gspca_vm_ops;
1659 	vma->vm_private_data = frame;
1660 	gspca_vm_open(vma);
1661 	ret = 0;
1662 out:
1663 	mutex_unlock(&gspca_dev->queue_lock);
1664 	return ret;
1665 }
1666 
1667 static int frame_ready_nolock(struct gspca_dev *gspca_dev, struct file *file,
1668 				enum v4l2_memory memory)
1669 {
1670 	if (!gspca_dev->present)
1671 		return -ENODEV;
1672 	if (gspca_dev->capt_file != file || gspca_dev->memory != memory ||
1673 			!gspca_dev->streaming)
1674 		return -EINVAL;
1675 
1676 	/* check if a frame is ready */
1677 	return gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i);
1678 }
1679 
1680 static int frame_ready(struct gspca_dev *gspca_dev, struct file *file,
1681 			enum v4l2_memory memory)
1682 {
1683 	int ret;
1684 
1685 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1686 		return -ERESTARTSYS;
1687 	ret = frame_ready_nolock(gspca_dev, file, memory);
1688 	mutex_unlock(&gspca_dev->queue_lock);
1689 	return ret;
1690 }
1691 
1692 /*
1693  * dequeue a video buffer
1694  *
1695  * If nonblock_ing is false, block until a buffer is available.
1696  */
1697 static int vidioc_dqbuf(struct file *file, void *priv,
1698 			struct v4l2_buffer *v4l2_buf)
1699 {
1700 	struct gspca_dev *gspca_dev = video_drvdata(file);
1701 	struct gspca_frame *frame;
1702 	int i, j, ret;
1703 
1704 	PDEBUG(D_FRAM, "dqbuf");
1705 
1706 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1707 		return -ERESTARTSYS;
1708 
1709 	for (;;) {
1710 		ret = frame_ready_nolock(gspca_dev, file, v4l2_buf->memory);
1711 		if (ret < 0)
1712 			goto out;
1713 		if (ret > 0)
1714 			break;
1715 
1716 		mutex_unlock(&gspca_dev->queue_lock);
1717 
1718 		if (file->f_flags & O_NONBLOCK)
1719 			return -EAGAIN;
1720 
1721 		/* wait till a frame is ready */
1722 		ret = wait_event_interruptible_timeout(gspca_dev->wq,
1723 			frame_ready(gspca_dev, file, v4l2_buf->memory),
1724 			msecs_to_jiffies(3000));
1725 		if (ret < 0)
1726 			return ret;
1727 		if (ret == 0)
1728 			return -EIO;
1729 
1730 		if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1731 			return -ERESTARTSYS;
1732 	}
1733 
1734 	i = gspca_dev->fr_o;
1735 	j = gspca_dev->fr_queue[i];
1736 	frame = &gspca_dev->frame[j];
1737 
1738 	gspca_dev->fr_o = (i + 1) % GSPCA_MAX_FRAMES;
1739 
1740 	frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1741 	memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1742 	PDEBUG(D_FRAM, "dqbuf %d", j);
1743 	ret = 0;
1744 
1745 	if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1746 		if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1747 				 frame->data,
1748 				 frame->v4l2_buf.bytesused)) {
1749 			PERR("dqbuf cp to user failed");
1750 			ret = -EFAULT;
1751 		}
1752 	}
1753 out:
1754 	mutex_unlock(&gspca_dev->queue_lock);
1755 
1756 	if (ret == 0 && gspca_dev->sd_desc->dq_callback) {
1757 		mutex_lock(&gspca_dev->usb_lock);
1758 		gspca_dev->usb_err = 0;
1759 		if (gspca_dev->present)
1760 			gspca_dev->sd_desc->dq_callback(gspca_dev);
1761 		mutex_unlock(&gspca_dev->usb_lock);
1762 	}
1763 
1764 	return ret;
1765 }
1766 
1767 /*
1768  * queue a video buffer
1769  *
1770  * Attempting to queue a buffer that has already been
1771  * queued will return -EINVAL.
1772  */
1773 static int vidioc_qbuf(struct file *file, void *priv,
1774 			struct v4l2_buffer *v4l2_buf)
1775 {
1776 	struct gspca_dev *gspca_dev = video_drvdata(file);
1777 	struct gspca_frame *frame;
1778 	int i, index, ret;
1779 
1780 	PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1781 
1782 	if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1783 		return -ERESTARTSYS;
1784 
1785 	index = v4l2_buf->index;
1786 	if ((unsigned) index >= gspca_dev->nframes) {
1787 		PDEBUG(D_FRAM,
1788 			"qbuf idx %d >= %d", index, gspca_dev->nframes);
1789 		ret = -EINVAL;
1790 		goto out;
1791 	}
1792 	if (v4l2_buf->memory != gspca_dev->memory) {
1793 		PDEBUG(D_FRAM, "qbuf bad memory type");
1794 		ret = -EINVAL;
1795 		goto out;
1796 	}
1797 
1798 	frame = &gspca_dev->frame[index];
1799 	if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1800 		PDEBUG(D_FRAM, "qbuf bad state");
1801 		ret = -EINVAL;
1802 		goto out;
1803 	}
1804 
1805 	frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1806 
1807 	if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1808 		frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1809 		frame->v4l2_buf.length = v4l2_buf->length;
1810 	}
1811 
1812 	/* put the buffer in the 'queued' queue */
1813 	i = atomic_read(&gspca_dev->fr_q);
1814 	gspca_dev->fr_queue[i] = index;
1815 	atomic_set(&gspca_dev->fr_q, (i + 1) % GSPCA_MAX_FRAMES);
1816 
1817 	v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1818 	v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1819 	ret = 0;
1820 out:
1821 	mutex_unlock(&gspca_dev->queue_lock);
1822 	return ret;
1823 }
1824 
1825 /*
1826  * allocate the resources for read()
1827  */
1828 static int read_alloc(struct gspca_dev *gspca_dev,
1829 			struct file *file)
1830 {
1831 	struct v4l2_buffer v4l2_buf;
1832 	int i, ret;
1833 
1834 	PDEBUG(D_STREAM, "read alloc");
1835 
1836 	if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1837 		return -ERESTARTSYS;
1838 
1839 	if (gspca_dev->nframes == 0) {
1840 		struct v4l2_requestbuffers rb;
1841 
1842 		memset(&rb, 0, sizeof rb);
1843 		rb.count = gspca_dev->nbufread;
1844 		rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1845 		rb.memory = GSPCA_MEMORY_READ;
1846 		ret = vidioc_reqbufs(file, gspca_dev, &rb);
1847 		if (ret != 0) {
1848 			PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1849 			goto out;
1850 		}
1851 		memset(&v4l2_buf, 0, sizeof v4l2_buf);
1852 		v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1853 		v4l2_buf.memory = GSPCA_MEMORY_READ;
1854 		for (i = 0; i < gspca_dev->nbufread; i++) {
1855 			v4l2_buf.index = i;
1856 			ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1857 			if (ret != 0) {
1858 				PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1859 				goto out;
1860 			}
1861 		}
1862 	}
1863 
1864 	/* start streaming */
1865 	ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1866 	if (ret != 0)
1867 		PDEBUG(D_STREAM, "read streamon err %d", ret);
1868 out:
1869 	mutex_unlock(&gspca_dev->usb_lock);
1870 	return ret;
1871 }
1872 
1873 static unsigned int dev_poll(struct file *file, poll_table *wait)
1874 {
1875 	struct gspca_dev *gspca_dev = video_drvdata(file);
1876 	unsigned long req_events = poll_requested_events(wait);
1877 	int ret = 0;
1878 
1879 	PDEBUG(D_FRAM, "poll");
1880 
1881 	if (req_events & POLLPRI)
1882 		ret |= v4l2_ctrl_poll(file, wait);
1883 
1884 	if (req_events & (POLLIN | POLLRDNORM)) {
1885 		/* if reqbufs is not done, the user would use read() */
1886 		if (gspca_dev->memory == GSPCA_MEMORY_NO) {
1887 			if (read_alloc(gspca_dev, file) != 0) {
1888 				ret |= POLLERR;
1889 				goto out;
1890 			}
1891 		}
1892 
1893 		poll_wait(file, &gspca_dev->wq, wait);
1894 
1895 		/* check if an image has been received */
1896 		if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0) {
1897 			ret |= POLLERR;
1898 			goto out;
1899 		}
1900 		if (gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i))
1901 			ret |= POLLIN | POLLRDNORM;
1902 		mutex_unlock(&gspca_dev->queue_lock);
1903 	}
1904 
1905 out:
1906 	if (!gspca_dev->present)
1907 		ret |= POLLHUP;
1908 
1909 	return ret;
1910 }
1911 
1912 static ssize_t dev_read(struct file *file, char __user *data,
1913 		    size_t count, loff_t *ppos)
1914 {
1915 	struct gspca_dev *gspca_dev = video_drvdata(file);
1916 	struct gspca_frame *frame;
1917 	struct v4l2_buffer v4l2_buf;
1918 	struct timeval timestamp;
1919 	int n, ret, ret2;
1920 
1921 	PDEBUG(D_FRAM, "read (%zd)", count);
1922 	if (gspca_dev->memory == GSPCA_MEMORY_NO) { /* first time ? */
1923 		ret = read_alloc(gspca_dev, file);
1924 		if (ret != 0)
1925 			return ret;
1926 	}
1927 
1928 	/* get a frame */
1929 	v4l2_get_timestamp(&timestamp);
1930 	timestamp.tv_sec--;
1931 	n = 2;
1932 	for (;;) {
1933 		memset(&v4l2_buf, 0, sizeof v4l2_buf);
1934 		v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1935 		v4l2_buf.memory = GSPCA_MEMORY_READ;
1936 		ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1937 		if (ret != 0) {
1938 			PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1939 			return ret;
1940 		}
1941 
1942 		/* if the process slept for more than 1 second,
1943 		 * get a newer frame */
1944 		frame = &gspca_dev->frame[v4l2_buf.index];
1945 		if (--n < 0)
1946 			break;			/* avoid infinite loop */
1947 		if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1948 			break;
1949 		ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1950 		if (ret != 0) {
1951 			PDEBUG(D_STREAM, "read qbuf err %d", ret);
1952 			return ret;
1953 		}
1954 	}
1955 
1956 	/* copy the frame */
1957 	if (count > frame->v4l2_buf.bytesused)
1958 		count = frame->v4l2_buf.bytesused;
1959 	ret = copy_to_user(data, frame->data, count);
1960 	if (ret != 0) {
1961 		PERR("read cp to user lack %d / %zd", ret, count);
1962 		ret = -EFAULT;
1963 		goto out;
1964 	}
1965 	ret = count;
1966 out:
1967 	/* in each case, requeue the buffer */
1968 	ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1969 	if (ret2 != 0)
1970 		return ret2;
1971 	return ret;
1972 }
1973 
1974 static struct v4l2_file_operations dev_fops = {
1975 	.owner = THIS_MODULE,
1976 	.open = dev_open,
1977 	.release = dev_close,
1978 	.read = dev_read,
1979 	.mmap = dev_mmap,
1980 	.unlocked_ioctl = video_ioctl2,
1981 	.poll	= dev_poll,
1982 };
1983 
1984 static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1985 	.vidioc_querycap	= vidioc_querycap,
1986 	.vidioc_dqbuf		= vidioc_dqbuf,
1987 	.vidioc_qbuf		= vidioc_qbuf,
1988 	.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1989 	.vidioc_try_fmt_vid_cap	= vidioc_try_fmt_vid_cap,
1990 	.vidioc_g_fmt_vid_cap	= vidioc_g_fmt_vid_cap,
1991 	.vidioc_s_fmt_vid_cap	= vidioc_s_fmt_vid_cap,
1992 	.vidioc_streamon	= vidioc_streamon,
1993 	.vidioc_enum_input	= vidioc_enum_input,
1994 	.vidioc_g_input		= vidioc_g_input,
1995 	.vidioc_s_input		= vidioc_s_input,
1996 	.vidioc_reqbufs		= vidioc_reqbufs,
1997 	.vidioc_querybuf	= vidioc_querybuf,
1998 	.vidioc_streamoff	= vidioc_streamoff,
1999 	.vidioc_g_jpegcomp	= vidioc_g_jpegcomp,
2000 	.vidioc_s_jpegcomp	= vidioc_s_jpegcomp,
2001 	.vidioc_g_parm		= vidioc_g_parm,
2002 	.vidioc_s_parm		= vidioc_s_parm,
2003 	.vidioc_enum_framesizes = vidioc_enum_framesizes,
2004 	.vidioc_enum_frameintervals = vidioc_enum_frameintervals,
2005 #ifdef CONFIG_VIDEO_ADV_DEBUG
2006 	.vidioc_g_chip_info	= vidioc_g_chip_info,
2007 	.vidioc_g_register	= vidioc_g_register,
2008 	.vidioc_s_register	= vidioc_s_register,
2009 #endif
2010 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2011 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2012 };
2013 
2014 static const struct video_device gspca_template = {
2015 	.name = "gspca main driver",
2016 	.fops = &dev_fops,
2017 	.ioctl_ops = &dev_ioctl_ops,
2018 	.release = video_device_release_empty, /* We use v4l2_dev.release */
2019 };
2020 
2021 /*
2022  * probe and create a new gspca device
2023  *
2024  * This function must be called by the sub-driver when it is
2025  * called for probing a new device.
2026  */
2027 int gspca_dev_probe2(struct usb_interface *intf,
2028 		const struct usb_device_id *id,
2029 		const struct sd_desc *sd_desc,
2030 		int dev_size,
2031 		struct module *module)
2032 {
2033 	struct gspca_dev *gspca_dev;
2034 	struct usb_device *dev = interface_to_usbdev(intf);
2035 	int ret;
2036 
2037 	pr_info("%s-" GSPCA_VERSION " probing %04x:%04x\n",
2038 		sd_desc->name, id->idVendor, id->idProduct);
2039 
2040 	/* create the device */
2041 	if (dev_size < sizeof *gspca_dev)
2042 		dev_size = sizeof *gspca_dev;
2043 	gspca_dev = kzalloc(dev_size, GFP_KERNEL);
2044 	if (!gspca_dev) {
2045 		pr_err("couldn't kzalloc gspca struct\n");
2046 		return -ENOMEM;
2047 	}
2048 	gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
2049 	if (!gspca_dev->usb_buf) {
2050 		pr_err("out of memory\n");
2051 		ret = -ENOMEM;
2052 		goto out;
2053 	}
2054 	gspca_dev->dev = dev;
2055 	gspca_dev->iface = intf->cur_altsetting->desc.bInterfaceNumber;
2056 	gspca_dev->xfer_ep = -1;
2057 
2058 	/* check if any audio device */
2059 	if (dev->actconfig->desc.bNumInterfaces != 1) {
2060 		int i;
2061 		struct usb_interface *intf2;
2062 
2063 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
2064 			intf2 = dev->actconfig->interface[i];
2065 			if (intf2 != NULL
2066 			 && intf2->altsetting != NULL
2067 			 && intf2->altsetting->desc.bInterfaceClass ==
2068 					 USB_CLASS_AUDIO) {
2069 				gspca_dev->audio = 1;
2070 				break;
2071 			}
2072 		}
2073 	}
2074 
2075 	gspca_dev->v4l2_dev.release = gspca_release;
2076 	ret = v4l2_device_register(&intf->dev, &gspca_dev->v4l2_dev);
2077 	if (ret)
2078 		goto out;
2079 	gspca_dev->sd_desc = sd_desc;
2080 	gspca_dev->nbufread = 2;
2081 	gspca_dev->empty_packet = -1;	/* don't check the empty packets */
2082 	gspca_dev->vdev = gspca_template;
2083 	gspca_dev->vdev.v4l2_dev = &gspca_dev->v4l2_dev;
2084 	video_set_drvdata(&gspca_dev->vdev, gspca_dev);
2085 	gspca_dev->module = module;
2086 	gspca_dev->present = 1;
2087 
2088 	mutex_init(&gspca_dev->usb_lock);
2089 	gspca_dev->vdev.lock = &gspca_dev->usb_lock;
2090 	mutex_init(&gspca_dev->queue_lock);
2091 	init_waitqueue_head(&gspca_dev->wq);
2092 
2093 	/* configure the subdriver and initialize the USB device */
2094 	ret = sd_desc->config(gspca_dev, id);
2095 	if (ret < 0)
2096 		goto out;
2097 	ret = sd_desc->init(gspca_dev);
2098 	if (ret < 0)
2099 		goto out;
2100 	if (sd_desc->init_controls)
2101 		ret = sd_desc->init_controls(gspca_dev);
2102 	if (ret < 0)
2103 		goto out;
2104 	gspca_set_default_mode(gspca_dev);
2105 
2106 	ret = gspca_input_connect(gspca_dev);
2107 	if (ret)
2108 		goto out;
2109 
2110 	/*
2111 	 * Don't take usb_lock for these ioctls. This improves latency if
2112 	 * usb_lock is taken for a long time, e.g. when changing a control
2113 	 * value, and a new frame is ready to be dequeued.
2114 	 */
2115 	v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_DQBUF);
2116 	v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QBUF);
2117 	v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QUERYBUF);
2118 #ifdef CONFIG_VIDEO_ADV_DEBUG
2119 	if (!gspca_dev->sd_desc->get_register)
2120 		v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_G_REGISTER);
2121 	if (!gspca_dev->sd_desc->set_register)
2122 		v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_S_REGISTER);
2123 #endif
2124 	if (!gspca_dev->sd_desc->get_jcomp)
2125 		v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_G_JPEGCOMP);
2126 	if (!gspca_dev->sd_desc->set_jcomp)
2127 		v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_S_JPEGCOMP);
2128 
2129 	/* init video stuff */
2130 	ret = video_register_device(&gspca_dev->vdev,
2131 				  VFL_TYPE_GRABBER,
2132 				  -1);
2133 	if (ret < 0) {
2134 		pr_err("video_register_device err %d\n", ret);
2135 		goto out;
2136 	}
2137 
2138 	usb_set_intfdata(intf, gspca_dev);
2139 	PDEBUG(D_PROBE, "%s created", video_device_node_name(&gspca_dev->vdev));
2140 
2141 	gspca_input_create_urb(gspca_dev);
2142 
2143 	return 0;
2144 out:
2145 #if IS_ENABLED(CONFIG_INPUT)
2146 	if (gspca_dev->input_dev)
2147 		input_unregister_device(gspca_dev->input_dev);
2148 #endif
2149 	v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
2150 	kfree(gspca_dev->usb_buf);
2151 	kfree(gspca_dev);
2152 	return ret;
2153 }
2154 EXPORT_SYMBOL(gspca_dev_probe2);
2155 
2156 /* same function as the previous one, but check the interface */
2157 int gspca_dev_probe(struct usb_interface *intf,
2158 		const struct usb_device_id *id,
2159 		const struct sd_desc *sd_desc,
2160 		int dev_size,
2161 		struct module *module)
2162 {
2163 	struct usb_device *dev = interface_to_usbdev(intf);
2164 
2165 	/* we don't handle multi-config cameras */
2166 	if (dev->descriptor.bNumConfigurations != 1) {
2167 		pr_err("%04x:%04x too many config\n",
2168 		       id->idVendor, id->idProduct);
2169 		return -ENODEV;
2170 	}
2171 
2172 	/* the USB video interface must be the first one */
2173 	if (dev->actconfig->desc.bNumInterfaces != 1
2174 	 && intf->cur_altsetting->desc.bInterfaceNumber != 0)
2175 		return -ENODEV;
2176 
2177 	return gspca_dev_probe2(intf, id, sd_desc, dev_size, module);
2178 }
2179 EXPORT_SYMBOL(gspca_dev_probe);
2180 
2181 /*
2182  * USB disconnection
2183  *
2184  * This function must be called by the sub-driver
2185  * when the device disconnects, after the specific resources are freed.
2186  */
2187 void gspca_disconnect(struct usb_interface *intf)
2188 {
2189 	struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2190 #if IS_ENABLED(CONFIG_INPUT)
2191 	struct input_dev *input_dev;
2192 #endif
2193 
2194 	PDEBUG(D_PROBE, "%s disconnect",
2195 		video_device_node_name(&gspca_dev->vdev));
2196 
2197 	mutex_lock(&gspca_dev->usb_lock);
2198 
2199 	gspca_dev->present = 0;
2200 	destroy_urbs(gspca_dev);
2201 
2202 #if IS_ENABLED(CONFIG_INPUT)
2203 	gspca_input_destroy_urb(gspca_dev);
2204 	input_dev = gspca_dev->input_dev;
2205 	if (input_dev) {
2206 		gspca_dev->input_dev = NULL;
2207 		input_unregister_device(input_dev);
2208 	}
2209 #endif
2210 	/* Free subdriver's streaming resources / stop sd workqueue(s) */
2211 	if (gspca_dev->sd_desc->stop0 && gspca_dev->streaming)
2212 		gspca_dev->sd_desc->stop0(gspca_dev);
2213 	gspca_dev->streaming = 0;
2214 	gspca_dev->dev = NULL;
2215 	wake_up_interruptible(&gspca_dev->wq);
2216 
2217 	v4l2_device_disconnect(&gspca_dev->v4l2_dev);
2218 	video_unregister_device(&gspca_dev->vdev);
2219 
2220 	mutex_unlock(&gspca_dev->usb_lock);
2221 
2222 	/* (this will call gspca_release() immediately or on last close) */
2223 	v4l2_device_put(&gspca_dev->v4l2_dev);
2224 }
2225 EXPORT_SYMBOL(gspca_disconnect);
2226 
2227 #ifdef CONFIG_PM
2228 int gspca_suspend(struct usb_interface *intf, pm_message_t message)
2229 {
2230 	struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2231 
2232 	gspca_input_destroy_urb(gspca_dev);
2233 
2234 	if (!gspca_dev->streaming)
2235 		return 0;
2236 
2237 	mutex_lock(&gspca_dev->usb_lock);
2238 	gspca_dev->frozen = 1;		/* avoid urb error messages */
2239 	gspca_dev->usb_err = 0;
2240 	if (gspca_dev->sd_desc->stopN)
2241 		gspca_dev->sd_desc->stopN(gspca_dev);
2242 	destroy_urbs(gspca_dev);
2243 	gspca_set_alt0(gspca_dev);
2244 	if (gspca_dev->sd_desc->stop0)
2245 		gspca_dev->sd_desc->stop0(gspca_dev);
2246 	mutex_unlock(&gspca_dev->usb_lock);
2247 
2248 	return 0;
2249 }
2250 EXPORT_SYMBOL(gspca_suspend);
2251 
2252 int gspca_resume(struct usb_interface *intf)
2253 {
2254 	struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2255 	int streaming, ret = 0;
2256 
2257 	mutex_lock(&gspca_dev->usb_lock);
2258 	gspca_dev->frozen = 0;
2259 	gspca_dev->usb_err = 0;
2260 	gspca_dev->sd_desc->init(gspca_dev);
2261 	/*
2262 	 * Most subdrivers send all ctrl values on sd_start and thus
2263 	 * only write to the device registers on s_ctrl when streaming ->
2264 	 * Clear streaming to avoid setting all ctrls twice.
2265 	 */
2266 	streaming = gspca_dev->streaming;
2267 	gspca_dev->streaming = 0;
2268 	if (streaming)
2269 		ret = gspca_init_transfer(gspca_dev);
2270 	else
2271 		gspca_input_create_urb(gspca_dev);
2272 	mutex_unlock(&gspca_dev->usb_lock);
2273 
2274 	return ret;
2275 }
2276 EXPORT_SYMBOL(gspca_resume);
2277 #endif
2278 
2279 /* -- module insert / remove -- */
2280 static int __init gspca_init(void)
2281 {
2282 	pr_info("v" GSPCA_VERSION " registered\n");
2283 	return 0;
2284 }
2285 static void __exit gspca_exit(void)
2286 {
2287 }
2288 
2289 module_init(gspca_init);
2290 module_exit(gspca_exit);
2291 
2292 module_param_named(debug, gspca_debug, int, 0644);
2293 MODULE_PARM_DESC(debug,
2294 		"1:probe 2:config 3:stream 4:frame 5:packet 6:usbi 7:usbo");
2295