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