GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / media / usb / zr364xx / zr364xx.c
1 /*
2  * Zoran 364xx based USB webcam module version 0.73
3  *
4  * Allows you to use your USB webcam with V4L2 applications
5  * This is still in heavy developpement !
6  *
7  * Copyright (C) 2004  Antoine Jacquet <royale@zerezo.com>
8  * http://royale.zerezo.com/zr364xx/
9  *
10  * Heavily inspired by usb-skeleton.c, vicam.c, cpia.c and spca50x.c drivers
11  * V4L2 version inspired by meye.c driver
12  *
13  * Some video buffer code by Lamarque based on s2255drv.c and vivi.c drivers.
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  */
25
26
27 #include <linux/module.h>
28 #include <linux/init.h>
29 #include <linux/usb.h>
30 #include <linux/vmalloc.h>
31 #include <linux/slab.h>
32 #include <linux/proc_fs.h>
33 #include <linux/highmem.h>
34 #include <media/v4l2-common.h>
35 #include <media/v4l2-ioctl.h>
36 #include <media/v4l2-device.h>
37 #include <media/v4l2-ctrls.h>
38 #include <media/v4l2-fh.h>
39 #include <media/v4l2-event.h>
40 #include <media/videobuf-vmalloc.h>
41
42
43 /* Version Information */
44 #define DRIVER_VERSION "0.7.4"
45 #define DRIVER_AUTHOR "Antoine Jacquet, http://royale.zerezo.com/"
46 #define DRIVER_DESC "Zoran 364xx"
47
48
49 /* Camera */
50 #define FRAMES 1
51 #define MAX_FRAME_SIZE 200000
52 #define BUFFER_SIZE 0x1000
53 #define CTRL_TIMEOUT 500
54
55 #define ZR364XX_DEF_BUFS        4
56 #define ZR364XX_READ_IDLE       0
57 #define ZR364XX_READ_FRAME      1
58
59 /* Debug macro */
60 #define DBG(fmt, args...) \
61         do { \
62                 if (debug) { \
63                         printk(KERN_INFO KBUILD_MODNAME " " fmt, ##args); \
64                 } \
65         } while (0)
66
67 /*#define FULL_DEBUG 1*/
68 #ifdef FULL_DEBUG
69 #define _DBG DBG
70 #else
71 #define _DBG(fmt, args...)
72 #endif
73
74 /* Init methods, need to find nicer names for these
75  * the exact names of the chipsets would be the best if someone finds it */
76 #define METHOD0 0
77 #define METHOD1 1
78 #define METHOD2 2
79 #define METHOD3 3
80
81
82 /* Module parameters */
83 static int debug;
84 static int mode;
85
86
87 /* Module parameters interface */
88 module_param(debug, int, 0644);
89 MODULE_PARM_DESC(debug, "Debug level");
90 module_param(mode, int, 0644);
91 MODULE_PARM_DESC(mode, "0 = 320x240, 1 = 160x120, 2 = 640x480");
92
93
94 /* Devices supported by this driver
95  * .driver_info contains the init method used by the camera */
96 static const struct usb_device_id device_table[] = {
97         {USB_DEVICE(0x08ca, 0x0109), .driver_info = METHOD0 },
98         {USB_DEVICE(0x041e, 0x4024), .driver_info = METHOD0 },
99         {USB_DEVICE(0x0d64, 0x0108), .driver_info = METHOD0 },
100         {USB_DEVICE(0x0546, 0x3187), .driver_info = METHOD0 },
101         {USB_DEVICE(0x0d64, 0x3108), .driver_info = METHOD0 },
102         {USB_DEVICE(0x0595, 0x4343), .driver_info = METHOD0 },
103         {USB_DEVICE(0x0bb0, 0x500d), .driver_info = METHOD0 },
104         {USB_DEVICE(0x0feb, 0x2004), .driver_info = METHOD0 },
105         {USB_DEVICE(0x055f, 0xb500), .driver_info = METHOD0 },
106         {USB_DEVICE(0x08ca, 0x2062), .driver_info = METHOD2 },
107         {USB_DEVICE(0x052b, 0x1a18), .driver_info = METHOD1 },
108         {USB_DEVICE(0x04c8, 0x0729), .driver_info = METHOD0 },
109         {USB_DEVICE(0x04f2, 0xa208), .driver_info = METHOD0 },
110         {USB_DEVICE(0x0784, 0x0040), .driver_info = METHOD1 },
111         {USB_DEVICE(0x06d6, 0x0034), .driver_info = METHOD0 },
112         {USB_DEVICE(0x0a17, 0x0062), .driver_info = METHOD2 },
113         {USB_DEVICE(0x06d6, 0x003b), .driver_info = METHOD0 },
114         {USB_DEVICE(0x0a17, 0x004e), .driver_info = METHOD2 },
115         {USB_DEVICE(0x041e, 0x405d), .driver_info = METHOD2 },
116         {USB_DEVICE(0x08ca, 0x2102), .driver_info = METHOD3 },
117         {USB_DEVICE(0x06d6, 0x003d), .driver_info = METHOD0 },
118         {}                      /* Terminating entry */
119 };
120
121 MODULE_DEVICE_TABLE(usb, device_table);
122
123 /* frame structure */
124 struct zr364xx_framei {
125         unsigned long ulState;  /* ulState:ZR364XX_READ_IDLE,
126                                            ZR364XX_READ_FRAME */
127         void *lpvbits;          /* image data */
128         unsigned long cur_size; /* current data copied to it */
129 };
130
131 /* image buffer structure */
132 struct zr364xx_bufferi {
133         unsigned long dwFrames;                 /* number of frames in buffer */
134         struct zr364xx_framei frame[FRAMES];    /* array of FRAME structures */
135 };
136
137 struct zr364xx_dmaqueue {
138         struct list_head        active;
139         struct zr364xx_camera   *cam;
140 };
141
142 struct zr364xx_pipeinfo {
143         u32 transfer_size;
144         u8 *transfer_buffer;
145         u32 state;
146         void *stream_urb;
147         void *cam;      /* back pointer to zr364xx_camera struct */
148         u32 err_count;
149         u32 idx;
150 };
151
152 struct zr364xx_fmt {
153         char *name;
154         u32 fourcc;
155         int depth;
156 };
157
158 /* image formats.  */
159 static const struct zr364xx_fmt formats[] = {
160         {
161                 .name = "JPG",
162                 .fourcc = V4L2_PIX_FMT_JPEG,
163                 .depth = 24
164         }
165 };
166
167 /* Camera stuff */
168 struct zr364xx_camera {
169         struct usb_device *udev;        /* save off the usb device pointer */
170         struct usb_interface *interface;/* the interface for this device */
171         struct v4l2_device v4l2_dev;
172         struct v4l2_ctrl_handler ctrl_handler;
173         struct video_device vdev;       /* v4l video device */
174         struct v4l2_fh *owner;          /* owns the streaming */
175         int nb;
176         struct zr364xx_bufferi          buffer;
177         int skip;
178         int width;
179         int height;
180         int method;
181         struct mutex lock;
182
183         spinlock_t              slock;
184         struct zr364xx_dmaqueue vidq;
185         int                     last_frame;
186         int                     cur_frame;
187         unsigned long           frame_count;
188         int                     b_acquire;
189         struct zr364xx_pipeinfo pipe[1];
190
191         u8                      read_endpoint;
192
193         const struct zr364xx_fmt *fmt;
194         struct videobuf_queue   vb_vidq;
195         bool was_streaming;
196 };
197
198 /* buffer for one video frame */
199 struct zr364xx_buffer {
200         /* common v4l buffer stuff -- must be first */
201         struct videobuf_buffer vb;
202         const struct zr364xx_fmt *fmt;
203 };
204
205 /* function used to send initialisation commands to the camera */
206 static int send_control_msg(struct usb_device *udev, u8 request, u16 value,
207                             u16 index, unsigned char *cp, u16 size)
208 {
209         int status;
210
211         unsigned char *transfer_buffer = kmalloc(size, GFP_KERNEL);
212         if (!transfer_buffer)
213                 return -ENOMEM;
214
215         memcpy(transfer_buffer, cp, size);
216
217         status = usb_control_msg(udev,
218                                  usb_sndctrlpipe(udev, 0),
219                                  request,
220                                  USB_DIR_OUT | USB_TYPE_VENDOR |
221                                  USB_RECIP_DEVICE, value, index,
222                                  transfer_buffer, size, CTRL_TIMEOUT);
223
224         kfree(transfer_buffer);
225         return status;
226 }
227
228
229 /* Control messages sent to the camera to initialize it
230  * and launch the capture */
231 typedef struct {
232         unsigned int value;
233         unsigned int size;
234         unsigned char *bytes;
235 } message;
236
237 /* method 0 */
238 static unsigned char m0d1[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
239 static unsigned char m0d2[] = { 0, 0, 0, 0, 0, 0 };
240 static unsigned char m0d3[] = { 0, 0 };
241 static message m0[] = {
242         {0x1f30, 0, NULL},
243         {0xd000, 0, NULL},
244         {0x3370, sizeof(m0d1), m0d1},
245         {0x2000, 0, NULL},
246         {0x2f0f, 0, NULL},
247         {0x2610, sizeof(m0d2), m0d2},
248         {0xe107, 0, NULL},
249         {0x2502, 0, NULL},
250         {0x1f70, 0, NULL},
251         {0xd000, 0, NULL},
252         {0x9a01, sizeof(m0d3), m0d3},
253         {-1, -1, NULL}
254 };
255
256 /* method 1 */
257 static unsigned char m1d1[] = { 0xff, 0xff };
258 static unsigned char m1d2[] = { 0x00, 0x00 };
259 static message m1[] = {
260         {0x1f30, 0, NULL},
261         {0xd000, 0, NULL},
262         {0xf000, 0, NULL},
263         {0x2000, 0, NULL},
264         {0x2f0f, 0, NULL},
265         {0x2650, 0, NULL},
266         {0xe107, 0, NULL},
267         {0x2502, sizeof(m1d1), m1d1},
268         {0x1f70, 0, NULL},
269         {0xd000, 0, NULL},
270         {0xd000, 0, NULL},
271         {0xd000, 0, NULL},
272         {0x9a01, sizeof(m1d2), m1d2},
273         {-1, -1, NULL}
274 };
275
276 /* method 2 */
277 static unsigned char m2d1[] = { 0xff, 0xff };
278 static message m2[] = {
279         {0x1f30, 0, NULL},
280         {0xf000, 0, NULL},
281         {0x2000, 0, NULL},
282         {0x2f0f, 0, NULL},
283         {0x2650, 0, NULL},
284         {0xe107, 0, NULL},
285         {0x2502, sizeof(m2d1), m2d1},
286         {0x1f70, 0, NULL},
287         {-1, -1, NULL}
288 };
289
290 /* init table */
291 static message *init[4] = { m0, m1, m2, m2 };
292
293
294 /* JPEG static data in header (Huffman table, etc) */
295 static unsigned char header1[] = {
296         0xFF, 0xD8,
297         /*
298         0xFF, 0xE0, 0x00, 0x10, 'J', 'F', 'I', 'F',
299         0x00, 0x01, 0x01, 0x00, 0x33, 0x8A, 0x00, 0x00, 0x33, 0x88,
300         */
301         0xFF, 0xDB, 0x00, 0x84
302 };
303 static unsigned char header2[] = {
304         0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01,
305         0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
306         0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
307         0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02,
308         0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01,
309         0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
310         0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1,
311         0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33,
312         0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25,
313         0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
314         0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54,
315         0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67,
316         0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,
317         0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94,
318         0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6,
319         0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8,
320         0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA,
321         0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
322         0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3,
323         0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xC4, 0x00, 0x1F,
324         0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
325         0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
326         0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5,
327         0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05,
328         0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11,
329         0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
330         0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1,
331         0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16,
332         0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27,
333         0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44,
334         0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57,
335         0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
336         0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84,
337         0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96,
338         0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8,
339         0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA,
340         0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3,
341         0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5,
342         0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
343         0xF8, 0xF9, 0xFA, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0xF0, 0x01,
344         0x40, 0x03, 0x01, 0x21, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
345         0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11,
346         0x00, 0x3F, 0x00
347 };
348 static unsigned char header3;
349
350 /* ------------------------------------------------------------------
351    Videobuf operations
352    ------------------------------------------------------------------*/
353
354 static int buffer_setup(struct videobuf_queue *vq, unsigned int *count,
355                         unsigned int *size)
356 {
357         struct zr364xx_camera *cam = vq->priv_data;
358
359         *size = cam->width * cam->height * (cam->fmt->depth >> 3);
360
361         if (*count == 0)
362                 *count = ZR364XX_DEF_BUFS;
363
364         if (*size * *count > ZR364XX_DEF_BUFS * 1024 * 1024)
365                 *count = (ZR364XX_DEF_BUFS * 1024 * 1024) / *size;
366
367         return 0;
368 }
369
370 static void free_buffer(struct videobuf_queue *vq, struct zr364xx_buffer *buf)
371 {
372         _DBG("%s\n", __func__);
373
374         BUG_ON(in_interrupt());
375
376         videobuf_vmalloc_free(&buf->vb);
377         buf->vb.state = VIDEOBUF_NEEDS_INIT;
378 }
379
380 static int buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
381                           enum v4l2_field field)
382 {
383         struct zr364xx_camera *cam = vq->priv_data;
384         struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
385                                                   vb);
386         int rc;
387
388         DBG("%s, field=%d, fmt name = %s\n", __func__, field,
389             cam->fmt ? cam->fmt->name : "");
390         if (!cam->fmt)
391                 return -EINVAL;
392
393         buf->vb.size = cam->width * cam->height * (cam->fmt->depth >> 3);
394
395         if (buf->vb.baddr != 0 && buf->vb.bsize < buf->vb.size) {
396                 DBG("invalid buffer prepare\n");
397                 return -EINVAL;
398         }
399
400         buf->fmt = cam->fmt;
401         buf->vb.width = cam->width;
402         buf->vb.height = cam->height;
403         buf->vb.field = field;
404
405         if (buf->vb.state == VIDEOBUF_NEEDS_INIT) {
406                 rc = videobuf_iolock(vq, &buf->vb, NULL);
407                 if (rc < 0)
408                         goto fail;
409         }
410
411         buf->vb.state = VIDEOBUF_PREPARED;
412         return 0;
413 fail:
414         free_buffer(vq, buf);
415         return rc;
416 }
417
418 static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
419 {
420         struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
421                                                   vb);
422         struct zr364xx_camera *cam = vq->priv_data;
423
424         _DBG("%s\n", __func__);
425
426         buf->vb.state = VIDEOBUF_QUEUED;
427         list_add_tail(&buf->vb.queue, &cam->vidq.active);
428 }
429
430 static void buffer_release(struct videobuf_queue *vq,
431                            struct videobuf_buffer *vb)
432 {
433         struct zr364xx_buffer *buf = container_of(vb, struct zr364xx_buffer,
434                                                   vb);
435
436         _DBG("%s\n", __func__);
437         free_buffer(vq, buf);
438 }
439
440 static const struct videobuf_queue_ops zr364xx_video_qops = {
441         .buf_setup = buffer_setup,
442         .buf_prepare = buffer_prepare,
443         .buf_queue = buffer_queue,
444         .buf_release = buffer_release,
445 };
446
447 /********************/
448 /* V4L2 integration */
449 /********************/
450 static int zr364xx_vidioc_streamon(struct file *file, void *priv,
451                                    enum v4l2_buf_type type);
452
453 static ssize_t zr364xx_read(struct file *file, char __user *buf, size_t count,
454                             loff_t * ppos)
455 {
456         struct zr364xx_camera *cam = video_drvdata(file);
457         int err = 0;
458
459         _DBG("%s\n", __func__);
460
461         if (!buf)
462                 return -EINVAL;
463
464         if (!count)
465                 return -EINVAL;
466
467         if (mutex_lock_interruptible(&cam->lock))
468                 return -ERESTARTSYS;
469
470         err = zr364xx_vidioc_streamon(file, file->private_data,
471                                 V4L2_BUF_TYPE_VIDEO_CAPTURE);
472         if (err == 0) {
473                 DBG("%s: reading %d bytes at pos %d.\n", __func__,
474                                 (int) count, (int) *ppos);
475
476                 /* NoMan Sux ! */
477                 err = videobuf_read_one(&cam->vb_vidq, buf, count, ppos,
478                                         file->f_flags & O_NONBLOCK);
479         }
480         mutex_unlock(&cam->lock);
481         return err;
482 }
483
484 /* video buffer vmalloc implementation based partly on VIVI driver which is
485  *          Copyright (c) 2006 by
486  *                  Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
487  *                  Ted Walther <ted--a.t--enumera.com>
488  *                  John Sokol <sokol--a.t--videotechnology.com>
489  *                  http://v4l.videotechnology.com/
490  *
491  */
492 static void zr364xx_fillbuff(struct zr364xx_camera *cam,
493                              struct zr364xx_buffer *buf,
494                              int jpgsize)
495 {
496         int pos = 0;
497         const char *tmpbuf;
498         char *vbuf = videobuf_to_vmalloc(&buf->vb);
499         unsigned long last_frame;
500
501         if (!vbuf)
502                 return;
503
504         last_frame = cam->last_frame;
505         if (last_frame != -1) {
506                 tmpbuf = (const char *)cam->buffer.frame[last_frame].lpvbits;
507                 switch (buf->fmt->fourcc) {
508                 case V4L2_PIX_FMT_JPEG:
509                         buf->vb.size = jpgsize;
510                         memcpy(vbuf, tmpbuf, buf->vb.size);
511                         break;
512                 default:
513                         printk(KERN_DEBUG KBUILD_MODNAME ": unknown format?\n");
514                 }
515                 cam->last_frame = -1;
516         } else {
517                 printk(KERN_ERR KBUILD_MODNAME ": =======no frame\n");
518                 return;
519         }
520         DBG("%s: Buffer %p size= %d\n", __func__, vbuf, pos);
521         /* tell v4l buffer was filled */
522
523         buf->vb.field_count = cam->frame_count * 2;
524         v4l2_get_timestamp(&buf->vb.ts);
525         buf->vb.state = VIDEOBUF_DONE;
526 }
527
528 static int zr364xx_got_frame(struct zr364xx_camera *cam, int jpgsize)
529 {
530         struct zr364xx_dmaqueue *dma_q = &cam->vidq;
531         struct zr364xx_buffer *buf;
532         unsigned long flags = 0;
533         int rc = 0;
534
535         DBG("wakeup: %p\n", &dma_q);
536         spin_lock_irqsave(&cam->slock, flags);
537
538         if (list_empty(&dma_q->active)) {
539                 DBG("No active queue to serve\n");
540                 rc = -1;
541                 goto unlock;
542         }
543         buf = list_entry(dma_q->active.next,
544                          struct zr364xx_buffer, vb.queue);
545
546         if (!waitqueue_active(&buf->vb.done)) {
547                 /* no one active */
548                 rc = -1;
549                 goto unlock;
550         }
551         list_del(&buf->vb.queue);
552         v4l2_get_timestamp(&buf->vb.ts);
553         DBG("[%p/%d] wakeup\n", buf, buf->vb.i);
554         zr364xx_fillbuff(cam, buf, jpgsize);
555         wake_up(&buf->vb.done);
556         DBG("wakeup [buf/i] [%p/%d]\n", buf, buf->vb.i);
557 unlock:
558         spin_unlock_irqrestore(&cam->slock, flags);
559         return rc;
560 }
561
562 /* this function moves the usb stream read pipe data
563  * into the system buffers.
564  * returns 0 on success, EAGAIN if more data to process (call this
565  * function again).
566  */
567 static int zr364xx_read_video_callback(struct zr364xx_camera *cam,
568                                         struct zr364xx_pipeinfo *pipe_info,
569                                         struct urb *purb)
570 {
571         unsigned char *pdest;
572         unsigned char *psrc;
573         s32 idx = -1;
574         struct zr364xx_framei *frm;
575         int i = 0;
576         unsigned char *ptr = NULL;
577
578         _DBG("buffer to user\n");
579         idx = cam->cur_frame;
580         frm = &cam->buffer.frame[idx];
581
582         /* swap bytes if camera needs it */
583         if (cam->method == METHOD0) {
584                 u16 *buf = (u16 *)pipe_info->transfer_buffer;
585                 for (i = 0; i < purb->actual_length/2; i++)
586                         swab16s(buf + i);
587         }
588
589         /* search done.  now find out if should be acquiring */
590         if (!cam->b_acquire) {
591                 /* we found a frame, but this channel is turned off */
592                 frm->ulState = ZR364XX_READ_IDLE;
593                 return -EINVAL;
594         }
595
596         psrc = (u8 *)pipe_info->transfer_buffer;
597         ptr = pdest = frm->lpvbits;
598
599         if (frm->ulState == ZR364XX_READ_IDLE) {
600                 if (purb->actual_length < 128) {
601                         /* header incomplete */
602                         dev_info(&cam->udev->dev,
603                                  "%s: buffer (%d bytes) too small to hold jpeg header. Discarding.\n",
604                                  __func__, purb->actual_length);
605                         return -EINVAL;
606                 }
607
608                 frm->ulState = ZR364XX_READ_FRAME;
609                 frm->cur_size = 0;
610
611                 _DBG("jpeg header, ");
612                 memcpy(ptr, header1, sizeof(header1));
613                 ptr += sizeof(header1);
614                 header3 = 0;
615                 memcpy(ptr, &header3, 1);
616                 ptr++;
617                 memcpy(ptr, psrc, 64);
618                 ptr += 64;
619                 header3 = 1;
620                 memcpy(ptr, &header3, 1);
621                 ptr++;
622                 memcpy(ptr, psrc + 64, 64);
623                 ptr += 64;
624                 memcpy(ptr, header2, sizeof(header2));
625                 ptr += sizeof(header2);
626                 memcpy(ptr, psrc + 128,
627                        purb->actual_length - 128);
628                 ptr += purb->actual_length - 128;
629                 _DBG("header : %d %d %d %d %d %d %d %d %d\n",
630                     psrc[0], psrc[1], psrc[2],
631                     psrc[3], psrc[4], psrc[5],
632                     psrc[6], psrc[7], psrc[8]);
633                 frm->cur_size = ptr - pdest;
634         } else {
635                 if (frm->cur_size + purb->actual_length > MAX_FRAME_SIZE) {
636                         dev_info(&cam->udev->dev,
637                                  "%s: buffer (%d bytes) too small to hold frame data. Discarding frame data.\n",
638                                  __func__, MAX_FRAME_SIZE);
639                 } else {
640                         pdest += frm->cur_size;
641                         memcpy(pdest, psrc, purb->actual_length);
642                         frm->cur_size += purb->actual_length;
643                 }
644         }
645         /*_DBG("cur_size %lu urb size %d\n", frm->cur_size,
646                 purb->actual_length);*/
647
648         if (purb->actual_length < pipe_info->transfer_size) {
649                 _DBG("****************Buffer[%d]full*************\n", idx);
650                 cam->last_frame = cam->cur_frame;
651                 cam->cur_frame++;
652                 /* end of system frame ring buffer, start at zero */
653                 if (cam->cur_frame == cam->buffer.dwFrames)
654                         cam->cur_frame = 0;
655
656                 /* frame ready */
657                 /* go back to find the JPEG EOI marker */
658                 ptr = pdest = frm->lpvbits;
659                 ptr += frm->cur_size - 2;
660                 while (ptr > pdest) {
661                         if (*ptr == 0xFF && *(ptr + 1) == 0xD9
662                             && *(ptr + 2) == 0xFF)
663                                 break;
664                         ptr--;
665                 }
666                 if (ptr == pdest)
667                         DBG("No EOI marker\n");
668
669                 /* Sometimes there is junk data in the middle of the picture,
670                  * we want to skip this bogus frames */
671                 while (ptr > pdest) {
672                         if (*ptr == 0xFF && *(ptr + 1) == 0xFF
673                             && *(ptr + 2) == 0xFF)
674                                 break;
675                         ptr--;
676                 }
677                 if (ptr != pdest) {
678                         DBG("Bogus frame ? %d\n", ++(cam->nb));
679                 } else if (cam->b_acquire) {
680                         /* we skip the 2 first frames which are usually buggy */
681                         if (cam->skip)
682                                 cam->skip--;
683                         else {
684                                 _DBG("jpeg(%lu): %d %d %d %d %d %d %d %d\n",
685                                     frm->cur_size,
686                                     pdest[0], pdest[1], pdest[2], pdest[3],
687                                     pdest[4], pdest[5], pdest[6], pdest[7]);
688
689                                 zr364xx_got_frame(cam, frm->cur_size);
690                         }
691                 }
692                 cam->frame_count++;
693                 frm->ulState = ZR364XX_READ_IDLE;
694                 frm->cur_size = 0;
695         }
696         /* done successfully */
697         return 0;
698 }
699
700 static int zr364xx_vidioc_querycap(struct file *file, void *priv,
701                                    struct v4l2_capability *cap)
702 {
703         struct zr364xx_camera *cam = video_drvdata(file);
704
705         strlcpy(cap->driver, DRIVER_DESC, sizeof(cap->driver));
706         if (cam->udev->product)
707                 strlcpy(cap->card, cam->udev->product, sizeof(cap->card));
708         strlcpy(cap->bus_info, dev_name(&cam->udev->dev),
709                 sizeof(cap->bus_info));
710         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE |
711                             V4L2_CAP_READWRITE |
712                             V4L2_CAP_STREAMING;
713         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
714
715         return 0;
716 }
717
718 static int zr364xx_vidioc_enum_input(struct file *file, void *priv,
719                                      struct v4l2_input *i)
720 {
721         if (i->index != 0)
722                 return -EINVAL;
723         strcpy(i->name, DRIVER_DESC " Camera");
724         i->type = V4L2_INPUT_TYPE_CAMERA;
725         return 0;
726 }
727
728 static int zr364xx_vidioc_g_input(struct file *file, void *priv,
729                                   unsigned int *i)
730 {
731         *i = 0;
732         return 0;
733 }
734
735 static int zr364xx_vidioc_s_input(struct file *file, void *priv,
736                                   unsigned int i)
737 {
738         if (i != 0)
739                 return -EINVAL;
740         return 0;
741 }
742
743 static int zr364xx_s_ctrl(struct v4l2_ctrl *ctrl)
744 {
745         struct zr364xx_camera *cam =
746                 container_of(ctrl->handler, struct zr364xx_camera, ctrl_handler);
747         int temp;
748
749         switch (ctrl->id) {
750         case V4L2_CID_BRIGHTNESS:
751                 /* hardware brightness */
752                 send_control_msg(cam->udev, 1, 0x2001, 0, NULL, 0);
753                 temp = (0x60 << 8) + 127 - ctrl->val;
754                 send_control_msg(cam->udev, 1, temp, 0, NULL, 0);
755                 break;
756         default:
757                 return -EINVAL;
758         }
759
760         return 0;
761 }
762
763 static int zr364xx_vidioc_enum_fmt_vid_cap(struct file *file,
764                                        void *priv, struct v4l2_fmtdesc *f)
765 {
766         if (f->index > 0)
767                 return -EINVAL;
768         f->flags = V4L2_FMT_FLAG_COMPRESSED;
769         strcpy(f->description, formats[0].name);
770         f->pixelformat = formats[0].fourcc;
771         return 0;
772 }
773
774 static char *decode_fourcc(__u32 pixelformat, char *buf)
775 {
776         buf[0] = pixelformat & 0xff;
777         buf[1] = (pixelformat >> 8) & 0xff;
778         buf[2] = (pixelformat >> 16) & 0xff;
779         buf[3] = (pixelformat >> 24) & 0xff;
780         buf[4] = '\0';
781         return buf;
782 }
783
784 static int zr364xx_vidioc_try_fmt_vid_cap(struct file *file, void *priv,
785                                       struct v4l2_format *f)
786 {
787         struct zr364xx_camera *cam = video_drvdata(file);
788         char pixelformat_name[5];
789
790         if (!cam)
791                 return -ENODEV;
792
793         if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG) {
794                 DBG("%s: unsupported pixelformat V4L2_PIX_FMT_%s\n", __func__,
795                     decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name));
796                 return -EINVAL;
797         }
798
799         if (!(f->fmt.pix.width == 160 && f->fmt.pix.height == 120) &&
800             !(f->fmt.pix.width == 640 && f->fmt.pix.height == 480)) {
801                 f->fmt.pix.width = 320;
802                 f->fmt.pix.height = 240;
803         }
804
805         f->fmt.pix.field = V4L2_FIELD_NONE;
806         f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
807         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
808         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
809         DBG("%s: V4L2_PIX_FMT_%s (%d) ok!\n", __func__,
810             decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name),
811             f->fmt.pix.field);
812         return 0;
813 }
814
815 static int zr364xx_vidioc_g_fmt_vid_cap(struct file *file, void *priv,
816                                     struct v4l2_format *f)
817 {
818         struct zr364xx_camera *cam;
819
820         if (!file)
821                 return -ENODEV;
822         cam = video_drvdata(file);
823
824         f->fmt.pix.pixelformat = formats[0].fourcc;
825         f->fmt.pix.field = V4L2_FIELD_NONE;
826         f->fmt.pix.width = cam->width;
827         f->fmt.pix.height = cam->height;
828         f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
829         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
830         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
831         return 0;
832 }
833
834 static int zr364xx_vidioc_s_fmt_vid_cap(struct file *file, void *priv,
835                                     struct v4l2_format *f)
836 {
837         struct zr364xx_camera *cam = video_drvdata(file);
838         struct videobuf_queue *q = &cam->vb_vidq;
839         char pixelformat_name[5];
840         int ret = zr364xx_vidioc_try_fmt_vid_cap(file, cam, f);
841         int i;
842
843         if (ret < 0)
844                 return ret;
845
846         mutex_lock(&q->vb_lock);
847
848         if (videobuf_queue_is_busy(&cam->vb_vidq)) {
849                 DBG("%s queue busy\n", __func__);
850                 ret = -EBUSY;
851                 goto out;
852         }
853
854         if (cam->owner) {
855                 DBG("%s can't change format after started\n", __func__);
856                 ret = -EBUSY;
857                 goto out;
858         }
859
860         cam->width = f->fmt.pix.width;
861         cam->height = f->fmt.pix.height;
862         DBG("%s: %dx%d mode selected\n", __func__,
863                  cam->width, cam->height);
864         f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
865         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
866         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
867         cam->vb_vidq.field = f->fmt.pix.field;
868
869         if (f->fmt.pix.width == 160 && f->fmt.pix.height == 120)
870                 mode = 1;
871         else if (f->fmt.pix.width == 640 && f->fmt.pix.height == 480)
872                 mode = 2;
873         else
874                 mode = 0;
875
876         m0d1[0] = mode;
877         m1[2].value = 0xf000 + mode;
878         m2[1].value = 0xf000 + mode;
879
880         /* special case for METHOD3, the modes are different */
881         if (cam->method == METHOD3) {
882                 switch (mode) {
883                 case 1:
884                         m2[1].value = 0xf000 + 4;
885                         break;
886                 case 2:
887                         m2[1].value = 0xf000 + 0;
888                         break;
889                 default:
890                         m2[1].value = 0xf000 + 1;
891                         break;
892                 }
893         }
894
895         header2[437] = cam->height / 256;
896         header2[438] = cam->height % 256;
897         header2[439] = cam->width / 256;
898         header2[440] = cam->width % 256;
899
900         for (i = 0; init[cam->method][i].size != -1; i++) {
901                 ret =
902                     send_control_msg(cam->udev, 1, init[cam->method][i].value,
903                                      0, init[cam->method][i].bytes,
904                                      init[cam->method][i].size);
905                 if (ret < 0) {
906                         dev_err(&cam->udev->dev,
907                            "error during resolution change sequence: %d\n", i);
908                         goto out;
909                 }
910         }
911
912         /* Added some delay here, since opening/closing the camera quickly,
913          * like Ekiga does during its startup, can crash the webcam
914          */
915         mdelay(100);
916         cam->skip = 2;
917         ret = 0;
918
919 out:
920         mutex_unlock(&q->vb_lock);
921
922         DBG("%s: V4L2_PIX_FMT_%s (%d) ok!\n", __func__,
923             decode_fourcc(f->fmt.pix.pixelformat, pixelformat_name),
924             f->fmt.pix.field);
925         return ret;
926 }
927
928 static int zr364xx_vidioc_reqbufs(struct file *file, void *priv,
929                           struct v4l2_requestbuffers *p)
930 {
931         struct zr364xx_camera *cam = video_drvdata(file);
932
933         if (cam->owner && cam->owner != priv)
934                 return -EBUSY;
935         return videobuf_reqbufs(&cam->vb_vidq, p);
936 }
937
938 static int zr364xx_vidioc_querybuf(struct file *file,
939                                 void *priv,
940                                 struct v4l2_buffer *p)
941 {
942         int rc;
943         struct zr364xx_camera *cam = video_drvdata(file);
944         rc = videobuf_querybuf(&cam->vb_vidq, p);
945         return rc;
946 }
947
948 static int zr364xx_vidioc_qbuf(struct file *file,
949                                 void *priv,
950                                 struct v4l2_buffer *p)
951 {
952         int rc;
953         struct zr364xx_camera *cam = video_drvdata(file);
954         _DBG("%s\n", __func__);
955         if (cam->owner && cam->owner != priv)
956                 return -EBUSY;
957         rc = videobuf_qbuf(&cam->vb_vidq, p);
958         return rc;
959 }
960
961 static int zr364xx_vidioc_dqbuf(struct file *file,
962                                 void *priv,
963                                 struct v4l2_buffer *p)
964 {
965         int rc;
966         struct zr364xx_camera *cam = video_drvdata(file);
967         _DBG("%s\n", __func__);
968         if (cam->owner && cam->owner != priv)
969                 return -EBUSY;
970         rc = videobuf_dqbuf(&cam->vb_vidq, p, file->f_flags & O_NONBLOCK);
971         return rc;
972 }
973
974 static void read_pipe_completion(struct urb *purb)
975 {
976         struct zr364xx_pipeinfo *pipe_info;
977         struct zr364xx_camera *cam;
978         int pipe;
979
980         pipe_info = purb->context;
981         _DBG("%s %p, status %d\n", __func__, purb, purb->status);
982         if (!pipe_info) {
983                 printk(KERN_ERR KBUILD_MODNAME ": no context!\n");
984                 return;
985         }
986
987         cam = pipe_info->cam;
988         if (!cam) {
989                 printk(KERN_ERR KBUILD_MODNAME ": no context!\n");
990                 return;
991         }
992
993         /* if shutting down, do not resubmit, exit immediately */
994         if (purb->status == -ESHUTDOWN) {
995                 DBG("%s, err shutdown\n", __func__);
996                 pipe_info->err_count++;
997                 return;
998         }
999
1000         if (pipe_info->state == 0) {
1001                 DBG("exiting USB pipe\n");
1002                 return;
1003         }
1004
1005         if (purb->actual_length > pipe_info->transfer_size) {
1006                 dev_err(&cam->udev->dev, "wrong number of bytes\n");
1007                 return;
1008         }
1009
1010         if (purb->status == 0)
1011                 zr364xx_read_video_callback(cam, pipe_info, purb);
1012         else {
1013                 pipe_info->err_count++;
1014                 DBG("%s: failed URB %d\n", __func__, purb->status);
1015         }
1016
1017         pipe = usb_rcvbulkpipe(cam->udev, cam->read_endpoint);
1018
1019         /* reuse urb */
1020         usb_fill_bulk_urb(pipe_info->stream_urb, cam->udev,
1021                           pipe,
1022                           pipe_info->transfer_buffer,
1023                           pipe_info->transfer_size,
1024                           read_pipe_completion, pipe_info);
1025
1026         if (pipe_info->state != 0) {
1027                 purb->status = usb_submit_urb(pipe_info->stream_urb,
1028                                               GFP_ATOMIC);
1029
1030                 if (purb->status)
1031                         dev_err(&cam->udev->dev,
1032                                 "error submitting urb (error=%i)\n",
1033                                 purb->status);
1034         } else
1035                 DBG("read pipe complete state 0\n");
1036 }
1037
1038 static int zr364xx_start_readpipe(struct zr364xx_camera *cam)
1039 {
1040         int pipe;
1041         int retval;
1042         struct zr364xx_pipeinfo *pipe_info = cam->pipe;
1043         pipe = usb_rcvbulkpipe(cam->udev, cam->read_endpoint);
1044         DBG("%s: start pipe IN x%x\n", __func__, cam->read_endpoint);
1045
1046         pipe_info->state = 1;
1047         pipe_info->err_count = 0;
1048         pipe_info->stream_urb = usb_alloc_urb(0, GFP_KERNEL);
1049         if (!pipe_info->stream_urb)
1050                 return -ENOMEM;
1051         /* transfer buffer allocated in board_init */
1052         usb_fill_bulk_urb(pipe_info->stream_urb, cam->udev,
1053                           pipe,
1054                           pipe_info->transfer_buffer,
1055                           pipe_info->transfer_size,
1056                           read_pipe_completion, pipe_info);
1057
1058         DBG("submitting URB %p\n", pipe_info->stream_urb);
1059         retval = usb_submit_urb(pipe_info->stream_urb, GFP_KERNEL);
1060         if (retval) {
1061                 usb_free_urb(pipe_info->stream_urb);
1062                 printk(KERN_ERR KBUILD_MODNAME ": start read pipe failed\n");
1063                 return retval;
1064         }
1065
1066         return 0;
1067 }
1068
1069 static void zr364xx_stop_readpipe(struct zr364xx_camera *cam)
1070 {
1071         struct zr364xx_pipeinfo *pipe_info;
1072
1073         if (!cam) {
1074                 printk(KERN_ERR KBUILD_MODNAME ": invalid device\n");
1075                 return;
1076         }
1077         DBG("stop read pipe\n");
1078         pipe_info = cam->pipe;
1079         if (pipe_info) {
1080                 if (pipe_info->state != 0)
1081                         pipe_info->state = 0;
1082
1083                 if (pipe_info->stream_urb) {
1084                         /* cancel urb */
1085                         usb_kill_urb(pipe_info->stream_urb);
1086                         usb_free_urb(pipe_info->stream_urb);
1087                         pipe_info->stream_urb = NULL;
1088                 }
1089         }
1090         return;
1091 }
1092
1093 /* starts acquisition process */
1094 static int zr364xx_start_acquire(struct zr364xx_camera *cam)
1095 {
1096         int j;
1097
1098         DBG("start acquire\n");
1099
1100         cam->last_frame = -1;
1101         cam->cur_frame = 0;
1102         for (j = 0; j < FRAMES; j++) {
1103                 cam->buffer.frame[j].ulState = ZR364XX_READ_IDLE;
1104                 cam->buffer.frame[j].cur_size = 0;
1105         }
1106         cam->b_acquire = 1;
1107         return 0;
1108 }
1109
1110 static inline int zr364xx_stop_acquire(struct zr364xx_camera *cam)
1111 {
1112         cam->b_acquire = 0;
1113         return 0;
1114 }
1115
1116 static int zr364xx_prepare(struct zr364xx_camera *cam)
1117 {
1118         int res;
1119         int i, j;
1120
1121         for (i = 0; init[cam->method][i].size != -1; i++) {
1122                 res = send_control_msg(cam->udev, 1, init[cam->method][i].value,
1123                                      0, init[cam->method][i].bytes,
1124                                      init[cam->method][i].size);
1125                 if (res < 0) {
1126                         dev_err(&cam->udev->dev,
1127                                 "error during open sequence: %d\n", i);
1128                         return res;
1129                 }
1130         }
1131
1132         cam->skip = 2;
1133         cam->last_frame = -1;
1134         cam->cur_frame = 0;
1135         cam->frame_count = 0;
1136         for (j = 0; j < FRAMES; j++) {
1137                 cam->buffer.frame[j].ulState = ZR364XX_READ_IDLE;
1138                 cam->buffer.frame[j].cur_size = 0;
1139         }
1140         v4l2_ctrl_handler_setup(&cam->ctrl_handler);
1141         return 0;
1142 }
1143
1144 static int zr364xx_vidioc_streamon(struct file *file, void *priv,
1145                                    enum v4l2_buf_type type)
1146 {
1147         struct zr364xx_camera *cam = video_drvdata(file);
1148         int res;
1149
1150         DBG("%s\n", __func__);
1151
1152         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1153                 return -EINVAL;
1154
1155         if (cam->owner && cam->owner != priv)
1156                 return -EBUSY;
1157
1158         res = zr364xx_prepare(cam);
1159         if (res)
1160                 return res;
1161         res = videobuf_streamon(&cam->vb_vidq);
1162         if (res == 0) {
1163                 zr364xx_start_acquire(cam);
1164                 cam->owner = file->private_data;
1165         }
1166         return res;
1167 }
1168
1169 static int zr364xx_vidioc_streamoff(struct file *file, void *priv,
1170                                     enum v4l2_buf_type type)
1171 {
1172         struct zr364xx_camera *cam = video_drvdata(file);
1173
1174         DBG("%s\n", __func__);
1175         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1176                 return -EINVAL;
1177         if (cam->owner && cam->owner != priv)
1178                 return -EBUSY;
1179         zr364xx_stop_acquire(cam);
1180         return videobuf_streamoff(&cam->vb_vidq);
1181 }
1182
1183
1184 /* open the camera */
1185 static int zr364xx_open(struct file *file)
1186 {
1187         struct zr364xx_camera *cam = video_drvdata(file);
1188         int err;
1189
1190         DBG("%s\n", __func__);
1191
1192         if (mutex_lock_interruptible(&cam->lock))
1193                 return -ERESTARTSYS;
1194
1195         err = v4l2_fh_open(file);
1196         if (err)
1197                 goto out;
1198
1199         /* Added some delay here, since opening/closing the camera quickly,
1200          * like Ekiga does during its startup, can crash the webcam
1201          */
1202         mdelay(100);
1203         err = 0;
1204
1205 out:
1206         mutex_unlock(&cam->lock);
1207         DBG("%s: %d\n", __func__, err);
1208         return err;
1209 }
1210
1211 static void zr364xx_release(struct v4l2_device *v4l2_dev)
1212 {
1213         struct zr364xx_camera *cam =
1214                 container_of(v4l2_dev, struct zr364xx_camera, v4l2_dev);
1215         unsigned long i;
1216
1217         v4l2_device_unregister(&cam->v4l2_dev);
1218
1219         videobuf_mmap_free(&cam->vb_vidq);
1220
1221         /* release sys buffers */
1222         for (i = 0; i < FRAMES; i++) {
1223                 if (cam->buffer.frame[i].lpvbits) {
1224                         DBG("vfree %p\n", cam->buffer.frame[i].lpvbits);
1225                         vfree(cam->buffer.frame[i].lpvbits);
1226                 }
1227                 cam->buffer.frame[i].lpvbits = NULL;
1228         }
1229
1230         v4l2_ctrl_handler_free(&cam->ctrl_handler);
1231         /* release transfer buffer */
1232         kfree(cam->pipe->transfer_buffer);
1233         kfree(cam);
1234 }
1235
1236 /* release the camera */
1237 static int zr364xx_close(struct file *file)
1238 {
1239         struct zr364xx_camera *cam;
1240         struct usb_device *udev;
1241         int i;
1242
1243         DBG("%s\n", __func__);
1244         cam = video_drvdata(file);
1245
1246         mutex_lock(&cam->lock);
1247         udev = cam->udev;
1248
1249         if (file->private_data == cam->owner) {
1250                 /* turn off stream */
1251                 if (cam->b_acquire)
1252                         zr364xx_stop_acquire(cam);
1253                 videobuf_streamoff(&cam->vb_vidq);
1254
1255                 for (i = 0; i < 2; i++) {
1256                         send_control_msg(udev, 1, init[cam->method][i].value,
1257                                         0, init[cam->method][i].bytes,
1258                                         init[cam->method][i].size);
1259                 }
1260                 cam->owner = NULL;
1261         }
1262
1263         /* Added some delay here, since opening/closing the camera quickly,
1264          * like Ekiga does during its startup, can crash the webcam
1265          */
1266         mdelay(100);
1267         mutex_unlock(&cam->lock);
1268         return v4l2_fh_release(file);
1269 }
1270
1271
1272 static int zr364xx_mmap(struct file *file, struct vm_area_struct *vma)
1273 {
1274         struct zr364xx_camera *cam = video_drvdata(file);
1275         int ret;
1276
1277         if (!cam) {
1278                 DBG("%s: cam == NULL\n", __func__);
1279                 return -ENODEV;
1280         }
1281         DBG("mmap called, vma=%p\n", vma);
1282
1283         ret = videobuf_mmap_mapper(&cam->vb_vidq, vma);
1284
1285         DBG("vma start=0x%08lx, size=%ld, ret=%d\n",
1286                 (unsigned long)vma->vm_start,
1287                 (unsigned long)vma->vm_end - (unsigned long)vma->vm_start, ret);
1288         return ret;
1289 }
1290
1291 static __poll_t zr364xx_poll(struct file *file,
1292                                struct poll_table_struct *wait)
1293 {
1294         struct zr364xx_camera *cam = video_drvdata(file);
1295         struct videobuf_queue *q = &cam->vb_vidq;
1296         __poll_t res = v4l2_ctrl_poll(file, wait);
1297
1298         _DBG("%s\n", __func__);
1299
1300         return res | videobuf_poll_stream(file, q, wait);
1301 }
1302
1303 static const struct v4l2_ctrl_ops zr364xx_ctrl_ops = {
1304         .s_ctrl = zr364xx_s_ctrl,
1305 };
1306
1307 static const struct v4l2_file_operations zr364xx_fops = {
1308         .owner = THIS_MODULE,
1309         .open = zr364xx_open,
1310         .release = zr364xx_close,
1311         .read = zr364xx_read,
1312         .mmap = zr364xx_mmap,
1313         .unlocked_ioctl = video_ioctl2,
1314         .poll = zr364xx_poll,
1315 };
1316
1317 static const struct v4l2_ioctl_ops zr364xx_ioctl_ops = {
1318         .vidioc_querycap        = zr364xx_vidioc_querycap,
1319         .vidioc_enum_fmt_vid_cap = zr364xx_vidioc_enum_fmt_vid_cap,
1320         .vidioc_try_fmt_vid_cap = zr364xx_vidioc_try_fmt_vid_cap,
1321         .vidioc_s_fmt_vid_cap   = zr364xx_vidioc_s_fmt_vid_cap,
1322         .vidioc_g_fmt_vid_cap   = zr364xx_vidioc_g_fmt_vid_cap,
1323         .vidioc_enum_input      = zr364xx_vidioc_enum_input,
1324         .vidioc_g_input         = zr364xx_vidioc_g_input,
1325         .vidioc_s_input         = zr364xx_vidioc_s_input,
1326         .vidioc_streamon        = zr364xx_vidioc_streamon,
1327         .vidioc_streamoff       = zr364xx_vidioc_streamoff,
1328         .vidioc_reqbufs         = zr364xx_vidioc_reqbufs,
1329         .vidioc_querybuf        = zr364xx_vidioc_querybuf,
1330         .vidioc_qbuf            = zr364xx_vidioc_qbuf,
1331         .vidioc_dqbuf           = zr364xx_vidioc_dqbuf,
1332         .vidioc_log_status      = v4l2_ctrl_log_status,
1333         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1334         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1335 };
1336
1337 static const struct video_device zr364xx_template = {
1338         .name = DRIVER_DESC,
1339         .fops = &zr364xx_fops,
1340         .ioctl_ops = &zr364xx_ioctl_ops,
1341         .release = video_device_release_empty,
1342 };
1343
1344
1345
1346 /*******************/
1347 /* USB integration */
1348 /*******************/
1349 static int zr364xx_board_init(struct zr364xx_camera *cam)
1350 {
1351         struct zr364xx_pipeinfo *pipe = cam->pipe;
1352         unsigned long i;
1353
1354         DBG("board init: %p\n", cam);
1355         memset(pipe, 0, sizeof(*pipe));
1356         pipe->cam = cam;
1357         pipe->transfer_size = BUFFER_SIZE;
1358
1359         pipe->transfer_buffer = kzalloc(pipe->transfer_size,
1360                                         GFP_KERNEL);
1361         if (!pipe->transfer_buffer) {
1362                 DBG("out of memory!\n");
1363                 return -ENOMEM;
1364         }
1365
1366         cam->b_acquire = 0;
1367         cam->frame_count = 0;
1368
1369         /*** start create system buffers ***/
1370         for (i = 0; i < FRAMES; i++) {
1371                 /* always allocate maximum size for system buffers */
1372                 cam->buffer.frame[i].lpvbits = vmalloc(MAX_FRAME_SIZE);
1373
1374                 DBG("valloc %p, idx %lu, pdata %p\n",
1375                         &cam->buffer.frame[i], i,
1376                         cam->buffer.frame[i].lpvbits);
1377                 if (!cam->buffer.frame[i].lpvbits) {
1378                         printk(KERN_INFO KBUILD_MODNAME ": out of memory. Using less frames\n");
1379                         break;
1380                 }
1381         }
1382
1383         if (i == 0) {
1384                 printk(KERN_INFO KBUILD_MODNAME ": out of memory. Aborting\n");
1385                 kfree(cam->pipe->transfer_buffer);
1386                 cam->pipe->transfer_buffer = NULL;
1387                 return -ENOMEM;
1388         } else
1389                 cam->buffer.dwFrames = i;
1390
1391         /* make sure internal states are set */
1392         for (i = 0; i < FRAMES; i++) {
1393                 cam->buffer.frame[i].ulState = ZR364XX_READ_IDLE;
1394                 cam->buffer.frame[i].cur_size = 0;
1395         }
1396
1397         cam->cur_frame = 0;
1398         cam->last_frame = -1;
1399         /*** end create system buffers ***/
1400
1401         /* start read pipe */
1402         zr364xx_start_readpipe(cam);
1403         DBG(": board initialized\n");
1404         return 0;
1405 }
1406
1407 static int zr364xx_probe(struct usb_interface *intf,
1408                          const struct usb_device_id *id)
1409 {
1410         struct usb_device *udev = interface_to_usbdev(intf);
1411         struct zr364xx_camera *cam = NULL;
1412         struct usb_host_interface *iface_desc;
1413         struct usb_endpoint_descriptor *endpoint;
1414         struct v4l2_ctrl_handler *hdl;
1415         int err;
1416         int i;
1417
1418         DBG("probing...\n");
1419
1420         dev_info(&intf->dev, DRIVER_DESC " compatible webcam plugged\n");
1421         dev_info(&intf->dev, "model %04x:%04x detected\n",
1422                  le16_to_cpu(udev->descriptor.idVendor),
1423                  le16_to_cpu(udev->descriptor.idProduct));
1424
1425         cam = kzalloc(sizeof(*cam), GFP_KERNEL);
1426         if (!cam)
1427                 return -ENOMEM;
1428
1429         cam->v4l2_dev.release = zr364xx_release;
1430         err = v4l2_device_register(&intf->dev, &cam->v4l2_dev);
1431         if (err < 0) {
1432                 dev_err(&udev->dev, "couldn't register v4l2_device\n");
1433                 kfree(cam);
1434                 return err;
1435         }
1436         hdl = &cam->ctrl_handler;
1437         v4l2_ctrl_handler_init(hdl, 1);
1438         v4l2_ctrl_new_std(hdl, &zr364xx_ctrl_ops,
1439                           V4L2_CID_BRIGHTNESS, 0, 127, 1, 64);
1440         if (hdl->error) {
1441                 err = hdl->error;
1442                 dev_err(&udev->dev, "couldn't register control\n");
1443                 goto fail;
1444         }
1445         /* save the init method used by this camera */
1446         cam->method = id->driver_info;
1447         mutex_init(&cam->lock);
1448         cam->vdev = zr364xx_template;
1449         cam->vdev.lock = &cam->lock;
1450         cam->vdev.v4l2_dev = &cam->v4l2_dev;
1451         cam->vdev.ctrl_handler = &cam->ctrl_handler;
1452         video_set_drvdata(&cam->vdev, cam);
1453
1454         cam->udev = udev;
1455
1456         switch (mode) {
1457         case 1:
1458                 dev_info(&udev->dev, "160x120 mode selected\n");
1459                 cam->width = 160;
1460                 cam->height = 120;
1461                 break;
1462         case 2:
1463                 dev_info(&udev->dev, "640x480 mode selected\n");
1464                 cam->width = 640;
1465                 cam->height = 480;
1466                 break;
1467         default:
1468                 dev_info(&udev->dev, "320x240 mode selected\n");
1469                 cam->width = 320;
1470                 cam->height = 240;
1471                 break;
1472         }
1473
1474         m0d1[0] = mode;
1475         m1[2].value = 0xf000 + mode;
1476         m2[1].value = 0xf000 + mode;
1477
1478         /* special case for METHOD3, the modes are different */
1479         if (cam->method == METHOD3) {
1480                 switch (mode) {
1481                 case 1:
1482                         m2[1].value = 0xf000 + 4;
1483                         break;
1484                 case 2:
1485                         m2[1].value = 0xf000 + 0;
1486                         break;
1487                 default:
1488                         m2[1].value = 0xf000 + 1;
1489                         break;
1490                 }
1491         }
1492
1493         header2[437] = cam->height / 256;
1494         header2[438] = cam->height % 256;
1495         header2[439] = cam->width / 256;
1496         header2[440] = cam->width % 256;
1497
1498         cam->nb = 0;
1499
1500         DBG("dev: %p, udev %p interface %p\n", cam, cam->udev, intf);
1501
1502         /* set up the endpoint information  */
1503         iface_desc = intf->cur_altsetting;
1504         DBG("num endpoints %d\n", iface_desc->desc.bNumEndpoints);
1505         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1506                 endpoint = &iface_desc->endpoint[i].desc;
1507                 if (!cam->read_endpoint && usb_endpoint_is_bulk_in(endpoint)) {
1508                         /* we found the bulk in endpoint */
1509                         cam->read_endpoint = endpoint->bEndpointAddress;
1510                 }
1511         }
1512
1513         if (!cam->read_endpoint) {
1514                 err = -ENOMEM;
1515                 dev_err(&intf->dev, "Could not find bulk-in endpoint\n");
1516                 goto fail;
1517         }
1518
1519         /* v4l */
1520         INIT_LIST_HEAD(&cam->vidq.active);
1521         cam->vidq.cam = cam;
1522
1523         usb_set_intfdata(intf, cam);
1524
1525         /* load zr364xx board specific */
1526         err = zr364xx_board_init(cam);
1527         if (!err)
1528                 err = v4l2_ctrl_handler_setup(hdl);
1529         if (err)
1530                 goto fail;
1531
1532         spin_lock_init(&cam->slock);
1533
1534         cam->fmt = formats;
1535
1536         videobuf_queue_vmalloc_init(&cam->vb_vidq, &zr364xx_video_qops,
1537                                     NULL, &cam->slock,
1538                                     V4L2_BUF_TYPE_VIDEO_CAPTURE,
1539                                     V4L2_FIELD_NONE,
1540                                     sizeof(struct zr364xx_buffer), cam, &cam->lock);
1541
1542         err = video_register_device(&cam->vdev, VFL_TYPE_GRABBER, -1);
1543         if (err) {
1544                 dev_err(&udev->dev, "video_register_device failed\n");
1545                 goto fail;
1546         }
1547
1548         dev_info(&udev->dev, DRIVER_DESC " controlling device %s\n",
1549                  video_device_node_name(&cam->vdev));
1550         return 0;
1551
1552 fail:
1553         v4l2_ctrl_handler_free(hdl);
1554         v4l2_device_unregister(&cam->v4l2_dev);
1555         kfree(cam);
1556         return err;
1557 }
1558
1559
1560 static void zr364xx_disconnect(struct usb_interface *intf)
1561 {
1562         struct zr364xx_camera *cam = usb_get_intfdata(intf);
1563
1564         mutex_lock(&cam->lock);
1565         usb_set_intfdata(intf, NULL);
1566         dev_info(&intf->dev, DRIVER_DESC " webcam unplugged\n");
1567         video_unregister_device(&cam->vdev);
1568         v4l2_device_disconnect(&cam->v4l2_dev);
1569
1570         /* stops the read pipe if it is running */
1571         if (cam->b_acquire)
1572                 zr364xx_stop_acquire(cam);
1573
1574         zr364xx_stop_readpipe(cam);
1575         mutex_unlock(&cam->lock);
1576         v4l2_device_put(&cam->v4l2_dev);
1577 }
1578
1579
1580 #ifdef CONFIG_PM
1581 static int zr364xx_suspend(struct usb_interface *intf, pm_message_t message)
1582 {
1583         struct zr364xx_camera *cam = usb_get_intfdata(intf);
1584
1585         cam->was_streaming = cam->b_acquire;
1586         if (!cam->was_streaming)
1587                 return 0;
1588         zr364xx_stop_acquire(cam);
1589         zr364xx_stop_readpipe(cam);
1590         return 0;
1591 }
1592
1593 static int zr364xx_resume(struct usb_interface *intf)
1594 {
1595         struct zr364xx_camera *cam = usb_get_intfdata(intf);
1596         int res;
1597
1598         if (!cam->was_streaming)
1599                 return 0;
1600
1601         zr364xx_start_readpipe(cam);
1602         res = zr364xx_prepare(cam);
1603         if (!res)
1604                 zr364xx_start_acquire(cam);
1605         return res;
1606 }
1607 #endif
1608
1609 /**********************/
1610 /* Module integration */
1611 /**********************/
1612
1613 static struct usb_driver zr364xx_driver = {
1614         .name = "zr364xx",
1615         .probe = zr364xx_probe,
1616         .disconnect = zr364xx_disconnect,
1617 #ifdef CONFIG_PM
1618         .suspend = zr364xx_suspend,
1619         .resume = zr364xx_resume,
1620         .reset_resume = zr364xx_resume,
1621 #endif
1622         .id_table = device_table
1623 };
1624
1625 module_usb_driver(zr364xx_driver);
1626
1627 MODULE_AUTHOR(DRIVER_AUTHOR);
1628 MODULE_DESCRIPTION(DRIVER_DESC);
1629 MODULE_LICENSE("GPL");
1630 MODULE_VERSION(DRIVER_VERSION);