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