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