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