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