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