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