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