File: /usr/src/linux/drivers/usb/pwc-if.c

1     /* Linux driver for Philips webcam 
2        USB and Video4Linux interface part.
3        (C) 1999-2001 Nemosoft Unv.
4     
5        This program is free software; you can redistribute it and/or modify
6        it under the terms of the GNU General Public License as published by
7        the Free Software Foundation; either version 2 of the License, or
8        (at your option) any later version.
9     
10        This program is distributed in the hope that it will be useful,
11        but WITHOUT ANY WARRANTY; without even the implied warranty of
12        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13        GNU General Public License for more details.
14     
15        You should have received a copy of the GNU General Public License
16        along with this program; if not, write to the Free Software
17        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18     
19     */
20     
21     /*  
22        This code forms the interface between the USB layers and the Philips
23        specific stuff. Some adanved stuff of the driver falls under an
24        NDA, signed between me and Philips B.V., Eindhoven, the Netherlands, and
25        is thus not distributed in source form. The binary pwcx.o module 
26        contains the code that falls under the NDA.
27        
28        In case you're wondering: 'pwc' stands for "Philips WebCam", but 
29        I really didn't want to type 'philips_web_cam' every time (I'm lazy as
30        any Linux kernel hacker, but I don't like uncomprehensible abbreviations
31        without explanation).
32        
33        Oh yes, convention: to disctinguish between all the various pointers to
34        device-structures, I use these names for the pointer variables:
35        udev: struct usb_device *
36        vdev: struct video_device *
37        pdev: struct pwc_devive *
38     */
39     
40     /* Contributors:
41        - Alvarado: adding whitebalance code
42        - Alistar Moire: QuickCam 3000 Pro testing
43     */
44     
45     #include <linux/errno.h>
46     #include <linux/init.h>
47     #include <linux/module.h>
48     #include <linux/poll.h>
49     #include <linux/slab.h>
50     #include <linux/vmalloc.h>
51     #include <linux/wrapper.h>
52     #include <asm/io.h>
53     
54     #include "pwc.h"
55     #include "pwc-ioctl.h"
56     #include "pwc-uncompress.h"
57     
58     #if !defined(MAP_NR)
59     #define MAP_NR(a) virt_to_page(a)
60     #endif
61     
62     /* Function prototypes and driver templates */
63     
64     /* hotplug device table support */
65     static __devinitdata struct usb_device_id pwc_device_table [] = {
66     	{ USB_DEVICE(0x0471, 0x0302) },
67     	{ USB_DEVICE(0x0471, 0x0303) },
68     	{ USB_DEVICE(0x0471, 0x0304) },
69     	{ USB_DEVICE(0x0471, 0x0307) },
70     	{ USB_DEVICE(0x0471, 0x0308) },
71     	{ USB_DEVICE(0x0471, 0x030C) },
72     	{ USB_DEVICE(0x0471, 0x0310) },
73     	{ USB_DEVICE(0x0471, 0x0311) },
74     	{ USB_DEVICE(0x0471, 0x0312) },
75     	{ USB_DEVICE(0x069A, 0x0001) },
76     	{ USB_DEVICE(0x046D, 0x0b80) },
77     	{ }
78     };
79     MODULE_DEVICE_TABLE(usb, pwc_device_table);
80     
81     static void *usb_pwc_probe(struct usb_device *udev, unsigned int ifnum, const struct usb_device_id *id);
82     static void usb_pwc_disconnect(struct usb_device *udev, void *ptr);
83     
84     static struct usb_driver pwc_driver =
85     {
86     	name:			"Philips webcam",	/* name */
87     	id_table:		pwc_device_table,
88     	probe:			usb_pwc_probe,		/* probe() */
89     	disconnect:		usb_pwc_disconnect,	/* disconnect() */
90     };
91     
92     static int default_size = PSZ_QCIF;
93     static int default_fps = 10;
94     static int default_palette = VIDEO_PALETTE_YUV420P; /* This format is understood by most tools */
95     static int default_fbufs = 3;   /* Default number of frame buffers */
96     static int default_mbufs = 2;	/* Default number of mmap() buffers */
97            int pwc_trace = TRACE_MODULE | TRACE_FLOW | TRACE_PWCX;
98     static int power_save = 0;
99     int pwc_preferred_compression = 2; /* 0..3 = uncompressed..high */
100     
101     static struct semaphore mem_lock;
102     static void *mem_leak = NULL; /* For delayed kfree()s. See below */
103     
104     static int video_nr = -1;
105     
106     /***/
107     
108     static int  pwc_video_open(struct video_device *vdev, int mode);
109     static void pwc_video_close(struct video_device *vdev);
110     static long pwc_video_read(struct video_device *vdev, char *buf, unsigned long count, int noblock);
111     static long pwc_video_write(struct video_device *vdev, const char *buf, unsigned long count, int noblock);
112     static unsigned int pwc_video_poll(struct video_device *vdev, struct file *file, poll_table *wait);
113     static int  pwc_video_ioctl(struct video_device *vdev, unsigned int cmd, void *arg);
114     static int  pwc_video_mmap(struct video_device *dev, const char *adr, unsigned long size);
115     
116     static struct video_device pwc_template = {
117     	owner:		THIS_MODULE,
118     	name:		"Philips Webcam",	/* Filled in later */
119     	type:		VID_TYPE_CAPTURE,
120     	hardware:	VID_HARDWARE_PWC,
121     	open:		pwc_video_open,
122     	close:		pwc_video_close,
123     	read:		pwc_video_read,
124     	write:		pwc_video_write,
125     	poll:		pwc_video_poll,
126     	ioctl:		pwc_video_ioctl,
127     	mmap:		pwc_video_mmap,
128     	initialize:	NULL,			/* initialize */
129     	minor:		0			/* minor */
130     };
131     
132     /***************************************************************************/
133     
134     /* Okay, this is some magic that I worked out and the reasoning behind it...
135     
136        The biggest problem with any USB device is of course: "what to do 
137        when the user unplugs the device while it is in use by an application?"
138        We have several options:
139        1) Curse them with the 7 plagues when they do (requires divine intervention)
140        2) Tell them not to (won't work: they'll do it anyway)
141        3) Oops the kernel (this will have a negative effect on a user's uptime)
142        4) Do something sensible.
143        
144        Of course, we go for option 4.
145     
146        It happens that this device will be linked to two times, once from
147        usb_device and once from the video_device in their respective 'private'
148        pointers. This is done when the device is probed() and all initialization
149        succeeded. The pwc_device struct links back to both structures.
150     
151        When a device is unplugged while in use it will be removed from the 
152        list of known USB devices; I also de-register as a V4L device, but 
153        unfortunately I can't free the memory since the struct is still in use
154        by the file descriptor. This free-ing is then deferend until the first
155        opportunity. Crude, but it works.
156        
157        A small 'advantage' is that if a user unplugs the cam and plugs it back
158        in, it should get assigned the same video device minor, but unfortunately
159        it's non-trivial to re-link the cam back to the video device... (that 
160        would surely be magic! :))
161     */
162     
163     /***************************************************************************/
164     /* Private functions */
165     
166     /* Memory management functions, nicked from cpia.c, which nicked them from
167        bttv.c. So far, I've counted duplication of this code 6 times 
168        (bttv, cpia, ibmcam, ov511, pwc, ieee1394).
169      */
170     
171     /* Given PGD from the address space's page table, return the kernel
172      * virtual mapping of the physical memory mapped at ADR.
173      */
174     static inline unsigned long uvirt_to_kva(pgd_t *pgd, unsigned long adr)
175     {
176             unsigned long ret = 0UL;
177     	pmd_t *pmd;
178     	pte_t *ptep, pte;
179       
180     	if (!pgd_none(*pgd)) {
181                     pmd = pmd_offset(pgd, adr);
182                     if (!pmd_none(*pmd)) {
183                             ptep = pte_offset(pmd, adr);
184                             pte = *ptep;
185                             if(pte_present(pte)) {
186     				ret  = (unsigned long) page_address(pte_page(pte));
187     				ret |= (adr & (PAGE_SIZE - 1));
188     				
189     			}
190                     }
191             }
192     	return ret;
193     }
194     
195     
196     
197     /* Here we want the physical address of the memory.
198      * This is used when initializing the contents of the
199      * area and marking the pages as reserved.
200      */
201     static inline unsigned long kvirt_to_pa(unsigned long adr) 
202     {
203             unsigned long va, kva, ret;
204     
205             va = VMALLOC_VMADDR(adr);
206             kva = uvirt_to_kva(pgd_offset_k(va), va);
207     	ret = __pa(kva);
208             return ret;
209     }
210     
211     static void * rvmalloc(signed long size)
212     {
213     	void * mem;
214     	unsigned long adr, page;
215     
216             /* Round it off to PAGE_SIZE */
217             size += (PAGE_SIZE - 1);
218             size &= ~(PAGE_SIZE - 1);	
219             
220             mem=vmalloc_32(size);
221     	if (mem) 
222     	{
223     		memset(mem, 0, size); /* Clear the ram out, no junk to the user */
224     	        adr=(unsigned long) mem;
225     		while (size > 0) 
226                     {
227     	                page = kvirt_to_pa(adr);
228     			mem_map_reserve(virt_to_page(__va(page)));
229     			adr+=PAGE_SIZE;
230     			size-=PAGE_SIZE;
231     		}
232     	}
233     	return mem;
234     }
235     
236     static void rvfree(void * mem, signed long size)
237     {
238             unsigned long adr, page;
239             
240             /* Round it off to PAGE_SIZE */
241             size += (PAGE_SIZE - 1);
242             size &= ~(PAGE_SIZE - 1);	
243     	if (mem) 
244     	{
245     	        adr=(unsigned long) mem;
246     		while (size > 0) 
247                     {
248     	                page = kvirt_to_pa(adr);
249     			mem_map_unreserve(virt_to_page(__va(page)));
250     			adr+=PAGE_SIZE;
251     			size-=PAGE_SIZE;
252     		}
253     		vfree(mem);
254     	}
255     }
256     
257     
258     
259     
260     static int pwc_allocate_buffers(struct pwc_device *pdev)
261     {
262     	int i;
263     	void *kbuf;
264     
265     	Trace(TRACE_MEMORY, "Entering allocate_buffers(%p).\n", pdev);
266     
267     	if (pdev == NULL)
268     		return -ENXIO;
269     		
270     #ifdef PWC_MAGIC
271     	if (pdev->magic != PWC_MAGIC) {
272     		Err("allocate_buffers(): magic failed.\n");
273     		return -ENXIO;
274     	}
275     #endif	
276     	/* Allocate Isochronuous pipe buffers */
277     	for (i = 0; i < MAX_ISO_BUFS; i++) {
278     		if (pdev->sbuf[i].data == NULL) {
279     			kbuf = kmalloc(ISO_BUFFER_SIZE, GFP_KERNEL);
280     			if (kbuf == NULL) {
281     				Err("Failed to allocate iso buffer %d.\n", i);
282     				return -ENOMEM;
283     			}
284     			Trace(TRACE_MEMORY, "Allocated iso buffer at %p.\n", kbuf);
285     			pdev->sbuf[i].data = kbuf;
286     			memset(kbuf, 0, ISO_BUFFER_SIZE);
287     		}
288     	}
289     
290     	/* Allocate frame buffer structure */
291     	if (pdev->fbuf == NULL) {
292     		kbuf = kmalloc(default_fbufs * sizeof(struct pwc_frame_buf), GFP_KERNEL);
293     		if (kbuf == NULL) {
294     			Err("Failed to allocate frame buffer structure.\n");
295     			return -ENOMEM;
296     		}
297     		Trace(TRACE_MEMORY, "Allocated frame buffer structure at %p.\n", kbuf);
298     		pdev->fbuf = kbuf;
299     		memset(kbuf, 0, default_fbufs * sizeof(struct pwc_frame_buf));
300     	}
301     	/* create frame buffers, and make circular ring */
302     	for (i = 0; i < default_fbufs; i++) {
303     		if (pdev->fbuf[i].data == NULL) {
304     			kbuf = vmalloc(PWC_FRAME_SIZE); /* need vmalloc since frame buffer > 128K */
305     			if (kbuf == NULL) {
306     				Err("Failed to allocate frame buffer %d.\n", i);
307     				return -ENOMEM;
308     			}
309     			Trace(TRACE_MEMORY, "Allocated frame buffer %d at %p.\n", i, kbuf);
310     			pdev->fbuf[i].data = kbuf;
311     			memset(kbuf, 128, PWC_FRAME_SIZE);
312     		}
313     	}
314     	
315     	/* Allocate decompressor table space */
316     	kbuf = NULL;
317     	if (pdev->decompressor != NULL) {
318     		kbuf = kmalloc(pdev->decompressor->table_size, GFP_KERNEL);
319     		if (kbuf == NULL) {
320     			Err("Failed to allocate decompress table.\n");
321     			return -ENOMEM;
322     		}
323     		Trace(TRACE_MEMORY, "Allocated decompress table %p.\n", kbuf);
324     	}
325     	pdev->decompress_data = kbuf;
326     	
327     	/* Allocate image buffer; double buffer for mmap() */
328     	kbuf = rvmalloc(default_mbufs * pdev->len_per_image);
329     	if (kbuf == NULL) {
330     		Err("Failed to allocate image buffer(s).\n");
331     		return -ENOMEM;
332     	}
333     	Trace(TRACE_MEMORY, "Allocated image buffer at %p.\n", kbuf);
334     	pdev->image_data = kbuf;
335     	for (i = 0; i < default_mbufs; i++)
336     		pdev->image_ptr[i] = kbuf + i * pdev->len_per_image;
337     	for (; i < MAX_IMAGES; i++)
338     		pdev->image_ptr[i] = NULL;
339     
340     	Trace(TRACE_MEMORY, "Leaving pwc_allocate_buffers().\n");
341     	return 0;
342     }
343     
344     static void pwc_free_buffers(struct pwc_device *pdev)
345     {
346     	int i;
347     
348     	Trace(TRACE_MEMORY, "Entering free_buffers(%p).\n", pdev);
349     
350     	if (pdev == NULL)
351     		return;
352     #ifdef PWC_MAGIC
353     	if (pdev->magic != PWC_MAGIC) {
354     		Err("free_buffers(): magic failed.\n");
355     		return;
356     	}
357     #endif	
358     
359     	/* Release Iso-pipe buffers */
360     	for (i = 0; i < MAX_ISO_BUFS; i++)
361     		if (pdev->sbuf[i].data != NULL) {
362     			Trace(TRACE_MEMORY, "Freeing ISO buffer at %p.\n", pdev->sbuf[i].data);
363     			kfree(pdev->sbuf[i].data);
364     			pdev->sbuf[i].data = NULL;
365     		}
366     
367     	/* The same for frame buffers */
368     	if (pdev->fbuf != NULL) {
369     		for (i = 0; i < default_fbufs; i++) {
370     			if (pdev->fbuf[i].data != NULL) {
371     				Trace(TRACE_MEMORY, "Freeing frame buffer %d at %p.\n", i, pdev->fbuf[i].data);
372     				vfree(pdev->fbuf[i].data);
373     				pdev->fbuf[i].data = NULL;
374     			}
375     		}
376     		kfree(pdev->fbuf);
377     		pdev->fbuf = NULL;
378     	}
379     
380     	/* Intermediate decompression buffer & tables */
381     	if (pdev->decompress_data != NULL) {
382     		Trace(TRACE_MEMORY, "Freeing decompression buffer at %p.\n", pdev->decompress_data);
383     		kfree(pdev->decompress_data);
384     		pdev->decompress_data = NULL;
385     	}
386     	pdev->decompressor = NULL;
387     
388     	/* Release image buffers */
389     	if (pdev->image_data != NULL) {
390     		Trace(TRACE_MEMORY, "Freeing image buffer at %p.\n", pdev->image_data);
391     		rvfree(pdev->image_data, default_mbufs * pdev->len_per_image);
392     	}
393     	pdev->image_data = NULL;
394     	Trace(TRACE_MEMORY, "Leaving free_buffers().\n");
395     }
396     
397     /* The frame & image buffer mess. 
398     
399        Yes, this is a mess. Well, it used to be simple, but alas...  In this
400        module, 3 buffers schemes are used to get the data from the USB bus to
401        the user program. The first scheme involves the ISO buffers (called thus
402        since they transport ISO data from the USB controller), and not really
403        interesting. Suffices to say the data from this buffer is quickly 
404        gathered in an interrupt handler (pwc_isoc_handler) and placed into the 
405        frame buffer.
406        
407        The frame buffer is the second scheme, and is the central element here.
408        It collects the data from a single frame from the camera (hence, the
409        name). Frames are delimited by the USB camera with a short USB packet,
410        so that's easy to detect. The frame buffers form a list that is filled
411        by the camera+USB controller and drained by the user process through 
412        either read() or mmap().
413        
414        The image buffer is the third scheme, in which frames are decompressed
415        and possibly converted into planar format. For mmap() there is more than
416        one image buffer available.
417     
418        The frame buffers provide the image buffering, in case the user process
419        is a bit slow. This introduces lag and some undesired side-effects.
420        The problem arises when the frame buffer is full. I used to drop the last 
421        frame, which makes the data in the queue stale very quickly. But dropping 
422        the frame at the head of the queue proved to be a litte bit more difficult.
423        I tried a circular linked scheme, but this introduced more problems than
424        it solved.
425     
426        Because filling and draining are completely asynchronous processes, this
427        requires some fiddling with pointers and mutexes.
428        
429        Eventually, I came up with a system with 2 lists: an 'empty' frame list
430        and a 'full' frame list:
431          * Initially, all frame buffers but one are on the 'empty' list; the one
432            remaining buffer is our initial fill frame.
433          * If a frame is needed for filling, we take it from the 'empty' list, 
434            unless that list is empty, in which case we take the buffer at the 
435            head of the 'full' list.
436          * When our fill buffer has been filled, it is appended to the 'full' 
437            list.
438          * If a frame is needed by read() or mmap(), it is taken from the head of 
439            the 'full' list, handled, and then appended to the 'empty' list. If no
440            buffer is present on the 'full' list, we wait.
441        The advantage is that the buffer that is currently being decompressed/
442        converted, is on neither list, and thus not in our way (any other scheme 
443        I tried had the problem of old data lingering in the queue).
444     
445        Whatever strategy you choose, it always remains a tradeoff: with more
446        frame buffers the chances of a missed frame are reduced. On the other
447        hand, on slower machines it introduces lag because the queue will 
448        always be full.
449      */
450     
451     /**
452       \brief Find next frame buffer to fill. Take from empty or full list, whichever comes first.
453      */
454     static inline int pwc_next_fill_frame(struct pwc_device *pdev)
455     {
456     	int ret;
457     	unsigned long flags;
458     	
459     	ret = 0;
460     	spin_lock_irqsave(&pdev->ptrlock, flags);
461     	if (pdev->fill_frame != NULL) {
462     		/* append to 'full' list */
463     		if (pdev->full_frames == NULL) {
464     			pdev->full_frames = pdev->fill_frame;
465     			pdev->full_frames_tail = pdev->full_frames;
466     		}
467     		else {
468     			pdev->full_frames_tail->next = pdev->fill_frame;
469     			pdev->full_frames_tail = pdev->fill_frame;
470     		}
471     	}
472     	if (pdev->empty_frames != NULL) {
473     		/* We have empty frames available. That's easy */
474     		pdev->fill_frame = pdev->empty_frames;
475     		pdev->empty_frames = pdev->empty_frames->next;	
476     	}
477     	else {
478     		/* Hmm. Take it from the full list */
479     #if PWC_DEBUG		
480     		/* sanity check */
481     		if (pdev->full_frames == NULL) {
482     			Err("Neither empty or full frames available!\n");
483     			spin_unlock_irqrestore(&pdev->ptrlock, flags);
484     			return -EINVAL;
485     		}
486     #endif
487     		pdev->fill_frame = pdev->full_frames;
488     		pdev->full_frames = pdev->full_frames->next;
489     		ret = 1;
490     	}
491     	pdev->fill_frame->next = NULL;
492     #if PWC_DEBUG
493     	Trace(TRACE_SEQUENCE, "Assigning sequence number %d.\n", pdev->sequence);
494     	pdev->fill_frame->sequence = pdev->sequence++;
495     #endif
496     	spin_unlock_irqrestore(&pdev->ptrlock, flags);
497     	return ret;
498     }
499      
500     
501     /**
502       \brief Reset all buffers, pointers and lists, except for the image_used[] buffer. 
503       
504       If the image_used[] buffer is cleared too, mmap()/VIDIOCSYNC will run into trouble.
505      */
506     static void pwc_reset_buffers(struct pwc_device *pdev)
507     {
508     	int i;
509     	unsigned long flags;
510     
511     	spin_lock_irqsave(&pdev->ptrlock, flags);
512     	pdev->full_frames = NULL;
513     	pdev->full_frames_tail = NULL;
514     	for (i = 0; i < default_fbufs; i++) {
515     		pdev->fbuf[i].filled = 0;
516     		if (i > 0)
517     			pdev->fbuf[i].next = &pdev->fbuf[i - 1];
518     		else
519     			pdev->fbuf->next = NULL;
520     	}
521     	pdev->empty_frames = &pdev->fbuf[default_fbufs - 1];
522     	pdev->empty_frames_tail = pdev->fbuf;
523     	pdev->read_frame = NULL;
524     	pdev->fill_frame = pdev->empty_frames;
525     	pdev->empty_frames = pdev->empty_frames->next;
526     
527     	pdev->image_read_pos = 0;
528     	pdev->fill_image = 0;
529     	spin_unlock_irqrestore(&pdev->ptrlock, flags);
530     }
531     
532     
533     /**
534       \brief Do all the handling for getting one frame: get pointer, decompress, advance pointers.
535      */
536     static int pwc_handle_frame(struct pwc_device *pdev)
537     {
538     	int ret = 0;
539     	unsigned long flags;
540     	
541     	spin_lock_irqsave(&pdev->ptrlock, flags);
542     	/* First grab our read_frame; this is removed from all lists, so
543     	   we can release the lock after this without problems */
544     	if (pdev->read_frame != NULL) {
545     		/* This can't theoretically happen */
546     		Err("Huh? Read frame still in use?\n");
547     	}
548     	else {
549     		if (pdev->full_frames == NULL) {
550     			Err("Woops. No frames ready.\n");
551     		}
552     		else {
553     			pdev->read_frame = pdev->full_frames;
554     			pdev->full_frames = pdev->full_frames->next;
555     			pdev->read_frame->next = NULL;
556     		}
557     
558     		if (pdev->read_frame != NULL) {
559     #if PWC_DEBUG
560     			Trace(TRACE_SEQUENCE, "Decompressing frame %d\n", pdev->read_frame->sequence);
561     #endif
562     			/* Decompression is a lenghty process, so it's outside of the lock.
563     			   This gives the isoc_handler the opportunity to fill more frames 
564     			   in the mean time.
565     			*/
566     			spin_unlock_irqrestore(&pdev->ptrlock, flags);
567     			ret = pwc_decompress(pdev);
568     			spin_lock_irqsave(&pdev->ptrlock, flags);
569     
570     			/* We're done with read_buffer, tack it to the end of the empty buffer list */
571     			if (pdev->empty_frames == NULL) {
572     				pdev->empty_frames = pdev->read_frame;
573     				pdev->empty_frames_tail = pdev->empty_frames;
574     			}
575     			else {
576     				pdev->empty_frames_tail->next = pdev->read_frame;
577     				pdev->empty_frames_tail = pdev->read_frame;
578     			}
579     			pdev->read_frame = NULL;
580     		}
581     	}
582     	spin_unlock_irqrestore(&pdev->ptrlock, flags);
583     	return ret;
584     }
585     
586     /**
587       \brief Advance pointers of image buffer (after each user request) 
588     */
589     static inline void pwc_next_image(struct pwc_device *pdev)
590     {
591     	pdev->image_used[pdev->fill_image] = 0;
592     	pdev->fill_image = (pdev->fill_image + 1) % default_mbufs;
593     }
594     
595     /* XXX: 2001-06-17: The YUV420 palette will be phased out soon */
596     static int pwc_set_palette(struct pwc_device *pdev, int pal)
597     {
598     	if (   pal == VIDEO_PALETTE_YUV420
599                 || pal == VIDEO_PALETTE_YUV420P
600     #if PWC_DEBUG
601                 || pal == VIDEO_PALETTE_RAW
602     #endif
603     	) {
604     		pdev->vpalette = pal;
605     		pwc_set_image_buffer_size(pdev);
606     		return 0;
607     	}
608     	Trace(TRACE_READ, "Palette %d not supported.\n", pal);
609     	return -1;
610     }
611     
612     
613     
614     /* This gets called for the Isochronous pipe (video). This is done in
615      * interrupt time, so it has to be fast, not crash, and not stall. Neat.
616      */
617     static void pwc_isoc_handler(purb_t urb)
618     {
619     	struct pwc_device *pdev;
620     	int i, fst, flen;
621     	int awake;
622     	struct pwc_frame_buf *fbuf;
623     	unsigned char *fillptr, *iso_buf;
624     
625     	pdev = (struct pwc_device *)urb->context;
626     	if (pdev == NULL) {
627     		Err("isoc_handler() called with NULL device?!\n");
628     		return;
629     	}
630     #ifdef PWC_MAGIC	
631     	if (pdev->magic != PWC_MAGIC) {
632     		Err("isoc_handler() called with bad magic!\n");
633     		return;
634     	}
635     #endif
636     	if (urb->status == -ENOENT || urb->status == -ECONNRESET) {
637     		Trace(TRACE_OPEN, "pwc_isoc_handler(): URB unlinked.\n");
638     		return;
639     	}
640     	if (urb->status != -EINPROGRESS && urb->status != 0) {
641     		char *errmsg;
642     		
643     		errmsg = "Unknown";
644     		switch(urb->status) {
645     			case -ENOSR:		errmsg = "Buffer error (overrun)"; break;
646     			case -EPIPE:		errmsg = "Babble/stalled (bad cable?)"; break;
647     			case -EPROTO:		errmsg = "Bit-stuff error (bad cable?)"; break;
648     			case -EILSEQ:		errmsg = "CRC/Timeout"; break;
649     			case -ETIMEDOUT:	errmsg = "NAK (device does not respond)"; break;
650     		}
651     		Trace(TRACE_FLOW, "pwc_isoc_handler() called with status %d [%s].\n", urb->status, errmsg);
652     		return;
653     	}
654     
655     	fbuf = pdev->fill_frame;
656     	if (fbuf == NULL) {
657     		Err("pwc_isoc_handler without valid fill frame.\n");
658     		wake_up_interruptible(&pdev->frameq);
659     		return;
660     	}
661     	fillptr = fbuf->data + fbuf->filled;
662     	awake = 0;
663     
664     	/* vsync: 0 = don't copy data
665     	          1 = sync-hunt
666     	          2 = synched 
667     	 */
668     	/* Compact data */
669     	for (i = 0; i < urb->number_of_packets; i++) {
670     		fst  = urb->iso_frame_desc[i].status;
671     		flen = urb->iso_frame_desc[i].actual_length;
672     		iso_buf = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
673     		if (fst == 0) {
674     			if (flen > 0) { /* if valid data... */
675     				if (pdev->vsync > 0) { /* ...and we are not sync-hunting... */
676     					pdev->vsync = 2;
677     
678     					/* ...copy data to frame buffer, if possible */
679     					if (flen + fbuf->filled > pdev->frame_size) {
680     						Trace(TRACE_FLOW, "Frame buffer overflow (flen = %d, frame_size = %d).\n", flen, pdev->frame_size);
681     						pdev->vsync = 0; /* Hmm, let's wait for an EOF (end-of-frame) */
682     						pdev->vframes_error++;
683     					}
684     					else {
685     						memmove(fillptr, iso_buf, flen);
686     						fillptr += flen;
687     					}
688     				}
689     				fbuf->filled += flen;
690     			} /* ..flen > 0 */
691     
692     			if (flen < pdev->vlast_packet_size) {
693     				/* Shorter packet... We probably have the end of an image-frame; 
694     				   wake up read() process and let select()/poll() do something.
695     				   Decompression is done in user time over there. 
696     				 */
697     				if (pdev->vsync == 2) {
698     					/* The ToUCam Fun CMOS sensor causes the firmware to send 2 or 3 bogus 
699     					   frames on the USB wire after an exposure change. This conditition is 
700     					   however detected  in the cam and a bit is set in the header.
701     					 */
702     					if (pdev->type == 730) {
703     						unsigned char *ptr = (unsigned char *)fbuf->data;
704     						
705     						if (ptr[1] == 1 && ptr[0] & 0x10) {
706     #if PWC_DEBUG
707     							Debug("Hyundai CMOS sensor bug. Dropping frame %d.\n", fbuf->sequence);
708     #endif
709     							pdev->drop_frames = 2;
710     							pdev->vframes_error++;
711     						}
712     						/* Sometimes the trailer of the 730 is still sent as a 4 byte packet 
713     						   after a short frame; this condition is filtered out specifically. A 4 byte
714     						   frame doesn't make sense anyway.
715     						   So we get either this sequence: 
716     						   	drop_bit set -> 4 byte frame -> short frame -> good frame
717     						   Or this one:
718     						   	drop_bit set -> short frame -> good frame
719     						   So we drop either 3 or 2 frames in all!
720     						 */
721     						if (fbuf->filled == 4)
722     							pdev->drop_frames++;
723     					}
724     
725     					/* In case we were instructed to drop the frame, do so silently.
726     					   The buffer pointers are not updated either (but the counters are reset below).
727     					 */
728     					if (pdev->drop_frames)
729     						pdev->drop_frames--;
730     					else {
731     						/* Check for underflow first */
732     						if (fbuf->filled < pdev->frame_size) {
733     							Trace(TRACE_FLOW, "Frame buffer underflow (%d bytes); discarded.\n", fbuf->filled);
734     							pdev->vframes_error++;
735     						}
736     						else {
737     							/* Send only once per EOF */
738     							awake = 1; /* delay wake_ups */
739     							
740     							/* Find our next frame to fill. This will always succeed, since we
741     							 * nick a frame from either empty or full list, but if we had to
742     							 * take it from the full list, it means a frame got dropped.
743     							 */
744     							if (pwc_next_fill_frame(pdev)) {
745     								pdev->vframes_dumped++;
746     								if ((pdev->vframe_count > FRAME_LOWMARK) && (pwc_trace & TRACE_FLOW)) {
747     									if (pdev->vframes_dumped < 20)
748     										Trace(TRACE_FLOW, "Dumping frame %d.\n", pdev->vframe_count);
749     									if (pdev->vframes_dumped == 20)
750     										Trace(TRACE_FLOW, "Dumping frame %d (last message).\n", pdev->vframe_count);
751     								}
752     							}
753     							fbuf = pdev->fill_frame;
754     						}
755     					} /* !drop_frames */
756     					pdev->vframe_count++;
757     				}
758     				fbuf->filled = 0;
759     				fillptr = fbuf->data;
760     				pdev->vsync = 1;
761     			} /* .. flen < last_packet_size */
762     			pdev->vlast_packet_size = flen;
763     		} /* ..status == 0 */
764     	}
765     	if (awake)
766     		wake_up_interruptible(&pdev->frameq);
767     }
768     
769     
770     static int pwc_isoc_init(struct pwc_device *pdev)
771     {
772     	struct usb_device *udev;
773     	purb_t urb;
774     	int i, j, ret;
775     
776     	struct usb_interface_descriptor *idesc;
777     	int cur_alt;
778     
779     	if (pdev == NULL)
780     		return -EFAULT;
781     	if (pdev->iso_init)
782     		return 0;
783     	pdev->vsync = 0;
784     	udev = pdev->udev;
785     	
786     	/* Get the current alternate interface, adjust packet size */
787     	if (!udev->actconfig)
788     		return -EFAULT;
789     	cur_alt = udev->actconfig->interface[0].act_altsetting;
790     	idesc = &udev->actconfig->interface[0].altsetting[cur_alt];
791     	if (!idesc)
792     		return -EFAULT;
793     
794     	/* Search video endpoint */
795     	pdev->vmax_packet_size = -1;
796     	for (i = 0; i < idesc->bNumEndpoints; i++)
797     		if ((idesc->endpoint[i].bEndpointAddress & 0xF) == pdev->vendpoint) {
798     			pdev->vmax_packet_size = idesc->endpoint[i].wMaxPacketSize;
799     			break;
800     		}
801     	
802     	if (pdev->vmax_packet_size < 0) {
803     		Err("Failed to find packet size for video endpoint in current alternate setting.\n");
804     		return -ENFILE; /* Odd error, that should be noticable */
805     	}
806     
807     	ret = 0;
808     	for (i = 0; i < MAX_ISO_BUFS; i++) {
809     		urb = usb_alloc_urb(ISO_FRAMES_PER_DESC);
810     		if (urb == NULL) {
811     			Err("Failed to allocate urb %d\n", i);
812     			ret = -ENOMEM;
813     			break;
814     		}
815     		pdev->sbuf[i].urb = urb;
816     	}
817     	if (ret) {
818     		/* De-allocate in reverse order */
819     		while (i >= 0) {
820     			if (pdev->sbuf[i].urb != NULL)
821     				usb_free_urb(pdev->sbuf[i].urb);
822     			pdev->sbuf[i].urb = NULL;
823     			i--;
824     		}
825     		return ret;
826     	}
827     	
828     	
829     	/* init URB structure */	
830     	for (i = 0; i < MAX_ISO_BUFS; i++) {
831     		urb = pdev->sbuf[i].urb;
832     
833     		urb->next = pdev->sbuf[(i + 1) % MAX_ISO_BUFS].urb;
834     		urb->dev = udev;
835     	        urb->pipe = usb_rcvisocpipe(udev, pdev->vendpoint);
836     		urb->transfer_flags = USB_ISO_ASAP;
837     	        urb->transfer_buffer = pdev->sbuf[i].data;
838     	        urb->transfer_buffer_length = ISO_BUFFER_SIZE;
839     	        urb->complete = pwc_isoc_handler;
840     	        urb->context = pdev;
841     		urb->start_frame = 0;
842     		urb->number_of_packets = ISO_FRAMES_PER_DESC;
843     		for (j = 0; j < ISO_FRAMES_PER_DESC; j++) {
844     			urb->iso_frame_desc[j].offset = j * ISO_MAX_FRAME_SIZE;
845     			urb->iso_frame_desc[j].length = ISO_MAX_FRAME_SIZE;
846     		}
847     	}
848     
849     	/* link */
850     	for (i = 0; i < MAX_ISO_BUFS; i++) {
851     		ret = usb_submit_urb(pdev->sbuf[i].urb);
852     		if (ret)
853     			Err("isoc_init() submit_urb %d failed with error %d\n", i, ret);
854     		else
855     			Trace(TRACE_OPEN, "pwc_isoc_init(): URB submitted.\n");
856     	}
857     
858     	/* data should stream in now */
859     	pdev->iso_init = 1;
860     	return 0;
861     }
862     
863     static void pwc_isoc_cleanup(struct pwc_device *pdev)
864     {
865     	int i;
866     	
867     	if (pdev == NULL)
868     		return;
869     	if (!pdev->iso_init)
870     		return;
871     	/* Stop camera, but only if we are sure the camera is still there */
872     	if (!pdev->unplugged)
873     		usb_set_interface(pdev->udev, 0, 0);
874     	for (i = MAX_ISO_BUFS - 1; i >= 0; i--) {
875     		pdev->sbuf[i].urb->next = NULL;
876     		usb_unlink_urb(pdev->sbuf[i].urb);
877     		usb_free_urb(pdev->sbuf[i].urb);
878     		pdev->sbuf[i].urb = NULL;
879     	}
880     	pdev->iso_init = 0;
881     }
882     
883     int pwc_try_video_mode(struct pwc_device *pdev, int width, int height, int new_fps, int new_compression, int new_snapshot)
884     {
885     	int ret;
886     
887     	/* Stop isoc stuff */
888     	pwc_isoc_cleanup(pdev);
889     	/* Reset parameters */
890     	pwc_reset_buffers(pdev);
891     	/* Try to set video mode... */
892     	ret = pwc_set_video_mode(pdev, width, height, new_fps, new_compression, new_snapshot);
893     	if (ret) /* That failed... restore old mode (we know that worked) */
894     		ret = pwc_set_video_mode(pdev, pdev->view.x, pdev->view.y, pdev->vframes, pdev->vcompression, pdev->vsnapshot);
895     	else /* Set (new) alternate interface */
896     		ret = usb_set_interface(pdev->udev, 0, pdev->valternate);
897     	if (!ret)
898     		ret = pwc_isoc_init(pdev);
899     	pdev->drop_frames = 1; /* try to avoid garbage during switch */
900     	return ret;
901     }
902     
903     
904     static inline void set_mem_leak(void *ptr)
905     {
906     	down(&mem_lock);
907     	if (mem_leak != NULL)
908     		Err("Memleak: overwriting mem_leak pointer!\n");
909     	Trace(TRACE_MEMORY, "Setting mem_leak to 0x%p.\n", ptr);
910     	mem_leak = ptr;
911     	up(&mem_lock);
912     }
913     
914     static inline void free_mem_leak(void)
915     {
916     	down(&mem_lock);
917     	if (mem_leak != NULL) {
918     		Trace(TRACE_MEMORY, "Freeing mem_leak ptr 0x%p.\n", mem_leak);
919     		kfree(mem_leak);
920     		mem_leak = NULL;
921     	}
922     	up(&mem_lock);
923     }
924     
925     
926     /***************************************************************************/
927     /* Video4Linux functions */
928     
929     static int pwc_video_open(struct video_device *vdev, int mode)
930     {
931     	int i;
932     	struct pwc_device *pdev;
933     
934     	Trace(TRACE_OPEN, "video_open called(0x%p, 0%o).\n", vdev, mode);
935     	
936     	if (vdev == NULL)
937     		BUG();
938     	pdev = (struct pwc_device *)vdev->priv;
939     	if (pdev == NULL)
940     		BUG();
941     	
942     	down(&pdev->modlock);
943     	if (!pdev->usb_init) {
944     		Trace(TRACE_OPEN, "Doing first time initialization.\n");
945     		/* Reset camera */
946     		if (usb_set_interface(pdev->udev, 0, 0))
947     			Info("Failed to set alternate interface to 0.\n");
948     		pdev->usb_init = 1;
949     	}
950     	else {
951     		/* Turn on camera */
952     		if (power_save) {
953     			i = pwc_camera_power(pdev, 1);
954     			if (i < 0)
955     				Info("Failed to restore power to the camera! (%d)\n", i);
956     		}
957     	}
958     
959     	/* Find our decompressor, if any */
960     	pdev->decompressor = pwc_find_decompressor(pdev->type);
961     #if PWC_DEBUG	
962     	Debug("Found decompressor for %d at 0x%p\n", pdev->type, pdev->decompressor);
963     #endif
964     
965     	/* So far, so good. Allocate memory. */
966     	i = pwc_allocate_buffers(pdev);
967     	if (i < 0) {
968     		Trace(TRACE_OPEN, "Failed to allocate buffer memory.\n");
969     		up(&pdev->modlock);
970     		return i;
971     	}
972     	
973     	/* Reset buffers & parameters */
974     	pwc_reset_buffers(pdev);
975     	for (i = 0; i < default_mbufs; i++)
976     		pdev->image_used[i] = 0;
977     	pdev->vframe_count = 0;
978     	pdev->vframes_dumped = 0;
979     	pdev->vframes_error = 0;
980     	pdev->vpalette = default_palette;
981     #if PWC_DEBUG	
982     	pdev->sequence = 0;
983     #endif
984     
985     	/* Set some defaults */
986     	pdev->vsnapshot = 0;
987     	if (pdev->type == 730 || pdev->type == 740 || pdev->type == 750)
988     		pdev->vsize = PSZ_QSIF;
989     	else
990     		pdev->vsize = PSZ_QCIF;
991     	pdev->vframes = 10;
992     
993     	/* Start iso pipe for video; first try user-supplied size/fps, if
994     	   that fails try QCIF/10 or QSIF/10 (a reasonable default), 
995     	   then give up 
996     	 */
997     	i = pwc_set_video_mode(pdev, pwc_image_sizes[default_size].x, pwc_image_sizes[default_size].y, default_fps, pdev->vcompression, 0);
998     	if (i)	{
999     		Trace(TRACE_OPEN, "First attempt at set_video_mode failed.\n");
1000     		if (pdev->type == 730 || pdev->type == 740 || pdev->type == 750)
1001     			i = pwc_set_video_mode(pdev, pwc_image_sizes[PSZ_QSIF].x, pwc_image_sizes[PSZ_QSIF].y, 10, pdev->vcompression, 0);
1002     		else
1003     			i = pwc_set_video_mode(pdev, pwc_image_sizes[PSZ_QCIF].x, pwc_image_sizes[PSZ_QCIF].y, 10, pdev->vcompression, 0);
1004     	}
1005     	if (i) {
1006     		Trace(TRACE_OPEN, "Second attempt at set_video_mode failed.\n");
1007     		up(&pdev->modlock);
1008     		return i;
1009     	}
1010     	i = usb_set_interface(pdev->udev, 0, pdev->valternate);
1011     	if (i) {
1012     		Trace(TRACE_OPEN, "Failed to set alternate interface = %d.\n", i);
1013     		up(&pdev->modlock);
1014     		return -EINVAL;
1015     	}
1016     	i = pwc_isoc_init(pdev);
1017     	if (i) {
1018     		Trace(TRACE_OPEN, "Failed to init ISOC stuff = %d.\n", i);
1019     		MOD_DEC_USE_COUNT;
1020     		up(&pdev->modlock);
1021     		return i;
1022     	}
1023     
1024     	pdev->vopen++;
1025     	/* lock decompressor; this has a small race condition, since we 
1026     	   could in theory unload pwcx.o between pwc_find_decompressor()
1027     	   above and this call. I doubt it's ever going to be a problem.
1028     	 */
1029     	if (pdev->decompressor != NULL)
1030     		pdev->decompressor->lock();
1031     	up(&pdev->modlock);
1032     	Trace(TRACE_OPEN, "video_open() returning 0.\n");
1033     	return 0;
1034     }
1035     
1036     /* Note that all cleanup is done in the reverse order as in _open */
1037     static void pwc_video_close(struct video_device *vdev)
1038     {
1039     	struct pwc_device *pdev;
1040     	int i;
1041     
1042     	Trace(TRACE_OPEN, "video_close called(0x%p).\n", vdev);
1043     
1044     	pdev = (struct pwc_device *)vdev->priv;
1045     	if (pdev->vopen == 0)
1046     		Info("video_close() called on closed device?\n");
1047     
1048     	/* Free isoc URBs */
1049     	pwc_isoc_cleanup(pdev);
1050     
1051     	/* Dump statistics, but only if a reasonable amount of frames were
1052     	   processed (to prevent endless log-entries in case of snap-shot
1053     	   programs) 
1054     	 */
1055     	if (pdev->vframe_count > 20)
1056     		Info("Closing video device: %d frames received, dumped %d frames, %d frames with errors.\n", pdev->vframe_count, pdev->vframes_dumped, pdev->vframes_error);
1057     
1058     	if (pdev->unplugged) {
1059     		/* The device was unplugged or some other error occured */
1060     		/* We unregister the video_device */
1061     		Trace(TRACE_OPEN, "Delayed video device unregistered.\n");
1062     		video_unregister_device(pdev->vdev);
1063     	}
1064     	else {
1065     		/* Normal close: stop isochronuous and interrupt endpoint */
1066     		Trace(TRACE_OPEN, "Normal close(): setting interface to 0.\n");
1067     		usb_set_interface(pdev->udev, 0, 0);
1068     
1069     		/* Turn off LED by powering down camera */
1070     		if (power_save) {
1071     			i = pwc_camera_power(pdev, 0);
1072     			if (i < 0) 
1073     				Err("Failed to power down camera (%d)\n", i);
1074     		}
1075     	}
1076     
1077     	pdev->vopen = 0;
1078     	if (pdev->decompressor != NULL) {
1079     		pdev->decompressor->exit();
1080     		pdev->decompressor->unlock();
1081     	}
1082     	pwc_free_buffers(pdev);
1083     
1084     	/* wake up _disconnect() routine */
1085     	if (pdev->unplugged)
1086     		wake_up(&pdev->remove_ok);
1087     }
1088     
1089     /*
1090      *	FIXME: what about two parallel reads ????
1091      *      ANSWER: Not supported. You can't open the device more than once,
1092                     despite what the V4L1 interface says. First, I don't see 
1093                     the need, second there's no mechanism of alerting the 
1094                     2nd/3rd/... process of events like changing image size.
1095                     And I don't see the point of blocking that for the 
1096                     2nd/3rd/... process.
1097                     In multi-threaded environments reading parallel from any
1098                     device is tricky anyhow.
1099      */
1100      
1101     static long pwc_video_read(struct video_device *vdev, char *buf, unsigned long count, int noblock)
1102     {
1103     	struct pwc_device *pdev;
1104     	DECLARE_WAITQUEUE(wait, current);
1105     
1106     	Trace(TRACE_READ, "video_read(0x%p, %p, %ld, %d) called.\n", vdev, buf, count, noblock);
1107     	if (vdev == NULL)
1108     		return -EFAULT;
1109     	pdev = vdev->priv;
1110     	if (pdev == NULL)
1111     		return -EFAULT;
1112     	if (pdev->unplugged) {
1113     		Info("pwc_video_read: Device got unplugged (1).\n");
1114     		return -EPIPE; /* unplugged device! */
1115     	}
1116     
1117     	/* In case we're doing partial reads, we don't have to wait for a frame */
1118     	if (pdev->image_read_pos == 0) {
1119     		/* Do wait queueing according to the (doc)book */
1120     		add_wait_queue(&pdev->frameq, &wait);
1121     		while (pdev->full_frames == NULL) {
1122     	                if (noblock) {
1123     	                	remove_wait_queue(&pdev->frameq, &wait);
1124     	                	current->state = TASK_RUNNING;
1125     	                	return -EWOULDBLOCK;
1126     	                }
1127     	                if (signal_pending(current)) {
1128     	                	remove_wait_queue(&pdev->frameq, &wait);
1129     	                	current->state = TASK_RUNNING;
1130     	                	return -ERESTARTSYS;
1131     	                }
1132     	                schedule();
1133     	                current->state = TASK_INTERRUPTIBLE;
1134     		}
1135     		remove_wait_queue(&pdev->frameq, &wait);
1136     		current->state = TASK_RUNNING;
1137     	                                                                                                                                                                                
1138     		/* Decompress [, convert] and release frame */
1139     		if (pwc_handle_frame(pdev))
1140     			return -EFAULT;
1141     	}
1142     
1143     	Trace(TRACE_READ, "Copying data to user space.\n");
1144     	/* copy bytes to user space; we allow for partial reads */
1145     	if (count + pdev->image_read_pos > pdev->view.size)
1146     		count = pdev->view.size - pdev->image_read_pos;
1147     	if (copy_to_user(buf, pdev->image_ptr[pdev->fill_image] + pdev->image_read_pos, count))
1148     		return -EFAULT;
1149     	pdev->image_read_pos += count;
1150     	if (pdev->image_read_pos >= pdev->view.size) { /* All data has been read */
1151     		pdev->image_read_pos = 0;
1152     		pwc_next_image(pdev);
1153     	}
1154     	return count;
1155     }
1156     
1157     
1158     static long pwc_video_write(struct video_device *vdev, const char *buf, unsigned long count, int noblock)
1159     {
1160     	return -EINVAL;   
1161     }
1162     
1163     static unsigned int pwc_video_poll(struct video_device *vdev, struct file *file, poll_table *wait)
1164     {
1165     	struct pwc_device *pdev;
1166     	
1167     	if (vdev == NULL)
1168     		return -EFAULT;
1169     	pdev = vdev->priv;
1170     	if (pdev == NULL)
1171     		return -EFAULT;
1172     	
1173     	poll_wait(file, &pdev->frameq, wait);
1174     	if (pdev->unplugged) {
1175     		Info("pwc_video_poll: Device got unplugged.\n");
1176     		return POLLERR;
1177     	}		
1178     	if (pdev->full_frames != NULL) /* we have frames waiting */
1179     		return (POLLIN | POLLRDNORM);
1180     
1181     	return 0;
1182     }
1183             
1184     static int pwc_video_ioctl(struct video_device *vdev, unsigned int cmd, void *arg)
1185     {
1186     	struct pwc_device *pdev;
1187     	DECLARE_WAITQUEUE(wait, current);
1188     	
1189     	if (vdev == NULL)
1190     		return -EFAULT;
1191     	pdev = vdev->priv;
1192     	if (pdev == NULL)
1193     		return -EFAULT;
1194     
1195     	switch (cmd) {
1196     		/* Query cabapilities */
1197     		case VIDIOCGCAP: 
1198     		{
1199     			struct video_capability caps;
1200     
1201     			strcpy(caps.name, vdev->name);
1202     			caps.type = VID_TYPE_CAPTURE;
1203     			caps.channels = 1;
1204     			caps.audios = 1;
1205     			caps.minwidth  = pdev->view_min.x;
1206     			caps.minheight = pdev->view_min.y;
1207     			caps.maxwidth  = pdev->view_max.x;
1208     			caps.maxheight = pdev->view_max.y;
1209     			if (copy_to_user(arg, &caps, sizeof(caps)))
1210     				return -EFAULT;
1211     			break;
1212     		}
1213     
1214     		/* Channel functions (simulate 1 channel) */
1215     		case VIDIOCGCHAN:
1216     		{
1217     			struct video_channel v;
1218     
1219     			if (copy_from_user(&v, arg, sizeof(v)))
1220     				return -EFAULT;
1221     			if (v.channel != 0)
1222     				return -EINVAL;
1223     
1224     			v.flags = 0;
1225     			v.tuners = 0;
1226     			v.type = VIDEO_TYPE_CAMERA;
1227     			strcpy(v.name, "Webcam");
1228     
1229     			if (copy_to_user(arg, &v, sizeof(v)))
1230     				return -EFAULT;
1231     
1232     			return 0;
1233     		}
1234     
1235     		case VIDIOCSCHAN:
1236     		{	
1237     			/* The spec says the argument is an integer, but
1238     			   the bttv driver uses a video_channel arg, which
1239     			   makes sense becasue it also has the norm flag.
1240     			 */
1241     			struct video_channel v;
1242     
1243     			if (copy_from_user(&v, arg, sizeof(v)))
1244     				return -EFAULT;
1245     
1246     			if (v.channel != 0)
1247     				return -EINVAL;
1248     
1249     			return 0;
1250     		}
1251     
1252     
1253     		/* Picture functions; contrast etc. */
1254     		case VIDIOCGPICT:
1255     		{
1256     			struct video_picture p;
1257     			int val;
1258     
1259     			p.colour = 0x8000;
1260     			p.hue = 0x8000;
1261     			val = pwc_get_brightness(pdev);
1262     			if (val >= 0)
1263     				p.brightness = val;
1264     			else
1265     				p.brightness = 0xffff;
1266     			val = pwc_get_contrast(pdev);
1267     			if (val >= 0)
1268     				p.contrast = val;
1269     			else
1270     				p.contrast = 0xffff;
1271     			/* Gamma, Whiteness, what's the difference? :) */
1272     			val = pwc_get_gamma(pdev);
1273     			if (val >= 0)
1274     				p.whiteness = val;
1275     			else
1276     				p.whiteness = 0xffff;
1277     			val = pwc_get_saturation(pdev);
1278     			if (val >= 0)
1279     				p.colour = val;
1280     			else
1281     				p.colour = 0xffff;
1282     			p.depth = 24;
1283     			p.palette = pdev->vpalette;
1284     			p.hue = 0xFFFF; /* N/A */
1285     
1286     			if (copy_to_user(arg, &p, sizeof(p)))
1287     				return -EFAULT;
1288     			break;
1289     		}
1290     		
1291     		case VIDIOCSPICT:
1292     		{
1293     			struct video_picture p;
1294     
1295     			if (copy_from_user(&p, arg, sizeof(p)))
1296     				return -EFAULT;
1297     
1298     			/*
1299     			 *	FIXME:	Suppose we are mid read
1300     			        ANSWER: No problem: the firmware of the camera
1301     			                can handle brightness/contrast/etc
1302     			                changes at _any_ time, and the palette
1303     			                is used exactly once in the uncompress
1304     			                routine.
1305     			 */
1306     			pwc_set_brightness(pdev, p.brightness);
1307     			pwc_set_contrast(pdev, p.contrast);
1308     			pwc_set_gamma(pdev, p.whiteness);
1309     			pwc_set_saturation(pdev, p.colour);
1310     			if (p.palette && p.palette != pdev->vpalette) {
1311     				if (pwc_set_palette(pdev, p.palette) < 0)
1312     					return -EINVAL;
1313     			}
1314     			break;
1315     		}
1316     
1317     		/* Window/size parameters */		
1318     		case VIDIOCGWIN:
1319     		{
1320     			struct video_window vw;
1321     			
1322     			vw.x = 0;
1323     			vw.y = 0;
1324     			vw.width = pdev->view.x;
1325     			vw.height = pdev->view.y;
1326     			vw.chromakey = 0;
1327     			vw.flags = (pdev->vframes << PWC_FPS_SHIFT) | 
1328     			           (pdev->vsnapshot ? PWC_FPS_SNAPSHOT : 0);
1329     			
1330     			if (copy_to_user(arg, &vw, sizeof(vw)))
1331     				return -EFAULT;			
1332     			break;
1333     		}
1334     		
1335     		case VIDIOCSWIN:
1336     		{
1337     			struct video_window vw;
1338     			int fps, snapshot, ret;
1339     		
1340     			if (copy_from_user(&vw, arg, sizeof(vw)))
1341     				return -EFAULT;
1342     
1343     			fps = (vw.flags & PWC_FPS_FRMASK) >> PWC_FPS_SHIFT;
1344     			snapshot = vw.flags & PWC_FPS_SNAPSHOT;
1345     			if (fps == 0)
1346     				fps = pdev->vframes;
1347     			if (pdev->view.x == vw.width && pdev->view.y && fps == pdev->vframes && snapshot == pdev->vsnapshot)
1348     				return 0;
1349     			ret = pwc_try_video_mode(pdev, vw.width, vw.height, fps, pdev->vcompression, snapshot);
1350     			if (ret)
1351     				return ret;
1352     			break;		
1353     		}
1354     		
1355     		/* We don't have overlay support (yet) */
1356     		case VIDIOCGFBUF:
1357     		{
1358     			struct video_buffer vb;
1359     			
1360     			vb.base = NULL;
1361     			vb.height = 0;
1362     			vb.width = 0;
1363     			vb.depth = 0;
1364     			vb.bytesperline = 0;
1365     			
1366     			if (copy_to_user((void *)arg, (void *)&vb, sizeof(vb)))
1367     				return -EFAULT;
1368     			break;
1369     		}
1370     
1371     		/* mmap() functions */
1372     		case VIDIOCGMBUF:
1373     		{
1374     			/* Tell the user program how much memory is needed for a mmap() */
1375     			struct video_mbuf vm;
1376     			int i;
1377     
1378     			memset(&vm, 0, sizeof(vm));
1379     			vm.size = default_mbufs * pdev->len_per_image;
1380     			vm.frames = default_mbufs; /* double buffering should be enough for most applications */
1381     			for (i = 0; i < default_mbufs; i++)
1382     				vm.offsets[i] = i * pdev->len_per_image;
1383     
1384     			if (copy_to_user((void *)arg, (void *)&vm, sizeof(vm)))
1385     				return -EFAULT;
1386     			break;
1387     		}
1388     
1389     		case VIDIOCMCAPTURE:
1390     		{
1391     			/* Start capture into a given image buffer (called 'frame' in video_mmap structure) */
1392     			struct video_mmap vm;
1393     
1394     			if (copy_from_user((void *)&vm, (void *)arg, sizeof(vm)))
1395     				return -EFAULT;
1396     			Trace(TRACE_READ, "VIDIOCMCAPTURE: %dx%d, frame %d, format %d\n", vm.width, vm.height, vm.frame, vm.format);
1397     			if (vm.frame < 0 || vm.frame >= default_mbufs)
1398     				return -EINVAL;
1399     
1400     			/* xawtv is nasty. It probes the available palettes
1401     			   by setting a very small image size and trying
1402     			   various palettes... The driver doesn't support
1403     			   such small images, so I'm working around it.
1404     			 */
1405     			if (vm.format && vm.format != pdev->vpalette)
1406     				if (pwc_set_palette(pdev, vm.format) < 0)
1407     					return -EINVAL;
1408     			 
1409     			if ((vm.width != pdev->view.x || vm.height != pdev->view.y) &&
1410     			    (vm.width >= pdev->view_min.x && vm.height >= pdev->view_min.y)) {
1411     				int ret;
1412     				
1413     				Trace(TRACE_OPEN, "VIDIOCMCAPTURE: changing size to please xawtv :-(.\n");
1414     				ret = pwc_try_video_mode(pdev, vm.width, vm.height, pdev->vframes, pdev->vcompression, pdev->vsnapshot);
1415     				if (ret)
1416     					return ret;
1417     			} /* ... size mismatch */
1418     
1419     			/* FIXME: should we lock here? */
1420     			if (pdev->image_used[vm.frame])
1421     				return -EBUSY;	/* buffer wasn't available. Bummer */
1422     			pdev->image_used[vm.frame] = 1;
1423     
1424     			/* Okay, we're done here. In the SYNC call we wait until a 
1425     			   frame comes available, then expand image into the given 
1426     			   buffer.
1427     			   In contrast to the CPiA cam the Philips cams deliver a 
1428     			   constant stream, almost like a grabber card. Also,
1429     			   we have separate buffers for the rawdata and the image,
1430     			   meaning we can nearly always expand into the requested buffer.
1431     			 */
1432     			Trace(TRACE_READ, "VIDIOCMCAPTURE done.\n");
1433     			break;
1434     		}
1435     
1436     		case VIDIOCSYNC:
1437     		{
1438     			/* The doc says: "Whenever a buffer is used it should
1439     			   call VIDIOCSYNC to free this frame up and continue."
1440     			   
1441     			   The only odd thing about this whole procedure is 
1442     			   that MCAPTURE flags the buffer as "in use", and
1443     			   SYNC immediately unmarks it, while it isn't 
1444     			   after SYNC that you know that the buffer actually
1445     			   got filled! So you better not start a CAPTURE in
1446     			   the same frame immediately (use double buffering). 
1447     			   This is not a problem for this cam, since it has 
1448     			   extra intermediate buffers, but a hardware 
1449     			   grabber card will then overwrite the buffer 
1450     			   you're working on.
1451     			 */
1452     			int mbuf, ret;
1453     
1454     			if (copy_from_user((void *)&mbuf, arg, sizeof(int)))
1455     				return -EFAULT;
1456     
1457     			Trace(TRACE_READ, "VIDIOCSYNC called (%d).\n", mbuf);
1458     
1459     			/* bounds check */
1460     			if (mbuf < 0 || mbuf >= default_mbufs)
1461     				return -EINVAL;
1462     			/* check if this buffer was requested anyway */
1463     			if (pdev->image_used[mbuf] == 0)
1464     				return -EINVAL;
1465     
1466     			/* Add ourselves to the frame wait-queue.
1467     			   
1468     			   FIXME: needs auditing for safety.
1469     			   QUSTION: In what respect? I think that using the
1470     			            frameq is safe now.
1471     			 */
1472     			add_wait_queue(&pdev->frameq, &wait);
1473     			while (pdev->full_frames == NULL) {
1474     	                	if (signal_pending(current)) {
1475     	                		remove_wait_queue(&pdev->frameq, &wait);
1476     		                	current->state = TASK_RUNNING;
1477     		                	return -ERESTARTSYS;
1478     	        	        }
1479     	                	schedule();
1480     		                current->state = TASK_INTERRUPTIBLE;
1481     			}
1482     			remove_wait_queue(&pdev->frameq, &wait);
1483     			current->state = TASK_RUNNING;
1484     				
1485     			/* The frame is ready. Expand in the image buffer 
1486     			   requested by the user. I don't care if you 
1487     			   mmap() 5 buffers and request data in this order: 
1488     			   buffer 4 2 3 0 1 2 3 0 4 3 1 . . .
1489     			   Grabber hardware may not be so forgiving.
1490     			 */
1491     			Trace(TRACE_READ, "VIDIOCSYNC: frame ready.\n");
1492     			pdev->fill_image = mbuf; /* tell in which buffer we want the image to be expanded */
1493     			/* Decompress, etc */
1494     			ret = pwc_handle_frame(pdev);
1495     			pdev->image_used[mbuf] = 0;
1496     			if (ret)
1497     				return -EFAULT;
1498     			break;
1499     		}
1500     		
1501     		case VIDIOCGAUDIO:
1502     		{
1503     			struct video_audio v;
1504     			
1505     			strcpy(v.name, "Microphone");
1506     			v.audio = -1; /* unknown audio minor */
1507     			v.flags = 0;
1508     			v.mode = VIDEO_SOUND_MONO;
1509     			v.volume = 0;
1510     			v.bass = 0;
1511     			v.treble = 0;
1512     			v.balance = 0x8000;
1513     			v.step = 1;
1514     			
1515     			if (copy_to_user(arg, &v, sizeof(v)))
1516     				return -EFAULT;
1517     			break;	
1518     		}
1519     		
1520     		case VIDIOCSAUDIO:
1521     		{
1522     			struct video_audio v;
1523     			
1524     			if (copy_from_user(&v, arg, sizeof(v)))
1525     				return -EFAULT;
1526     			/* Dummy: nothing can be set */
1527     			break;
1528     		}
1529     		
1530     		case VIDIOCGUNIT:
1531     		{
1532     			struct video_unit vu;
1533     			
1534     			vu.video = pdev->vdev->minor & 0x3F;
1535     			vu.audio = -1; /* not known yet */
1536     			vu.vbi = -1;
1537     			vu.radio = -1;
1538     			vu.teletext = -1;
1539     			if (copy_to_user(arg, &vu, sizeof(vu)))
1540     				return -EFAULT;
1541     			break;
1542     		}
1543     		default:
1544     			return pwc_ioctl(pdev, cmd, arg);
1545     	} /* ..switch */
1546     	return 0;
1547     }	
1548     
1549     static int pwc_video_mmap(struct video_device *vdev, const char *adr, unsigned long size)
1550     {
1551     	struct pwc_device *pdev;
1552     	unsigned long start = (unsigned long)adr;
1553     	unsigned long page, pos;
1554     	
1555     	Trace(TRACE_MEMORY, "mmap(0x%p, 0x%p, %lu) called.\n", vdev, adr, size);
1556     	pdev = vdev->priv;
1557     
1558     	/* FIXME - audit mmap during a read */		
1559     	pos = (unsigned long)pdev->image_data;
1560     	while (size > 0) {
1561     		page = kvirt_to_pa(pos);
1562     		if (remap_page_range(start, page, PAGE_SIZE, PAGE_SHARED))
1563     			return -EAGAIN;
1564     
1565     		start += PAGE_SIZE;
1566     		pos += PAGE_SIZE;
1567     		if (size > PAGE_SIZE)
1568     			size -= PAGE_SIZE;
1569     		else
1570     			size = 0;
1571     	}
1572     
1573     	return 0;
1574     }
1575     
1576     /***************************************************************************/
1577     /* USB functions */
1578     
1579     /* This function gets called when a new device is plugged in or the usb core
1580      * is loaded.
1581      */
1582     
1583     static void *usb_pwc_probe(struct usb_device *udev, unsigned int ifnum, const struct usb_device_id *id)
1584     {
1585     	struct pwc_device *pdev = NULL;
1586     	struct video_device *vdev;
1587     	int vendor_id, product_id, type_id;
1588     	int i;
1589     
1590     	free_mem_leak();
1591     	
1592     	/* Check if we can handle this device */
1593     	Trace(TRACE_PROBE, "probe() called [%04X %04X], if %d\n", udev->descriptor.idVendor, udev->descriptor.idProduct, ifnum);
1594     
1595     	/* the interfaces are probed one by one. We are only interested in the
1596     	   video interface (0) now.
1597     	   Interface 1 is the Audio Control, and interface 2 Audio itself.
1598     	 */
1599     	if (ifnum > 0) 
1600     		return NULL;
1601     
1602     	vendor_id = udev->descriptor.idVendor;
1603     	product_id = udev->descriptor.idProduct;
1604     
1605     	if (vendor_id == 0x0471) {
1606     		switch (product_id) {
1607     		case 0x0302:
1608     			Info("Philips PCA645VC USB webcam detected.\n");
1609     			type_id = 645;
1610     			break;
1611     		case 0x0303:
1612     			Info("Philips PCA646VC USB webcam detected.\n");
1613     			type_id = 646;
1614     			break;
1615     		case 0x0304:
1616     			Info("Askey VC010 type 2 USB webcam detected.\n");
1617     			type_id = 646;
1618     			break;
1619     		case 0x0307:
1620     			Info("Philips PCVC675K (Vesta) USB webcam detected.\n");
1621     			type_id = 675;
1622     			break;
1623     		case 0x0308:
1624     			Info("Philips PCVC680K (Vesta Pro) USB webcam detected.\n");
1625     			type_id = 680;
1626     			break;
1627     		case 0x030C:
1628     			Info("Philips PCVC690K (Vesta Pro Scan) USB webcam detected.\n");
1629     			type_id = 690;
1630     			break;
1631     		case 0x0310:
1632     			Info("Philips PCVC730K (ToUCam Fun) USB webcam detected.\n");
1633     			type_id = 730;
1634     			break;
1635     		case 0x0311:
1636     			Info("Philips PCVC740K (ToUCam Pro) USB webcam detected.\n");
1637     			type_id = 740;
1638     			break;
1639     		case 0x0312:
1640     			Info("Philips PCVC750K (ToUCam Pro Scan) USB webcam detected.\n");
1641     			type_id = 750;
1642     			break;
1643     		default:
1644     			return NULL;
1645     			break;
1646     		}
1647     	}
1648     	else if (vendor_id == 0x069A) {
1649     		switch(product_id) {
1650     		case 0x0001:
1651     			Info("Askey VC010 type 1 USB webcam detected.\n");
1652     			type_id = 645;
1653     			break;
1654     		default:
1655     			return NULL;
1656     			break;
1657     		}
1658     	}
1659             else if (vendor_id == 0x046d) {
1660             	switch(product_id) {
1661             	case 0x08b0:
1662             		Info("Logitech QuickCam 3000 Pro detected.\n");
1663             		type_id = 730;
1664             		break;
1665             	default:
1666             		return NULL;
1667             		break;
1668             	}
1669             }
1670             else return NULL; /* Not Philips or Askey, for sure. */
1671     
1672     	if (udev->descriptor.bNumConfigurations > 1)
1673     		Info("Warning: more than 1 configuration available.\n");
1674     
1675     	/* Allocate structure, initialize pointers, mutexes, etc. and link it to the usb_device */
1676     	pdev = kmalloc(sizeof(struct pwc_device), GFP_KERNEL);
1677     	if (pdev == NULL) {
1678     		Err("Oops, could not allocate memory for pwc_device.\n");
1679     		return NULL;
1680     	}
1681     	memset(pdev, 0, sizeof(struct pwc_device));
1682     	pdev->type = type_id;
1683     	pwc_construct(pdev);
1684     
1685     	init_MUTEX(&pdev->modlock);
1686     	pdev->ptrlock = SPIN_LOCK_UNLOCKED;
1687     
1688     	pdev->udev = udev;
1689     	init_waitqueue_head(&pdev->frameq);
1690     	init_waitqueue_head(&pdev->remove_ok);
1691     	pdev->vcompression = pwc_preferred_compression;
1692     
1693     	/* Now hook it up to the video subsystem */
1694     	vdev = kmalloc(sizeof(struct video_device), GFP_KERNEL);
1695     	if (vdev == NULL) {
1696     		Err("Oops, could not allocate memory for video_device.\n");
1697     		return NULL;
1698     	}
1699     	memcpy(vdev, &pwc_template, sizeof(pwc_template));
1700     	sprintf(vdev->name, "Philips %d webcam", pdev->type);
1701     	SET_MODULE_OWNER(vdev);
1702     	pdev->vdev = vdev;
1703     	vdev->priv = pdev;
1704     
1705     	pdev->release = udev->descriptor.bcdDevice;
1706     	Trace(TRACE_PROBE, "Release: %04x\n", pdev->release);
1707     
1708     	i = video_register_device(vdev, VFL_TYPE_GRABBER, video_nr);
1709     	if (i < 0) {
1710     		Err("Failed to register as video device (%d).\n", i);
1711     		return NULL;
1712     	}
1713     	else {
1714     		Trace(TRACE_PROBE, "Registered video struct at 0x%p.\n", vdev);
1715     		Info("Registered as /dev/video%d.\n", vdev->minor & 0x3F);
1716     	}
1717     
1718     #if 0
1719     	/* Shut down camera now (some people like the LED off) */
1720     	if (power_save) {
1721     		Trace(TRACE_PROBE, "Powering down camera");
1722     		i = pwc_camera_power(pdev, 0);
1723     		if (i < 0)
1724     			Info("Failed to power-down the camera (%d)\n", i);
1725     	}
1726     #endif
1727     
1728     	Trace(TRACE_PROBE, "probe() function returning struct at 0x%p.\n", pdev);
1729     	return pdev;
1730     }
1731     
1732     /* The user janked out the cable... */
1733     static void usb_pwc_disconnect(struct usb_device *udev, void *ptr)
1734     {
1735     	struct pwc_device *pdev;
1736     
1737     	lock_kernel();
1738     	free_mem_leak();
1739     
1740     	pdev = (struct pwc_device *)ptr;
1741     	if (pdev == NULL) {
1742     		Err("pwc_disconnect() Called without private pointer.\n");
1743     		return;
1744     	}
1745     	if (pdev->udev == NULL) {
1746     		Err("pwc_disconnect() already called for %p\n", pdev);
1747     		return;
1748     	}
1749     	if (pdev->udev != udev) {
1750     		Err("pwc_disconnect() Woops: pointer mismatch udev/pdev.\n");
1751     		return;
1752     	}
1753     #ifdef PWC_MAGIC	
1754     	if (pdev->magic != PWC_MAGIC) {
1755     		Err("pwc_disconnect() Magic number failed. Consult your scrolls and try again.\n");
1756     		return;
1757     	}
1758     #endif	
1759     	
1760     	pdev->unplugged = 1;
1761     	if (pdev->vdev != NULL) {
1762     		if (pdev->vopen) {
1763     			Info("Disconnected while device/video is open!\n");
1764     			
1765     			/* Wake up any processes that might be waiting for
1766     			   a frame, let them return an error condition
1767     			 */
1768     			wake_up(&pdev->frameq);
1769     			
1770     			/* Wait until we get a 'go' from _close(). This
1771     			   had a gigantic race condition, since we kfree()
1772     			   stuff here, but we have to wait until close() 
1773     			   is finished. */
1774     			   
1775     			Trace(TRACE_PROBE, "Sleeping on remove_ok.\n");
1776     			sleep_on(&pdev->remove_ok);
1777     			Trace(TRACE_PROBE, "Done sleeping.\n");
1778     			set_mem_leak(pdev->vdev);
1779     			pdev->vdev = NULL;
1780     		}
1781     		else {
1782     			/* Normal disconnect; remove from available devices */
1783     			Trace(TRACE_PROBE, "Unregistering video device normally.\n");
1784     			video_unregister_device(pdev->vdev); 
1785     			kfree(pdev->vdev);
1786     			pdev->vdev = NULL;
1787     		}
1788     	}
1789     	pdev->udev = NULL;
1790     	unlock_kernel();
1791     	kfree(pdev);
1792     }
1793     
1794     
1795     
1796     /* 
1797      * Initialization code & module stuff 
1798      */
1799     
1800     static char *size = NULL;
1801     static int fps = 0;
1802     static char *palette = NULL;
1803     static int fbufs = 0;
1804     static int mbufs = 0;
1805     static int trace = -1;
1806     static int compression = -1;
1807     
1808     MODULE_PARM(video_nr, "i");
1809     MODULE_PARM(size, "s");
1810     MODULE_PARM_DESC(size, "Initial image size. One of sqcif, qsif, qcif, sif, cif, vga");
1811     MODULE_PARM(fps, "i");
1812     MODULE_PARM_DESC(fps, "Initial frames per second. Varies with model, useful range 5-30");
1813     MODULE_PARM(palette, "s");
1814     MODULE_PARM_DESC(palette, "Initial colour format of images. One of yuv420, yuv420p");
1815     MODULE_PARM(fbufs, "i");
1816     MODULE_PARM_DESC(fbufs, "Number of internal frame buffers to reserve");
1817     MODULE_PARM(mbufs, "i");
1818     MODULE_PARM_DESC(mbufs, "Number of external (mmap()ed) image buffers");
1819     MODULE_PARM(trace, "i");
1820     MODULE_PARM_DESC(trace, "For debugging purposes");
1821     MODULE_PARM(power_save, "i");
1822     MODULE_PARM_DESC(power_save, "Turn power save feature in camera on or off");
1823     MODULE_PARM(compression, "i");
1824     MODULE_PARM_DESC(compression, "Preferred compression quality. Range 0 (uncompressed) to 3 (high compression)");
1825     
1826     MODULE_DESCRIPTION("Philips USB webcam driver");
1827     MODULE_AUTHOR("Nemosoft Unv. <nemosoft@smcc.demon.nl>");
1828     MODULE_LICENSE("GPL");
1829     
1830     static int __init usb_pwc_init(void)
1831     {
1832     	int s;
1833     	char *sizenames[PSZ_MAX] = { "sqcif", "qsif", "qcif", "sif", "cif", "vga" };
1834     
1835     	Info("Philips PCA645/646 + PCVC675/680/690 + PCVC730/740/750 webcam module version " PWC_VERSION " loaded.\n");
1836     	Info("Also supports Askey VC010 cam.\n");
1837     
1838     	if (fps) {
1839     		if (fps < 5 || fps > 30) {
1840     			Err("Framerate out of bounds (5-30).\n");
1841     			return -EINVAL;
1842     		}
1843     		default_fps = fps;
1844     		Info("Default framerate set to %d.\n", default_fps);
1845     	}
1846     	
1847     	if (size) {
1848     		/* string; try matching with array */
1849     		for (s = 0; s < PSZ_MAX; s++) {
1850     			if (!strcmp(sizenames[s], size)) { /* Found! */
1851     				default_size = s;
1852     				break;
1853     			}
1854     		}
1855     		if (s == PSZ_MAX) {
1856     			Err("Size not recognized; try size=[sqcif | qsif | qcif | sif | cif | vga].\n");
1857     			return -EINVAL;
1858     		}
1859     		Info("Default image size set to %s [%dx%d].\n", sizenames[default_size], pwc_image_sizes[default_size].x, pwc_image_sizes[default_size].y);
1860     	}
1861     	if (palette) {
1862     		/* Determine default palette */
1863     		if (!strcmp(palette, "yuv420"))
1864     			default_palette = VIDEO_PALETTE_YUV420;
1865     		else if (!strcmp(palette, "yuv420p"))
1866     			default_palette = VIDEO_PALETTE_YUV420P;
1867     		else {
1868     			Err("Palette not recognized: try palette=yuv420 or yuv420p.\n");
1869     			return -EINVAL;
1870     		}
1871     		Info("Default palette set to %d.\n", default_palette);
1872     	}
1873     	if (mbufs) {
1874     		if (mbufs < 1 || mbufs > MAX_IMAGES) {
1875     			Err("Illegal number of mmap() buffers; use a number between 1 and %d.\n", MAX_IMAGES);
1876     			return -EINVAL;
1877     		}
1878     		default_mbufs = mbufs;
1879     		Info("Number of image buffers set to %d.\n", default_mbufs);
1880     	}
1881     	if (fbufs) {
1882     		if (fbufs < 2 || fbufs > MAX_FRAMES) {
1883     			Err("Illegal number of frame buffers; use a number between 2 and %d.\n", MAX_FRAMES);
1884     			return -EINVAL;
1885     		}
1886     		default_fbufs = fbufs;
1887     		Info("Number of frame buffers set to %d.\n", default_fbufs);
1888     	}
1889     	if (trace >= 0) {
1890     		Info("Trace options: 0x%04x\n", trace);
1891     		pwc_trace = trace;
1892     	}
1893     	if (compression >= 0) {
1894     		if (compression > 3) {
1895     			Err("Invalid compression setting; use a number between 0 (uncompressed) and 3 (high).\n");
1896     			return -EINVAL;
1897     		}
1898     		pwc_preferred_compression = compression;
1899     		Info("Preferred compression set to %d.\n", pwc_preferred_compression);
1900     	}
1901     	if (power_save)
1902     		Info("Enabling power save on open/close.\n");
1903     
1904     	init_MUTEX(&mem_lock);
1905      	Trace(TRACE_PROBE, "Registering driver at address 0x%p.\n", &pwc_driver);
1906     	return usb_register(&pwc_driver);
1907     }
1908     
1909     static void __exit usb_pwc_exit(void)
1910     {
1911     	free_mem_leak();
1912     	Trace(TRACE_MODULE, "Deregistering driver.\n");
1913     	usb_deregister(&pwc_driver);
1914     	Info("Philips webcam module removed.\n");
1915     }
1916     
1917     module_init(usb_pwc_init);
1918     module_exit(usb_pwc_exit);
1919     
1920