Merge branch 'for-linus' of master.kernel.org:/pub/scm/linux/kernel/git/dtor/input
[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 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.07"
56 #define ZC0301_MODULE_VERSION_CODE  KERNEL_VERSION(1, 1, 7)
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                 init_waitqueue_head(&cam->open);
577                 qctrl = s->qctrl;
578                 rect = &(s->cropcap.defrect);
579                 cam->compression.quality = ZC0301_COMPRESSION_QUALITY;
580         } else { /* use current values */
581                 qctrl = s->_qctrl;
582                 rect = &(s->_rect);
583         }
584
585         if (s->init) {
586                 err = s->init(cam);
587                 if (err) {
588                         DBG(3, "Sensor initialization failed");
589                         return err;
590                 }
591         }
592
593         if ((err = zc0301_set_compression(cam, &cam->compression))) {
594                 DBG(3, "set_compression() failed");
595                 return err;
596         }
597
598         if (s->set_crop)
599                 if ((err = s->set_crop(cam, rect))) {
600                         DBG(3, "set_crop() failed");
601                         return err;
602                 }
603
604         if (s->set_ctrl) {
605                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
606                         if (s->qctrl[i].id != 0 &&
607                             !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
608                                 ctrl.id = s->qctrl[i].id;
609                                 ctrl.value = qctrl[i].default_value;
610                                 err = s->set_ctrl(cam, &ctrl);
611                                 if (err) {
612                                         DBG(3, "Set %s control failed",
613                                             s->qctrl[i].name);
614                                         return err;
615                                 }
616                                 DBG(3, "Image sensor supports '%s' control",
617                                     s->qctrl[i].name);
618                         }
619         }
620
621         if (!(cam->state & DEV_INITIALIZED)) {
622                 mutex_init(&cam->fileop_mutex);
623                 spin_lock_init(&cam->queue_lock);
624                 init_waitqueue_head(&cam->wait_frame);
625                 init_waitqueue_head(&cam->wait_stream);
626                 cam->nreadbuffers = 2;
627                 memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
628                 memcpy(&(s->_rect), &(s->cropcap.defrect),
629                        sizeof(struct v4l2_rect));
630                 cam->state |= DEV_INITIALIZED;
631         }
632
633         DBG(2, "Initialization succeeded");
634         return 0;
635 }
636
637
638 static void zc0301_release_resources(struct zc0301_device* cam)
639 {
640         DBG(2, "V4L2 device /dev/video%d deregistered", cam->v4ldev->minor);
641         video_set_drvdata(cam->v4ldev, NULL);
642         video_unregister_device(cam->v4ldev);
643         kfree(cam->control_buffer);
644 }
645
646 /*****************************************************************************/
647
648 static int zc0301_open(struct inode* inode, struct file* filp)
649 {
650         struct zc0301_device* cam;
651         int err = 0;
652
653         /*
654            This is the only safe way to prevent race conditions with
655            disconnect
656         */
657         if (!down_read_trylock(&zc0301_disconnect))
658                 return -ERESTARTSYS;
659
660         cam = video_get_drvdata(video_devdata(filp));
661
662         if (mutex_lock_interruptible(&cam->dev_mutex)) {
663                 up_read(&zc0301_disconnect);
664                 return -ERESTARTSYS;
665         }
666
667         if (cam->users) {
668                 DBG(2, "Device /dev/video%d is busy...", cam->v4ldev->minor);
669                 if ((filp->f_flags & O_NONBLOCK) ||
670                     (filp->f_flags & O_NDELAY)) {
671                         err = -EWOULDBLOCK;
672                         goto out;
673                 }
674                 mutex_unlock(&cam->dev_mutex);
675                 err = wait_event_interruptible_exclusive(cam->open,
676                                                   cam->state & DEV_DISCONNECTED
677                                                          || !cam->users);
678                 if (err) {
679                         up_read(&zc0301_disconnect);
680                         return err;
681                 }
682                 if (cam->state & DEV_DISCONNECTED) {
683                         up_read(&zc0301_disconnect);
684                         return -ENODEV;
685                 }
686                 mutex_lock(&cam->dev_mutex);
687         }
688
689
690         if (cam->state & DEV_MISCONFIGURED) {
691                 err = zc0301_init(cam);
692                 if (err) {
693                         DBG(1, "Initialization failed again. "
694                                "I will retry on next open().");
695                         goto out;
696                 }
697                 cam->state &= ~DEV_MISCONFIGURED;
698         }
699
700         if ((err = zc0301_start_transfer(cam)))
701                 goto out;
702
703         filp->private_data = cam;
704         cam->users++;
705         cam->io = IO_NONE;
706         cam->stream = STREAM_OFF;
707         cam->nbuffers = 0;
708         cam->frame_count = 0;
709         zc0301_empty_framequeues(cam);
710
711         DBG(3, "Video device /dev/video%d is open", cam->v4ldev->minor);
712
713 out:
714         mutex_unlock(&cam->dev_mutex);
715         up_read(&zc0301_disconnect);
716         return err;
717 }
718
719
720 static int zc0301_release(struct inode* inode, struct file* filp)
721 {
722         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
723
724         mutex_lock(&cam->dev_mutex); /* prevent disconnect() to be called */
725
726         zc0301_stop_transfer(cam);
727
728         zc0301_release_buffers(cam);
729
730         if (cam->state & DEV_DISCONNECTED) {
731                 zc0301_release_resources(cam);
732                 usb_put_dev(cam->usbdev);
733                 mutex_unlock(&cam->dev_mutex);
734                 kfree(cam);
735                 return 0;
736         }
737
738         cam->users--;
739         wake_up_interruptible_nr(&cam->open, 1);
740
741         DBG(3, "Video device /dev/video%d closed", cam->v4ldev->minor);
742
743         mutex_unlock(&cam->dev_mutex);
744
745         return 0;
746 }
747
748
749 static ssize_t
750 zc0301_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
751 {
752         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
753         struct zc0301_frame_t* f, * i;
754         unsigned long lock_flags;
755         long timeout;
756         int err = 0;
757
758         if (mutex_lock_interruptible(&cam->fileop_mutex))
759                 return -ERESTARTSYS;
760
761         if (cam->state & DEV_DISCONNECTED) {
762                 DBG(1, "Device not present");
763                 mutex_unlock(&cam->fileop_mutex);
764                 return -ENODEV;
765         }
766
767         if (cam->state & DEV_MISCONFIGURED) {
768                 DBG(1, "The camera is misconfigured. Close and open it "
769                        "again.");
770                 mutex_unlock(&cam->fileop_mutex);
771                 return -EIO;
772         }
773
774         if (cam->io == IO_MMAP) {
775                 DBG(3, "Close and open the device again to choose the read "
776                        "method");
777                 mutex_unlock(&cam->fileop_mutex);
778                 return -EINVAL;
779         }
780
781         if (cam->io == IO_NONE) {
782                 if (!zc0301_request_buffers(cam, cam->nreadbuffers, IO_READ)) {
783                         DBG(1, "read() failed, not enough memory");
784                         mutex_unlock(&cam->fileop_mutex);
785                         return -ENOMEM;
786                 }
787                 cam->io = IO_READ;
788                 cam->stream = STREAM_ON;
789         }
790
791         if (list_empty(&cam->inqueue)) {
792                 if (!list_empty(&cam->outqueue))
793                         zc0301_empty_framequeues(cam);
794                 zc0301_queue_unusedframes(cam);
795         }
796
797         if (!count) {
798                 mutex_unlock(&cam->fileop_mutex);
799                 return 0;
800         }
801
802         if (list_empty(&cam->outqueue)) {
803                 if (filp->f_flags & O_NONBLOCK) {
804                         mutex_unlock(&cam->fileop_mutex);
805                         return -EAGAIN;
806                 }
807                 timeout = wait_event_interruptible_timeout
808                           ( cam->wait_frame,
809                             (!list_empty(&cam->outqueue)) ||
810                             (cam->state & DEV_DISCONNECTED) ||
811                             (cam->state & DEV_MISCONFIGURED),
812                             cam->module_param.frame_timeout *
813                             1000 * msecs_to_jiffies(1) );
814                 if (timeout < 0) {
815                         mutex_unlock(&cam->fileop_mutex);
816                         return timeout;
817                 }
818                 if (cam->state & DEV_DISCONNECTED) {
819                         mutex_unlock(&cam->fileop_mutex);
820                         return -ENODEV;
821                 }
822                 if (!timeout || (cam->state & DEV_MISCONFIGURED)) {
823                         mutex_unlock(&cam->fileop_mutex);
824                         return -EIO;
825                 }
826         }
827
828         f = list_entry(cam->outqueue.prev, struct zc0301_frame_t, frame);
829
830         if (count > f->buf.bytesused)
831                 count = f->buf.bytesused;
832
833         if (copy_to_user(buf, f->bufmem, count)) {
834                 err = -EFAULT;
835                 goto exit;
836         }
837         *f_pos += count;
838
839 exit:
840         spin_lock_irqsave(&cam->queue_lock, lock_flags);
841         list_for_each_entry(i, &cam->outqueue, frame)
842                 i->state = F_UNUSED;
843         INIT_LIST_HEAD(&cam->outqueue);
844         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
845
846         zc0301_queue_unusedframes(cam);
847
848         PDBGG("Frame #%lu, bytes read: %zu",
849               (unsigned long)f->buf.index, count);
850
851         mutex_unlock(&cam->fileop_mutex);
852
853         return err ? err : count;
854 }
855
856
857 static unsigned int zc0301_poll(struct file *filp, poll_table *wait)
858 {
859         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
860         struct zc0301_frame_t* f;
861         unsigned long lock_flags;
862         unsigned int mask = 0;
863
864         if (mutex_lock_interruptible(&cam->fileop_mutex))
865                 return POLLERR;
866
867         if (cam->state & DEV_DISCONNECTED) {
868                 DBG(1, "Device not present");
869                 goto error;
870         }
871
872         if (cam->state & DEV_MISCONFIGURED) {
873                 DBG(1, "The camera is misconfigured. Close and open it "
874                        "again.");
875                 goto error;
876         }
877
878         if (cam->io == IO_NONE) {
879                 if (!zc0301_request_buffers(cam, cam->nreadbuffers, IO_READ)) {
880                         DBG(1, "poll() failed, not enough memory");
881                         goto error;
882                 }
883                 cam->io = IO_READ;
884                 cam->stream = STREAM_ON;
885         }
886
887         if (cam->io == IO_READ) {
888                 spin_lock_irqsave(&cam->queue_lock, lock_flags);
889                 list_for_each_entry(f, &cam->outqueue, frame)
890                         f->state = F_UNUSED;
891                 INIT_LIST_HEAD(&cam->outqueue);
892                 spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
893                 zc0301_queue_unusedframes(cam);
894         }
895
896         poll_wait(filp, &cam->wait_frame, wait);
897
898         if (!list_empty(&cam->outqueue))
899                 mask |= POLLIN | POLLRDNORM;
900
901         mutex_unlock(&cam->fileop_mutex);
902
903         return mask;
904
905 error:
906         mutex_unlock(&cam->fileop_mutex);
907         return POLLERR;
908 }
909
910
911 static void zc0301_vm_open(struct vm_area_struct* vma)
912 {
913         struct zc0301_frame_t* f = vma->vm_private_data;
914         f->vma_use_count++;
915 }
916
917
918 static void zc0301_vm_close(struct vm_area_struct* vma)
919 {
920         /* NOTE: buffers are not freed here */
921         struct zc0301_frame_t* f = vma->vm_private_data;
922         f->vma_use_count--;
923 }
924
925
926 static struct vm_operations_struct zc0301_vm_ops = {
927         .open = zc0301_vm_open,
928         .close = zc0301_vm_close,
929 };
930
931
932 static int zc0301_mmap(struct file* filp, struct vm_area_struct *vma)
933 {
934         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
935         unsigned long size = vma->vm_end - vma->vm_start,
936                       start = vma->vm_start;
937         void *pos;
938         u32 i;
939
940         if (mutex_lock_interruptible(&cam->fileop_mutex))
941                 return -ERESTARTSYS;
942
943         if (cam->state & DEV_DISCONNECTED) {
944                 DBG(1, "Device not present");
945                 mutex_unlock(&cam->fileop_mutex);
946                 return -ENODEV;
947         }
948
949         if (cam->state & DEV_MISCONFIGURED) {
950                 DBG(1, "The camera is misconfigured. Close and open it "
951                        "again.");
952                 mutex_unlock(&cam->fileop_mutex);
953                 return -EIO;
954         }
955
956         if (cam->io != IO_MMAP || !(vma->vm_flags & VM_WRITE) ||
957             size != PAGE_ALIGN(cam->frame[0].buf.length)) {
958                 mutex_unlock(&cam->fileop_mutex);
959                 return -EINVAL;
960         }
961
962         for (i = 0; i < cam->nbuffers; i++) {
963                 if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
964                         break;
965         }
966         if (i == cam->nbuffers) {
967                 mutex_unlock(&cam->fileop_mutex);
968                 return -EINVAL;
969         }
970
971         vma->vm_flags |= VM_IO;
972         vma->vm_flags |= VM_RESERVED;
973
974         pos = cam->frame[i].bufmem;
975         while (size > 0) { /* size is page-aligned */
976                 if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
977                         mutex_unlock(&cam->fileop_mutex);
978                         return -EAGAIN;
979                 }
980                 start += PAGE_SIZE;
981                 pos += PAGE_SIZE;
982                 size -= PAGE_SIZE;
983         }
984
985         vma->vm_ops = &zc0301_vm_ops;
986         vma->vm_private_data = &cam->frame[i];
987
988         zc0301_vm_open(vma);
989
990         mutex_unlock(&cam->fileop_mutex);
991
992         return 0;
993 }
994
995 /*****************************************************************************/
996
997 static int
998 zc0301_vidioc_querycap(struct zc0301_device* cam, void __user * arg)
999 {
1000         struct v4l2_capability cap = {
1001                 .driver = "zc0301",
1002                 .version = ZC0301_MODULE_VERSION_CODE,
1003                 .capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
1004                                 V4L2_CAP_STREAMING,
1005         };
1006
1007         strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
1008         if (usb_make_path(cam->usbdev, cap.bus_info, sizeof(cap.bus_info)) < 0)
1009                 strlcpy(cap.bus_info, cam->usbdev->dev.bus_id,
1010                         sizeof(cap.bus_info));
1011
1012         if (copy_to_user(arg, &cap, sizeof(cap)))
1013                 return -EFAULT;
1014
1015         return 0;
1016 }
1017
1018
1019 static int
1020 zc0301_vidioc_enuminput(struct zc0301_device* cam, void __user * arg)
1021 {
1022         struct v4l2_input i;
1023
1024         if (copy_from_user(&i, arg, sizeof(i)))
1025                 return -EFAULT;
1026
1027         if (i.index)
1028                 return -EINVAL;
1029
1030         memset(&i, 0, sizeof(i));
1031         strcpy(i.name, "Camera");
1032         i.type = V4L2_INPUT_TYPE_CAMERA;
1033
1034         if (copy_to_user(arg, &i, sizeof(i)))
1035                 return -EFAULT;
1036
1037         return 0;
1038 }
1039
1040
1041 static int
1042 zc0301_vidioc_g_input(struct zc0301_device* cam, void __user * arg)
1043 {
1044         int index = 0;
1045
1046         if (copy_to_user(arg, &index, sizeof(index)))
1047                 return -EFAULT;
1048
1049         return 0;
1050 }
1051
1052
1053 static int
1054 zc0301_vidioc_s_input(struct zc0301_device* cam, void __user * arg)
1055 {
1056         int index;
1057
1058         if (copy_from_user(&index, arg, sizeof(index)))
1059                 return -EFAULT;
1060
1061         if (index != 0)
1062                 return -EINVAL;
1063
1064         return 0;
1065 }
1066
1067
1068 static int
1069 zc0301_vidioc_query_ctrl(struct zc0301_device* cam, void __user * arg)
1070 {
1071         struct zc0301_sensor* s = &cam->sensor;
1072         struct v4l2_queryctrl qc;
1073         u8 i;
1074
1075         if (copy_from_user(&qc, arg, sizeof(qc)))
1076                 return -EFAULT;
1077
1078         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1079                 if (qc.id && qc.id == s->qctrl[i].id) {
1080                         memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
1081                         if (copy_to_user(arg, &qc, sizeof(qc)))
1082                                 return -EFAULT;
1083                         return 0;
1084                 }
1085
1086         return -EINVAL;
1087 }
1088
1089
1090 static int
1091 zc0301_vidioc_g_ctrl(struct zc0301_device* cam, void __user * arg)
1092 {
1093         struct zc0301_sensor* s = &cam->sensor;
1094         struct v4l2_control ctrl;
1095         int err = 0;
1096         u8 i;
1097
1098         if (!s->get_ctrl && !s->set_ctrl)
1099                 return -EINVAL;
1100
1101         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1102                 return -EFAULT;
1103
1104         if (!s->get_ctrl) {
1105                 for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1106                         if (ctrl.id == s->qctrl[i].id) {
1107                                 ctrl.value = s->_qctrl[i].default_value;
1108                                 goto exit;
1109                         }
1110                 return -EINVAL;
1111         } else
1112                 err = s->get_ctrl(cam, &ctrl);
1113
1114 exit:
1115         if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
1116                 return -EFAULT;
1117
1118         return err;
1119 }
1120
1121
1122 static int
1123 zc0301_vidioc_s_ctrl(struct zc0301_device* cam, void __user * arg)
1124 {
1125         struct zc0301_sensor* s = &cam->sensor;
1126         struct v4l2_control ctrl;
1127         u8 i;
1128         int err = 0;
1129
1130         if (!s->set_ctrl)
1131                 return -EINVAL;
1132
1133         if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1134                 return -EFAULT;
1135
1136         for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1137                 if (ctrl.id == s->qctrl[i].id) {
1138                         if (s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)
1139                                 return -EINVAL;
1140                         if (ctrl.value < s->qctrl[i].minimum ||
1141                             ctrl.value > s->qctrl[i].maximum)
1142                                 return -ERANGE;
1143                         ctrl.value -= ctrl.value % s->qctrl[i].step;
1144                         break;
1145                 }
1146
1147         if ((err = s->set_ctrl(cam, &ctrl)))
1148                 return err;
1149
1150         s->_qctrl[i].default_value = ctrl.value;
1151
1152         return 0;
1153 }
1154
1155
1156 static int
1157 zc0301_vidioc_cropcap(struct zc0301_device* cam, void __user * arg)
1158 {
1159         struct v4l2_cropcap* cc = &(cam->sensor.cropcap);
1160
1161         cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1162         cc->pixelaspect.numerator = 1;
1163         cc->pixelaspect.denominator = 1;
1164
1165         if (copy_to_user(arg, cc, sizeof(*cc)))
1166                 return -EFAULT;
1167
1168         return 0;
1169 }
1170
1171
1172 static int
1173 zc0301_vidioc_g_crop(struct zc0301_device* cam, void __user * arg)
1174 {
1175         struct zc0301_sensor* s = &cam->sensor;
1176         struct v4l2_crop crop = {
1177                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1178         };
1179
1180         memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));
1181
1182         if (copy_to_user(arg, &crop, sizeof(crop)))
1183                 return -EFAULT;
1184
1185         return 0;
1186 }
1187
1188
1189 static int
1190 zc0301_vidioc_s_crop(struct zc0301_device* cam, void __user * arg)
1191 {
1192         struct zc0301_sensor* s = &cam->sensor;
1193         struct v4l2_crop crop;
1194         struct v4l2_rect* rect;
1195         struct v4l2_rect* bounds = &(s->cropcap.bounds);
1196         const enum zc0301_stream_state stream = cam->stream;
1197         const u32 nbuffers = cam->nbuffers;
1198         u32 i;
1199         int err = 0;
1200
1201         if (copy_from_user(&crop, arg, sizeof(crop)))
1202                 return -EFAULT;
1203
1204         rect = &(crop.c);
1205
1206         if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1207                 return -EINVAL;
1208
1209         if (cam->module_param.force_munmap)
1210                 for (i = 0; i < cam->nbuffers; i++)
1211                         if (cam->frame[i].vma_use_count) {
1212                                 DBG(3, "VIDIOC_S_CROP failed. "
1213                                        "Unmap the buffers first.");
1214                                 return -EINVAL;
1215                         }
1216
1217         if (!s->set_crop) {
1218                 memcpy(rect, &(s->_rect), sizeof(*rect));
1219                 if (copy_to_user(arg, &crop, sizeof(crop)))
1220                         return -EFAULT;
1221                 return 0;
1222         }
1223
1224         rect->left &= ~7L;
1225         rect->top &= ~7L;
1226         if (rect->width < 8)
1227                 rect->width = 8;
1228         if (rect->height < 8)
1229                 rect->height = 8;
1230         if (rect->width > bounds->width)
1231                 rect->width = bounds->width;
1232         if (rect->height > bounds->height)
1233                 rect->height = bounds->height;
1234         if (rect->left < bounds->left)
1235                 rect->left = bounds->left;
1236         if (rect->top < bounds->top)
1237                 rect->top = bounds->top;
1238         if (rect->left + rect->width > bounds->left + bounds->width)
1239                 rect->left = bounds->left+bounds->width - rect->width;
1240         if (rect->top + rect->height > bounds->top + bounds->height)
1241                 rect->top = bounds->top+bounds->height - rect->height;
1242         rect->width &= ~7L;
1243         rect->height &= ~7L;
1244
1245         if (cam->stream == STREAM_ON)
1246                 if ((err = zc0301_stream_interrupt(cam)))
1247                         return err;
1248
1249         if (copy_to_user(arg, &crop, sizeof(crop))) {
1250                 cam->stream = stream;
1251                 return -EFAULT;
1252         }
1253
1254         if (cam->module_param.force_munmap || cam->io == IO_READ)
1255                 zc0301_release_buffers(cam);
1256
1257         if (s->set_crop)
1258                 err += s->set_crop(cam, rect);
1259
1260         if (err) { /* atomic, no rollback in ioctl() */
1261                 cam->state |= DEV_MISCONFIGURED;
1262                 DBG(1, "VIDIOC_S_CROP failed because of hardware problems. To "
1263                        "use the camera, close and open /dev/video%d again.",
1264                     cam->v4ldev->minor);
1265                 return -EIO;
1266         }
1267
1268         s->pix_format.width = rect->width;
1269         s->pix_format.height = rect->height;
1270         memcpy(&(s->_rect), rect, sizeof(*rect));
1271
1272         if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
1273             nbuffers != zc0301_request_buffers(cam, nbuffers, cam->io)) {
1274                 cam->state |= DEV_MISCONFIGURED;
1275                 DBG(1, "VIDIOC_S_CROP failed because of not enough memory. To "
1276                        "use the camera, close and open /dev/video%d again.",
1277                     cam->v4ldev->minor);
1278                 return -ENOMEM;
1279         }
1280
1281         if (cam->io == IO_READ)
1282                 zc0301_empty_framequeues(cam);
1283         else if (cam->module_param.force_munmap)
1284                 zc0301_requeue_outqueue(cam);
1285
1286         cam->stream = stream;
1287
1288         return 0;
1289 }
1290
1291
1292 static int
1293 zc0301_vidioc_enum_framesizes(struct zc0301_device* cam, void __user * arg)
1294 {
1295         struct v4l2_frmsizeenum frmsize;
1296
1297         if (copy_from_user(&frmsize, arg, sizeof(frmsize)))
1298                 return -EFAULT;
1299
1300         if (frmsize.index != 0 && frmsize.index != 1)
1301                 return -EINVAL;
1302
1303         if (frmsize.pixel_format != V4L2_PIX_FMT_JPEG)
1304                 return -EINVAL;
1305
1306         frmsize.type = V4L2_FRMSIZE_TYPE_DISCRETE;
1307
1308         if (frmsize.index == 1) {
1309                 frmsize.discrete.width = cam->sensor.cropcap.defrect.width;
1310                 frmsize.discrete.height = cam->sensor.cropcap.defrect.height;
1311         }
1312         memset(&frmsize.reserved, 0, sizeof(frmsize.reserved));
1313
1314         if (copy_to_user(arg, &frmsize, sizeof(frmsize)))
1315                 return -EFAULT;
1316
1317         return 0;
1318 }
1319
1320
1321 static int
1322 zc0301_vidioc_enum_fmt(struct zc0301_device* cam, void __user * arg)
1323 {
1324         struct v4l2_fmtdesc fmtd;
1325
1326         if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
1327                 return -EFAULT;
1328
1329         if (fmtd.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1330                 return -EINVAL;
1331
1332         if (fmtd.index == 0) {
1333                 strcpy(fmtd.description, "JPEG");
1334                 fmtd.pixelformat = V4L2_PIX_FMT_JPEG;
1335                 fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
1336         } else
1337                 return -EINVAL;
1338
1339         fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1340         memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));
1341
1342         if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
1343                 return -EFAULT;
1344
1345         return 0;
1346 }
1347
1348
1349 static int
1350 zc0301_vidioc_g_fmt(struct zc0301_device* cam, void __user * arg)
1351 {
1352         struct v4l2_format format;
1353         struct v4l2_pix_format* pfmt = &(cam->sensor.pix_format);
1354
1355         if (copy_from_user(&format, arg, sizeof(format)))
1356                 return -EFAULT;
1357
1358         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1359                 return -EINVAL;
1360
1361         pfmt->bytesperline = 0;
1362         pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
1363         pfmt->field = V4L2_FIELD_NONE;
1364         memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));
1365
1366         if (copy_to_user(arg, &format, sizeof(format)))
1367                 return -EFAULT;
1368
1369         return 0;
1370 }
1371
1372
1373 static int
1374 zc0301_vidioc_try_s_fmt(struct zc0301_device* cam, unsigned int cmd,
1375                         void __user * arg)
1376 {
1377         struct zc0301_sensor* s = &cam->sensor;
1378         struct v4l2_format format;
1379         struct v4l2_pix_format* pix;
1380         struct v4l2_pix_format* pfmt = &(s->pix_format);
1381         struct v4l2_rect* bounds = &(s->cropcap.bounds);
1382         struct v4l2_rect rect;
1383         const enum zc0301_stream_state stream = cam->stream;
1384         const u32 nbuffers = cam->nbuffers;
1385         u32 i;
1386         int err = 0;
1387
1388         if (copy_from_user(&format, arg, sizeof(format)))
1389                 return -EFAULT;
1390
1391         pix = &(format.fmt.pix);
1392
1393         if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1394                 return -EINVAL;
1395
1396         memcpy(&rect, &(s->_rect), sizeof(rect));
1397
1398         if (!s->set_crop) {
1399                 pix->width = rect.width;
1400                 pix->height = rect.height;
1401         } else {
1402                 rect.width = pix->width;
1403                 rect.height = pix->height;
1404         }
1405
1406         if (rect.width < 8)
1407                 rect.width = 8;
1408         if (rect.height < 8)
1409                 rect.height = 8;
1410         if (rect.width > bounds->left + bounds->width - rect.left)
1411                 rect.width = bounds->left + bounds->width - rect.left;
1412         if (rect.height > bounds->top + bounds->height - rect.top)
1413                 rect.height = bounds->top + bounds->height - rect.top;
1414         rect.width &= ~7L;
1415         rect.height &= ~7L;
1416
1417         pix->width = rect.width;
1418         pix->height = rect.height;
1419         pix->pixelformat = pfmt->pixelformat;
1420         pix->priv = pfmt->priv;
1421         pix->colorspace = pfmt->colorspace;
1422         pix->bytesperline = 0;
1423         pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
1424         pix->field = V4L2_FIELD_NONE;
1425
1426         if (cmd == VIDIOC_TRY_FMT) {
1427                 if (copy_to_user(arg, &format, sizeof(format)))
1428                         return -EFAULT;
1429                 return 0;
1430         }
1431
1432         if (cam->module_param.force_munmap)
1433                 for (i = 0; i < cam->nbuffers; i++)
1434                         if (cam->frame[i].vma_use_count) {
1435                                 DBG(3, "VIDIOC_S_FMT failed. "
1436                                        "Unmap the buffers first.");
1437                                 return -EINVAL;
1438                         }
1439
1440         if (cam->stream == STREAM_ON)
1441                 if ((err = zc0301_stream_interrupt(cam)))
1442                         return err;
1443
1444         if (copy_to_user(arg, &format, sizeof(format))) {
1445                 cam->stream = stream;
1446                 return -EFAULT;
1447         }
1448
1449         if (cam->module_param.force_munmap || cam->io == IO_READ)
1450                 zc0301_release_buffers(cam);
1451
1452         if (s->set_crop)
1453                 err += s->set_crop(cam, &rect);
1454
1455         if (err) { /* atomic, no rollback in ioctl() */
1456                 cam->state |= DEV_MISCONFIGURED;
1457                 DBG(1, "VIDIOC_S_FMT failed because of hardware problems. To "
1458                        "use the camera, close and open /dev/video%d again.",
1459                     cam->v4ldev->minor);
1460                 return -EIO;
1461         }
1462
1463         memcpy(pfmt, pix, sizeof(*pix));
1464         memcpy(&(s->_rect), &rect, sizeof(rect));
1465
1466         if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
1467             nbuffers != zc0301_request_buffers(cam, nbuffers, cam->io)) {
1468                 cam->state |= DEV_MISCONFIGURED;
1469                 DBG(1, "VIDIOC_S_FMT failed because of not enough memory. To "
1470                        "use the camera, close and open /dev/video%d again.",
1471                     cam->v4ldev->minor);
1472                 return -ENOMEM;
1473         }
1474
1475         if (cam->io == IO_READ)
1476                 zc0301_empty_framequeues(cam);
1477         else if (cam->module_param.force_munmap)
1478                 zc0301_requeue_outqueue(cam);
1479
1480         cam->stream = stream;
1481
1482         return 0;
1483 }
1484
1485
1486 static int
1487 zc0301_vidioc_g_jpegcomp(struct zc0301_device* cam, void __user * arg)
1488 {
1489         if (copy_to_user(arg, &cam->compression, sizeof(cam->compression)))
1490                 return -EFAULT;
1491
1492         return 0;
1493 }
1494
1495
1496 static int
1497 zc0301_vidioc_s_jpegcomp(struct zc0301_device* cam, void __user * arg)
1498 {
1499         struct v4l2_jpegcompression jc;
1500         const enum zc0301_stream_state stream = cam->stream;
1501         int err = 0;
1502
1503         if (copy_from_user(&jc, arg, sizeof(jc)))
1504                 return -EFAULT;
1505
1506         if (jc.quality != 0)
1507                 return -EINVAL;
1508
1509         if (cam->stream == STREAM_ON)
1510                 if ((err = zc0301_stream_interrupt(cam)))
1511                         return err;
1512
1513         err += zc0301_set_compression(cam, &jc);
1514         if (err) { /* atomic, no rollback in ioctl() */
1515                 cam->state |= DEV_MISCONFIGURED;
1516                 DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware "
1517                        "problems. To use the camera, close and open "
1518                        "/dev/video%d again.", cam->v4ldev->minor);
1519                 return -EIO;
1520         }
1521
1522         cam->compression.quality = jc.quality;
1523
1524         cam->stream = stream;
1525
1526         return 0;
1527 }
1528
1529
1530 static int
1531 zc0301_vidioc_reqbufs(struct zc0301_device* cam, void __user * arg)
1532 {
1533         struct v4l2_requestbuffers rb;
1534         u32 i;
1535         int err;
1536
1537         if (copy_from_user(&rb, arg, sizeof(rb)))
1538                 return -EFAULT;
1539
1540         if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1541             rb.memory != V4L2_MEMORY_MMAP)
1542                 return -EINVAL;
1543
1544         if (cam->io == IO_READ) {
1545                 DBG(3, "Close and open the device again to choose the mmap "
1546                        "I/O method");
1547                 return -EINVAL;
1548         }
1549
1550         for (i = 0; i < cam->nbuffers; i++)
1551                 if (cam->frame[i].vma_use_count) {
1552                         DBG(3, "VIDIOC_REQBUFS failed. "
1553                                "Previous buffers are still mapped.");
1554                         return -EINVAL;
1555                 }
1556
1557         if (cam->stream == STREAM_ON)
1558                 if ((err = zc0301_stream_interrupt(cam)))
1559                         return err;
1560
1561         zc0301_empty_framequeues(cam);
1562
1563         zc0301_release_buffers(cam);
1564         if (rb.count)
1565                 rb.count = zc0301_request_buffers(cam, rb.count, IO_MMAP);
1566
1567         if (copy_to_user(arg, &rb, sizeof(rb))) {
1568                 zc0301_release_buffers(cam);
1569                 cam->io = IO_NONE;
1570                 return -EFAULT;
1571         }
1572
1573         cam->io = rb.count ? IO_MMAP : IO_NONE;
1574
1575         return 0;
1576 }
1577
1578
1579 static int
1580 zc0301_vidioc_querybuf(struct zc0301_device* cam, void __user * arg)
1581 {
1582         struct v4l2_buffer b;
1583
1584         if (copy_from_user(&b, arg, sizeof(b)))
1585                 return -EFAULT;
1586
1587         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1588             b.index >= cam->nbuffers || cam->io != IO_MMAP)
1589                 return -EINVAL;
1590
1591         memcpy(&b, &cam->frame[b.index].buf, sizeof(b));
1592
1593         if (cam->frame[b.index].vma_use_count)
1594                 b.flags |= V4L2_BUF_FLAG_MAPPED;
1595
1596         if (cam->frame[b.index].state == F_DONE)
1597                 b.flags |= V4L2_BUF_FLAG_DONE;
1598         else if (cam->frame[b.index].state != F_UNUSED)
1599                 b.flags |= V4L2_BUF_FLAG_QUEUED;
1600
1601         if (copy_to_user(arg, &b, sizeof(b)))
1602                 return -EFAULT;
1603
1604         return 0;
1605 }
1606
1607
1608 static int
1609 zc0301_vidioc_qbuf(struct zc0301_device* cam, void __user * arg)
1610 {
1611         struct v4l2_buffer b;
1612         unsigned long lock_flags;
1613
1614         if (copy_from_user(&b, arg, sizeof(b)))
1615                 return -EFAULT;
1616
1617         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1618             b.index >= cam->nbuffers || cam->io != IO_MMAP)
1619                 return -EINVAL;
1620
1621         if (cam->frame[b.index].state != F_UNUSED)
1622                 return -EINVAL;
1623
1624         cam->frame[b.index].state = F_QUEUED;
1625
1626         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1627         list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
1628         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1629
1630         PDBGG("Frame #%lu queued", (unsigned long)b.index);
1631
1632         return 0;
1633 }
1634
1635
1636 static int
1637 zc0301_vidioc_dqbuf(struct zc0301_device* cam, struct file* filp,
1638                     void __user * arg)
1639 {
1640         struct v4l2_buffer b;
1641         struct zc0301_frame_t *f;
1642         unsigned long lock_flags;
1643         long timeout;
1644
1645         if (copy_from_user(&b, arg, sizeof(b)))
1646                 return -EFAULT;
1647
1648         if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io!= IO_MMAP)
1649                 return -EINVAL;
1650
1651         if (list_empty(&cam->outqueue)) {
1652                 if (cam->stream == STREAM_OFF)
1653                         return -EINVAL;
1654                 if (filp->f_flags & O_NONBLOCK)
1655                         return -EAGAIN;
1656                 timeout = wait_event_interruptible_timeout
1657                           ( cam->wait_frame,
1658                             (!list_empty(&cam->outqueue)) ||
1659                             (cam->state & DEV_DISCONNECTED) ||
1660                             (cam->state & DEV_MISCONFIGURED),
1661                             cam->module_param.frame_timeout *
1662                             1000 * msecs_to_jiffies(1) );
1663                 if (timeout < 0)
1664                         return timeout;
1665                 if (cam->state & DEV_DISCONNECTED)
1666                         return -ENODEV;
1667                 if (!timeout || (cam->state & DEV_MISCONFIGURED))
1668                         return -EIO;
1669         }
1670
1671         spin_lock_irqsave(&cam->queue_lock, lock_flags);
1672         f = list_entry(cam->outqueue.next, struct zc0301_frame_t, frame);
1673         list_del(cam->outqueue.next);
1674         spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1675
1676         f->state = F_UNUSED;
1677
1678         memcpy(&b, &f->buf, sizeof(b));
1679         if (f->vma_use_count)
1680                 b.flags |= V4L2_BUF_FLAG_MAPPED;
1681
1682         if (copy_to_user(arg, &b, sizeof(b)))
1683                 return -EFAULT;
1684
1685         PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index);
1686
1687         return 0;
1688 }
1689
1690
1691 static int
1692 zc0301_vidioc_streamon(struct zc0301_device* cam, void __user * arg)
1693 {
1694         int type;
1695
1696         if (copy_from_user(&type, arg, sizeof(type)))
1697                 return -EFAULT;
1698
1699         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
1700                 return -EINVAL;
1701
1702         if (list_empty(&cam->inqueue))
1703                 return -EINVAL;
1704
1705         cam->stream = STREAM_ON;
1706
1707         DBG(3, "Stream on");
1708
1709         return 0;
1710 }
1711
1712
1713 static int
1714 zc0301_vidioc_streamoff(struct zc0301_device* cam, void __user * arg)
1715 {
1716         int type, err;
1717
1718         if (copy_from_user(&type, arg, sizeof(type)))
1719                 return -EFAULT;
1720
1721         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
1722                 return -EINVAL;
1723
1724         if (cam->stream == STREAM_ON)
1725                 if ((err = zc0301_stream_interrupt(cam)))
1726                         return err;
1727
1728         zc0301_empty_framequeues(cam);
1729
1730         DBG(3, "Stream off");
1731
1732         return 0;
1733 }
1734
1735
1736 static int
1737 zc0301_vidioc_g_parm(struct zc0301_device* cam, void __user * arg)
1738 {
1739         struct v4l2_streamparm sp;
1740
1741         if (copy_from_user(&sp, arg, sizeof(sp)))
1742                 return -EFAULT;
1743
1744         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1745                 return -EINVAL;
1746
1747         sp.parm.capture.extendedmode = 0;
1748         sp.parm.capture.readbuffers = cam->nreadbuffers;
1749
1750         if (copy_to_user(arg, &sp, sizeof(sp)))
1751                 return -EFAULT;
1752
1753         return 0;
1754 }
1755
1756
1757 static int
1758 zc0301_vidioc_s_parm(struct zc0301_device* cam, void __user * arg)
1759 {
1760         struct v4l2_streamparm sp;
1761
1762         if (copy_from_user(&sp, arg, sizeof(sp)))
1763                 return -EFAULT;
1764
1765         if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1766                 return -EINVAL;
1767
1768         sp.parm.capture.extendedmode = 0;
1769
1770         if (sp.parm.capture.readbuffers == 0)
1771                 sp.parm.capture.readbuffers = cam->nreadbuffers;
1772
1773         if (sp.parm.capture.readbuffers > ZC0301_MAX_FRAMES)
1774                 sp.parm.capture.readbuffers = ZC0301_MAX_FRAMES;
1775
1776         if (copy_to_user(arg, &sp, sizeof(sp)))
1777                 return -EFAULT;
1778
1779         cam->nreadbuffers = sp.parm.capture.readbuffers;
1780
1781         return 0;
1782 }
1783
1784
1785 static int zc0301_ioctl_v4l2(struct inode* inode, struct file* filp,
1786                              unsigned int cmd, void __user * arg)
1787 {
1788         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
1789
1790         switch (cmd) {
1791
1792         case VIDIOC_QUERYCAP:
1793                 return zc0301_vidioc_querycap(cam, arg);
1794
1795         case VIDIOC_ENUMINPUT:
1796                 return zc0301_vidioc_enuminput(cam, arg);
1797
1798         case VIDIOC_G_INPUT:
1799                 return zc0301_vidioc_g_input(cam, arg);
1800
1801         case VIDIOC_S_INPUT:
1802                 return zc0301_vidioc_s_input(cam, arg);
1803
1804         case VIDIOC_QUERYCTRL:
1805                 return zc0301_vidioc_query_ctrl(cam, arg);
1806
1807         case VIDIOC_G_CTRL:
1808                 return zc0301_vidioc_g_ctrl(cam, arg);
1809
1810         case VIDIOC_S_CTRL:
1811                 return zc0301_vidioc_s_ctrl(cam, arg);
1812
1813         case VIDIOC_CROPCAP:
1814                 return zc0301_vidioc_cropcap(cam, arg);
1815
1816         case VIDIOC_G_CROP:
1817                 return zc0301_vidioc_g_crop(cam, arg);
1818
1819         case VIDIOC_S_CROP:
1820                 return zc0301_vidioc_s_crop(cam, arg);
1821
1822         case VIDIOC_ENUM_FMT:
1823                 return zc0301_vidioc_enum_fmt(cam, arg);
1824
1825         case VIDIOC_G_FMT:
1826                 return zc0301_vidioc_g_fmt(cam, arg);
1827
1828         case VIDIOC_TRY_FMT:
1829         case VIDIOC_S_FMT:
1830                 return zc0301_vidioc_try_s_fmt(cam, cmd, arg);
1831
1832         case VIDIOC_ENUM_FRAMESIZES:
1833                 return zc0301_vidioc_enum_framesizes(cam, arg);
1834
1835         case VIDIOC_G_JPEGCOMP:
1836                 return zc0301_vidioc_g_jpegcomp(cam, arg);
1837
1838         case VIDIOC_S_JPEGCOMP:
1839                 return zc0301_vidioc_s_jpegcomp(cam, arg);
1840
1841         case VIDIOC_REQBUFS:
1842                 return zc0301_vidioc_reqbufs(cam, arg);
1843
1844         case VIDIOC_QUERYBUF:
1845                 return zc0301_vidioc_querybuf(cam, arg);
1846
1847         case VIDIOC_QBUF:
1848                 return zc0301_vidioc_qbuf(cam, arg);
1849
1850         case VIDIOC_DQBUF:
1851                 return zc0301_vidioc_dqbuf(cam, filp, arg);
1852
1853         case VIDIOC_STREAMON:
1854                 return zc0301_vidioc_streamon(cam, arg);
1855
1856         case VIDIOC_STREAMOFF:
1857                 return zc0301_vidioc_streamoff(cam, arg);
1858
1859         case VIDIOC_G_PARM:
1860                 return zc0301_vidioc_g_parm(cam, arg);
1861
1862         case VIDIOC_S_PARM:
1863                 return zc0301_vidioc_s_parm(cam, arg);
1864
1865         case VIDIOC_G_STD:
1866         case VIDIOC_S_STD:
1867         case VIDIOC_QUERYSTD:
1868         case VIDIOC_ENUMSTD:
1869         case VIDIOC_QUERYMENU:
1870         case VIDIOC_ENUM_FRAMEINTERVALS:
1871                 return -EINVAL;
1872
1873         default:
1874                 return -EINVAL;
1875
1876         }
1877 }
1878
1879
1880 static int zc0301_ioctl(struct inode* inode, struct file* filp,
1881                         unsigned int cmd, unsigned long arg)
1882 {
1883         struct zc0301_device* cam = video_get_drvdata(video_devdata(filp));
1884         int err = 0;
1885
1886         if (mutex_lock_interruptible(&cam->fileop_mutex))
1887                 return -ERESTARTSYS;
1888
1889         if (cam->state & DEV_DISCONNECTED) {
1890                 DBG(1, "Device not present");
1891                 mutex_unlock(&cam->fileop_mutex);
1892                 return -ENODEV;
1893         }
1894
1895         if (cam->state & DEV_MISCONFIGURED) {
1896                 DBG(1, "The camera is misconfigured. Close and open it "
1897                        "again.");
1898                 mutex_unlock(&cam->fileop_mutex);
1899                 return -EIO;
1900         }
1901
1902         V4LDBG(3, "zc0301", cmd);
1903
1904         err = zc0301_ioctl_v4l2(inode, filp, cmd, (void __user *)arg);
1905
1906         mutex_unlock(&cam->fileop_mutex);
1907
1908         return err;
1909 }
1910
1911
1912 static const struct file_operations zc0301_fops = {
1913         .owner =   THIS_MODULE,
1914         .open =    zc0301_open,
1915         .release = zc0301_release,
1916         .ioctl =   zc0301_ioctl,
1917         .compat_ioctl = v4l_compat_ioctl32,
1918         .read =    zc0301_read,
1919         .poll =    zc0301_poll,
1920         .mmap =    zc0301_mmap,
1921         .llseek =  no_llseek,
1922 };
1923
1924 /*****************************************************************************/
1925
1926 static int
1927 zc0301_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
1928 {
1929         struct usb_device *udev = interface_to_usbdev(intf);
1930         struct zc0301_device* cam;
1931         static unsigned int dev_nr = 0;
1932         unsigned int i;
1933         int err = 0;
1934
1935         if (!(cam = kzalloc(sizeof(struct zc0301_device), GFP_KERNEL)))
1936                 return -ENOMEM;
1937
1938         cam->usbdev = udev;
1939
1940         if (!(cam->control_buffer = kzalloc(4, GFP_KERNEL))) {
1941                 DBG(1, "kmalloc() failed");
1942                 err = -ENOMEM;
1943                 goto fail;
1944         }
1945
1946         if (!(cam->v4ldev = video_device_alloc())) {
1947                 DBG(1, "video_device_alloc() failed");
1948                 err = -ENOMEM;
1949                 goto fail;
1950         }
1951
1952         mutex_init(&cam->dev_mutex);
1953
1954         DBG(2, "ZC0301[P] Image Processor and Control Chip detected "
1955                "(vid/pid 0x%04X:0x%04X)",id->idVendor, id->idProduct);
1956
1957         for  (i = 0; zc0301_sensor_table[i]; i++) {
1958                 err = zc0301_sensor_table[i](cam);
1959                 if (!err)
1960                         break;
1961         }
1962
1963         if (!err)
1964                 DBG(2, "%s image sensor detected", cam->sensor.name);
1965         else {
1966                 DBG(1, "No supported image sensor detected");
1967                 err = -ENODEV;
1968                 goto fail;
1969         }
1970
1971         if (zc0301_init(cam)) {
1972                 DBG(1, "Initialization failed. I will retry on open().");
1973                 cam->state |= DEV_MISCONFIGURED;
1974         }
1975
1976         strcpy(cam->v4ldev->name, "ZC0301[P] PC Camera");
1977         cam->v4ldev->owner = THIS_MODULE;
1978         cam->v4ldev->type = VID_TYPE_CAPTURE | VID_TYPE_SCALES;
1979         cam->v4ldev->hardware = 0;
1980         cam->v4ldev->fops = &zc0301_fops;
1981         cam->v4ldev->minor = video_nr[dev_nr];
1982         cam->v4ldev->release = video_device_release;
1983         video_set_drvdata(cam->v4ldev, cam);
1984
1985         mutex_lock(&cam->dev_mutex);
1986
1987         err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
1988                                     video_nr[dev_nr]);
1989         if (err) {
1990                 DBG(1, "V4L2 device registration failed");
1991                 if (err == -ENFILE && video_nr[dev_nr] == -1)
1992                         DBG(1, "Free /dev/videoX node not found");
1993                 video_nr[dev_nr] = -1;
1994                 dev_nr = (dev_nr < ZC0301_MAX_DEVICES-1) ? dev_nr+1 : 0;
1995                 mutex_unlock(&cam->dev_mutex);
1996                 goto fail;
1997         }
1998
1999         DBG(2, "V4L2 device registered as /dev/video%d", cam->v4ldev->minor);
2000
2001         cam->module_param.force_munmap = force_munmap[dev_nr];
2002         cam->module_param.frame_timeout = frame_timeout[dev_nr];
2003
2004         dev_nr = (dev_nr < ZC0301_MAX_DEVICES-1) ? dev_nr+1 : 0;
2005
2006         usb_set_intfdata(intf, cam);
2007
2008         mutex_unlock(&cam->dev_mutex);
2009
2010         return 0;
2011
2012 fail:
2013         if (cam) {
2014                 kfree(cam->control_buffer);
2015                 if (cam->v4ldev)
2016                         video_device_release(cam->v4ldev);
2017                 kfree(cam);
2018         }
2019         return err;
2020 }
2021
2022
2023 static void zc0301_usb_disconnect(struct usb_interface* intf)
2024 {
2025         struct zc0301_device* cam = usb_get_intfdata(intf);
2026
2027         if (!cam)
2028                 return;
2029
2030         down_write(&zc0301_disconnect);
2031
2032         mutex_lock(&cam->dev_mutex);
2033
2034         DBG(2, "Disconnecting %s...", cam->v4ldev->name);
2035
2036         wake_up_interruptible_all(&cam->open);
2037
2038         if (cam->users) {
2039                 DBG(2, "Device /dev/video%d is open! Deregistration and "
2040                        "memory deallocation are deferred on close.",
2041                     cam->v4ldev->minor);
2042                 cam->state |= DEV_MISCONFIGURED;
2043                 zc0301_stop_transfer(cam);
2044                 cam->state |= DEV_DISCONNECTED;
2045                 wake_up_interruptible(&cam->wait_frame);
2046                 wake_up(&cam->wait_stream);
2047                 usb_get_dev(cam->usbdev);
2048         } else {
2049                 cam->state |= DEV_DISCONNECTED;
2050                 zc0301_release_resources(cam);
2051         }
2052
2053         mutex_unlock(&cam->dev_mutex);
2054
2055         if (!cam->users)
2056                 kfree(cam);
2057
2058         up_write(&zc0301_disconnect);
2059 }
2060
2061
2062 static struct usb_driver zc0301_usb_driver = {
2063         .name =       "zc0301",
2064         .id_table =   zc0301_id_table,
2065         .probe =      zc0301_usb_probe,
2066         .disconnect = zc0301_usb_disconnect,
2067 };
2068
2069 /*****************************************************************************/
2070
2071 static int __init zc0301_module_init(void)
2072 {
2073         int err = 0;
2074
2075         KDBG(2, ZC0301_MODULE_NAME " v" ZC0301_MODULE_VERSION);
2076         KDBG(3, ZC0301_MODULE_AUTHOR);
2077
2078         if ((err = usb_register(&zc0301_usb_driver)))
2079                 KDBG(1, "usb_register() failed");
2080
2081         return err;
2082 }
2083
2084
2085 static void __exit zc0301_module_exit(void)
2086 {
2087         usb_deregister(&zc0301_usb_driver);
2088 }
2089
2090
2091 module_init(zc0301_module_init);
2092 module_exit(zc0301_module_exit);