• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-WNDR4500-V1.0.1.40_1.0.68/src/linux/linux-2.6/drivers/media/video/usbvideo/
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2, or (at your option)
5 * any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17#include <linux/kernel.h>
18#include <linux/sched.h>
19#include <linux/list.h>
20#include <linux/slab.h>
21#include <linux/module.h>
22#include <linux/mm.h>
23#include <linux/vmalloc.h>
24#include <linux/init.h>
25#include <linux/spinlock.h>
26
27#include <asm/io.h>
28
29#include "usbvideo.h"
30
31#if defined(MAP_NR)
32#define	virt_to_page(v)	MAP_NR(v)	/* Kernels 2.2.x */
33#endif
34
35static int video_nr = -1;
36module_param(video_nr, int, 0);
37
38/*
39 * Local prototypes.
40 */
41static void usbvideo_Disconnect(struct usb_interface *intf);
42static void usbvideo_CameraRelease(struct uvd *uvd);
43
44static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
45			      unsigned int cmd, unsigned long arg);
46static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma);
47static int usbvideo_v4l_open(struct inode *inode, struct file *file);
48static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
49			     size_t count, loff_t *ppos);
50static int usbvideo_v4l_close(struct inode *inode, struct file *file);
51
52static int usbvideo_StartDataPump(struct uvd *uvd);
53static void usbvideo_StopDataPump(struct uvd *uvd);
54static int usbvideo_GetFrame(struct uvd *uvd, int frameNum);
55static int usbvideo_NewFrame(struct uvd *uvd, int framenum);
56static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
57						struct usbvideo_frame *frame);
58
59/*******************************/
60/* Memory management functions */
61/*******************************/
62static void *usbvideo_rvmalloc(unsigned long size)
63{
64	void *mem;
65	unsigned long adr;
66
67	size = PAGE_ALIGN(size);
68	mem = vmalloc_32(size);
69	if (!mem)
70		return NULL;
71
72	memset(mem, 0, size); /* Clear the ram out, no junk to the user */
73	adr = (unsigned long) mem;
74	while (size > 0) {
75		SetPageReserved(vmalloc_to_page((void *)adr));
76		adr += PAGE_SIZE;
77		size -= PAGE_SIZE;
78	}
79
80	return mem;
81}
82
83static void usbvideo_rvfree(void *mem, unsigned long size)
84{
85	unsigned long adr;
86
87	if (!mem)
88		return;
89
90	adr = (unsigned long) mem;
91	while ((long) size > 0) {
92		ClearPageReserved(vmalloc_to_page((void *)adr));
93		adr += PAGE_SIZE;
94		size -= PAGE_SIZE;
95	}
96	vfree(mem);
97}
98
99static void RingQueue_Initialize(struct RingQueue *rq)
100{
101	assert(rq != NULL);
102	init_waitqueue_head(&rq->wqh);
103}
104
105static void RingQueue_Allocate(struct RingQueue *rq, int rqLen)
106{
107	/* Make sure the requested size is a power of 2 and
108	   round up if necessary. This allows index wrapping
109	   using masks rather than modulo */
110
111	int i = 1;
112	assert(rq != NULL);
113	assert(rqLen > 0);
114
115	while(rqLen >> i)
116		i++;
117	if(rqLen != 1 << (i-1))
118		rqLen = 1 << i;
119
120	rq->length = rqLen;
121	rq->ri = rq->wi = 0;
122	rq->queue = usbvideo_rvmalloc(rq->length);
123	assert(rq->queue != NULL);
124}
125
126static int RingQueue_IsAllocated(const struct RingQueue *rq)
127{
128	if (rq == NULL)
129		return 0;
130	return (rq->queue != NULL) && (rq->length > 0);
131}
132
133static void RingQueue_Free(struct RingQueue *rq)
134{
135	assert(rq != NULL);
136	if (RingQueue_IsAllocated(rq)) {
137		usbvideo_rvfree(rq->queue, rq->length);
138		rq->queue = NULL;
139		rq->length = 0;
140	}
141}
142
143int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len)
144{
145	int rql, toread;
146
147	assert(rq != NULL);
148	assert(dst != NULL);
149
150	rql = RingQueue_GetLength(rq);
151	if(!rql)
152		return 0;
153
154	/* Clip requested length to available data */
155	if(len > rql)
156		len = rql;
157
158	toread = len;
159	if(rq->ri > rq->wi) {
160		/* Read data from tail */
161		int read = (toread < (rq->length - rq->ri)) ? toread : rq->length - rq->ri;
162		memcpy(dst, rq->queue + rq->ri, read);
163		toread -= read;
164		dst += read;
165		rq->ri = (rq->ri + read) & (rq->length-1);
166	}
167	if(toread) {
168		/* Read data from head */
169		memcpy(dst, rq->queue + rq->ri, toread);
170		rq->ri = (rq->ri + toread) & (rq->length-1);
171	}
172	return len;
173}
174
175EXPORT_SYMBOL(RingQueue_Dequeue);
176
177int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n)
178{
179	int enqueued = 0;
180
181	assert(rq != NULL);
182	assert(cdata != NULL);
183	assert(rq->length > 0);
184	while (n > 0) {
185		int m, q_avail;
186
187		/* Calculate the largest chunk that fits the tail of the ring */
188		q_avail = rq->length - rq->wi;
189		if (q_avail <= 0) {
190			rq->wi = 0;
191			q_avail = rq->length;
192		}
193		m = n;
194		assert(q_avail > 0);
195		if (m > q_avail)
196			m = q_avail;
197
198		memcpy(rq->queue + rq->wi, cdata, m);
199		RING_QUEUE_ADVANCE_INDEX(rq, wi, m);
200		cdata += m;
201		enqueued += m;
202		n -= m;
203	}
204	return enqueued;
205}
206
207EXPORT_SYMBOL(RingQueue_Enqueue);
208
209static void RingQueue_InterruptibleSleepOn(struct RingQueue *rq)
210{
211	assert(rq != NULL);
212	interruptible_sleep_on(&rq->wqh);
213}
214
215void RingQueue_WakeUpInterruptible(struct RingQueue *rq)
216{
217	assert(rq != NULL);
218	if (waitqueue_active(&rq->wqh))
219		wake_up_interruptible(&rq->wqh);
220}
221
222EXPORT_SYMBOL(RingQueue_WakeUpInterruptible);
223
224void RingQueue_Flush(struct RingQueue *rq)
225{
226	assert(rq != NULL);
227	rq->ri = 0;
228	rq->wi = 0;
229}
230
231EXPORT_SYMBOL(RingQueue_Flush);
232
233
234/*
235 * usbvideo_VideosizeToString()
236 *
237 * This procedure converts given videosize value to readable string.
238 *
239 * History:
240 * 07-Aug-2000 Created.
241 * 19-Oct-2000 Reworked for usbvideo module.
242 */
243static void usbvideo_VideosizeToString(char *buf, int bufLen, videosize_t vs)
244{
245	char tmp[40];
246	int n;
247
248	n = 1 + sprintf(tmp, "%ldx%ld", VIDEOSIZE_X(vs), VIDEOSIZE_Y(vs));
249	assert(n < sizeof(tmp));
250	if ((buf == NULL) || (bufLen < n))
251		err("usbvideo_VideosizeToString: buffer is too small.");
252	else
253		memmove(buf, tmp, n);
254}
255
256/*
257 * usbvideo_OverlayChar()
258 *
259 * History:
260 * 01-Feb-2000 Created.
261 */
262static void usbvideo_OverlayChar(struct uvd *uvd, struct usbvideo_frame *frame,
263				 int x, int y, int ch)
264{
265	static const unsigned short digits[16] = {
266		0xF6DE, /* 0 */
267		0x2492, /* 1 */
268		0xE7CE, /* 2 */
269		0xE79E, /* 3 */
270		0xB792, /* 4 */
271		0xF39E, /* 5 */
272		0xF3DE, /* 6 */
273		0xF492, /* 7 */
274		0xF7DE, /* 8 */
275		0xF79E, /* 9 */
276		0x77DA, /* a */
277		0xD75C, /* b */
278		0xF24E, /* c */
279		0xD6DC, /* d */
280		0xF34E, /* e */
281		0xF348  /* f */
282	};
283	unsigned short digit;
284	int ix, iy;
285
286	if ((uvd == NULL) || (frame == NULL))
287		return;
288
289	if (ch >= '0' && ch <= '9')
290		ch -= '0';
291	else if (ch >= 'A' && ch <= 'F')
292		ch = 10 + (ch - 'A');
293	else if (ch >= 'a' && ch <= 'f')
294		ch = 10 + (ch - 'a');
295	else
296		return;
297	digit = digits[ch];
298
299	for (iy=0; iy < 5; iy++) {
300		for (ix=0; ix < 3; ix++) {
301			if (digit & 0x8000) {
302				if (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24)) {
303/* TODO */				RGB24_PUTPIXEL(frame, x+ix, y+iy, 0xFF, 0xFF, 0xFF);
304				}
305			}
306			digit = digit << 1;
307		}
308	}
309}
310
311/*
312 * usbvideo_OverlayString()
313 *
314 * History:
315 * 01-Feb-2000 Created.
316 */
317static void usbvideo_OverlayString(struct uvd *uvd, struct usbvideo_frame *frame,
318				   int x, int y, const char *str)
319{
320	while (*str) {
321		usbvideo_OverlayChar(uvd, frame, x, y, *str);
322		str++;
323		x += 4; /* 3 pixels character + 1 space */
324	}
325}
326
327/*
328 * usbvideo_OverlayStats()
329 *
330 * Overlays important debugging information.
331 *
332 * History:
333 * 01-Feb-2000 Created.
334 */
335static void usbvideo_OverlayStats(struct uvd *uvd, struct usbvideo_frame *frame)
336{
337	const int y_diff = 8;
338	char tmp[16];
339	int x = 10, y=10;
340	long i, j, barLength;
341	const int qi_x1 = 60, qi_y1 = 10;
342	const int qi_x2 = VIDEOSIZE_X(frame->request) - 10, qi_h = 10;
343
344	/* Call the user callback, see if we may proceed after that */
345	if (VALID_CALLBACK(uvd, overlayHook)) {
346		if (GET_CALLBACK(uvd, overlayHook)(uvd, frame) < 0)
347			return;
348	}
349
350	/*
351	 * We draw a (mostly) hollow rectangle with qi_xxx coordinates.
352	 * Left edge symbolizes the queue index 0; right edge symbolizes
353	 * the full capacity of the queue.
354	 */
355	barLength = qi_x2 - qi_x1 - 2;
356	if ((barLength > 10) && (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24))) {
357/* TODO */	long u_lo, u_hi, q_used;
358		long m_ri, m_wi, m_lo, m_hi;
359
360		/*
361		 * Determine fill zones (used areas of the queue):
362		 * 0 xxxxxxx u_lo ...... uvd->dp.ri xxxxxxxx u_hi ..... uvd->dp.length
363		 *
364		 * if u_lo < 0 then there is no first filler.
365		 */
366
367		q_used = RingQueue_GetLength(&uvd->dp);
368		if ((uvd->dp.ri + q_used) >= uvd->dp.length) {
369			u_hi = uvd->dp.length;
370			u_lo = (q_used + uvd->dp.ri) & (uvd->dp.length-1);
371		} else {
372			u_hi = (q_used + uvd->dp.ri);
373			u_lo = -1;
374		}
375
376		/* Convert byte indices into screen units */
377		m_ri = qi_x1 + ((barLength * uvd->dp.ri) / uvd->dp.length);
378		m_wi = qi_x1 + ((barLength * uvd->dp.wi) / uvd->dp.length);
379		m_lo = (u_lo > 0) ? (qi_x1 + ((barLength * u_lo) / uvd->dp.length)) : -1;
380		m_hi = qi_x1 + ((barLength * u_hi) / uvd->dp.length);
381
382		for (j=qi_y1; j < (qi_y1 + qi_h); j++) {
383			for (i=qi_x1; i < qi_x2; i++) {
384				/* Draw border lines */
385				if ((j == qi_y1) || (j == (qi_y1 + qi_h - 1)) ||
386				    (i == qi_x1) || (i == (qi_x2 - 1))) {
387					RGB24_PUTPIXEL(frame, i, j, 0xFF, 0xFF, 0xFF);
388					continue;
389				}
390				/* For all other points the Y coordinate does not matter */
391				if ((i >= m_ri) && (i <= (m_ri + 3))) {
392					RGB24_PUTPIXEL(frame, i, j, 0x00, 0xFF, 0x00);
393				} else if ((i >= m_wi) && (i <= (m_wi + 3))) {
394					RGB24_PUTPIXEL(frame, i, j, 0xFF, 0x00, 0x00);
395				} else if ((i < m_lo) || ((i > m_ri) && (i < m_hi)))
396					RGB24_PUTPIXEL(frame, i, j, 0x00, 0x00, 0xFF);
397			}
398		}
399	}
400
401	sprintf(tmp, "%8lx", uvd->stats.frame_num);
402	usbvideo_OverlayString(uvd, frame, x, y, tmp);
403	y += y_diff;
404
405	sprintf(tmp, "%8lx", uvd->stats.urb_count);
406	usbvideo_OverlayString(uvd, frame, x, y, tmp);
407	y += y_diff;
408
409	sprintf(tmp, "%8lx", uvd->stats.urb_length);
410	usbvideo_OverlayString(uvd, frame, x, y, tmp);
411	y += y_diff;
412
413	sprintf(tmp, "%8lx", uvd->stats.data_count);
414	usbvideo_OverlayString(uvd, frame, x, y, tmp);
415	y += y_diff;
416
417	sprintf(tmp, "%8lx", uvd->stats.header_count);
418	usbvideo_OverlayString(uvd, frame, x, y, tmp);
419	y += y_diff;
420
421	sprintf(tmp, "%8lx", uvd->stats.iso_skip_count);
422	usbvideo_OverlayString(uvd, frame, x, y, tmp);
423	y += y_diff;
424
425	sprintf(tmp, "%8lx", uvd->stats.iso_err_count);
426	usbvideo_OverlayString(uvd, frame, x, y, tmp);
427	y += y_diff;
428
429	sprintf(tmp, "%8x", uvd->vpic.colour);
430	usbvideo_OverlayString(uvd, frame, x, y, tmp);
431	y += y_diff;
432
433	sprintf(tmp, "%8x", uvd->vpic.hue);
434	usbvideo_OverlayString(uvd, frame, x, y, tmp);
435	y += y_diff;
436
437	sprintf(tmp, "%8x", uvd->vpic.brightness >> 8);
438	usbvideo_OverlayString(uvd, frame, x, y, tmp);
439	y += y_diff;
440
441	sprintf(tmp, "%8x", uvd->vpic.contrast >> 12);
442	usbvideo_OverlayString(uvd, frame, x, y, tmp);
443	y += y_diff;
444
445	sprintf(tmp, "%8d", uvd->vpic.whiteness >> 8);
446	usbvideo_OverlayString(uvd, frame, x, y, tmp);
447	y += y_diff;
448}
449
450/*
451 * usbvideo_ReportStatistics()
452 *
453 * This procedure prints packet and transfer statistics.
454 *
455 * History:
456 * 14-Jan-2000 Corrected default multiplier.
457 */
458static void usbvideo_ReportStatistics(const struct uvd *uvd)
459{
460	if ((uvd != NULL) && (uvd->stats.urb_count > 0)) {
461		unsigned long allPackets, badPackets, goodPackets, percent;
462		allPackets = uvd->stats.urb_count * CAMERA_URB_FRAMES;
463		badPackets = uvd->stats.iso_skip_count + uvd->stats.iso_err_count;
464		goodPackets = allPackets - badPackets;
465		/* Calculate percentage wisely, remember integer limits */
466		assert(allPackets != 0);
467		if (goodPackets < (((unsigned long)-1)/100))
468			percent = (100 * goodPackets) / allPackets;
469		else
470			percent = goodPackets / (allPackets / 100);
471		info("Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%",
472		     allPackets, badPackets, percent);
473		if (uvd->iso_packet_len > 0) {
474			unsigned long allBytes, xferBytes;
475			char multiplier = ' ';
476			allBytes = allPackets * uvd->iso_packet_len;
477			xferBytes = uvd->stats.data_count;
478			assert(allBytes != 0);
479			if (xferBytes < (((unsigned long)-1)/100))
480				percent = (100 * xferBytes) / allBytes;
481			else
482				percent = xferBytes / (allBytes / 100);
483			/* Scale xferBytes for easy reading */
484			if (xferBytes > 10*1024) {
485				xferBytes /= 1024;
486				multiplier = 'K';
487				if (xferBytes > 10*1024) {
488					xferBytes /= 1024;
489					multiplier = 'M';
490					if (xferBytes > 10*1024) {
491						xferBytes /= 1024;
492						multiplier = 'G';
493						if (xferBytes > 10*1024) {
494							xferBytes /= 1024;
495							multiplier = 'T';
496						}
497					}
498				}
499			}
500			info("Transfer Statistics: Transferred=%lu%cB Usage=%lu%%",
501			     xferBytes, multiplier, percent);
502		}
503	}
504}
505
506/*
507 * usbvideo_TestPattern()
508 *
509 * Procedure forms a test pattern (yellow grid on blue background).
510 *
511 * Parameters:
512 * fullframe: if TRUE then entire frame is filled, otherwise the procedure
513 *	      continues from the current scanline.
514 * pmode      0: fill the frame with solid blue color (like on VCR or TV)
515 *	      1: Draw a colored grid
516 *
517 * History:
518 * 01-Feb-2000 Created.
519 */
520void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode)
521{
522	struct usbvideo_frame *frame;
523	int num_cell = 0;
524	int scan_length = 0;
525	static int num_pass = 0;
526
527	if (uvd == NULL) {
528		err("%s: uvd == NULL", __FUNCTION__);
529		return;
530	}
531	if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) {
532		err("%s: uvd->curframe=%d.", __FUNCTION__, uvd->curframe);
533		return;
534	}
535
536	/* Grab the current frame */
537	frame = &uvd->frame[uvd->curframe];
538
539	/* Optionally start at the beginning */
540	if (fullframe) {
541		frame->curline = 0;
542		frame->seqRead_Length = 0;
543	}
544	/* Form every scan line */
545	for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) {
546		int i;
547		unsigned char *f = frame->data +
548			(VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline);
549		for (i=0; i < VIDEOSIZE_X(frame->request); i++) {
550			unsigned char cb=0x80;
551			unsigned char cg = 0;
552			unsigned char cr = 0;
553
554			if (pmode == 1) {
555				if (frame->curline % 32 == 0)
556					cb = 0, cg = cr = 0xFF;
557				else if (i % 32 == 0) {
558					if (frame->curline % 32 == 1)
559						num_cell++;
560					cb = 0, cg = cr = 0xFF;
561				} else {
562					cb = ((num_cell*7) + num_pass) & 0xFF;
563					cg = ((num_cell*5) + num_pass*2) & 0xFF;
564					cr = ((num_cell*3) + num_pass*3) & 0xFF;
565				}
566			} else {
567				/* Just the blue screen */
568			}
569
570			*f++ = cb;
571			*f++ = cg;
572			*f++ = cr;
573			scan_length += 3;
574		}
575	}
576
577	frame->frameState = FrameState_Done;
578	frame->seqRead_Length += scan_length;
579	++num_pass;
580
581	/* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */
582	usbvideo_OverlayStats(uvd, frame);
583}
584
585EXPORT_SYMBOL(usbvideo_TestPattern);
586
587
588#ifdef DEBUG
589/*
590 * usbvideo_HexDump()
591 *
592 * A debugging tool. Prints hex dumps.
593 *
594 * History:
595 * 29-Jul-2000 Added printing of offsets.
596 */
597void usbvideo_HexDump(const unsigned char *data, int len)
598{
599	const int bytes_per_line = 32;
600	char tmp[128]; /* 32*3 + 5 */
601	int i, k;
602
603	for (i=k=0; len > 0; i++, len--) {
604		if (i > 0 && ((i % bytes_per_line) == 0)) {
605			printk("%s\n", tmp);
606			k=0;
607		}
608		if ((i % bytes_per_line) == 0)
609			k += sprintf(&tmp[k], "%04x: ", i);
610		k += sprintf(&tmp[k], "%02x ", data[i]);
611	}
612	if (k > 0)
613		printk("%s\n", tmp);
614}
615
616EXPORT_SYMBOL(usbvideo_HexDump);
617
618#endif
619
620/* ******************************************************************** */
621
622static int usbvideo_ClientIncModCount(struct uvd *uvd)
623{
624	if (uvd == NULL) {
625		err("%s: uvd == NULL", __FUNCTION__);
626		return -EINVAL;
627	}
628	if (uvd->handle == NULL) {
629		err("%s: uvd->handle == NULL", __FUNCTION__);
630		return -EINVAL;
631	}
632	if (!try_module_get(uvd->handle->md_module)) {
633		err("%s: try_module_get() == 0", __FUNCTION__);
634		return -ENODEV;
635	}
636	return 0;
637}
638
639static void usbvideo_ClientDecModCount(struct uvd *uvd)
640{
641	if (uvd == NULL) {
642		err("%s: uvd == NULL", __FUNCTION__);
643		return;
644	}
645	if (uvd->handle == NULL) {
646		err("%s: uvd->handle == NULL", __FUNCTION__);
647		return;
648	}
649	if (uvd->handle->md_module == NULL) {
650		err("%s: uvd->handle->md_module == NULL", __FUNCTION__);
651		return;
652	}
653	module_put(uvd->handle->md_module);
654}
655
656int usbvideo_register(
657	struct usbvideo **pCams,
658	const int num_cams,
659	const int num_extra,
660	const char *driverName,
661	const struct usbvideo_cb *cbTbl,
662	struct module *md,
663	const struct usb_device_id *id_table)
664{
665	struct usbvideo *cams;
666	int i, base_size, result;
667
668	/* Check parameters for sanity */
669	if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) {
670		err("%s: Illegal call", __FUNCTION__);
671		return -EINVAL;
672	}
673
674	/* Check registration callback - must be set! */
675	if (cbTbl->probe == NULL) {
676		err("%s: probe() is required!", __FUNCTION__);
677		return -EINVAL;
678	}
679
680	base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo);
681	cams = kzalloc(base_size, GFP_KERNEL);
682	if (cams == NULL) {
683		err("Failed to allocate %d. bytes for usbvideo struct", base_size);
684		return -ENOMEM;
685	}
686	dbg("%s: Allocated $%p (%d. bytes) for %d. cameras",
687	    __FUNCTION__, cams, base_size, num_cams);
688
689	/* Copy callbacks, apply defaults for those that are not set */
690	memmove(&cams->cb, cbTbl, sizeof(cams->cb));
691	if (cams->cb.getFrame == NULL)
692		cams->cb.getFrame = usbvideo_GetFrame;
693	if (cams->cb.disconnect == NULL)
694		cams->cb.disconnect = usbvideo_Disconnect;
695	if (cams->cb.startDataPump == NULL)
696		cams->cb.startDataPump = usbvideo_StartDataPump;
697	if (cams->cb.stopDataPump == NULL)
698		cams->cb.stopDataPump = usbvideo_StopDataPump;
699
700	cams->num_cameras = num_cams;
701	cams->cam = (struct uvd *) &cams[1];
702	cams->md_module = md;
703	mutex_init(&cams->lock);	/* to 1 == available */
704
705	for (i = 0; i < num_cams; i++) {
706		struct uvd *up = &cams->cam[i];
707
708		up->handle = cams;
709
710		/* Allocate user_data separately because of kmalloc's limits */
711		if (num_extra > 0) {
712			up->user_size = num_cams * num_extra;
713			up->user_data = kmalloc(up->user_size, GFP_KERNEL);
714			if (up->user_data == NULL) {
715				err("%s: Failed to allocate user_data (%d. bytes)",
716				    __FUNCTION__, up->user_size);
717				while (i) {
718					up = &cams->cam[--i];
719					kfree(up->user_data);
720				}
721				kfree(cams);
722				return -ENOMEM;
723			}
724			dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)",
725			     __FUNCTION__, i, up->user_data, up->user_size);
726		}
727	}
728
729	/*
730	 * Register ourselves with USB stack.
731	 */
732	strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown");
733	cams->usbdrv.name = cams->drvName;
734	cams->usbdrv.probe = cams->cb.probe;
735	cams->usbdrv.disconnect = cams->cb.disconnect;
736	cams->usbdrv.id_table = id_table;
737
738	/*
739	 * Update global handle to usbvideo. This is very important
740	 * because probe() can be called before usb_register() returns.
741	 * If the handle is not yet updated then the probe() will fail.
742	 */
743	*pCams = cams;
744	result = usb_register(&cams->usbdrv);
745	if (result) {
746		for (i = 0; i < num_cams; i++) {
747			struct uvd *up = &cams->cam[i];
748			kfree(up->user_data);
749		}
750		kfree(cams);
751	}
752
753	return result;
754}
755
756EXPORT_SYMBOL(usbvideo_register);
757
758/*
759 * usbvideo_Deregister()
760 *
761 * Procedure frees all usbvideo and user data structures. Be warned that
762 * if you had some dynamically allocated components in ->user field then
763 * you should free them before calling here.
764 */
765void usbvideo_Deregister(struct usbvideo **pCams)
766{
767	struct usbvideo *cams;
768	int i;
769
770	if (pCams == NULL) {
771		err("%s: pCams == NULL", __FUNCTION__);
772		return;
773	}
774	cams = *pCams;
775	if (cams == NULL) {
776		err("%s: cams == NULL", __FUNCTION__);
777		return;
778	}
779
780	dbg("%s: Deregistering %s driver.", __FUNCTION__, cams->drvName);
781	usb_deregister(&cams->usbdrv);
782
783	dbg("%s: Deallocating cams=$%p (%d. cameras)", __FUNCTION__, cams, cams->num_cameras);
784	for (i=0; i < cams->num_cameras; i++) {
785		struct uvd *up = &cams->cam[i];
786		int warning = 0;
787
788		if (up->user_data != NULL) {
789			if (up->user_size <= 0)
790				++warning;
791		} else {
792			if (up->user_size > 0)
793				++warning;
794		}
795		if (warning) {
796			err("%s: Warning: user_data=$%p user_size=%d.",
797			    __FUNCTION__, up->user_data, up->user_size);
798		} else {
799			dbg("%s: Freeing %d. $%p->user_data=$%p",
800			    __FUNCTION__, i, up, up->user_data);
801			kfree(up->user_data);
802		}
803	}
804	/* Whole array was allocated in one chunk */
805	dbg("%s: Freed %d uvd structures",
806	    __FUNCTION__, cams->num_cameras);
807	kfree(cams);
808	*pCams = NULL;
809}
810
811EXPORT_SYMBOL(usbvideo_Deregister);
812
813/*
814 * usbvideo_Disconnect()
815 *
816 * This procedure stops all driver activity. Deallocation of
817 * the interface-private structure (pointed by 'ptr') is done now
818 * (if we don't have any open files) or later, when those files
819 * are closed. After that driver should be removable.
820 *
821 * This code handles surprise removal. The uvd->user is a counter which
822 * increments on open() and decrements on close(). If we see here that
823 * this counter is not 0 then we have a client who still has us opened.
824 * We set uvd->remove_pending flag as early as possible, and after that
825 * all access to the camera will gracefully fail. These failures should
826 * prompt client to (eventually) close the video device, and then - in
827 * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter.
828 *
829 * History:
830 * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone.
831 * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close()
832 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
833 * 19-Oct-2000 Moved to usbvideo module.
834 */
835static void usbvideo_Disconnect(struct usb_interface *intf)
836{
837	struct uvd *uvd = usb_get_intfdata (intf);
838	int i;
839
840	if (uvd == NULL) {
841		err("%s($%p): Illegal call.", __FUNCTION__, intf);
842		return;
843	}
844
845	usb_set_intfdata (intf, NULL);
846
847	usbvideo_ClientIncModCount(uvd);
848	if (uvd->debug > 0)
849		info("%s(%p.)", __FUNCTION__, intf);
850
851	mutex_lock(&uvd->lock);
852	uvd->remove_pending = 1; /* Now all ISO data will be ignored */
853
854	/* At this time we ask to cancel outstanding URBs */
855	GET_CALLBACK(uvd, stopDataPump)(uvd);
856
857	for (i=0; i < USBVIDEO_NUMSBUF; i++)
858		usb_free_urb(uvd->sbuf[i].urb);
859
860	usb_put_dev(uvd->dev);
861	uvd->dev = NULL;    	    /* USB device is no more */
862
863	video_unregister_device(&uvd->vdev);
864	if (uvd->debug > 0)
865		info("%s: Video unregistered.", __FUNCTION__);
866
867	if (uvd->user)
868		info("%s: In use, disconnect pending.", __FUNCTION__);
869	else
870		usbvideo_CameraRelease(uvd);
871	mutex_unlock(&uvd->lock);
872	info("USB camera disconnected.");
873
874	usbvideo_ClientDecModCount(uvd);
875}
876
877/*
878 * usbvideo_CameraRelease()
879 *
880 * This code does final release of uvd. This happens
881 * after the device is disconnected -and- all clients
882 * closed their files.
883 *
884 * History:
885 * 27-Jan-2000 Created.
886 */
887static void usbvideo_CameraRelease(struct uvd *uvd)
888{
889	if (uvd == NULL) {
890		err("%s: Illegal call", __FUNCTION__);
891		return;
892	}
893
894	RingQueue_Free(&uvd->dp);
895	if (VALID_CALLBACK(uvd, userFree))
896		GET_CALLBACK(uvd, userFree)(uvd);
897	uvd->uvd_used = 0;	/* This is atomic, no need to take mutex */
898}
899
900/*
901 * usbvideo_find_struct()
902 *
903 * This code searches the array of preallocated (static) structures
904 * and returns index of the first one that isn't in use. Returns -1
905 * if there are no free structures.
906 *
907 * History:
908 * 27-Jan-2000 Created.
909 */
910static int usbvideo_find_struct(struct usbvideo *cams)
911{
912	int u, rv = -1;
913
914	if (cams == NULL) {
915		err("No usbvideo handle?");
916		return -1;
917	}
918	mutex_lock(&cams->lock);
919	for (u = 0; u < cams->num_cameras; u++) {
920		struct uvd *uvd = &cams->cam[u];
921		if (!uvd->uvd_used) /* This one is free */
922		{
923			uvd->uvd_used = 1;	/* In use now */
924			mutex_init(&uvd->lock);	/* to 1 == available */
925			uvd->dev = NULL;
926			rv = u;
927			break;
928		}
929	}
930	mutex_unlock(&cams->lock);
931	return rv;
932}
933
934static const struct file_operations usbvideo_fops = {
935	.owner =  THIS_MODULE,
936	.open =   usbvideo_v4l_open,
937	.release =usbvideo_v4l_close,
938	.read =   usbvideo_v4l_read,
939	.mmap =   usbvideo_v4l_mmap,
940	.ioctl =  usbvideo_v4l_ioctl,
941	.compat_ioctl = v4l_compat_ioctl32,
942	.llseek = no_llseek,
943};
944static const struct video_device usbvideo_template = {
945	.owner =      THIS_MODULE,
946	.type =       VID_TYPE_CAPTURE,
947	.hardware =   VID_HARDWARE_CPIA,
948	.fops =       &usbvideo_fops,
949};
950
951struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
952{
953	int i, devnum;
954	struct uvd *uvd = NULL;
955
956	if (cams == NULL) {
957		err("No usbvideo handle?");
958		return NULL;
959	}
960
961	devnum = usbvideo_find_struct(cams);
962	if (devnum == -1) {
963		err("IBM USB camera driver: Too many devices!");
964		return NULL;
965	}
966	uvd = &cams->cam[devnum];
967	dbg("Device entry #%d. at $%p", devnum, uvd);
968
969	/* Not relying upon caller we increase module counter ourselves */
970	usbvideo_ClientIncModCount(uvd);
971
972	mutex_lock(&uvd->lock);
973	for (i=0; i < USBVIDEO_NUMSBUF; i++) {
974		uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
975		if (uvd->sbuf[i].urb == NULL) {
976			err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
977			uvd->uvd_used = 0;
978			uvd = NULL;
979			goto allocate_done;
980		}
981	}
982	uvd->user=0;
983	uvd->remove_pending = 0;
984	uvd->last_error = 0;
985	RingQueue_Initialize(&uvd->dp);
986
987	/* Initialize video device structure */
988	uvd->vdev = usbvideo_template;
989	sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
990	/*
991	 * The client is free to overwrite those because we
992	 * return control to the client's probe function right now.
993	 */
994allocate_done:
995	mutex_unlock(&uvd->lock);
996	usbvideo_ClientDecModCount(uvd);
997	return uvd;
998}
999
1000EXPORT_SYMBOL(usbvideo_AllocateDevice);
1001
1002int usbvideo_RegisterVideoDevice(struct uvd *uvd)
1003{
1004	char tmp1[20], tmp2[20];	/* Buffers for printing */
1005
1006	if (uvd == NULL) {
1007		err("%s: Illegal call.", __FUNCTION__);
1008		return -EINVAL;
1009	}
1010	if (uvd->video_endp == 0) {
1011		info("%s: No video endpoint specified; data pump disabled.", __FUNCTION__);
1012	}
1013	if (uvd->paletteBits == 0) {
1014		err("%s: No palettes specified!", __FUNCTION__);
1015		return -EINVAL;
1016	}
1017	if (uvd->defaultPalette == 0) {
1018		info("%s: No default palette!", __FUNCTION__);
1019	}
1020
1021	uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) *
1022		VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL;
1023	usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize);
1024	usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas);
1025
1026	if (uvd->debug > 0) {
1027		info("%s: iface=%d. endpoint=$%02x paletteBits=$%08lx",
1028		     __FUNCTION__, uvd->iface, uvd->video_endp, uvd->paletteBits);
1029	}
1030	if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
1031		err("%s: video_register_device failed", __FUNCTION__);
1032		return -EPIPE;
1033	}
1034	if (uvd->debug > 1) {
1035		info("%s: video_register_device() successful", __FUNCTION__);
1036	}
1037	if (uvd->dev == NULL) {
1038		err("%s: uvd->dev == NULL", __FUNCTION__);
1039		return -EINVAL;
1040	}
1041
1042	info("%s on /dev/video%d: canvas=%s videosize=%s",
1043	     (uvd->handle != NULL) ? uvd->handle->drvName : "???",
1044	     uvd->vdev.minor, tmp2, tmp1);
1045
1046	usb_get_dev(uvd->dev);
1047	return 0;
1048}
1049
1050EXPORT_SYMBOL(usbvideo_RegisterVideoDevice);
1051
1052/* ******************************************************************** */
1053
1054static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma)
1055{
1056	struct uvd *uvd = file->private_data;
1057	unsigned long start = vma->vm_start;
1058	unsigned long size  = vma->vm_end-vma->vm_start;
1059	unsigned long page, pos;
1060
1061	if (!CAMERA_IS_OPERATIONAL(uvd))
1062		return -EFAULT;
1063
1064	if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
1065		return -EINVAL;
1066
1067	pos = (unsigned long) uvd->fbuf;
1068	while (size > 0) {
1069		page = vmalloc_to_pfn((void *)pos);
1070		if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1071			return -EAGAIN;
1072
1073		start += PAGE_SIZE;
1074		pos += PAGE_SIZE;
1075		if (size > PAGE_SIZE)
1076			size -= PAGE_SIZE;
1077		else
1078			size = 0;
1079	}
1080
1081	return 0;
1082}
1083
1084/*
1085 * usbvideo_v4l_open()
1086 *
1087 * This is part of Video 4 Linux API. The driver can be opened by one
1088 * client only (checks internal counter 'uvdser'). The procedure
1089 * then allocates buffers needed for video processing.
1090 *
1091 * History:
1092 * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the
1093 *             camera is also initialized here (once per connect), at
1094 *             expense of V4L client (it waits on open() call).
1095 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1096 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
1097 */
1098static int usbvideo_v4l_open(struct inode *inode, struct file *file)
1099{
1100	struct video_device *dev = video_devdata(file);
1101	struct uvd *uvd = (struct uvd *) dev;
1102	const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len;
1103	int i, errCode = 0;
1104
1105	if (uvd->debug > 1)
1106		info("%s($%p)", __FUNCTION__, dev);
1107
1108	if (0 < usbvideo_ClientIncModCount(uvd))
1109		return -ENODEV;
1110	mutex_lock(&uvd->lock);
1111
1112	if (uvd->user) {
1113		err("%s: Someone tried to open an already opened device!", __FUNCTION__);
1114		errCode = -EBUSY;
1115	} else {
1116		/* Clear statistics */
1117		memset(&uvd->stats, 0, sizeof(uvd->stats));
1118
1119		/* Clean pointers so we know if we allocated something */
1120		for (i=0; i < USBVIDEO_NUMSBUF; i++)
1121			uvd->sbuf[i].data = NULL;
1122
1123		/* Allocate memory for the frame buffers */
1124		uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
1125		uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
1126		RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
1127		if ((uvd->fbuf == NULL) ||
1128		    (!RingQueue_IsAllocated(&uvd->dp))) {
1129			err("%s: Failed to allocate fbuf or dp", __FUNCTION__);
1130			errCode = -ENOMEM;
1131		} else {
1132			/* Allocate all buffers */
1133			for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
1134				uvd->frame[i].frameState = FrameState_Unused;
1135				uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
1136				/*
1137				 * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
1138				 * is not used (using read() instead).
1139				 */
1140				uvd->frame[i].canvas = uvd->canvas;
1141				uvd->frame[i].seqRead_Index = 0;
1142			}
1143			for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1144				uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
1145				if (uvd->sbuf[i].data == NULL) {
1146					errCode = -ENOMEM;
1147					break;
1148				}
1149			}
1150		}
1151		if (errCode != 0) {
1152			/* Have to free all that memory */
1153			if (uvd->fbuf != NULL) {
1154				usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1155				uvd->fbuf = NULL;
1156			}
1157			RingQueue_Free(&uvd->dp);
1158			for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1159				kfree(uvd->sbuf[i].data);
1160				uvd->sbuf[i].data = NULL;
1161			}
1162		}
1163	}
1164
1165	/* If so far no errors then we shall start the camera */
1166	if (errCode == 0) {
1167		/* Start data pump if we have valid endpoint */
1168		if (uvd->video_endp != 0)
1169			errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
1170		if (errCode == 0) {
1171			if (VALID_CALLBACK(uvd, setupOnOpen)) {
1172				if (uvd->debug > 1)
1173					info("%s: setupOnOpen callback", __FUNCTION__);
1174				errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
1175				if (errCode < 0) {
1176					err("%s: setupOnOpen callback failed (%d.).",
1177					    __FUNCTION__, errCode);
1178				} else if (uvd->debug > 1) {
1179					info("%s: setupOnOpen callback successful", __FUNCTION__);
1180				}
1181			}
1182			if (errCode == 0) {
1183				uvd->settingsAdjusted = 0;
1184				if (uvd->debug > 1)
1185					info("%s: Open succeeded.", __FUNCTION__);
1186				uvd->user++;
1187				file->private_data = uvd;
1188			}
1189		}
1190	}
1191	mutex_unlock(&uvd->lock);
1192	if (errCode != 0)
1193		usbvideo_ClientDecModCount(uvd);
1194	if (uvd->debug > 0)
1195		info("%s: Returning %d.", __FUNCTION__, errCode);
1196	return errCode;
1197}
1198
1199/*
1200 * usbvideo_v4l_close()
1201 *
1202 * This is part of Video 4 Linux API. The procedure
1203 * stops streaming and deallocates all buffers that were earlier
1204 * allocated in usbvideo_v4l_open().
1205 *
1206 * History:
1207 * 22-Jan-2000 Moved scratch buffer deallocation here.
1208 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1209 * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
1210 */
1211static int usbvideo_v4l_close(struct inode *inode, struct file *file)
1212{
1213	struct video_device *dev = file->private_data;
1214	struct uvd *uvd = (struct uvd *) dev;
1215	int i;
1216
1217	if (uvd->debug > 1)
1218		info("%s($%p)", __FUNCTION__, dev);
1219
1220	mutex_lock(&uvd->lock);
1221	GET_CALLBACK(uvd, stopDataPump)(uvd);
1222	usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1223	uvd->fbuf = NULL;
1224	RingQueue_Free(&uvd->dp);
1225
1226	for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1227		kfree(uvd->sbuf[i].data);
1228		uvd->sbuf[i].data = NULL;
1229	}
1230
1231#if USBVIDEO_REPORT_STATS
1232	usbvideo_ReportStatistics(uvd);
1233#endif
1234
1235	uvd->user--;
1236	if (uvd->remove_pending) {
1237		if (uvd->debug > 0)
1238			info("usbvideo_v4l_close: Final disconnect.");
1239		usbvideo_CameraRelease(uvd);
1240	}
1241	mutex_unlock(&uvd->lock);
1242	usbvideo_ClientDecModCount(uvd);
1243
1244	if (uvd->debug > 1)
1245		info("%s: Completed.", __FUNCTION__);
1246	file->private_data = NULL;
1247	return 0;
1248}
1249
1250/*
1251 * usbvideo_v4l_ioctl()
1252 *
1253 * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
1254 *
1255 * History:
1256 * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
1257 */
1258static int usbvideo_v4l_do_ioctl(struct inode *inode, struct file *file,
1259				 unsigned int cmd, void *arg)
1260{
1261	struct uvd *uvd = file->private_data;
1262
1263	if (!CAMERA_IS_OPERATIONAL(uvd))
1264		return -EIO;
1265
1266	switch (cmd) {
1267		case VIDIOCGCAP:
1268		{
1269			struct video_capability *b = arg;
1270			*b = uvd->vcap;
1271			return 0;
1272		}
1273		case VIDIOCGCHAN:
1274		{
1275			struct video_channel *v = arg;
1276			*v = uvd->vchan;
1277			return 0;
1278		}
1279		case VIDIOCSCHAN:
1280		{
1281			struct video_channel *v = arg;
1282			if (v->channel != 0)
1283				return -EINVAL;
1284			return 0;
1285		}
1286		case VIDIOCGPICT:
1287		{
1288			struct video_picture *pic = arg;
1289			*pic = uvd->vpic;
1290			return 0;
1291		}
1292		case VIDIOCSPICT:
1293		{
1294			struct video_picture *pic = arg;
1295			/*
1296			 * Use temporary 'video_picture' structure to preserve our
1297			 * own settings (such as color depth, palette) that we
1298			 * aren't allowing everyone (V4L client) to change.
1299			 */
1300			uvd->vpic.brightness = pic->brightness;
1301			uvd->vpic.hue = pic->hue;
1302			uvd->vpic.colour = pic->colour;
1303			uvd->vpic.contrast = pic->contrast;
1304			uvd->settingsAdjusted = 0;	/* Will force new settings */
1305			return 0;
1306		}
1307		case VIDIOCSWIN:
1308		{
1309			struct video_window *vw = arg;
1310
1311			if(VALID_CALLBACK(uvd, setVideoMode)) {
1312				return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
1313			}
1314
1315			if (vw->flags)
1316				return -EINVAL;
1317			if (vw->clipcount)
1318				return -EINVAL;
1319			if (vw->width != VIDEOSIZE_X(uvd->canvas))
1320				return -EINVAL;
1321			if (vw->height != VIDEOSIZE_Y(uvd->canvas))
1322				return -EINVAL;
1323
1324			return 0;
1325		}
1326		case VIDIOCGWIN:
1327		{
1328			struct video_window *vw = arg;
1329
1330			vw->x = 0;
1331			vw->y = 0;
1332			vw->width = VIDEOSIZE_X(uvd->videosize);
1333			vw->height = VIDEOSIZE_Y(uvd->videosize);
1334			vw->chromakey = 0;
1335			if (VALID_CALLBACK(uvd, getFPS))
1336				vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
1337			else
1338				vw->flags = 10;
1339			return 0;
1340		}
1341		case VIDIOCGMBUF:
1342		{
1343			struct video_mbuf *vm = arg;
1344			int i;
1345
1346			memset(vm, 0, sizeof(*vm));
1347			vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
1348			vm->frames = USBVIDEO_NUMFRAMES;
1349			for(i = 0; i < USBVIDEO_NUMFRAMES; i++)
1350			  vm->offsets[i] = i * uvd->max_frame_size;
1351
1352			return 0;
1353		}
1354		case VIDIOCMCAPTURE:
1355		{
1356			struct video_mmap *vm = arg;
1357
1358			if (uvd->debug >= 1) {
1359				info("VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.",
1360				     vm->frame, vm->width, vm->height, vm->format);
1361			}
1362			/*
1363			 * Check if the requested size is supported. If the requestor
1364			 * requests too big a frame then we may be tricked into accessing
1365			 * outside of own preallocated frame buffer (in uvd->frame).
1366			 * This will cause oops or a security hole. Theoretically, we
1367			 * could only clamp the size down to acceptable bounds, but then
1368			 * we'd need to figure out how to insert our smaller buffer into
1369			 * larger caller's buffer... this is not an easy question. So we
1370			 * here just flatly reject too large requests, assuming that the
1371			 * caller will resubmit with smaller size. Callers should know
1372			 * what size we support (returned by VIDIOCGCAP). However vidcat,
1373			 * for one, does not care and allows to ask for any size.
1374			 */
1375			if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
1376			    (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
1377				if (uvd->debug > 0) {
1378					info("VIDIOCMCAPTURE: Size=%dx%d too large; "
1379					     "allowed only up to %ldx%ld", vm->width, vm->height,
1380					     VIDEOSIZE_X(uvd->canvas), VIDEOSIZE_Y(uvd->canvas));
1381				}
1382				return -EINVAL;
1383			}
1384			/* Check if the palette is supported */
1385			if (((1L << vm->format) & uvd->paletteBits) == 0) {
1386				if (uvd->debug > 0) {
1387					info("VIDIOCMCAPTURE: format=%d. not supported"
1388					     " (paletteBits=$%08lx)",
1389					     vm->format, uvd->paletteBits);
1390				}
1391				return -EINVAL;
1392			}
1393			if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
1394				err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
1395				return -EINVAL;
1396			}
1397			if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
1398				/* Not an error - can happen */
1399			}
1400			uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
1401			uvd->frame[vm->frame].palette = vm->format;
1402
1403			/* Mark it as ready */
1404			uvd->frame[vm->frame].frameState = FrameState_Ready;
1405
1406			return usbvideo_NewFrame(uvd, vm->frame);
1407		}
1408		case VIDIOCSYNC:
1409		{
1410			int *frameNum = arg;
1411			int ret;
1412
1413			if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
1414				return -EINVAL;
1415
1416			if (uvd->debug >= 1)
1417				info("VIDIOCSYNC: syncing to frame %d.", *frameNum);
1418			if (uvd->flags & FLAGS_NO_DECODING)
1419				ret = usbvideo_GetFrame(uvd, *frameNum);
1420			else if (VALID_CALLBACK(uvd, getFrame)) {
1421				ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
1422				if ((ret < 0) && (uvd->debug >= 1)) {
1423					err("VIDIOCSYNC: getFrame() returned %d.", ret);
1424				}
1425			} else {
1426				err("VIDIOCSYNC: getFrame is not set");
1427				ret = -EFAULT;
1428			}
1429
1430			/*
1431			 * The frame is in FrameState_Done_Hold state. Release it
1432			 * right now because its data is already mapped into
1433			 * the user space and it's up to the application to
1434			 * make use of it until it asks for another frame.
1435			 */
1436			uvd->frame[*frameNum].frameState = FrameState_Unused;
1437			return ret;
1438		}
1439		case VIDIOCGFBUF:
1440		{
1441			struct video_buffer *vb = arg;
1442
1443			memset(vb, 0, sizeof(*vb));
1444			return 0;
1445		}
1446		case VIDIOCKEY:
1447			return 0;
1448
1449		case VIDIOCCAPTURE:
1450			return -EINVAL;
1451
1452		case VIDIOCSFBUF:
1453
1454		case VIDIOCGTUNER:
1455		case VIDIOCSTUNER:
1456
1457		case VIDIOCGFREQ:
1458		case VIDIOCSFREQ:
1459
1460		case VIDIOCGAUDIO:
1461		case VIDIOCSAUDIO:
1462			return -EINVAL;
1463
1464		default:
1465			return -ENOIOCTLCMD;
1466	}
1467	return 0;
1468}
1469
1470static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
1471		       unsigned int cmd, unsigned long arg)
1472{
1473	return video_usercopy(inode, file, cmd, arg, usbvideo_v4l_do_ioctl);
1474}
1475
1476/*
1477 * usbvideo_v4l_read()
1478 *
1479 * This is mostly boring stuff. We simply ask for a frame and when it
1480 * arrives copy all the video data from it into user space. There is
1481 * no obvious need to override this method.
1482 *
1483 * History:
1484 * 20-Oct-2000 Created.
1485 * 01-Nov-2000 Added mutex (uvd->lock).
1486 */
1487static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
1488		      size_t count, loff_t *ppos)
1489{
1490	struct uvd *uvd = file->private_data;
1491	int noblock = file->f_flags & O_NONBLOCK;
1492	int frmx = -1, i;
1493	struct usbvideo_frame *frame;
1494
1495	if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
1496		return -EFAULT;
1497
1498	if (uvd->debug >= 1)
1499		info("%s: %Zd. bytes, noblock=%d.", __FUNCTION__, count, noblock);
1500
1501	mutex_lock(&uvd->lock);
1502
1503	/* See if a frame is completed, then use it. */
1504	for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1505		if ((uvd->frame[i].frameState == FrameState_Done) ||
1506		    (uvd->frame[i].frameState == FrameState_Done_Hold) ||
1507		    (uvd->frame[i].frameState == FrameState_Error)) {
1508			frmx = i;
1509			break;
1510		}
1511	}
1512
1513	if (noblock && (frmx == -1)) {
1514		count = -EAGAIN;
1515		goto read_done;
1516	}
1517
1518	/*
1519	 * If no FrameState_Done, look for a FrameState_Grabbing state.
1520	 * See if a frame is in process (grabbing), then use it.
1521	 * We will need to wait until it becomes cooked, of course.
1522	 */
1523	if (frmx == -1) {
1524		for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1525			if (uvd->frame[i].frameState == FrameState_Grabbing) {
1526				frmx = i;
1527				break;
1528			}
1529		}
1530	}
1531
1532	/*
1533	 * If no frame is active, start one. We don't care which one
1534	 * it will be, so #0 is as good as any.
1535	 * In read access mode we don't have convenience of VIDIOCMCAPTURE
1536	 * to specify the requested palette (video format) on per-frame
1537	 * basis. This means that we have to return data in -some- format
1538	 * and just hope that the client knows what to do with it.
1539	 * The default format is configured in uvd->defaultPalette field
1540	 * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
1541	 * frame and initiate the frame filling process.
1542	 */
1543	if (frmx == -1) {
1544		if (uvd->defaultPalette == 0) {
1545			err("%s: No default palette; don't know what to do!", __FUNCTION__);
1546			count = -EFAULT;
1547			goto read_done;
1548		}
1549		frmx = 0;
1550		/*
1551		 * We have no per-frame control over video size.
1552		 * Therefore we only can use whatever size was
1553		 * specified as default.
1554		 */
1555		uvd->frame[frmx].request = uvd->videosize;
1556		uvd->frame[frmx].palette = uvd->defaultPalette;
1557		uvd->frame[frmx].frameState = FrameState_Ready;
1558		usbvideo_NewFrame(uvd, frmx);
1559		/* Now frame 0 is supposed to start filling... */
1560	}
1561
1562	/*
1563	 * Get a pointer to the active frame. It is either previously
1564	 * completed frame or frame in progress but not completed yet.
1565	 */
1566	frame = &uvd->frame[frmx];
1567
1568	/*
1569	 * Sit back & wait until the frame gets filled and postprocessed.
1570	 * If we fail to get the picture [in time] then return the error.
1571	 * In this call we specify that we want the frame to be waited for,
1572	 * postprocessed and switched into FrameState_Done_Hold state. This
1573	 * state is used to hold the frame as "fully completed" between
1574	 * subsequent partial reads of the same frame.
1575	 */
1576	if (frame->frameState != FrameState_Done_Hold) {
1577		long rv = -EFAULT;
1578		if (uvd->flags & FLAGS_NO_DECODING)
1579			rv = usbvideo_GetFrame(uvd, frmx);
1580		else if (VALID_CALLBACK(uvd, getFrame))
1581			rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
1582		else
1583			err("getFrame is not set");
1584		if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
1585			count = rv;
1586			goto read_done;
1587		}
1588	}
1589
1590	/*
1591	 * Copy bytes to user space. We allow for partial reads, which
1592	 * means that the user application can request read less than
1593	 * the full frame size. It is up to the application to issue
1594	 * subsequent calls until entire frame is read.
1595	 *
1596	 * First things first, make sure we don't copy more than we
1597	 * have - even if the application wants more. That would be
1598	 * a big security embarassment!
1599	 */
1600	if ((count + frame->seqRead_Index) > frame->seqRead_Length)
1601		count = frame->seqRead_Length - frame->seqRead_Index;
1602
1603	/*
1604	 * Copy requested amount of data to user space. We start
1605	 * copying from the position where we last left it, which
1606	 * will be zero for a new frame (not read before).
1607	 */
1608	if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
1609		count = -EFAULT;
1610		goto read_done;
1611	}
1612
1613	/* Update last read position */
1614	frame->seqRead_Index += count;
1615	if (uvd->debug >= 1) {
1616		err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
1617			__FUNCTION__, count, frame->seqRead_Index);
1618	}
1619
1620	/* Finally check if the frame is done with and "release" it */
1621	if (frame->seqRead_Index >= frame->seqRead_Length) {
1622		/* All data has been read */
1623		frame->seqRead_Index = 0;
1624
1625		/* Mark it as available to be used again. */
1626		uvd->frame[frmx].frameState = FrameState_Unused;
1627		if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
1628			err("%s: usbvideo_NewFrame failed.", __FUNCTION__);
1629		}
1630	}
1631read_done:
1632	mutex_unlock(&uvd->lock);
1633	return count;
1634}
1635
1636/*
1637 * Make all of the blocks of data contiguous
1638 */
1639static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
1640{
1641	char *cdata;
1642	int i, totlen = 0;
1643
1644	for (i = 0; i < urb->number_of_packets; i++) {
1645		int n = urb->iso_frame_desc[i].actual_length;
1646		int st = urb->iso_frame_desc[i].status;
1647
1648		cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1649
1650		/* Detect and ignore errored packets */
1651		if (st < 0) {
1652			if (uvd->debug >= 1)
1653				err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
1654			uvd->stats.iso_err_count++;
1655			continue;
1656		}
1657
1658		/* Detect and ignore empty packets */
1659		if (n <= 0) {
1660			uvd->stats.iso_skip_count++;
1661			continue;
1662		}
1663		totlen += n;	/* Little local accounting */
1664		RingQueue_Enqueue(&uvd->dp, cdata, n);
1665	}
1666	return totlen;
1667}
1668
1669static void usbvideo_IsocIrq(struct urb *urb)
1670{
1671	int i, ret, len;
1672	struct uvd *uvd = urb->context;
1673
1674	/* We don't want to do anything if we are about to be removed! */
1675	if (!CAMERA_IS_OPERATIONAL(uvd))
1676		return;
1677
1678	if (!uvd->streaming) {
1679		if (uvd->debug >= 1)
1680			info("Not streaming, but interrupt!");
1681		return;
1682	}
1683
1684	uvd->stats.urb_count++;
1685	if (urb->actual_length <= 0)
1686		goto urb_done_with;
1687
1688	/* Copy the data received into ring queue */
1689	len = usbvideo_CompressIsochronous(uvd, urb);
1690	uvd->stats.urb_length = len;
1691	if (len <= 0)
1692		goto urb_done_with;
1693
1694	/* Here we got some data */
1695	uvd->stats.data_count += len;
1696	RingQueue_WakeUpInterruptible(&uvd->dp);
1697
1698urb_done_with:
1699	for (i = 0; i < FRAMES_PER_DESC; i++) {
1700		urb->iso_frame_desc[i].status = 0;
1701		urb->iso_frame_desc[i].actual_length = 0;
1702	}
1703	urb->status = 0;
1704	urb->dev = uvd->dev;
1705	ret = usb_submit_urb (urb, GFP_KERNEL);
1706	if(ret)
1707		err("usb_submit_urb error (%d)", ret);
1708	return;
1709}
1710
1711/*
1712 * usbvideo_StartDataPump()
1713 *
1714 * History:
1715 * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead
1716 *             of hardcoded values. Simplified by using for loop,
1717 *             allowed any number of URBs.
1718 */
1719static int usbvideo_StartDataPump(struct uvd *uvd)
1720{
1721	struct usb_device *dev = uvd->dev;
1722	int i, errFlag;
1723
1724	if (uvd->debug > 1)
1725		info("%s($%p)", __FUNCTION__, uvd);
1726
1727	if (!CAMERA_IS_OPERATIONAL(uvd)) {
1728		err("%s: Camera is not operational", __FUNCTION__);
1729		return -EFAULT;
1730	}
1731	uvd->curframe = -1;
1732
1733	/* Alternate interface 1 is is the biggest frame size */
1734	i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
1735	if (i < 0) {
1736		err("%s: usb_set_interface error", __FUNCTION__);
1737		uvd->last_error = i;
1738		return -EBUSY;
1739	}
1740	if (VALID_CALLBACK(uvd, videoStart))
1741		GET_CALLBACK(uvd, videoStart)(uvd);
1742	else
1743		err("%s: videoStart not set", __FUNCTION__);
1744
1745	/* We double buffer the Iso lists */
1746	for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1747		int j, k;
1748		struct urb *urb = uvd->sbuf[i].urb;
1749		urb->dev = dev;
1750		urb->context = uvd;
1751		urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
1752		urb->interval = 1;
1753		urb->transfer_flags = URB_ISO_ASAP;
1754		urb->transfer_buffer = uvd->sbuf[i].data;
1755		urb->complete = usbvideo_IsocIrq;
1756		urb->number_of_packets = FRAMES_PER_DESC;
1757		urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC;
1758		for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) {
1759			urb->iso_frame_desc[j].offset = k;
1760			urb->iso_frame_desc[j].length = uvd->iso_packet_len;
1761		}
1762	}
1763
1764	/* Submit all URBs */
1765	for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1766		errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
1767		if (errFlag)
1768			err("%s: usb_submit_isoc(%d) ret %d", __FUNCTION__, i, errFlag);
1769	}
1770
1771	uvd->streaming = 1;
1772	if (uvd->debug > 1)
1773		info("%s: streaming=1 video_endp=$%02x", __FUNCTION__, uvd->video_endp);
1774	return 0;
1775}
1776
1777/*
1778 * usbvideo_StopDataPump()
1779 *
1780 * This procedure stops streaming and deallocates URBs. Then it
1781 * activates zero-bandwidth alt. setting of the video interface.
1782 *
1783 * History:
1784 * 22-Jan-2000 Corrected order of actions to work after surprise removal.
1785 * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
1786 */
1787static void usbvideo_StopDataPump(struct uvd *uvd)
1788{
1789	int i, j;
1790
1791	if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
1792		return;
1793
1794	if (uvd->debug > 1)
1795		info("%s($%p)", __FUNCTION__, uvd);
1796
1797	/* Unschedule all of the iso td's */
1798	for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1799		usb_kill_urb(uvd->sbuf[i].urb);
1800	}
1801	if (uvd->debug > 1)
1802		info("%s: streaming=0", __FUNCTION__);
1803	uvd->streaming = 0;
1804
1805	if (!uvd->remove_pending) {
1806		/* Invoke minidriver's magic to stop the camera */
1807		if (VALID_CALLBACK(uvd, videoStop))
1808			GET_CALLBACK(uvd, videoStop)(uvd);
1809		else
1810			err("%s: videoStop not set", __FUNCTION__);
1811
1812		/* Set packet size to 0 */
1813		j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
1814		if (j < 0) {
1815			err("%s: usb_set_interface() error %d.", __FUNCTION__, j);
1816			uvd->last_error = j;
1817		}
1818	}
1819}
1820
1821/*
1822 * usbvideo_NewFrame()
1823 *
1824 * History:
1825 * 29-Mar-00 Added copying of previous frame into the current one.
1826 * 6-Aug-00  Added model 3 video sizes, removed redundant width, height.
1827 */
1828static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
1829{
1830	struct usbvideo_frame *frame;
1831	int n;
1832
1833	if (uvd->debug > 1)
1834		info("usbvideo_NewFrame($%p,%d.)", uvd, framenum);
1835
1836	/* If we're not grabbing a frame right now and the other frame is */
1837	/*  ready to be grabbed into, then use it instead */
1838	if (uvd->curframe != -1)
1839		return 0;
1840
1841	/* If necessary we adjust picture settings between frames */
1842	if (!uvd->settingsAdjusted) {
1843		if (VALID_CALLBACK(uvd, adjustPicture))
1844			GET_CALLBACK(uvd, adjustPicture)(uvd);
1845		uvd->settingsAdjusted = 1;
1846	}
1847
1848	n = (framenum + 1) % USBVIDEO_NUMFRAMES;
1849	if (uvd->frame[n].frameState == FrameState_Ready)
1850		framenum = n;
1851
1852	frame = &uvd->frame[framenum];
1853
1854	frame->frameState = FrameState_Grabbing;
1855	frame->scanstate = ScanState_Scanning;
1856	frame->seqRead_Length = 0;	/* Accumulated in xxx_parse_data() */
1857	frame->deinterlace = Deinterlace_None;
1858	frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
1859	uvd->curframe = framenum;
1860
1861	/*
1862	 * Normally we would want to copy previous frame into the current one
1863	 * before we even start filling it with data; this allows us to stop
1864	 * filling at any moment; top portion of the frame will be new and
1865	 * bottom portion will stay as it was in previous frame. If we don't
1866	 * do that then missing chunks of video stream will result in flickering
1867	 * portions of old data whatever it was before.
1868	 *
1869	 * If we choose not to copy previous frame (to, for example, save few
1870	 * bus cycles - the frame can be pretty large!) then we have an option
1871	 * to clear the frame before using. If we experience losses in this
1872	 * mode then missing picture will be black (no flickering).
1873	 *
1874	 * Finally, if user chooses not to clean the current frame before
1875	 * filling it with data then the old data will be visible if we fail
1876	 * to refill entire frame with new data.
1877	 */
1878	if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
1879		/* This copies previous frame into this one to mask losses */
1880		int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
1881		memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
1882	} else {
1883		if (uvd->flags & FLAGS_CLEAN_FRAMES) {
1884			/* This provides a "clean" frame but slows things down */
1885			memset(frame->data, 0, uvd->max_frame_size);
1886		}
1887	}
1888	return 0;
1889}
1890
1891/*
1892 * usbvideo_CollectRawData()
1893 *
1894 * This procedure can be used instead of 'processData' callback if you
1895 * only want to dump the raw data from the camera into the output
1896 * device (frame buffer). You can look at it with V4L client, but the
1897 * image will be unwatchable. The main purpose of this code and of the
1898 * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
1899 * new, unknown cameras. This procedure will be automatically invoked
1900 * instead of the specified callback handler when uvd->flags has bit
1901 * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
1902 * based on usbvideo can use this feature at any time.
1903 */
1904static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
1905{
1906	int n;
1907
1908	assert(uvd != NULL);
1909	assert(frame != NULL);
1910
1911	/* Try to move data from queue into frame buffer */
1912	n = RingQueue_GetLength(&uvd->dp);
1913	if (n > 0) {
1914		int m;
1915		/* See how much space we have left */
1916		m = uvd->max_frame_size - frame->seqRead_Length;
1917		if (n > m)
1918			n = m;
1919		/* Now move that much data into frame buffer */
1920		RingQueue_Dequeue(
1921			&uvd->dp,
1922			frame->data + frame->seqRead_Length,
1923			m);
1924		frame->seqRead_Length += m;
1925	}
1926	/* See if we filled the frame */
1927	if (frame->seqRead_Length >= uvd->max_frame_size) {
1928		frame->frameState = FrameState_Done;
1929		uvd->curframe = -1;
1930		uvd->stats.frame_num++;
1931	}
1932}
1933
1934static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
1935{
1936	struct usbvideo_frame *frame = &uvd->frame[frameNum];
1937
1938	if (uvd->debug >= 2)
1939		info("%s($%p,%d.)", __FUNCTION__, uvd, frameNum);
1940
1941	switch (frame->frameState) {
1942	case FrameState_Unused:
1943		if (uvd->debug >= 2)
1944			info("%s: FrameState_Unused", __FUNCTION__);
1945		return -EINVAL;
1946	case FrameState_Ready:
1947	case FrameState_Grabbing:
1948	case FrameState_Error:
1949	{
1950		int ntries, signalPending;
1951	redo:
1952		if (!CAMERA_IS_OPERATIONAL(uvd)) {
1953			if (uvd->debug >= 2)
1954				info("%s: Camera is not operational (1)", __FUNCTION__);
1955			return -EIO;
1956		}
1957		ntries = 0;
1958		do {
1959			RingQueue_InterruptibleSleepOn(&uvd->dp);
1960			signalPending = signal_pending(current);
1961			if (!CAMERA_IS_OPERATIONAL(uvd)) {
1962				if (uvd->debug >= 2)
1963					info("%s: Camera is not operational (2)", __FUNCTION__);
1964				return -EIO;
1965			}
1966			assert(uvd->fbuf != NULL);
1967			if (signalPending) {
1968				if (uvd->debug >= 2)
1969					info("%s: Signal=$%08x", __FUNCTION__, signalPending);
1970				if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
1971					usbvideo_TestPattern(uvd, 1, 0);
1972					uvd->curframe = -1;
1973					uvd->stats.frame_num++;
1974					if (uvd->debug >= 2)
1975						info("%s: Forced test pattern screen", __FUNCTION__);
1976					return 0;
1977				} else {
1978					/* Standard answer: Interrupted! */
1979					if (uvd->debug >= 2)
1980						info("%s: Interrupted!", __FUNCTION__);
1981					return -EINTR;
1982				}
1983			} else {
1984				/* No signals - we just got new data in dp queue */
1985				if (uvd->flags & FLAGS_NO_DECODING)
1986					usbvideo_CollectRawData(uvd, frame);
1987				else if (VALID_CALLBACK(uvd, processData))
1988					GET_CALLBACK(uvd, processData)(uvd, frame);
1989				else
1990					err("%s: processData not set", __FUNCTION__);
1991			}
1992		} while (frame->frameState == FrameState_Grabbing);
1993		if (uvd->debug >= 2) {
1994			info("%s: Grabbing done; state=%d. (%lu. bytes)",
1995			     __FUNCTION__, frame->frameState, frame->seqRead_Length);
1996		}
1997		if (frame->frameState == FrameState_Error) {
1998			int ret = usbvideo_NewFrame(uvd, frameNum);
1999			if (ret < 0) {
2000				err("%s: usbvideo_NewFrame() failed (%d.)", __FUNCTION__, ret);
2001				return ret;
2002			}
2003			goto redo;
2004		}
2005		/* Note that we fall through to meet our destiny below */
2006	}
2007	case FrameState_Done:
2008		/*
2009		 * Do all necessary postprocessing of data prepared in
2010		 * "interrupt" code and the collecting code above. The
2011		 * frame gets marked as FrameState_Done by queue parsing code.
2012		 * This status means that we collected enough data and
2013		 * most likely processed it as we went through. However
2014		 * the data may need postprocessing, such as deinterlacing
2015		 * or picture adjustments implemented in software (horror!)
2016		 *
2017		 * As soon as the frame becomes "final" it gets promoted to
2018		 * FrameState_Done_Hold status where it will remain until the
2019		 * caller consumed all the video data from the frame. Then
2020		 * the empty shell of ex-frame is thrown out for dogs to eat.
2021		 * But we, worried about pets, will recycle the frame!
2022		 */
2023		uvd->stats.frame_num++;
2024		if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
2025			if (VALID_CALLBACK(uvd, postProcess))
2026				GET_CALLBACK(uvd, postProcess)(uvd, frame);
2027			if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
2028				usbvideo_SoftwareContrastAdjustment(uvd, frame);
2029		}
2030		frame->frameState = FrameState_Done_Hold;
2031		if (uvd->debug >= 2)
2032			info("%s: Entered FrameState_Done_Hold state.", __FUNCTION__);
2033		return 0;
2034
2035	case FrameState_Done_Hold:
2036		/*
2037		 * We stay in this state indefinitely until someone external,
2038		 * like ioctl() or read() call finishes digesting the frame
2039		 * data. Then it will mark the frame as FrameState_Unused and
2040		 * it will be released back into the wild to roam freely.
2041		 */
2042		if (uvd->debug >= 2)
2043			info("%s: FrameState_Done_Hold state.", __FUNCTION__);
2044		return 0;
2045	}
2046
2047	/* Catch-all for other cases. We shall not be here. */
2048	err("%s: Invalid state %d.", __FUNCTION__, frame->frameState);
2049	frame->frameState = FrameState_Unused;
2050	return 0;
2051}
2052
2053/*
2054 * usbvideo_DeinterlaceFrame()
2055 *
2056 * This procedure deinterlaces the given frame. Some cameras produce
2057 * only half of scanlines - sometimes only even lines, sometimes only
2058 * odd lines. The deinterlacing method is stored in frame->deinterlace
2059 * variable.
2060 *
2061 * Here we scan the frame vertically and replace missing scanlines with
2062 * average between surrounding ones - before and after. If we have no
2063 * line above then we just copy next line. Similarly, if we need to
2064 * create a last line then preceding line is used.
2065 */
2066void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
2067{
2068	if ((uvd == NULL) || (frame == NULL))
2069		return;
2070
2071	if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
2072	    (frame->deinterlace == Deinterlace_FillOddLines))
2073	{
2074		const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2075		int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
2076
2077		for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
2078			const unsigned char *fs1, *fs2;
2079			unsigned char *fd;
2080			int ip, in, j;	/* Previous and next lines */
2081
2082			/*
2083			 * Need to average lines before and after 'i'.
2084			 * If we go out of bounds seeking those lines then
2085			 * we point back to existing line.
2086			 */
2087			ip = i - 1;	/* First, get rough numbers */
2088			in = i + 1;
2089
2090			/* Now validate */
2091			if (ip < 0)
2092				ip = in;
2093			if (in >= VIDEOSIZE_Y(frame->request))
2094				in = ip;
2095
2096			/* Sanity check */
2097			if ((ip < 0) || (in < 0) ||
2098			    (ip >= VIDEOSIZE_Y(frame->request)) ||
2099			    (in >= VIDEOSIZE_Y(frame->request)))
2100			{
2101				err("Error: ip=%d. in=%d. req.height=%ld.",
2102				    ip, in, VIDEOSIZE_Y(frame->request));
2103				break;
2104			}
2105
2106			/* Now we need to average lines 'ip' and 'in' to produce line 'i' */
2107			fs1 = frame->data + (v4l_linesize * ip);
2108			fs2 = frame->data + (v4l_linesize * in);
2109			fd = frame->data + (v4l_linesize * i);
2110
2111			/* Average lines around destination */
2112			for (j=0; j < v4l_linesize; j++) {
2113				fd[j] = (unsigned char)((((unsigned) fs1[j]) +
2114							 ((unsigned)fs2[j])) >> 1);
2115			}
2116		}
2117	}
2118
2119	/* Optionally display statistics on the screen */
2120	if (uvd->flags & FLAGS_OVERLAY_STATS)
2121		usbvideo_OverlayStats(uvd, frame);
2122}
2123
2124EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
2125
2126/*
2127 * usbvideo_SoftwareContrastAdjustment()
2128 *
2129 * This code adjusts the contrast of the frame, assuming RGB24 format.
2130 * As most software image processing, this job is CPU-intensive.
2131 * Get a camera that supports hardware adjustment!
2132 *
2133 * History:
2134 * 09-Feb-2001  Created.
2135 */
2136static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
2137						struct usbvideo_frame *frame)
2138{
2139	int i, j, v4l_linesize;
2140	signed long adj;
2141	const int ccm = 128; /* Color correction median - see below */
2142
2143	if ((uvd == NULL) || (frame == NULL)) {
2144		err("%s: Illegal call.", __FUNCTION__);
2145		return;
2146	}
2147	adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
2148	RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
2149	if (adj == 0) {
2150		/* In rare case of no adjustment */
2151		return;
2152	}
2153	v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2154	for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
2155		unsigned char *fd = frame->data + (v4l_linesize * i);
2156		for (j=0; j < v4l_linesize; j++) {
2157			signed long v = (signed long) fd[j];
2158			/* Magnify up to 2 times, reduce down to zero */
2159			v = 128 + ((ccm + adj) * (v - 128)) / ccm;
2160			RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
2161			fd[j] = (unsigned char) v;
2162		}
2163	}
2164}
2165
2166MODULE_LICENSE("GPL");
2167