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