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