Merge branch 'for-linus' of git://linux-nfs.org/~bfields/linux
[linux-2.6] / drivers / media / video / zc0301 / zc0301_core.c
1 /***************************************************************************
2  * Video4Linux2 driver for ZC0301[P] Image Processor and Control Chip      *
3  *                                                                         *
4  * Copyright (C) 2006-2007 by Luca Risolia <luca.risolia@studio.unibo.it>  *
5  *                                                                         *
6  * Informations about the chip internals needed to enable the I2C protocol *
7  * have been taken from the documentation of the ZC030x Video4Linux1       *
8  * driver written by Andrew Birkett <andy@nobugs.org>                      *
9  *                                                                         *
10  * This program is free software; you can redistribute it and/or modify    *
11  * it under the terms of the GNU General Public License as published by    *
12  * the Free Software Foundation; either version 2 of the License, or       *
13  * (at your option) any later version.                                     *
14  *                                                                         *
15  * This program is distributed in the hope that it will be useful,         *
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
18  * GNU General Public License for more details.                            *
19  *                                                                         *
20  * You should have received a copy of the GNU General Public License       *
21  * along with this program; if not, write to the Free Software             *
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.               *
23  ***************************************************************************/
24
25 #include <linux/module.h>
26 #include <linux/init.h>
27 #include <linux/kernel.h>
28 #include <linux/param.h>
29 #include <linux/moduleparam.h>
30 #include <linux/errno.h>
31 #include <linux/slab.h>
32 #include <linux/device.h>
33 #include <linux/fs.h>
34 #include <linux/delay.h>
35 #include <linux/compiler.h>
36 #include <linux/ioctl.h>
37 #include <linux/poll.h>
38 #include <linux/stat.h>
39 #include <linux/mm.h>
40 #include <linux/vmalloc.h>
41 #include <linux/page-flags.h>
42 #include <linux/byteorder/generic.h>
43 #include <asm/page.h>
44 #include <asm/uaccess.h>
45
46 #include "zc0301.h"
47
48 /*****************************************************************************/
49
50 #define ZC0301_MODULE_NAME    "V4L2 driver for ZC0301[P] "                    \
51                               "Image Processor and Control Chip"
52 #define ZC0301_MODULE_AUTHOR  "(C) 2006-2007 Luca Risolia"
53 #define ZC0301_AUTHOR_EMAIL   "<luca.risolia@studio.unibo.it>"
54 #define ZC0301_MODULE_LICENSE "GPL"
55 #define ZC0301_MODULE_VERSION "1:1.10"
56 #define ZC0301_MODULE_VERSION_CODE  KERNEL_VERSION(1, 1, 10)
57
58 /*****************************************************************************/
59
60 MODULE_DEVICE_TABLE(usb, zc0301_id_table);
61
62 MODULE_AUTHOR(ZC0301_MODULE_AUTHOR " " ZC0301_AUTHOR_EMAIL);
63 MODULE_DESCRIPTION(ZC0301_MODULE_NAME);
64 MODULE_VERSION(ZC0301_MODULE_VERSION);
65 MODULE_LICENSE(ZC0301_MODULE_LICENSE);
66
67 static short video_nr[] = {[0 ... ZC0301_MAX_DEVICES-1] = -1};
68 module_param_array(video_nr, short, NULL, 0444);
69 MODULE_PARM_DESC(video_nr,
70                  "\n<-1|n[,...]> Specify V4L2 minor mode number."
71                  "\n -1 = use next available (default)"
72                  "\n  n = use minor number n (integer >= 0)"
73                  "\nYou can specify up to "
74                  __MODULE_STRING(ZC0301_MAX_DEVICES) " cameras this way."
75                  "\nFor example:"
76                  "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
77                  "\nthe second registered camera and use auto for the first"
78                  "\none and for every other camera."
79                  "\n");
80
81 static short force_munmap[] = {[0 ... ZC0301_MAX_DEVICES-1] =
82                                ZC0301_FORCE_MUNMAP};
83 module_param_array(force_munmap, bool, NULL, 0444);
84 MODULE_PARM_DESC(force_munmap,
85                  "\n<0|1[,...]> Force the application to unmap previously"
86                  "\nmapped buffer memory before calling any VIDIOC_S_CROP or"
87                  "\nVIDIOC_S_FMT ioctl's. Not all the applications support"
88                  "\nthis feature. This parameter is specific for each"
89                  "\ndetected camera."
90                  "\n 0 = do not force memory unmapping"
91                  "\n 1 = force memory unmapping (save memory)"
92                  "\nDefault value is "__MODULE_STRING(ZC0301_FORCE_MUNMAP)"."
93                  "\n");
94
95 static unsigned int frame_timeout[] = {[0 ... ZC0301_MAX_DEVICES-1] =
96                                        ZC0301_FRAME_TIMEOUT};
97 module_param_array(frame_timeout, uint, NULL, 0644);
98 MODULE_PARM_DESC(frame_timeout,
99                  "\n<n[,...]> Timeout for a video frame in seconds."
100                  "\nThis parameter is specific for each detected camera."
101                  "\nDefault value is "__MODULE_STRING(ZC0301_FRAME_TIMEOUT)"."
102                  "\n");
103
104 #ifdef ZC0301_DEBUG
105 static unsigned short debug = ZC0301_DEBUG_LEVEL;
106 module_param(debug, ushort, 0644);
107 MODULE_PARM_DESC(debug,
108                  "\n<n> Debugging information level, from 0 to 3:"
109                  "\n0 = none (use carefully)"
110                  "\n1 = critical errors"
111                  "\n2 = significant informations"
112                  "\n3 = more verbose messages"
113                  "\nLevel 3 is useful for testing only, when only "
114                  "one device is used."
115                  "\nDefault value is "__MODULE_STRING(ZC0301_DEBUG_LEVEL)"."
116                  "\n");
117 #endif
118
119 /*****************************************************************************/
120
121 static u32
122 zc0301_request_buffers(struct zc0301_device* cam, u32 count,
123                        enum zc0301_io_method io)
124 {
125         struct v4l2_pix_format* p = &(cam->sensor.pix_format);
126         struct v4l2_rect* r = &(cam->sensor.cropcap.bounds);
127         const size_t imagesize = cam->module_param.force_munmap ||
128                                  io == IO_READ ?
129                                  (p->width * p->height * p->priv) / 8 :
130                                  (r->width * r->height * p->priv) / 8;
131         void* buff = NULL;
132         u32 i;
133
134         if (count > ZC0301_MAX_FRAMES)
135                 count = ZC0301_MAX_FRAMES;
136
137         cam->nbuffers = count;
138         while (cam->nbuffers > 0) {
139                 if ((buff = vmalloc_32_user(cam->nbuffers *
140                                             PAGE_ALIGN(imagesize))))
141                         break;
142                 cam->nbuffers--;
143         }
144
145         for (i = 0; i < cam->nbuffers; i++) {
146                 cam->frame[i].bufmem = buff + i*PAGE_ALIGN(imagesize);
147                 cam->frame[i].buf.index = i;
148                 cam->frame[i].buf.m.offset = i*PAGE_ALIGN(imagesize);
149                 cam->frame[i].buf.length = imagesize;
150                 cam->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
151                 cam->frame[i].buf.sequence = 0;
152                 cam->frame[i].buf.field = V4L2_FIELD_NONE;
153                 cam->frame[i].buf.memory = V4L2_MEMORY_MMAP;
154                 cam->frame[i].buf.flags = 0;
155         }
156
157         return cam->nbuffers;
158 }
159
160
161 static void zc0301_release_buffers(struct zc0301_device* cam)
162 {
163         if (cam->nbuffers) {
164                 vfree(cam->frame[0].bufmem);
165                 cam->nbuffers = 0;
166         }
167         cam->frame_current = NULL;
168 }
169
170
171 static void zc0301_empty_framequeues(struct zc0301_device* cam)
172 {
173         u32 i;
174
175         INIT_LIST_HEAD(&cam->inqueue);
176         INIT_LIST_HEAD(&cam->outqueue);
177
178         for (i = 0; i < ZC0301_MAX_FRAMES; i++) {
179                 cam->frame[i].state = F_UNUSED;
180                 cam->frame[i].buf.bytesused = 0;
181         }
182 }
183
184
185 static void zc0301_requeue_outqueue(struct zc0301_device* cam)
186 {
187         struct zc0301_frame_t *i;
188
189         list_for_each_entry(i, &cam->outqueue, frame) {
190                 i->state = F_QUEUED;
191                 list_add(&i->frame, &cam->inqueue);
192         }
193
194         INIT_LIST_HEAD(&cam->outqueue);
195 }
196
197
198 static void zc0301_queue_unusedframes(struct zc0301_device* cam)
199 {
200         unsigned long lock_flags;
201         u32 i;
202
203         for (i = 0; i < cam->nbuffers; i++)
204                 if (cam->frame[i].state == F_UNUSED) {
205                         cam->frame[i].state = F_QUEUED;
206                         spin_lock_irqsave(&cam->queue_lock, lock_flags);
207                         list_add_tail(&cam->frame[i].frame, &cam->inqueue);
208                         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
209                 }
210 }
211
212 /*****************************************************************************/
213
214 int zc0301_write_reg(struct zc0301_device* cam, u16 index, u16 value)
215 {
216         struct usb_device* udev = cam->usbdev;
217         int res;
218
219         res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0xa0, 0x40,
220                               value, index, NULL, 0, ZC0301_CTRL_TIMEOUT);
221         if (res < 0) {
222                 DBG(3, "Failed to write a register (index 0x%04X, "
223                        "value 0x%02X, error %d)",index, value, res);
224                 return -1;
225         }
226
227         return 0;
228 }
229
230
231 int zc0301_read_reg(struct zc0301_device* cam, u16 index)
232 {
233         struct usb_device* udev = cam->usbdev;
234         u8* buff = cam->control_buffer;
235         int res;
236
237         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0xa1, 0xc0,
238                               0x0001, index, buff, 1, ZC0301_CTRL_TIMEOUT);
239         if (res < 0)
240                 DBG(3, "Failed to read a register (index 0x%04X, error %d)",
241                     index, res);
242
243         PDBGG("Read: index 0x%04X, value: 0x%04X", index, (int)(*buff));
244
245         return (res >= 0) ? (int)(*buff) : -1;
246 }
247
248
249 int zc0301_i2c_read(struct zc0301_device* cam, u16 address, u8 length)
250 {
251         int err = 0, res, r0, r1;
252
253         err += zc0301_write_reg(cam, 0x0092, address);
254         err += zc0301_write_reg(cam, 0x0090, 0x02);
255
256         msleep(1);
257
258         res = zc0301_read_reg(cam, 0x0091);
259         if (res < 0)
260                 err += res;
261         r0 = zc0301_read_reg(cam, 0x0095);
262         if (r0 < 0)
263                 err += r0;
264         r1 = zc0301_read_reg(cam, 0x0096);
265         if (r1 < 0)
266                 err += r1;
267
268         res = (length <= 1) ? r0 : r0 | (r1 << 8);
269
270         if (err)
271                 DBG(3, "I2C read failed at address 0x%04X, value: 0x%04X",
272                     address, res);
273
274
275         PDBGG("I2C read: address 0x%04X, value: 0x%04X", address, res);
276
277         return err ? -1 : res;
278 }
279
280
281 int zc0301_i2c_write(struct zc0301_device* cam, u16 address, u16 value)
282 {
283         int err = 0, res;
284
285         err += zc0301_write_reg(cam, 0x0092, address);
286         err += zc0301_write_reg(cam, 0x0093, value & 0xff);
287         err += zc0301_write_reg(cam, 0x0094, value >> 8);
288         err += zc0301_write_reg(cam, 0x0090, 0x01);
289
290         msleep(1);
291
292         res = zc0301_read_reg(cam, 0x0091);
293         if (res < 0)
294                 err += res;
295
296         if (err)
297                 DBG(3, "I2C write failed at address 0x%04X, value: 0x%04X",
298                     address, value);
299
300         PDBGG("I2C write: address 0x%04X, value: 0x%04X", address, value);
301
302         return err ? -1 : 0;
303 }
304
305 /*****************************************************************************/
306
307 static void zc0301_urb_complete(struct urb *urb)
308 {
309         struct zc0301_device* cam = urb->context;
310         struct zc0301_frame_t** f;
311         size_t imagesize;
312         u8 i;
313         int err = 0;
314
315         if (urb->status == -ENOENT)
316                 return;
317
318         f = &cam->frame_current;
319
320         if (cam->stream == STREAM_INTERRUPT) {
321                 cam->stream = STREAM_OFF;
322                 if ((*f))
323                         (*f)->state = F_QUEUED;
324                 DBG(3, "Stream interrupted");
325                 wake_up(&cam->wait_stream);
326         }
327
328         if (cam->state & DEV_DISCONNECTED)
329                 return;
330
331         if (cam->state & DEV_MISCONFIGURED) {
332                 wake_up_interruptible(&cam->wait_frame);
333                 return;
334         }
335
336         if (cam->stream == STREAM_OFF || list_empty(&cam->inqueue))
337                 goto resubmit_urb;
338
339         if (!(*f))
340                 (*f) = list_entry(cam->inqueue.next, struct zc0301_frame_t,
341                                   frame);
342
343         imagesize = (cam->sensor.pix_format.width *
344                      cam->sensor.pix_format.height *
345                      cam->sensor.pix_format.priv) / 8;
346
347         for (i = 0; i < urb->number_of_packets; i++) {
348                 unsigned int len, status;
349                 void *pos;
350                 u16* soi;
351                 u8 sof;
352
353                 len = urb->iso_frame_desc[i].actual_length;
354                 status = urb->iso_frame_desc[i].status;
355                 pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;
356
357                 if (status) {
358                         DBG(3, "Error in isochronous frame");
359                         (*f)->state = F_ERROR;
360                         continue;
361                 }
362
363                 sof = (*(soi = pos) == 0xd8ff);
364
365                 PDBGG("Isochrnous frame: length %u, #%u i,", len, i);
366
367                 if ((*f)->state == F_QUEUED || (*f)->state == F_ERROR)
368 start_of_frame:
369                         if (sof) {
370                                 (*f)->state = F_GRABBING;
371                                 (*f)->buf.bytesused = 0;
372                                 do_gettimeofday(&(*f)->buf.timestamp);
373                                 DBG(3, "SOF detected: new video frame");
374                         }
375
376                 if ((*f)->state == F_GRABBING) {
377                         if (sof && (*f)->buf.bytesused)
378                                         goto end_of_frame;
379
380                         if ((*f)->buf.bytesused + len > imagesize) {
381                                 DBG(3, "Video frame size exceeded");
382                                 (*f)->state = F_ERROR;
383                                 continue;
384                         }
385
386                         memcpy((*f)->bufmem+(*f)->buf.bytesused, pos, len);
387                         (*f)->buf.bytesused += len;
388
389                         if ((*f)->buf.bytesused == imagesize) {
390                                 u32 b;
391 end_of_frame:
392                                 b = (*f)->buf.bytesused;
393                                 (*f)->state = F_DONE;
394                                 (*f)->buf.sequence= ++cam->frame_count;
395                                 spin_lock(&cam->queue_lock);
396                                 list_move_tail(&(*f)->frame, &cam->outqueue);
397                                 if (!list_empty(&cam->inqueue))
398                                         (*f) = list_entry(cam->inqueue.next,
399                                                        struct zc0301_frame_t,
400                                                           frame);
401                                 else
402                                         (*f) = NULL;
403                                 spin_unlock(&cam->queue_lock);
404                                 DBG(3, "Video frame captured: : %lu bytes",
405                                        (unsigned long)(b));
406
407                                 if (!(*f))
408                                         goto resubmit_urb;
409
410                                 if (sof)
411                                         goto start_of_frame;
412                         }
413                 }
414         }
415
416 resubmit_urb:
417         urb->dev = cam->usbdev;
418         err = usb_submit_urb(urb, GFP_ATOMIC);
419         if (err < 0 && err != -EPERM) {
420                 cam->state |= DEV_MISCONFIGURED;
421                 DBG(1, "usb_submit_urb() failed");
422         }
423
424         wake_up_interruptible(&cam->wait_frame);
425 }
426
427
428 static int zc0301_start_transfer(struct zc0301_device* cam)
429 {
430         struct usb_device *udev = cam->usbdev;
431         struct usb_host_interface* altsetting = usb_altnum_to_altsetting(
432                                                      usb_ifnum_to_if(udev, 0),
433                                                      ZC0301_ALTERNATE_SETTING);
434         const unsigned int psz = le16_to_cpu(altsetting->
435                                              endpoint[0].desc.wMaxPacketSize);
436         struct urb* urb;
437         s8 i, j;
438         int err = 0;
439
440         for (i = 0; i < ZC0301_URBS; i++) {
441                 cam->transfer_buffer[i] = kzalloc(ZC0301_ISO_PACKETS * psz,
442                                                   GFP_KERNEL);
443                 if (!cam->transfer_buffer[i]) {
444                         err = -ENOMEM;
445                         DBG(1, "Not enough memory");
446                         goto free_buffers;
447                 }
448         }
449
450         for (i = 0; i < ZC0301_URBS; i++) {
451                 urb = usb_alloc_urb(ZC0301_ISO_PACKETS, GFP_KERNEL);
452                 cam->urb[i] = urb;
453                 if (!urb) {
454                         err = -ENOMEM;
455                         DBG(1, "usb_alloc_urb() failed");
456                         goto free_urbs;
457                 }
458                 urb->dev = udev;
459                 urb->context = cam;
460                 urb->pipe = usb_rcvisocpipe(udev, 1);
461                 urb->transfer_flags = URB_ISO_ASAP;
462                 urb->number_of_packets = ZC0301_ISO_PACKETS;
463                 urb->complete = zc0301_urb_complete;
464                 urb->transfer_buffer = cam->transfer_buffer[i];
465                 urb->transfer_buffer_length = psz * ZC0301_ISO_PACKETS;
466                 urb->interval = 1;
467                 for (j = 0; j < ZC0301_ISO_PACKETS; j++) {
468                         urb->iso_frame_desc[j].offset = psz * j;
469                         urb->iso_frame_desc[j].length = psz;
470                 }
471         }
472
473         err = usb_set_interface(udev, 0, ZC0301_ALTERNATE_SETTING);
474         if (err) {
475                 DBG(1, "usb_set_interface() failed");
476                 goto free_urbs;
477         }
478
479         cam->frame_current = NULL;
480
481         for (i = 0; i < ZC0301_URBS; i++) {
482                 err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
483                 if (err) {
484                         for (j = i-1; j >= 0; j--)
485                                 usb_kill_urb(cam->urb[j]);
486                         DBG(1, "usb_submit_urb() failed, error %d", err);
487                         goto free_urbs;
488                 }
489         }
490
491         return 0;
492
493 free_urbs:
494         for (i = 0; (i < ZC0301_URBS) && cam->urb[i]; i++)
495                 usb_free_urb(cam->urb[i]);
496
497 free_buffers:
498         for (i = 0; (i < ZC0301_URBS) && cam->transfer_buffer[i]; i++)
499                 kfree(cam->transfer_buffer[i]);
500
501         return err;
502 }
503
504
505 static int zc0301_stop_transfer(struct zc0301_device* cam)
506 {
507         struct usb_device *udev = cam->usbdev;
508         s8 i;
509         int err = 0;
510
511         if (cam->state & DEV_DISCONNECTED)
512                 return 0;
513
514         for (i = ZC0301_URBS-1; i >= 0; i--) {
515                 usb_kill_urb(cam->urb[i]);
516                 usb_free_urb(cam->urb[i]);
517                 kfree(cam->transfer_buffer[i]);
518         }
519
520         err = usb_set_interface(udev, 0, 0); /* 0 Mb/s */
521         if (err)
522                 DBG(3, "usb_set_interface() failed");
523
524         return err;
525 }
526
527
528 static int zc0301_stream_interrupt(struct zc0301_device* cam)
529 {
530         long timeout;
531
532         cam->stream = STREAM_INTERRUPT;
533         timeout = wait_event_timeout(cam->wait_stream,
534                                      (cam->stream == STREAM_OFF) ||
535                                      (cam->state & DEV_DISCONNECTED),
536                                      ZC0301_URB_TIMEOUT);
537         if (cam->state & DEV_DISCONNECTED)
538                 return -ENODEV;
539         else if (cam->stream != STREAM_OFF) {
540                 cam->state |= DEV_MISCONFIGURED;
541                 DBG(1, "URB timeout reached. The camera is misconfigured. To "
542                        "use it, close and open /dev/video%d again.",
543                     cam->v4ldev->minor);
544                 return -EIO;
545         }
546
547         return 0;
548 }
549
550 /*****************************************************************************/
551
552 static int
553 zc0301_set_compression(struct zc0301_device* cam,
554                        struct v4l2_jpegcompression* compression)
555 {
556         int r, err = 0;
557
558         if ((r = zc0301_read_reg(cam, 0x0008)) < 0)
559                 err += r;
560         err += zc0301_write_reg(cam, 0x0008, r | 0x11 | compression->quality);
561
562         return err ? -EIO : 0;
563 }
564
565
566 static int zc0301_init(struct zc0301_device* cam)
567 {
568         struct zc0301_sensor* s = &cam->sensor;
569         struct v4l2_control ctrl;
570         struct v4l2_queryctrl *qctrl;
571         struct v4l2_rect* rect;
572         u8 i = 0;
573         int err = 0;
574
575         if (!(cam->state & DEV_INITIALIZED)) {
576                 mutex_init(&cam->open_mutex);
577                 init_waitqueue_head(&cam->wait_open);
578                 qctrl = s->qctrl;
579                 rect = &(s->cropcap.defrect);
580                 cam->compression.quality = ZC0301_COMPRESSION_QUALITY;
581         } else { /* use current values */
582                 qctrl = s->_qctrl;
583                 rect = &(s->_rect);
584         }
585
586         if (s->init) {
587                 err = s->init(cam);
588                 if (err) {
589                         DBG(3, "Sensor initialization failed");
590                         return err;
591                 }
592         }
593
594         if ((err = zc0301_set_compression(cam, &cam->compression))) {
595                 DBG(3, "set_compression() failed");
596                 return err;
597         }
598
599         if (s->set_crop)
600                 if ((err = s->set_crop(cam, rect))) {
601                         DBG(3, "set_crop() failed");
602                         return err;
603                 }
604
605         if (s->set_ctrl) {
606                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
607                         if (s->qctrl[i].id != 0 &&
608                             !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
609                                 ctrl.id = s->qctrl[i].id;
610                                 ctrl.value = qctrl[i].default_value;
611                                 err = s->set_ctrl(cam, &ctrl);
612                                 if (err) {
613                                         DBG(3, "Set %s control failed",
614                                             s->qctrl[i].name);
615                                         return err;
616                                 }
617                                 DBG(3, "Image sensor supports '%s' control",
618                                     s->qctrl[i].name);
619                         }
620         }
621
622         if (!(cam->state & DEV_INITIALIZED)) {
623                 mutex_init(&cam->fileop_mutex);
624                 spin_lock_init(&cam->queue_lock);
625                 init_waitqueue_head(&cam->wait_frame);
626                 init_waitqueue_head(&cam->wait_stream);
627                 cam->nreadbuffers = 2;
628                 memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
629                 memcpy(&(s->_rect), &(s->cropcap.defrect),
630                        sizeof(struct v4l2_rect));
631                 cam->state |= DEV_INITIALIZED;
632         }
633
634         DBG(2, "Initialization succeeded");
635         return 0;
636 }
637
638 /*****************************************************************************/
639
640 static void zc0301_release_resources(struct kref *kref)
641 {
642         struct zc0301_device *cam = container_of(kref, struct zc0301_device,
643                                                  kref);
644         DBG(2, "V4L2 device /dev/video%d deregistered", cam->v4ldev->minor);
645         video_set_drvdata(cam->v4ldev, NULL);
646         video_unregister_device(cam->v4ldev);
647         usb_put_dev(cam->usbdev);
648         kfree(cam->control_buffer);
649         kfree(cam);
650 }
651
652
653 static int zc0301_open(struct inode* inode, struct file* filp)
654 {
655         struct zc0301_device* cam;
656         int err = 0;
657
658         if (!down_read_trylock(&zc0301_dev_lock))
659                 return -ERESTARTSYS;
660
661         cam = video_get_drvdata(video_devdata(filp));
662
663         if (wait_for_completion_interruptible(&cam->probe)) {
664                 up_read(&zc0301_dev_lock);
665                 return -ERESTARTSYS;
666         }
667
668         kref_get(&cam->kref);
669
670         if (mutex_lock_interruptible(&cam->open_mutex)) {
671                 kref_put(&cam->kref, zc0301_release_resources);
672                 up_read(&zc0301_dev_lock);
673                 return -ERESTARTSYS;
674         }
675
676         if (cam->state & DEV_DISCONNECTED) {
677                 DBG(1, "Device not present");
678                 err = -ENODEV;
679                 goto out;
680         }
681
682         if (cam->users) {
683                 DBG(2, "Device /dev/video%d is busy...", cam->v4ldev->minor);
684                 DBG(3, "Simultaneous opens are not supported");
685                 if ((filp->f_flags & O_NONBLOCK) ||
686                     (filp->f_flags & O_NDELAY)) {
687                         err = -EWOULDBLOCK;
688                         goto out;
689                 }
690                 DBG(2, "A blocking open() has been requested. Wait for the "
691                        "device to be released...");
692                 up_read(&zc0301_dev_lock);
693                 err = wait_event_interruptible_exclusive(cam->wait_open,
694                                                 (cam->state & DEV_DISCONNECTED)
695                                                          || !cam->users);
696                 down_read(&zc0301_dev_lock);
697                 if (err)
698                         goto out;
699                 if (cam->state & DEV_DISCONNECTED) {
700                         err = -ENODEV;
701                         goto out;
702                 }
703         }
704
705         if (cam->state & DEV_MISCONFIGURED) {
706                 err = zc0301_init(cam);
707                 if (err) {
708                         DBG(1, "Initialization failed again. "
709                                "I will retry on next open().");
710                         goto out;
711                 }
712                 cam->state &= ~DEV_MISCONFIGURED;
713         }
714
715         if ((err = zc0301_start_transfer(cam)))
716                 goto out;
717
718         filp->private_data = cam;
719         cam->users++;
720         cam->io = IO_NONE;
721         cam->stream = STREAM_OFF;
722         cam->nbuffers = 0;
723         cam->frame_count = 0;
724         zc0301_empty_framequeues(cam);
725
726         DBG(3, "Video device /dev/video%d is open", cam->v4ldev->minor);
727
728 out:
729         mutex_unlock(&cam->open_mutex);
730         if (err)
731                 kref_put(&cam->kref, zc0301_release_resources);
732         up_read(&zc0301_dev_lock);
733         return err;
734 }
735
736
737 static int zc0301_release(struct inode* inode, struct file* filp)
738 {
739         struct zc0301_device* cam;
740
741         down_write(&zc0301_dev_lock);
742
743         cam = video_get_drvdata(video_devdata(filp));
744
745         zc0301_stop_transfer(cam);
746         zc0301_release_buffers(cam);
747         cam->users--;
748         wake_up_interruptible_nr(&cam->wait_open, 1);
749
750         DBG(3, "Video device /dev/video%d closed", cam->v4ldev->minor);
751
752         kref_put(&cam->kref, zc0301_release_resources);
753
754         up_write(&zc0301_dev_lock);
755
756         return 0;
757 }
758
759
760 static ssize_t
761 zc0301_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
762 {
763         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
764         struct zc0301_frame_t* f, * i;
765         unsigned long lock_flags;
766         long timeout;
767         int err = 0;
768
769         if (mutex_lock_interruptible(&cam->fileop_mutex))
770                 return -ERESTARTSYS;
771
772         if (cam->state & DEV_DISCONNECTED) {
773                 DBG(1, "Device not present");
774                 mutex_unlock(&cam->fileop_mutex);
775                 return -ENODEV;
776         }
777
778         if (cam->state & DEV_MISCONFIGURED) {
779                 DBG(1, "The camera is misconfigured. Close and open it "
780                        "again.");
781                 mutex_unlock(&cam->fileop_mutex);
782                 return -EIO;
783         }
784
785         if (cam->io == IO_MMAP) {
786                 DBG(3, "Close and open the device again to choose the read "
787                        "method");
788                 mutex_unlock(&cam->fileop_mutex);
789                 return -EBUSY;
790         }
791
792         if (cam->io == IO_NONE) {
793                 if (!zc0301_request_buffers(cam, cam->nreadbuffers, IO_READ)) {
794                         DBG(1, "read() failed, not enough memory");
795                         mutex_unlock(&cam->fileop_mutex);
796                         return -ENOMEM;
797                 }
798                 cam->io = IO_READ;
799                 cam->stream = STREAM_ON;
800         }
801
802         if (list_empty(&cam->inqueue)) {
803                 if (!list_empty(&cam->outqueue))
804                         zc0301_empty_framequeues(cam);
805                 zc0301_queue_unusedframes(cam);
806         }
807
808         if (!count) {
809                 mutex_unlock(&cam->fileop_mutex);
810                 return 0;
811         }
812
813         if (list_empty(&cam->outqueue)) {
814                 if (filp->f_flags & O_NONBLOCK) {
815                         mutex_unlock(&cam->fileop_mutex);
816                         return -EAGAIN;
817                 }
818                 timeout = wait_event_interruptible_timeout
819                           ( cam->wait_frame,
820                             (!list_empty(&cam->outqueue)) ||
821                             (cam->state & DEV_DISCONNECTED) ||
822                             (cam->state & DEV_MISCONFIGURED),
823                             cam->module_param.frame_timeout *
824                             1000 * msecs_to_jiffies(1) );
825                 if (timeout < 0) {
826                         mutex_unlock(&cam->fileop_mutex);
827                         return timeout;
828                 }
829                 if (cam->state & DEV_DISCONNECTED) {
830                         mutex_unlock(&cam->fileop_mutex);
831                         return -ENODEV;
832                 }
833                 if (!timeout || (cam->state & DEV_MISCONFIGURED)) {
834                         mutex_unlock(&cam->fileop_mutex);
835                         return -EIO;
836                 }
837         }
838
839         f = list_entry(cam->outqueue.prev, struct zc0301_frame_t, frame);
840
841         if (count > f->buf.bytesused)
842                 count = f->buf.bytesused;
843
844         if (copy_to_user(buf, f->bufmem, count)) {
845                 err = -EFAULT;
846                 goto exit;
847         }
848         *f_pos += count;
849
850 exit:
851         spin_lock_irqsave(&cam->queue_lock, lock_flags);
852         list_for_each_entry(i, &cam->outqueue, frame)
853                 i->state = F_UNUSED;
854         INIT_LIST_HEAD(&cam->outqueue);
855         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
856
857         zc0301_queue_unusedframes(cam);
858
859         PDBGG("Frame #%lu, bytes read: %zu",
860               (unsigned long)f->buf.index, count);
861
862         mutex_unlock(&cam->fileop_mutex);
863
864         return err ? err : count;
865 }
866
867
868 static unsigned int zc0301_poll(struct file *filp, poll_table *wait)
869 {
870         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
871         struct zc0301_frame_t* f;
872         unsigned long lock_flags;
873         unsigned int mask = 0;
874
875         if (mutex_lock_interruptible(&cam->fileop_mutex))
876                 return POLLERR;
877
878         if (cam->state & DEV_DISCONNECTED) {
879                 DBG(1, "Device not present");
880                 goto error;
881         }
882
883         if (cam->state & DEV_MISCONFIGURED) {
884                 DBG(1, "The camera is misconfigured. Close and open it "
885                        "again.");
886                 goto error;
887         }
888
889         if (cam->io == IO_NONE) {
890                 if (!zc0301_request_buffers(cam, cam->nreadbuffers, IO_READ)) {
891                         DBG(1, "poll() failed, not enough memory");
892                         goto error;
893                 }
894                 cam->io = IO_READ;
895                 cam->stream = STREAM_ON;
896         }
897
898         if (cam->io == IO_READ) {
899                 spin_lock_irqsave(&cam->queue_lock, lock_flags);
900                 list_for_each_entry(f, &cam->outqueue, frame)
901                         f->state = F_UNUSED;
902                 INIT_LIST_HEAD(&cam->outqueue);
903                 spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
904                 zc0301_queue_unusedframes(cam);
905         }
906
907         poll_wait(filp, &cam->wait_frame, wait);
908
909         if (!list_empty(&cam->outqueue))
910                 mask |= POLLIN | POLLRDNORM;
911
912         mutex_unlock(&cam->fileop_mutex);
913
914         return mask;
915
916 error:
917         mutex_unlock(&cam->fileop_mutex);
918         return POLLERR;
919 }
920
921
922 static void zc0301_vm_open(struct vm_area_struct* vma)
923 {
924         struct zc0301_frame_t* f = vma->vm_private_data;
925         f->vma_use_count++;
926 }
927
928
929 static void zc0301_vm_close(struct vm_area_struct* vma)
930 {
931         /* NOTE: buffers are not freed here */
932         struct zc0301_frame_t* f = vma->vm_private_data;
933         f->vma_use_count--;
934 }
935
936
937 static struct vm_operations_struct zc0301_vm_ops = {
938         .open = zc0301_vm_open,
939         .close = zc0301_vm_close,
940 };
941
942
943 static int zc0301_mmap(struct file* filp, struct vm_area_struct *vma)
944 {
945         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
946         unsigned long size = vma->vm_end - vma->vm_start,
947                       start = vma->vm_start;
948         void *pos;
949         u32 i;
950
951         if (mutex_lock_interruptible(&cam->fileop_mutex))
952                 return -ERESTARTSYS;
953
954         if (cam->state & DEV_DISCONNECTED) {
955                 DBG(1, "Device not present");
956                 mutex_unlock(&cam->fileop_mutex);
957                 return -ENODEV;
958         }
959
960         if (cam->state & DEV_MISCONFIGURED) {
961                 DBG(1, "The camera is misconfigured. Close and open it "
962                        "again.");
963                 mutex_unlock(&cam->fileop_mutex);
964                 return -EIO;
965         }
966
967         if (!(vma->vm_flags & (VM_WRITE | VM_READ))) {
968                 mutex_unlock(&cam->fileop_mutex);
969                 return -EACCES;
970         }
971
972         if (cam->io != IO_MMAP ||
973             size != PAGE_ALIGN(cam->frame[0].buf.length)) {
974                 mutex_unlock(&cam->fileop_mutex);
975                 return -EINVAL;
976         }
977
978         for (i = 0; i < cam->nbuffers; i++) {
979                 if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
980                         break;
981         }
982         if (i == cam->nbuffers) {
983                 mutex_unlock(&cam->fileop_mutex);
984                 return -EINVAL;
985         }
986
987         vma->vm_flags |= VM_IO;
988         vma->vm_flags |= VM_RESERVED;
989
990         pos = cam->frame[i].bufmem;
991         while (size > 0) { /* size is page-aligned */
992                 if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
993                         mutex_unlock(&cam->fileop_mutex);
994                         return -EAGAIN;
995                 }
996                 start += PAGE_SIZE;
997                 pos += PAGE_SIZE;
998                 size -= PAGE_SIZE;
999         }
1000
1001         vma->vm_ops = &zc0301_vm_ops;
1002         vma->vm_private_data = &cam->frame[i];
1003         zc0301_vm_open(vma);
1004
1005         mutex_unlock(&cam->fileop_mutex);
1006
1007         return 0;
1008 }
1009
1010 /*****************************************************************************/
1011
1012 static int
1013 zc0301_vidioc_querycap(struct zc0301_device* cam, void __user * arg)
1014 {
1015         struct v4l2_capability cap = {
1016                 .driver = "zc0301",
1017                 .version = ZC0301_MODULE_VERSION_CODE,
1018                 .capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
1019                                 V4L2_CAP_STREAMING,
1020         };
1021
1022         strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
1023         if (usb_make_path(cam->usbdev, cap.bus_info, sizeof(cap.bus_info)) < 0)
1024                 strlcpy(cap.bus_info, cam->usbdev->dev.bus_id,
1025                         sizeof(cap.bus_info));
1026
1027         if (copy_to_user(arg, &cap, sizeof(cap)))
1028                 return -EFAULT;
1029
1030         return 0;
1031 }
1032
1033
1034 static int
1035 zc0301_vidioc_enuminput(struct zc0301_device* cam, void __user * arg)
1036 {
1037         struct v4l2_input i;
1038
1039         if (copy_from_user(&i, arg, sizeof(i)))
1040                 return -EFAULT;
1041
1042         if (i.index)
1043                 return -EINVAL;
1044
1045         memset(&i, 0, sizeof(i));
1046         strcpy(i.name, "Camera");
1047         i.type = V4L2_INPUT_TYPE_CAMERA;
1048
1049         if (copy_to_user(arg, &i, sizeof(i)))
1050                 return -EFAULT;
1051
1052         return 0;
1053 }
1054
1055
1056 static int
1057 zc0301_vidioc_g_input(struct zc0301_device* cam, void __user * arg)
1058 {
1059         int index = 0;
1060
1061         if (copy_to_user(arg, &index, sizeof(index)))
1062                 return -EFAULT;
1063
1064         return 0;
1065 }
1066
1067
1068 static int
1069 zc0301_vidioc_s_input(struct zc0301_device* cam, void __user * arg)
1070 {
1071         int index;
1072
1073         if (copy_from_user(&index, arg, sizeof(index)))
1074                 return -EFAULT;
1075
1076         if (index != 0)
1077                 return -EINVAL;
1078
1079         return 0;
1080 }
1081
1082
1083 static int
1084 zc0301_vidioc_query_ctrl(struct zc0301_device* cam, void __user * arg)
1085 {
1086         struct zc0301_sensor* s = &cam->sensor;
1087         struct v4l2_queryctrl qc;
1088         u8 i;
1089
1090         if (copy_from_user(&qc, arg, sizeof(qc)))
1091                 return -EFAULT;
1092
1093         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1094                 if (qc.id && qc.id == s->qctrl[i].id) {
1095                         memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
1096                         if (copy_to_user(arg, &qc, sizeof(qc)))
1097                                 return -EFAULT;
1098                         return 0;
1099                 }
1100
1101         return -EINVAL;
1102 }
1103
1104
1105 static int
1106 zc0301_vidioc_g_ctrl(struct zc0301_device* cam, void __user * arg)
1107 {
1108         struct zc0301_sensor* s = &cam->sensor;
1109         struct v4l2_control ctrl;
1110         int err = 0;
1111         u8 i;
1112
1113         if (!s->get_ctrl && !s->set_ctrl)
1114                 return -EINVAL;
1115
1116         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1117                 return -EFAULT;
1118
1119         if (!s->get_ctrl) {
1120                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1121                         if (ctrl.id == s->qctrl[i].id) {
1122                                 ctrl.value = s->_qctrl[i].default_value;
1123                                 goto exit;
1124                         }
1125                 return -EINVAL;
1126         } else
1127                 err = s->get_ctrl(cam, &ctrl);
1128
1129 exit:
1130         if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
1131                 return -EFAULT;
1132
1133         return err;
1134 }
1135
1136
1137 static int
1138 zc0301_vidioc_s_ctrl(struct zc0301_device* cam, void __user * arg)
1139 {
1140         struct zc0301_sensor* s = &cam->sensor;
1141         struct v4l2_control ctrl;
1142         u8 i;
1143         int err = 0;
1144
1145         if (!s->set_ctrl)
1146                 return -EINVAL;
1147
1148         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1149                 return -EFAULT;
1150
1151         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1152                 if (ctrl.id == s->qctrl[i].id) {
1153                         if (s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)
1154                                 return -EINVAL;
1155                         if (ctrl.value < s->qctrl[i].minimum ||
1156                             ctrl.value > s->qctrl[i].maximum)
1157                                 return -ERANGE;
1158                         ctrl.value -= ctrl.value % s->qctrl[i].step;
1159                         break;
1160                 }
1161
1162         if ((err = s->set_ctrl(cam, &ctrl)))
1163                 return err;
1164
1165         s->_qctrl[i].default_value = ctrl.value;
1166
1167         return 0;
1168 }
1169
1170
1171 static int
1172 zc0301_vidioc_cropcap(struct zc0301_device* cam, void __user * arg)
1173 {
1174         struct v4l2_cropcap* cc = &(cam->sensor.cropcap);
1175
1176         cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1177         cc->pixelaspect.numerator = 1;
1178         cc->pixelaspect.denominator = 1;
1179
1180         if (copy_to_user(arg, cc, sizeof(*cc)))
1181                 return -EFAULT;
1182
1183         return 0;
1184 }
1185
1186
1187 static int
1188 zc0301_vidioc_g_crop(struct zc0301_device* cam, void __user * arg)
1189 {
1190         struct zc0301_sensor* s = &cam->sensor;
1191         struct v4l2_crop crop = {
1192                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1193         };
1194
1195         memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));
1196
1197         if (copy_to_user(arg, &crop, sizeof(crop)))
1198                 return -EFAULT;
1199
1200         return 0;
1201 }
1202
1203
1204 static int
1205 zc0301_vidioc_s_crop(struct zc0301_device* cam, void __user * arg)
1206 {
1207         struct zc0301_sensor* s = &cam->sensor;
1208         struct v4l2_crop crop;
1209         struct v4l2_rect* rect;
1210         struct v4l2_rect* bounds = &(s->cropcap.bounds);
1211         const enum zc0301_stream_state stream = cam->stream;
1212         const u32 nbuffers = cam->nbuffers;
1213         u32 i;
1214         int err = 0;
1215
1216         if (copy_from_user(&crop, arg, sizeof(crop)))
1217                 return -EFAULT;
1218
1219         rect = &(crop.c);
1220
1221         if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1222                 return -EINVAL;
1223
1224         if (cam->module_param.force_munmap)
1225                 for (i = 0; i < cam->nbuffers; i++)
1226                         if (cam->frame[i].vma_use_count) {
1227                                 DBG(3, "VIDIOC_S_CROP failed. "
1228                                        "Unmap the buffers first.");
1229                                 return -EBUSY;
1230                         }
1231
1232         if (!s->set_crop) {
1233                 memcpy(rect, &(s->_rect), sizeof(*rect));
1234                 if (copy_to_user(arg, &crop, sizeof(crop)))
1235                         return -EFAULT;
1236                 return 0;
1237         }
1238
1239         rect->left &= ~7L;
1240         rect->top &= ~7L;
1241         if (rect->width < 8)
1242                 rect->width = 8;
1243         if (rect->height < 8)
1244                 rect->height = 8;
1245         if (rect->width > bounds->width)
1246                 rect->width = bounds->width;
1247         if (rect->height > bounds->height)
1248                 rect->height = bounds->height;
1249         if (rect->left < bounds->left)
1250                 rect->left = bounds->left;
1251         if (rect->top < bounds->top)
1252                 rect->top = bounds->top;
1253         if (rect->left + rect->width > bounds->left + bounds->width)
1254                 rect->left = bounds->left+bounds->width - rect->width;
1255         if (rect->top + rect->height > bounds->top + bounds->height)
1256                 rect->top = bounds->top+bounds->height - rect->height;
1257         rect->width &= ~7L;
1258         rect->height &= ~7L;
1259
1260         if (cam->stream == STREAM_ON)
1261                 if ((err = zc0301_stream_interrupt(cam)))
1262                         return err;
1263
1264         if (copy_to_user(arg, &crop, sizeof(crop))) {
1265                 cam->stream = stream;
1266                 return -EFAULT;
1267         }
1268
1269         if (cam->module_param.force_munmap || cam->io == IO_READ)
1270                 zc0301_release_buffers(cam);
1271
1272         if (s->set_crop)
1273                 err += s->set_crop(cam, rect);
1274
1275         if (err) { /* atomic, no rollback in ioctl() */
1276                 cam->state |= DEV_MISCONFIGURED;
1277                 DBG(1, "VIDIOC_S_CROP failed because of hardware problems. To "
1278                        "use the camera, close and open /dev/video%d again.",
1279                     cam->v4ldev->minor);
1280                 return -EIO;
1281         }
1282
1283         s->pix_format.width = rect->width;
1284         s->pix_format.height = rect->height;
1285         memcpy(&(s->_rect), rect, sizeof(*rect));
1286
1287         if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
1288             nbuffers != zc0301_request_buffers(cam, nbuffers, cam->io)) {
1289                 cam->state |= DEV_MISCONFIGURED;
1290                 DBG(1, "VIDIOC_S_CROP failed because of not enough memory. To "
1291                        "use the camera, close and open /dev/video%d again.",
1292                     cam->v4ldev->minor);
1293                 return -ENOMEM;
1294         }
1295
1296         if (cam->io == IO_READ)
1297                 zc0301_empty_framequeues(cam);
1298         else if (cam->module_param.force_munmap)
1299                 zc0301_requeue_outqueue(cam);
1300
1301         cam->stream = stream;
1302
1303         return 0;
1304 }
1305
1306
1307 static int
1308 zc0301_vidioc_enum_framesizes(struct zc0301_device* cam, void __user * arg)
1309 {
1310         struct v4l2_frmsizeenum frmsize;
1311
1312         if (copy_from_user(&frmsize, arg, sizeof(frmsize)))
1313                 return -EFAULT;
1314
1315         if (frmsize.index != 0 && frmsize.index != 1)
1316                 return -EINVAL;
1317
1318         if (frmsize.pixel_format != V4L2_PIX_FMT_JPEG)
1319                 return -EINVAL;
1320
1321         frmsize.type = V4L2_FRMSIZE_TYPE_DISCRETE;
1322
1323         if (frmsize.index == 1) {
1324                 frmsize.discrete.width = cam->sensor.cropcap.defrect.width;
1325                 frmsize.discrete.height = cam->sensor.cropcap.defrect.height;
1326         }
1327         memset(&frmsize.reserved, 0, sizeof(frmsize.reserved));
1328
1329         if (copy_to_user(arg, &frmsize, sizeof(frmsize)))
1330                 return -EFAULT;
1331
1332         return 0;
1333 }
1334
1335
1336 static int
1337 zc0301_vidioc_enum_fmt(struct zc0301_device* cam, void __user * arg)
1338 {
1339         struct v4l2_fmtdesc fmtd;
1340
1341         if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
1342                 return -EFAULT;
1343
1344         if (fmtd.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1345                 return -EINVAL;
1346
1347         if (fmtd.index == 0) {
1348                 strcpy(fmtd.description, "JPEG");
1349                 fmtd.pixelformat = V4L2_PIX_FMT_JPEG;
1350                 fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
1351         } else
1352                 return -EINVAL;
1353
1354         fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1355         memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));
1356
1357         if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
1358                 return -EFAULT;
1359
1360         return 0;
1361 }
1362
1363
1364 static int
1365 zc0301_vidioc_g_fmt(struct zc0301_device* cam, void __user * arg)
1366 {
1367         struct v4l2_format format;
1368         struct v4l2_pix_format* pfmt = &(cam->sensor.pix_format);
1369
1370         if (copy_from_user(&format, arg, sizeof(format)))
1371                 return -EFAULT;
1372
1373         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1374                 return -EINVAL;
1375
1376         pfmt->bytesperline = 0;
1377         pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
1378         pfmt->field = V4L2_FIELD_NONE;
1379         memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));
1380
1381         if (copy_to_user(arg, &format, sizeof(format)))
1382                 return -EFAULT;
1383
1384         return 0;
1385 }
1386
1387
1388 static int
1389 zc0301_vidioc_try_s_fmt(struct zc0301_device* cam, unsigned int cmd,
1390                         void __user * arg)
1391 {
1392         struct zc0301_sensor* s = &cam->sensor;
1393         struct v4l2_format format;
1394         struct v4l2_pix_format* pix;
1395         struct v4l2_pix_format* pfmt = &(s->pix_format);
1396         struct v4l2_rect* bounds = &(s->cropcap.bounds);
1397         struct v4l2_rect rect;
1398         const enum zc0301_stream_state stream = cam->stream;
1399         const u32 nbuffers = cam->nbuffers;
1400         u32 i;
1401         int err = 0;
1402
1403         if (copy_from_user(&format, arg, sizeof(format)))
1404                 return -EFAULT;
1405
1406         pix = &(format.fmt.pix);
1407
1408         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1409                 return -EINVAL;
1410
1411         memcpy(&rect, &(s->_rect), sizeof(rect));
1412
1413         if (!s->set_crop) {
1414                 pix->width = rect.width;
1415                 pix->height = rect.height;
1416         } else {
1417                 rect.width = pix->width;
1418                 rect.height = pix->height;
1419         }
1420
1421         if (rect.width < 8)
1422                 rect.width = 8;
1423         if (rect.height < 8)
1424                 rect.height = 8;
1425         if (rect.width > bounds->left + bounds->width - rect.left)
1426                 rect.width = bounds->left + bounds->width - rect.left;
1427         if (rect.height > bounds->top + bounds->height - rect.top)
1428                 rect.height = bounds->top + bounds->height - rect.top;
1429         rect.width &= ~7L;
1430         rect.height &= ~7L;
1431
1432         pix->width = rect.width;
1433         pix->height = rect.height;
1434         pix->pixelformat = pfmt->pixelformat;
1435         pix->priv = pfmt->priv;
1436         pix->colorspace = pfmt->colorspace;
1437         pix->bytesperline = 0;
1438         pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
1439         pix->field = V4L2_FIELD_NONE;
1440
1441         if (cmd == VIDIOC_TRY_FMT) {
1442                 if (copy_to_user(arg, &format, sizeof(format)))
1443                         return -EFAULT;
1444                 return 0;
1445         }
1446
1447         if (cam->module_param.force_munmap)
1448                 for (i = 0; i < cam->nbuffers; i++)
1449                         if (cam->frame[i].vma_use_count) {
1450                                 DBG(3, "VIDIOC_S_FMT failed. "
1451                                        "Unmap the buffers first.");
1452                                 return -EBUSY;
1453                         }
1454
1455         if (cam->stream == STREAM_ON)
1456                 if ((err = zc0301_stream_interrupt(cam)))
1457                         return err;
1458
1459         if (copy_to_user(arg, &format, sizeof(format))) {
1460                 cam->stream = stream;
1461                 return -EFAULT;
1462         }
1463
1464         if (cam->module_param.force_munmap || cam->io == IO_READ)
1465                 zc0301_release_buffers(cam);
1466
1467         if (s->set_crop)
1468                 err += s->set_crop(cam, &rect);
1469
1470         if (err) { /* atomic, no rollback in ioctl() */
1471                 cam->state |= DEV_MISCONFIGURED;
1472                 DBG(1, "VIDIOC_S_FMT failed because of hardware problems. To "
1473                        "use the camera, close and open /dev/video%d again.",
1474                     cam->v4ldev->minor);
1475                 return -EIO;
1476         }
1477
1478         memcpy(pfmt, pix, sizeof(*pix));
1479         memcpy(&(s->_rect), &rect, sizeof(rect));
1480
1481         if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
1482             nbuffers != zc0301_request_buffers(cam, nbuffers, cam->io)) {
1483                 cam->state |= DEV_MISCONFIGURED;
1484                 DBG(1, "VIDIOC_S_FMT failed because of not enough memory. To "
1485                        "use the camera, close and open /dev/video%d again.",
1486                     cam->v4ldev->minor);
1487                 return -ENOMEM;
1488         }
1489
1490         if (cam->io == IO_READ)
1491                 zc0301_empty_framequeues(cam);
1492         else if (cam->module_param.force_munmap)
1493                 zc0301_requeue_outqueue(cam);
1494
1495         cam->stream = stream;
1496
1497         return 0;
1498 }
1499
1500
1501 static int
1502 zc0301_vidioc_g_jpegcomp(struct zc0301_device* cam, void __user * arg)
1503 {
1504         if (copy_to_user(arg, &cam->compression, sizeof(cam->compression)))
1505                 return -EFAULT;
1506
1507         return 0;
1508 }
1509
1510
1511 static int
1512 zc0301_vidioc_s_jpegcomp(struct zc0301_device* cam, void __user * arg)
1513 {
1514         struct v4l2_jpegcompression jc;
1515         const enum zc0301_stream_state stream = cam->stream;
1516         int err = 0;
1517
1518         if (copy_from_user(&jc, arg, sizeof(jc)))
1519                 return -EFAULT;
1520
1521         if (jc.quality != 0)
1522                 return -EINVAL;
1523
1524         if (cam->stream == STREAM_ON)
1525                 if ((err = zc0301_stream_interrupt(cam)))
1526                         return err;
1527
1528         err += zc0301_set_compression(cam, &jc);
1529         if (err) { /* atomic, no rollback in ioctl() */
1530                 cam->state |= DEV_MISCONFIGURED;
1531                 DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware "
1532                        "problems. To use the camera, close and open "
1533                        "/dev/video%d again.", cam->v4ldev->minor);
1534                 return -EIO;
1535         }
1536
1537         cam->compression.quality = jc.quality;
1538
1539         cam->stream = stream;
1540
1541         return 0;
1542 }
1543
1544
1545 static int
1546 zc0301_vidioc_reqbufs(struct zc0301_device* cam, void __user * arg)
1547 {
1548         struct v4l2_requestbuffers rb;
1549         u32 i;
1550         int err;
1551
1552         if (copy_from_user(&rb, arg, sizeof(rb)))
1553                 return -EFAULT;
1554
1555         if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1556             rb.memory != V4L2_MEMORY_MMAP)
1557                 return -EINVAL;
1558
1559         if (cam->io == IO_READ) {
1560                 DBG(3, "Close and open the device again to choose the mmap "
1561                        "I/O method");
1562                 return -EBUSY;
1563         }
1564
1565         for (i = 0; i < cam->nbuffers; i++)
1566                 if (cam->frame[i].vma_use_count) {
1567                         DBG(3, "VIDIOC_REQBUFS failed. "
1568                                "Previous buffers are still mapped.");
1569                         return -EBUSY;
1570                 }
1571
1572         if (cam->stream == STREAM_ON)
1573                 if ((err = zc0301_stream_interrupt(cam)))
1574                         return err;
1575
1576         zc0301_empty_framequeues(cam);
1577
1578         zc0301_release_buffers(cam);
1579         if (rb.count)
1580                 rb.count = zc0301_request_buffers(cam, rb.count, IO_MMAP);
1581
1582         if (copy_to_user(arg, &rb, sizeof(rb))) {
1583                 zc0301_release_buffers(cam);
1584                 cam->io = IO_NONE;
1585                 return -EFAULT;
1586         }
1587
1588         cam->io = rb.count ? IO_MMAP : IO_NONE;
1589
1590         return 0;
1591 }
1592
1593
1594 static int
1595 zc0301_vidioc_querybuf(struct zc0301_device* cam, void __user * arg)
1596 {
1597         struct v4l2_buffer b;
1598
1599         if (copy_from_user(&b, arg, sizeof(b)))
1600                 return -EFAULT;
1601
1602         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1603             b.index >= cam->nbuffers || cam->io != IO_MMAP)
1604                 return -EINVAL;
1605
1606         memcpy(&b, &cam->frame[b.index].buf, sizeof(b));
1607
1608         if (cam->frame[b.index].vma_use_count)
1609                 b.flags |= V4L2_BUF_FLAG_MAPPED;
1610
1611         if (cam->frame[b.index].state == F_DONE)
1612                 b.flags |= V4L2_BUF_FLAG_DONE;
1613         else if (cam->frame[b.index].state != F_UNUSED)
1614                 b.flags |= V4L2_BUF_FLAG_QUEUED;
1615
1616         if (copy_to_user(arg, &b, sizeof(b)))
1617                 return -EFAULT;
1618
1619         return 0;
1620 }
1621
1622
1623 static int
1624 zc0301_vidioc_qbuf(struct zc0301_device* cam, void __user * arg)
1625 {
1626         struct v4l2_buffer b;
1627         unsigned long lock_flags;
1628
1629         if (copy_from_user(&b, arg, sizeof(b)))
1630                 return -EFAULT;
1631
1632         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1633             b.index >= cam->nbuffers || cam->io != IO_MMAP)
1634                 return -EINVAL;
1635
1636         if (cam->frame[b.index].state != F_UNUSED)
1637                 return -EINVAL;
1638
1639         cam->frame[b.index].state = F_QUEUED;
1640
1641         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1642         list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
1643         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1644
1645         PDBGG("Frame #%lu queued", (unsigned long)b.index);
1646
1647         return 0;
1648 }
1649
1650
1651 static int
1652 zc0301_vidioc_dqbuf(struct zc0301_device* cam, struct file* filp,
1653                     void __user * arg)
1654 {
1655         struct v4l2_buffer b;
1656         struct zc0301_frame_t *f;
1657         unsigned long lock_flags;
1658         long timeout;
1659
1660         if (copy_from_user(&b, arg, sizeof(b)))
1661                 return -EFAULT;
1662
1663         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io!= IO_MMAP)
1664                 return -EINVAL;
1665
1666         if (list_empty(&cam->outqueue)) {
1667                 if (cam->stream == STREAM_OFF)
1668                         return -EINVAL;
1669                 if (filp->f_flags & O_NONBLOCK)
1670                         return -EAGAIN;
1671                 timeout = wait_event_interruptible_timeout
1672                           ( cam->wait_frame,
1673                             (!list_empty(&cam->outqueue)) ||
1674                             (cam->state & DEV_DISCONNECTED) ||
1675                             (cam->state & DEV_MISCONFIGURED),
1676                             cam->module_param.frame_timeout *
1677                             1000 * msecs_to_jiffies(1) );
1678                 if (timeout < 0)
1679                         return timeout;
1680                 if (cam->state & DEV_DISCONNECTED)
1681                         return -ENODEV;
1682                 if (!timeout || (cam->state & DEV_MISCONFIGURED))
1683                         return -EIO;
1684         }
1685
1686         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1687         f = list_entry(cam->outqueue.next, struct zc0301_frame_t, frame);
1688         list_del(cam->outqueue.next);
1689         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1690
1691         f->state = F_UNUSED;
1692
1693         memcpy(&b, &f->buf, sizeof(b));
1694         if (f->vma_use_count)
1695                 b.flags |= V4L2_BUF_FLAG_MAPPED;
1696
1697         if (copy_to_user(arg, &b, sizeof(b)))
1698                 return -EFAULT;
1699
1700         PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index);
1701
1702         return 0;
1703 }
1704
1705
1706 static int
1707 zc0301_vidioc_streamon(struct zc0301_device* cam, void __user * arg)
1708 {
1709         int type;
1710
1711         if (copy_from_user(&type, arg, sizeof(type)))
1712                 return -EFAULT;
1713
1714         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
1715                 return -EINVAL;
1716
1717         cam->stream = STREAM_ON;
1718
1719         DBG(3, "Stream on");
1720
1721         return 0;
1722 }
1723
1724
1725 static int
1726 zc0301_vidioc_streamoff(struct zc0301_device* cam, void __user * arg)
1727 {
1728         int type, err;
1729
1730         if (copy_from_user(&type, arg, sizeof(type)))
1731                 return -EFAULT;
1732
1733         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
1734                 return -EINVAL;
1735
1736         if (cam->stream == STREAM_ON)
1737                 if ((err = zc0301_stream_interrupt(cam)))
1738                         return err;
1739
1740         zc0301_empty_framequeues(cam);
1741
1742         DBG(3, "Stream off");
1743
1744         return 0;
1745 }
1746
1747
1748 static int
1749 zc0301_vidioc_g_parm(struct zc0301_device* cam, void __user * arg)
1750 {
1751         struct v4l2_streamparm sp;
1752
1753         if (copy_from_user(&sp, arg, sizeof(sp)))
1754                 return -EFAULT;
1755
1756         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1757                 return -EINVAL;
1758
1759         sp.parm.capture.extendedmode = 0;
1760         sp.parm.capture.readbuffers = cam->nreadbuffers;
1761
1762         if (copy_to_user(arg, &sp, sizeof(sp)))
1763                 return -EFAULT;
1764
1765         return 0;
1766 }
1767
1768
1769 static int
1770 zc0301_vidioc_s_parm(struct zc0301_device* cam, void __user * arg)
1771 {
1772         struct v4l2_streamparm sp;
1773
1774         if (copy_from_user(&sp, arg, sizeof(sp)))
1775                 return -EFAULT;
1776
1777         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1778                 return -EINVAL;
1779
1780         sp.parm.capture.extendedmode = 0;
1781
1782         if (sp.parm.capture.readbuffers == 0)
1783                 sp.parm.capture.readbuffers = cam->nreadbuffers;
1784
1785         if (sp.parm.capture.readbuffers > ZC0301_MAX_FRAMES)
1786                 sp.parm.capture.readbuffers = ZC0301_MAX_FRAMES;
1787
1788         if (copy_to_user(arg, &sp, sizeof(sp)))
1789                 return -EFAULT;
1790
1791         cam->nreadbuffers = sp.parm.capture.readbuffers;
1792
1793         return 0;
1794 }
1795
1796
1797 static int zc0301_ioctl_v4l2(struct inode* inode, struct file* filp,
1798                              unsigned int cmd, void __user * arg)
1799 {
1800         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
1801
1802         switch (cmd) {
1803
1804         case VIDIOC_QUERYCAP:
1805                 return zc0301_vidioc_querycap(cam, arg);
1806
1807         case VIDIOC_ENUMINPUT:
1808                 return zc0301_vidioc_enuminput(cam, arg);
1809
1810         case VIDIOC_G_INPUT:
1811                 return zc0301_vidioc_g_input(cam, arg);
1812
1813         case VIDIOC_S_INPUT:
1814                 return zc0301_vidioc_s_input(cam, arg);
1815
1816         case VIDIOC_QUERYCTRL:
1817                 return zc0301_vidioc_query_ctrl(cam, arg);
1818
1819         case VIDIOC_G_CTRL:
1820                 return zc0301_vidioc_g_ctrl(cam, arg);
1821
1822         case VIDIOC_S_CTRL:
1823                 return zc0301_vidioc_s_ctrl(cam, arg);
1824
1825         case VIDIOC_CROPCAP:
1826                 return zc0301_vidioc_cropcap(cam, arg);
1827
1828         case VIDIOC_G_CROP:
1829                 return zc0301_vidioc_g_crop(cam, arg);
1830
1831         case VIDIOC_S_CROP:
1832                 return zc0301_vidioc_s_crop(cam, arg);
1833
1834         case VIDIOC_ENUM_FMT:
1835                 return zc0301_vidioc_enum_fmt(cam, arg);
1836
1837         case VIDIOC_G_FMT:
1838                 return zc0301_vidioc_g_fmt(cam, arg);
1839
1840         case VIDIOC_TRY_FMT:
1841         case VIDIOC_S_FMT:
1842                 return zc0301_vidioc_try_s_fmt(cam, cmd, arg);
1843
1844         case VIDIOC_ENUM_FRAMESIZES:
1845                 return zc0301_vidioc_enum_framesizes(cam, arg);
1846
1847         case VIDIOC_G_JPEGCOMP:
1848                 return zc0301_vidioc_g_jpegcomp(cam, arg);
1849
1850         case VIDIOC_S_JPEGCOMP:
1851                 return zc0301_vidioc_s_jpegcomp(cam, arg);
1852
1853         case VIDIOC_REQBUFS:
1854                 return zc0301_vidioc_reqbufs(cam, arg);
1855
1856         case VIDIOC_QUERYBUF:
1857                 return zc0301_vidioc_querybuf(cam, arg);
1858
1859         case VIDIOC_QBUF:
1860                 return zc0301_vidioc_qbuf(cam, arg);
1861
1862         case VIDIOC_DQBUF:
1863                 return zc0301_vidioc_dqbuf(cam, filp, arg);
1864
1865         case VIDIOC_STREAMON:
1866                 return zc0301_vidioc_streamon(cam, arg);
1867
1868         case VIDIOC_STREAMOFF:
1869                 return zc0301_vidioc_streamoff(cam, arg);
1870
1871         case VIDIOC_G_PARM:
1872                 return zc0301_vidioc_g_parm(cam, arg);
1873
1874         case VIDIOC_S_PARM:
1875                 return zc0301_vidioc_s_parm(cam, arg);
1876
1877         case VIDIOC_G_STD:
1878         case VIDIOC_S_STD:
1879         case VIDIOC_QUERYSTD:
1880         case VIDIOC_ENUMSTD:
1881         case VIDIOC_QUERYMENU:
1882         case VIDIOC_ENUM_FRAMEINTERVALS:
1883                 return -EINVAL;
1884
1885         default:
1886                 return -EINVAL;
1887
1888         }
1889 }
1890
1891
1892 static int zc0301_ioctl(struct inode* inode, struct file* filp,
1893                         unsigned int cmd, unsigned long arg)
1894 {
1895         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
1896         int err = 0;
1897
1898         if (mutex_lock_interruptible(&cam->fileop_mutex))
1899                 return -ERESTARTSYS;
1900
1901         if (cam->state & DEV_DISCONNECTED) {
1902                 DBG(1, "Device not present");
1903                 mutex_unlock(&cam->fileop_mutex);
1904                 return -ENODEV;
1905         }
1906
1907         if (cam->state & DEV_MISCONFIGURED) {
1908                 DBG(1, "The camera is misconfigured. Close and open it "
1909                        "again.");
1910                 mutex_unlock(&cam->fileop_mutex);
1911                 return -EIO;
1912         }
1913
1914         V4LDBG(3, "zc0301", cmd);
1915
1916         err = zc0301_ioctl_v4l2(inode, filp, cmd, (void __user *)arg);
1917
1918         mutex_unlock(&cam->fileop_mutex);
1919
1920         return err;
1921 }
1922
1923
1924 static const struct file_operations zc0301_fops = {
1925         .owner =   THIS_MODULE,
1926         .open =    zc0301_open,
1927         .release = zc0301_release,
1928         .ioctl =   zc0301_ioctl,
1929         .compat_ioctl = v4l_compat_ioctl32,
1930         .read =    zc0301_read,
1931         .poll =    zc0301_poll,
1932         .mmap =    zc0301_mmap,
1933         .llseek =  no_llseek,
1934 };
1935
1936 /*****************************************************************************/
1937
1938 static int
1939 zc0301_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
1940 {
1941         struct usb_device *udev = interface_to_usbdev(intf);
1942         struct zc0301_device* cam;
1943         static unsigned int dev_nr = 0;
1944         unsigned int i;
1945         int err = 0;
1946
1947         if (!(cam = kzalloc(sizeof(struct zc0301_device), GFP_KERNEL)))
1948                 return -ENOMEM;
1949
1950         cam->usbdev = udev;
1951
1952         if (!(cam->control_buffer = kzalloc(4, GFP_KERNEL))) {
1953                 DBG(1, "kmalloc() failed");
1954                 err = -ENOMEM;
1955                 goto fail;
1956         }
1957
1958         if (!(cam->v4ldev = video_device_alloc())) {
1959                 DBG(1, "video_device_alloc() failed");
1960                 err = -ENOMEM;
1961                 goto fail;
1962         }
1963
1964         DBG(2, "ZC0301[P] Image Processor and Control Chip detected "
1965                "(vid/pid 0x%04X:0x%04X)",id->idVendor, id->idProduct);
1966
1967         for  (i = 0; zc0301_sensor_table[i]; i++) {
1968                 err = zc0301_sensor_table[i](cam);
1969                 if (!err)
1970                         break;
1971         }
1972
1973         if (!err)
1974                 DBG(2, "%s image sensor detected", cam->sensor.name);
1975         else {
1976                 DBG(1, "No supported image sensor detected");
1977                 err = -ENODEV;
1978                 goto fail;
1979         }
1980
1981         if (zc0301_init(cam)) {
1982                 DBG(1, "Initialization failed. I will retry on open().");
1983                 cam->state |= DEV_MISCONFIGURED;
1984         }
1985
1986         strcpy(cam->v4ldev->name, "ZC0301[P] PC Camera");
1987         cam->v4ldev->owner = THIS_MODULE;
1988         cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
1989         cam->v4ldev->hardware = 0;
1990         cam->v4ldev->fops = &zc0301_fops;
1991         cam->v4ldev->minor = video_nr[dev_nr];
1992         cam->v4ldev->release = video_device_release;
1993         video_set_drvdata(cam->v4ldev, cam);
1994
1995         init_completion(&cam->probe);
1996
1997         err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
1998                                     video_nr[dev_nr]);
1999         if (err) {
2000                 DBG(1, "V4L2 device registration failed");
2001                 if (err == -ENFILE && video_nr[dev_nr] == -1)
2002                         DBG(1, "Free /dev/videoX node not found");
2003                 video_nr[dev_nr] = -1;
2004                 dev_nr = (dev_nr < ZC0301_MAX_DEVICES-1) ? dev_nr+1 : 0;
2005                 complete_all(&cam->probe);
2006                 goto fail;
2007         }
2008
2009         DBG(2, "V4L2 device registered as /dev/video%d", cam->v4ldev->minor);
2010
2011         cam->module_param.force_munmap = force_munmap[dev_nr];
2012         cam->module_param.frame_timeout = frame_timeout[dev_nr];
2013
2014         dev_nr = (dev_nr < ZC0301_MAX_DEVICES-1) ? dev_nr+1 : 0;
2015
2016         usb_set_intfdata(intf, cam);
2017         kref_init(&cam->kref);
2018         usb_get_dev(cam->usbdev);
2019
2020         complete_all(&cam->probe);
2021
2022         return 0;
2023
2024 fail:
2025         if (cam) {
2026                 kfree(cam->control_buffer);
2027                 if (cam->v4ldev)
2028                         video_device_release(cam->v4ldev);
2029                 kfree(cam);
2030         }
2031         return err;
2032 }
2033
2034
2035 static void zc0301_usb_disconnect(struct usb_interface* intf)
2036 {
2037         struct zc0301_device* cam;
2038
2039         down_write(&zc0301_dev_lock);
2040
2041         cam = usb_get_intfdata(intf);
2042
2043         DBG(2, "Disconnecting %s...", cam->v4ldev->name);
2044
2045         if (cam->users) {
2046                 DBG(2, "Device /dev/video%d is open! Deregistration and "
2047                        "memory deallocation are deferred.",
2048                     cam->v4ldev->minor);
2049                 cam->state |= DEV_MISCONFIGURED;
2050                 zc0301_stop_transfer(cam);
2051                 cam->state |= DEV_DISCONNECTED;
2052                 wake_up_interruptible(&cam->wait_frame);
2053                 wake_up(&cam->wait_stream);
2054         } else
2055                 cam->state |= DEV_DISCONNECTED;
2056
2057         wake_up_interruptible_all(&cam->wait_open);
2058
2059         kref_put(&cam->kref, zc0301_release_resources);
2060
2061         up_write(&zc0301_dev_lock);
2062 }
2063
2064
2065 static struct usb_driver zc0301_usb_driver = {
2066         .name =       "zc0301",
2067         .id_table =   zc0301_id_table,
2068         .probe =      zc0301_usb_probe,
2069         .disconnect = zc0301_usb_disconnect,
2070 };
2071
2072 /*****************************************************************************/
2073
2074 static int __init zc0301_module_init(void)
2075 {
2076         int err = 0;
2077
2078         KDBG(2, ZC0301_MODULE_NAME " v" ZC0301_MODULE_VERSION);
2079         KDBG(3, ZC0301_MODULE_AUTHOR);
2080
2081         if ((err = usb_register(&zc0301_usb_driver)))
2082                 KDBG(1, "usb_register() failed");
2083
2084         return err;
2085 }
2086
2087
2088 static void __exit zc0301_module_exit(void)
2089 {
2090         usb_deregister(&zc0301_usb_driver);
2091 }
2092
2093
2094 module_init(zc0301_module_init);
2095 module_exit(zc0301_module_exit);