de39cf0890fc0267dbfe09af4e8713ba744a288e
[safe/jmp/linux-2.6] / drivers / media / video / s2255drv.c
1 /*
2  *  s2255drv.c - a driver for the Sensoray 2255 USB video capture device
3  *
4  *   Copyright (C) 2007-2008 by Sensoray Company Inc.
5  *                              Dean Anderson
6  *
7  * Some video buffer code based on vivi driver:
8  *
9  * Sensoray 2255 device supports 4 simultaneous channels.
10  * The channels are not "crossbar" inputs, they are physically
11  * attached to separate video decoders.
12  *
13  * Because of USB2.0 bandwidth limitations. There is only a
14  * certain amount of data which may be transferred at one time.
15  *
16  * Example maximum bandwidth utilization:
17  *
18  * -full size, color mode YUYV or YUV422P: 2 channels at once
19  *
20  * -full or half size Grey scale: all 4 channels at once
21  *
22  * -half size, color mode YUYV or YUV422P: all 4 channels at once
23  *
24  * -full size, color mode YUYV or YUV422P 1/2 frame rate: all 4 channels
25  *  at once.
26  *  (TODO: Incorporate videodev2 frame rate(FR) enumeration,
27  *  which is currently experimental.)
28  *
29  * This program is free software; you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation; either version 2 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program; if not, write to the Free Software
41  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42  */
43
44 #include <linux/module.h>
45 #include <linux/firmware.h>
46 #include <linux/kernel.h>
47 #include <linux/mutex.h>
48 #include <linux/videodev2.h>
49 #include <linux/version.h>
50 #include <linux/mm.h>
51 #include <media/videobuf-vmalloc.h>
52 #include <media/v4l2-common.h>
53 #include <media/v4l2-ioctl.h>
54 #include <linux/vmalloc.h>
55 #include <linux/usb.h>
56
57 #define FIRMWARE_FILE_NAME "f2255usb.bin"
58
59
60
61 /* vendor request in */
62 #define S2255_VR_IN             0
63 /* vendor request out */
64 #define S2255_VR_OUT            1
65 /* firmware query */
66 #define S2255_VR_FW             0x30
67 /* USB endpoint number for configuring the device */
68 #define S2255_CONFIG_EP         2
69 /* maximum time for DSP to start responding after last FW word loaded(ms) */
70 #define S2255_DSP_BOOTTIME      400
71 /* maximum time to wait for firmware to load (ms) */
72 #define S2255_LOAD_TIMEOUT      (5000 + S2255_DSP_BOOTTIME)
73 #define S2255_DEF_BUFS          16
74 #define MAX_CHANNELS            4
75 #define FRAME_MARKER            0x2255DA4AL
76 #define MAX_PIPE_USBBLOCK       (40 * 1024)
77 #define DEFAULT_PIPE_USBBLOCK   (16 * 1024)
78 #define MAX_CHANNELS            4
79 #define MAX_PIPE_BUFFERS        1
80 #define SYS_FRAMES              4
81 /* maximum size is PAL full size plus room for the marker header(s) */
82 #define SYS_FRAMES_MAXSIZE      (720 * 288 * 2 * 2 + 4096)
83 #define DEF_USB_BLOCK           (4096)
84 #define LINE_SZ_4CIFS_NTSC      640
85 #define LINE_SZ_2CIFS_NTSC      640
86 #define LINE_SZ_1CIFS_NTSC      320
87 #define LINE_SZ_4CIFS_PAL       704
88 #define LINE_SZ_2CIFS_PAL       704
89 #define LINE_SZ_1CIFS_PAL       352
90 #define NUM_LINES_4CIFS_NTSC    240
91 #define NUM_LINES_2CIFS_NTSC    240
92 #define NUM_LINES_1CIFS_NTSC    240
93 #define NUM_LINES_4CIFS_PAL     288
94 #define NUM_LINES_2CIFS_PAL     288
95 #define NUM_LINES_1CIFS_PAL     288
96 #define LINE_SZ_DEF             640
97 #define NUM_LINES_DEF           240
98
99
100 /* predefined settings */
101 #define FORMAT_NTSC     1
102 #define FORMAT_PAL      2
103
104 #define SCALE_4CIFS     1       /* 640x480(NTSC) or 704x576(PAL) */
105 #define SCALE_2CIFS     2       /* 640x240(NTSC) or 704x288(PAL) */
106 #define SCALE_1CIFS     3       /* 320x240(NTSC) or 352x288(PAL) */
107
108 #define COLOR_YUVPL     1       /* YUV planar */
109 #define COLOR_YUVPK     2       /* YUV packed */
110 #define COLOR_Y8        4       /* monochrome */
111
112 /* frame decimation. Not implemented by V4L yet(experimental in V4L) */
113 #define FDEC_1          1       /* capture every frame. default */
114 #define FDEC_2          2       /* capture every 2nd frame */
115 #define FDEC_3          3       /* capture every 3rd frame */
116 #define FDEC_5          5       /* capture every 5th frame */
117
118 /*-------------------------------------------------------
119  * Default mode parameters.
120  *-------------------------------------------------------*/
121 #define DEF_SCALE       SCALE_4CIFS
122 #define DEF_COLOR       COLOR_YUVPL
123 #define DEF_FDEC        FDEC_1
124 #define DEF_BRIGHT      0
125 #define DEF_CONTRAST    0x5c
126 #define DEF_SATURATION  0x80
127 #define DEF_HUE         0
128
129 /* usb config commands */
130 #define IN_DATA_TOKEN   0x2255c0de
131 #define CMD_2255        0xc2255000
132 #define CMD_SET_MODE    (CMD_2255 | 0x10)
133 #define CMD_START       (CMD_2255 | 0x20)
134 #define CMD_STOP        (CMD_2255 | 0x30)
135 #define CMD_STATUS      (CMD_2255 | 0x40)
136
137 struct s2255_mode {
138         u32 format;     /* input video format (NTSC, PAL) */
139         u32 scale;      /* output video scale */
140         u32 color;      /* output video color format */
141         u32 fdec;       /* frame decimation */
142         u32 bright;     /* brightness */
143         u32 contrast;   /* contrast */
144         u32 saturation; /* saturation */
145         u32 hue;        /* hue (NTSC only)*/
146         u32 single;     /* capture 1 frame at a time (!=0), continuously (==0)*/
147         u32 usb_block;  /* block size. should be 4096 of DEF_USB_BLOCK */
148         u32 restart;    /* if DSP requires restart */
149 };
150
151 /* frame structure */
152 #define FRAME_STATE_UNUSED      0
153 #define FRAME_STATE_FILLING     1
154 #define FRAME_STATE_FULL        2
155
156
157 struct s2255_framei {
158         unsigned long size;
159
160         unsigned long ulState;  /* ulState ==0 unused, 1 being filled, 2 full */
161         void *lpvbits;          /* image data */
162         unsigned long cur_size; /* current data copied to it */
163 };
164
165 /* image buffer structure */
166 struct s2255_bufferi {
167         unsigned long dwFrames;                 /* number of frames in buffer */
168         struct s2255_framei frame[SYS_FRAMES];  /* array of FRAME structures */
169 };
170
171 #define DEF_MODEI_NTSC_CONT     {FORMAT_NTSC, DEF_SCALE, DEF_COLOR,     \
172                         DEF_FDEC, DEF_BRIGHT, DEF_CONTRAST, DEF_SATURATION, \
173                         DEF_HUE, 0, DEF_USB_BLOCK, 0}
174
175 struct s2255_dmaqueue {
176         struct list_head        active;
177         /* thread for acquisition */
178         struct task_struct      *kthread;
179         int                     frame;
180         struct s2255_dev        *dev;
181         int                     channel;
182 };
183
184 /* for firmware loading, fw_state */
185 #define S2255_FW_NOTLOADED      0
186 #define S2255_FW_LOADED_DSPWAIT 1
187 #define S2255_FW_SUCCESS        2
188 #define S2255_FW_FAILED         3
189 #define S2255_FW_DISCONNECTING  4
190
191 struct s2255_fw {
192         int                   fw_loaded;
193         int                   fw_size;
194         struct urb            *fw_urb;
195         atomic_t              fw_state;
196         void                  *pfw_data;
197         wait_queue_head_t     wait_fw;
198         struct timer_list     dsp_wait;
199         const struct firmware *fw;
200 };
201
202 struct s2255_pipeinfo {
203         u32 max_transfer_size;
204         u32 cur_transfer_size;
205         u8 *transfer_buffer;
206         u32 transfer_flags;;
207         u32 state;
208         u32 prev_state;
209         u32 urb_size;
210         void *stream_urb;
211         void *dev;      /* back pointer to s2255_dev struct*/
212         u32 err_count;
213         u32 buf_index;
214         u32 idx;
215         u32 priority_set;
216 };
217
218 struct s2255_fmt; /*forward declaration */
219
220 struct s2255_dev {
221         int                     frames;
222         int                     users[MAX_CHANNELS];
223         struct mutex            lock;
224         struct mutex            open_lock;
225         int                     resources[MAX_CHANNELS];
226         struct usb_device       *udev;
227         struct usb_interface    *interface;
228         u8                      read_endpoint;
229
230         struct s2255_dmaqueue   vidq[MAX_CHANNELS];
231         struct video_device     *vdev[MAX_CHANNELS];
232         struct list_head        s2255_devlist;
233         struct timer_list       timer;
234         struct s2255_fw *fw_data;
235         int                     board_num;
236         int                     is_open;
237         struct s2255_pipeinfo   pipes[MAX_PIPE_BUFFERS];
238         struct s2255_bufferi            buffer[MAX_CHANNELS];
239         struct s2255_mode       mode[MAX_CHANNELS];
240         const struct s2255_fmt  *cur_fmt[MAX_CHANNELS];
241         int                     cur_frame[MAX_CHANNELS];
242         int                     last_frame[MAX_CHANNELS];
243         u32                     cc;     /* current channel */
244         int                     b_acquire[MAX_CHANNELS];
245         unsigned long           req_image_size[MAX_CHANNELS];
246         int                     bad_payload[MAX_CHANNELS];
247         unsigned long           frame_count[MAX_CHANNELS];
248         int                     frame_ready;
249         struct kref             kref;
250         spinlock_t              slock;
251 };
252 #define to_s2255_dev(d) container_of(d, struct s2255_dev, kref)
253
254 struct s2255_fmt {
255         char *name;
256         u32 fourcc;
257         int depth;
258 };
259
260 /* buffer for one video frame */
261 struct s2255_buffer {
262         /* common v4l buffer stuff -- must be first */
263         struct videobuf_buffer vb;
264         const struct s2255_fmt *fmt;
265 };
266
267 struct s2255_fh {
268         struct s2255_dev        *dev;
269         const struct s2255_fmt  *fmt;
270         unsigned int            width;
271         unsigned int            height;
272         struct videobuf_queue   vb_vidq;
273         enum v4l2_buf_type      type;
274         int                     channel;
275         /* mode below is the desired mode.
276            mode in s2255_dev is the current mode that was last set */
277         struct s2255_mode       mode;
278         int                     resources[MAX_CHANNELS];
279 };
280
281 #define CUR_USB_FWVER   774     /* current cypress EEPROM firmware version */
282 #define S2255_MAJOR_VERSION     1
283 #define S2255_MINOR_VERSION     13
284 #define S2255_RELEASE           0
285 #define S2255_VERSION           KERNEL_VERSION(S2255_MAJOR_VERSION, \
286                                                S2255_MINOR_VERSION, \
287                                                S2255_RELEASE)
288
289 /* vendor ids */
290 #define USB_S2255_VENDOR_ID     0x1943
291 #define USB_S2255_PRODUCT_ID    0x2255
292 #define S2255_NORMS             (V4L2_STD_PAL | V4L2_STD_NTSC)
293 /* frame prefix size (sent once every frame) */
294 #define PREFIX_SIZE             512
295
296 /* Channels on box are in reverse order */
297 static unsigned long G_chnmap[MAX_CHANNELS] = {3, 2, 1, 0};
298
299 static LIST_HEAD(s2255_devlist);
300
301 static int debug;
302 static int *s2255_debug = &debug;
303
304 static int s2255_start_readpipe(struct s2255_dev *dev);
305 static void s2255_stop_readpipe(struct s2255_dev *dev);
306 static int s2255_start_acquire(struct s2255_dev *dev, unsigned long chn);
307 static int s2255_stop_acquire(struct s2255_dev *dev, unsigned long chn);
308 static void s2255_fillbuff(struct s2255_dev *dev, struct s2255_buffer *buf,
309                            int chn);
310 static int s2255_set_mode(struct s2255_dev *dev, unsigned long chn,
311                           struct s2255_mode *mode);
312 static int s2255_board_shutdown(struct s2255_dev *dev);
313 static void s2255_exit_v4l(struct s2255_dev *dev);
314 static void s2255_fwload_start(struct s2255_dev *dev);
315
316 #define dprintk(level, fmt, arg...)                                     \
317         do {                                                            \
318                 if (*s2255_debug >= (level)) {                          \
319                         printk(KERN_DEBUG "s2255: " fmt, ##arg);        \
320                 }                                                       \
321         } while (0)
322
323
324 static struct usb_driver s2255_driver;
325
326
327 /* Declare static vars that will be used as parameters */
328 static unsigned int vid_limit = 16;     /* Video memory limit, in Mb */
329
330 /* start video number */
331 static int video_nr = -1;       /* /dev/videoN, -1 for autodetect */
332
333 module_param(debug, int, 0644);
334 MODULE_PARM_DESC(debug, "Debug level(0-100) default 0");
335 module_param(vid_limit, int, 0644);
336 MODULE_PARM_DESC(vid_limit, "video memory limit(Mb)");
337 module_param(video_nr, int, 0644);
338 MODULE_PARM_DESC(video_nr, "start video minor(-1 default autodetect)");
339
340 /* USB device table */
341 static struct usb_device_id s2255_table[] = {
342         {USB_DEVICE(USB_S2255_VENDOR_ID, USB_S2255_PRODUCT_ID)},
343         { }                     /* Terminating entry */
344 };
345 MODULE_DEVICE_TABLE(usb, s2255_table);
346
347
348 #define BUFFER_TIMEOUT msecs_to_jiffies(400)
349
350 /* supported controls */
351 static struct v4l2_queryctrl s2255_qctrl[] = {
352         {
353         .id = V4L2_CID_BRIGHTNESS,
354         .type = V4L2_CTRL_TYPE_INTEGER,
355         .name = "Brightness",
356         .minimum = -127,
357         .maximum = 128,
358         .step = 1,
359         .default_value = 0,
360         .flags = 0,
361         }, {
362         .id = V4L2_CID_CONTRAST,
363         .type = V4L2_CTRL_TYPE_INTEGER,
364         .name = "Contrast",
365         .minimum = 0,
366         .maximum = 255,
367         .step = 0x1,
368         .default_value = DEF_CONTRAST,
369         .flags = 0,
370         }, {
371         .id = V4L2_CID_SATURATION,
372         .type = V4L2_CTRL_TYPE_INTEGER,
373         .name = "Saturation",
374         .minimum = 0,
375         .maximum = 255,
376         .step = 0x1,
377         .default_value = DEF_SATURATION,
378         .flags = 0,
379         }, {
380         .id = V4L2_CID_HUE,
381         .type = V4L2_CTRL_TYPE_INTEGER,
382         .name = "Hue",
383         .minimum = 0,
384         .maximum = 255,
385         .step = 0x1,
386         .default_value = DEF_HUE,
387         .flags = 0,
388         }
389 };
390
391 static int qctl_regs[ARRAY_SIZE(s2255_qctrl)];
392
393 /* image formats.  */
394 static const struct s2255_fmt formats[] = {
395         {
396                 .name = "4:2:2, planar, YUV422P",
397                 .fourcc = V4L2_PIX_FMT_YUV422P,
398                 .depth = 16
399
400         }, {
401                 .name = "4:2:2, packed, YUYV",
402                 .fourcc = V4L2_PIX_FMT_YUYV,
403                 .depth = 16
404
405         }, {
406                 .name = "4:2:2, packed, UYVY",
407                 .fourcc = V4L2_PIX_FMT_UYVY,
408                 .depth = 16
409         }, {
410                 .name = "8bpp GREY",
411                 .fourcc = V4L2_PIX_FMT_GREY,
412                 .depth = 8
413         }
414 };
415
416 static int norm_maxw(struct video_device *vdev)
417 {
418         return (vdev->current_norm & V4L2_STD_NTSC) ?
419             LINE_SZ_4CIFS_NTSC : LINE_SZ_4CIFS_PAL;
420 }
421
422 static int norm_maxh(struct video_device *vdev)
423 {
424         return (vdev->current_norm & V4L2_STD_NTSC) ?
425             (NUM_LINES_1CIFS_NTSC * 2) : (NUM_LINES_1CIFS_PAL * 2);
426 }
427
428 static int norm_minw(struct video_device *vdev)
429 {
430         return (vdev->current_norm & V4L2_STD_NTSC) ?
431             LINE_SZ_1CIFS_NTSC : LINE_SZ_1CIFS_PAL;
432 }
433
434 static int norm_minh(struct video_device *vdev)
435 {
436         return (vdev->current_norm & V4L2_STD_NTSC) ?
437             (NUM_LINES_1CIFS_NTSC) : (NUM_LINES_1CIFS_PAL);
438 }
439
440
441 /*
442  * TODO: fixme: move YUV reordering to hardware
443  * converts 2255 planar format to yuyv or uyvy
444  */
445 static void planar422p_to_yuv_packed(const unsigned char *in,
446                                      unsigned char *out,
447                                      int width, int height,
448                                      int fmt)
449 {
450         unsigned char *pY;
451         unsigned char *pCb;
452         unsigned char *pCr;
453         unsigned long size = height * width;
454         unsigned int i;
455         pY = (unsigned char *)in;
456         pCr = (unsigned char *)in + height * width;
457         pCb = (unsigned char *)in + height * width + (height * width / 2);
458         for (i = 0; i < size * 2; i += 4) {
459                 out[i] = (fmt == V4L2_PIX_FMT_YUYV) ? *pY++ : *pCr++;
460                 out[i + 1] = (fmt == V4L2_PIX_FMT_YUYV) ? *pCr++ : *pY++;
461                 out[i + 2] = (fmt == V4L2_PIX_FMT_YUYV) ? *pY++ : *pCb++;
462                 out[i + 3] = (fmt == V4L2_PIX_FMT_YUYV) ? *pCb++ : *pY++;
463         }
464         return;
465 }
466
467
468 /* kickstarts the firmware loading. from probe
469  */
470 static void s2255_timer(unsigned long user_data)
471 {
472         struct s2255_fw *data = (struct s2255_fw *)user_data;
473         dprintk(100, "s2255 timer\n");
474         if (usb_submit_urb(data->fw_urb, GFP_ATOMIC) < 0) {
475                 printk(KERN_ERR "s2255: can't submit urb\n");
476                 atomic_set(&data->fw_state, S2255_FW_FAILED);
477                 /* wake up anything waiting for the firmware */
478                 wake_up(&data->wait_fw);
479                 return;
480         }
481 }
482
483 /* called when DSP is up and running.  DSP is guaranteed to
484    be running after S2255_DSP_BOOTTIME */
485 static void s2255_dsp_running(unsigned long user_data)
486 {
487         struct s2255_fw *data = (struct s2255_fw *)user_data;
488         dprintk(1, "dsp running\n");
489         atomic_set(&data->fw_state, S2255_FW_SUCCESS);
490         wake_up(&data->wait_fw);
491         printk(KERN_INFO "s2255: firmware loaded successfully\n");
492         return;
493 }
494
495
496 /* this loads the firmware asynchronously.
497    Originally this was done synchroously in probe.
498    But it is better to load it asynchronously here than block
499    inside the probe function. Blocking inside probe affects boot time.
500    FW loading is triggered by the timer in the probe function
501 */
502 static void s2255_fwchunk_complete(struct urb *urb)
503 {
504         struct s2255_fw *data = urb->context;
505         struct usb_device *udev = urb->dev;
506         int len;
507         dprintk(100, "udev %p urb %p", udev, urb);
508         if (urb->status) {
509                 dev_err(&udev->dev, "URB failed with status %d", urb->status);
510                 atomic_set(&data->fw_state, S2255_FW_FAILED);
511                 /* wake up anything waiting for the firmware */
512                 wake_up(&data->wait_fw);
513                 return;
514         }
515         if (data->fw_urb == NULL) {
516                 dev_err(&udev->dev, "s2255 disconnected\n");
517                 atomic_set(&data->fw_state, S2255_FW_FAILED);
518                 /* wake up anything waiting for the firmware */
519                 wake_up(&data->wait_fw);
520                 return;
521         }
522 #define CHUNK_SIZE 512
523         /* all USB transfers must be done with continuous kernel memory.
524            can't allocate more than 128k in current linux kernel, so
525            upload the firmware in chunks
526          */
527         if (data->fw_loaded < data->fw_size) {
528                 len = (data->fw_loaded + CHUNK_SIZE) > data->fw_size ?
529                     data->fw_size % CHUNK_SIZE : CHUNK_SIZE;
530
531                 if (len < CHUNK_SIZE)
532                         memset(data->pfw_data, 0, CHUNK_SIZE);
533
534                 dprintk(100, "completed len %d, loaded %d \n", len,
535                         data->fw_loaded);
536
537                 memcpy(data->pfw_data,
538                        (char *) data->fw->data + data->fw_loaded, len);
539
540                 usb_fill_bulk_urb(data->fw_urb, udev, usb_sndbulkpipe(udev, 2),
541                                   data->pfw_data, CHUNK_SIZE,
542                                   s2255_fwchunk_complete, data);
543                 if (usb_submit_urb(data->fw_urb, GFP_ATOMIC) < 0) {
544                         dev_err(&udev->dev, "failed submit URB\n");
545                         atomic_set(&data->fw_state, S2255_FW_FAILED);
546                         /* wake up anything waiting for the firmware */
547                         wake_up(&data->wait_fw);
548                         return;
549                 }
550                 data->fw_loaded += len;
551         } else {
552                 init_timer(&data->dsp_wait);
553                 data->dsp_wait.function = s2255_dsp_running;
554                 data->dsp_wait.data = (unsigned long)data;
555                 atomic_set(&data->fw_state, S2255_FW_LOADED_DSPWAIT);
556                 mod_timer(&data->dsp_wait, msecs_to_jiffies(S2255_DSP_BOOTTIME)
557                           + jiffies);
558         }
559         dprintk(100, "2255 complete done\n");
560         return;
561
562 }
563
564 static int s2255_got_frame(struct s2255_dev *dev, int chn)
565 {
566         struct s2255_dmaqueue *dma_q = &dev->vidq[chn];
567         struct s2255_buffer *buf;
568         unsigned long flags = 0;
569         int rc = 0;
570         dprintk(2, "wakeup: %p channel: %d\n", &dma_q, chn);
571         spin_lock_irqsave(&dev->slock, flags);
572
573         if (list_empty(&dma_q->active)) {
574                 dprintk(1, "No active queue to serve\n");
575                 rc = -1;
576                 goto unlock;
577         }
578         buf = list_entry(dma_q->active.next,
579                          struct s2255_buffer, vb.queue);
580
581         if (!waitqueue_active(&buf->vb.done)) {
582                 /* no one active */
583                 rc = -1;
584                 goto unlock;
585         }
586         list_del(&buf->vb.queue);
587         do_gettimeofday(&buf->vb.ts);
588         dprintk(100, "[%p/%d] wakeup\n", buf, buf->vb.i);
589
590         s2255_fillbuff(dev, buf, dma_q->channel);
591         wake_up(&buf->vb.done);
592         dprintk(2, "wakeup [buf/i] [%p/%d]\n", buf, buf->vb.i);
593 unlock:
594         spin_unlock_irqrestore(&dev->slock, flags);
595         return 0;
596 }
597
598
599 static const struct s2255_fmt *format_by_fourcc(int fourcc)
600 {
601         unsigned int i;
602
603         for (i = 0; i < ARRAY_SIZE(formats); i++) {
604                 if (-1 == formats[i].fourcc)
605                         continue;
606                 if (formats[i].fourcc == fourcc)
607                         return formats + i;
608         }
609         return NULL;
610 }
611
612
613
614
615 /* video buffer vmalloc implementation based partly on VIVI driver which is
616  *          Copyright (c) 2006 by
617  *                  Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
618  *                  Ted Walther <ted--a.t--enumera.com>
619  *                  John Sokol <sokol--a.t--videotechnology.com>
620  *                  http://v4l.videotechnology.com/
621  *
622  */
623 static void s2255_fillbuff(struct s2255_dev *dev, struct s2255_buffer *buf,
624                            int chn)
625 {
626         int pos = 0;
627         struct timeval ts;
628         const char *tmpbuf;
629         char *vbuf = videobuf_to_vmalloc(&buf->vb);
630         unsigned long last_frame;
631         struct s2255_framei *frm;
632
633         if (!vbuf)
634                 return;
635
636         last_frame = dev->last_frame[chn];
637         if (last_frame != -1) {
638                 frm = &dev->buffer[chn].frame[last_frame];
639                 tmpbuf =
640                     (const char *)dev->buffer[chn].frame[last_frame].lpvbits;
641                 switch (buf->fmt->fourcc) {
642                 case V4L2_PIX_FMT_YUYV:
643                 case V4L2_PIX_FMT_UYVY:
644                         planar422p_to_yuv_packed((const unsigned char *)tmpbuf,
645                                                  vbuf, buf->vb.width,
646                                                  buf->vb.height,
647                                                  buf->fmt->fourcc);
648                         break;
649                 case V4L2_PIX_FMT_GREY:
650                         memcpy(vbuf, tmpbuf, buf->vb.width * buf->vb.height);
651                         break;
652                 case V4L2_PIX_FMT_YUV422P:
653                         memcpy(vbuf, tmpbuf,
654                                buf->vb.width * buf->vb.height * 2);
655                         break;
656                 default:
657                         printk(KERN_DEBUG "s2255: unknown format?\n");
658                 }
659                 dev->last_frame[chn] = -1;
660                 /* done with the frame, free it */
661                 frm->ulState = 0;
662                 dprintk(4, "freeing buffer\n");
663         } else {
664                 printk(KERN_ERR "s2255: =======no frame\n");
665                 return;
666
667         }
668         dprintk(2, "s2255fill at : Buffer 0x%08lx size= %d\n",
669                 (unsigned long)vbuf, pos);
670         /* tell v4l buffer was filled */
671
672         buf->vb.field_count = dev->frame_count[chn] * 2;
673         do_gettimeofday(&ts);
674         buf->vb.ts = ts;
675         buf->vb.state = VIDEOBUF_DONE;
676 }
677
678
679 /* ------------------------------------------------------------------
680    Videobuf operations
681    ------------------------------------------------------------------*/
682
683 static int buffer_setup(struct videobuf_queue *vq, unsigned int *count,
684                         unsigned int *size)
685 {
686         struct s2255_fh *fh = vq->priv_data;
687
688         *size = fh->width * fh->height * (fh->fmt->depth >> 3);
689
690         if (0 == *count)
691                 *count = S2255_DEF_BUFS;
692
693         while (*size * (*count) > vid_limit * 1024 * 1024)
694                 (*count)--;
695
696         return 0;
697 }
698
699 static void free_buffer(struct videobuf_queue *vq, struct s2255_buffer *buf)
700 {
701         dprintk(4, "%s\n", __func__);
702
703         videobuf_waiton(&buf->vb, 0, 0);
704         videobuf_vmalloc_free(&buf->vb);
705         buf->vb.state = VIDEOBUF_NEEDS_INIT;
706 }
707
708 static int buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
709                           enum v4l2_field field)
710 {
711         struct s2255_fh *fh = vq->priv_data;
712         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
713         int rc;
714         dprintk(4, "%s, field=%d\n", __func__, field);
715         if (fh->fmt == NULL)
716                 return -EINVAL;
717
718         if ((fh->width < norm_minw(fh->dev->vdev[fh->channel])) ||
719             (fh->width > norm_maxw(fh->dev->vdev[fh->channel])) ||
720             (fh->height < norm_minh(fh->dev->vdev[fh->channel])) ||
721             (fh->height > norm_maxh(fh->dev->vdev[fh->channel]))) {
722                 dprintk(4, "invalid buffer prepare\n");
723                 return -EINVAL;
724         }
725
726         buf->vb.size = fh->width * fh->height * (fh->fmt->depth >> 3);
727
728         if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size) {
729                 dprintk(4, "invalid buffer prepare\n");
730                 return -EINVAL;
731         }
732
733         buf->fmt = fh->fmt;
734         buf->vb.width = fh->width;
735         buf->vb.height = fh->height;
736         buf->vb.field = field;
737
738
739         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
740                 rc = videobuf_iolock(vq, &buf->vb, NULL);
741                 if (rc < 0)
742                         goto fail;
743         }
744
745         buf->vb.state = VIDEOBUF_PREPARED;
746         return 0;
747 fail:
748         free_buffer(vq, buf);
749         return rc;
750 }
751
752 static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
753 {
754         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
755         struct s2255_fh *fh = vq->priv_data;
756         struct s2255_dev *dev = fh->dev;
757         struct s2255_dmaqueue *vidq = &dev->vidq[fh->channel];
758
759         dprintk(1, "%s\n", __func__);
760
761         buf->vb.state = VIDEOBUF_QUEUED;
762         list_add_tail(&buf->vb.queue, &vidq->active);
763 }
764
765 static void buffer_release(struct videobuf_queue *vq,
766                            struct videobuf_buffer *vb)
767 {
768         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
769         struct s2255_fh *fh = vq->priv_data;
770         dprintk(4, "%s %d\n", __func__, fh->channel);
771         free_buffer(vq, buf);
772 }
773
774 static struct videobuf_queue_ops s2255_video_qops = {
775         .buf_setup = buffer_setup,
776         .buf_prepare = buffer_prepare,
777         .buf_queue = buffer_queue,
778         .buf_release = buffer_release,
779 };
780
781
782 static int res_get(struct s2255_dev *dev, struct s2255_fh *fh)
783 {
784         /* is it free? */
785         mutex_lock(&dev->lock);
786         if (dev->resources[fh->channel]) {
787                 /* no, someone else uses it */
788                 mutex_unlock(&dev->lock);
789                 return 0;
790         }
791         /* it's free, grab it */
792         dev->resources[fh->channel] = 1;
793         fh->resources[fh->channel] = 1;
794         dprintk(1, "s2255: res: get\n");
795         mutex_unlock(&dev->lock);
796         return 1;
797 }
798
799 static int res_locked(struct s2255_dev *dev, struct s2255_fh *fh)
800 {
801         return dev->resources[fh->channel];
802 }
803
804 static int res_check(struct s2255_fh *fh)
805 {
806         return fh->resources[fh->channel];
807 }
808
809
810 static void res_free(struct s2255_dev *dev, struct s2255_fh *fh)
811 {
812         mutex_lock(&dev->lock);
813         dev->resources[fh->channel] = 0;
814         fh->resources[fh->channel] = 0;
815         mutex_unlock(&dev->lock);
816         dprintk(1, "res: put\n");
817 }
818
819
820 static int vidioc_querycap(struct file *file, void *priv,
821                            struct v4l2_capability *cap)
822 {
823         struct s2255_fh *fh = file->private_data;
824         struct s2255_dev *dev = fh->dev;
825         strlcpy(cap->driver, "s2255", sizeof(cap->driver));
826         strlcpy(cap->card, "s2255", sizeof(cap->card));
827         strlcpy(cap->bus_info, dev_name(&dev->udev->dev),
828                 sizeof(cap->bus_info));
829         cap->version = S2255_VERSION;
830         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
831         return 0;
832 }
833
834 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
835                                struct v4l2_fmtdesc *f)
836 {
837         int index = 0;
838         if (f)
839                 index = f->index;
840
841         if (index >= ARRAY_SIZE(formats))
842                 return -EINVAL;
843
844         dprintk(4, "name %s\n", formats[index].name);
845         strlcpy(f->description, formats[index].name, sizeof(f->description));
846         f->pixelformat = formats[index].fourcc;
847         return 0;
848 }
849
850 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
851                             struct v4l2_format *f)
852 {
853         struct s2255_fh *fh = priv;
854
855         f->fmt.pix.width = fh->width;
856         f->fmt.pix.height = fh->height;
857         f->fmt.pix.field = fh->vb_vidq.field;
858         f->fmt.pix.pixelformat = fh->fmt->fourcc;
859         f->fmt.pix.bytesperline = f->fmt.pix.width * (fh->fmt->depth >> 3);
860         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
861         return 0;
862 }
863
864 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
865                               struct v4l2_format *f)
866 {
867         const struct s2255_fmt *fmt;
868         enum v4l2_field field;
869         int  b_any_field = 0;
870         struct s2255_fh *fh = priv;
871         struct s2255_dev *dev = fh->dev;
872         int is_ntsc;
873
874         is_ntsc =
875             (dev->vdev[fh->channel]->current_norm & V4L2_STD_NTSC) ? 1 : 0;
876
877         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
878
879         if (fmt == NULL)
880                 return -EINVAL;
881
882         field = f->fmt.pix.field;
883         if (field == V4L2_FIELD_ANY)
884                 b_any_field = 1;
885
886         dprintk(4, "try format %d \n", is_ntsc);
887         /* supports 3 sizes. see s2255drv.h */
888         dprintk(50, "width test %d, height %d\n",
889                 f->fmt.pix.width, f->fmt.pix.height);
890         if (is_ntsc) {
891                 /* NTSC */
892                 if (f->fmt.pix.height >= NUM_LINES_1CIFS_NTSC * 2) {
893                         f->fmt.pix.height = NUM_LINES_1CIFS_NTSC * 2;
894                         if (b_any_field) {
895                                 field = V4L2_FIELD_SEQ_TB;
896                         } else if (!((field == V4L2_FIELD_INTERLACED) ||
897                                       (field == V4L2_FIELD_SEQ_TB) ||
898                                       (field == V4L2_FIELD_INTERLACED_TB))) {
899                                 dprintk(1, "unsupported field setting\n");
900                                 return -EINVAL;
901                         }
902                 } else {
903                         f->fmt.pix.height = NUM_LINES_1CIFS_NTSC;
904                         if (b_any_field) {
905                                 field = V4L2_FIELD_TOP;
906                         } else if (!((field == V4L2_FIELD_TOP) ||
907                                       (field == V4L2_FIELD_BOTTOM))) {
908                                 dprintk(1, "unsupported field setting\n");
909                                 return -EINVAL;
910                         }
911
912                 }
913                 if (f->fmt.pix.width >= LINE_SZ_4CIFS_NTSC)
914                         f->fmt.pix.width = LINE_SZ_4CIFS_NTSC;
915                 else if (f->fmt.pix.width >= LINE_SZ_2CIFS_NTSC)
916                         f->fmt.pix.width = LINE_SZ_2CIFS_NTSC;
917                 else if (f->fmt.pix.width >= LINE_SZ_1CIFS_NTSC)
918                         f->fmt.pix.width = LINE_SZ_1CIFS_NTSC;
919                 else
920                         f->fmt.pix.width = LINE_SZ_1CIFS_NTSC;
921         } else {
922                 /* PAL */
923                 if (f->fmt.pix.height >= NUM_LINES_1CIFS_PAL * 2) {
924                         f->fmt.pix.height = NUM_LINES_1CIFS_PAL * 2;
925                         if (b_any_field) {
926                                 field = V4L2_FIELD_SEQ_TB;
927                         } else if (!((field == V4L2_FIELD_INTERLACED) ||
928                                       (field == V4L2_FIELD_SEQ_TB) ||
929                                       (field == V4L2_FIELD_INTERLACED_TB))) {
930                                 dprintk(1, "unsupported field setting\n");
931                                 return -EINVAL;
932                         }
933                 } else {
934                         f->fmt.pix.height = NUM_LINES_1CIFS_PAL;
935                         if (b_any_field) {
936                                 field = V4L2_FIELD_TOP;
937                         } else if (!((field == V4L2_FIELD_TOP) ||
938                                      (field == V4L2_FIELD_BOTTOM))) {
939                                 dprintk(1, "unsupported field setting\n");
940                                 return -EINVAL;
941                         }
942                 }
943                 if (f->fmt.pix.width >= LINE_SZ_4CIFS_PAL) {
944                         dprintk(50, "pal 704\n");
945                         f->fmt.pix.width = LINE_SZ_4CIFS_PAL;
946                         field = V4L2_FIELD_SEQ_TB;
947                 } else if (f->fmt.pix.width >= LINE_SZ_2CIFS_PAL) {
948                         dprintk(50, "pal 352A\n");
949                         f->fmt.pix.width = LINE_SZ_2CIFS_PAL;
950                         field = V4L2_FIELD_TOP;
951                 } else if (f->fmt.pix.width >= LINE_SZ_1CIFS_PAL) {
952                         dprintk(50, "pal 352B\n");
953                         f->fmt.pix.width = LINE_SZ_1CIFS_PAL;
954                         field = V4L2_FIELD_TOP;
955                 } else {
956                         dprintk(50, "pal 352C\n");
957                         f->fmt.pix.width = LINE_SZ_1CIFS_PAL;
958                         field = V4L2_FIELD_TOP;
959                 }
960         }
961
962         dprintk(50, "width %d height %d field %d \n", f->fmt.pix.width,
963                 f->fmt.pix.height, f->fmt.pix.field);
964         f->fmt.pix.field = field;
965         f->fmt.pix.bytesperline = (f->fmt.pix.width * fmt->depth) >> 3;
966         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
967         return 0;
968 }
969
970 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
971                             struct v4l2_format *f)
972 {
973         struct s2255_fh *fh = priv;
974         const struct s2255_fmt *fmt;
975         struct videobuf_queue *q = &fh->vb_vidq;
976         int ret;
977         int norm;
978
979         ret = vidioc_try_fmt_vid_cap(file, fh, f);
980
981         if (ret < 0)
982                 return ret;
983
984         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
985
986         if (fmt == NULL)
987                 return -EINVAL;
988
989         mutex_lock(&q->vb_lock);
990
991         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
992                 dprintk(1, "queue busy\n");
993                 ret = -EBUSY;
994                 goto out_s_fmt;
995         }
996
997         if (res_locked(fh->dev, fh)) {
998                 dprintk(1, "can't change format after started\n");
999                 ret = -EBUSY;
1000                 goto out_s_fmt;
1001         }
1002
1003         fh->fmt = fmt;
1004         fh->width = f->fmt.pix.width;
1005         fh->height = f->fmt.pix.height;
1006         fh->vb_vidq.field = f->fmt.pix.field;
1007         fh->type = f->type;
1008         norm = norm_minw(fh->dev->vdev[fh->channel]);
1009         if (fh->width > norm_minw(fh->dev->vdev[fh->channel])) {
1010                 if (fh->height > norm_minh(fh->dev->vdev[fh->channel]))
1011                         fh->mode.scale = SCALE_4CIFS;
1012                 else
1013                         fh->mode.scale = SCALE_2CIFS;
1014
1015         } else {
1016                 fh->mode.scale = SCALE_1CIFS;
1017         }
1018
1019         /* color mode */
1020         switch (fh->fmt->fourcc) {
1021         case V4L2_PIX_FMT_GREY:
1022                 fh->mode.color = COLOR_Y8;
1023                 break;
1024         case V4L2_PIX_FMT_YUV422P:
1025                 fh->mode.color = COLOR_YUVPL;
1026                 break;
1027         case V4L2_PIX_FMT_YUYV:
1028         case V4L2_PIX_FMT_UYVY:
1029         default:
1030                 fh->mode.color = COLOR_YUVPK;
1031                 break;
1032         }
1033         ret = 0;
1034 out_s_fmt:
1035         mutex_unlock(&q->vb_lock);
1036         return ret;
1037 }
1038
1039 static int vidioc_reqbufs(struct file *file, void *priv,
1040                           struct v4l2_requestbuffers *p)
1041 {
1042         int rc;
1043         struct s2255_fh *fh = priv;
1044         rc = videobuf_reqbufs(&fh->vb_vidq, p);
1045         return rc;
1046 }
1047
1048 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
1049 {
1050         int rc;
1051         struct s2255_fh *fh = priv;
1052         rc = videobuf_querybuf(&fh->vb_vidq, p);
1053         return rc;
1054 }
1055
1056 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1057 {
1058         int rc;
1059         struct s2255_fh *fh = priv;
1060         rc = videobuf_qbuf(&fh->vb_vidq, p);
1061         return rc;
1062 }
1063
1064 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1065 {
1066         int rc;
1067         struct s2255_fh *fh = priv;
1068         rc = videobuf_dqbuf(&fh->vb_vidq, p, file->f_flags & O_NONBLOCK);
1069         return rc;
1070 }
1071
1072 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1073 static int vidioc_cgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
1074 {
1075         struct s2255_fh *fh = priv;
1076
1077         return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
1078 }
1079 #endif
1080
1081 /* write to the configuration pipe, synchronously */
1082 static int s2255_write_config(struct usb_device *udev, unsigned char *pbuf,
1083                               int size)
1084 {
1085         int pipe;
1086         int done;
1087         long retval = -1;
1088         if (udev) {
1089                 pipe = usb_sndbulkpipe(udev, S2255_CONFIG_EP);
1090                 retval = usb_bulk_msg(udev, pipe, pbuf, size, &done, 500);
1091         }
1092         return retval;
1093 }
1094
1095 static u32 get_transfer_size(struct s2255_mode *mode)
1096 {
1097         int linesPerFrame = LINE_SZ_DEF;
1098         int pixelsPerLine = NUM_LINES_DEF;
1099         u32 outImageSize;
1100         u32 usbInSize;
1101         unsigned int mask_mult;
1102
1103         if (mode == NULL)
1104                 return 0;
1105
1106         if (mode->format == FORMAT_NTSC) {
1107                 switch (mode->scale) {
1108                 case SCALE_4CIFS:
1109                         linesPerFrame = NUM_LINES_4CIFS_NTSC * 2;
1110                         pixelsPerLine = LINE_SZ_4CIFS_NTSC;
1111                         break;
1112                 case SCALE_2CIFS:
1113                         linesPerFrame = NUM_LINES_2CIFS_NTSC;
1114                         pixelsPerLine = LINE_SZ_2CIFS_NTSC;
1115                         break;
1116                 case SCALE_1CIFS:
1117                         linesPerFrame = NUM_LINES_1CIFS_NTSC;
1118                         pixelsPerLine = LINE_SZ_1CIFS_NTSC;
1119                         break;
1120                 default:
1121                         break;
1122                 }
1123         } else if (mode->format == FORMAT_PAL) {
1124                 switch (mode->scale) {
1125                 case SCALE_4CIFS:
1126                         linesPerFrame = NUM_LINES_4CIFS_PAL * 2;
1127                         pixelsPerLine = LINE_SZ_4CIFS_PAL;
1128                         break;
1129                 case SCALE_2CIFS:
1130                         linesPerFrame = NUM_LINES_2CIFS_PAL;
1131                         pixelsPerLine = LINE_SZ_2CIFS_PAL;
1132                         break;
1133                 case SCALE_1CIFS:
1134                         linesPerFrame = NUM_LINES_1CIFS_PAL;
1135                         pixelsPerLine = LINE_SZ_1CIFS_PAL;
1136                         break;
1137                 default:
1138                         break;
1139                 }
1140         }
1141         outImageSize = linesPerFrame * pixelsPerLine;
1142         if (mode->color != COLOR_Y8) {
1143                 /* 2 bytes/pixel if not monochrome */
1144                 outImageSize *= 2;
1145         }
1146
1147         /* total bytes to send including prefix and 4K padding;
1148            must be a multiple of USB_READ_SIZE */
1149         usbInSize = outImageSize + PREFIX_SIZE; /* always send prefix */
1150         mask_mult = 0xffffffffUL - DEF_USB_BLOCK + 1;
1151         /* if size not a multiple of USB_READ_SIZE */
1152         if (usbInSize & ~mask_mult)
1153                 usbInSize = (usbInSize & mask_mult) + (DEF_USB_BLOCK);
1154         return usbInSize;
1155 }
1156
1157 static void dump_verify_mode(struct s2255_dev *sdev, struct s2255_mode *mode)
1158 {
1159         struct device *dev = &sdev->udev->dev;
1160         dev_info(dev, "------------------------------------------------\n");
1161         dev_info(dev, "verify mode\n");
1162         dev_info(dev, "format: %d\n", mode->format);
1163         dev_info(dev, "scale: %d\n", mode->scale);
1164         dev_info(dev, "fdec: %d\n", mode->fdec);
1165         dev_info(dev, "color: %d\n", mode->color);
1166         dev_info(dev, "bright: 0x%x\n", mode->bright);
1167         dev_info(dev, "restart: 0x%x\n", mode->restart);
1168         dev_info(dev, "usb_block: 0x%x\n", mode->usb_block);
1169         dev_info(dev, "single: 0x%x\n", mode->single);
1170         dev_info(dev, "------------------------------------------------\n");
1171 }
1172
1173 /*
1174  * set mode is the function which controls the DSP.
1175  * the restart parameter in struct s2255_mode should be set whenever
1176  * the image size could change via color format, video system or image
1177  * size.
1178  * When the restart parameter is set, we sleep for ONE frame to allow the
1179  * DSP time to get the new frame
1180  */
1181 static int s2255_set_mode(struct s2255_dev *dev, unsigned long chn,
1182                           struct s2255_mode *mode)
1183 {
1184         int res;
1185         u32 *buffer;
1186         unsigned long chn_rev;
1187
1188         chn_rev = G_chnmap[chn];
1189         dprintk(3, "mode scale [%ld] %p %d\n", chn, mode, mode->scale);
1190         dprintk(3, "mode scale [%ld] %p %d\n", chn, &dev->mode[chn],
1191                 dev->mode[chn].scale);
1192         dprintk(2, "mode contrast %x\n", mode->contrast);
1193
1194         /* save the mode */
1195         dev->mode[chn] = *mode;
1196         dev->req_image_size[chn] = get_transfer_size(mode);
1197         dprintk(1, "transfer size %ld\n", dev->req_image_size[chn]);
1198
1199         buffer = kzalloc(512, GFP_KERNEL);
1200         if (buffer == NULL) {
1201                 dev_err(&dev->udev->dev, "out of mem\n");
1202                 return -ENOMEM;
1203         }
1204
1205         /* set the mode */
1206         buffer[0] = IN_DATA_TOKEN;
1207         buffer[1] = (u32) chn_rev;
1208         buffer[2] = CMD_SET_MODE;
1209         memcpy(&buffer[3], &dev->mode[chn], sizeof(struct s2255_mode));
1210         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
1211         if (debug)
1212                 dump_verify_mode(dev, mode);
1213         kfree(buffer);
1214         dprintk(1, "set mode done chn %lu, %d\n", chn, res);
1215
1216         /* wait at least 3 frames before continuing */
1217         if (mode->restart)
1218                 msleep(125);
1219
1220         /* clear the restart flag */
1221         dev->mode[chn].restart = 0;
1222
1223         return res;
1224 }
1225
1226 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
1227 {
1228         int res;
1229         struct s2255_fh *fh = priv;
1230         struct s2255_dev *dev = fh->dev;
1231         struct s2255_mode *new_mode;
1232         struct s2255_mode *old_mode;
1233         int chn;
1234         int j;
1235         dprintk(4, "%s\n", __func__);
1236         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1237                 dev_err(&dev->udev->dev, "invalid fh type0\n");
1238                 return -EINVAL;
1239         }
1240         if (i != fh->type) {
1241                 dev_err(&dev->udev->dev, "invalid fh type1\n");
1242                 return -EINVAL;
1243         }
1244
1245         if (!res_get(dev, fh)) {
1246                 dev_err(&dev->udev->dev, "s2255: stream busy\n");
1247                 return -EBUSY;
1248         }
1249
1250         /* send a set mode command everytime with restart.
1251            in case we switch resolutions or other parameters */
1252         chn = fh->channel;
1253         new_mode = &fh->mode;
1254         old_mode = &fh->dev->mode[chn];
1255
1256         if (new_mode->color != old_mode->color)
1257                 new_mode->restart = 1;
1258         else if (new_mode->scale != old_mode->scale)
1259                 new_mode->restart = 1;
1260         else if (new_mode->format != old_mode->format)
1261                 new_mode->restart = 1;
1262
1263         s2255_set_mode(dev, chn, new_mode);
1264         new_mode->restart = 0;
1265         *old_mode = *new_mode;
1266         dev->cur_fmt[chn] = fh->fmt;
1267         dprintk(1, "%s[%d]\n", __func__, chn);
1268         dev->last_frame[chn] = -1;
1269         dev->bad_payload[chn] = 0;
1270         dev->cur_frame[chn] = 0;
1271         dev->frame_count[chn] = 0;
1272         for (j = 0; j < SYS_FRAMES; j++) {
1273                 dev->buffer[chn].frame[j].ulState = 0;
1274                 dev->buffer[chn].frame[j].cur_size = 0;
1275         }
1276         res = videobuf_streamon(&fh->vb_vidq);
1277         if (res == 0) {
1278                 s2255_start_acquire(dev, chn);
1279                 dev->b_acquire[chn] = 1;
1280         } else {
1281                 res_free(dev, fh);
1282         }
1283         return res;
1284 }
1285
1286 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1287 {
1288         int res;
1289         struct s2255_fh *fh = priv;
1290         struct s2255_dev *dev = fh->dev;
1291
1292         dprintk(4, "%s\n, channel: %d", __func__, fh->channel);
1293         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1294                 printk(KERN_ERR "invalid fh type0\n");
1295                 return -EINVAL;
1296         }
1297         if (i != fh->type) {
1298                 printk(KERN_ERR "invalid type i\n");
1299                 return -EINVAL;
1300         }
1301         s2255_stop_acquire(dev, fh->channel);
1302         res = videobuf_streamoff(&fh->vb_vidq);
1303         if (res < 0)
1304                 return res;
1305         res_free(dev, fh);
1306         return 0;
1307 }
1308
1309 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *i)
1310 {
1311         struct s2255_fh *fh = priv;
1312         struct s2255_mode *mode;
1313         struct videobuf_queue *q = &fh->vb_vidq;
1314         int ret = 0;
1315
1316         mutex_lock(&q->vb_lock);
1317         if (videobuf_queue_is_busy(q)) {
1318                 dprintk(1, "queue busy\n");
1319                 ret = -EBUSY;
1320                 goto out_s_std;
1321         }
1322
1323         if (res_locked(fh->dev, fh)) {
1324                 dprintk(1, "can't change standard after started\n");
1325                 ret = -EBUSY;
1326                 goto out_s_std;
1327         }
1328         mode = &fh->mode;
1329
1330         if (*i & V4L2_STD_NTSC) {
1331                 dprintk(4, "vidioc_s_std NTSC\n");
1332                 mode->format = FORMAT_NTSC;
1333         } else if (*i & V4L2_STD_PAL) {
1334                 dprintk(4, "vidioc_s_std PAL\n");
1335                 mode->format = FORMAT_PAL;
1336         } else {
1337                 ret = -EINVAL;
1338         }
1339 out_s_std:
1340         mutex_unlock(&q->vb_lock);
1341         return ret;
1342 }
1343
1344 /* Sensoray 2255 is a multiple channel capture device.
1345    It does not have a "crossbar" of inputs.
1346    We use one V4L device per channel. The user must
1347    be aware that certain combinations are not allowed.
1348    For instance, you cannot do full FPS on more than 2 channels(2 videodevs)
1349    at once in color(you can do full fps on 4 channels with greyscale.
1350 */
1351 static int vidioc_enum_input(struct file *file, void *priv,
1352                              struct v4l2_input *inp)
1353 {
1354         if (inp->index != 0)
1355                 return -EINVAL;
1356
1357         inp->type = V4L2_INPUT_TYPE_CAMERA;
1358         inp->std = S2255_NORMS;
1359         strlcpy(inp->name, "Camera", sizeof(inp->name));
1360         return 0;
1361 }
1362
1363 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1364 {
1365         *i = 0;
1366         return 0;
1367 }
1368 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1369 {
1370         if (i > 0)
1371                 return -EINVAL;
1372         return 0;
1373 }
1374
1375 /* --- controls ---------------------------------------------- */
1376 static int vidioc_queryctrl(struct file *file, void *priv,
1377                             struct v4l2_queryctrl *qc)
1378 {
1379         int i;
1380
1381         for (i = 0; i < ARRAY_SIZE(s2255_qctrl); i++)
1382                 if (qc->id && qc->id == s2255_qctrl[i].id) {
1383                         memcpy(qc, &(s2255_qctrl[i]), sizeof(*qc));
1384                         return 0;
1385                 }
1386
1387         dprintk(4, "query_ctrl -EINVAL %d\n", qc->id);
1388         return -EINVAL;
1389 }
1390
1391 static int vidioc_g_ctrl(struct file *file, void *priv,
1392                          struct v4l2_control *ctrl)
1393 {
1394         int i;
1395
1396         for (i = 0; i < ARRAY_SIZE(s2255_qctrl); i++)
1397                 if (ctrl->id == s2255_qctrl[i].id) {
1398                         ctrl->value = qctl_regs[i];
1399                         return 0;
1400                 }
1401         dprintk(4, "g_ctrl -EINVAL\n");
1402
1403         return -EINVAL;
1404 }
1405
1406 static int vidioc_s_ctrl(struct file *file, void *priv,
1407                          struct v4l2_control *ctrl)
1408 {
1409         int i;
1410         struct s2255_fh *fh = priv;
1411         struct s2255_dev *dev = fh->dev;
1412         struct s2255_mode *mode;
1413         mode = &fh->mode;
1414         dprintk(4, "vidioc_s_ctrl\n");
1415         for (i = 0; i < ARRAY_SIZE(s2255_qctrl); i++) {
1416                 if (ctrl->id == s2255_qctrl[i].id) {
1417                         if (ctrl->value < s2255_qctrl[i].minimum ||
1418                             ctrl->value > s2255_qctrl[i].maximum)
1419                                 return -ERANGE;
1420
1421                         qctl_regs[i] = ctrl->value;
1422                         /* update the mode to the corresponding value */
1423                         switch (ctrl->id) {
1424                         case V4L2_CID_BRIGHTNESS:
1425                                 mode->bright = ctrl->value;
1426                                 break;
1427                         case V4L2_CID_CONTRAST:
1428                                 mode->contrast = ctrl->value;
1429                                 break;
1430                         case V4L2_CID_HUE:
1431                                 mode->hue = ctrl->value;
1432                                 break;
1433                         case V4L2_CID_SATURATION:
1434                                 mode->saturation = ctrl->value;
1435                                 break;
1436                         }
1437                         mode->restart = 0;
1438                         /* set mode here.  Note: stream does not need restarted.
1439                            some V4L programs restart stream unnecessarily
1440                            after a s_crtl.
1441                          */
1442                         s2255_set_mode(dev, fh->channel, mode);
1443                         return 0;
1444                 }
1445         }
1446         return -EINVAL;
1447 }
1448
1449 static int s2255_open(struct inode *inode, struct file *file)
1450 {
1451         int minor = iminor(inode);
1452         struct s2255_dev *h, *dev = NULL;
1453         struct s2255_fh *fh;
1454         struct list_head *list;
1455         enum v4l2_buf_type type = 0;
1456         int i = 0;
1457         int cur_channel = -1;
1458         dprintk(1, "s2255: open called (minor=%d)\n", minor);
1459
1460         lock_kernel();
1461         list_for_each(list, &s2255_devlist) {
1462                 h = list_entry(list, struct s2255_dev, s2255_devlist);
1463                 for (i = 0; i < MAX_CHANNELS; i++) {
1464                         if (h->vdev[i]->minor == minor) {
1465                                 cur_channel = i;
1466                                 dev = h;
1467                                 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1468                         }
1469                 }
1470         }
1471
1472         if ((NULL == dev) || (cur_channel == -1)) {
1473                 unlock_kernel();
1474                 dprintk(1, "s2255: openv4l no dev\n");
1475                 return -ENODEV;
1476         }
1477
1478         mutex_lock(&dev->open_lock);
1479
1480         dev->users[cur_channel]++;
1481         dprintk(4, "s2255: open_handles %d\n", dev->users[cur_channel]);
1482
1483         if (atomic_read(&dev->fw_data->fw_state) == S2255_FW_FAILED) {
1484                 err("2255 firmware load failed. retrying.\n");
1485                 s2255_fwload_start(dev);
1486                 wait_event_timeout(dev->fw_data->wait_fw,
1487                                    (atomic_read(&dev->fw_data->fw_state)
1488                                     != S2255_FW_NOTLOADED),
1489                                    msecs_to_jiffies(S2255_LOAD_TIMEOUT));
1490                 if (atomic_read(&dev->fw_data->fw_state)
1491                     != S2255_FW_SUCCESS) {
1492                         printk(KERN_INFO "2255 FW load failed.\n");
1493                         dev->users[cur_channel]--;
1494                         mutex_unlock(&dev->open_lock);
1495                         unlock_kernel();
1496                         return -EFAULT;
1497                 }
1498         } else if (atomic_read(&dev->fw_data->fw_state) == S2255_FW_NOTLOADED) {
1499                 /* give S2255_LOAD_TIMEOUT time for firmware to load in case
1500                    driver loaded and then device immediately opened */
1501                 printk(KERN_INFO "%s waiting for firmware load\n", __func__);
1502                 wait_event_timeout(dev->fw_data->wait_fw,
1503                                    (atomic_read(&dev->fw_data->fw_state)
1504                                    != S2255_FW_NOTLOADED),
1505                                    msecs_to_jiffies(S2255_LOAD_TIMEOUT));
1506                 if (atomic_read(&dev->fw_data->fw_state)
1507                     != S2255_FW_SUCCESS) {
1508                         printk(KERN_INFO "2255 firmware not loaded"
1509                                "try again\n");
1510                         dev->users[cur_channel]--;
1511                         mutex_unlock(&dev->open_lock);
1512                         unlock_kernel();
1513                         return -EBUSY;
1514                 }
1515         }
1516
1517         /* allocate + initialize per filehandle data */
1518         fh = kzalloc(sizeof(*fh), GFP_KERNEL);
1519         if (NULL == fh) {
1520                 dev->users[cur_channel]--;
1521                 mutex_unlock(&dev->open_lock);
1522                 unlock_kernel();
1523                 return -ENOMEM;
1524         }
1525
1526         file->private_data = fh;
1527         fh->dev = dev;
1528         fh->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1529         fh->mode = dev->mode[cur_channel];
1530         fh->fmt = dev->cur_fmt[cur_channel];
1531         /* default 4CIF NTSC */
1532         fh->width = LINE_SZ_4CIFS_NTSC;
1533         fh->height = NUM_LINES_4CIFS_NTSC * 2;
1534         fh->channel = cur_channel;
1535
1536         /* Put all controls at a sane state */
1537         for (i = 0; i < ARRAY_SIZE(s2255_qctrl); i++)
1538                 qctl_regs[i] = s2255_qctrl[i].default_value;
1539
1540         dprintk(1, "s2255drv: open minor=%d type=%s users=%d\n",
1541                 minor, v4l2_type_names[type], dev->users[cur_channel]);
1542         dprintk(2, "s2255drv: open: fh=0x%08lx, dev=0x%08lx, vidq=0x%08lx\n",
1543                 (unsigned long)fh, (unsigned long)dev,
1544                 (unsigned long)&dev->vidq[cur_channel]);
1545         dprintk(4, "s2255drv: open: list_empty active=%d\n",
1546                 list_empty(&dev->vidq[cur_channel].active));
1547
1548         videobuf_queue_vmalloc_init(&fh->vb_vidq, &s2255_video_qops,
1549                                     NULL, &dev->slock,
1550                                     fh->type,
1551                                     V4L2_FIELD_INTERLACED,
1552                                     sizeof(struct s2255_buffer), fh);
1553
1554         kref_get(&dev->kref);
1555         mutex_unlock(&dev->open_lock);
1556         unlock_kernel();
1557         return 0;
1558 }
1559
1560
1561 static unsigned int s2255_poll(struct file *file,
1562                                struct poll_table_struct *wait)
1563 {
1564         struct s2255_fh *fh = file->private_data;
1565         int rc;
1566         dprintk(100, "%s\n", __func__);
1567
1568         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1569                 return POLLERR;
1570
1571         rc = videobuf_poll_stream(file, &fh->vb_vidq, wait);
1572         return rc;
1573 }
1574
1575 static void s2255_destroy(struct kref *kref)
1576 {
1577         struct s2255_dev *dev = to_s2255_dev(kref);
1578         if (!dev) {
1579                 printk(KERN_ERR "s2255drv: kref problem\n");
1580                 return;
1581         }
1582
1583         /*
1584          * Wake up any firmware load waiting (only done in .open,
1585          * which holds the open_lock mutex)
1586          */
1587         atomic_set(&dev->fw_data->fw_state, S2255_FW_DISCONNECTING);
1588         wake_up(&dev->fw_data->wait_fw);
1589
1590         /* prevent s2255_disconnect from racing s2255_open */
1591         mutex_lock(&dev->open_lock);
1592         s2255_exit_v4l(dev);
1593         /*
1594          * device unregistered so no longer possible to open. open_mutex
1595          *  can be unlocked and timers deleted afterwards.
1596          */
1597         mutex_unlock(&dev->open_lock);
1598
1599         /* board shutdown stops the read pipe if it is running */
1600         s2255_board_shutdown(dev);
1601
1602         /* make sure firmware still not trying to load */
1603         del_timer(&dev->timer);  /* only started in .probe and .open */
1604
1605         if (dev->fw_data->fw_urb) {
1606                 dprintk(2, "kill fw_urb\n");
1607                 usb_kill_urb(dev->fw_data->fw_urb);
1608                 usb_free_urb(dev->fw_data->fw_urb);
1609                 dev->fw_data->fw_urb = NULL;
1610         }
1611
1612         /*
1613          * delete the dsp_wait timer, which sets the firmware
1614          * state on completion.  This is done before fw_data
1615          * is freed below.
1616          */
1617
1618         del_timer(&dev->fw_data->dsp_wait); /* only started in .open */
1619
1620         if (dev->fw_data->fw)
1621                 release_firmware(dev->fw_data->fw);
1622         kfree(dev->fw_data->pfw_data);
1623         kfree(dev->fw_data);
1624
1625         usb_put_dev(dev->udev);
1626         dprintk(1, "%s", __func__);
1627         kfree(dev);
1628 }
1629
1630 static int s2255_close(struct inode *inode, struct file *file)
1631 {
1632         struct s2255_fh *fh = file->private_data;
1633         struct s2255_dev *dev = fh->dev;
1634         int minor = iminor(inode);
1635         if (!dev)
1636                 return -ENODEV;
1637
1638         mutex_lock(&dev->open_lock);
1639
1640         /* turn off stream */
1641         if (res_check(fh)) {
1642                 if (dev->b_acquire[fh->channel])
1643                         s2255_stop_acquire(dev, fh->channel);
1644                 videobuf_streamoff(&fh->vb_vidq);
1645                 res_free(dev, fh);
1646         }
1647
1648         videobuf_mmap_free(&fh->vb_vidq);
1649         dev->users[fh->channel]--;
1650
1651         mutex_unlock(&dev->open_lock);
1652
1653         kref_put(&dev->kref, s2255_destroy);
1654         dprintk(1, "s2255: close called (minor=%d, users=%d)\n",
1655                 minor, dev->users[fh->channel]);
1656         kfree(fh);
1657         return 0;
1658 }
1659
1660 static int s2255_mmap_v4l(struct file *file, struct vm_area_struct *vma)
1661 {
1662         struct s2255_fh *fh = file->private_data;
1663         int ret;
1664
1665         if (!fh)
1666                 return -ENODEV;
1667         dprintk(4, "mmap called, vma=0x%08lx\n", (unsigned long)vma);
1668
1669         ret = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1670
1671         dprintk(4, "vma start=0x%08lx, size=%ld, ret=%d\n",
1672                 (unsigned long)vma->vm_start,
1673                 (unsigned long)vma->vm_end - (unsigned long)vma->vm_start, ret);
1674
1675         return ret;
1676 }
1677
1678 static const struct file_operations s2255_fops_v4l = {
1679         .owner = THIS_MODULE,
1680         .open = s2255_open,
1681         .release = s2255_close,
1682         .poll = s2255_poll,
1683         .ioctl = video_ioctl2,  /* V4L2 ioctl handler */
1684         .compat_ioctl = v4l_compat_ioctl32,
1685         .mmap = s2255_mmap_v4l,
1686         .llseek = no_llseek,
1687 };
1688
1689 static const struct v4l2_ioctl_ops s2255_ioctl_ops = {
1690         .vidioc_querycap = vidioc_querycap,
1691         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1692         .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
1693         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1694         .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
1695         .vidioc_reqbufs = vidioc_reqbufs,
1696         .vidioc_querybuf = vidioc_querybuf,
1697         .vidioc_qbuf = vidioc_qbuf,
1698         .vidioc_dqbuf = vidioc_dqbuf,
1699         .vidioc_s_std = vidioc_s_std,
1700         .vidioc_enum_input = vidioc_enum_input,
1701         .vidioc_g_input = vidioc_g_input,
1702         .vidioc_s_input = vidioc_s_input,
1703         .vidioc_queryctrl = vidioc_queryctrl,
1704         .vidioc_g_ctrl = vidioc_g_ctrl,
1705         .vidioc_s_ctrl = vidioc_s_ctrl,
1706         .vidioc_streamon = vidioc_streamon,
1707         .vidioc_streamoff = vidioc_streamoff,
1708 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1709         .vidiocgmbuf = vidioc_cgmbuf,
1710 #endif
1711 };
1712
1713 static struct video_device template = {
1714         .name = "s2255v",
1715         .fops = &s2255_fops_v4l,
1716         .ioctl_ops = &s2255_ioctl_ops,
1717         .minor = -1,
1718         .release = video_device_release,
1719         .tvnorms = S2255_NORMS,
1720         .current_norm = V4L2_STD_NTSC_M,
1721 };
1722
1723 static int s2255_probe_v4l(struct s2255_dev *dev)
1724 {
1725         int ret;
1726         int i;
1727         int cur_nr = video_nr;
1728
1729         /* initialize all video 4 linux */
1730         list_add_tail(&dev->s2255_devlist, &s2255_devlist);
1731         /* register 4 video devices */
1732         for (i = 0; i < MAX_CHANNELS; i++) {
1733                 INIT_LIST_HEAD(&dev->vidq[i].active);
1734                 dev->vidq[i].dev = dev;
1735                 dev->vidq[i].channel = i;
1736                 dev->vidq[i].kthread = NULL;
1737                 /* register 4 video devices */
1738                 dev->vdev[i] = video_device_alloc();
1739                 memcpy(dev->vdev[i], &template, sizeof(struct video_device));
1740                 dev->vdev[i]->parent = &dev->interface->dev;
1741                 if (video_nr == -1)
1742                         ret = video_register_device(dev->vdev[i],
1743                                                     VFL_TYPE_GRABBER,
1744                                                     video_nr);
1745                 else
1746                         ret = video_register_device(dev->vdev[i],
1747                                                     VFL_TYPE_GRABBER,
1748                                                     cur_nr + i);
1749                 dev->vdev[i]->priv = dev;
1750
1751                 if (ret != 0) {
1752                         dev_err(&dev->udev->dev,
1753                                 "failed to register video device!\n");
1754                         return ret;
1755                 }
1756         }
1757         printk(KERN_INFO "Sensoray 2255 V4L driver\n");
1758         return ret;
1759 }
1760
1761 static void s2255_exit_v4l(struct s2255_dev *dev)
1762 {
1763         struct list_head *list;
1764         int i;
1765         /* unregister the video devices */
1766         while (!list_empty(&s2255_devlist)) {
1767                 list = s2255_devlist.next;
1768                 list_del(list);
1769         }
1770         for (i = 0; i < MAX_CHANNELS; i++) {
1771                 if (-1 != dev->vdev[i]->minor)
1772                         video_unregister_device(dev->vdev[i]);
1773                 else
1774                         video_device_release(dev->vdev[i]);
1775         }
1776 }
1777
1778 /* this function moves the usb stream read pipe data
1779  * into the system buffers.
1780  * returns 0 on success, EAGAIN if more data to process( call this
1781  * function again).
1782  *
1783  * Received frame structure:
1784  * bytes 0-3:  marker : 0x2255DA4AL (FRAME_MARKER)
1785  * bytes 4-7:  channel: 0-3
1786  * bytes 8-11: payload size:  size of the frame
1787  * bytes 12-payloadsize+12:  frame data
1788  */
1789 static int save_frame(struct s2255_dev *dev, struct s2255_pipeinfo *pipe_info)
1790 {
1791         static int dbgsync; /* = 0; */
1792         char *pdest;
1793         u32 offset = 0;
1794         int bsync = 0;
1795         int btrunc = 0;
1796         char *psrc;
1797         unsigned long copy_size;
1798         unsigned long size;
1799         s32 idx = -1;
1800         struct s2255_framei *frm;
1801         unsigned char *pdata;
1802         unsigned long cur_size;
1803         int bsearch = 0;
1804         struct s2255_bufferi *buf;
1805         dprintk(100, "buffer to user\n");
1806
1807         idx = dev->cur_frame[dev->cc];
1808         buf = &dev->buffer[dev->cc];
1809         frm = &buf->frame[idx];
1810
1811         if (frm->ulState == 0) {
1812                 frm->ulState = 1;
1813                 frm->cur_size = 0;
1814                 bsearch = 1;
1815         } else if (frm->ulState == 2) {
1816                 /* system frame was not freed */
1817                 dprintk(2, "sys frame not free.  overrun ringbuf\n");
1818                 bsearch = 1;
1819                 frm->ulState = 1;
1820                 frm->cur_size = 0;
1821         }
1822
1823         if (bsearch) {
1824                 if (*(s32 *) pipe_info->transfer_buffer != FRAME_MARKER) {
1825                         u32 jj;
1826                         if (dbgsync == 0) {
1827                                 dprintk(3, "not synched, discarding all packets"
1828                                         "until marker\n");
1829
1830                                 dbgsync++;
1831                         }
1832                         pdata = (unsigned char *)pipe_info->transfer_buffer;
1833                         for (jj = 0; jj < (pipe_info->cur_transfer_size - 12);
1834                              jj++) {
1835                                 if (*(s32 *) pdata == FRAME_MARKER) {
1836                                         int cc;
1837                                         dprintk(3,
1838                                                 "found frame marker at offset:"
1839                                                 " %d [%x %x]\n", jj, pdata[0],
1840                                                 pdata[1]);
1841                                         offset = jj;
1842                                         bsync = 1;
1843                                         cc = *(u32 *) (pdata + sizeof(u32));
1844                                         if (cc >= MAX_CHANNELS) {
1845                                                 printk(KERN_ERR
1846                                                        "bad channel\n");
1847                                                 return -EINVAL;
1848                                         }
1849                                         /* reverse it */
1850                                         dev->cc = G_chnmap[cc];
1851                                         break;
1852                                 }
1853                                 pdata++;
1854                         }
1855                         if (bsync == 0)
1856                                 return -EINVAL;
1857                 } else {
1858                         u32 *pword;
1859                         u32 payload;
1860                         int cc;
1861                         dbgsync = 0;
1862                         bsync = 1;
1863                         pword = (u32 *) pipe_info->transfer_buffer;
1864                         cc = pword[1];
1865
1866                         if (cc >= MAX_CHANNELS) {
1867                                 printk("invalid channel found. "
1868                                         "throwing out data!\n");
1869                                 return -EINVAL;
1870                         }
1871                         dev->cc = G_chnmap[cc];
1872                         payload = pword[2];
1873                         if (payload != dev->req_image_size[dev->cc]) {
1874                                 dprintk(1, "[%d][%d]unexpected payload: %d"
1875                                         "required: %lu \n", cc, dev->cc,
1876                                         payload, dev->req_image_size[dev->cc]);
1877                                 dev->bad_payload[dev->cc]++;
1878                                 /* discard the bad frame */
1879                                 return -EINVAL;
1880                         }
1881
1882                 }
1883         }
1884         /* search done.  now find out if should be acquiring
1885            on this channel */
1886         if (!dev->b_acquire[dev->cc]) {
1887                 frm->ulState = 0;
1888                 return -EINVAL;
1889         }
1890
1891         idx = dev->cur_frame[dev->cc];
1892         frm = &dev->buffer[dev->cc].frame[idx];
1893
1894         if (frm->ulState == 0) {
1895                 frm->ulState = 1;
1896                 frm->cur_size = 0;
1897         } else if (frm->ulState == 2) {
1898                 /* system frame ring buffer overrun */
1899                 dprintk(2, "sys frame overrun.  overwriting frame %d %d\n",
1900                         dev->cc, idx);
1901                 frm->ulState = 1;
1902                 frm->cur_size = 0;
1903         }
1904
1905         if (bsync) {
1906                 /* skip the marker 512 bytes (and offset if out of sync) */
1907                 psrc = (u8 *)pipe_info->transfer_buffer + offset + PREFIX_SIZE;
1908         } else {
1909                 psrc = (u8 *)pipe_info->transfer_buffer;
1910         }
1911
1912         if (frm->lpvbits == NULL) {
1913                 dprintk(1, "s2255 frame buffer == NULL.%p %p %d %d",
1914                         frm, dev, dev->cc, idx);
1915                 return -ENOMEM;
1916         }
1917
1918         pdest = frm->lpvbits + frm->cur_size;
1919
1920         if (bsync) {
1921                 copy_size =
1922                     (pipe_info->cur_transfer_size - offset) - PREFIX_SIZE;
1923                 if (copy_size > pipe_info->cur_transfer_size) {
1924                         printk("invalid copy size, overflow!\n");
1925                         return -ENOMEM;
1926                 }
1927         } else {
1928                 copy_size = pipe_info->cur_transfer_size;
1929         }
1930
1931         cur_size = frm->cur_size;
1932         size = dev->req_image_size[dev->cc];
1933
1934         if ((copy_size + cur_size) > size) {
1935                 copy_size = size - cur_size;
1936                 btrunc = 1;
1937         }
1938
1939         memcpy(pdest, psrc, copy_size);
1940         cur_size += copy_size;
1941         frm->cur_size += copy_size;
1942         dprintk(50, "cur_size size %lu size %lu \n", cur_size, size);
1943
1944         if (cur_size >= (size - PREFIX_SIZE)) {
1945                 u32 cc = dev->cc;
1946                 frm->ulState = 2;
1947                 dprintk(2, "****************[%d]Buffer[%d]full*************\n",
1948                         cc, idx);
1949                 dev->last_frame[cc] = dev->cur_frame[cc];
1950                 dev->cur_frame[cc]++;
1951                 /* end of system frame ring buffer, start at zero */
1952                 if ((dev->cur_frame[cc] == SYS_FRAMES) ||
1953                     (dev->cur_frame[cc] == dev->buffer[cc].dwFrames))
1954                         dev->cur_frame[cc] = 0;
1955
1956                 /* signal the semaphore for this channel */
1957                 if (dev->b_acquire[cc])
1958                         s2255_got_frame(dev, cc);
1959                 dev->frame_count[cc]++;
1960         }
1961         /* frame was truncated */
1962         if (btrunc) {
1963                 /* return more data to process */
1964                 return EAGAIN;
1965         }
1966         /* done successfully */
1967         return 0;
1968 }
1969
1970 static void s2255_read_video_callback(struct s2255_dev *dev,
1971                                       struct s2255_pipeinfo *pipe_info)
1972 {
1973         int res;
1974         dprintk(50, "callback read video \n");
1975
1976         if (dev->cc >= MAX_CHANNELS) {
1977                 dev->cc = 0;
1978                 dev_err(&dev->udev->dev, "invalid channel\n");
1979                 return;
1980         }
1981         /* otherwise copy to the system buffers */
1982         res = save_frame(dev, pipe_info);
1983         if (res == EAGAIN)
1984                 save_frame(dev, pipe_info);
1985
1986         dprintk(50, "callback read video done\n");
1987         return;
1988 }
1989
1990 static long s2255_vendor_req(struct s2255_dev *dev, unsigned char Request,
1991                              u16 Index, u16 Value, void *TransferBuffer,
1992                              s32 TransferBufferLength, int bOut)
1993 {
1994         int r;
1995         if (!bOut) {
1996                 r = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
1997                                     Request,
1998                                     USB_TYPE_VENDOR | USB_RECIP_DEVICE |
1999                                     USB_DIR_IN,
2000                                     Value, Index, TransferBuffer,
2001                                     TransferBufferLength, HZ * 5);
2002         } else {
2003                 r = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
2004                                     Request, USB_TYPE_VENDOR | USB_RECIP_DEVICE,
2005                                     Value, Index, TransferBuffer,
2006                                     TransferBufferLength, HZ * 5);
2007         }
2008         return r;
2009 }
2010
2011 /*
2012  * retrieve FX2 firmware version. future use.
2013  * @param dev pointer to device extension
2014  * @return -1 for fail, else returns firmware version as an int(16 bits)
2015  */
2016 static int s2255_get_fx2fw(struct s2255_dev *dev)
2017 {
2018         int fw;
2019         int ret;
2020         unsigned char transBuffer[64];
2021         ret = s2255_vendor_req(dev, S2255_VR_FW, 0, 0, transBuffer, 2,
2022                                S2255_VR_IN);
2023         if (ret < 0)
2024                 dprintk(2, "get fw error: %x\n", ret);
2025         fw = transBuffer[0] + (transBuffer[1] << 8);
2026         dprintk(2, "Get FW %x %x\n", transBuffer[0], transBuffer[1]);
2027         return fw;
2028 }
2029
2030 /*
2031  * Create the system ring buffer to copy frames into from the
2032  * usb read pipe.
2033  */
2034 static int s2255_create_sys_buffers(struct s2255_dev *dev, unsigned long chn)
2035 {
2036         unsigned long i;
2037         unsigned long reqsize;
2038         dprintk(1, "create sys buffers\n");
2039         if (chn >= MAX_CHANNELS)
2040                 return -1;
2041
2042         dev->buffer[chn].dwFrames = SYS_FRAMES;
2043
2044         /* always allocate maximum size(PAL) for system buffers */
2045         reqsize = SYS_FRAMES_MAXSIZE;
2046
2047         if (reqsize > SYS_FRAMES_MAXSIZE)
2048                 reqsize = SYS_FRAMES_MAXSIZE;
2049
2050         for (i = 0; i < SYS_FRAMES; i++) {
2051                 /* allocate the frames */
2052                 dev->buffer[chn].frame[i].lpvbits = vmalloc(reqsize);
2053
2054                 dprintk(1, "valloc %p chan %lu, idx %lu, pdata %p\n",
2055                         &dev->buffer[chn].frame[i], chn, i,
2056                         dev->buffer[chn].frame[i].lpvbits);
2057                 dev->buffer[chn].frame[i].size = reqsize;
2058                 if (dev->buffer[chn].frame[i].lpvbits == NULL) {
2059                         printk(KERN_INFO "out of memory.  using less frames\n");
2060                         dev->buffer[chn].dwFrames = i;
2061                         break;
2062                 }
2063         }
2064
2065         /* make sure internal states are set */
2066         for (i = 0; i < SYS_FRAMES; i++) {
2067                 dev->buffer[chn].frame[i].ulState = 0;
2068                 dev->buffer[chn].frame[i].cur_size = 0;
2069         }
2070
2071         dev->cur_frame[chn] = 0;
2072         dev->last_frame[chn] = -1;
2073         return 0;
2074 }
2075
2076 static int s2255_release_sys_buffers(struct s2255_dev *dev,
2077                                      unsigned long channel)
2078 {
2079         unsigned long i;
2080         dprintk(1, "release sys buffers\n");
2081         for (i = 0; i < SYS_FRAMES; i++) {
2082                 if (dev->buffer[channel].frame[i].lpvbits) {
2083                         dprintk(1, "vfree %p\n",
2084                                 dev->buffer[channel].frame[i].lpvbits);
2085                         vfree(dev->buffer[channel].frame[i].lpvbits);
2086                 }
2087                 dev->buffer[channel].frame[i].lpvbits = NULL;
2088         }
2089         return 0;
2090 }
2091
2092 static int s2255_board_init(struct s2255_dev *dev)
2093 {
2094         int j;
2095         struct s2255_mode mode_def = DEF_MODEI_NTSC_CONT;
2096         int fw_ver;
2097         dprintk(4, "board init: %p", dev);
2098
2099         for (j = 0; j < MAX_PIPE_BUFFERS; j++) {
2100                 struct s2255_pipeinfo *pipe = &dev->pipes[j];
2101
2102                 memset(pipe, 0, sizeof(*pipe));
2103                 pipe->dev = dev;
2104                 pipe->cur_transfer_size = DEFAULT_PIPE_USBBLOCK;
2105                 pipe->max_transfer_size = MAX_PIPE_USBBLOCK;
2106
2107                 if (pipe->cur_transfer_size > pipe->max_transfer_size)
2108                         pipe->cur_transfer_size = pipe->max_transfer_size;
2109                 pipe->transfer_buffer = kzalloc(pipe->max_transfer_size,
2110                                                 GFP_KERNEL);
2111                 if (pipe->transfer_buffer == NULL) {
2112                         dprintk(1, "out of memory!\n");
2113                         return -ENOMEM;
2114                 }
2115
2116         }
2117
2118         /* query the firmware */
2119         fw_ver = s2255_get_fx2fw(dev);
2120
2121         printk(KERN_INFO "2255 usb firmware version %d \n", fw_ver);
2122         if (fw_ver < CUR_USB_FWVER)
2123                 err("usb firmware not up to date %d\n", fw_ver);
2124
2125         for (j = 0; j < MAX_CHANNELS; j++) {
2126                 dev->b_acquire[j] = 0;
2127                 dev->mode[j] = mode_def;
2128                 dev->cur_fmt[j] = &formats[0];
2129                 dev->mode[j].restart = 1;
2130                 dev->req_image_size[j] = get_transfer_size(&mode_def);
2131                 dev->frame_count[j] = 0;
2132                 /* create the system buffers */
2133                 s2255_create_sys_buffers(dev, j);
2134         }
2135         /* start read pipe */
2136         s2255_start_readpipe(dev);
2137
2138         dprintk(1, "S2255: board initialized\n");
2139         return 0;
2140 }
2141
2142 static int s2255_board_shutdown(struct s2255_dev *dev)
2143 {
2144         u32 i;
2145
2146         dprintk(1, "S2255: board shutdown: %p", dev);
2147
2148         for (i = 0; i < MAX_CHANNELS; i++) {
2149                 if (dev->b_acquire[i])
2150                         s2255_stop_acquire(dev, i);
2151         }
2152
2153         s2255_stop_readpipe(dev);
2154
2155         for (i = 0; i < MAX_CHANNELS; i++)
2156                 s2255_release_sys_buffers(dev, i);
2157
2158         /* release transfer buffers */
2159         for (i = 0; i < MAX_PIPE_BUFFERS; i++) {
2160                 struct s2255_pipeinfo *pipe = &dev->pipes[i];
2161                 kfree(pipe->transfer_buffer);
2162         }
2163         return 0;
2164 }
2165
2166 static void read_pipe_completion(struct urb *purb)
2167 {
2168         struct s2255_pipeinfo *pipe_info;
2169         struct s2255_dev *dev;
2170         int status;
2171         int pipe;
2172
2173         pipe_info = purb->context;
2174         dprintk(100, "read pipe completion %p, status %d\n", purb,
2175                 purb->status);
2176         if (pipe_info == NULL) {
2177                 err("no context !");
2178                 return;
2179         }
2180
2181         dev = pipe_info->dev;
2182         if (dev == NULL) {
2183                 err("no context !");
2184                 return;
2185         }
2186         status = purb->status;
2187         if (status != 0) {
2188                 dprintk(2, "read_pipe_completion: err\n");
2189                 return;
2190         }
2191
2192         if (pipe_info->state == 0) {
2193                 dprintk(2, "exiting USB pipe");
2194                 return;
2195         }
2196
2197         s2255_read_video_callback(dev, pipe_info);
2198
2199         pipe_info->err_count = 0;
2200         pipe = usb_rcvbulkpipe(dev->udev, dev->read_endpoint);
2201         /* reuse urb */
2202         usb_fill_bulk_urb(pipe_info->stream_urb, dev->udev,
2203                           pipe,
2204                           pipe_info->transfer_buffer,
2205                           pipe_info->cur_transfer_size,
2206                           read_pipe_completion, pipe_info);
2207
2208         if (pipe_info->state != 0) {
2209                 if (usb_submit_urb(pipe_info->stream_urb, GFP_KERNEL)) {
2210                         dev_err(&dev->udev->dev, "error submitting urb\n");
2211                         usb_free_urb(pipe_info->stream_urb);
2212                 }
2213         } else {
2214                 dprintk(2, "read pipe complete state 0\n");
2215         }
2216         return;
2217 }
2218
2219 static int s2255_start_readpipe(struct s2255_dev *dev)
2220 {
2221         int pipe;
2222         int retval;
2223         int i;
2224         struct s2255_pipeinfo *pipe_info = dev->pipes;
2225         pipe = usb_rcvbulkpipe(dev->udev, dev->read_endpoint);
2226         dprintk(2, "start pipe IN %d\n", dev->read_endpoint);
2227
2228         for (i = 0; i < MAX_PIPE_BUFFERS; i++) {
2229                 pipe_info->state = 1;
2230                 pipe_info->buf_index = (u32) i;
2231                 pipe_info->priority_set = 0;
2232                 pipe_info->stream_urb = usb_alloc_urb(0, GFP_KERNEL);
2233                 if (!pipe_info->stream_urb) {
2234                         dev_err(&dev->udev->dev,
2235                                 "ReadStream: Unable to alloc URB");
2236                         return -ENOMEM;
2237                 }
2238                 /* transfer buffer allocated in board_init */
2239                 usb_fill_bulk_urb(pipe_info->stream_urb, dev->udev,
2240                                   pipe,
2241                                   pipe_info->transfer_buffer,
2242                                   pipe_info->cur_transfer_size,
2243                                   read_pipe_completion, pipe_info);
2244
2245                 pipe_info->urb_size = sizeof(pipe_info->stream_urb);
2246                 dprintk(4, "submitting URB %p\n", pipe_info->stream_urb);
2247                 retval = usb_submit_urb(pipe_info->stream_urb, GFP_KERNEL);
2248                 if (retval) {
2249                         printk(KERN_ERR "s2255: start read pipe failed\n");
2250                         return retval;
2251                 }
2252         }
2253
2254         return 0;
2255 }
2256
2257 /* starts acquisition process */
2258 static int s2255_start_acquire(struct s2255_dev *dev, unsigned long chn)
2259 {
2260         unsigned char *buffer;
2261         int res;
2262         unsigned long chn_rev;
2263         int j;
2264         if (chn >= MAX_CHANNELS) {
2265                 dprintk(2, "start acquire failed, bad channel %lu\n", chn);
2266                 return -1;
2267         }
2268
2269         chn_rev = G_chnmap[chn];
2270         dprintk(1, "S2255: start acquire %lu \n", chn);
2271
2272         buffer = kzalloc(512, GFP_KERNEL);
2273         if (buffer == NULL) {
2274                 dev_err(&dev->udev->dev, "out of mem\n");
2275                 return -ENOMEM;
2276         }
2277
2278         dev->last_frame[chn] = -1;
2279         dev->bad_payload[chn] = 0;
2280         dev->cur_frame[chn] = 0;
2281         for (j = 0; j < SYS_FRAMES; j++) {
2282                 dev->buffer[chn].frame[j].ulState = 0;
2283                 dev->buffer[chn].frame[j].cur_size = 0;
2284         }
2285
2286         /* send the start command */
2287         *(u32 *) buffer = IN_DATA_TOKEN;
2288         *((u32 *) buffer + 1) = (u32) chn_rev;
2289         *((u32 *) buffer + 2) = (u32) CMD_START;
2290         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
2291         if (res != 0)
2292                 dev_err(&dev->udev->dev, "CMD_START error\n");
2293
2294         dprintk(2, "start acquire exit[%lu] %d \n", chn, res);
2295         kfree(buffer);
2296         return 0;
2297 }
2298
2299 static int s2255_stop_acquire(struct s2255_dev *dev, unsigned long chn)
2300 {
2301         unsigned char *buffer;
2302         int res;
2303         unsigned long chn_rev;
2304
2305         if (chn >= MAX_CHANNELS) {
2306                 dprintk(2, "stop acquire failed, bad channel %lu\n", chn);
2307                 return -1;
2308         }
2309         chn_rev = G_chnmap[chn];
2310
2311         buffer = kzalloc(512, GFP_KERNEL);
2312         if (buffer == NULL) {
2313                 dev_err(&dev->udev->dev, "out of mem\n");
2314                 return -ENOMEM;
2315         }
2316
2317         /* send the stop command */
2318         dprintk(4, "stop acquire %lu\n", chn);
2319         *(u32 *) buffer = IN_DATA_TOKEN;
2320         *((u32 *) buffer + 1) = (u32) chn_rev;
2321         *((u32 *) buffer + 2) = CMD_STOP;
2322         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
2323
2324         if (res != 0)
2325                 dev_err(&dev->udev->dev, "CMD_STOP error\n");
2326
2327         dprintk(4, "stop acquire: releasing states \n");
2328
2329         kfree(buffer);
2330         dev->b_acquire[chn] = 0;
2331
2332         return 0;
2333 }
2334
2335 static void s2255_stop_readpipe(struct s2255_dev *dev)
2336 {
2337         int j;
2338
2339         if (dev == NULL) {
2340                 err("s2255: invalid device");
2341                 return;
2342         }
2343         dprintk(4, "stop read pipe\n");
2344         for (j = 0; j < MAX_PIPE_BUFFERS; j++) {
2345                 struct s2255_pipeinfo *pipe_info = &dev->pipes[j];
2346                 if (pipe_info) {
2347                         if (pipe_info->state == 0)
2348                                 continue;
2349                         pipe_info->state = 0;
2350                         pipe_info->prev_state = 1;
2351
2352                 }
2353         }
2354
2355         for (j = 0; j < MAX_PIPE_BUFFERS; j++) {
2356                 struct s2255_pipeinfo *pipe_info = &dev->pipes[j];
2357                 if (pipe_info->stream_urb) {
2358                         /* cancel urb */
2359                         usb_kill_urb(pipe_info->stream_urb);
2360                         usb_free_urb(pipe_info->stream_urb);
2361                         pipe_info->stream_urb = NULL;
2362                 }
2363         }
2364         dprintk(2, "s2255 stop read pipe: %d\n", j);
2365         return;
2366 }
2367
2368 static void s2255_fwload_start(struct s2255_dev *dev)
2369 {
2370         dev->fw_data->fw_size = dev->fw_data->fw->size;
2371         atomic_set(&dev->fw_data->fw_state, S2255_FW_NOTLOADED);
2372         memcpy(dev->fw_data->pfw_data,
2373                dev->fw_data->fw->data, CHUNK_SIZE);
2374         dev->fw_data->fw_loaded = CHUNK_SIZE;
2375         usb_fill_bulk_urb(dev->fw_data->fw_urb, dev->udev,
2376                           usb_sndbulkpipe(dev->udev, 2),
2377                           dev->fw_data->pfw_data,
2378                           CHUNK_SIZE, s2255_fwchunk_complete,
2379                           dev->fw_data);
2380         mod_timer(&dev->timer, jiffies + HZ);
2381 }
2382
2383 /* standard usb probe function */
2384 static int s2255_probe(struct usb_interface *interface,
2385                        const struct usb_device_id *id)
2386 {
2387         struct s2255_dev *dev = NULL;
2388         struct usb_host_interface *iface_desc;
2389         struct usb_endpoint_descriptor *endpoint;
2390         int i;
2391         int retval = -ENOMEM;
2392
2393         dprintk(2, "s2255: probe\n");
2394
2395         /* allocate memory for our device state and initialize it to zero */
2396         dev = kzalloc(sizeof(struct s2255_dev), GFP_KERNEL);
2397         if (dev == NULL) {
2398                 err("s2255: out of memory");
2399                 goto error;
2400         }
2401
2402         dev->fw_data = kzalloc(sizeof(struct s2255_fw), GFP_KERNEL);
2403         if (!dev->fw_data)
2404                 goto error;
2405
2406         mutex_init(&dev->lock);
2407         mutex_init(&dev->open_lock);
2408
2409         /* grab usb_device and save it */
2410         dev->udev = usb_get_dev(interface_to_usbdev(interface));
2411         if (dev->udev == NULL) {
2412                 dev_err(&interface->dev, "null usb device\n");
2413                 retval = -ENODEV;
2414                 goto error;
2415         }
2416         kref_init(&dev->kref);
2417         dprintk(1, "dev: %p, kref: %p udev %p interface %p\n", dev, &dev->kref,
2418                 dev->udev, interface);
2419         dev->interface = interface;
2420         /* set up the endpoint information  */
2421         iface_desc = interface->cur_altsetting;
2422         dprintk(1, "num endpoints %d\n", iface_desc->desc.bNumEndpoints);
2423         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
2424                 endpoint = &iface_desc->endpoint[i].desc;
2425                 if (!dev->read_endpoint && usb_endpoint_is_bulk_in(endpoint)) {
2426                         /* we found the bulk in endpoint */
2427                         dev->read_endpoint = endpoint->bEndpointAddress;
2428                 }
2429         }
2430
2431         if (!dev->read_endpoint) {
2432                 dev_err(&interface->dev, "Could not find bulk-in endpoint");
2433                 goto error;
2434         }
2435
2436         /* set intfdata */
2437         usb_set_intfdata(interface, dev);
2438
2439         dprintk(100, "after intfdata %p\n", dev);
2440
2441         init_timer(&dev->timer);
2442         dev->timer.function = s2255_timer;
2443         dev->timer.data = (unsigned long)dev->fw_data;
2444
2445         init_waitqueue_head(&dev->fw_data->wait_fw);
2446
2447
2448         dev->fw_data->fw_urb = usb_alloc_urb(0, GFP_KERNEL);
2449
2450         if (!dev->fw_data->fw_urb) {
2451                 dev_err(&interface->dev, "out of memory!\n");
2452                 goto error;
2453         }
2454         dev->fw_data->pfw_data = kzalloc(CHUNK_SIZE, GFP_KERNEL);
2455         if (!dev->fw_data->pfw_data) {
2456                 dev_err(&interface->dev, "out of memory!\n");
2457                 goto error;
2458         }
2459         /* load the first chunk */
2460         if (request_firmware(&dev->fw_data->fw,
2461                              FIRMWARE_FILE_NAME, &dev->udev->dev)) {
2462                 printk(KERN_ERR "sensoray 2255 failed to get firmware\n");
2463                 goto error;
2464         }
2465
2466         /* loads v4l specific */
2467         s2255_probe_v4l(dev);
2468         /* load 2255 board specific */
2469         s2255_board_init(dev);
2470
2471         dprintk(4, "before probe done %p\n", dev);
2472         spin_lock_init(&dev->slock);
2473
2474         s2255_fwload_start(dev);
2475         dev_info(&interface->dev, "Sensoray 2255 detected\n");
2476         return 0;
2477 error:
2478         return retval;
2479 }
2480
2481 /* disconnect routine. when board is removed physically or with rmmod */
2482 static void s2255_disconnect(struct usb_interface *interface)
2483 {
2484         struct s2255_dev *dev = NULL;
2485         dprintk(1, "s2255: disconnect interface %p\n", interface);
2486         dev = usb_get_intfdata(interface);
2487         if (dev) {
2488                 kref_put(&dev->kref, s2255_destroy);
2489                 dprintk(1, "s2255drv: disconnect\n");
2490                 dev_info(&interface->dev, "s2255usb now disconnected\n");
2491         }
2492         usb_set_intfdata(interface, NULL);
2493 }
2494
2495 static struct usb_driver s2255_driver = {
2496         .name = "s2255",
2497         .probe = s2255_probe,
2498         .disconnect = s2255_disconnect,
2499         .id_table = s2255_table,
2500 };
2501
2502 static int __init usb_s2255_init(void)
2503 {
2504         int result;
2505
2506         /* register this driver with the USB subsystem */
2507         result = usb_register(&s2255_driver);
2508
2509         if (result)
2510                 err("usb_register failed. Error number %d", result);
2511
2512         dprintk(2, "s2255_init: done\n");
2513         return result;
2514 }
2515
2516 static void __exit usb_s2255_exit(void)
2517 {
2518         usb_deregister(&s2255_driver);
2519 }
2520
2521 module_init(usb_s2255_init);
2522 module_exit(usb_s2255_exit);
2523
2524 MODULE_DESCRIPTION("Sensoray 2255 Video for Linux driver");
2525 MODULE_AUTHOR("Dean Anderson (Sensoray Company Inc.)");
2526 MODULE_LICENSE("GPL");