1/*
2 * Zoran zr36057/zr36067 PCI controller driver, for the
3 * Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
4 * Media Labs LML33/LML33R10.
5 *
6 * Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
7 *
8 * Changes for BUZ by Wolfgang Scherr <scherr@net4you.net>
9 *
10 * Changes for DC10/DC30 by Laurent Pinchart <laurent.pinchart@skynet.be>
11 *
12 * Changes for LML33R10 by Maxim Yevtyushkin <max@linuxmedialabs.com>
13 *
14 * Changes for videodev2/v4l2 by Ronald Bultje <rbultje@ronald.bitfreak.net>
15 *
16 * Based on
17 *
18 * Miro DC10 driver
19 * Copyright (C) 1999 Wolfgang Scherr <scherr@net4you.net>
20 *
21 * Iomega Buz driver version 1.0
22 * Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
23 *
24 * buz.0.0.3
25 * Copyright (C) 1998 Dave Perks <dperks@ibm.net>
26 *
27 * bttv - Bt848 frame grabber driver
28 * Copyright (C) 1996,97,98 Ralph  Metzler (rjkm@thp.uni-koeln.de)
29 *                        & Marcus Metzler (mocm@thp.uni-koeln.de)
30 *
31 *
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 2 of the License, or
35 * (at your option) any later version.
36 *
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40 * GNU General Public License for more details.
41 *
42 * You should have received a copy of the GNU General Public License
43 * along with this program; if not, write to the Free Software
44 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
45 */
46
47#include <linux/version.h>
48#include <linux/init.h>
49#include <linux/module.h>
50#include <linux/delay.h>
51#include <linux/slab.h>
52#include <linux/pci.h>
53#include <linux/vmalloc.h>
54#include <linux/wait.h>
55#include <linux/byteorder/generic.h>
56
57#include <linux/interrupt.h>
58#include <linux/i2c.h>
59#include <linux/i2c-algo-bit.h>
60
61#include <linux/spinlock.h>
62#define     MAP_NR(x)       virt_to_page(x)
63#define     ZORAN_HARDWARE  VID_HARDWARE_ZR36067
64#define     ZORAN_VID_TYPE  ( \
65				VID_TYPE_CAPTURE | \
66				VID_TYPE_OVERLAY | \
67				VID_TYPE_CLIPPING | \
68				VID_TYPE_FRAMERAM | \
69				VID_TYPE_SCALES | \
70				VID_TYPE_MJPEG_DECODER | \
71				VID_TYPE_MJPEG_ENCODER \
72			     )
73
74#include <linux/videodev.h>
75#include <media/v4l2-common.h>
76#include "videocodec.h"
77
78#include <asm/io.h>
79#include <asm/uaccess.h>
80#include <linux/proc_fs.h>
81
82#include <linux/video_decoder.h>
83#include <linux/video_encoder.h>
84#include <linux/mutex.h>
85#include "zoran.h"
86#include "zoran_device.h"
87#include "zoran_card.h"
88
89#ifdef CONFIG_VIDEO_V4L2
90	/* we declare some card type definitions here, they mean
91	 * the same as the v4l1 ZORAN_VID_TYPE above, except it's v4l2 */
92#define ZORAN_V4L2_VID_FLAGS ( \
93				V4L2_CAP_STREAMING |\
94				V4L2_CAP_VIDEO_CAPTURE |\
95				V4L2_CAP_VIDEO_OUTPUT |\
96				V4L2_CAP_VIDEO_OVERLAY \
97			      )
98#endif
99
100#include <asm/byteorder.h>
101
102const struct zoran_format zoran_formats[] = {
103	{
104		.name = "15-bit RGB",
105		.palette = VIDEO_PALETTE_RGB555,
106#ifdef CONFIG_VIDEO_V4L2
107#ifdef __LITTLE_ENDIAN
108		.fourcc = V4L2_PIX_FMT_RGB555,
109#else
110		.fourcc = V4L2_PIX_FMT_RGB555X,
111#endif
112		.colorspace = V4L2_COLORSPACE_SRGB,
113#endif
114		.depth = 15,
115		.flags = ZORAN_FORMAT_CAPTURE |
116			 ZORAN_FORMAT_OVERLAY,
117	}, {
118		.name = "16-bit RGB",
119		.palette = VIDEO_PALETTE_RGB565,
120#ifdef CONFIG_VIDEO_V4L2
121#ifdef __LITTLE_ENDIAN
122		.fourcc = V4L2_PIX_FMT_RGB565,
123#else
124		.fourcc = V4L2_PIX_FMT_RGB565X,
125#endif
126		.colorspace = V4L2_COLORSPACE_SRGB,
127#endif
128		.depth = 16,
129		.flags = ZORAN_FORMAT_CAPTURE |
130			 ZORAN_FORMAT_OVERLAY,
131	}, {
132		.name = "24-bit RGB",
133		.palette = VIDEO_PALETTE_RGB24,
134#ifdef CONFIG_VIDEO_V4L2
135#ifdef __LITTLE_ENDIAN
136		.fourcc = V4L2_PIX_FMT_BGR24,
137#else
138		.fourcc = V4L2_PIX_FMT_RGB24,
139#endif
140		.colorspace = V4L2_COLORSPACE_SRGB,
141#endif
142		.depth = 24,
143		.flags = ZORAN_FORMAT_CAPTURE |
144			 ZORAN_FORMAT_OVERLAY,
145	}, {
146		.name = "32-bit RGB",
147		.palette = VIDEO_PALETTE_RGB32,
148#ifdef CONFIG_VIDEO_V4L2
149#ifdef __LITTLE_ENDIAN
150		.fourcc = V4L2_PIX_FMT_BGR32,
151#else
152		.fourcc = V4L2_PIX_FMT_RGB32,
153#endif
154		.colorspace = V4L2_COLORSPACE_SRGB,
155#endif
156		.depth = 32,
157		.flags = ZORAN_FORMAT_CAPTURE |
158			 ZORAN_FORMAT_OVERLAY,
159	}, {
160		.name = "4:2:2, packed, YUYV",
161		.palette = VIDEO_PALETTE_YUV422,
162#ifdef CONFIG_VIDEO_V4L2
163		.fourcc = V4L2_PIX_FMT_YUYV,
164		.colorspace = V4L2_COLORSPACE_SMPTE170M,
165#endif
166		.depth = 16,
167		.flags = ZORAN_FORMAT_CAPTURE |
168			 ZORAN_FORMAT_OVERLAY,
169	}, {
170		.name = "Hardware-encoded Motion-JPEG",
171		.palette = -1,
172#ifdef CONFIG_VIDEO_V4L2
173		.fourcc = V4L2_PIX_FMT_MJPEG,
174		.colorspace = V4L2_COLORSPACE_SMPTE170M,
175#endif
176		.depth = 0,
177		.flags = ZORAN_FORMAT_CAPTURE |
178			 ZORAN_FORMAT_PLAYBACK |
179			 ZORAN_FORMAT_COMPRESSED,
180	}
181};
182static const int zoran_num_formats =
183    (sizeof(zoran_formats) / sizeof(struct zoran_format));
184
185// RJ: Test only - want to test BUZ_USE_HIMEM even when CONFIG_BIGPHYS_AREA is defined
186#if !defined(CONFIG_BIGPHYS_AREA)
187//#undef CONFIG_BIGPHYS_AREA
188#define BUZ_USE_HIMEM
189#endif
190
191#if defined(CONFIG_BIGPHYS_AREA)
192#   include <linux/bigphysarea.h>
193#endif
194
195extern int *zr_debug;
196
197#define dprintk(num, format, args...) \
198	do { \
199		if (*zr_debug >= num) \
200			printk(format, ##args);	\
201	} while (0)
202
203extern int v4l_nbufs;
204extern int v4l_bufsize;
205extern int jpg_nbufs;
206extern int jpg_bufsize;
207extern int pass_through;
208
209static int lock_norm = 0;	/* 1=Don't change TV standard (norm) */
210module_param(lock_norm, int, 0);
211MODULE_PARM_DESC(lock_norm, "Users can't change norm");
212
213#ifdef CONFIG_VIDEO_V4L2
214	/* small helper function for calculating buffersizes for v4l2
215	 * we calculate the nearest higher power-of-two, which
216	 * will be the recommended buffersize */
217static __u32
218zoran_v4l2_calc_bufsize (struct zoran_jpg_settings *settings)
219{
220	__u8 div = settings->VerDcm * settings->HorDcm * settings->TmpDcm;
221	__u32 num = (1024 * 512) / (div);
222	__u32 result = 2;
223
224	num--;
225	while (num) {
226		num >>= 1;
227		result <<= 1;
228	}
229
230	if (result > jpg_bufsize)
231		return jpg_bufsize;
232	if (result < 8192)
233		return 8192;
234	return result;
235}
236#endif
237
238/* forward references */
239static void v4l_fbuffer_free(struct file *file);
240static void jpg_fbuffer_free(struct file *file);
241
242/*
243 *   Allocate the V4L grab buffers
244 *
245 *   These have to be pysically contiguous.
246 *   If v4l_bufsize <= MAX_KMALLOC_MEM we use kmalloc
247 *   else we try to allocate them with bigphysarea_alloc_pages
248 *   if the bigphysarea patch is present in the kernel,
249 *   else we try to use high memory (if the user has bootet
250 *   Linux with the necessary memory left over).
251 */
252
253#if defined(BUZ_USE_HIMEM) && !defined(CONFIG_BIGPHYS_AREA)
254static unsigned long
255get_high_mem (unsigned long size)
256{
257/*
258 * Check if there is usable memory at the end of Linux memory
259 * of at least size. Return the physical address of this memory,
260 * return 0 on failure.
261 *
262 * The idea is from Alexandro Rubini's book "Linux device drivers".
263 * The driver from him which is downloadable from O'Reilly's
264 * web site misses the "virt_to_phys(high_memory)" part
265 * (and therefore doesn't work at all - at least with 2.2.x kernels).
266 *
267 * It should be unnecessary to mention that THIS IS DANGEROUS,
268 * if more than one driver at a time has the idea to use this memory!!!!
269 */
270
271	volatile unsigned char __iomem *mem;
272	unsigned char c;
273	unsigned long hi_mem_ph;
274	unsigned long i;
275
276	/* Map the high memory to user space */
277
278	hi_mem_ph = virt_to_phys(high_memory);
279
280	mem = ioremap(hi_mem_ph, size);
281	if (!mem) {
282		dprintk(1,
283			KERN_ERR "%s: get_high_mem() - ioremap failed\n",
284			ZORAN_NAME);
285		return 0;
286	}
287
288	for (i = 0; i < size; i++) {
289		/* Check if it is memory */
290		c = i & 0xff;
291		writeb(c, mem + i);
292		if (readb(mem + i) != c)
293			break;
294		c = 255 - c;
295		writeb(c, mem + i);
296		if (readb(mem + i) != c)
297			break;
298		writeb(0, mem + i);	/* zero out memory */
299
300		/* give the kernel air to breath */
301		if ((i & 0x3ffff) == 0x3ffff)
302			schedule();
303	}
304
305	iounmap(mem);
306
307	if (i != size) {
308		dprintk(1,
309			KERN_ERR
310			"%s: get_high_mem() - requested %lu, avail %lu\n",
311			ZORAN_NAME, size, i);
312		return 0;
313	}
314
315	return hi_mem_ph;
316}
317#endif
318
319static int
320v4l_fbuffer_alloc (struct file *file)
321{
322	struct zoran_fh *fh = file->private_data;
323	struct zoran *zr = fh->zr;
324	int i, off;
325	unsigned char *mem;
326#if defined(BUZ_USE_HIMEM) && !defined(CONFIG_BIGPHYS_AREA)
327	unsigned long pmem = 0;
328#endif
329
330	/* we might have old buffers lying around... */
331	if (fh->v4l_buffers.ready_to_be_freed) {
332		v4l_fbuffer_free(file);
333	}
334
335	for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
336		if (fh->v4l_buffers.buffer[i].fbuffer)
337			dprintk(2,
338				KERN_WARNING
339				"%s: v4l_fbuffer_alloc() - buffer %d allready allocated!?\n",
340				ZR_DEVNAME(zr), i);
341
342		//udelay(20);
343		if (fh->v4l_buffers.buffer_size <= MAX_KMALLOC_MEM) {
344			/* Use kmalloc */
345
346			mem =
347			    (unsigned char *) kmalloc(fh->v4l_buffers.
348						      buffer_size,
349						      GFP_KERNEL);
350			if (mem == 0) {
351				dprintk(1,
352					KERN_ERR
353					"%s: v4l_fbuffer_alloc() - kmalloc for V4L buf %d failed\n",
354					ZR_DEVNAME(zr), i);
355				v4l_fbuffer_free(file);
356				return -ENOBUFS;
357			}
358			fh->v4l_buffers.buffer[i].fbuffer = mem;
359			fh->v4l_buffers.buffer[i].fbuffer_phys =
360			    virt_to_phys(mem);
361			fh->v4l_buffers.buffer[i].fbuffer_bus =
362			    virt_to_bus(mem);
363			for (off = 0; off < fh->v4l_buffers.buffer_size;
364			     off += PAGE_SIZE)
365				SetPageReserved(MAP_NR(mem + off));
366			dprintk(4,
367				KERN_INFO
368				"%s: v4l_fbuffer_alloc() - V4L frame %d mem 0x%lx (bus: 0x%lx)\n",
369				ZR_DEVNAME(zr), i, (unsigned long) mem,
370				virt_to_bus(mem));
371		} else {
372#if defined(CONFIG_BIGPHYS_AREA)
373			/* Use bigphysarea_alloc_pages */
374
375			int n =
376			    (fh->v4l_buffers.buffer_size + PAGE_SIZE -
377			     1) / PAGE_SIZE;
378
379			mem =
380			    (unsigned char *) bigphysarea_alloc_pages(n, 0,
381								      GFP_KERNEL);
382			if (mem == 0) {
383				dprintk(1,
384					KERN_ERR
385					"%s: v4l_fbuffer_alloc() - bigphysarea_alloc_pages for V4L buf %d failed\n",
386					ZR_DEVNAME(zr), i);
387				v4l_fbuffer_free(file);
388				return -ENOBUFS;
389			}
390			fh->v4l_buffers.buffer[i].fbuffer = mem;
391			fh->v4l_buffers.buffer[i].fbuffer_phys =
392			    virt_to_phys(mem);
393			fh->v4l_buffers.buffer[i].fbuffer_bus =
394			    virt_to_bus(mem);
395			dprintk(4,
396				KERN_INFO
397				"%s: Bigphysarea frame %d mem 0x%x (bus: 0x%x)\n",
398				ZR_DEVNAME(zr), i, (unsigned) mem,
399				(unsigned) virt_to_bus(mem));
400
401			/* Zero out the allocated memory */
402			memset(fh->v4l_buffers.buffer[i].fbuffer, 0,
403			       fh->v4l_buffers.buffer_size);
404#elif defined(BUZ_USE_HIMEM)
405
406			/* Use high memory which has been left at boot time */
407
408			/* Ok., Ok. this is an evil hack - we make
409			 * the assumption that physical addresses are
410			 * the same as bus addresses (true at least
411			 * for Intel processors). The whole method of
412			 * obtaining and using this memory is not very
413			 * nice - but I hope it saves some poor users
414			 * from kernel hacking, which might have even
415			 * more evil results */
416
417			if (i == 0) {
418				int size =
419				    fh->v4l_buffers.num_buffers *
420				    fh->v4l_buffers.buffer_size;
421
422				pmem = get_high_mem(size);
423				if (pmem == 0) {
424					dprintk(1,
425						KERN_ERR
426						"%s: v4l_fbuffer_alloc() - get_high_mem (size = %d KB) for V4L bufs failed\n",
427						ZR_DEVNAME(zr), size >> 10);
428					return -ENOBUFS;
429				}
430				fh->v4l_buffers.buffer[0].fbuffer = NULL;
431				fh->v4l_buffers.buffer[0].fbuffer_phys = pmem;
432				fh->v4l_buffers.buffer[0].fbuffer_bus = pmem;
433				dprintk(4,
434					KERN_INFO
435					"%s: v4l_fbuffer_alloc() - using %d KB high memory\n",
436					ZR_DEVNAME(zr), size >> 10);
437			} else {
438				fh->v4l_buffers.buffer[i].fbuffer = NULL;
439				fh->v4l_buffers.buffer[i].fbuffer_phys =
440				    pmem + i * fh->v4l_buffers.buffer_size;
441				fh->v4l_buffers.buffer[i].fbuffer_bus =
442				    pmem + i * fh->v4l_buffers.buffer_size;
443			}
444#else
445			/* No bigphysarea present, usage of high memory disabled,
446			 * but user wants buffers of more than MAX_KMALLOC_MEM */
447			dprintk(1,
448				KERN_ERR
449				"%s: v4l_fbuffer_alloc() - no bigphysarea_patch present, usage of high memory disabled,\n",
450				ZR_DEVNAME(zr));
451			dprintk(1,
452				KERN_ERR
453				"%s: v4l_fbuffer_alloc() - sorry, could not allocate %d V4L buffers of size %d KB.\n",
454				ZR_DEVNAME(zr), fh->v4l_buffers.num_buffers,
455				fh->v4l_buffers.buffer_size >> 10);
456			return -ENOBUFS;
457#endif
458		}
459	}
460
461	fh->v4l_buffers.allocated = 1;
462
463	return 0;
464}
465
466/* free the V4L grab buffers */
467static void
468v4l_fbuffer_free (struct file *file)
469{
470	struct zoran_fh *fh = file->private_data;
471	struct zoran *zr = fh->zr;
472	int i, off;
473	unsigned char *mem;
474
475	dprintk(4, KERN_INFO "%s: v4l_fbuffer_free()\n", ZR_DEVNAME(zr));
476
477	for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
478		if (!fh->v4l_buffers.buffer[i].fbuffer)
479			continue;
480
481		if (fh->v4l_buffers.buffer_size <= MAX_KMALLOC_MEM) {
482			mem = fh->v4l_buffers.buffer[i].fbuffer;
483			for (off = 0; off < fh->v4l_buffers.buffer_size;
484			     off += PAGE_SIZE)
485				ClearPageReserved(MAP_NR(mem + off));
486			kfree((void *) fh->v4l_buffers.buffer[i].fbuffer);
487		}
488#if defined(CONFIG_BIGPHYS_AREA)
489		else
490			bigphysarea_free_pages((void *) fh->v4l_buffers.
491					       buffer[i].fbuffer);
492#endif
493		fh->v4l_buffers.buffer[i].fbuffer = NULL;
494	}
495
496	fh->v4l_buffers.allocated = 0;
497	fh->v4l_buffers.ready_to_be_freed = 0;
498}
499
500/*
501 *   Allocate the MJPEG grab buffers.
502 *
503 *   If the requested buffer size is smaller than MAX_KMALLOC_MEM,
504 *   kmalloc is used to request a physically contiguous area,
505 *   else we allocate the memory in framgents with get_zeroed_page.
506 *
507 *   If a Natoma chipset is present and this is a revision 1 zr36057,
508 *   each MJPEG buffer needs to be physically contiguous.
509 *   (RJ: This statement is from Dave Perks' original driver,
510 *   I could never check it because I have a zr36067)
511 *   The driver cares about this because it reduces the buffer
512 *   size to MAX_KMALLOC_MEM in that case (which forces contiguous allocation).
513 *
514 *   RJ: The contents grab buffers needs never be accessed in the driver.
515 *       Therefore there is no need to allocate them with vmalloc in order
516 *       to get a contiguous virtual memory space.
517 *       I don't understand why many other drivers first allocate them with
518 *       vmalloc (which uses internally also get_zeroed_page, but delivers you
519 *       virtual addresses) and then again have to make a lot of efforts
520 *       to get the physical address.
521 *
522 *   Ben Capper:
523 *       On big-endian architectures (such as ppc) some extra steps
524 *       are needed. When reading and writing to the stat_com array
525 *       and fragment buffers, the device expects to see little-
526 *       endian values. The use of cpu_to_le32() and le32_to_cpu()
527 *       in this function (and one or two others in zoran_device.c)
528 *       ensure that these values are always stored in little-endian
529 *       form, regardless of architecture. The zr36057 does Very Bad
530 *       Things on big endian architectures if the stat_com array
531 *       and fragment buffers are not little-endian.
532 */
533
534static int
535jpg_fbuffer_alloc (struct file *file)
536{
537	struct zoran_fh *fh = file->private_data;
538	struct zoran *zr = fh->zr;
539	int i, j, off;
540	unsigned long mem;
541
542	/* we might have old buffers lying around */
543	if (fh->jpg_buffers.ready_to_be_freed) {
544		jpg_fbuffer_free(file);
545	}
546
547	for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
548		if (fh->jpg_buffers.buffer[i].frag_tab)
549			dprintk(2,
550				KERN_WARNING
551				"%s: jpg_fbuffer_alloc() - buffer %d allready allocated!?\n",
552				ZR_DEVNAME(zr), i);
553
554		/* Allocate fragment table for this buffer */
555
556		mem = get_zeroed_page(GFP_KERNEL);
557		if (mem == 0) {
558			dprintk(1,
559				KERN_ERR
560				"%s: jpg_fbuffer_alloc() - get_zeroed_page (frag_tab) failed for buffer %d\n",
561				ZR_DEVNAME(zr), i);
562			jpg_fbuffer_free(file);
563			return -ENOBUFS;
564		}
565		fh->jpg_buffers.buffer[i].frag_tab = (u32 *) mem;
566		fh->jpg_buffers.buffer[i].frag_tab_bus =
567		    virt_to_bus((void *) mem);
568
569		//if (alloc_contig) {
570		if (fh->jpg_buffers.need_contiguous) {
571			mem =
572			    (unsigned long) kmalloc(fh->jpg_buffers.
573						    buffer_size,
574						    GFP_KERNEL);
575			if (mem == 0) {
576				dprintk(1,
577					KERN_ERR
578					"%s: jpg_fbuffer_alloc() - kmalloc failed for buffer %d\n",
579					ZR_DEVNAME(zr), i);
580				jpg_fbuffer_free(file);
581				return -ENOBUFS;
582			}
583			fh->jpg_buffers.buffer[i].frag_tab[0] =
584			    cpu_to_le32(virt_to_bus((void *) mem));
585			fh->jpg_buffers.buffer[i].frag_tab[1] =
586			    cpu_to_le32(((fh->jpg_buffers.buffer_size / 4) << 1) | 1);
587			for (off = 0; off < fh->jpg_buffers.buffer_size;
588			     off += PAGE_SIZE)
589				SetPageReserved(MAP_NR(mem + off));
590		} else {
591			/* jpg_bufsize is allreay page aligned */
592			for (j = 0;
593			     j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
594			     j++) {
595				mem = get_zeroed_page(GFP_KERNEL);
596				if (mem == 0) {
597					dprintk(1,
598						KERN_ERR
599						"%s: jpg_fbuffer_alloc() - get_zeroed_page failed for buffer %d\n",
600						ZR_DEVNAME(zr), i);
601					jpg_fbuffer_free(file);
602					return -ENOBUFS;
603				}
604
605				fh->jpg_buffers.buffer[i].frag_tab[2 * j] =
606				    cpu_to_le32(virt_to_bus((void *) mem));
607				fh->jpg_buffers.buffer[i].frag_tab[2 * j +
608								   1] =
609				    cpu_to_le32((PAGE_SIZE / 4) << 1);
610				SetPageReserved(MAP_NR(mem));
611			}
612
613			fh->jpg_buffers.buffer[i].frag_tab[2 * j - 1] |= cpu_to_le32(1);
614		}
615	}
616
617	dprintk(4,
618		KERN_DEBUG "%s: jpg_fbuffer_alloc() - %d KB allocated\n",
619		ZR_DEVNAME(zr),
620		(fh->jpg_buffers.num_buffers *
621		 fh->jpg_buffers.buffer_size) >> 10);
622
623	fh->jpg_buffers.allocated = 1;
624
625	return 0;
626}
627
628/* free the MJPEG grab buffers */
629static void
630jpg_fbuffer_free (struct file *file)
631{
632	struct zoran_fh *fh = file->private_data;
633	struct zoran *zr = fh->zr;
634	int i, j, off;
635	unsigned char *mem;
636
637	dprintk(4, KERN_DEBUG "%s: jpg_fbuffer_free()\n", ZR_DEVNAME(zr));
638
639	for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
640		if (!fh->jpg_buffers.buffer[i].frag_tab)
641			continue;
642
643		//if (alloc_contig) {
644		if (fh->jpg_buffers.need_contiguous) {
645			if (fh->jpg_buffers.buffer[i].frag_tab[0]) {
646				mem = (unsigned char *) bus_to_virt(le32_to_cpu(
647					fh->jpg_buffers.buffer[i].frag_tab[0]));
648				for (off = 0;
649				     off < fh->jpg_buffers.buffer_size;
650				     off += PAGE_SIZE)
651					ClearPageReserved(MAP_NR
652							  (mem + off));
653				kfree(mem);
654				fh->jpg_buffers.buffer[i].frag_tab[0] = 0;
655				fh->jpg_buffers.buffer[i].frag_tab[1] = 0;
656			}
657		} else {
658			for (j = 0;
659			     j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
660			     j++) {
661				if (!fh->jpg_buffers.buffer[i].
662				    frag_tab[2 * j])
663					break;
664				ClearPageReserved(MAP_NR
665						  (bus_to_virt
666						   (le32_to_cpu
667						    (fh->jpg_buffers.
668						     buffer[i].frag_tab[2 *
669								       j]))));
670				free_page((unsigned long)
671					  bus_to_virt
672						  (le32_to_cpu
673						   (fh->jpg_buffers.
674						      buffer[i].
675						      frag_tab[2 * j])));
676				fh->jpg_buffers.buffer[i].frag_tab[2 * j] =
677				    0;
678				fh->jpg_buffers.buffer[i].frag_tab[2 * j +
679								   1] = 0;
680			}
681		}
682
683		free_page((unsigned long) fh->jpg_buffers.buffer[i].
684			  frag_tab);
685		fh->jpg_buffers.buffer[i].frag_tab = NULL;
686	}
687
688	fh->jpg_buffers.allocated = 0;
689	fh->jpg_buffers.ready_to_be_freed = 0;
690}
691
692/*
693 *   V4L Buffer grabbing
694 */
695
696static int
697zoran_v4l_set_format (struct file               *file,
698		      int                        width,
699		      int                        height,
700		      const struct zoran_format *format)
701{
702	struct zoran_fh *fh = file->private_data;
703	struct zoran *zr = fh->zr;
704	int bpp;
705
706	/* Check size and format of the grab wanted */
707
708	if (height < BUZ_MIN_HEIGHT || width < BUZ_MIN_WIDTH ||
709	    height > BUZ_MAX_HEIGHT || width > BUZ_MAX_WIDTH) {
710		dprintk(1,
711			KERN_ERR
712			"%s: v4l_set_format() - wrong frame size (%dx%d)\n",
713			ZR_DEVNAME(zr), width, height);
714		return -EINVAL;
715	}
716
717	bpp = (format->depth + 7) / 8;
718
719	/* Check against available buffer size */
720	if (height * width * bpp > fh->v4l_buffers.buffer_size) {
721		dprintk(1,
722			KERN_ERR
723			"%s: v4l_set_format() - video buffer size (%d kB) is too small\n",
724			ZR_DEVNAME(zr), fh->v4l_buffers.buffer_size >> 10);
725		return -EINVAL;
726	}
727
728	/* The video front end needs 4-byte alinged line sizes */
729
730	if ((bpp == 2 && (width & 1)) || (bpp == 3 && (width & 3))) {
731		dprintk(1,
732			KERN_ERR
733			"%s: v4l_set_format() - wrong frame alingment\n",
734			ZR_DEVNAME(zr));
735		return -EINVAL;
736	}
737
738	fh->v4l_settings.width = width;
739	fh->v4l_settings.height = height;
740	fh->v4l_settings.format = format;
741	fh->v4l_settings.bytesperline = bpp * fh->v4l_settings.width;
742
743	return 0;
744}
745
746static int
747zoran_v4l_queue_frame (struct file *file,
748		       int          num)
749{
750	struct zoran_fh *fh = file->private_data;
751	struct zoran *zr = fh->zr;
752	unsigned long flags;
753	int res = 0;
754
755	if (!fh->v4l_buffers.allocated) {
756		dprintk(1,
757			KERN_ERR
758			"%s: v4l_queue_frame() - buffers not yet allocated\n",
759			ZR_DEVNAME(zr));
760		res = -ENOMEM;
761	}
762
763	/* No grabbing outside the buffer range! */
764	if (num >= fh->v4l_buffers.num_buffers || num < 0) {
765		dprintk(1,
766			KERN_ERR
767			"%s: v4l_queue_frame() - buffer %d is out of range\n",
768			ZR_DEVNAME(zr), num);
769		res = -EINVAL;
770	}
771
772	spin_lock_irqsave(&zr->spinlock, flags);
773
774	if (fh->v4l_buffers.active == ZORAN_FREE) {
775		if (zr->v4l_buffers.active == ZORAN_FREE) {
776			zr->v4l_buffers = fh->v4l_buffers;
777			fh->v4l_buffers.active = ZORAN_ACTIVE;
778		} else {
779			dprintk(1,
780				KERN_ERR
781				"%s: v4l_queue_frame() - another session is already capturing\n",
782				ZR_DEVNAME(zr));
783			res = -EBUSY;
784		}
785	}
786
787	/* make sure a grab isn't going on currently with this buffer */
788	if (!res) {
789		switch (zr->v4l_buffers.buffer[num].state) {
790		default:
791		case BUZ_STATE_PEND:
792			if (zr->v4l_buffers.active == ZORAN_FREE) {
793				fh->v4l_buffers.active = ZORAN_FREE;
794				zr->v4l_buffers.allocated = 0;
795			}
796			res = -EBUSY;	/* what are you doing? */
797			break;
798		case BUZ_STATE_DONE:
799			dprintk(2,
800				KERN_WARNING
801				"%s: v4l_queue_frame() - queueing buffer %d in state DONE!?\n",
802				ZR_DEVNAME(zr), num);
803		case BUZ_STATE_USER:
804			/* since there is at least one unused buffer there's room for at least
805			 * one more pend[] entry */
806			zr->v4l_pend[zr->v4l_pend_head++ &
807					V4L_MASK_FRAME] = num;
808			zr->v4l_buffers.buffer[num].state = BUZ_STATE_PEND;
809			zr->v4l_buffers.buffer[num].bs.length =
810			    fh->v4l_settings.bytesperline *
811			    zr->v4l_settings.height;
812			fh->v4l_buffers.buffer[num] =
813			    zr->v4l_buffers.buffer[num];
814			break;
815		}
816	}
817
818	spin_unlock_irqrestore(&zr->spinlock, flags);
819
820	if (!res && zr->v4l_buffers.active == ZORAN_FREE)
821		zr->v4l_buffers.active = fh->v4l_buffers.active;
822
823	return res;
824}
825
826static int
827v4l_grab (struct file       *file,
828	  struct video_mmap *mp)
829{
830	struct zoran_fh *fh = file->private_data;
831	struct zoran *zr = fh->zr;
832	int res = 0, i;
833
834	for (i = 0; i < zoran_num_formats; i++) {
835		if (zoran_formats[i].palette == mp->format &&
836		    zoran_formats[i].flags & ZORAN_FORMAT_CAPTURE &&
837		    !(zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED))
838			break;
839	}
840	if (i == zoran_num_formats || zoran_formats[i].depth == 0) {
841		dprintk(1,
842			KERN_ERR
843			"%s: v4l_grab() - wrong bytes-per-pixel format\n",
844			ZR_DEVNAME(zr));
845		return -EINVAL;
846	}
847
848	/*
849	 * To minimize the time spent in the IRQ routine, we avoid setting up
850	 * the video front end there.
851	 * If this grab has different parameters from a running streaming capture
852	 * we stop the streaming capture and start it over again.
853	 */
854	if (zr->v4l_memgrab_active &&
855	    (zr->v4l_settings.width != mp->width ||
856	     zr->v4l_settings.height != mp->height ||
857	     zr->v4l_settings.format->palette != mp->format)) {
858		res = wait_grab_pending(zr);
859		if (res)
860			return res;
861	}
862	if ((res = zoran_v4l_set_format(file,
863					mp->width,
864					mp->height,
865					&zoran_formats[i])))
866		return res;
867	zr->v4l_settings = fh->v4l_settings;
868
869	/* queue the frame in the pending queue */
870	if ((res = zoran_v4l_queue_frame(file, mp->frame))) {
871		fh->v4l_buffers.active = ZORAN_FREE;
872		return res;
873	}
874
875	/* put the 36057 into frame grabbing mode */
876	if (!res && !zr->v4l_memgrab_active)
877		zr36057_set_memgrab(zr, 1);
878
879	//dprintk(4, KERN_INFO "%s: Frame grab 3...\n", ZR_DEVNAME(zr));
880
881	return res;
882}
883
884/*
885 * Sync on a V4L buffer
886 */
887
888static int
889v4l_sync (struct file *file,
890	  int          frame)
891{
892	struct zoran_fh *fh = file->private_data;
893	struct zoran *zr = fh->zr;
894	unsigned long flags;
895
896	if (fh->v4l_buffers.active == ZORAN_FREE) {
897		dprintk(1,
898			KERN_ERR
899			"%s: v4l_sync() - no grab active for this session\n",
900			ZR_DEVNAME(zr));
901		return -EINVAL;
902	}
903
904	/* check passed-in frame number */
905	if (frame >= fh->v4l_buffers.num_buffers || frame < 0) {
906		dprintk(1,
907			KERN_ERR "%s: v4l_sync() - frame %d is invalid\n",
908			ZR_DEVNAME(zr), frame);
909		return -EINVAL;
910	}
911
912	/* Check if is buffer was queued at all */
913	if (zr->v4l_buffers.buffer[frame].state == BUZ_STATE_USER) {
914		dprintk(1,
915			KERN_ERR
916			"%s: v4l_sync() - attempt to sync on a buffer which was not queued?\n",
917			ZR_DEVNAME(zr));
918		return -EPROTO;
919	}
920
921	/* wait on this buffer to get ready */
922	if (!wait_event_interruptible_timeout(zr->v4l_capq,
923				(zr->v4l_buffers.buffer[frame].state != BUZ_STATE_PEND),
924				10*HZ))
925		return -ETIME;
926	if (signal_pending(current))
927		return -ERESTARTSYS;
928
929	/* buffer should now be in BUZ_STATE_DONE */
930	if (zr->v4l_buffers.buffer[frame].state != BUZ_STATE_DONE)
931		dprintk(2,
932			KERN_ERR "%s: v4l_sync() - internal state error\n",
933			ZR_DEVNAME(zr));
934
935	zr->v4l_buffers.buffer[frame].state = BUZ_STATE_USER;
936	fh->v4l_buffers.buffer[frame] = zr->v4l_buffers.buffer[frame];
937
938	spin_lock_irqsave(&zr->spinlock, flags);
939
940	/* Check if streaming capture has finished */
941	if (zr->v4l_pend_tail == zr->v4l_pend_head) {
942		zr36057_set_memgrab(zr, 0);
943		if (zr->v4l_buffers.active == ZORAN_ACTIVE) {
944			fh->v4l_buffers.active = zr->v4l_buffers.active =
945			    ZORAN_FREE;
946			zr->v4l_buffers.allocated = 0;
947		}
948	}
949
950	spin_unlock_irqrestore(&zr->spinlock, flags);
951
952	return 0;
953}
954
955/*
956 *   Queue a MJPEG buffer for capture/playback
957 */
958
959static int
960zoran_jpg_queue_frame (struct file          *file,
961		       int                   num,
962		       enum zoran_codec_mode mode)
963{
964	struct zoran_fh *fh = file->private_data;
965	struct zoran *zr = fh->zr;
966	unsigned long flags;
967	int res = 0;
968
969	/* Check if buffers are allocated */
970	if (!fh->jpg_buffers.allocated) {
971		dprintk(1,
972			KERN_ERR
973			"%s: jpg_queue_frame() - buffers not yet allocated\n",
974			ZR_DEVNAME(zr));
975		return -ENOMEM;
976	}
977
978	/* No grabbing outside the buffer range! */
979	if (num >= fh->jpg_buffers.num_buffers || num < 0) {
980		dprintk(1,
981			KERN_ERR
982			"%s: jpg_queue_frame() - buffer %d out of range\n",
983			ZR_DEVNAME(zr), num);
984		return -EINVAL;
985	}
986
987	/* what is the codec mode right now? */
988	if (zr->codec_mode == BUZ_MODE_IDLE) {
989		zr->jpg_settings = fh->jpg_settings;
990	} else if (zr->codec_mode != mode) {
991		/* wrong codec mode active - invalid */
992		dprintk(1,
993			KERN_ERR
994			"%s: jpg_queue_frame() - codec in wrong mode\n",
995			ZR_DEVNAME(zr));
996		return -EINVAL;
997	}
998
999	if (fh->jpg_buffers.active == ZORAN_FREE) {
1000		if (zr->jpg_buffers.active == ZORAN_FREE) {
1001			zr->jpg_buffers = fh->jpg_buffers;
1002			fh->jpg_buffers.active = ZORAN_ACTIVE;
1003		} else {
1004			dprintk(1,
1005				KERN_ERR
1006				"%s: jpg_queue_frame() - another session is already capturing\n",
1007				ZR_DEVNAME(zr));
1008			res = -EBUSY;
1009		}
1010	}
1011
1012	if (!res && zr->codec_mode == BUZ_MODE_IDLE) {
1013		/* Ok load up the jpeg codec */
1014		zr36057_enable_jpg(zr, mode);
1015	}
1016
1017	spin_lock_irqsave(&zr->spinlock, flags);
1018
1019	if (!res) {
1020		switch (zr->jpg_buffers.buffer[num].state) {
1021		case BUZ_STATE_DONE:
1022			dprintk(2,
1023				KERN_WARNING
1024				"%s: jpg_queue_frame() - queing frame in BUZ_STATE_DONE state!?\n",
1025				ZR_DEVNAME(zr));
1026		case BUZ_STATE_USER:
1027			/* since there is at least one unused buffer there's room for at
1028			 *least one more pend[] entry */
1029			zr->jpg_pend[zr->jpg_que_head++ & BUZ_MASK_FRAME] =
1030			    num;
1031			zr->jpg_buffers.buffer[num].state = BUZ_STATE_PEND;
1032			fh->jpg_buffers.buffer[num] =
1033			    zr->jpg_buffers.buffer[num];
1034			zoran_feed_stat_com(zr);
1035			break;
1036		default:
1037		case BUZ_STATE_DMA:
1038		case BUZ_STATE_PEND:
1039			if (zr->jpg_buffers.active == ZORAN_FREE) {
1040				fh->jpg_buffers.active = ZORAN_FREE;
1041				zr->jpg_buffers.allocated = 0;
1042			}
1043			res = -EBUSY;	/* what are you doing? */
1044			break;
1045		}
1046	}
1047
1048	spin_unlock_irqrestore(&zr->spinlock, flags);
1049
1050	if (!res && zr->jpg_buffers.active == ZORAN_FREE) {
1051		zr->jpg_buffers.active = fh->jpg_buffers.active;
1052	}
1053
1054	return res;
1055}
1056
1057static int
1058jpg_qbuf (struct file          *file,
1059	  int                   frame,
1060	  enum zoran_codec_mode mode)
1061{
1062	struct zoran_fh *fh = file->private_data;
1063	struct zoran *zr = fh->zr;
1064	int res = 0;
1065
1066	/* Does the user want to stop streaming? */
1067	if (frame < 0) {
1068		if (zr->codec_mode == mode) {
1069			if (fh->jpg_buffers.active == ZORAN_FREE) {
1070				dprintk(1,
1071					KERN_ERR
1072					"%s: jpg_qbuf(-1) - session not active\n",
1073					ZR_DEVNAME(zr));
1074				return -EINVAL;
1075			}
1076			fh->jpg_buffers.active = zr->jpg_buffers.active =
1077			    ZORAN_FREE;
1078			zr->jpg_buffers.allocated = 0;
1079			zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1080			return 0;
1081		} else {
1082			dprintk(1,
1083				KERN_ERR
1084				"%s: jpg_qbuf() - stop streaming but not in streaming mode\n",
1085				ZR_DEVNAME(zr));
1086			return -EINVAL;
1087		}
1088	}
1089
1090	if ((res = zoran_jpg_queue_frame(file, frame, mode)))
1091		return res;
1092
1093	/* Start the jpeg codec when the first frame is queued  */
1094	if (!res && zr->jpg_que_head == 1)
1095		jpeg_start(zr);
1096
1097	return res;
1098}
1099
1100/*
1101 *   Sync on a MJPEG buffer
1102 */
1103
1104static int
1105jpg_sync (struct file       *file,
1106	  struct zoran_sync *bs)
1107{
1108	struct zoran_fh *fh = file->private_data;
1109	struct zoran *zr = fh->zr;
1110	unsigned long flags;
1111	int frame;
1112
1113	if (fh->jpg_buffers.active == ZORAN_FREE) {
1114		dprintk(1,
1115			KERN_ERR
1116			"%s: jpg_sync() - capture is not currently active\n",
1117			ZR_DEVNAME(zr));
1118		return -EINVAL;
1119	}
1120	if (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS &&
1121	    zr->codec_mode != BUZ_MODE_MOTION_COMPRESS) {
1122		dprintk(1,
1123			KERN_ERR
1124			"%s: jpg_sync() - codec not in streaming mode\n",
1125			ZR_DEVNAME(zr));
1126		return -EINVAL;
1127	}
1128	if (!wait_event_interruptible_timeout(zr->jpg_capq,
1129			(zr->jpg_que_tail != zr->jpg_dma_tail ||
1130			 zr->jpg_dma_tail == zr->jpg_dma_head),
1131			10*HZ)) {
1132		int isr;
1133
1134		btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
1135		udelay(1);
1136		zr->codec->control(zr->codec, CODEC_G_STATUS,
1137					   sizeof(isr), &isr);
1138		dprintk(1,
1139			KERN_ERR
1140			"%s: jpg_sync() - timeout: codec isr=0x%02x\n",
1141			ZR_DEVNAME(zr), isr);
1142
1143		return -ETIME;
1144
1145	}
1146	if (signal_pending(current))
1147		return -ERESTARTSYS;
1148
1149	spin_lock_irqsave(&zr->spinlock, flags);
1150
1151	if (zr->jpg_dma_tail != zr->jpg_dma_head)
1152		frame = zr->jpg_pend[zr->jpg_que_tail++ & BUZ_MASK_FRAME];
1153	else
1154		frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
1155
1156	/* buffer should now be in BUZ_STATE_DONE */
1157	if (*zr_debug > 0)
1158		if (zr->jpg_buffers.buffer[frame].state != BUZ_STATE_DONE)
1159			dprintk(2,
1160				KERN_ERR
1161				"%s: jpg_sync() - internal state error\n",
1162				ZR_DEVNAME(zr));
1163
1164	*bs = zr->jpg_buffers.buffer[frame].bs;
1165	bs->frame = frame;
1166	zr->jpg_buffers.buffer[frame].state = BUZ_STATE_USER;
1167	fh->jpg_buffers.buffer[frame] = zr->jpg_buffers.buffer[frame];
1168
1169	spin_unlock_irqrestore(&zr->spinlock, flags);
1170
1171	return 0;
1172}
1173
1174static void
1175zoran_open_init_session (struct file *file)
1176{
1177	int i;
1178	struct zoran_fh *fh = file->private_data;
1179	struct zoran *zr = fh->zr;
1180
1181	/* Per default, map the V4L Buffers */
1182	fh->map_mode = ZORAN_MAP_MODE_RAW;
1183
1184	/* take over the card's current settings */
1185	fh->overlay_settings = zr->overlay_settings;
1186	fh->overlay_settings.is_set = 0;
1187	fh->overlay_settings.format = zr->overlay_settings.format;
1188	fh->overlay_active = ZORAN_FREE;
1189
1190	/* v4l settings */
1191	fh->v4l_settings = zr->v4l_settings;
1192
1193	/* v4l_buffers */
1194	memset(&fh->v4l_buffers, 0, sizeof(struct zoran_v4l_struct));
1195	for (i = 0; i < VIDEO_MAX_FRAME; i++) {
1196		fh->v4l_buffers.buffer[i].state = BUZ_STATE_USER;	/* nothing going on */
1197		fh->v4l_buffers.buffer[i].bs.frame = i;
1198	}
1199	fh->v4l_buffers.allocated = 0;
1200	fh->v4l_buffers.ready_to_be_freed = 0;
1201	fh->v4l_buffers.active = ZORAN_FREE;
1202	fh->v4l_buffers.buffer_size = v4l_bufsize;
1203	fh->v4l_buffers.num_buffers = v4l_nbufs;
1204
1205	/* jpg settings */
1206	fh->jpg_settings = zr->jpg_settings;
1207
1208	/* jpg_buffers */
1209	memset(&fh->jpg_buffers, 0, sizeof(struct zoran_jpg_struct));
1210	for (i = 0; i < BUZ_MAX_FRAME; i++) {
1211		fh->jpg_buffers.buffer[i].state = BUZ_STATE_USER;	/* nothing going on */
1212		fh->jpg_buffers.buffer[i].bs.frame = i;
1213	}
1214	fh->jpg_buffers.need_contiguous = zr->jpg_buffers.need_contiguous;
1215	fh->jpg_buffers.allocated = 0;
1216	fh->jpg_buffers.ready_to_be_freed = 0;
1217	fh->jpg_buffers.active = ZORAN_FREE;
1218	fh->jpg_buffers.buffer_size = jpg_bufsize;
1219	fh->jpg_buffers.num_buffers = jpg_nbufs;
1220}
1221
1222static void
1223zoran_close_end_session (struct file *file)
1224{
1225	struct zoran_fh *fh = file->private_data;
1226	struct zoran *zr = fh->zr;
1227
1228	/* overlay */
1229	if (fh->overlay_active != ZORAN_FREE) {
1230		fh->overlay_active = zr->overlay_active = ZORAN_FREE;
1231		zr->v4l_overlay_active = 0;
1232		if (!zr->v4l_memgrab_active)
1233			zr36057_overlay(zr, 0);
1234		zr->overlay_mask = NULL;
1235	}
1236
1237	/* v4l capture */
1238	if (fh->v4l_buffers.active != ZORAN_FREE) {
1239		zr36057_set_memgrab(zr, 0);
1240		zr->v4l_buffers.allocated = 0;
1241		zr->v4l_buffers.active = fh->v4l_buffers.active =
1242		    ZORAN_FREE;
1243	}
1244
1245	/* v4l buffers */
1246	if (fh->v4l_buffers.allocated ||
1247	    fh->v4l_buffers.ready_to_be_freed) {
1248		v4l_fbuffer_free(file);
1249	}
1250
1251	/* jpg capture */
1252	if (fh->jpg_buffers.active != ZORAN_FREE) {
1253		zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1254		zr->jpg_buffers.allocated = 0;
1255		zr->jpg_buffers.active = fh->jpg_buffers.active =
1256		    ZORAN_FREE;
1257	}
1258
1259	/* jpg buffers */
1260	if (fh->jpg_buffers.allocated ||
1261	    fh->jpg_buffers.ready_to_be_freed) {
1262		jpg_fbuffer_free(file);
1263	}
1264}
1265
1266/*
1267 *   Open a zoran card. Right now the flags stuff is just playing
1268 */
1269
1270static int
1271zoran_open (struct inode *inode,
1272	    struct file  *file)
1273{
1274	unsigned int minor = iminor(inode);
1275	struct zoran *zr = NULL;
1276	struct zoran_fh *fh;
1277	int i, res, first_open = 0, have_module_locks = 0;
1278
1279	/* find the device */
1280	for (i = 0; i < zoran_num; i++) {
1281		if (zoran[i].video_dev->minor == minor) {
1282			zr = &zoran[i];
1283			break;
1284		}
1285	}
1286
1287	if (!zr) {
1288		dprintk(1, KERN_ERR "%s: device not found!\n", ZORAN_NAME);
1289		res = -ENODEV;
1290		goto open_unlock_and_return;
1291	}
1292
1293	/* see fs/device.c - the kernel already locks during open(),
1294	 * so locking ourselves only causes deadlocks */
1295	/*mutex_lock(&zr->resource_lock);*/
1296
1297	if (!zr->decoder) {
1298		dprintk(1,
1299			KERN_ERR "%s: no TV decoder loaded for device!\n",
1300			ZR_DEVNAME(zr));
1301		res = -EIO;
1302		goto open_unlock_and_return;
1303	}
1304
1305	/* try to grab a module lock */
1306	if (!try_module_get(THIS_MODULE)) {
1307		dprintk(1,
1308			KERN_ERR
1309			"%s: failed to acquire my own lock! PANIC!\n",
1310			ZR_DEVNAME(zr));
1311		res = -ENODEV;
1312		goto open_unlock_and_return;
1313	}
1314	if (!try_module_get(zr->decoder->driver->driver.owner)) {
1315		dprintk(1,
1316			KERN_ERR
1317			"%s: failed to grab ownership of i2c decoder\n",
1318			ZR_DEVNAME(zr));
1319		res = -EIO;
1320		module_put(THIS_MODULE);
1321		goto open_unlock_and_return;
1322	}
1323	if (zr->encoder &&
1324	    !try_module_get(zr->encoder->driver->driver.owner)) {
1325		dprintk(1,
1326			KERN_ERR
1327			"%s: failed to grab ownership of i2c encoder\n",
1328			ZR_DEVNAME(zr));
1329		res = -EIO;
1330		module_put(zr->decoder->driver->driver.owner);
1331		module_put(THIS_MODULE);
1332		goto open_unlock_and_return;
1333	}
1334
1335	have_module_locks = 1;
1336
1337	if (zr->user >= 2048) {
1338		dprintk(1, KERN_ERR "%s: too many users (%d) on device\n",
1339			ZR_DEVNAME(zr), zr->user);
1340		res = -EBUSY;
1341		goto open_unlock_and_return;
1342	}
1343
1344	dprintk(1, KERN_INFO "%s: zoran_open(%s, pid=[%d]), users(-)=%d\n",
1345		ZR_DEVNAME(zr), current->comm, current->pid, zr->user);
1346
1347	/* now, create the open()-specific file_ops struct */
1348	fh = kzalloc(sizeof(struct zoran_fh), GFP_KERNEL);
1349	if (!fh) {
1350		dprintk(1,
1351			KERN_ERR
1352			"%s: zoran_open() - allocation of zoran_fh failed\n",
1353			ZR_DEVNAME(zr));
1354		res = -ENOMEM;
1355		goto open_unlock_and_return;
1356	}
1357	/* used to be BUZ_MAX_WIDTH/HEIGHT, but that gives overflows
1358	 * on norm-change! */
1359	fh->overlay_mask =
1360	    kmalloc(((768 + 31) / 32) * 576 * 4, GFP_KERNEL);
1361	if (!fh->overlay_mask) {
1362		dprintk(1,
1363			KERN_ERR
1364			"%s: zoran_open() - allocation of overlay_mask failed\n",
1365			ZR_DEVNAME(zr));
1366		kfree(fh);
1367		res = -ENOMEM;
1368		goto open_unlock_and_return;
1369	}
1370
1371	if (zr->user++ == 0)
1372		first_open = 1;
1373
1374	/*mutex_unlock(&zr->resource_lock);*/
1375
1376	/* default setup - TODO: look at flags */
1377	if (first_open) {	/* First device open */
1378		zr36057_restart(zr);
1379		zoran_open_init_params(zr);
1380		zoran_init_hardware(zr);
1381
1382		btor(ZR36057_ICR_IntPinEn, ZR36057_ICR);
1383	}
1384
1385	/* set file_ops stuff */
1386	file->private_data = fh;
1387	fh->zr = zr;
1388	zoran_open_init_session(file);
1389
1390	return 0;
1391
1392open_unlock_and_return:
1393	/* if we grabbed locks, release them accordingly */
1394	if (have_module_locks) {
1395		module_put(zr->decoder->driver->driver.owner);
1396		if (zr->encoder) {
1397			module_put(zr->encoder->driver->driver.owner);
1398		}
1399		module_put(THIS_MODULE);
1400	}
1401
1402	/* if there's no device found, we didn't obtain the lock either */
1403	if (zr) {
1404		/*mutex_unlock(&zr->resource_lock);*/
1405	}
1406
1407	return res;
1408}
1409
1410static int
1411zoran_close (struct inode *inode,
1412	     struct file  *file)
1413{
1414	struct zoran_fh *fh = file->private_data;
1415	struct zoran *zr = fh->zr;
1416
1417	dprintk(1, KERN_INFO "%s: zoran_close(%s, pid=[%d]), users(+)=%d\n",
1418		ZR_DEVNAME(zr), current->comm, current->pid, zr->user);
1419
1420	/* kernel locks (fs/device.c), so don't do that ourselves
1421	 * (prevents deadlocks) */
1422	/*mutex_lock(&zr->resource_lock);*/
1423
1424	zoran_close_end_session(file);
1425
1426	if (zr->user-- == 1) {	/* Last process */
1427		/* Clean up JPEG process */
1428		wake_up_interruptible(&zr->jpg_capq);
1429		zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1430		zr->jpg_buffers.allocated = 0;
1431		zr->jpg_buffers.active = ZORAN_FREE;
1432
1433		/* disable interrupts */
1434		btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
1435
1436		if (*zr_debug > 1)
1437			print_interrupts(zr);
1438
1439		/* Overlay off */
1440		zr->v4l_overlay_active = 0;
1441		zr36057_overlay(zr, 0);
1442		zr->overlay_mask = NULL;
1443
1444		/* capture off */
1445		wake_up_interruptible(&zr->v4l_capq);
1446		zr36057_set_memgrab(zr, 0);
1447		zr->v4l_buffers.allocated = 0;
1448		zr->v4l_buffers.active = ZORAN_FREE;
1449		zoran_set_pci_master(zr, 0);
1450
1451		if (!pass_through) {	/* Switch to color bar */
1452			int zero = 0, two = 2;
1453			decoder_command(zr, DECODER_ENABLE_OUTPUT, &zero);
1454			encoder_command(zr, ENCODER_SET_INPUT, &two);
1455		}
1456	}
1457
1458	file->private_data = NULL;
1459	kfree(fh->overlay_mask);
1460	kfree(fh);
1461
1462	/* release locks on the i2c modules */
1463	module_put(zr->decoder->driver->driver.owner);
1464	if (zr->encoder) {
1465		 module_put(zr->encoder->driver->driver.owner);
1466	}
1467	module_put(THIS_MODULE);
1468
1469	/*mutex_unlock(&zr->resource_lock);*/
1470
1471	dprintk(4, KERN_INFO "%s: zoran_close() done\n", ZR_DEVNAME(zr));
1472
1473	return 0;
1474}
1475
1476
1477static ssize_t
1478zoran_read (struct file *file,
1479	    char        __user *data,
1480	    size_t       count,
1481	    loff_t      *ppos)
1482{
1483	/* we simply don't support read() (yet)... */
1484
1485	return -EINVAL;
1486}
1487
1488static ssize_t
1489zoran_write (struct file *file,
1490	     const char  __user *data,
1491	     size_t       count,
1492	     loff_t      *ppos)
1493{
1494	/* ...and the same goes for write() */
1495
1496	return -EINVAL;
1497}
1498
1499static int
1500setup_fbuffer (struct file               *file,
1501	       void                      *base,
1502	       const struct zoran_format *fmt,
1503	       int                        width,
1504	       int                        height,
1505	       int                        bytesperline)
1506{
1507	struct zoran_fh *fh = file->private_data;
1508	struct zoran *zr = fh->zr;
1509
1510	/* (Ronald) v4l/v4l2 guidelines */
1511	if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
1512		return -EPERM;
1513
1514	/* Don't allow frame buffer overlay if PCI or AGP is buggy, or on
1515	   ALi Magik (that needs very low latency while the card needs a
1516	   higher value always) */
1517
1518	if (pci_pci_problems & (PCIPCI_FAIL | PCIAGP_FAIL | PCIPCI_ALIMAGIK))
1519		return -ENXIO;
1520
1521	/* we need a bytesperline value, even if not given */
1522	if (!bytesperline)
1523		bytesperline = width * ((fmt->depth + 7) & ~7) / 8;
1524
1525
1526	if (!(fmt->flags & ZORAN_FORMAT_OVERLAY)) {
1527		dprintk(1,
1528			KERN_ERR
1529			"%s: setup_fbuffer() - no valid overlay format given\n",
1530			ZR_DEVNAME(zr));
1531		return -EINVAL;
1532	}
1533	if (height <= 0 || width <= 0 || bytesperline <= 0) {
1534		dprintk(1,
1535			KERN_ERR
1536			"%s: setup_fbuffer() - invalid height/width/bpl value (%d|%d|%d)\n",
1537			ZR_DEVNAME(zr), width, height, bytesperline);
1538		return -EINVAL;
1539	}
1540	if (bytesperline & 3) {
1541		dprintk(1,
1542			KERN_ERR
1543			"%s: setup_fbuffer() - bytesperline (%d) must be 4-byte aligned\n",
1544			ZR_DEVNAME(zr), bytesperline);
1545		return -EINVAL;
1546	}
1547
1548	zr->buffer.base = (void *) ((unsigned long) base & ~3);
1549	zr->buffer.height = height;
1550	zr->buffer.width = width;
1551	zr->buffer.depth = fmt->depth;
1552	zr->overlay_settings.format = fmt;
1553	zr->buffer.bytesperline = bytesperline;
1554
1555	/* The user should set new window parameters */
1556	zr->overlay_settings.is_set = 0;
1557
1558	return 0;
1559}
1560
1561
1562static int
1563setup_window (struct file       *file,
1564	      int                x,
1565	      int                y,
1566	      int                width,
1567	      int                height,
1568	      struct video_clip __user *clips,
1569	      int                clipcount,
1570	      void              __user *bitmap)
1571{
1572	struct zoran_fh *fh = file->private_data;
1573	struct zoran *zr = fh->zr;
1574	struct video_clip *vcp = NULL;
1575	int on, end;
1576
1577
1578	if (!zr->buffer.base) {
1579		dprintk(1,
1580			KERN_ERR
1581			"%s: setup_window() - frame buffer has to be set first\n",
1582			ZR_DEVNAME(zr));
1583		return -EINVAL;
1584	}
1585
1586	if (!fh->overlay_settings.format) {
1587		dprintk(1,
1588			KERN_ERR
1589			"%s: setup_window() - no overlay format set\n",
1590			ZR_DEVNAME(zr));
1591		return -EINVAL;
1592	}
1593
1594	/*
1595	 * The video front end needs 4-byte alinged line sizes, we correct that
1596	 * silently here if necessary
1597	 */
1598	if (zr->buffer.depth == 15 || zr->buffer.depth == 16) {
1599		end = (x + width) & ~1;	/* round down */
1600		x = (x + 1) & ~1;	/* round up */
1601		width = end - x;
1602	}
1603
1604	if (zr->buffer.depth == 24) {
1605		end = (x + width) & ~3;	/* round down */
1606		x = (x + 3) & ~3;	/* round up */
1607		width = end - x;
1608	}
1609
1610	if (width > BUZ_MAX_WIDTH)
1611		width = BUZ_MAX_WIDTH;
1612	if (height > BUZ_MAX_HEIGHT)
1613		height = BUZ_MAX_HEIGHT;
1614
1615	/* Check for vaild parameters */
1616	if (width < BUZ_MIN_WIDTH || height < BUZ_MIN_HEIGHT ||
1617	    width > BUZ_MAX_WIDTH || height > BUZ_MAX_HEIGHT) {
1618		dprintk(1,
1619			KERN_ERR
1620			"%s: setup_window() - width = %d or height = %d invalid\n",
1621			ZR_DEVNAME(zr), width, height);
1622		return -EINVAL;
1623	}
1624
1625	fh->overlay_settings.x = x;
1626	fh->overlay_settings.y = y;
1627	fh->overlay_settings.width = width;
1628	fh->overlay_settings.height = height;
1629	fh->overlay_settings.clipcount = clipcount;
1630
1631	/*
1632	 * If an overlay is running, we have to switch it off
1633	 * and switch it on again in order to get the new settings in effect.
1634	 *
1635	 * We also want to avoid that the overlay mask is written
1636	 * when an overlay is running.
1637	 */
1638
1639	on = zr->v4l_overlay_active && !zr->v4l_memgrab_active &&
1640	    zr->overlay_active != ZORAN_FREE &&
1641	    fh->overlay_active != ZORAN_FREE;
1642	if (on)
1643		zr36057_overlay(zr, 0);
1644
1645	/*
1646	 *   Write the overlay mask if clips are wanted.
1647	 *   We prefer a bitmap.
1648	 */
1649	if (bitmap) {
1650		/* fake value - it just means we want clips */
1651		fh->overlay_settings.clipcount = 1;
1652
1653		if (copy_from_user(fh->overlay_mask, bitmap,
1654				   (width * height + 7) / 8)) {
1655			return -EFAULT;
1656		}
1657	} else if (clipcount > 0) {
1658		/* write our own bitmap from the clips */
1659		vcp = vmalloc(sizeof(struct video_clip) * (clipcount + 4));
1660		if (vcp == NULL) {
1661			dprintk(1,
1662				KERN_ERR
1663				"%s: setup_window() - Alloc of clip mask failed\n",
1664				ZR_DEVNAME(zr));
1665			return -ENOMEM;
1666		}
1667		if (copy_from_user
1668		    (vcp, clips, sizeof(struct video_clip) * clipcount)) {
1669			vfree(vcp);
1670			return -EFAULT;
1671		}
1672		write_overlay_mask(file, vcp, clipcount);
1673		vfree(vcp);
1674	}
1675
1676	fh->overlay_settings.is_set = 1;
1677	if (fh->overlay_active != ZORAN_FREE &&
1678	    zr->overlay_active != ZORAN_FREE)
1679		zr->overlay_settings = fh->overlay_settings;
1680
1681	if (on)
1682		zr36057_overlay(zr, 1);
1683
1684	/* Make sure the changes come into effect */
1685	return wait_grab_pending(zr);
1686}
1687
1688static int
1689setup_overlay (struct file *file,
1690	       int          on)
1691{
1692	struct zoran_fh *fh = file->private_data;
1693	struct zoran *zr = fh->zr;
1694
1695	/* If there is nothing to do, return immediatly */
1696	if ((on && fh->overlay_active != ZORAN_FREE) ||
1697	    (!on && fh->overlay_active == ZORAN_FREE))
1698		return 0;
1699
1700	/* check whether we're touching someone else's overlay */
1701	if (on && zr->overlay_active != ZORAN_FREE &&
1702	    fh->overlay_active == ZORAN_FREE) {
1703		dprintk(1,
1704			KERN_ERR
1705			"%s: setup_overlay() - overlay is already active for another session\n",
1706			ZR_DEVNAME(zr));
1707		return -EBUSY;
1708	}
1709	if (!on && zr->overlay_active != ZORAN_FREE &&
1710	    fh->overlay_active == ZORAN_FREE) {
1711		dprintk(1,
1712			KERN_ERR
1713			"%s: setup_overlay() - you cannot cancel someone else's session\n",
1714			ZR_DEVNAME(zr));
1715		return -EPERM;
1716	}
1717
1718	if (on == 0) {
1719		zr->overlay_active = fh->overlay_active = ZORAN_FREE;
1720		zr->v4l_overlay_active = 0;
1721		/* When a grab is running, the video simply
1722		 * won't be switched on any more */
1723		if (!zr->v4l_memgrab_active)
1724			zr36057_overlay(zr, 0);
1725		zr->overlay_mask = NULL;
1726	} else {
1727		if (!zr->buffer.base || !fh->overlay_settings.is_set) {
1728			dprintk(1,
1729				KERN_ERR
1730				"%s: setup_overlay() - buffer or window not set\n",
1731				ZR_DEVNAME(zr));
1732			return -EINVAL;
1733		}
1734		if (!fh->overlay_settings.format) {
1735			dprintk(1,
1736				KERN_ERR
1737				"%s: setup_overlay() - no overlay format set\n",
1738				ZR_DEVNAME(zr));
1739			return -EINVAL;
1740		}
1741		zr->overlay_active = fh->overlay_active = ZORAN_LOCKED;
1742		zr->v4l_overlay_active = 1;
1743		zr->overlay_mask = fh->overlay_mask;
1744		zr->overlay_settings = fh->overlay_settings;
1745		if (!zr->v4l_memgrab_active)
1746			zr36057_overlay(zr, 1);
1747		/* When a grab is running, the video will be
1748		 * switched on when grab is finished */
1749	}
1750
1751	/* Make sure the changes come into effect */
1752	return wait_grab_pending(zr);
1753}
1754
1755#ifdef CONFIG_VIDEO_V4L2
1756	/* get the status of a buffer in the clients buffer queue */
1757static int
1758zoran_v4l2_buffer_status (struct file        *file,
1759			  struct v4l2_buffer *buf,
1760			  int                 num)
1761{
1762	struct zoran_fh *fh = file->private_data;
1763	struct zoran *zr = fh->zr;
1764
1765	buf->flags = V4L2_BUF_FLAG_MAPPED;
1766
1767	switch (fh->map_mode) {
1768	case ZORAN_MAP_MODE_RAW:
1769
1770		/* check range */
1771		if (num < 0 || num >= fh->v4l_buffers.num_buffers ||
1772		    !fh->v4l_buffers.allocated) {
1773			dprintk(1,
1774				KERN_ERR
1775				"%s: v4l2_buffer_status() - wrong number or buffers not allocated\n",
1776				ZR_DEVNAME(zr));
1777			return -EINVAL;
1778		}
1779
1780		buf->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1781		buf->length = fh->v4l_buffers.buffer_size;
1782
1783		/* get buffer */
1784		buf->bytesused = fh->v4l_buffers.buffer[num].bs.length;
1785		if (fh->v4l_buffers.buffer[num].state == BUZ_STATE_DONE ||
1786		    fh->v4l_buffers.buffer[num].state == BUZ_STATE_USER) {
1787			buf->sequence = fh->v4l_buffers.buffer[num].bs.seq;
1788			buf->flags |= V4L2_BUF_FLAG_DONE;
1789			buf->timestamp =
1790			    fh->v4l_buffers.buffer[num].bs.timestamp;
1791		} else {
1792			buf->flags |= V4L2_BUF_FLAG_QUEUED;
1793		}
1794
1795		if (fh->v4l_settings.height <= BUZ_MAX_HEIGHT / 2)
1796			buf->field = V4L2_FIELD_TOP;
1797		else
1798			buf->field = V4L2_FIELD_INTERLACED;
1799
1800		break;
1801
1802	case ZORAN_MAP_MODE_JPG_REC:
1803	case ZORAN_MAP_MODE_JPG_PLAY:
1804
1805		/* check range */
1806		if (num < 0 || num >= fh->jpg_buffers.num_buffers ||
1807		    !fh->jpg_buffers.allocated) {
1808			dprintk(1,
1809				KERN_ERR
1810				"%s: v4l2_buffer_status() - wrong number or buffers not allocated\n",
1811				ZR_DEVNAME(zr));
1812			return -EINVAL;
1813		}
1814
1815		buf->type = (fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
1816			      V4L2_BUF_TYPE_VIDEO_CAPTURE :
1817			      V4L2_BUF_TYPE_VIDEO_OUTPUT;
1818		buf->length = fh->jpg_buffers.buffer_size;
1819
1820		/* these variables are only written after frame has been captured */
1821		if (fh->jpg_buffers.buffer[num].state == BUZ_STATE_DONE ||
1822		    fh->jpg_buffers.buffer[num].state == BUZ_STATE_USER) {
1823			buf->sequence = fh->jpg_buffers.buffer[num].bs.seq;
1824			buf->timestamp =
1825			    fh->jpg_buffers.buffer[num].bs.timestamp;
1826			buf->bytesused =
1827			    fh->jpg_buffers.buffer[num].bs.length;
1828			buf->flags |= V4L2_BUF_FLAG_DONE;
1829		} else {
1830			buf->flags |= V4L2_BUF_FLAG_QUEUED;
1831		}
1832
1833		/* which fields are these? */
1834		if (fh->jpg_settings.TmpDcm != 1)
1835			buf->field =
1836			    fh->jpg_settings.
1837			    odd_even ? V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM;
1838		else
1839			buf->field =
1840			    fh->jpg_settings.
1841			    odd_even ? V4L2_FIELD_SEQ_TB :
1842			    V4L2_FIELD_SEQ_BT;
1843
1844		break;
1845
1846	default:
1847
1848		dprintk(5,
1849			KERN_ERR
1850			"%s: v4l2_buffer_status() - invalid buffer type|map_mode (%d|%d)\n",
1851			ZR_DEVNAME(zr), buf->type, fh->map_mode);
1852		return -EINVAL;
1853	}
1854
1855	buf->memory = V4L2_MEMORY_MMAP;
1856	buf->index = num;
1857	buf->m.offset = buf->length * num;
1858
1859	return 0;
1860}
1861#endif
1862
1863static int
1864zoran_set_norm (struct zoran *zr,
1865		int           norm) /* VIDEO_MODE_* */
1866{
1867	int norm_encoder, on;
1868
1869	if (zr->v4l_buffers.active != ZORAN_FREE ||
1870	    zr->jpg_buffers.active != ZORAN_FREE) {
1871		dprintk(1,
1872			KERN_WARNING
1873			"%s: set_norm() called while in playback/capture mode\n",
1874			ZR_DEVNAME(zr));
1875		return -EBUSY;
1876	}
1877
1878	if (lock_norm && norm != zr->norm) {
1879		if (lock_norm > 1) {
1880			dprintk(1,
1881				KERN_WARNING
1882				"%s: set_norm() - TV standard is locked, can not switch norm\n",
1883				ZR_DEVNAME(zr));
1884			return -EPERM;
1885		} else {
1886			dprintk(1,
1887				KERN_WARNING
1888				"%s: set_norm() - TV standard is locked, norm was not changed\n",
1889				ZR_DEVNAME(zr));
1890			norm = zr->norm;
1891		}
1892	}
1893
1894	if (norm != VIDEO_MODE_AUTO &&
1895	    (norm < 0 || norm >= zr->card.norms ||
1896	     !zr->card.tvn[norm])) {
1897		dprintk(1,
1898			KERN_ERR "%s: set_norm() - unsupported norm %d\n",
1899			ZR_DEVNAME(zr), norm);
1900		return -EINVAL;
1901	}
1902
1903	if (norm == VIDEO_MODE_AUTO) {
1904		int status;
1905
1906		/* if we have autodetect, ... */
1907		struct video_decoder_capability caps;
1908		decoder_command(zr, DECODER_GET_CAPABILITIES, &caps);
1909		if (!(caps.flags & VIDEO_DECODER_AUTO)) {
1910			dprintk(1, KERN_ERR "%s: norm=auto unsupported\n",
1911				ZR_DEVNAME(zr));
1912			return -EINVAL;
1913		}
1914
1915		decoder_command(zr, DECODER_SET_NORM, &norm);
1916
1917		/* let changes come into effect */
1918		ssleep(2);
1919
1920		decoder_command(zr, DECODER_GET_STATUS, &status);
1921		if (!(status & DECODER_STATUS_GOOD)) {
1922			dprintk(1,
1923				KERN_ERR
1924				"%s: set_norm() - no norm detected\n",
1925				ZR_DEVNAME(zr));
1926			/* reset norm */
1927			decoder_command(zr, DECODER_SET_NORM, &zr->norm);
1928			return -EIO;
1929		}
1930
1931		if (status & DECODER_STATUS_NTSC)
1932			norm = VIDEO_MODE_NTSC;
1933		else if (status & DECODER_STATUS_SECAM)
1934			norm = VIDEO_MODE_SECAM;
1935		else
1936			norm = VIDEO_MODE_PAL;
1937	}
1938	zr->timing = zr->card.tvn[norm];
1939	norm_encoder = norm;
1940
1941	/* We switch overlay off and on since a change in the
1942	 * norm needs different VFE settings */
1943	on = zr->overlay_active && !zr->v4l_memgrab_active;
1944	if (on)
1945		zr36057_overlay(zr, 0);
1946
1947	decoder_command(zr, DECODER_SET_NORM, &norm);
1948	encoder_command(zr, ENCODER_SET_NORM, &norm_encoder);
1949
1950	if (on)
1951		zr36057_overlay(zr, 1);
1952
1953	/* Make sure the changes come into effect */
1954	zr->norm = norm;
1955
1956	return 0;
1957}
1958
1959static int
1960zoran_set_input (struct zoran *zr,
1961		 int           input)
1962{
1963	int realinput;
1964
1965	if (input == zr->input) {
1966		return 0;
1967	}
1968
1969	if (zr->v4l_buffers.active != ZORAN_FREE ||
1970	    zr->jpg_buffers.active != ZORAN_FREE) {
1971		dprintk(1,
1972			KERN_WARNING
1973			"%s: set_input() called while in playback/capture mode\n",
1974			ZR_DEVNAME(zr));
1975		return -EBUSY;
1976	}
1977
1978	if (input < 0 || input >= zr->card.inputs) {
1979		dprintk(1,
1980			KERN_ERR
1981			"%s: set_input() - unnsupported input %d\n",
1982			ZR_DEVNAME(zr), input);
1983		return -EINVAL;
1984	}
1985
1986	realinput = zr->card.input[input].muxsel;
1987	zr->input = input;
1988
1989	decoder_command(zr, DECODER_SET_INPUT, &realinput);
1990
1991	return 0;
1992}
1993
1994/*
1995 *   ioctl routine
1996 */
1997
1998static int
1999zoran_do_ioctl (struct inode *inode,
2000		struct file  *file,
2001		unsigned int  cmd,
2002		void         *arg)
2003{
2004	struct zoran_fh *fh = file->private_data;
2005	struct zoran *zr = fh->zr;
2006	/* CAREFUL: used in multiple places here */
2007	struct zoran_jpg_settings settings;
2008
2009	/* we might have older buffers lying around... We don't want
2010	 * to wait, but we do want to try cleaning them up ASAP. So
2011	 * we try to obtain the lock and free them. If that fails, we
2012	 * don't do anything and wait for the next turn. In the end,
2013	 * zoran_close() or a new allocation will still free them...
2014	 * This is just a 'the sooner the better' extra 'feature'
2015	 *
2016	 * We don't free the buffers right on munmap() because that
2017	 * causes oopses (kfree() inside munmap() oopses for no
2018	 * apparent reason - it's also not reproduceable in any way,
2019	 * but moving the free code outside the munmap() handler fixes
2020	 * all this... If someone knows why, please explain me (Ronald)
2021	 */
2022	if (mutex_trylock(&zr->resource_lock)) {
2023		/* we obtained it! Let's try to free some things */
2024		if (fh->jpg_buffers.ready_to_be_freed)
2025			jpg_fbuffer_free(file);
2026		if (fh->v4l_buffers.ready_to_be_freed)
2027			v4l_fbuffer_free(file);
2028
2029		mutex_unlock(&zr->resource_lock);
2030	}
2031
2032	switch (cmd) {
2033
2034	case VIDIOCGCAP:
2035	{
2036		struct video_capability *vcap = arg;
2037
2038		dprintk(3, KERN_DEBUG "%s: VIDIOCGCAP\n", ZR_DEVNAME(zr));
2039
2040		memset(vcap, 0, sizeof(struct video_capability));
2041		strncpy(vcap->name, ZR_DEVNAME(zr), sizeof(vcap->name)-1);
2042		vcap->type = ZORAN_VID_TYPE;
2043
2044		vcap->channels = zr->card.inputs;
2045		vcap->audios = 0;
2046		mutex_lock(&zr->resource_lock);
2047		vcap->maxwidth = BUZ_MAX_WIDTH;
2048		vcap->maxheight = BUZ_MAX_HEIGHT;
2049		vcap->minwidth = BUZ_MIN_WIDTH;
2050		vcap->minheight = BUZ_MIN_HEIGHT;
2051		mutex_unlock(&zr->resource_lock);
2052
2053		return 0;
2054	}
2055		break;
2056
2057	case VIDIOCGCHAN:
2058	{
2059		struct video_channel *vchan = arg;
2060		int channel = vchan->channel;
2061
2062		dprintk(3, KERN_DEBUG "%s: VIDIOCGCHAN - channel=%d\n",
2063			ZR_DEVNAME(zr), vchan->channel);
2064
2065		memset(vchan, 0, sizeof(struct video_channel));
2066		if (channel > zr->card.inputs || channel < 0) {
2067			dprintk(1,
2068				KERN_ERR
2069				"%s: VIDIOCGCHAN on not existing channel %d\n",
2070				ZR_DEVNAME(zr), channel);
2071			return -EINVAL;
2072		}
2073
2074		strcpy(vchan->name, zr->card.input[channel].name);
2075
2076		vchan->tuners = 0;
2077		vchan->flags = 0;
2078		vchan->type = VIDEO_TYPE_CAMERA;
2079		mutex_lock(&zr->resource_lock);
2080		vchan->norm = zr->norm;
2081		mutex_unlock(&zr->resource_lock);
2082		vchan->channel = channel;
2083
2084		return 0;
2085	}
2086		break;
2087
2088		/* RJ: the documentation at http://roadrunner.swansea.linux.org.uk/v4lapi.shtml says:
2089		 *
2090		 * * "The VIDIOCSCHAN ioctl takes an integer argument and switches the capture to this input."
2091		 * *                                 ^^^^^^^
2092		 * * The famos BTTV driver has it implemented with a struct video_channel argument
2093		 * * and we follow it for compatibility reasons
2094		 * *
2095		 * * BTW: this is the only way the user can set the norm!
2096		 */
2097
2098	case VIDIOCSCHAN:
2099	{
2100		struct video_channel *vchan = arg;
2101		int res;
2102
2103		dprintk(3,
2104			KERN_DEBUG
2105			"%s: VIDIOCSCHAN - channel=%d, norm=%d\n",
2106			ZR_DEVNAME(zr), vchan->channel, vchan->norm);
2107
2108		mutex_lock(&zr->resource_lock);
2109		if ((res = zoran_set_input(zr, vchan->channel)))
2110			goto schan_unlock_and_return;
2111		if ((res = zoran_set_norm(zr, vchan->norm)))
2112			goto schan_unlock_and_return;
2113
2114		/* Make sure the changes come into effect */
2115		res = wait_grab_pending(zr);
2116	schan_unlock_and_return:
2117		mutex_unlock(&zr->resource_lock);
2118		return res;
2119	}
2120		break;
2121
2122	case VIDIOCGPICT:
2123	{
2124		struct video_picture *vpict = arg;
2125
2126		dprintk(3, KERN_DEBUG "%s: VIDIOCGPICT\n", ZR_DEVNAME(zr));
2127
2128		memset(vpict, 0, sizeof(struct video_picture));
2129		mutex_lock(&zr->resource_lock);
2130		vpict->hue = zr->hue;
2131		vpict->brightness = zr->brightness;
2132		vpict->contrast = zr->contrast;
2133		vpict->colour = zr->saturation;
2134		if (fh->overlay_settings.format) {
2135			vpict->depth = fh->overlay_settings.format->depth;
2136			vpict->palette = fh->overlay_settings.format->palette;
2137		} else {
2138			vpict->depth = 0;
2139		}
2140		mutex_unlock(&zr->resource_lock);
2141
2142		return 0;
2143	}
2144		break;
2145
2146	case VIDIOCSPICT:
2147	{
2148		struct video_picture *vpict = arg;
2149		int i;
2150
2151		dprintk(3,
2152			KERN_DEBUG
2153			"%s: VIDIOCSPICT - bri=%d, hue=%d, col=%d, con=%d, dep=%d, pal=%d\n",
2154			ZR_DEVNAME(zr), vpict->brightness, vpict->hue,
2155			vpict->colour, vpict->contrast, vpict->depth,
2156			vpict->palette);
2157
2158		for (i = 0; i < zoran_num_formats; i++) {
2159			const struct zoran_format *fmt = &zoran_formats[i];
2160
2161			if (fmt->palette != -1 &&
2162			    fmt->flags & ZORAN_FORMAT_OVERLAY &&
2163			    fmt->palette == vpict->palette &&
2164			    fmt->depth == vpict->depth)
2165				break;
2166		}
2167		if (i == zoran_num_formats) {
2168			dprintk(1,
2169				KERN_ERR
2170				"%s: VIDIOCSPICT - Invalid palette %d\n",
2171				ZR_DEVNAME(zr), vpict->palette);
2172			return -EINVAL;
2173		}
2174
2175		mutex_lock(&zr->resource_lock);
2176
2177		decoder_command(zr, DECODER_SET_PICTURE, vpict);
2178
2179		zr->hue = vpict->hue;
2180		zr->contrast = vpict->contrast;
2181		zr->saturation = vpict->colour;
2182		zr->brightness = vpict->brightness;
2183
2184		fh->overlay_settings.format = &zoran_formats[i];
2185
2186		mutex_unlock(&zr->resource_lock);
2187
2188		return 0;
2189	}
2190		break;
2191
2192	case VIDIOCCAPTURE:
2193	{
2194		int *on = arg, res;
2195
2196		dprintk(3, KERN_DEBUG "%s: VIDIOCCAPTURE - on=%d\n",
2197			ZR_DEVNAME(zr), *on);
2198
2199		mutex_lock(&zr->resource_lock);
2200		res = setup_overlay(file, *on);
2201		mutex_unlock(&zr->resource_lock);
2202
2203		return res;
2204	}
2205		break;
2206
2207	case VIDIOCGWIN:
2208	{
2209		struct video_window *vwin = arg;
2210
2211		dprintk(3, KERN_DEBUG "%s: VIDIOCGWIN\n", ZR_DEVNAME(zr));
2212
2213		memset(vwin, 0, sizeof(struct video_window));
2214		mutex_lock(&zr->resource_lock);
2215		vwin->x = fh->overlay_settings.x;
2216		vwin->y = fh->overlay_settings.y;
2217		vwin->width = fh->overlay_settings.width;
2218		vwin->height = fh->overlay_settings.height;
2219		mutex_unlock(&zr->resource_lock);
2220		vwin->clipcount = 0;
2221		return 0;
2222	}
2223		break;
2224
2225	case VIDIOCSWIN:
2226	{
2227		struct video_window *vwin = arg;
2228		int res;
2229
2230		dprintk(3,
2231			KERN_DEBUG
2232			"%s: VIDIOCSWIN - x=%d, y=%d, w=%d, h=%d, clipcount=%d\n",
2233			ZR_DEVNAME(zr), vwin->x, vwin->y, vwin->width,
2234			vwin->height, vwin->clipcount);
2235
2236		mutex_lock(&zr->resource_lock);
2237		res =
2238		    setup_window(file, vwin->x, vwin->y, vwin->width,
2239				 vwin->height, vwin->clips,
2240				 vwin->clipcount, NULL);
2241		mutex_unlock(&zr->resource_lock);
2242
2243		return res;
2244	}
2245		break;
2246
2247	case VIDIOCGFBUF:
2248	{
2249		struct video_buffer *vbuf = arg;
2250
2251		dprintk(3, KERN_DEBUG "%s: VIDIOCGFBUF\n", ZR_DEVNAME(zr));
2252
2253		mutex_lock(&zr->resource_lock);
2254		*vbuf = zr->buffer;
2255		mutex_unlock(&zr->resource_lock);
2256		return 0;
2257	}
2258		break;
2259
2260	case VIDIOCSFBUF:
2261	{
2262		struct video_buffer *vbuf = arg;
2263		int i, res = 0;
2264
2265		dprintk(3,
2266			KERN_DEBUG
2267			"%s: VIDIOCSFBUF - base=%p, w=%d, h=%d, depth=%d, bpl=%d\n",
2268			ZR_DEVNAME(zr), vbuf->base, vbuf->width,
2269			vbuf->height, vbuf->depth, vbuf->bytesperline);
2270
2271		for (i = 0; i < zoran_num_formats; i++)
2272			if (zoran_formats[i].depth == vbuf->depth)
2273				break;
2274		if (i == zoran_num_formats) {
2275			dprintk(1,
2276				KERN_ERR
2277				"%s: VIDIOCSFBUF - invalid fbuf depth %d\n",
2278				ZR_DEVNAME(zr), vbuf->depth);
2279			return -EINVAL;
2280		}
2281
2282		mutex_lock(&zr->resource_lock);
2283		res =
2284		    setup_fbuffer(file, vbuf->base, &zoran_formats[i],
2285				  vbuf->width, vbuf->height,
2286				  vbuf->bytesperline);
2287		mutex_unlock(&zr->resource_lock);
2288
2289		return res;
2290	}
2291		break;
2292
2293	case VIDIOCSYNC:
2294	{
2295		int *frame = arg, res;
2296
2297		dprintk(3, KERN_DEBUG "%s: VIDIOCSYNC - frame=%d\n",
2298			ZR_DEVNAME(zr), *frame);
2299
2300		mutex_lock(&zr->resource_lock);
2301		res = v4l_sync(file, *frame);
2302		mutex_unlock(&zr->resource_lock);
2303		if (!res)
2304			zr->v4l_sync_tail++;
2305		return res;
2306	}
2307		break;
2308
2309	case VIDIOCMCAPTURE:
2310	{
2311		struct video_mmap *vmap = arg;
2312		int res;
2313
2314		dprintk(3,
2315			KERN_DEBUG
2316			"%s: VIDIOCMCAPTURE - frame=%d, geom=%dx%d, fmt=%d\n",
2317			ZR_DEVNAME(zr), vmap->frame, vmap->width, vmap->height,
2318			vmap->format);
2319
2320		mutex_lock(&zr->resource_lock);
2321		res = v4l_grab(file, vmap);
2322		mutex_unlock(&zr->resource_lock);
2323		return res;
2324	}
2325		break;
2326
2327	case VIDIOCGMBUF:
2328	{
2329		struct video_mbuf *vmbuf = arg;
2330		int i, res = 0;
2331
2332		dprintk(3, KERN_DEBUG "%s: VIDIOCGMBUF\n", ZR_DEVNAME(zr));
2333
2334		vmbuf->size =
2335		    fh->v4l_buffers.num_buffers *
2336		    fh->v4l_buffers.buffer_size;
2337		vmbuf->frames = fh->v4l_buffers.num_buffers;
2338		for (i = 0; i < vmbuf->frames; i++) {
2339			vmbuf->offsets[i] =
2340			    i * fh->v4l_buffers.buffer_size;
2341		}
2342
2343		mutex_lock(&zr->resource_lock);
2344
2345		if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
2346			dprintk(1,
2347				KERN_ERR
2348				"%s: VIDIOCGMBUF - buffers already allocated\n",
2349				ZR_DEVNAME(zr));
2350			res = -EINVAL;
2351			goto v4l1reqbuf_unlock_and_return;
2352		}
2353
2354		if (v4l_fbuffer_alloc(file)) {
2355			res = -ENOMEM;
2356			goto v4l1reqbuf_unlock_and_return;
2357		}
2358
2359		/* The next mmap will map the V4L buffers */
2360		fh->map_mode = ZORAN_MAP_MODE_RAW;
2361	v4l1reqbuf_unlock_and_return:
2362		mutex_unlock(&zr->resource_lock);
2363
2364		return res;
2365	}
2366		break;
2367
2368	case VIDIOCGUNIT:
2369	{
2370		struct video_unit *vunit = arg;
2371
2372		dprintk(3, KERN_DEBUG "%s: VIDIOCGUNIT\n", ZR_DEVNAME(zr));
2373
2374		vunit->video = zr->video_dev->minor;
2375		vunit->vbi = VIDEO_NO_UNIT;
2376		vunit->radio = VIDEO_NO_UNIT;
2377		vunit->audio = VIDEO_NO_UNIT;
2378		vunit->teletext = VIDEO_NO_UNIT;
2379
2380		return 0;
2381	}
2382		break;
2383
2384		/*
2385		 * RJ: In principal we could support subcaptures for V4L grabbing.
2386		 *     Not even the famous BTTV driver has them, however.
2387		 *     If there should be a strong demand, one could consider
2388		 *     to implement them.
2389		 */
2390	case VIDIOCGCAPTURE:
2391	{
2392		dprintk(3, KERN_ERR "%s: VIDIOCGCAPTURE not supported\n",
2393			ZR_DEVNAME(zr));
2394		return -EINVAL;
2395	}
2396		break;
2397
2398	case VIDIOCSCAPTURE:
2399	{
2400		dprintk(3, KERN_ERR "%s: VIDIOCSCAPTURE not supported\n",
2401			ZR_DEVNAME(zr));
2402		return -EINVAL;
2403	}
2404		break;
2405
2406	case BUZIOC_G_PARAMS:
2407	{
2408		struct zoran_params *bparams = arg;
2409
2410		dprintk(3, KERN_DEBUG "%s: BUZIOC_G_PARAMS\n", ZR_DEVNAME(zr));
2411
2412		memset(bparams, 0, sizeof(struct zoran_params));
2413		bparams->major_version = MAJOR_VERSION;
2414		bparams->minor_version = MINOR_VERSION;
2415
2416		mutex_lock(&zr->resource_lock);
2417
2418		bparams->norm = zr->norm;
2419		bparams->input = zr->input;
2420
2421		bparams->decimation = fh->jpg_settings.decimation;
2422		bparams->HorDcm = fh->jpg_settings.HorDcm;
2423		bparams->VerDcm = fh->jpg_settings.VerDcm;
2424		bparams->TmpDcm = fh->jpg_settings.TmpDcm;
2425		bparams->field_per_buff = fh->jpg_settings.field_per_buff;
2426		bparams->img_x = fh->jpg_settings.img_x;
2427		bparams->img_y = fh->jpg_settings.img_y;
2428		bparams->img_width = fh->jpg_settings.img_width;
2429		bparams->img_height = fh->jpg_settings.img_height;
2430		bparams->odd_even = fh->jpg_settings.odd_even;
2431
2432		bparams->quality = fh->jpg_settings.jpg_comp.quality;
2433		bparams->APPn = fh->jpg_settings.jpg_comp.APPn;
2434		bparams->APP_len = fh->jpg_settings.jpg_comp.APP_len;
2435		memcpy(bparams->APP_data,
2436		       fh->jpg_settings.jpg_comp.APP_data,
2437		       sizeof(bparams->APP_data));
2438		bparams->COM_len = zr->jpg_settings.jpg_comp.COM_len;
2439		memcpy(bparams->COM_data,
2440		       fh->jpg_settings.jpg_comp.COM_data,
2441		       sizeof(bparams->COM_data));
2442		bparams->jpeg_markers =
2443		    fh->jpg_settings.jpg_comp.jpeg_markers;
2444
2445		mutex_unlock(&zr->resource_lock);
2446
2447		bparams->VFIFO_FB = 0;
2448
2449		return 0;
2450	}
2451		break;
2452
2453	case BUZIOC_S_PARAMS:
2454	{
2455		struct zoran_params *bparams = arg;
2456		int res = 0;
2457
2458		dprintk(3, KERN_DEBUG "%s: BUZIOC_S_PARAMS\n", ZR_DEVNAME(zr));
2459
2460		settings.decimation = bparams->decimation;
2461		settings.HorDcm = bparams->HorDcm;
2462		settings.VerDcm = bparams->VerDcm;
2463		settings.TmpDcm = bparams->TmpDcm;
2464		settings.field_per_buff = bparams->field_per_buff;
2465		settings.img_x = bparams->img_x;
2466		settings.img_y = bparams->img_y;
2467		settings.img_width = bparams->img_width;
2468		settings.img_height = bparams->img_height;
2469		settings.odd_even = bparams->odd_even;
2470
2471		settings.jpg_comp.quality = bparams->quality;
2472		settings.jpg_comp.APPn = bparams->APPn;
2473		settings.jpg_comp.APP_len = bparams->APP_len;
2474		memcpy(settings.jpg_comp.APP_data, bparams->APP_data,
2475		       sizeof(bparams->APP_data));
2476		settings.jpg_comp.COM_len = bparams->COM_len;
2477		memcpy(settings.jpg_comp.COM_data, bparams->COM_data,
2478		       sizeof(bparams->COM_data));
2479		settings.jpg_comp.jpeg_markers = bparams->jpeg_markers;
2480
2481		mutex_lock(&zr->resource_lock);
2482
2483		if (zr->codec_mode != BUZ_MODE_IDLE) {
2484			dprintk(1,
2485				KERN_ERR
2486				"%s: BUZIOC_S_PARAMS called, but Buz in capture/playback mode\n",
2487				ZR_DEVNAME(zr));
2488			res = -EINVAL;
2489			goto sparams_unlock_and_return;
2490		}
2491
2492		/* Check the params first before overwriting our
2493		 * nternal values */
2494		if (zoran_check_jpg_settings(zr, &settings)) {
2495			res = -EINVAL;
2496			goto sparams_unlock_and_return;
2497		}
2498
2499		fh->jpg_settings = settings;
2500	sparams_unlock_and_return:
2501		mutex_unlock(&zr->resource_lock);
2502
2503		return res;
2504	}
2505		break;
2506
2507	case BUZIOC_REQBUFS:
2508	{
2509		struct zoran_requestbuffers *breq = arg;
2510		int res = 0;
2511
2512		dprintk(3,
2513			KERN_DEBUG
2514			"%s: BUZIOC_REQBUFS - count=%lu, size=%lu\n",
2515			ZR_DEVNAME(zr), breq->count, breq->size);
2516
2517		/* Enforce reasonable lower and upper limits */
2518		if (breq->count < 4)
2519			breq->count = 4;	/* Could be choosen smaller */
2520		if (breq->count > jpg_nbufs)
2521			breq->count = jpg_nbufs;
2522		breq->size = PAGE_ALIGN(breq->size);
2523		if (breq->size < 8192)
2524			breq->size = 8192;	/* Arbitrary */
2525		/* breq->size is limited by 1 page for the stat_com
2526		 * tables to a Maximum of 2 MB */
2527		if (breq->size > jpg_bufsize)
2528			breq->size = jpg_bufsize;
2529		if (fh->jpg_buffers.need_contiguous &&
2530		    breq->size > MAX_KMALLOC_MEM)
2531			breq->size = MAX_KMALLOC_MEM;
2532
2533		mutex_lock(&zr->resource_lock);
2534
2535		if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
2536			dprintk(1,
2537				KERN_ERR
2538				"%s: BUZIOC_REQBUFS - buffers allready allocated\n",
2539				ZR_DEVNAME(zr));
2540			res = -EBUSY;
2541			goto jpgreqbuf_unlock_and_return;
2542		}
2543
2544		fh->jpg_buffers.num_buffers = breq->count;
2545		fh->jpg_buffers.buffer_size = breq->size;
2546
2547		if (jpg_fbuffer_alloc(file)) {
2548			res = -ENOMEM;
2549			goto jpgreqbuf_unlock_and_return;
2550		}
2551
2552		/* The next mmap will map the MJPEG buffers - could
2553		 * also be *_PLAY, but it doesn't matter here */
2554		fh->map_mode = ZORAN_MAP_MODE_JPG_REC;
2555	jpgreqbuf_unlock_and_return:
2556		mutex_unlock(&zr->resource_lock);
2557
2558		return res;
2559	}
2560		break;
2561
2562	case BUZIOC_QBUF_CAPT:
2563	{
2564		int *frame = arg, res;
2565
2566		dprintk(3, KERN_DEBUG "%s: BUZIOC_QBUF_CAPT - frame=%d\n",
2567			ZR_DEVNAME(zr), *frame);
2568
2569		mutex_lock(&zr->resource_lock);
2570		res = jpg_qbuf(file, *frame, BUZ_MODE_MOTION_COMPRESS);
2571		mutex_unlock(&zr->resource_lock);
2572
2573		return res;
2574	}
2575		break;
2576
2577	case BUZIOC_QBUF_PLAY:
2578	{
2579		int *frame = arg, res;
2580
2581		dprintk(3, KERN_DEBUG "%s: BUZIOC_QBUF_PLAY - frame=%d\n",
2582			ZR_DEVNAME(zr), *frame);
2583
2584		mutex_lock(&zr->resource_lock);
2585		res = jpg_qbuf(file, *frame, BUZ_MODE_MOTION_DECOMPRESS);
2586		mutex_unlock(&zr->resource_lock);
2587
2588		return res;
2589	}
2590		break;
2591
2592	case BUZIOC_SYNC:
2593	{
2594		struct zoran_sync *bsync = arg;
2595		int res;
2596
2597		dprintk(3, KERN_DEBUG "%s: BUZIOC_SYNC\n", ZR_DEVNAME(zr));
2598
2599		mutex_lock(&zr->resource_lock);
2600		res = jpg_sync(file, bsync);
2601		mutex_unlock(&zr->resource_lock);
2602
2603		return res;
2604	}
2605		break;
2606
2607	case BUZIOC_G_STATUS:
2608	{
2609		struct zoran_status *bstat = arg;
2610		int norm, input, status, res = 0;
2611
2612		dprintk(3, KERN_DEBUG "%s: BUZIOC_G_STATUS\n", ZR_DEVNAME(zr));
2613
2614		if (zr->codec_mode != BUZ_MODE_IDLE) {
2615			dprintk(1,
2616				KERN_ERR
2617				"%s: BUZIOC_G_STATUS called but Buz in capture/playback mode\n",
2618				ZR_DEVNAME(zr));
2619			return -EINVAL;
2620		}
2621
2622		input = zr->card.input[bstat->input].muxsel;
2623		norm = VIDEO_MODE_AUTO;
2624
2625		mutex_lock(&zr->resource_lock);
2626
2627		if (zr->codec_mode != BUZ_MODE_IDLE) {
2628			dprintk(1,
2629				KERN_ERR
2630				"%s: BUZIOC_G_STATUS called, but Buz in capture/playback mode\n",
2631				ZR_DEVNAME(zr));
2632			res = -EINVAL;
2633			goto gstat_unlock_and_return;
2634		}
2635
2636		decoder_command(zr, DECODER_SET_INPUT, &input);
2637		decoder_command(zr, DECODER_SET_NORM, &norm);
2638
2639		/* sleep 1 second */
2640		ssleep(1);
2641
2642		/* Get status of video decoder */
2643		decoder_command(zr, DECODER_GET_STATUS, &status);
2644
2645		/* restore previous input and norm */
2646		input = zr->card.input[zr->input].muxsel;
2647		decoder_command(zr, DECODER_SET_INPUT, &input);
2648		decoder_command(zr, DECODER_SET_NORM, &zr->norm);
2649	gstat_unlock_and_return:
2650		mutex_unlock(&zr->resource_lock);
2651
2652		if (!res) {
2653			bstat->signal =
2654			    (status & DECODER_STATUS_GOOD) ? 1 : 0;
2655			if (status & DECODER_STATUS_NTSC)
2656				bstat->norm = VIDEO_MODE_NTSC;
2657			else if (status & DECODER_STATUS_SECAM)
2658				bstat->norm = VIDEO_MODE_SECAM;
2659			else
2660				bstat->norm = VIDEO_MODE_PAL;
2661
2662			bstat->color =
2663			    (status & DECODER_STATUS_COLOR) ? 1 : 0;
2664		}
2665
2666		return res;
2667	}
2668		break;
2669
2670#ifdef CONFIG_VIDEO_V4L2
2671
2672		/* The new video4linux2 capture interface - much nicer than video4linux1, since
2673		 * it allows for integrating the JPEG capturing calls inside standard v4l2
2674		 */
2675
2676	case VIDIOC_QUERYCAP:
2677	{
2678		struct v4l2_capability *cap = arg;
2679
2680		dprintk(3, KERN_DEBUG "%s: VIDIOC_QUERYCAP\n", ZR_DEVNAME(zr));
2681
2682		memset(cap, 0, sizeof(*cap));
2683		strncpy(cap->card, ZR_DEVNAME(zr), sizeof(cap->card)-1);
2684		strncpy(cap->driver, "zoran", sizeof(cap->driver)-1);
2685		snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s",
2686			 pci_name(zr->pci_dev));
2687		cap->version =
2688		    KERNEL_VERSION(MAJOR_VERSION, MINOR_VERSION,
2689				   RELEASE_VERSION);
2690		cap->capabilities = ZORAN_V4L2_VID_FLAGS;
2691
2692		return 0;
2693	}
2694		break;
2695
2696	case VIDIOC_ENUM_FMT:
2697	{
2698		struct v4l2_fmtdesc *fmt = arg;
2699		int index = fmt->index, num = -1, i, flag = 0, type =
2700		    fmt->type;
2701
2702		dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUM_FMT - index=%d\n",
2703			ZR_DEVNAME(zr), fmt->index);
2704
2705		switch (fmt->type) {
2706		case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2707			flag = ZORAN_FORMAT_CAPTURE;
2708			break;
2709		case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2710			flag = ZORAN_FORMAT_PLAYBACK;
2711			break;
2712		case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2713			flag = ZORAN_FORMAT_OVERLAY;
2714			break;
2715		default:
2716			dprintk(1,
2717				KERN_ERR
2718				"%s: VIDIOC_ENUM_FMT - unknown type %d\n",
2719				ZR_DEVNAME(zr), fmt->type);
2720			return -EINVAL;
2721		}
2722
2723		for (i = 0; i < zoran_num_formats; i++) {
2724			if (zoran_formats[i].flags & flag)
2725				num++;
2726			if (num == fmt->index)
2727				break;
2728		}
2729		if (fmt->index < 0 /* late, but not too late */  ||
2730		    i == zoran_num_formats)
2731			return -EINVAL;
2732
2733		memset(fmt, 0, sizeof(*fmt));
2734		fmt->index = index;
2735		fmt->type = type;
2736		strncpy(fmt->description, zoran_formats[i].name, sizeof(fmt->description)-1);
2737		fmt->pixelformat = zoran_formats[i].fourcc;
2738		if (zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED)
2739			fmt->flags |= V4L2_FMT_FLAG_COMPRESSED;
2740
2741		return 0;
2742	}
2743		break;
2744
2745	case VIDIOC_G_FMT:
2746	{
2747		struct v4l2_format *fmt = arg;
2748		int type = fmt->type;
2749
2750		dprintk(5, KERN_DEBUG "%s: VIDIOC_G_FMT\n", ZR_DEVNAME(zr));
2751
2752		memset(fmt, 0, sizeof(*fmt));
2753		fmt->type = type;
2754
2755		switch (fmt->type) {
2756		case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2757
2758			mutex_lock(&zr->resource_lock);
2759
2760			fmt->fmt.win.w.left = fh->overlay_settings.x;
2761			fmt->fmt.win.w.top = fh->overlay_settings.y;
2762			fmt->fmt.win.w.width = fh->overlay_settings.width;
2763			fmt->fmt.win.w.height =
2764			    fh->overlay_settings.height;
2765			if (fh->overlay_settings.width * 2 >
2766			    BUZ_MAX_HEIGHT)
2767				fmt->fmt.win.field = V4L2_FIELD_INTERLACED;
2768			else
2769				fmt->fmt.win.field = V4L2_FIELD_TOP;
2770
2771			mutex_unlock(&zr->resource_lock);
2772
2773			break;
2774
2775		case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2776		case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2777
2778			mutex_lock(&zr->resource_lock);
2779
2780			if (fmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2781			    fh->map_mode == ZORAN_MAP_MODE_RAW) {
2782
2783				fmt->fmt.pix.width =
2784				    fh->v4l_settings.width;
2785				fmt->fmt.pix.height =
2786				    fh->v4l_settings.height;
2787				fmt->fmt.pix.sizeimage =
2788				    fh->v4l_buffers.buffer_size;
2789				fmt->fmt.pix.pixelformat =
2790				    fh->v4l_settings.format->fourcc;
2791				fmt->fmt.pix.colorspace =
2792				    fh->v4l_settings.format->colorspace;
2793				fmt->fmt.pix.bytesperline = 0;
2794				if (BUZ_MAX_HEIGHT <
2795				    (fh->v4l_settings.height * 2))
2796					fmt->fmt.pix.field =
2797					    V4L2_FIELD_INTERLACED;
2798				else
2799					fmt->fmt.pix.field =
2800					    V4L2_FIELD_TOP;
2801
2802			} else {
2803
2804				fmt->fmt.pix.width =
2805				    fh->jpg_settings.img_width /
2806				    fh->jpg_settings.HorDcm;
2807				fmt->fmt.pix.height =
2808				    fh->jpg_settings.img_height /
2809				    (fh->jpg_settings.VerDcm *
2810				     fh->jpg_settings.TmpDcm);
2811				fmt->fmt.pix.sizeimage =
2812				    zoran_v4l2_calc_bufsize(&fh->
2813							    jpg_settings);
2814				fmt->fmt.pix.pixelformat =
2815				    V4L2_PIX_FMT_MJPEG;
2816				if (fh->jpg_settings.TmpDcm == 1)
2817					fmt->fmt.pix.field =
2818					    (fh->jpg_settings.
2819					     odd_even ? V4L2_FIELD_SEQ_BT :
2820					     V4L2_FIELD_SEQ_BT);
2821				else
2822					fmt->fmt.pix.field =
2823					    (fh->jpg_settings.
2824					     odd_even ? V4L2_FIELD_TOP :
2825					     V4L2_FIELD_BOTTOM);
2826
2827				fmt->fmt.pix.bytesperline = 0;
2828				fmt->fmt.pix.colorspace =
2829				    V4L2_COLORSPACE_SMPTE170M;
2830			}
2831
2832			mutex_unlock(&zr->resource_lock);
2833
2834			break;
2835
2836		default:
2837			dprintk(1,
2838				KERN_ERR
2839				"%s: VIDIOC_G_FMT - unsupported type %d\n",
2840				ZR_DEVNAME(zr), fmt->type);
2841			return -EINVAL;
2842		}
2843		return 0;
2844	}
2845		break;
2846
2847	case VIDIOC_S_FMT:
2848	{
2849		struct v4l2_format *fmt = arg;
2850		int i, res = 0;
2851		__u32 printformat;
2852
2853		dprintk(3, KERN_DEBUG "%s: VIDIOC_S_FMT - type=%d, ",
2854			ZR_DEVNAME(zr), fmt->type);
2855
2856		switch (fmt->type) {
2857		case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2858
2859			dprintk(3, "x=%d, y=%d, w=%d, h=%d, cnt=%d, map=0x%p\n",
2860				fmt->fmt.win.w.left, fmt->fmt.win.w.top,
2861				fmt->fmt.win.w.width,
2862				fmt->fmt.win.w.height,
2863				fmt->fmt.win.clipcount,
2864				fmt->fmt.win.bitmap);
2865			mutex_lock(&zr->resource_lock);
2866			res =
2867			    setup_window(file, fmt->fmt.win.w.left,
2868					 fmt->fmt.win.w.top,
2869					 fmt->fmt.win.w.width,
2870					 fmt->fmt.win.w.height,
2871					 (struct video_clip __user *)
2872					   fmt->fmt.win.clips,
2873					 fmt->fmt.win.clipcount,
2874					 fmt->fmt.win.bitmap);
2875			mutex_unlock(&zr->resource_lock);
2876			return res;
2877			break;
2878
2879		case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2880		case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2881
2882			printformat =
2883			    __cpu_to_le32(fmt->fmt.pix.pixelformat);
2884			dprintk(3, "size=%dx%d, fmt=0x%x (%4.4s)\n",
2885				fmt->fmt.pix.width, fmt->fmt.pix.height,
2886				fmt->fmt.pix.pixelformat,
2887				(char *) &printformat);
2888
2889			if (fmt->fmt.pix.bytesperline > 0) {
2890				dprintk(5,
2891					KERN_ERR "%s: bpl not supported\n",
2892					ZR_DEVNAME(zr));
2893				return -EINVAL;
2894			}
2895
2896			/* we can be requested to do JPEG/raw playback/capture */
2897			if (!
2898			    (fmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2899			     (fmt->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
2900			      fmt->fmt.pix.pixelformat ==
2901			      V4L2_PIX_FMT_MJPEG))) {
2902				dprintk(1,
2903					KERN_ERR
2904					"%s: VIDIOC_S_FMT - unknown type %d/0x%x(%4.4s) combination\n",
2905					ZR_DEVNAME(zr), fmt->type,
2906					fmt->fmt.pix.pixelformat,
2907					(char *) &printformat);
2908				return -EINVAL;
2909			}
2910
2911			if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {
2912				mutex_lock(&zr->resource_lock);
2913
2914				settings = fh->jpg_settings;
2915
2916				if (fh->v4l_buffers.allocated ||
2917				    fh->jpg_buffers.allocated) {
2918					dprintk(1,
2919						KERN_ERR
2920						"%s: VIDIOC_S_FMT - cannot change capture mode\n",
2921						ZR_DEVNAME(zr));
2922					res = -EBUSY;
2923					goto sfmtjpg_unlock_and_return;
2924				}
2925
2926				/* we actually need to set 'real' parameters now */
2927				if ((fmt->fmt.pix.height * 2) >
2928				    BUZ_MAX_HEIGHT)
2929					settings.TmpDcm = 1;
2930				else
2931					settings.TmpDcm = 2;
2932				settings.decimation = 0;
2933				if (fmt->fmt.pix.height <=
2934				    fh->jpg_settings.img_height / 2)
2935					settings.VerDcm = 2;
2936				else
2937					settings.VerDcm = 1;
2938				if (fmt->fmt.pix.width <=
2939				    fh->jpg_settings.img_width / 4)
2940					settings.HorDcm = 4;
2941				else if (fmt->fmt.pix.width <=
2942					 fh->jpg_settings.img_width / 2)
2943					settings.HorDcm = 2;
2944				else
2945					settings.HorDcm = 1;
2946				if (settings.TmpDcm == 1)
2947					settings.field_per_buff = 2;
2948				else
2949					settings.field_per_buff = 1;
2950
2951				/* check */
2952				if ((res =
2953				     zoran_check_jpg_settings(zr,
2954							      &settings)))
2955					goto sfmtjpg_unlock_and_return;
2956
2957				/* it's ok, so set them */
2958				fh->jpg_settings = settings;
2959
2960				/* tell the user what we actually did */
2961				fmt->fmt.pix.width =
2962				    settings.img_width / settings.HorDcm;
2963				fmt->fmt.pix.height =
2964				    settings.img_height * 2 /
2965				    (settings.TmpDcm * settings.VerDcm);
2966				if (settings.TmpDcm == 1)
2967					fmt->fmt.pix.field =
2968					    (fh->jpg_settings.
2969					     odd_even ? V4L2_FIELD_SEQ_TB :
2970					     V4L2_FIELD_SEQ_BT);
2971				else
2972					fmt->fmt.pix.field =
2973					    (fh->jpg_settings.
2974					     odd_even ? V4L2_FIELD_TOP :
2975					     V4L2_FIELD_BOTTOM);
2976				fh->jpg_buffers.buffer_size =
2977				    zoran_v4l2_calc_bufsize(&fh->
2978							    jpg_settings);
2979				fmt->fmt.pix.sizeimage =
2980				    fh->jpg_buffers.buffer_size;
2981
2982				/* we hereby abuse this variable to show that
2983				 * we're gonna do mjpeg capture */
2984				fh->map_mode =
2985				    (fmt->type ==
2986				     V4L2_BUF_TYPE_VIDEO_CAPTURE) ?
2987				    ZORAN_MAP_MODE_JPG_REC :
2988				    ZORAN_MAP_MODE_JPG_PLAY;
2989			sfmtjpg_unlock_and_return:
2990				mutex_unlock(&zr->resource_lock);
2991			} else {
2992				for (i = 0; i < zoran_num_formats; i++)
2993					if (fmt->fmt.pix.pixelformat ==
2994					    zoran_formats[i].fourcc)
2995						break;
2996				if (i == zoran_num_formats) {
2997					dprintk(1,
2998						KERN_ERR
2999						"%s: VIDIOC_S_FMT - unknown/unsupported format 0x%x (%4.4s)\n",
3000						ZR_DEVNAME(zr),
3001						fmt->fmt.pix.pixelformat,
3002						(char *) &printformat);
3003					return -EINVAL;
3004				}
3005				mutex_lock(&zr->resource_lock);
3006				if (fh->jpg_buffers.allocated ||
3007				    (fh->v4l_buffers.allocated &&
3008				     fh->v4l_buffers.active !=
3009				     ZORAN_FREE)) {
3010					dprintk(1,
3011						KERN_ERR
3012						"%s: VIDIOC_S_FMT - cannot change capture mode\n",
3013						ZR_DEVNAME(zr));
3014					res = -EBUSY;
3015					goto sfmtv4l_unlock_and_return;
3016				}
3017				if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
3018					fmt->fmt.pix.height =
3019					    BUZ_MAX_HEIGHT;
3020				if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
3021					fmt->fmt.pix.width = BUZ_MAX_WIDTH;
3022
3023				if ((res =
3024				     zoran_v4l_set_format(file,
3025							  fmt->fmt.pix.
3026							  width,
3027							  fmt->fmt.pix.
3028							  height,
3029							  &zoran_formats
3030							  [i])))
3031					goto sfmtv4l_unlock_and_return;
3032
3033				/* tell the user the
3034				 * results/missing stuff */
3035				fmt->fmt.pix.sizeimage = fh->v4l_buffers.buffer_size	/*zr->gbpl * zr->gheight */
3036				    ;
3037				if (BUZ_MAX_HEIGHT <
3038				    (fh->v4l_settings.height * 2))
3039					fmt->fmt.pix.field =
3040					    V4L2_FIELD_INTERLACED;
3041				else
3042					fmt->fmt.pix.field =
3043					    V4L2_FIELD_TOP;
3044
3045				fh->map_mode = ZORAN_MAP_MODE_RAW;
3046			sfmtv4l_unlock_and_return:
3047				mutex_unlock(&zr->resource_lock);
3048			}
3049
3050			break;
3051
3052		default:
3053			dprintk(3, "unsupported\n");
3054			dprintk(1,
3055				KERN_ERR
3056				"%s: VIDIOC_S_FMT - unsupported type %d\n",
3057				ZR_DEVNAME(zr), fmt->type);
3058			return -EINVAL;
3059		}
3060
3061		return res;
3062	}
3063		break;
3064
3065	case VIDIOC_G_FBUF:
3066	{
3067		struct v4l2_framebuffer *fb = arg;
3068
3069		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_FBUF\n", ZR_DEVNAME(zr));
3070
3071		memset(fb, 0, sizeof(*fb));
3072		mutex_lock(&zr->resource_lock);
3073		fb->base = zr->buffer.base;
3074		fb->fmt.width = zr->buffer.width;
3075		fb->fmt.height = zr->buffer.height;
3076		if (zr->overlay_settings.format) {
3077			fb->fmt.pixelformat =
3078				fh->overlay_settings.format->fourcc;
3079		}
3080		fb->fmt.bytesperline = zr->buffer.bytesperline;
3081		mutex_unlock(&zr->resource_lock);
3082		fb->fmt.colorspace = V4L2_COLORSPACE_SRGB;
3083		fb->fmt.field = V4L2_FIELD_INTERLACED;
3084		fb->flags = V4L2_FBUF_FLAG_OVERLAY;
3085		fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
3086
3087		return 0;
3088	}
3089		break;
3090
3091	case VIDIOC_S_FBUF:
3092	{
3093		int i, res = 0;
3094		struct v4l2_framebuffer *fb = arg;
3095		__u32 printformat = __cpu_to_le32(fb->fmt.pixelformat);
3096
3097		dprintk(3,
3098			KERN_DEBUG
3099			"%s: VIDIOC_S_FBUF - base=0x%p, size=%dx%d, bpl=%d, fmt=0x%x (%4.4s)\n",
3100			ZR_DEVNAME(zr), fb->base, fb->fmt.width, fb->fmt.height,
3101			fb->fmt.bytesperline, fb->fmt.pixelformat,
3102			(char *) &printformat);
3103
3104		for (i = 0; i < zoran_num_formats; i++)
3105			if (zoran_formats[i].fourcc == fb->fmt.pixelformat)
3106				break;
3107		if (i == zoran_num_formats) {
3108			dprintk(1,
3109				KERN_ERR
3110				"%s: VIDIOC_S_FBUF - format=0x%x (%4.4s) not allowed\n",
3111				ZR_DEVNAME(zr), fb->fmt.pixelformat,
3112				(char *) &printformat);
3113			return -EINVAL;
3114		}
3115
3116		mutex_lock(&zr->resource_lock);
3117		res =
3118		    setup_fbuffer(file, fb->base, &zoran_formats[i],
3119				  fb->fmt.width, fb->fmt.height,
3120				  fb->fmt.bytesperline);
3121		mutex_unlock(&zr->resource_lock);
3122
3123		return res;
3124	}
3125		break;
3126
3127	case VIDIOC_OVERLAY:
3128	{
3129		int *on = arg, res;
3130
3131		dprintk(3, KERN_DEBUG "%s: VIDIOC_PREVIEW - on=%d\n",
3132			ZR_DEVNAME(zr), *on);
3133
3134		mutex_lock(&zr->resource_lock);
3135		res = setup_overlay(file, *on);
3136		mutex_unlock(&zr->resource_lock);
3137
3138		return res;
3139	}
3140		break;
3141
3142	case VIDIOC_REQBUFS:
3143	{
3144		struct v4l2_requestbuffers *req = arg;
3145		int res = 0;
3146
3147		dprintk(3, KERN_DEBUG "%s: VIDIOC_REQBUFS - type=%d\n",
3148			ZR_DEVNAME(zr), req->type);
3149
3150		if (req->memory != V4L2_MEMORY_MMAP) {
3151			dprintk(1,
3152				KERN_ERR
3153				"%s: only MEMORY_MMAP capture is supported, not %d\n",
3154				ZR_DEVNAME(zr), req->memory);
3155			return -EINVAL;
3156		}
3157
3158		mutex_lock(&zr->resource_lock);
3159
3160		if (fh->v4l_buffers.allocated || fh->jpg_buffers.allocated) {
3161			dprintk(1,
3162				KERN_ERR
3163				"%s: VIDIOC_REQBUFS - buffers allready allocated\n",
3164				ZR_DEVNAME(zr));
3165			res = -EBUSY;
3166			goto v4l2reqbuf_unlock_and_return;
3167		}
3168
3169		if (fh->map_mode == ZORAN_MAP_MODE_RAW &&
3170		    req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3171
3172			/* control user input */
3173			if (req->count < 2)
3174				req->count = 2;
3175			if (req->count > v4l_nbufs)
3176				req->count = v4l_nbufs;
3177			fh->v4l_buffers.num_buffers = req->count;
3178
3179			if (v4l_fbuffer_alloc(file)) {
3180				res = -ENOMEM;
3181				goto v4l2reqbuf_unlock_and_return;
3182			}
3183
3184			/* The next mmap will map the V4L buffers */
3185			fh->map_mode = ZORAN_MAP_MODE_RAW;
3186
3187		} else if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC ||
3188			   fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
3189
3190			/* we need to calculate size ourselves now */
3191			if (req->count < 4)
3192				req->count = 4;
3193			if (req->count > jpg_nbufs)
3194				req->count = jpg_nbufs;
3195			fh->jpg_buffers.num_buffers = req->count;
3196			fh->jpg_buffers.buffer_size =
3197			    zoran_v4l2_calc_bufsize(&fh->jpg_settings);
3198
3199			if (jpg_fbuffer_alloc(file)) {
3200				res = -ENOMEM;
3201				goto v4l2reqbuf_unlock_and_return;
3202			}
3203
3204			/* The next mmap will map the MJPEG buffers */
3205			if (req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
3206				fh->map_mode = ZORAN_MAP_MODE_JPG_REC;
3207			else
3208				fh->map_mode = ZORAN_MAP_MODE_JPG_PLAY;
3209
3210		} else {
3211			dprintk(1,
3212				KERN_ERR
3213				"%s: VIDIOC_REQBUFS - unknown type %d\n",
3214				ZR_DEVNAME(zr), req->type);
3215			res = -EINVAL;
3216			goto v4l2reqbuf_unlock_and_return;
3217		}
3218	v4l2reqbuf_unlock_and_return:
3219		mutex_unlock(&zr->resource_lock);
3220
3221		return 0;
3222	}
3223		break;
3224
3225	case VIDIOC_QUERYBUF:
3226	{
3227		struct v4l2_buffer *buf = arg;
3228		__u32 type = buf->type;
3229		int index = buf->index, res;
3230
3231		dprintk(3,
3232			KERN_DEBUG
3233			"%s: VIDIOC_QUERYBUF - index=%d, type=%d\n",
3234			ZR_DEVNAME(zr), buf->index, buf->type);
3235
3236		memset(buf, 0, sizeof(buf));
3237		buf->type = type;
3238		buf->index = index;
3239
3240		mutex_lock(&zr->resource_lock);
3241		res = zoran_v4l2_buffer_status(file, buf, buf->index);
3242		mutex_unlock(&zr->resource_lock);
3243
3244		return res;
3245	}
3246		break;
3247
3248	case VIDIOC_QBUF:
3249	{
3250		struct v4l2_buffer *buf = arg;
3251		int res = 0, codec_mode, buf_type;
3252
3253		dprintk(3,
3254			KERN_DEBUG "%s: VIDIOC_QBUF - type=%d, index=%d\n",
3255			ZR_DEVNAME(zr), buf->type, buf->index);
3256
3257		mutex_lock(&zr->resource_lock);
3258
3259		switch (fh->map_mode) {
3260		case ZORAN_MAP_MODE_RAW:
3261			if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3262				dprintk(1,
3263					KERN_ERR
3264					"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3265					ZR_DEVNAME(zr), buf->type, fh->map_mode);
3266				res = -EINVAL;
3267				goto qbuf_unlock_and_return;
3268			}
3269
3270			res = zoran_v4l_queue_frame(file, buf->index);
3271			if (res)
3272				goto qbuf_unlock_and_return;
3273			if (!zr->v4l_memgrab_active &&
3274			    fh->v4l_buffers.active == ZORAN_LOCKED)
3275				zr36057_set_memgrab(zr, 1);
3276			break;
3277
3278		case ZORAN_MAP_MODE_JPG_REC:
3279		case ZORAN_MAP_MODE_JPG_PLAY:
3280			if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
3281				buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
3282				codec_mode = BUZ_MODE_MOTION_DECOMPRESS;
3283			} else {
3284				buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3285				codec_mode = BUZ_MODE_MOTION_COMPRESS;
3286			}
3287
3288			if (buf->type != buf_type) {
3289				dprintk(1,
3290					KERN_ERR
3291					"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3292					ZR_DEVNAME(zr), buf->type, fh->map_mode);
3293				res = -EINVAL;
3294				goto qbuf_unlock_and_return;
3295			}
3296
3297			res =
3298			    zoran_jpg_queue_frame(file, buf->index,
3299						  codec_mode);
3300			if (res != 0)
3301				goto qbuf_unlock_and_return;
3302			if (zr->codec_mode == BUZ_MODE_IDLE &&
3303			    fh->jpg_buffers.active == ZORAN_LOCKED) {
3304				zr36057_enable_jpg(zr, codec_mode);
3305			}
3306			break;
3307
3308		default:
3309			dprintk(1,
3310				KERN_ERR
3311				"%s: VIDIOC_QBUF - unsupported type %d\n",
3312				ZR_DEVNAME(zr), buf->type);
3313			res = -EINVAL;
3314			goto qbuf_unlock_and_return;
3315		}
3316	qbuf_unlock_and_return:
3317		mutex_unlock(&zr->resource_lock);
3318
3319		return res;
3320	}
3321		break;
3322
3323	case VIDIOC_DQBUF:
3324	{
3325		struct v4l2_buffer *buf = arg;
3326		int res = 0, buf_type, num = -1;	/* compiler borks here (?) */
3327
3328		dprintk(3, KERN_DEBUG "%s: VIDIOC_DQBUF - type=%d\n",
3329			ZR_DEVNAME(zr), buf->type);
3330
3331		mutex_lock(&zr->resource_lock);
3332
3333		switch (fh->map_mode) {
3334		case ZORAN_MAP_MODE_RAW:
3335			if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3336				dprintk(1,
3337					KERN_ERR
3338					"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3339					ZR_DEVNAME(zr), buf->type, fh->map_mode);
3340				res = -EINVAL;
3341				goto dqbuf_unlock_and_return;
3342			}
3343
3344			num = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
3345			if (file->f_flags & O_NONBLOCK &&
3346			    zr->v4l_buffers.buffer[num].state !=
3347			    BUZ_STATE_DONE) {
3348				res = -EAGAIN;
3349				goto dqbuf_unlock_and_return;
3350			}
3351			res = v4l_sync(file, num);
3352			if (res)
3353				goto dqbuf_unlock_and_return;
3354			else
3355				zr->v4l_sync_tail++;
3356			res = zoran_v4l2_buffer_status(file, buf, num);
3357			break;
3358
3359		case ZORAN_MAP_MODE_JPG_REC:
3360		case ZORAN_MAP_MODE_JPG_PLAY:
3361		{
3362			struct zoran_sync bs;
3363
3364			if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY)
3365				buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
3366			else
3367				buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3368
3369			if (buf->type != buf_type) {
3370				dprintk(1,
3371					KERN_ERR
3372					"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3373					ZR_DEVNAME(zr), buf->type, fh->map_mode);
3374				res = -EINVAL;
3375				goto dqbuf_unlock_and_return;
3376			}
3377
3378			num =
3379			    zr->jpg_pend[zr->
3380					 jpg_que_tail & BUZ_MASK_FRAME];
3381
3382			if (file->f_flags & O_NONBLOCK &&
3383			    zr->jpg_buffers.buffer[num].state !=
3384			    BUZ_STATE_DONE) {
3385				res = -EAGAIN;
3386				goto dqbuf_unlock_and_return;
3387			}
3388			res = jpg_sync(file, &bs);
3389			if (res)
3390				goto dqbuf_unlock_and_return;
3391			res =
3392			    zoran_v4l2_buffer_status(file, buf, bs.frame);
3393			break;
3394		}
3395
3396		default:
3397			dprintk(1,
3398				KERN_ERR
3399				"%s: VIDIOC_DQBUF - unsupported type %d\n",
3400				ZR_DEVNAME(zr), buf->type);
3401			res = -EINVAL;
3402			goto dqbuf_unlock_and_return;
3403		}
3404	dqbuf_unlock_and_return:
3405		mutex_unlock(&zr->resource_lock);
3406
3407		return res;
3408	}
3409		break;
3410
3411	case VIDIOC_STREAMON:
3412	{
3413		int res = 0;
3414
3415		dprintk(3, KERN_DEBUG "%s: VIDIOC_STREAMON\n", ZR_DEVNAME(zr));
3416
3417		mutex_lock(&zr->resource_lock);
3418
3419		switch (fh->map_mode) {
3420		case ZORAN_MAP_MODE_RAW:	/* raw capture */
3421			if (zr->v4l_buffers.active != ZORAN_ACTIVE ||
3422			    fh->v4l_buffers.active != ZORAN_ACTIVE) {
3423				res = -EBUSY;
3424				goto strmon_unlock_and_return;
3425			}
3426
3427			zr->v4l_buffers.active = fh->v4l_buffers.active =
3428			    ZORAN_LOCKED;
3429			zr->v4l_settings = fh->v4l_settings;
3430
3431			zr->v4l_sync_tail = zr->v4l_pend_tail;
3432			if (!zr->v4l_memgrab_active &&
3433			    zr->v4l_pend_head != zr->v4l_pend_tail) {
3434				zr36057_set_memgrab(zr, 1);
3435			}
3436			break;
3437
3438		case ZORAN_MAP_MODE_JPG_REC:
3439		case ZORAN_MAP_MODE_JPG_PLAY:
3440			/* what is the codec mode right now? */
3441			if (zr->jpg_buffers.active != ZORAN_ACTIVE ||
3442			    fh->jpg_buffers.active != ZORAN_ACTIVE) {
3443				res = -EBUSY;
3444				goto strmon_unlock_and_return;
3445			}
3446
3447			zr->jpg_buffers.active = fh->jpg_buffers.active =
3448			    ZORAN_LOCKED;
3449
3450			if (zr->jpg_que_head != zr->jpg_que_tail) {
3451				/* Start the jpeg codec when the first frame is queued  */
3452				jpeg_start(zr);
3453			}
3454
3455			break;
3456		default:
3457			dprintk(1,
3458				KERN_ERR
3459				"%s: VIDIOC_STREAMON - invalid map mode %d\n",
3460				ZR_DEVNAME(zr), fh->map_mode);
3461			res = -EINVAL;
3462			goto strmon_unlock_and_return;
3463		}
3464	strmon_unlock_and_return:
3465		mutex_unlock(&zr->resource_lock);
3466
3467		return res;
3468	}
3469		break;
3470
3471	case VIDIOC_STREAMOFF:
3472	{
3473		int i, res = 0;
3474
3475		dprintk(3, KERN_DEBUG "%s: VIDIOC_STREAMOFF\n", ZR_DEVNAME(zr));
3476
3477		mutex_lock(&zr->resource_lock);
3478
3479		switch (fh->map_mode) {
3480		case ZORAN_MAP_MODE_RAW:	/* raw capture */
3481			if (fh->v4l_buffers.active == ZORAN_FREE &&
3482			    zr->v4l_buffers.active != ZORAN_FREE) {
3483				res = -EPERM;	/* stay off other's settings! */
3484				goto strmoff_unlock_and_return;
3485			}
3486			if (zr->v4l_buffers.active == ZORAN_FREE)
3487				goto strmoff_unlock_and_return;
3488
3489			/* unload capture */
3490			if (zr->v4l_memgrab_active)
3491				zr36057_set_memgrab(zr, 0);
3492
3493			for (i = 0; i < fh->v4l_buffers.num_buffers; i++)
3494				zr->v4l_buffers.buffer[i].state =
3495				    BUZ_STATE_USER;
3496			fh->v4l_buffers = zr->v4l_buffers;
3497
3498			zr->v4l_buffers.active = fh->v4l_buffers.active =
3499			    ZORAN_FREE;
3500
3501			zr->v4l_grab_seq = 0;
3502			zr->v4l_pend_head = zr->v4l_pend_tail = 0;
3503			zr->v4l_sync_tail = 0;
3504
3505			break;
3506
3507		case ZORAN_MAP_MODE_JPG_REC:
3508		case ZORAN_MAP_MODE_JPG_PLAY:
3509			if (fh->jpg_buffers.active == ZORAN_FREE &&
3510			    zr->jpg_buffers.active != ZORAN_FREE) {
3511				res = -EPERM;	/* stay off other's settings! */
3512				goto strmoff_unlock_and_return;
3513			}
3514			if (zr->jpg_buffers.active == ZORAN_FREE)
3515				goto strmoff_unlock_and_return;
3516
3517			res =
3518			    jpg_qbuf(file, -1,
3519				     (fh->map_mode ==
3520				      ZORAN_MAP_MODE_JPG_REC) ?
3521				     BUZ_MODE_MOTION_COMPRESS :
3522				     BUZ_MODE_MOTION_DECOMPRESS);
3523			if (res)
3524				goto strmoff_unlock_and_return;
3525			break;
3526		default:
3527			dprintk(1,
3528				KERN_ERR
3529				"%s: VIDIOC_STREAMOFF - invalid map mode %d\n",
3530				ZR_DEVNAME(zr), fh->map_mode);
3531			res = -EINVAL;
3532			goto strmoff_unlock_and_return;
3533		}
3534	strmoff_unlock_and_return:
3535		mutex_unlock(&zr->resource_lock);
3536
3537		return res;
3538	}
3539		break;
3540
3541	case VIDIOC_QUERYCTRL:
3542	{
3543		struct v4l2_queryctrl *ctrl = arg;
3544
3545		dprintk(3, KERN_DEBUG "%s: VIDIOC_QUERYCTRL - id=%d\n",
3546			ZR_DEVNAME(zr), ctrl->id);
3547
3548		/* we only support hue/saturation/contrast/brightness */
3549		if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3550		    ctrl->id > V4L2_CID_HUE)
3551			return -EINVAL;
3552		else {
3553			int id = ctrl->id;
3554			memset(ctrl, 0, sizeof(*ctrl));
3555			ctrl->id = id;
3556		}
3557
3558		switch (ctrl->id) {
3559		case V4L2_CID_BRIGHTNESS:
3560			strncpy(ctrl->name, "Brightness", sizeof(ctrl->name)-1);
3561			break;
3562		case V4L2_CID_CONTRAST:
3563			strncpy(ctrl->name, "Contrast", sizeof(ctrl->name)-1);
3564			break;
3565		case V4L2_CID_SATURATION:
3566			strncpy(ctrl->name, "Saturation", sizeof(ctrl->name)-1);
3567			break;
3568		case V4L2_CID_HUE:
3569			strncpy(ctrl->name, "Hue", sizeof(ctrl->name)-1);
3570			break;
3571		}
3572
3573		ctrl->minimum = 0;
3574		ctrl->maximum = 65535;
3575		ctrl->step = 1;
3576		ctrl->default_value = 32768;
3577		ctrl->type = V4L2_CTRL_TYPE_INTEGER;
3578
3579		return 0;
3580	}
3581		break;
3582
3583	case VIDIOC_G_CTRL:
3584	{
3585		struct v4l2_control *ctrl = arg;
3586
3587		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_CTRL - id=%d\n",
3588			ZR_DEVNAME(zr), ctrl->id);
3589
3590		/* we only support hue/saturation/contrast/brightness */
3591		if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3592		    ctrl->id > V4L2_CID_HUE)
3593			return -EINVAL;
3594
3595		mutex_lock(&zr->resource_lock);
3596		switch (ctrl->id) {
3597		case V4L2_CID_BRIGHTNESS:
3598			ctrl->value = zr->brightness;
3599			break;
3600		case V4L2_CID_CONTRAST:
3601			ctrl->value = zr->contrast;
3602			break;
3603		case V4L2_CID_SATURATION:
3604			ctrl->value = zr->saturation;
3605			break;
3606		case V4L2_CID_HUE:
3607			ctrl->value = zr->hue;
3608			break;
3609		}
3610		mutex_unlock(&zr->resource_lock);
3611
3612		return 0;
3613	}
3614		break;
3615
3616	case VIDIOC_S_CTRL:
3617	{
3618		struct v4l2_control *ctrl = arg;
3619		struct video_picture pict;
3620
3621		dprintk(3, KERN_DEBUG "%s: VIDIOC_S_CTRL - id=%d\n",
3622			ZR_DEVNAME(zr), ctrl->id);
3623
3624		/* we only support hue/saturation/contrast/brightness */
3625		if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3626		    ctrl->id > V4L2_CID_HUE)
3627			return -EINVAL;
3628
3629		if (ctrl->value < 0 || ctrl->value > 65535) {
3630			dprintk(1,
3631				KERN_ERR
3632				"%s: VIDIOC_S_CTRL - invalid value %d for id=%d\n",
3633				ZR_DEVNAME(zr), ctrl->value, ctrl->id);
3634			return -EINVAL;
3635		}
3636
3637		mutex_lock(&zr->resource_lock);
3638		switch (ctrl->id) {
3639		case V4L2_CID_BRIGHTNESS:
3640			zr->brightness = ctrl->value;
3641			break;
3642		case V4L2_CID_CONTRAST:
3643			zr->contrast = ctrl->value;
3644			break;
3645		case V4L2_CID_SATURATION:
3646			zr->saturation = ctrl->value;
3647			break;
3648		case V4L2_CID_HUE:
3649			zr->hue = ctrl->value;
3650			break;
3651		}
3652		pict.brightness = zr->brightness;
3653		pict.contrast = zr->contrast;
3654		pict.colour = zr->saturation;
3655		pict.hue = zr->hue;
3656
3657		decoder_command(zr, DECODER_SET_PICTURE, &pict);
3658
3659		mutex_unlock(&zr->resource_lock);
3660
3661		return 0;
3662	}
3663		break;
3664
3665	case VIDIOC_ENUMSTD:
3666	{
3667		struct v4l2_standard *std = arg;
3668
3669		dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMSTD - index=%d\n",
3670			ZR_DEVNAME(zr), std->index);
3671
3672		if (std->index < 0 || std->index >= (zr->card.norms + 1))
3673			return -EINVAL;
3674		else {
3675			int id = std->index;
3676			memset(std, 0, sizeof(*std));
3677			std->index = id;
3678		}
3679
3680		if (std->index == zr->card.norms) {
3681			/* if we have autodetect, ... */
3682			struct video_decoder_capability caps;
3683			decoder_command(zr, DECODER_GET_CAPABILITIES,
3684					&caps);
3685			if (caps.flags & VIDEO_DECODER_AUTO) {
3686				std->id = V4L2_STD_ALL;
3687				strncpy(std->name, "Autodetect", sizeof(std->name)-1);
3688				return 0;
3689			} else
3690				return -EINVAL;
3691		}
3692		switch (std->index) {
3693		case 0:
3694			std->id = V4L2_STD_PAL;
3695			strncpy(std->name, "PAL", sizeof(std->name)-1);
3696			std->frameperiod.numerator = 1;
3697			std->frameperiod.denominator = 25;
3698			std->framelines = zr->card.tvn[0]->Ht;
3699			break;
3700		case 1:
3701			std->id = V4L2_STD_NTSC;
3702			strncpy(std->name, "NTSC", sizeof(std->name)-1);
3703			std->frameperiod.numerator = 1001;
3704			std->frameperiod.denominator = 30000;
3705			std->framelines = zr->card.tvn[1]->Ht;
3706			break;
3707		case 2:
3708			std->id = V4L2_STD_SECAM;
3709			strncpy(std->name, "SECAM", sizeof(std->name)-1);
3710			std->frameperiod.numerator = 1;
3711			std->frameperiod.denominator = 25;
3712			std->framelines = zr->card.tvn[2]->Ht;
3713			break;
3714		}
3715
3716		return 0;
3717	}
3718		break;
3719
3720	case VIDIOC_G_STD:
3721	{
3722		v4l2_std_id *std = arg;
3723		int norm;
3724
3725		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_STD\n", ZR_DEVNAME(zr));
3726
3727		mutex_lock(&zr->resource_lock);
3728		norm = zr->norm;
3729		mutex_unlock(&zr->resource_lock);
3730
3731		switch (norm) {
3732		case VIDEO_MODE_PAL:
3733			*std = V4L2_STD_PAL;
3734			break;
3735		case VIDEO_MODE_NTSC:
3736			*std = V4L2_STD_NTSC;
3737			break;
3738		case VIDEO_MODE_SECAM:
3739			*std = V4L2_STD_SECAM;
3740			break;
3741		}
3742
3743		return 0;
3744	}
3745		break;
3746
3747	case VIDIOC_S_STD:
3748	{
3749		int norm = -1, res = 0;
3750		v4l2_std_id *std = arg;
3751
3752		dprintk(3, KERN_DEBUG "%s: VIDIOC_S_STD - norm=0x%llx\n",
3753			ZR_DEVNAME(zr), (unsigned long long)*std);
3754
3755		if (*std == V4L2_STD_PAL)
3756			norm = VIDEO_MODE_PAL;
3757		else if (*std == V4L2_STD_NTSC)
3758			norm = VIDEO_MODE_NTSC;
3759		else if (*std == V4L2_STD_SECAM)
3760			norm = VIDEO_MODE_SECAM;
3761		else if (*std == V4L2_STD_ALL)
3762			norm = VIDEO_MODE_AUTO;
3763		else {
3764			dprintk(1,
3765				KERN_ERR
3766				"%s: VIDIOC_S_STD - invalid norm 0x%llx\n",
3767				ZR_DEVNAME(zr), (unsigned long long)*std);
3768			return -EINVAL;
3769		}
3770
3771		mutex_lock(&zr->resource_lock);
3772		if ((res = zoran_set_norm(zr, norm)))
3773			goto sstd_unlock_and_return;
3774
3775		res = wait_grab_pending(zr);
3776	sstd_unlock_and_return:
3777		mutex_unlock(&zr->resource_lock);
3778		return res;
3779	}
3780		break;
3781
3782	case VIDIOC_ENUMINPUT:
3783	{
3784		struct v4l2_input *inp = arg;
3785		int status;
3786
3787		dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMINPUT - index=%d\n",
3788			ZR_DEVNAME(zr), inp->index);
3789
3790		if (inp->index < 0 || inp->index >= zr->card.inputs)
3791			return -EINVAL;
3792		else {
3793			int id = inp->index;
3794			memset(inp, 0, sizeof(*inp));
3795			inp->index = id;
3796		}
3797
3798		strncpy(inp->name, zr->card.input[inp->index].name,
3799			sizeof(inp->name) - 1);
3800		inp->type = V4L2_INPUT_TYPE_CAMERA;
3801		inp->std = V4L2_STD_ALL;
3802
3803		/* Get status of video decoder */
3804		mutex_lock(&zr->resource_lock);
3805		decoder_command(zr, DECODER_GET_STATUS, &status);
3806		mutex_unlock(&zr->resource_lock);
3807
3808		if (!(status & DECODER_STATUS_GOOD)) {
3809			inp->status |= V4L2_IN_ST_NO_POWER;
3810			inp->status |= V4L2_IN_ST_NO_SIGNAL;
3811		}
3812		if (!(status & DECODER_STATUS_COLOR))
3813			inp->status |= V4L2_IN_ST_NO_COLOR;
3814
3815		return 0;
3816	}
3817		break;
3818
3819	case VIDIOC_G_INPUT:
3820	{
3821		int *input = arg;
3822
3823		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_INPUT\n", ZR_DEVNAME(zr));
3824
3825		mutex_lock(&zr->resource_lock);
3826		*input = zr->input;
3827		mutex_unlock(&zr->resource_lock);
3828
3829		return 0;
3830	}
3831		break;
3832
3833	case VIDIOC_S_INPUT:
3834	{
3835		int *input = arg, res = 0;
3836
3837		dprintk(3, KERN_DEBUG "%s: VIDIOC_S_INPUT - input=%d\n",
3838			ZR_DEVNAME(zr), *input);
3839
3840		mutex_lock(&zr->resource_lock);
3841		if ((res = zoran_set_input(zr, *input)))
3842			goto sinput_unlock_and_return;
3843
3844		/* Make sure the changes come into effect */
3845		res = wait_grab_pending(zr);
3846	sinput_unlock_and_return:
3847		mutex_unlock(&zr->resource_lock);
3848		return res;
3849	}
3850		break;
3851
3852	case VIDIOC_ENUMOUTPUT:
3853	{
3854		struct v4l2_output *outp = arg;
3855
3856		dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMOUTPUT - index=%d\n",
3857			ZR_DEVNAME(zr), outp->index);
3858
3859		if (outp->index != 0)
3860			return -EINVAL;
3861
3862		memset(outp, 0, sizeof(*outp));
3863		outp->index = 0;
3864		outp->type = V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY;
3865		strncpy(outp->name, "Autodetect", sizeof(outp->name)-1);
3866
3867		return 0;
3868	}
3869		break;
3870
3871	case VIDIOC_G_OUTPUT:
3872	{
3873		int *output = arg;
3874
3875		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_OUTPUT\n", ZR_DEVNAME(zr));
3876
3877		*output = 0;
3878
3879		return 0;
3880	}
3881		break;
3882
3883	case VIDIOC_S_OUTPUT:
3884	{
3885		int *output = arg;
3886
3887		dprintk(3, KERN_DEBUG "%s: VIDIOC_S_OUTPUT - output=%d\n",
3888			ZR_DEVNAME(zr), *output);
3889
3890		if (*output != 0)
3891			return -EINVAL;
3892
3893		return 0;
3894	}
3895		break;
3896
3897		/* cropping (sub-frame capture) */
3898	case VIDIOC_CROPCAP:
3899	{
3900		struct v4l2_cropcap *cropcap = arg;
3901		int type = cropcap->type, res = 0;
3902
3903		dprintk(3, KERN_ERR "%s: VIDIOC_CROPCAP - type=%d\n",
3904			ZR_DEVNAME(zr), cropcap->type);
3905
3906		memset(cropcap, 0, sizeof(*cropcap));
3907		cropcap->type = type;
3908
3909		mutex_lock(&zr->resource_lock);
3910
3911		if (cropcap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3912		    (cropcap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3913		     fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3914			dprintk(1,
3915				KERN_ERR
3916				"%s: VIDIOC_CROPCAP - subcapture only supported for compressed capture\n",
3917				ZR_DEVNAME(zr));
3918			res = -EINVAL;
3919			goto cropcap_unlock_and_return;
3920		}
3921
3922		cropcap->bounds.top = cropcap->bounds.left = 0;
3923		cropcap->bounds.width = BUZ_MAX_WIDTH;
3924		cropcap->bounds.height = BUZ_MAX_HEIGHT;
3925		cropcap->defrect.top = cropcap->defrect.left = 0;
3926		cropcap->defrect.width = BUZ_MIN_WIDTH;
3927		cropcap->defrect.height = BUZ_MIN_HEIGHT;
3928	cropcap_unlock_and_return:
3929		mutex_unlock(&zr->resource_lock);
3930		return res;
3931	}
3932		break;
3933
3934	case VIDIOC_G_CROP:
3935	{
3936		struct v4l2_crop *crop = arg;
3937		int type = crop->type, res = 0;
3938
3939		dprintk(3, KERN_ERR "%s: VIDIOC_G_CROP - type=%d\n",
3940			ZR_DEVNAME(zr), crop->type);
3941
3942		memset(crop, 0, sizeof(*crop));
3943		crop->type = type;
3944
3945		mutex_lock(&zr->resource_lock);
3946
3947		if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3948		    (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3949		     fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3950			dprintk(1,
3951				KERN_ERR
3952				"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
3953				ZR_DEVNAME(zr));
3954			res = -EINVAL;
3955			goto gcrop_unlock_and_return;
3956		}
3957
3958		crop->c.top = fh->jpg_settings.img_y;
3959		crop->c.left = fh->jpg_settings.img_x;
3960		crop->c.width = fh->jpg_settings.img_width;
3961		crop->c.height = fh->jpg_settings.img_height;
3962
3963	gcrop_unlock_and_return:
3964		mutex_unlock(&zr->resource_lock);
3965
3966		return res;
3967	}
3968		break;
3969
3970	case VIDIOC_S_CROP:
3971	{
3972		struct v4l2_crop *crop = arg;
3973		int res = 0;
3974
3975		settings = fh->jpg_settings;
3976
3977		dprintk(3,
3978			KERN_ERR
3979			"%s: VIDIOC_S_CROP - type=%d, x=%d,y=%d,w=%d,h=%d\n",
3980			ZR_DEVNAME(zr), crop->type, crop->c.left, crop->c.top,
3981			crop->c.width, crop->c.height);
3982
3983		mutex_lock(&zr->resource_lock);
3984
3985		if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
3986			dprintk(1,
3987				KERN_ERR
3988				"%s: VIDIOC_S_CROP - cannot change settings while active\n",
3989				ZR_DEVNAME(zr));
3990			res = -EBUSY;
3991			goto scrop_unlock_and_return;
3992		}
3993
3994		if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3995		    (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3996		     fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3997			dprintk(1,
3998				KERN_ERR
3999				"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
4000				ZR_DEVNAME(zr));
4001			res = -EINVAL;
4002			goto scrop_unlock_and_return;
4003		}
4004
4005		/* move into a form that we understand */
4006		settings.img_x = crop->c.left;
4007		settings.img_y = crop->c.top;
4008		settings.img_width = crop->c.width;
4009		settings.img_height = crop->c.height;
4010
4011		/* check validity */
4012		if ((res = zoran_check_jpg_settings(zr, &settings)))
4013			goto scrop_unlock_and_return;
4014
4015		/* accept */
4016		fh->jpg_settings = settings;
4017
4018	scrop_unlock_and_return:
4019		mutex_unlock(&zr->resource_lock);
4020		return res;
4021	}
4022		break;
4023
4024	case VIDIOC_G_JPEGCOMP:
4025	{
4026		struct v4l2_jpegcompression *params = arg;
4027
4028		dprintk(3, KERN_DEBUG "%s: VIDIOC_G_JPEGCOMP\n",
4029			ZR_DEVNAME(zr));
4030
4031		memset(params, 0, sizeof(*params));
4032
4033		mutex_lock(&zr->resource_lock);
4034
4035		params->quality = fh->jpg_settings.jpg_comp.quality;
4036		params->APPn = fh->jpg_settings.jpg_comp.APPn;
4037		memcpy(params->APP_data,
4038		       fh->jpg_settings.jpg_comp.APP_data,
4039		       fh->jpg_settings.jpg_comp.APP_len);
4040		params->APP_len = fh->jpg_settings.jpg_comp.APP_len;
4041		memcpy(params->COM_data,
4042		       fh->jpg_settings.jpg_comp.COM_data,
4043		       fh->jpg_settings.jpg_comp.COM_len);
4044		params->COM_len = fh->jpg_settings.jpg_comp.COM_len;
4045		params->jpeg_markers =
4046		    fh->jpg_settings.jpg_comp.jpeg_markers;
4047
4048		mutex_unlock(&zr->resource_lock);
4049
4050		return 0;
4051	}
4052		break;
4053
4054	case VIDIOC_S_JPEGCOMP:
4055	{
4056		struct v4l2_jpegcompression *params = arg;
4057		int res = 0;
4058
4059		settings = fh->jpg_settings;
4060
4061		dprintk(3,
4062			KERN_DEBUG
4063			"%s: VIDIOC_S_JPEGCOMP - quality=%d, APPN=%d, APP_len=%d, COM_len=%d\n",
4064			ZR_DEVNAME(zr), params->quality, params->APPn,
4065			params->APP_len, params->COM_len);
4066
4067		settings.jpg_comp = *params;
4068
4069		mutex_lock(&zr->resource_lock);
4070
4071		if (fh->v4l_buffers.active != ZORAN_FREE ||
4072		    fh->jpg_buffers.active != ZORAN_FREE) {
4073			dprintk(1,
4074				KERN_WARNING
4075				"%s: VIDIOC_S_JPEGCOMP called while in playback/capture mode\n",
4076				ZR_DEVNAME(zr));
4077			res = -EBUSY;
4078			goto sjpegc_unlock_and_return;
4079		}
4080
4081		if ((res = zoran_check_jpg_settings(zr, &settings)))
4082			goto sjpegc_unlock_and_return;
4083		if (!fh->jpg_buffers.allocated)
4084			fh->jpg_buffers.buffer_size =
4085			    zoran_v4l2_calc_bufsize(&fh->jpg_settings);
4086		fh->jpg_settings.jpg_comp = *params = settings.jpg_comp;
4087	sjpegc_unlock_and_return:
4088		mutex_unlock(&zr->resource_lock);
4089
4090		return 0;
4091	}
4092		break;
4093
4094	case VIDIOC_QUERYSTD:	/* why is this useful? */
4095	{
4096		v4l2_std_id *std = arg;
4097
4098		dprintk(3,
4099			KERN_DEBUG "%s: VIDIOC_QUERY_STD - std=0x%llx\n",
4100			ZR_DEVNAME(zr), (unsigned long long)*std);
4101
4102		if (*std == V4L2_STD_ALL || *std == V4L2_STD_NTSC ||
4103		    *std == V4L2_STD_PAL || (*std == V4L2_STD_SECAM &&
4104					     zr->card.norms == 3)) {
4105			return 0;
4106		}
4107
4108		return -EINVAL;
4109	}
4110		break;
4111
4112	case VIDIOC_TRY_FMT:
4113	{
4114		struct v4l2_format *fmt = arg;
4115		int res = 0;
4116
4117		dprintk(3, KERN_DEBUG "%s: VIDIOC_TRY_FMT - type=%d\n",
4118			ZR_DEVNAME(zr), fmt->type);
4119
4120		switch (fmt->type) {
4121		case V4L2_BUF_TYPE_VIDEO_OVERLAY:
4122			mutex_lock(&zr->resource_lock);
4123
4124			if (fmt->fmt.win.w.width > BUZ_MAX_WIDTH)
4125				fmt->fmt.win.w.width = BUZ_MAX_WIDTH;
4126			if (fmt->fmt.win.w.width < BUZ_MIN_WIDTH)
4127				fmt->fmt.win.w.width = BUZ_MIN_WIDTH;
4128			if (fmt->fmt.win.w.height > BUZ_MAX_HEIGHT)
4129				fmt->fmt.win.w.height = BUZ_MAX_HEIGHT;
4130			if (fmt->fmt.win.w.height < BUZ_MIN_HEIGHT)
4131				fmt->fmt.win.w.height = BUZ_MIN_HEIGHT;
4132
4133			mutex_unlock(&zr->resource_lock);
4134			break;
4135
4136		case V4L2_BUF_TYPE_VIDEO_CAPTURE:
4137		case V4L2_BUF_TYPE_VIDEO_OUTPUT:
4138			if (fmt->fmt.pix.bytesperline > 0)
4139				return -EINVAL;
4140
4141			mutex_lock(&zr->resource_lock);
4142
4143			if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {
4144				settings = fh->jpg_settings;
4145
4146				/* we actually need to set 'real' parameters now */
4147				if ((fmt->fmt.pix.height * 2) >
4148				    BUZ_MAX_HEIGHT)
4149					settings.TmpDcm = 1;
4150				else
4151					settings.TmpDcm = 2;
4152				settings.decimation = 0;
4153				if (fmt->fmt.pix.height <=
4154				    fh->jpg_settings.img_height / 2)
4155					settings.VerDcm = 2;
4156				else
4157					settings.VerDcm = 1;
4158				if (fmt->fmt.pix.width <=
4159				    fh->jpg_settings.img_width / 4)
4160					settings.HorDcm = 4;
4161				else if (fmt->fmt.pix.width <=
4162					 fh->jpg_settings.img_width / 2)
4163					settings.HorDcm = 2;
4164				else
4165					settings.HorDcm = 1;
4166				if (settings.TmpDcm == 1)
4167					settings.field_per_buff = 2;
4168				else
4169					settings.field_per_buff = 1;
4170
4171				/* check */
4172				if ((res =
4173				     zoran_check_jpg_settings(zr,
4174							      &settings)))
4175					goto tryfmt_unlock_and_return;
4176
4177				/* tell the user what we actually did */
4178				fmt->fmt.pix.width =
4179				    settings.img_width / settings.HorDcm;
4180				fmt->fmt.pix.height =
4181				    settings.img_height * 2 /
4182				    (settings.TmpDcm * settings.VerDcm);
4183				if (settings.TmpDcm == 1)
4184					fmt->fmt.pix.field =
4185					    (fh->jpg_settings.
4186					     odd_even ? V4L2_FIELD_SEQ_TB :
4187					     V4L2_FIELD_SEQ_BT);
4188				else
4189					fmt->fmt.pix.field =
4190					    (fh->jpg_settings.
4191					     odd_even ? V4L2_FIELD_TOP :
4192					     V4L2_FIELD_BOTTOM);
4193
4194				fmt->fmt.pix.sizeimage =
4195				    zoran_v4l2_calc_bufsize(&settings);
4196			} else if (fmt->type ==
4197				   V4L2_BUF_TYPE_VIDEO_CAPTURE) {
4198				int i;
4199
4200				for (i = 0; i < zoran_num_formats; i++)
4201					if (zoran_formats[i].fourcc ==
4202					    fmt->fmt.pix.pixelformat)
4203						break;
4204				if (i == zoran_num_formats) {
4205					res = -EINVAL;
4206					goto tryfmt_unlock_and_return;
4207				}
4208
4209				if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
4210					fmt->fmt.pix.width = BUZ_MAX_WIDTH;
4211				if (fmt->fmt.pix.width < BUZ_MIN_WIDTH)
4212					fmt->fmt.pix.width = BUZ_MIN_WIDTH;
4213				if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
4214					fmt->fmt.pix.height =
4215					    BUZ_MAX_HEIGHT;
4216				if (fmt->fmt.pix.height < BUZ_MIN_HEIGHT)
4217					fmt->fmt.pix.height =
4218					    BUZ_MIN_HEIGHT;
4219			} else {
4220				res = -EINVAL;
4221				goto tryfmt_unlock_and_return;
4222			}
4223		tryfmt_unlock_and_return:
4224			mutex_unlock(&zr->resource_lock);
4225
4226			return res;
4227			break;
4228
4229		default:
4230			return -EINVAL;
4231		}
4232
4233		return 0;
4234	}
4235		break;
4236#endif
4237
4238	default:
4239		dprintk(1, KERN_DEBUG "%s: UNKNOWN ioctl cmd: 0x%x\n",
4240			ZR_DEVNAME(zr), cmd);
4241		return -ENOIOCTLCMD;
4242		break;
4243
4244	}
4245	return 0;
4246}
4247
4248
4249static int
4250zoran_ioctl (struct inode *inode,
4251	     struct file  *file,
4252	     unsigned int  cmd,
4253	     unsigned long arg)
4254{
4255	return video_usercopy(inode, file, cmd, arg, zoran_do_ioctl);
4256}
4257
4258static unsigned int
4259zoran_poll (struct file *file,
4260	    poll_table  *wait)
4261{
4262	struct zoran_fh *fh = file->private_data;
4263	struct zoran *zr = fh->zr;
4264	wait_queue_head_t *queue = NULL;
4265	int res = 0, frame;
4266
4267	/* we should check whether buffers are ready to be synced on
4268	 * (w/o waits - O_NONBLOCK) here
4269	 * if ready for read (sync), return POLLIN|POLLRDNORM,
4270	 * if ready for write (sync), return POLLOUT|POLLWRNORM,
4271	 * if error, return POLLERR,
4272	 * if no buffers queued or so, return POLLNVAL
4273	 */
4274
4275	mutex_lock(&zr->resource_lock);
4276
4277	switch (fh->map_mode) {
4278	case ZORAN_MAP_MODE_RAW:
4279		if (fh->v4l_buffers.active == ZORAN_FREE ||
4280		    zr->v4l_pend_head == zr->v4l_pend_tail) {
4281			dprintk(1,
4282				"%s: zoran_poll() - no buffers queued\n",
4283				ZR_DEVNAME(zr));
4284			res = POLLNVAL;
4285			goto poll_unlock_and_return;
4286		}
4287		queue = &zr->v4l_capq;
4288		frame = zr->v4l_pend[zr->v4l_pend_tail & V4L_MASK_FRAME];
4289		poll_wait(file, queue, wait);
4290		if (fh->v4l_buffers.buffer[frame].state == BUZ_STATE_DONE)
4291			res = POLLIN | POLLRDNORM;
4292		break;
4293
4294	case ZORAN_MAP_MODE_JPG_REC:
4295	case ZORAN_MAP_MODE_JPG_PLAY:
4296		if (fh->jpg_buffers.active == ZORAN_FREE ||
4297		    zr->jpg_que_head == zr->jpg_que_tail) {
4298			dprintk(1,
4299				"%s: zoran_poll() - no buffers queued\n",
4300				ZR_DEVNAME(zr));
4301			res = POLLNVAL;
4302			goto poll_unlock_and_return;
4303		}
4304		queue = &zr->jpg_capq;
4305		frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
4306		poll_wait(file, queue, wait);
4307		if (fh->jpg_buffers.buffer[frame].state == BUZ_STATE_DONE) {
4308			if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC)
4309				res = POLLIN | POLLRDNORM;
4310			else
4311				res = POLLOUT | POLLWRNORM;
4312		}
4313		break;
4314
4315	default:
4316		dprintk(1,
4317			"%s: zoran_poll() - internal error, unknown map_mode=%d\n",
4318			ZR_DEVNAME(zr), fh->map_mode);
4319		res = POLLNVAL;
4320		goto poll_unlock_and_return;
4321	}
4322
4323poll_unlock_and_return:
4324	mutex_unlock(&zr->resource_lock);
4325
4326	return res;
4327}
4328
4329
4330/*
4331 * This maps the buffers to user space.
4332 *
4333 * Depending on the state of fh->map_mode
4334 * the V4L or the MJPEG buffers are mapped
4335 * per buffer or all together
4336 *
4337 * Note that we need to connect to some
4338 * unmap signal event to unmap the de-allocate
4339 * the buffer accordingly (zoran_vm_close())
4340 */
4341
4342static void
4343zoran_vm_open (struct vm_area_struct *vma)
4344{
4345	struct zoran_mapping *map = vma->vm_private_data;
4346
4347	map->count++;
4348}
4349
4350static void
4351zoran_vm_close (struct vm_area_struct *vma)
4352{
4353	struct zoran_mapping *map = vma->vm_private_data;
4354	struct file *file = map->file;
4355	struct zoran_fh *fh = file->private_data;
4356	struct zoran *zr = fh->zr;
4357	int i;
4358
4359	map->count--;
4360	if (map->count == 0) {
4361		switch (fh->map_mode) {
4362		case ZORAN_MAP_MODE_JPG_REC:
4363		case ZORAN_MAP_MODE_JPG_PLAY:
4364
4365			dprintk(3, KERN_INFO "%s: munmap(MJPEG)\n",
4366				ZR_DEVNAME(zr));
4367
4368			for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
4369				if (fh->jpg_buffers.buffer[i].map == map) {
4370					fh->jpg_buffers.buffer[i].map =
4371					    NULL;
4372				}
4373			}
4374			kfree(map);
4375
4376			for (i = 0; i < fh->jpg_buffers.num_buffers; i++)
4377				if (fh->jpg_buffers.buffer[i].map)
4378					break;
4379			if (i == fh->jpg_buffers.num_buffers) {
4380				mutex_lock(&zr->resource_lock);
4381
4382				if (fh->jpg_buffers.active != ZORAN_FREE) {
4383					jpg_qbuf(file, -1, zr->codec_mode);
4384					zr->jpg_buffers.allocated = 0;
4385					zr->jpg_buffers.active =
4386					    fh->jpg_buffers.active =
4387					    ZORAN_FREE;
4388				}
4389				//jpg_fbuffer_free(file);
4390				fh->jpg_buffers.allocated = 0;
4391				fh->jpg_buffers.ready_to_be_freed = 1;
4392
4393				mutex_unlock(&zr->resource_lock);
4394			}
4395
4396			break;
4397
4398		case ZORAN_MAP_MODE_RAW:
4399
4400			dprintk(3, KERN_INFO "%s: munmap(V4L)\n",
4401				ZR_DEVNAME(zr));
4402
4403			for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
4404				if (fh->v4l_buffers.buffer[i].map == map) {
4405					/* unqueue/unmap */
4406					fh->v4l_buffers.buffer[i].map =
4407					    NULL;
4408				}
4409			}
4410			kfree(map);
4411
4412			for (i = 0; i < fh->v4l_buffers.num_buffers; i++)
4413				if (fh->v4l_buffers.buffer[i].map)
4414					break;
4415			if (i == fh->v4l_buffers.num_buffers) {
4416				mutex_lock(&zr->resource_lock);
4417
4418				if (fh->v4l_buffers.active != ZORAN_FREE) {
4419					zr36057_set_memgrab(zr, 0);
4420					zr->v4l_buffers.allocated = 0;
4421					zr->v4l_buffers.active =
4422					    fh->v4l_buffers.active =
4423					    ZORAN_FREE;
4424				}
4425				//v4l_fbuffer_free(file);
4426				fh->v4l_buffers.allocated = 0;
4427				fh->v4l_buffers.ready_to_be_freed = 1;
4428
4429				mutex_unlock(&zr->resource_lock);
4430			}
4431
4432			break;
4433
4434		default:
4435			printk(KERN_ERR
4436			       "%s: munmap() - internal error - unknown map mode %d\n",
4437			       ZR_DEVNAME(zr), fh->map_mode);
4438			break;
4439
4440		}
4441	}
4442}
4443
4444static struct vm_operations_struct zoran_vm_ops = {
4445	.open = zoran_vm_open,
4446	.close = zoran_vm_close,
4447};
4448
4449static int
4450zoran_mmap (struct file           *file,
4451	    struct vm_area_struct *vma)
4452{
4453	struct zoran_fh *fh = file->private_data;
4454	struct zoran *zr = fh->zr;
4455	unsigned long size = (vma->vm_end - vma->vm_start);
4456	unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
4457	int i, j;
4458	unsigned long page, start = vma->vm_start, todo, pos, fraglen;
4459	int first, last;
4460	struct zoran_mapping *map;
4461	int res = 0;
4462
4463	dprintk(3,
4464		KERN_INFO "%s: mmap(%s) of 0x%08lx-0x%08lx (size=%lu)\n",
4465		ZR_DEVNAME(zr),
4466		fh->map_mode == ZORAN_MAP_MODE_RAW ? "V4L" : "MJPEG",
4467		vma->vm_start, vma->vm_end, size);
4468
4469	if (!(vma->vm_flags & VM_SHARED) || !(vma->vm_flags & VM_READ) ||
4470	    !(vma->vm_flags & VM_WRITE)) {
4471		dprintk(1,
4472			KERN_ERR
4473			"%s: mmap() - no MAP_SHARED/PROT_{READ,WRITE} given\n",
4474			ZR_DEVNAME(zr));
4475		return -EINVAL;
4476	}
4477
4478	switch (fh->map_mode) {
4479
4480	case ZORAN_MAP_MODE_JPG_REC:
4481	case ZORAN_MAP_MODE_JPG_PLAY:
4482
4483		/* lock */
4484		mutex_lock(&zr->resource_lock);
4485
4486		/* Map the MJPEG buffers */
4487		if (!fh->jpg_buffers.allocated) {
4488			dprintk(1,
4489				KERN_ERR
4490				"%s: zoran_mmap(MJPEG) - buffers not yet allocated\n",
4491				ZR_DEVNAME(zr));
4492			res = -ENOMEM;
4493			goto jpg_mmap_unlock_and_return;
4494		}
4495
4496		first = offset / fh->jpg_buffers.buffer_size;
4497		last = first - 1 + size / fh->jpg_buffers.buffer_size;
4498		if (offset % fh->jpg_buffers.buffer_size != 0 ||
4499		    size % fh->jpg_buffers.buffer_size != 0 || first < 0 ||
4500		    last < 0 || first >= fh->jpg_buffers.num_buffers ||
4501		    last >= fh->jpg_buffers.num_buffers) {
4502			dprintk(1,
4503				KERN_ERR
4504				"%s: mmap(MJPEG) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
4505				ZR_DEVNAME(zr), offset, size,
4506				fh->jpg_buffers.buffer_size,
4507				fh->jpg_buffers.num_buffers);
4508			res = -EINVAL;
4509			goto jpg_mmap_unlock_and_return;
4510		}
4511		for (i = first; i <= last; i++) {
4512			if (fh->jpg_buffers.buffer[i].map) {
4513				dprintk(1,
4514					KERN_ERR
4515					"%s: mmap(MJPEG) - buffer %d already mapped\n",
4516					ZR_DEVNAME(zr), i);
4517				res = -EBUSY;
4518				goto jpg_mmap_unlock_and_return;
4519			}
4520		}
4521
4522		/* map these buffers (v4l_buffers[i]) */
4523		map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
4524		if (!map) {
4525			res = -ENOMEM;
4526			goto jpg_mmap_unlock_and_return;
4527		}
4528		map->file = file;
4529		map->count = 1;
4530
4531		vma->vm_ops = &zoran_vm_ops;
4532		vma->vm_flags |= VM_DONTEXPAND;
4533		vma->vm_private_data = map;
4534
4535		for (i = first; i <= last; i++) {
4536			for (j = 0;
4537			     j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
4538			     j++) {
4539				fraglen =
4540				    (le32_to_cpu(fh->jpg_buffers.buffer[i].
4541				     frag_tab[2 * j + 1]) & ~1) << 1;
4542				todo = size;
4543				if (todo > fraglen)
4544					todo = fraglen;
4545				pos =
4546				    le32_to_cpu((unsigned long) fh->jpg_buffers.
4547				    buffer[i].frag_tab[2 * j]);
4548				/* should just be pos on i386 */
4549				page = virt_to_phys(bus_to_virt(pos))
4550								>> PAGE_SHIFT;
4551				if (remap_pfn_range(vma, start, page,
4552							todo, PAGE_SHARED)) {
4553					dprintk(1,
4554						KERN_ERR
4555						"%s: zoran_mmap(V4L) - remap_pfn_range failed\n",
4556						ZR_DEVNAME(zr));
4557					res = -EAGAIN;
4558					goto jpg_mmap_unlock_and_return;
4559				}
4560				size -= todo;
4561				start += todo;
4562				if (size == 0)
4563					break;
4564				if (le32_to_cpu(fh->jpg_buffers.buffer[i].
4565				    frag_tab[2 * j + 1]) & 1)
4566					break;	/* was last fragment */
4567			}
4568			fh->jpg_buffers.buffer[i].map = map;
4569			if (size == 0)
4570				break;
4571
4572		}
4573	jpg_mmap_unlock_and_return:
4574		mutex_unlock(&zr->resource_lock);
4575
4576		break;
4577
4578	case ZORAN_MAP_MODE_RAW:
4579
4580		mutex_lock(&zr->resource_lock);
4581
4582		/* Map the V4L buffers */
4583		if (!fh->v4l_buffers.allocated) {
4584			dprintk(1,
4585				KERN_ERR
4586				"%s: zoran_mmap(V4L) - buffers not yet allocated\n",
4587				ZR_DEVNAME(zr));
4588			res = -ENOMEM;
4589			goto v4l_mmap_unlock_and_return;
4590		}
4591
4592		first = offset / fh->v4l_buffers.buffer_size;
4593		last = first - 1 + size / fh->v4l_buffers.buffer_size;
4594		if (offset % fh->v4l_buffers.buffer_size != 0 ||
4595		    size % fh->v4l_buffers.buffer_size != 0 || first < 0 ||
4596		    last < 0 || first >= fh->v4l_buffers.num_buffers ||
4597		    last >= fh->v4l_buffers.buffer_size) {
4598			dprintk(1,
4599				KERN_ERR
4600				"%s: mmap(V4L) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
4601				ZR_DEVNAME(zr), offset, size,
4602				fh->v4l_buffers.buffer_size,
4603				fh->v4l_buffers.num_buffers);
4604			res = -EINVAL;
4605			goto v4l_mmap_unlock_and_return;
4606		}
4607		for (i = first; i <= last; i++) {
4608			if (fh->v4l_buffers.buffer[i].map) {
4609				dprintk(1,
4610					KERN_ERR
4611					"%s: mmap(V4L) - buffer %d already mapped\n",
4612					ZR_DEVNAME(zr), i);
4613				res = -EBUSY;
4614				goto v4l_mmap_unlock_and_return;
4615			}
4616		}
4617
4618		/* map these buffers (v4l_buffers[i]) */
4619		map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
4620		if (!map) {
4621			res = -ENOMEM;
4622			goto v4l_mmap_unlock_and_return;
4623		}
4624		map->file = file;
4625		map->count = 1;
4626
4627		vma->vm_ops = &zoran_vm_ops;
4628		vma->vm_flags |= VM_DONTEXPAND;
4629		vma->vm_private_data = map;
4630
4631		for (i = first; i <= last; i++) {
4632			todo = size;
4633			if (todo > fh->v4l_buffers.buffer_size)
4634				todo = fh->v4l_buffers.buffer_size;
4635			page = fh->v4l_buffers.buffer[i].fbuffer_phys;
4636			if (remap_pfn_range(vma, start, page >> PAGE_SHIFT,
4637							todo, PAGE_SHARED)) {
4638				dprintk(1,
4639					KERN_ERR
4640					"%s: zoran_mmap(V4L)i - remap_pfn_range failed\n",
4641					ZR_DEVNAME(zr));
4642				res = -EAGAIN;
4643				goto v4l_mmap_unlock_and_return;
4644			}
4645			size -= todo;
4646			start += todo;
4647			fh->v4l_buffers.buffer[i].map = map;
4648			if (size == 0)
4649				break;
4650		}
4651	v4l_mmap_unlock_and_return:
4652		mutex_unlock(&zr->resource_lock);
4653
4654		break;
4655
4656	default:
4657		dprintk(1,
4658			KERN_ERR
4659			"%s: zoran_mmap() - internal error - unknown map mode %d\n",
4660			ZR_DEVNAME(zr), fh->map_mode);
4661		break;
4662	}
4663
4664	return 0;
4665}
4666
4667static const struct file_operations zoran_fops = {
4668	.owner = THIS_MODULE,
4669	.open = zoran_open,
4670	.release = zoran_close,
4671	.ioctl = zoran_ioctl,
4672	.compat_ioctl	= v4l_compat_ioctl32,
4673	.llseek = no_llseek,
4674	.read = zoran_read,
4675	.write = zoran_write,
4676	.mmap = zoran_mmap,
4677	.poll = zoran_poll,
4678};
4679
4680struct video_device zoran_template __devinitdata = {
4681	.name = ZORAN_NAME,
4682	.type = ZORAN_VID_TYPE,
4683#ifdef CONFIG_VIDEO_V4L2
4684	.type2 = ZORAN_V4L2_VID_FLAGS,
4685#endif
4686	.hardware = ZORAN_HARDWARE,
4687	.fops = &zoran_fops,
4688	.release = &zoran_vdev_release,
4689	.minor = -1
4690};
4691