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