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