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