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