1#define DEBUGLEVEL 0
2#define MAX_KMALLOC_MEM (128*1024)
3
4/*
5   Miro/Pinnacle Systems Inc. DC10/DC10plus and
6   Linux Media Labs LML33 video capture boards driver
7   now with IOMega BUZ support!
8
9   Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
10
11   Changes for BUZ by Wolfgang Scherr <scherr@net4you.net>
12
13   Based on
14
15    Miro DC10 driver
16    Copyright (C) 1999 Wolfgang Scherr <scherr@net4you.net>
17
18    Iomega Buz driver version 1.0
19    Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
20
21    buz.0.0.3
22    Copyright (C) 1998 Dave Perks <dperks@ibm.net>
23
24    bttv - Bt848 frame grabber driver
25    Copyright (C) 1996,97,98 Ralph  Metzler (rjkm@thp.uni-koeln.de)
26                           & Marcus Metzler (mocm@thp.uni-koeln.de)
27
28
29    This program is free software; you can redistribute it and/or modify
30    it under the terms of the GNU General Public License as published by
31    the Free Software Foundation; either version 2 of the License, or
32    (at your option) any later version.
33
34    This program is distributed in the hope that it will be useful,
35    but WITHOUT ANY WARRANTY; without even the implied warranty of
36    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37    GNU General Public License for more details.
38
39    You should have received a copy of the GNU General Public License
40    along with this program; if not, write to the Free Software
41    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42*/
43
44#include <linux/config.h>
45#include <linux/version.h>
46#include <linux/init.h>
47#include <linux/module.h>
48#include <linux/delay.h>
49#include <linux/errno.h>
50#include <linux/fs.h>
51#include <linux/kernel.h>
52#include <linux/major.h>
53#include <linux/slab.h>
54#include <linux/mm.h>
55#include <linux/pci.h>
56#include <linux/signal.h>
57#include <asm/io.h>
58#include <asm/pgtable.h>
59#include <asm/page.h>
60#include <linux/sched.h>
61#include <asm/segment.h>
62#include <linux/types.h>
63#include <linux/wrapper.h>
64
65#include <linux/spinlock.h>
66#include <linux/vmalloc.h>
67#include <linux/i2c-old.h>
68#define     MAP_NR(x)       virt_to_page(x)
69#define     ZORAN_HARDWARE  VID_HARDWARE_ZR36067
70
71#include <linux/videodev.h>
72
73#include <asm/uaccess.h>
74#include <linux/proc_fs.h>
75
76#include "zoran.h"
77#include <linux/video_decoder.h>
78#include <linux/video_encoder.h>
79
80// RJ: Test only - want to test BUZ_USE_HIMEM even when CONFIG_BIGPHYS_AREA is defined
81#if !defined(CONFIG_BIGPHYS_AREA)
82//#undef CONFIG_BIGPHYS_AREA
83#define BUZ_USE_HIMEM
84#endif
85
86#if defined(CONFIG_BIGPHYS_AREA)
87#   include <linux/bigphysarea.h>
88#endif
89
90#define IRQ_MASK ( ZR36057_ISR_GIRQ0 | ZR36057_ISR_GIRQ1 | /* ZR36057_ISR_CodRepIRQ | */  ZR36057_ISR_JPEGRepIRQ )	// SW
91//#define GPIO_MASK 0xcd
92//#define GPIO_MASK 0x8d
93
94/*
95DC10:
96GPIO0 = /RESET ZR 36060
97GPIO1 = VIDEO BUS DIRECTION (0: CAPTURE, 1: DISPLAY)
98GPIO2 = VIDEO BUS ENABLE    (0: ON, 1: OFF)
99GPIO3 = /SLEEP ZR 36060
100GPIO4 = ADC7175 (video out) FREQUENCY (0: LCC/SAA7110, 1: 27 MHz (quarz))
101GPIO5 = ZORAN FREQUENCY  (0: LCC and LCC2 from SAA7110,
102                          1: 27 and 13.5 MHz (quarz))
103GPIO6 = /FRAME ZR 36060
104GPIO7 = /RESET ADV7175 (video out)
105(I think they lost the SAA7110 reset.....)
106
107GIRQ0 signals that ZR36060's DATERR# line is asserted.
108GIRQ1 signals a vertical sync of the video signal (VS SAA7110)
109
110  SAA7110A:
111   mode 0 - Composite
112   mode 1 -
113   mode 2 -
114   mode 3 -
115   mode 4 -
116   mode 5 - internal Composite (from PCTV)
117   mode 6 -
118   mode 7 - S-Video
119
120BUZ:
121GPIO0 = 1, take board out of reset
122GPIO1 = 1, take JPEG codec out of sleep mode
123GPIO3 = 1, deassert FRAME# to 36060
124
125GIRQ0 signals a vertical sync of the video signal
126GIRQ1 signals that ZR36060's DATERR# line is asserted.
127
128SAA7111A
129
130   In their infinite wisdom, the Iomega engineers decided to
131   use the same input line for composite and S-Video Color,
132   although there are two entries not connected at all!
133   Through this ingenious strike, it is not possible to
134   keep two running video sources connected at the same time
135   to Composite and S-VHS input!
136
137   mode 0 - N/C
138   mode 1 - S-Video Y
139   mode 2 - noise or something I don't know
140   mode 3 - Composite and S-Video C
141   mode 4 - N/C
142   mode 5 - S-Video (gain C independently selectable of gain Y)
143   mode 6 - N/C
144   mode 7 - S-Video (gain C adapted to gain Y)
145*/
146
147#define MAJOR_VERSION 0		/* driver major version */
148#define MINOR_VERSION 7		/* driver minor version */
149
150#define ZORAN_NAME    "zr36067"	/* name of the device */
151
152#define BUZ_ERR       KERN_ERR     ZORAN_NAME
153#define BUZ_DEBUG     KERN_INFO    ZORAN_NAME
154#define BUZ_INFO      KERN_INFO    ZORAN_NAME
155#define BUZ_WARNING   KERN_WARNING ZORAN_NAME
156
157#if(DEBUGLEVEL>0)
158#define DEBUG1(x...)    x
159#else
160#define DEBUG1(x...)
161#endif
162
163#if(DEBUGLEVEL>1)
164#define DEBUG2(x...)    x
165#else
166#define DEBUG2(x...)
167#endif
168
169#if(DEBUGLEVEL>2)
170#define DEBUG3(x...)    x
171#else
172#define DEBUG3(x...)
173#endif
174
175#if(DEBUGLEVEL>3)
176#define DEBUG4(x...)    x
177#else
178#define DEBUG4(x...)
179#endif
180
181/* The parameters for this driver */
182
183/*
184   The video mem address of the video card.
185   The driver has a little database for some videocards
186   to determine it from there. If your video card is not in there
187   you have either to give it to the driver as a parameter
188   or set in in a VIDIOCSFBUF ioctl
189 */
190
191static unsigned long vidmem = 0;	/* Video memory base address */
192
193/* Special purposes only: */
194
195static int triton = 0;		/* 0=no, 1=yes */
196static int natoma = 0;		/* 0=no, 1=yes */
197
198/*
199   Number and size of grab buffers for Video 4 Linux
200   The vast majority of applications should not need more than 2,
201   the very popular BTTV driver actually does ONLY have 2.
202   Time sensitive applications might need more, the maximum
203   is VIDEO_MAX_FRAME (defined in <linux/videodev.h>).
204
205   The size is set so that the maximum possible request
206   can be satisfied. Decrease  it, if bigphys_area alloc'd
207   memory is low. If you don't have the bigphys_area patch,
208   set it to 128 KB. Will you allow only to grab small
209   images with V4L, but that's better than nothing.
210
211   v4l_bufsize has to be given in KB !
212
213*/
214
215static int v4l_nbufs = 2;
216static int v4l_bufsize = 128;	/* Everybody should be able to work with this setting */
217
218/*
219   Default input and video norm at startup of the driver.
220*/
221
222static int default_input = 0;	/* 0=Composite, 1=S-VHS */
223static int default_norm = 0;	/* 0=PAL, 1=NTSC 2=SECAM */
224static int lock_norm = 0;	/* 1=Don't change TV standard (norm) */
225
226static int pass_through = 0;	/* 1=Pass through TV signal when device is not used */
227				/* 0=Show color bar when device is not used (LML33: only if lml33dpath=1) */
228
229static int lml33dpath = 0;	/* 1 will use digital path in capture mode instead of analog.
230				   It can be used for picture adjustments using tool like xawtv
231				   while watching image on TV monitor connected to the output.
232				   However, due to absence of 75 Ohm load on Bt819 input, there
233				   will be some image imperfections */
234static int video_nr = -1;
235
236MODULE_PARM(vidmem, "i");
237MODULE_PARM(triton, "i");
238MODULE_PARM(natoma, "i");
239MODULE_PARM(v4l_nbufs, "i");
240MODULE_PARM(v4l_bufsize, "i");
241MODULE_PARM(default_input, "i");
242MODULE_PARM(default_norm, "i");
243MODULE_PARM(lock_norm, "i");
244MODULE_PARM(pass_through, "i");
245MODULE_PARM(lml33dpath, "i");
246MODULE_PARM(video_nr, "i");
247
248static struct pci_device_id zr36067_pci_tbl[] = {
249	{ PCI_VENDOR_ID_ZORAN, PCI_DEVICE_ID_ZORAN_36057,
250	  PCI_ANY_ID, PCI_ANY_ID,  0, 0, 0 },
251	{ 0 }
252};
253MODULE_DEVICE_TABLE(pci, zr36067_pci_tbl);
254
255/* Anybody who uses more than four? */
256#define BUZ_MAX 4
257
258static int zoran_num;		/* number of Buzs in use */
259static struct zoran zoran[BUZ_MAX];
260
261/* forward references */
262
263static void v4l_fbuffer_free(struct zoran *zr);
264static void jpg_fbuffer_free(struct zoran *zr);
265static void zoran_feed_stat_com(struct zoran *zr);
266
267/*
268 *   Allocate the V4L grab buffers
269 *
270 *   These have to be pysically contiguous.
271 *   If v4l_bufsize <= MAX_KMALLOC_MEM we use kmalloc
272 *   else we try to allocate them with bigphysarea_alloc_pages
273 *   if the bigphysarea patch is present in the kernel,
274 *   else we try to use high memory (if the user has bootet
275 *   Linux with the necessary memory left over).
276 */
277
278static int v4l_fbuffer_alloc(struct zoran *zr)
279{
280	int i, off;
281	unsigned char *mem;
282
283	for (i = 0; i < v4l_nbufs; i++) {
284		if (zr->v4l_gbuf[i].fbuffer)
285			printk(KERN_WARNING
286			       "%s: v4l_fbuffer_alloc: buffer %d allready allocated ???\n",
287			       zr->name, i);
288
289		//udelay(20);
290		if (v4l_bufsize <= MAX_KMALLOC_MEM) {
291			/* Use kmalloc */
292
293			mem =
294			    (unsigned char *) kmalloc(v4l_bufsize,
295						      GFP_KERNEL);
296			if (mem == 0) {
297				printk(KERN_ERR
298				       "%s: kmalloc for V4L bufs failed\n",
299				       zr->name);
300				v4l_fbuffer_free(zr);
301				return -ENOBUFS;
302			}
303			zr->v4l_gbuf[i].fbuffer = mem;
304			zr->v4l_gbuf[i].fbuffer_phys = virt_to_phys(mem);
305			zr->v4l_gbuf[i].fbuffer_bus = virt_to_bus(mem);
306			for (off = 0; off < v4l_bufsize; off += PAGE_SIZE)
307				mem_map_reserve(MAP_NR(mem + off));
308			DEBUG1(printk
309			       (KERN_INFO
310				"%s: V4L frame %d mem 0x%lx (bus: 0x%lx)\n",
311				zr->name, i, (unsigned long) mem,
312				virt_to_bus(mem)));
313		} else {
314#if defined(CONFIG_BIGPHYS_AREA)
315			/* Use bigphysarea_alloc_pages */
316
317			int n = (v4l_bufsize + PAGE_SIZE - 1) / PAGE_SIZE;
318			mem =
319			    (unsigned char *) bigphysarea_alloc_pages(n, 0,
320								      GFP_KERNEL);
321			if (mem == 0) {
322				printk(KERN_ERR
323				       "%s: bigphysarea_alloc_pages for V4L bufs failed\n",
324				       zr->name);
325				v4l_fbuffer_free(zr);
326				return -ENOBUFS;
327			}
328			zr->v4l_gbuf[i].fbuffer = mem;
329			zr->v4l_gbuf[i].fbuffer_phys = virt_to_phys(mem);
330			zr->v4l_gbuf[i].fbuffer_bus = virt_to_bus(mem);
331			DEBUG1(printk
332			       (KERN_INFO
333				"%s: Bigphysarea frame %d mem 0x%x (bus: 0x%x)\n",
334				zr->name, i, (unsigned) mem,
335				(unsigned) virt_to_bus(mem)));
336
337			/* Zero out the allocated memory */
338			memset(zr->v4l_gbuf[i].fbuffer, 0, v4l_bufsize);
339#else
340			/* No bigphysarea present, usage of high memory disabled,
341			   but user wants buffers of more than MAX_KMALLOC_MEM */
342			printk(KERN_ERR
343			       "%s: No bigphysarea_patch present, usage of high memory disabled,\n",
344			       zr->name);
345			printk(KERN_ERR
346			       "%s: sorry, could not allocate V4L buffers of size %d KB.\n",
347			       zr->name, v4l_bufsize >> 10);
348			return -ENOBUFS;
349#endif
350		}
351	}
352
353	return 0;
354}
355
356/* free the V4L grab buffers */
357
358static void v4l_fbuffer_free(struct zoran *zr)
359{
360	int i, off;
361	unsigned char *mem;
362
363	for (i = 0; i < v4l_nbufs; i++) {
364		if (!zr->v4l_gbuf[i].fbuffer)
365			continue;
366
367		if (v4l_bufsize <= MAX_KMALLOC_MEM) {
368			mem = zr->v4l_gbuf[i].fbuffer;
369			for (off = 0; off < v4l_bufsize; off += PAGE_SIZE)
370				mem_map_unreserve(MAP_NR(mem + off));
371			kfree((void *) zr->v4l_gbuf[i].fbuffer);
372		}
373#if defined(CONFIG_BIGPHYS_AREA)
374		else
375			bigphysarea_free_pages((void *) zr->v4l_gbuf[i].
376					       fbuffer);
377#endif
378		zr->v4l_gbuf[i].fbuffer = NULL;
379	}
380}
381
382/*
383 *   Allocate the MJPEG grab buffers.
384 *
385 *   If the requested buffer size is smaller than MAX_KMALLOC_MEM,
386 *   kmalloc is used to request a physically contiguous area,
387 *   else we allocate the memory in framgents with get_free_page.
388 *
389 *   If a Natoma chipset is present and this is a revision 1 zr36057,
390 *   each MJPEG buffer needs to be physically contiguous.
391 *   (RJ: This statement is from Dave Perks' original driver,
392 *   I could never check it because I have a zr36067)
393 *   The driver cares about this because it reduces the buffer
394 *   size to MAX_KMALLOC_MEM in that case (which forces contiguous allocation).
395 *
396 *   RJ: The contents grab buffers needs never be accessed in the driver.
397 *       Therefore there is no need to allocate them with vmalloc in order
398 *       to get a contiguous virtual memory space.
399 *       I don't understand why many other drivers first allocate them with
400 *       vmalloc (which uses internally also get_free_page, but delivers you
401 *       virtual addresses) and then again have to make a lot of efforts
402 *       to get the physical address.
403 *
404 */
405
406static int jpg_fbuffer_alloc(struct zoran *zr)
407{
408	int i, j, off;		//alloc_contig;
409	unsigned long mem;
410
411	/* Decide if we should alloc contiguous or fragmented memory */
412	/* This has to be identical in jpg_fbuffer_alloc and jpg_fbuffer_free */
413
414	//alloc_contig = (zr->jpg_bufsize <= MAX_KMALLOC_MEM);
415
416	for (i = 0; i < zr->jpg_nbufs; i++) {
417		if (zr->jpg_gbuf[i].frag_tab)
418			printk(KERN_WARNING
419			       "%s: jpg_fbuffer_alloc: buffer %d allready allocated ???\n",
420			       zr->name, i);
421
422		/* Allocate fragment table for this buffer */
423
424		mem = get_free_page(GFP_KERNEL);
425		if (mem == 0) {
426			printk(KERN_ERR
427			       "%s: jpg_fbuffer_alloc: get_free_page (frag_tab) failed for buffer %d\n",
428			       zr->name, i);
429			jpg_fbuffer_free(zr);
430			return -ENOBUFS;
431		}
432		memset((void *) mem, 0, PAGE_SIZE);
433		zr->jpg_gbuf[i].frag_tab = (u32 *) mem;
434		zr->jpg_gbuf[i].frag_tab_bus = virt_to_bus((void *) mem);
435
436		//if (alloc_contig) {
437		if (zr->need_contiguous) {
438			mem = (unsigned long) kmalloc(zr->jpg_bufsize, GFP_KERNEL);
439			if (mem == 0) {
440				printk(KERN_ERR "%s: jpg_fbuffer_alloc: kmalloc failed for buffer %d\n",
441				       zr->name, i);
442				jpg_fbuffer_free(zr);
443				return -ENOBUFS;
444			}
445			zr->jpg_gbuf[i].frag_tab[0] = virt_to_bus((void *) mem);
446			zr->jpg_gbuf[i].frag_tab[1] =
447			    ((zr->jpg_bufsize / 4) << 1) | 1;
448			for (off = 0; off < zr->jpg_bufsize; off += PAGE_SIZE)
449				mem_map_reserve(MAP_NR(mem + off));
450		} else {
451			/* jpg_bufsize is allreay page aligned */
452			for (j = 0; j < zr->jpg_bufsize / PAGE_SIZE; j++)
453			{
454				mem = get_free_page(GFP_KERNEL);
455				if (mem == 0) {
456					printk(KERN_ERR
457					       "%s: jpg_fbuffer_alloc: get_free_page failed for buffer %d\n",
458					       zr->name, i);
459					jpg_fbuffer_free(zr);
460					return -ENOBUFS;
461				}
462
463				zr->jpg_gbuf[i].frag_tab[2 * j] =
464				    virt_to_bus((void *) mem);
465				zr->jpg_gbuf[i].frag_tab[2 * j + 1] =
466				    (PAGE_SIZE / 4) << 1;
467				mem_map_reserve(MAP_NR(mem));
468			}
469
470			zr->jpg_gbuf[i].frag_tab[2 * j - 1] |= 1;
471		}
472	}
473
474	DEBUG1(printk
475	       ("%s: jpg_fbuffer_alloc: %ld KB allocated\n", zr->name,
476		(zr->jpg_nbufs * zr->jpg_bufsize) >> 10));
477	zr->jpg_buffers_allocated = 1;
478	return 0;
479}
480
481/* free the MJPEG grab buffers */
482static void jpg_fbuffer_free(struct zoran *zr)
483{
484	int i, j, off;		// alloc_contig;
485	unsigned char *mem;
486
487	/* Decide if we should alloc contiguous or fragmented memory */
488	/* This has to be identical in jpg_fbuffer_alloc and jpg_fbuffer_free */
489
490	//alloc_contig = (zr->jpg_bufsize <= MAX_KMALLOC_MEM);
491
492	for (i = 0; i < zr->jpg_nbufs; i++) {
493		if (!zr->jpg_gbuf[i].frag_tab)
494			continue;
495
496		//if (alloc_contig) {
497		if (zr->need_contiguous) {
498			if (zr->jpg_gbuf[i].frag_tab[0]) {
499				mem =
500				    (unsigned char *) bus_to_virt(zr->
501								  jpg_gbuf
502								  [i].
503								  frag_tab
504								  [0]);
505				for (off = 0; off < zr->jpg_bufsize;
506				     off += PAGE_SIZE)
507					mem_map_unreserve(MAP_NR
508							  (mem + off));
509				kfree((void *) mem);
510				zr->jpg_gbuf[i].frag_tab[0] = 0;
511				zr->jpg_gbuf[i].frag_tab[1] = 0;
512			}
513		} else {
514			for (j = 0; j < zr->jpg_bufsize / PAGE_SIZE; j++) {
515				if (!zr->jpg_gbuf[i].frag_tab[2 * j])
516					break;
517				mem_map_unreserve(MAP_NR
518						  (bus_to_virt
519						   (zr->jpg_gbuf[i].
520						    frag_tab[2 * j])));
521				free_page((unsigned long)
522					  bus_to_virt(zr->jpg_gbuf[i].
523						      frag_tab[2 * j]));
524				zr->jpg_gbuf[i].frag_tab[2 * j] = 0;
525				zr->jpg_gbuf[i].frag_tab[2 * j + 1] = 0;
526			}
527		}
528
529		free_page((unsigned long) zr->jpg_gbuf[i].frag_tab);
530		zr->jpg_gbuf[i].frag_tab = NULL;
531	}
532	zr->jpg_buffers_allocated = 0;
533}
534
535
536/* ----------------------------------------------------------------------- */
537
538/* I2C functions                                                           */
539
540#define I2C_DELAY   10
541
542
543/* software I2C functions */
544
545static void i2c_setlines(struct i2c_bus *bus, int ctrl, int data)
546{
547	struct zoran *zr = (struct zoran *) bus->data;
548	btwrite((data << 1) | ctrl, ZR36057_I2CBR);
549	udelay(I2C_DELAY);
550}
551
552static int i2c_getdataline(struct i2c_bus *bus)
553{
554	struct zoran *zr = (struct zoran *) bus->data;
555	return (btread(ZR36057_I2CBR) >> 1) & 1;
556}
557
558static void attach_inform(struct i2c_bus *bus, int id)
559{
560	int i;
561	struct zoran *zr = (struct zoran *) bus->data;
562
563	DEBUG1(printk(KERN_DEBUG "%s: i2c attach %02x\n", zr->name, id));
564	for (i = 0; i < bus->devcount; i++) {
565		if (strcmp(bus->devices[i]->name, "saa7110") == 0) {
566			if (zr->revision < 2) {
567				zr->card = DC10;
568				sprintf(zr->name, "DC10[%u]", zr->id);
569			} else {
570				zr->card = DC10plus;
571				sprintf(zr->name, "DC10plus[%u]", zr->id);
572			}
573			break;
574		}
575		if (strcmp(bus->devices[i]->name, "bt819") == 0) {
576			zr->card = LML33;
577			sprintf(zr->name, "LML33[%u]", zr->id);
578			break;
579		}
580		if (strcmp(bus->devices[i]->name, "saa7111") == 0) {
581			zr->card = BUZ;
582			sprintf(zr->name, "Buz[%u]", zr->id);
583			break;
584		}
585	}
586}
587
588static void detach_inform(struct i2c_bus *bus, int id)
589{
590	DEBUG1(struct zoran *zr = (struct zoran *) bus->data);
591	DEBUG1(printk(KERN_DEBUG "%s: i2c detach %02x\n", zr->name, id));
592}
593
594static struct i2c_bus zoran_i2c_bus_template = {
595	"zr36057",
596	I2C_BUSID_BT848,
597	NULL,
598
599	SPIN_LOCK_UNLOCKED,
600
601	attach_inform,
602	detach_inform,
603
604	i2c_setlines,
605	i2c_getdataline,
606	NULL,
607	NULL,
608};
609
610/*
611 *   Set the registers for the size we have specified. Don't bother
612 *   trying to understand this without the ZR36057 manual in front of
613 *   you [AC].
614 *
615 *   PS: The manual is free for download in .pdf format from
616 *   www.zoran.com - nicely done those folks.
617 */
618
619static struct tvnorm f50sqpixel = { 944, 768, 83, 880, 625, 576, 16 };
620static struct tvnorm f60sqpixel = { 780, 640, 51, 716, 525, 480, 12 };
621
622static struct tvnorm f50ccir601 = { 864, 720, 75, 804, 625, 576, 18 };
623static struct tvnorm f60ccir601 = { 858, 720, 57, 788, 525, 480, 16 };
624
625static struct tvnorm *dc10norms[] = {
626	&f50sqpixel,		/* PAL-BDGHI */
627	&f60sqpixel,		/* NTSC */
628	&f50sqpixel,		/* SECAM */
629};
630
631static struct tvnorm *lml33norms[] = {
632	&f50ccir601,		/* PAL-BDGHI */
633	&f60ccir601,		/* NTSC      */
634	NULL,			/* SECAM (not supported in LML33) */
635};
636
637static struct tvnorm *buznorms[] = {
638	&f50ccir601,		/* PAL-BDGHI */
639	&f60ccir601,		/* NTSC      */
640	NULL,			/* SECAM     */
641};
642
643static struct tvnorm *unsupported[] = {
644	NULL,			/* PAL-BDGHI */
645	NULL,			/* NTSC      */
646	NULL,			/* SECAM     */
647};
648
649static struct tvnorm **cardnorms[] = {
650	unsupported,		/* UNKNOWN  */
651	dc10norms,		/* DC10     */
652	dc10norms,		/* DC10plus */
653	lml33norms,		/* LML33    */
654	buznorms,		/* Buz      */
655};
656
657static u32 cardvsync[] = {
658	0,			/* UNKNOWN  */
659	ZR36057_ISR_GIRQ1,	/* DC10     */
660	ZR36057_ISR_GIRQ1,	/* DC10plus */
661	ZR36057_ISR_GIRQ0,	/* LML33    */
662	ZR36057_ISR_GIRQ0,	/* Buz      */
663};
664
665static u32 cardjpegint[] = {
666	0,			/* UNKNOWN  */
667	ZR36057_ISR_GIRQ0,	/* DC10     */
668	ZR36057_ISR_GIRQ0,	/* DC10plus */
669	ZR36057_ISR_GIRQ1,	/* LML33    */
670	ZR36057_ISR_GIRQ1,	/* Buz      */
671};
672
673static int format2bpp(int format)
674{
675	int bpp;
676
677	/* Determine the number of bytes per pixel for the video format requested */
678
679	switch (format) {
680
681	case VIDEO_PALETTE_YUV422:
682		bpp = 2;
683		break;
684
685	case VIDEO_PALETTE_RGB555:
686		bpp = 2;
687		break;
688
689	case VIDEO_PALETTE_RGB565:
690		bpp = 2;
691		break;
692
693	case VIDEO_PALETTE_RGB24:
694		bpp = 3;
695		break;
696
697	case VIDEO_PALETTE_RGB32:
698		bpp = 4;
699		break;
700
701	default:
702		bpp = 0;
703	}
704
705	return bpp;
706}
707
708static void zr36057_adjust_vfe(struct zoran *zr,
709			       enum zoran_codec_mode mode)
710{
711	u32 reg;
712	switch (mode) {
713	case BUZ_MODE_MOTION_DECOMPRESS:
714		btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
715		reg = btread(ZR36057_VFEHCR);
716		if (reg & (1 << 10)) {
717			reg += ((1 << 10) | 1);
718		}
719		btwrite(reg, ZR36057_VFEHCR);
720		break;
721	case BUZ_MODE_MOTION_COMPRESS:
722	case BUZ_MODE_IDLE:
723	default:
724		if (zr->params.norm == VIDEO_MODE_NTSC)
725			btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
726		else
727			btor(ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
728		reg = btread(ZR36057_VFEHCR);
729		if (!(reg & (1 << 10))) {
730			reg -= ((1 << 10) | 1);
731		}
732		btwrite(reg, ZR36057_VFEHCR);
733		break;
734	}
735}
736
737/*
738 * set geometry
739 */
740static void zr36057_set_vfe(struct zoran *zr, int video_width,
741			    int video_height, unsigned int video_format)
742{
743	struct tvnorm *tvn;
744	unsigned HStart, HEnd, VStart, VEnd;
745	unsigned DispMode;
746	unsigned VidWinWid, VidWinHt;
747	unsigned hcrop1, hcrop2, vcrop1, vcrop2;
748	unsigned Wa, We, Ha, He;
749	unsigned X, Y, HorDcm, VerDcm;
750	u32 reg;
751	unsigned mask_line_size;
752
753	tvn = zr->timing;
754
755	Wa = tvn->Wa;
756	Ha = tvn->Ha;
757
758	DEBUG1(printk (BUZ_INFO ": width = %d, height = %d\n", video_width, video_height));
759
760	if (zr->params.norm != VIDEO_MODE_PAL
761	    && zr->params.norm != VIDEO_MODE_NTSC
762	    && zr->params.norm != VIDEO_MODE_SECAM) {
763		printk(KERN_ERR "%s: set_vfe: video_norm = %d not valid\n",
764		       zr->name, zr->params.norm);
765		return;
766	}
767	if (video_width < BUZ_MIN_WIDTH || video_height < BUZ_MIN_HEIGHT
768	    || video_width > Wa || video_height > Ha) {
769		printk(KERN_ERR "%s: set_vfe: w=%d h=%d not valid\n",
770		       zr->name, video_width, video_height);
771		return;
772	}
773
774	/* if window has more than half of active height,
775	   switch on interlacing - we want the full information */
776
777	zr->video_interlace = (video_height > Ha / 2);
778
779	/**** zr36057 ****/
780
781	/* horizontal */
782	VidWinWid = video_width;
783	X = (VidWinWid * 64 + tvn->Wa - 1) / tvn->Wa;
784	We = (VidWinWid * 64) / X;
785	HorDcm = 64 - X;
786	hcrop1 = 2 * ((tvn->Wa - We) / 4);
787	hcrop2 = tvn->Wa - We - hcrop1;
788	HStart = tvn->HStart | 1;
789	if (zr->card == LML33)
790		HStart += 62;
791	if (zr->card == BUZ) {	//HStart += 67;
792		HStart += 44;
793	}
794	HEnd = HStart + tvn->Wa - 1;
795	HStart += hcrop1;
796	HEnd -= hcrop2;
797	reg = ((HStart & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HStart)
798	    | ((HEnd & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HEnd);
799	if (zr->card != BUZ)
800		reg |= ZR36057_VFEHCR_HSPol;
801	btwrite(reg, ZR36057_VFEHCR);
802
803	/* Vertical */
804	DispMode = !zr->video_interlace;
805	VidWinHt = DispMode ? video_height : video_height / 2;
806	Y = (VidWinHt * 64 * 2 + tvn->Ha - 1) / tvn->Ha;
807	He = (VidWinHt * 64) / Y;
808	VerDcm = 64 - Y;
809	vcrop1 = (tvn->Ha / 2 - He) / 2;
810	vcrop2 = tvn->Ha / 2 - He - vcrop1;
811	VStart = tvn->VStart;
812	VEnd = VStart + tvn->Ha / 2 - 1;
813	VStart += vcrop1;
814	VEnd -= vcrop2;
815	reg = ((VStart & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VStart)
816	    | ((VEnd & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VEnd);
817	reg |= ZR36057_VFEVCR_VSPol;
818	btwrite(reg, ZR36057_VFEVCR);
819
820	/* scaler and pixel format */
821	reg = 0;
822	reg |= (HorDcm << ZR36057_VFESPFR_HorDcm);
823	reg |= (VerDcm << ZR36057_VFESPFR_VerDcm);
824	reg |= (DispMode << ZR36057_VFESPFR_DispMode);
825	reg |= ZR36057_VFESPFR_LittleEndian;
826	/* RJ: I don't know, why the following has to be the opposite
827	   of the corresponding ZR36060 setting, but only this way
828	   we get the correct colors when uncompressing to the screen  */
829	//reg |= ZR36057_VFESPFR_VCLKPol; /**/
830	/* RJ: Don't know if that is needed for NTSC also */
831	if (zr->params.norm != VIDEO_MODE_NTSC)
832		reg |= ZR36057_VFESPFR_ExtFl;	// NEEDED!!!!!!! Wolfgang
833	reg |= ZR36057_VFESPFR_TopField;
834	switch (video_format) {
835
836	case VIDEO_PALETTE_YUV422:
837		reg |= ZR36057_VFESPFR_YUV422;
838		break;
839
840	case VIDEO_PALETTE_RGB555:
841		reg |= ZR36057_VFESPFR_RGB555 | ZR36057_VFESPFR_ErrDif;
842		break;
843
844	case VIDEO_PALETTE_RGB565:
845		reg |= ZR36057_VFESPFR_RGB565 | ZR36057_VFESPFR_ErrDif;
846		break;
847
848	case VIDEO_PALETTE_RGB24:
849		reg |= ZR36057_VFESPFR_RGB888 | ZR36057_VFESPFR_Pack24;
850		break;
851
852	case VIDEO_PALETTE_RGB32:
853		reg |= ZR36057_VFESPFR_RGB888;
854		break;
855
856	default:
857		printk(KERN_INFO "%s: Unknown color_fmt=%x\n", zr->name,
858		       video_format);
859		return;
860
861	}
862	if (HorDcm >= 48) {
863		reg |= 3 << ZR36057_VFESPFR_HFilter;	/* 5 tap filter */
864	} else if (HorDcm >= 32) {
865		reg |= 2 << ZR36057_VFESPFR_HFilter;	/* 4 tap filter */
866	} else if (HorDcm >= 16) {
867		reg |= 1 << ZR36057_VFESPFR_HFilter;	/* 3 tap filter */
868	}
869	btwrite(reg, ZR36057_VFESPFR);
870
871	/* display configuration */
872
873	reg = (16 << ZR36057_VDCR_MinPix)
874	    | (VidWinHt << ZR36057_VDCR_VidWinHt)
875	    | (VidWinWid << ZR36057_VDCR_VidWinWid);
876	if (triton || zr->revision <= 1)
877		reg &= ~ZR36057_VDCR_Triton;
878	else
879		reg |= ZR36057_VDCR_Triton;
880	btwrite(reg, ZR36057_VDCR);
881
882	/* Write overlay clipping mask data, but don't enable overlay clipping */
883	/* RJ: since this makes only sense on the screen, we use
884	   zr->window.width instead of video_width */
885
886	mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
887	reg = virt_to_bus(zr->overlay_mask);
888	btwrite(reg, ZR36057_MMTR);
889	reg = virt_to_bus(zr->overlay_mask + mask_line_size);
890	btwrite(reg, ZR36057_MMBR);
891	reg = mask_line_size - (zr->window.width + 31) / 32;
892	if (DispMode == 0)
893		reg += mask_line_size;
894	reg <<= ZR36057_OCR_MaskStride;
895	btwrite(reg, ZR36057_OCR);
896
897	zr36057_adjust_vfe(zr, zr->codec_mode);
898
899}
900
901/*
902 * Switch overlay on or off
903 */
904
905static void zr36057_overlay(struct zoran *zr, int on)
906{
907	int fmt, bpp;
908	u32 reg;
909
910	if (on) {
911		/* do the necessary settings ... */
912
913		btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);	/* switch it off first */
914
915		switch (zr->buffer.depth) {
916		case 15:
917			fmt = VIDEO_PALETTE_RGB555;
918			bpp = 2;
919			break;
920		case 16:
921			fmt = VIDEO_PALETTE_RGB565;
922			bpp = 2;
923			break;
924		case 24:
925			fmt = VIDEO_PALETTE_RGB24;
926			bpp = 3;
927			break;
928		case 32:
929			fmt = VIDEO_PALETTE_RGB32;
930			bpp = 4;
931			break;
932		default:
933			fmt = 0;
934			bpp = 0;
935		}
936
937		zr36057_set_vfe(zr, zr->window.width, zr->window.height,
938				fmt);
939
940		/* Start and length of each line MUST be 4-byte aligned.
941		   This should be allready checked before the call to this routine.
942		   All error messages are internal driver checking only! */
943
944		/* video display top and bottom registers */
945
946		reg =
947		    (u32) zr->buffer.base + zr->window.x * bpp +
948		    zr->window.y * zr->buffer.bytesperline;
949		btwrite(reg, ZR36057_VDTR);
950		if (reg & 3)
951			printk(KERN_ERR
952			       "%s: zr36057_overlay: video_address not aligned\n",
953			       zr->name);
954		if (zr->video_interlace)
955			reg += zr->buffer.bytesperline;
956		btwrite(reg, ZR36057_VDBR);
957
958		/* video stride, status, and frame grab register */
959
960		reg = zr->buffer.bytesperline - zr->window.width * bpp;
961		if (zr->video_interlace)
962			reg += zr->buffer.bytesperline;
963		if (reg & 3)
964			printk(KERN_ERR
965			       "%s: zr36057_overlay: video_stride not aligned\n",
966			       zr->name);
967		reg = (reg << ZR36057_VSSFGR_DispStride);
968		reg |= ZR36057_VSSFGR_VidOvf;	/* clear overflow status */
969		btwrite(reg, ZR36057_VSSFGR);
970
971		/* Set overlay clipping */
972
973		if (zr->window.clipcount)
974			btor(ZR36057_OCR_OvlEnable, ZR36057_OCR);
975
976		/* ... and switch it on */
977
978		btor(ZR36057_VDCR_VidEn, ZR36057_VDCR);
979	} else {
980		/* Switch it off */
981
982		btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
983	}
984}
985
986/*
987 * The overlay mask has one bit for each pixel on a scan line,
988 *  and the maximum window size is BUZ_MAX_WIDTH * BUZ_MAX_HEIGHT pixels.
989 */
990static void write_overlay_mask(struct zoran *zr, struct video_clip *vp,
991			       int count)
992{
993	unsigned mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
994	u32 *mask;
995	int x, y, width, height;
996	unsigned i, j, k;
997	u32 reg;
998
999	/* fill mask with one bits */
1000	memset(zr->overlay_mask, ~0, mask_line_size * 4 * BUZ_MAX_HEIGHT);
1001	reg = 0;
1002
1003	for (i = 0; i < count; ++i) {
1004		/* pick up local copy of clip */
1005		x = vp[i].x;
1006		y = vp[i].y;
1007		width = vp[i].width;
1008		height = vp[i].height;
1009
1010		/* trim clips that extend beyond the window */
1011		if (x < 0) {
1012			width += x;
1013			x = 0;
1014		}
1015		if (y < 0) {
1016			height += y;
1017			y = 0;
1018		}
1019		if (x + width > zr->window.width) {
1020			width = zr->window.width - x;
1021		}
1022		if (y + height > zr->window.height) {
1023			height = zr->window.height - y;
1024		}
1025
1026		/* ignore degenerate clips */
1027		if (height <= 0) {
1028			continue;
1029		}
1030		if (width <= 0) {
1031			continue;
1032		}
1033
1034		/* apply clip for each scan line */
1035		for (j = 0; j < height; ++j) {
1036			/* reset bit for each pixel */
1037			/* this can be optimized later if need be */
1038			mask = zr->overlay_mask + (y + j) * mask_line_size;
1039			for (k = 0; k < width; ++k) {
1040				mask[(x + k) / 32] &=
1041				    ~((u32) 1 << (x + k) % 32);
1042			}
1043		}
1044	}
1045}
1046
1047/* Enable/Disable uncompressed memory grabbing of the 36057 */
1048
1049static void zr36057_set_memgrab(struct zoran *zr, int mode)
1050{
1051	if (mode) {
1052		if (btread(ZR36057_VSSFGR) &
1053		    (ZR36057_VSSFGR_SnapShot | ZR36057_VSSFGR_FrameGrab))
1054			printk(KERN_WARNING
1055			       "%s: zr36057_set_memgrab_on with SnapShot or FrameGrab on ???\n",
1056			       zr->name);
1057
1058		/* switch on VSync interrupts */
1059
1060		btwrite(IRQ_MASK, ZR36057_ISR);	// Clear Interrupts
1061		btor(cardvsync[zr->card], ZR36057_ICR);	// SW
1062
1063		/* enable SnapShot */
1064
1065		btor(ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
1066
1067		/* Set zr36057 video front end  and enable video */
1068
1069		zr36057_set_vfe(zr, zr->gwidth, zr->gheight, zr->gformat);
1070
1071		zr->v4l_memgrab_active = 1;
1072	} else {
1073		zr->v4l_memgrab_active = 0;
1074
1075		/* switch off VSync interrupts */
1076
1077		//btand(~ZR36057_ICR_GIRQ1, ZR36057_ICR); // SW
1078
1079		/* reenable grabbing to screen if it was running */
1080
1081		if (zr->v4l_overlay_active) {
1082			zr36057_overlay(zr, 1);
1083		} else {
1084			btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
1085			btand(~ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
1086		}
1087	}
1088}
1089
1090static int wait_grab_pending(struct zoran *zr)
1091{
1092	unsigned long flags;
1093
1094	/* wait until all pending grabs are finished */
1095
1096	if (!zr->v4l_memgrab_active)
1097		return 0;
1098
1099	while (zr->v4l_pend_tail != zr->v4l_pend_head) {
1100		interruptible_sleep_on(&zr->v4l_capq);
1101		if (signal_pending(current))
1102			return -ERESTARTSYS;
1103	}
1104
1105	spin_lock_irqsave(&zr->lock, flags);
1106	zr36057_set_memgrab(zr, 0);
1107	spin_unlock_irqrestore(&zr->lock, flags);
1108
1109	return 0;
1110}
1111
1112/*
1113 *   V4L Buffer grabbing
1114 */
1115
1116static int v4l_grab(struct zoran *zr, struct video_mmap *mp)
1117{
1118	unsigned long flags;
1119	int res, bpp;
1120
1121	/*
1122	 * There is a long list of limitations to what is allowed to be grabbed
1123	 * We don't output error messages here, since some programs (e.g. xawtv)
1124	 * just try several settings to find out what is valid or not.
1125	 */
1126
1127	/* No grabbing outside the buffer range! */
1128
1129	if (mp->frame >= v4l_nbufs || mp->frame < 0) {
1130		DEBUG2(printk
1131		       (KERN_ERR "%s: Can not grab frame %d\n", zr->name,
1132			mp->frame));
1133		return -EINVAL;
1134	}
1135
1136	/* Check size and format of the grab wanted */
1137
1138	if (mp->height < BUZ_MIN_HEIGHT || mp->width < BUZ_MIN_WIDTH
1139	    || mp->height > BUZ_MAX_HEIGHT || mp->width > BUZ_MAX_WIDTH) {
1140		DEBUG2(printk
1141		       (KERN_ERR "%s: Wrong frame size.\n", zr->name));
1142		return -EINVAL;
1143	}
1144
1145	bpp = format2bpp(mp->format);
1146	if (bpp == 0) {
1147		DEBUG2(printk
1148		       (KERN_ERR "%s: Wrong bytes-per-pixel format\n",
1149			zr->name));
1150		return -EINVAL;
1151	}
1152
1153	/* Check against available buffer size */
1154
1155	if (mp->height * mp->width * bpp > v4l_bufsize) {
1156		DEBUG2(printk
1157		       (KERN_ERR "%s: Video buffer size is too small\n",
1158			zr->name));
1159		return -EINVAL;
1160	}
1161
1162	/* The video front end needs 4-byte alinged line sizes */
1163
1164	if ((bpp == 2 && (mp->width & 1)) || (bpp == 3 && (mp->width & 3))) {
1165		DEBUG2(printk
1166		       (KERN_ERR "%s: Wrong frame alingment\n", zr->name));
1167		return -EINVAL;
1168	}
1169
1170	/*
1171	 * To minimize the time spent in the IRQ routine, we avoid setting up
1172	 * the video front end there.
1173	 * If this grab has different parameters from a running streaming capture
1174	 * we stop the streaming capture and start it over again.
1175	 */
1176
1177	if (zr->v4l_memgrab_active
1178	    && (zr->gwidth != mp->width || zr->gheight != mp->height
1179		|| zr->gformat != mp->format)) {
1180		res = wait_grab_pending(zr);
1181		if (res)
1182			return res;
1183	}
1184	zr->gwidth = mp->width;
1185	zr->gheight = mp->height;
1186	zr->gformat = mp->format;
1187	zr->gbpl = bpp * zr->gwidth;
1188
1189
1190	spin_lock_irqsave(&zr->lock, flags);
1191
1192	/* make sure a grab isn't going on currently with this buffer */
1193
1194	switch (zr->v4l_gbuf[mp->frame].state) {
1195
1196	default:
1197	case BUZ_STATE_PEND:
1198		res = -EBUSY;	/* what are you doing? */
1199		break;
1200
1201	case BUZ_STATE_USER:
1202	case BUZ_STATE_DONE:
1203		/* since there is at least one unused buffer there's room for at least one more pend[] entry */
1204		zr->v4l_pend[zr->v4l_pend_head++ & V4L_MASK_FRAME] =
1205		    mp->frame;
1206		zr->v4l_gbuf[mp->frame].state = BUZ_STATE_PEND;
1207		res = 0;
1208		break;
1209
1210	}
1211
1212	/* put the 36057 into frame grabbing mode */
1213
1214	if (!res && !zr->v4l_memgrab_active)
1215		zr36057_set_memgrab(zr, 1);
1216
1217	spin_unlock_irqrestore(&zr->lock, flags);
1218	//DEBUG2(printk(KERN_INFO "%s: Frame grab 3...\n", zr->name));
1219
1220	return res;
1221}
1222
1223/*
1224 * Sync on a V4L buffer
1225 */
1226
1227static int v4l_sync(struct zoran *zr, int frame)
1228{
1229	unsigned long flags;
1230
1231	/* check passed-in frame number */
1232
1233	if (frame >= v4l_nbufs || frame < 0) {
1234		DEBUG1(printk(KERN_ERR "%s: v4l_sync: frame %d is invalid\n",
1235		       zr->name, frame));
1236		return -EINVAL;
1237	}
1238
1239	/* Check if is buffer was queued at all */
1240
1241	if (zr->v4l_gbuf[frame].state == BUZ_STATE_USER) {
1242		DEBUG1(printk(KERN_ERR
1243		       "%s: v4l_sync: Attempt to sync on a buffer which was not queued?\n",
1244		       zr->name));
1245		return -EPROTO;
1246	}
1247
1248	/* wait on this buffer to get ready */
1249
1250	while (zr->v4l_gbuf[frame].state == BUZ_STATE_PEND) {
1251		interruptible_sleep_on(&zr->v4l_capq);
1252		if (signal_pending(current))
1253			return -ERESTARTSYS;
1254	}
1255
1256	/* buffer should now be in BUZ_STATE_DONE */
1257
1258	if (zr->v4l_gbuf[frame].state != BUZ_STATE_DONE)
1259		printk(KERN_ERR "%s: v4l_sync - internal error\n",
1260		       zr->name);
1261
1262	/* Check if streaming capture has finished */
1263
1264	spin_lock_irqsave(&zr->lock, flags);
1265
1266	if (zr->v4l_pend_tail == zr->v4l_pend_head)
1267		zr36057_set_memgrab(zr, 0);
1268
1269	spin_unlock_irqrestore(&zr->lock, flags);
1270
1271	return 0;
1272}
1273
1274/*****************************************************************************
1275 *                                                                           *
1276 *  Set up the Buz-specific MJPEG part                                       *
1277 *                                                                           *
1278 *****************************************************************************/
1279
1280/*
1281Wait til post office is no longer busy */
1282static int post_office_wait(struct zoran *zr)
1283{
1284	u32 por;
1285
1286//      while (((por = btread(ZR36057_POR)) & (ZR36057_POR_POPen | ZR36057_POR_POTime)) == ZR36057_POR_POPen) {
1287	while ((por = btread(ZR36057_POR)) & ZR36057_POR_POPen) {
1288		/* wait for something to happen */
1289	}
1290	if ((por & ZR36057_POR_POTime) && zr->card != LML33
1291	    && zr->card != BUZ) {
1292		/* In LML33/BUZ \GWS line is not connected, so it has always timeout set */
1293		printk(KERN_WARNING "%s: pop timeout %08x\n", zr->name, por);
1294		return -1;
1295	}
1296	return 0;
1297}
1298
1299static int post_office_write(struct zoran *zr, unsigned guest,
1300			     unsigned reg, unsigned value)
1301{
1302	u32 por;
1303
1304	por =
1305	    ZR36057_POR_PODir | ZR36057_POR_POTime | ((guest & 7) << 20) |
1306	    ((reg & 7) << 16) | (value & 0xFF);
1307	btwrite(por, ZR36057_POR);
1308	return post_office_wait(zr);
1309}
1310
1311static int post_office_read(struct zoran *zr, unsigned guest, unsigned reg)
1312{
1313	u32 por;
1314
1315	por = ZR36057_POR_POTime | ((guest & 7) << 20) | ((reg & 7) << 16);
1316	btwrite(por, ZR36057_POR);
1317	if (post_office_wait(zr) < 0) {
1318		return -1;
1319	}
1320	return btread(ZR36057_POR) & 0xFF;
1321}
1322
1323static int zr36060_write_8(struct zoran *zr, unsigned reg, unsigned val)
1324{
1325	if (post_office_wait(zr)
1326	    || post_office_write(zr, 0, 1, reg >> 8)
1327	    || post_office_write(zr, 0, 2, reg)) {
1328		return -1;
1329	}
1330	return post_office_write(zr, 0, 3, val);
1331}
1332
1333static int zr36060_write_16(struct zoran *zr, unsigned reg, unsigned val)
1334{
1335	if (zr36060_write_8(zr, reg + 0, val >> 8)) {
1336		return -1;
1337	}
1338	return zr36060_write_8(zr, reg + 1, val >> 0);
1339}
1340
1341static int zr36060_write_24(struct zoran *zr, unsigned reg, unsigned val)
1342{
1343	if (zr36060_write_8(zr, reg + 0, val >> 16)) {
1344		return -1;
1345	}
1346	return zr36060_write_16(zr, reg + 1, val >> 0);
1347}
1348
1349static int zr36060_write_32(struct zoran *zr, unsigned reg, unsigned val)
1350{
1351	if (zr36060_write_16(zr, reg + 0, val >> 16)) {
1352		return -1;
1353	}
1354	return zr36060_write_16(zr, reg + 2, val >> 0);
1355}
1356
1357static u32 zr36060_read_8(struct zoran *zr, unsigned reg)
1358{
1359	if (post_office_wait(zr)
1360	    || post_office_write(zr, 0, 1, reg >> 8)
1361	    || post_office_write(zr, 0, 2, reg)) {
1362		return -1;
1363	}
1364	return post_office_read(zr, 0, 3) & 0xFF;
1365}
1366
1367/* ----------------------------------------------------------------------- */
1368
1369static void GPIO(struct zoran *zr, unsigned bit, unsigned value)
1370{
1371	u32 reg;
1372	u32 mask;
1373
1374	mask = 1 << (24 + bit);
1375	reg = btread(ZR36057_GPPGCR1) & ~mask;
1376	if (value) {
1377		reg |= mask;
1378	}
1379	btwrite(reg, ZR36057_GPPGCR1);
1380	udelay(1);
1381}
1382
1383
1384static void zr36060_sleep(struct zoran *zr, int sleep)
1385{
1386	switch (zr->card) {
1387	case DC10:
1388	case DC10plus:
1389		GPIO(zr, 3, !sleep);
1390		break;
1391	case BUZ:
1392	case LML33:
1393		GPIO(zr, 1, !sleep);
1394		break;
1395	default:
1396		break;
1397	}
1398	if (!sleep)
1399		udelay(500);
1400	else
1401		udelay(2);
1402}
1403
1404static int zr36060_reset(struct zoran *zr)
1405{
1406	switch (zr->card) {
1407	case DC10:
1408	case DC10plus:
1409		zr36060_sleep(zr, 0);
1410		GPIO(zr, 0, 0);
1411		udelay(2);
1412		GPIO(zr, 0, 1);
1413		udelay(2);
1414		break;
1415	case LML33:
1416	case BUZ:
1417		zr36060_sleep(zr, 0);
1418		post_office_write(zr, 3, 0, 0);
1419		udelay(2);
1420	default:;
1421	}
1422	return 0;
1423}
1424
1425static void set_frame(struct zoran *zr, int val)
1426{
1427	switch (zr->card) {
1428	case DC10:
1429	case DC10plus:
1430		GPIO(zr, 6, val);
1431		break;
1432	case LML33:
1433	case BUZ:
1434		GPIO(zr, 3, val);
1435		break;
1436	default:
1437		break;
1438	}
1439}
1440
1441static void set_videobus_dir(struct zoran *zr, int val)
1442{
1443	switch (zr->card) {
1444	case DC10:
1445	case DC10plus:
1446		GPIO(zr, 1, val);
1447		break;
1448	case LML33:
1449		if (lml33dpath == 0)
1450			GPIO(zr, 5, val);
1451		else
1452			GPIO(zr, 5, 1);
1453		break;
1454	case BUZ:
1455	default:
1456		break;
1457	}
1458}
1459
1460static void set_videobus_enable(struct zoran *zr, int val)
1461{
1462	switch (zr->card) {
1463	case LML33:
1464		GPIO(zr, 7, val);
1465		break;
1466	case DC10:
1467	case DC10plus:
1468	case BUZ:
1469	default:
1470		break;
1471	}
1472}
1473
1474static void zr36060_set_jpg(struct zoran *zr, enum zoran_codec_mode mode)
1475{
1476	struct tvnorm *tvn;
1477	u32 reg;
1478	int size, blocks;
1479
1480	reg = (1 << 0)		/* CodeMstr */
1481	    |(0 << 2)		/* CFIS=0 */
1482	    |(0 << 6)		/* Endian=0 */
1483	    |(0 << 7);		/* Code16=0 */
1484	zr36060_write_8(zr, 0x002, reg);
1485
1486	switch (mode) {
1487
1488	case BUZ_MODE_MOTION_DECOMPRESS:
1489	case BUZ_MODE_STILL_DECOMPRESS:
1490		reg = 0x00;	/* Codec mode = decompression */
1491		break;
1492
1493	case BUZ_MODE_MOTION_COMPRESS:
1494	case BUZ_MODE_STILL_COMPRESS:
1495	default:
1496		reg = 0xa4;	/* Codec mode = compression with variable scale factor */
1497		break;
1498
1499	}
1500	zr36060_write_8(zr, 0x003, reg);
1501
1502	reg = 0x00;		/* reserved, mbz */
1503	zr36060_write_8(zr, 0x004, reg);
1504
1505	/* code volume */
1506
1507	/* Target field size in pixels: */
1508	tvn = zr->timing;
1509	size =
1510	    (tvn->Ha / 2) * (tvn->Wa) / (zr->params.HorDcm) /
1511	    (zr->params.VerDcm);
1512	blocks = size / 64;
1513
1514	/* Target compressed field size in bits: */
1515	size = size * 16;	/* uncompressed size in bits */
1516	size = size * zr->params.quality / 400;	/* quality = 100 is a compression ratio 1:4 */
1517
1518	/* Lower limit (arbitrary, 1 KB) */
1519	if (size < 8192)
1520		size = 8192;
1521
1522	/* Upper limit: 6/8 of the code buffers */
1523	if (size * zr->params.field_per_buff > zr->jpg_bufsize * 6)
1524		size = zr->jpg_bufsize * 6 / zr->params.field_per_buff;
1525
1526	reg = size * 4 / blocks;
1527	if (reg > 0xf0)
1528		reg = 0xf0;	/* 480 bits/block, does 0xff represents unlimited? */
1529	zr36060_write_8(zr, 0x005, reg);
1530
1531	/* JPEG markers */
1532	reg = (zr->params.jpeg_markers) & 0x38;	/* DRI, DQT, DHT */
1533	if (zr->params.COM_len)
1534		reg |= JPEG_MARKER_COM;
1535	if (zr->params.APP_len)
1536		reg |= JPEG_MARKER_APP;
1537	zr36060_write_8(zr, 0x006, reg);
1538
1539	if (zr->card != LML33 && zr->card != BUZ) {
1540		reg = (0 << 3)	/* EOAV=0 */
1541		    |(0 << 2)	/* EOI=0 */
1542		    |(0 << 1)	/* END=0 */
1543		    |(1 << 0);	/* DATERR=1 */
1544	} else {
1545		reg = (0 << 3)	/* EOAV=0 */
1546		    |(0 << 2)	/* EOI=0 */
1547		    |(0 << 1)	/* END=0 */
1548		    |(0 << 0);	/* DATERR=0 */
1549	}
1550	zr36060_write_8(zr, 0x007, reg);
1551
1552	reg = size;
1553	zr36060_write_32(zr, 0x009, reg);
1554
1555	reg = (size * 10) / 11;
1556	zr36060_write_32(zr, 0x00d, reg);	// Not needed for compr. with variable scale factor, just in case ...
1557
1558	/* how do we set initial SF as a function of quality parameter? */
1559	reg = 0x0100;		/* SF=1.0 */
1560	zr36060_write_16(zr, 0x011, reg);
1561
1562	reg = 0x00ffffff;	/* AF=max */
1563	zr36060_write_24(zr, 0x013, reg);
1564
1565	reg = 0x0000;		/* test */
1566	zr36060_write_16(zr, 0x024, reg);
1567
1568	//post_office_read(zr,1,0);
1569}
1570
1571static void zr36060_set_video(struct zoran *zr, enum zoran_codec_mode mode)
1572{
1573	struct tvnorm *tvn;
1574	u32 reg;
1575	unsigned HStart;
1576
1577	tvn = zr->timing;
1578
1579	reg = (0 << 7)		/* Video8     */
1580	    |(0 << 6)		/* Range      */
1581	    |(0 << 3)		/* FlDet      */
1582	    |(1 << 2)		/* FlVedge    */
1583	    |(0 << 1)		/* FlExt      */
1584	    |(0 << 0);		/* SyncMstr   */
1585
1586	if (mode != BUZ_MODE_STILL_DECOMPRESS) {
1587		/* limit pixels to range 16..235 as per CCIR-601 */
1588		reg |= (1 << 6);	/* Range=1 */
1589	}
1590	zr36060_write_8(zr, 0x030, reg);
1591
1592	switch (zr->card) {
1593	case DC10:
1594	case DC10plus:
1595		reg = (0 << 7)	/* VCLKPol   */
1596		    |(0 << 6)	/* PValPol   */
1597		    |(0 << 5)	/* PoePol    */
1598		    |(0 << 4)	/* SImgPol   */
1599		    |(1 << 3)	/* BLPol     */
1600		    |(1 << 2)	/* FlPol     */
1601		    |(1 << 1)	/* HSPol     */
1602		    |(1 << 0);	/* VSPol     */
1603		break;
1604	case LML33:
1605		reg = (0 << 7)	/* VCLKPol=0 */
1606		    |(0 << 6)	/* PValPol=0 */
1607		    |(1 << 5)	/* PoePol=1 */
1608		    |(0 << 4)	/* SImgPol=0 */
1609		    |(0 << 3)	/* BLPol=0 */
1610		    |(0 << 2)	/* FlPol=0 */
1611		    |(0 << 1)	/* HSPol=0, sync on falling edge */
1612		    |(1 << 0);	/* VSPol=1 */
1613		break;
1614	case BUZ:
1615	default:
1616		reg = (0 << 7)	/* VCLKPol=0 */
1617		    |(0 << 6)	/* PValPol=0 */
1618		    |(1 << 5)	/* PoePol=1 */
1619		    |(0 << 4)	/* SImgPol=0 */
1620		    |(0 << 3)	/* BLPol=0 */
1621		    |(0 << 2)	/* FlPol=0 */
1622		    |(1 << 1)	/* HSPol=0, sync on falling edge */
1623		    |(1 << 0);	/* VSPol=1 */
1624		break;
1625	}
1626	zr36060_write_8(zr, 0x031, reg);
1627
1628	switch (zr->params.HorDcm) {
1629	default:
1630	case 1:
1631		reg = (0 << 0);
1632		break;		/* HScale = 0 */
1633
1634	case 2:
1635		reg = (1 << 0);
1636		break;		/* HScale = 1 */
1637
1638	case 4:
1639		reg = (2 << 0);
1640		break;		/* HScale = 2 */
1641	}
1642	if (zr->params.VerDcm == 2)
1643		reg |= (1 << 2);
1644	zr36060_write_8(zr, 0x032, reg);
1645
1646	reg = 0x00;		/* BackY */
1647	zr36060_write_8(zr, 0x033, reg);
1648
1649	reg = 0x80;		/* BackU */
1650	zr36060_write_8(zr, 0x034, reg);
1651
1652	reg = 0x80;		/* BackV */
1653	zr36060_write_8(zr, 0x035, reg);
1654
1655	/* sync generator */
1656
1657	reg = tvn->Ht - 1;	/* Vtotal */
1658	zr36060_write_16(zr, 0x036, reg);
1659
1660	reg = tvn->Wt - 1;	/* Htotal */
1661	zr36060_write_16(zr, 0x038, reg);
1662
1663	reg = 6 - 1;		/* VsyncSize */
1664	zr36060_write_8(zr, 0x03a, reg);
1665
1666	//reg   = 30 - 1;               /* HsyncSize */
1667	reg = (zr->params.norm == 1 ? 57 : 68);
1668	zr36060_write_8(zr, 0x03b, reg);
1669
1670	reg = tvn->VStart - 1;	/* BVstart */
1671	zr36060_write_8(zr, 0x03c, reg);
1672
1673	reg += tvn->Ha / 2;	/* BVend */
1674	zr36060_write_16(zr, 0x03e, reg);
1675
1676	reg = tvn->HStart + 64 - 1;	/* BHstart */
1677	zr36060_write_8(zr, 0x03d, reg);
1678
1679	reg += tvn->Wa;		/* BHend */
1680	zr36060_write_16(zr, 0x040, reg);
1681
1682	/* active area */
1683	reg = zr->params.img_y + tvn->VStart;	/* Vstart */
1684	zr36060_write_16(zr, 0x042, reg);
1685
1686	reg += zr->params.img_height;	/* Vend */
1687	zr36060_write_16(zr, 0x044, reg);
1688
1689	HStart = tvn->HStart;
1690	if (zr->card == BUZ) {
1691		HStart += 44;
1692	} else {
1693		HStart += 64;
1694	}
1695	reg = zr->params.img_x + HStart;	/* Hstart */
1696	zr36060_write_16(zr, 0x046, reg);
1697
1698	reg += zr->params.img_width;	/* Hend */
1699	zr36060_write_16(zr, 0x048, reg);
1700
1701	/* subimage area */
1702	reg = tvn->VStart - 4;	/* SVstart */
1703	zr36060_write_16(zr, 0x04a, reg);
1704
1705	reg += tvn->Ha / 2 + 8;	/* SVend */
1706	zr36060_write_16(zr, 0x04c, reg);
1707
1708	reg = tvn->HStart + 64 - 4;	/* SHstart */
1709	zr36060_write_16(zr, 0x04e, reg);
1710
1711	reg += tvn->Wa + 8;	/* SHend */
1712	zr36060_write_16(zr, 0x050, reg);
1713}
1714
1715static void zr36060_set_jpg_SOF(struct zoran *zr)
1716{
1717	u32 reg;
1718
1719
1720	reg = 0xffc0;		/* SOF marker */
1721	zr36060_write_16(zr, 0x060, reg);
1722
1723	reg = 17;		/* SOF length */
1724	zr36060_write_16(zr, 0x062, reg);
1725
1726	reg = 8;		/* precision 8 bits */
1727	zr36060_write_8(zr, 0x064, reg);
1728
1729	reg = zr->params.img_height / zr->params.VerDcm;	/* image height */
1730	zr36060_write_16(zr, 0x065, reg);
1731
1732	reg = zr->params.img_width / zr->params.HorDcm;	/* image width */
1733	zr36060_write_16(zr, 0x067, reg);
1734
1735	reg = 3;		/* 3 color components */
1736	zr36060_write_8(zr, 0x069, reg);
1737
1738	reg = 0x002100;		/* Y component */
1739	zr36060_write_24(zr, 0x06a, reg);
1740
1741	reg = 0x011101;		/* U component */
1742	zr36060_write_24(zr, 0x06d, reg);
1743
1744	reg = 0x021101;		/* V component */
1745	zr36060_write_24(zr, 0x070, reg);
1746}
1747
1748static void zr36060_set_jpg_SOS(struct zoran *zr)
1749{
1750	u32 reg;
1751
1752
1753	reg = 0xffda;		/* SOS marker */
1754	zr36060_write_16(zr, 0x07a, reg);
1755
1756	reg = 12;		/* SOS length */
1757	zr36060_write_16(zr, 0x07c, reg);
1758
1759	reg = 3;		/* 3 color components */
1760	zr36060_write_8(zr, 0x07e, reg);
1761
1762	reg = 0x0000;		/* Y component */
1763	zr36060_write_16(zr, 0x07f, reg);
1764
1765	reg = 0x0111;		/* U component */
1766	zr36060_write_16(zr, 0x081, reg);
1767
1768	reg = 0x0211;		/* V component */
1769	zr36060_write_16(zr, 0x083, reg);
1770
1771	reg = 0x003f00;		/* Start, end spectral scans */
1772	zr36060_write_24(zr, 0x085, reg);
1773}
1774
1775static void zr36060_set_jpg_DRI(struct zoran *zr)
1776{
1777	u32 reg;
1778
1779
1780	reg = 0xffdd;		/* DRI marker */
1781	zr36060_write_16(zr, 0x0c0, reg);
1782
1783	reg = 4;		/* DRI length */
1784	zr36060_write_16(zr, 0x0c2, reg);
1785
1786	reg = 8;		/* length in MCUs */
1787	zr36060_write_16(zr, 0x0c4, reg);
1788}
1789
1790static void zr36060_set_jpg_DQT(struct zoran *zr)
1791{
1792	unsigned i;
1793	unsigned adr;
1794	static const u8 dqt[] = {
1795		0xff, 0xdb,	/* DHT marker */
1796		0x00, 0x84,	/* DHT length */
1797		0x00,		/* table ID 0 */
1798		0x10, 0x0b, 0x0c, 0x0e, 0x0c, 0x0a, 0x10, 0x0e,
1799		0x0d, 0x0e, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28,
1800		0x1a, 0x18, 0x16, 0x16, 0x18, 0x31, 0x23, 0x25,
1801		0x1d, 0x28, 0x3a, 0x33, 0x3d, 0x3c, 0x39, 0x33,
1802		0x38, 0x37, 0x40, 0x48, 0x5c, 0x4e, 0x40, 0x44,
1803		0x57, 0x45, 0x37, 0x38, 0x50, 0x6d, 0x51, 0x57,
1804		0x5f, 0x62, 0x67, 0x68, 0x67, 0x3e, 0x4d, 0x71,
1805		0x79, 0x70, 0x64, 0x78, 0x5c, 0x65, 0x67, 0x63,
1806		0x01,		/* table ID 1 */
1807		0x11, 0x12, 0x12, 0x18, 0x15, 0x18, 0x2f, 0x1a,
1808		0x1a, 0x2f, 0x63, 0x42, 0x38, 0x42, 0x63, 0x63,
1809		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1810		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1811		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1812		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1813		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1814		0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63
1815	};
1816
1817	/* write fixed quantitization tables */
1818	adr = 0x0cc;
1819	for (i = 0; i < sizeof(dqt); ++i) {
1820		zr36060_write_8(zr, adr++, dqt[i]);
1821	}
1822}
1823
1824static void zr36060_set_jpg_DHT(struct zoran *zr)
1825{
1826	unsigned i;
1827	unsigned adr;
1828	static const u8 dht[] = {
1829		0xff, 0xc4,	/* DHT marker */
1830		0x01, 0xa2,	/* DHT length */
1831		0x00,		/* table class 0, ID 0 */
1832		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,	/* # codes of length 1..8 */
1833		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,	/* # codes of length 8..16 */
1834		0x00,		/* values for codes of length 2 */
1835		0x01, 0x02, 0x03, 0x04, 0x05,	/* values for codes of length 3 */
1836		0x06,		/* values for codes of length 4 */
1837		0x07,		/* values for codes of length 5 */
1838		0x08,		/* values for codes of length 6 */
1839		0x09,		/* values for codes of length 7 */
1840		0x0a,		/* values for codes of length 8 */
1841		0x0b,		/* values for codes of length 9 */
1842		0x01,		/* table class 0, ID 1 */
1843		0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,	/* # codes of length 1..8 */
1844		0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,	/* # codes of length 9..16 */
1845		0x00, 0x01, 0x02,	/* values for codes of length 2 */
1846		0x03,		/* values for codes of length 3 */
1847		0x04,		/* values for codes of length 4 */
1848		0x05,		/* values for codes of length 5 */
1849		0x06,		/* values for codes of length 6 */
1850		0x07,		/* values for codes of length 7 */
1851		0x08,		/* values for codes of length 8 */
1852		0x09,		/* values for codes of length 9 */
1853		0x0a,		/* values for codes of length 10 */
1854		0x0b,		/* values for codes of length 11 */
1855		0x10,
1856		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
1857		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d,
1858		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
1859		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
1860		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
1861		0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
1862		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
1863		0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
1864		0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
1865		0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
1866		0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
1867		0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
1868		0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
1869		0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
1870		0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
1871		0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
1872		0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
1873		0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
1874		0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
1875		0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
1876		0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
1877		0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
1878		0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04,
1879		0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00,
1880		0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11,
1881		0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51,
1882		0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08,
1883		0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23,
1884		0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a,
1885		0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18,
1886		0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35,
1887		0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45,
1888		0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55,
1889		0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65,
1890		0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75,
1891		0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84,
1892		0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93,
1893		0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2,
1894		0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
1895		0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9,
1896		0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8,
1897		0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
1898		0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
1899		0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5,
1900		0xf6, 0xf7, 0xf8, 0xf9, 0xfa
1901	};
1902
1903	/* write fixed Huffman tables */
1904	adr = 0x1d4;
1905	for (i = 0; i < sizeof(dht); ++i) {
1906		zr36060_write_8(zr, adr++, dht[i]);
1907	}
1908}
1909
1910static void zr36060_set_jpg_APP(struct zoran *zr)
1911{
1912	unsigned adr;
1913	int len, i;
1914	u32 reg;
1915
1916
1917	len = zr->params.APP_len;
1918	if (len < 0)
1919		len = 0;
1920	if (len > 60)
1921		len = 60;
1922
1923	i = zr->params.APPn;
1924	if (i < 0)
1925		i = 0;
1926	if (i > 15)
1927		i = 15;
1928
1929	reg = 0xffe0 + i;	/* APPn marker */
1930	zr36060_write_16(zr, 0x380, reg);
1931
1932	reg = len + 2;		/* APPn len */
1933	zr36060_write_16(zr, 0x382, reg);
1934
1935	/* write APPn data */
1936	adr = 0x384;
1937	for (i = 0; i < 60; i++) {
1938		zr36060_write_8(zr, adr++,
1939				(i < len ? zr->params.APP_data[i] : 0));
1940	}
1941}
1942
1943static void zr36060_set_jpg_COM(struct zoran *zr)
1944{
1945	unsigned adr;
1946	int len, i;
1947	u32 reg;
1948
1949
1950	len = zr->params.COM_len;
1951	if (len < 0)
1952		len = 0;
1953	if (len > 60)
1954		len = 60;
1955
1956	reg = 0xfffe;		/* COM marker */
1957	zr36060_write_16(zr, 0x3c0, reg);
1958
1959	reg = len + 2;		/* COM len */
1960	zr36060_write_16(zr, 0x3c2, reg);
1961
1962	/* write COM data */
1963	adr = 0x3c4;
1964	for (i = 0; i < 60; i++) {
1965		zr36060_write_8(zr, adr++,
1966				(i < len ? zr->params.COM_data[i] : 0));
1967	}
1968}
1969
1970static void zr36060_set_cap(struct zoran *zr, enum zoran_codec_mode mode)
1971{
1972	unsigned i;
1973	u32 reg;
1974
1975	zr36060_reset(zr);
1976	mdelay(10);
1977
1978	reg = (0 << 7)		/* Load=0 */
1979	    |(1 << 0);		/* SynRst=1 */
1980	zr36060_write_8(zr, 0x000, reg);
1981
1982	zr36060_set_jpg(zr, mode);
1983	zr36060_set_video(zr, mode);
1984	zr36060_set_jpg_SOF(zr);
1985	zr36060_set_jpg_SOS(zr);
1986	zr36060_set_jpg_DRI(zr);
1987	zr36060_set_jpg_DQT(zr);
1988	zr36060_set_jpg_DHT(zr);
1989	zr36060_set_jpg_APP(zr);
1990	zr36060_set_jpg_COM(zr);
1991
1992	reg = (1 << 7)		/* Load=1 */
1993	    |(1 << 0);		/* SynRst=0 */
1994	zr36060_write_8(zr, 0x000, reg);
1995
1996	/* wait for codec to unbusy */
1997	for (i = 0; i < 100000; ++i) {
1998		reg = zr36060_read_8(zr, 0x001);
1999		if ((reg & (1 << 7)) == 0) {
2000			return;
2001		}
2002		//udelay(100);
2003	}
2004	printk(KERN_ERR "%sZR36060: stuck busy, statux=%02x\n", zr->name,
2005	       reg);
2006}
2007
2008static void init_jpeg_queue(struct zoran *zr)
2009{
2010	int i;
2011	/* re-initialize DMA ring stuff */
2012	zr->jpg_que_head = 0;
2013	zr->jpg_dma_head = 0;
2014	zr->jpg_dma_tail = 0;
2015	zr->jpg_que_tail = 0;
2016	zr->jpg_seq_num = 0;
2017	zr->JPEG_error = 0;
2018	zr->num_errors = 0;
2019	zr->jpg_err_seq = 0;
2020	zr->jpg_err_shift = 0;
2021	zr->jpg_queued_num = 0;
2022	for (i = 0; i < zr->jpg_nbufs; i++) {
2023		zr->jpg_gbuf[i].state = BUZ_STATE_USER;	/* nothing going on */
2024	}
2025	for (i = 0; i < BUZ_NUM_STAT_COM; i++) {
2026		zr->stat_com[i] = 1;	/* mark as unavailable to zr36057 */
2027	}
2028}
2029
2030static void zr36057_set_jpg(struct zoran *zr, enum zoran_codec_mode mode)
2031{
2032	struct tvnorm *tvn;
2033	u32 reg;
2034
2035	tvn = zr->timing;
2036
2037	/* assert P_Reset */
2038	btwrite(0, ZR36057_JPC);
2039
2040	/* MJPEG compression mode */
2041	switch (mode) {
2042
2043	case BUZ_MODE_MOTION_COMPRESS:
2044	default:
2045		reg = ZR36057_JMC_MJPGCmpMode;
2046		break;
2047
2048	case BUZ_MODE_MOTION_DECOMPRESS:
2049		reg = ZR36057_JMC_MJPGExpMode;
2050		reg |= ZR36057_JMC_SyncMstr;
2051		/* RJ: The following is experimental - improves the output to screen */
2052		//if(zr->params.VFIFO_FB) reg |= ZR36057_JMC_VFIFO_FB; // No, it doesn't. SM
2053		break;
2054
2055	case BUZ_MODE_STILL_COMPRESS:
2056		reg = ZR36057_JMC_JPGCmpMode;
2057		break;
2058
2059	case BUZ_MODE_STILL_DECOMPRESS:
2060		reg = ZR36057_JMC_JPGExpMode;
2061		break;
2062
2063	}
2064	reg |= ZR36057_JMC_JPG;
2065	if (zr->params.field_per_buff == 1)
2066		reg |= ZR36057_JMC_Fld_per_buff;
2067	btwrite(reg, ZR36057_JMC);
2068
2069	/* vertical */
2070	btor(ZR36057_VFEVCR_VSPol, ZR36057_VFEVCR);
2071	reg =
2072	    (6 << ZR36057_VSP_VsyncSize) | (tvn->Ht << ZR36057_VSP_FrmTot);
2073	btwrite(reg, ZR36057_VSP);
2074	reg = ((zr->params.img_y + tvn->VStart) << ZR36057_FVAP_NAY)
2075	    | (zr->params.img_height << ZR36057_FVAP_PAY);
2076	btwrite(reg, ZR36057_FVAP);
2077
2078	/* horizontal */
2079	btor(ZR36057_VFEHCR_HSPol, ZR36057_VFEHCR);
2080	reg =
2081	    ((tvn->HSyncStart) << ZR36057_HSP_HsyncStart) | (tvn->
2082							     Wt <<
2083							     ZR36057_HSP_LineTot);
2084	btwrite(reg, ZR36057_HSP);
2085	reg = ((zr->params.img_x + tvn->HStart + 4) << ZR36057_FHAP_NAX)
2086	    | (zr->params.img_width << ZR36057_FHAP_PAX);
2087	btwrite(reg, ZR36057_FHAP);
2088
2089	/* field process parameters */
2090	if (zr->params.odd_even)
2091		reg = ZR36057_FPP_Odd_Even;
2092	else
2093		reg = 0;
2094	if (mode == BUZ_MODE_MOTION_DECOMPRESS && zr->card != LML33
2095	    && zr->card != BUZ)
2096		reg ^= ZR36057_FPP_Odd_Even;
2097
2098	btwrite(reg, ZR36057_FPP);
2099
2100	/* Set proper VCLK Polarity, else colors will be wrong during playback */
2101	//btor(ZR36057_VFESPFR_VCLKPol, ZR36057_VFESPFR);
2102
2103	/* code base address */
2104	reg = virt_to_bus(zr->stat_com);
2105	btwrite(reg, ZR36057_JCBA);
2106
2107	/* FIFO threshold (FIFO is 160. double words) */
2108	/* NOTE: decimal values here */
2109	switch (mode) {
2110
2111	case BUZ_MODE_STILL_COMPRESS:
2112	case BUZ_MODE_MOTION_COMPRESS:
2113		reg = 140;
2114		break;
2115
2116	case BUZ_MODE_STILL_DECOMPRESS:
2117	case BUZ_MODE_MOTION_DECOMPRESS:
2118		reg = 20;
2119		break;
2120
2121	default:
2122		reg = 80;
2123		break;
2124
2125	}
2126	btwrite(reg, ZR36057_JCFT);
2127	zr36057_adjust_vfe(zr, mode);
2128
2129}
2130
2131#if (DEBUGLEVEL > 2)
2132static void dump_guests(struct zoran *zr)
2133{
2134	int i, guest[8];
2135
2136	for (i = 1; i < 8; i++) {	// Don't read zr36060 here
2137		guest[i] = post_office_read(zr, i, 0);
2138	}
2139
2140	printk(KERN_INFO "%s: Guests:", zr->name);
2141
2142	for (i = 1; i < 8; i++) {
2143		printk(" 0x%02x", guest[i]);
2144	}
2145	printk("\n");
2146}
2147
2148static unsigned long get_time(void)
2149{
2150	struct timeval tv;
2151	do_gettimeofday(&tv);
2152	return (1000000 * tv.tv_sec + tv.tv_usec);
2153}
2154
2155static void detect_guest_activity(struct zoran *zr)
2156{
2157	int timeout, i, j, res, guest[8], guest0[8], change[8][3];
2158	unsigned long t0, t1;
2159
2160	dump_guests(zr);
2161	printk(KERN_INFO "%s: Detecting guests activity, please wait...\n",
2162	       zr->name);
2163	for (i = 1; i < 8; i++) {	// Don't read zr36060 here
2164		guest0[i] = guest[i] = post_office_read(zr, i, 0);
2165	}
2166
2167	timeout = 0;
2168	j = 0;
2169	t0 = get_time();
2170	while (timeout < 10000) {
2171		udelay(10);
2172		timeout++;
2173		for (i = 1; (i < 8) && (j < 8); i++) {
2174			res = post_office_read(zr, i, 0);
2175			if (res != guest[i]) {
2176				t1 = get_time();
2177				change[j][0] = (t1 - t0);
2178				t0 = t1;
2179				change[j][1] = i;
2180				change[j][2] = res;
2181				j++;
2182				guest[i] = res;
2183			}
2184		}
2185		if (j >= 8)
2186			break;
2187	}
2188	printk(KERN_INFO "%s: Guests:", zr->name);
2189
2190	for (i = 1; i < 8; i++) {
2191		printk(" 0x%02x", guest0[i]);
2192	}
2193	printk("\n");
2194	if (j == 0) {
2195		printk(KERN_INFO "%s: No activity detected.\n", zr->name);
2196		return;
2197	}
2198	for (i = 0; i < j; i++) {
2199		printk(KERN_INFO "%s: %6d: %d => 0x%02x\n", zr->name,
2200		       change[i][0], change[i][1], change[i][2]);
2201	}
2202}
2203#endif
2204
2205static void print_interrupts(struct zoran *zr)
2206{
2207	int res, noerr;
2208	noerr = 0;
2209	printk(KERN_INFO "%s: interrupts received:", zr->name);
2210	if ((res = zr->field_counter) < -1 || res > 1) {
2211		printk(" FD:%d", res);
2212	}
2213	if ((res = zr->intr_counter_GIRQ1) != 0) {
2214		printk(" GIRQ1:%d", res);
2215		noerr++;
2216	}
2217	if ((res = zr->intr_counter_GIRQ0) != 0) {
2218		printk(" GIRQ0:%d", res);
2219		noerr++;
2220	}
2221	if ((res = zr->intr_counter_CodRepIRQ) != 0) {
2222		printk(" CodRepIRQ:%d", res);
2223		noerr++;
2224	}
2225	if ((res = zr->intr_counter_JPEGRepIRQ) != 0) {
2226		printk(" JPEGRepIRQ:%d", res);
2227		noerr++;
2228	}
2229	if (zr->JPEG_max_missed) {
2230		printk(" JPEG delays: max=%d min=%d", zr->JPEG_max_missed,
2231		       zr->JPEG_min_missed);
2232	}
2233	if (zr->END_event_missed) {
2234		printk(" ENDs missed: %d", zr->END_event_missed);
2235	}
2236	//if (zr->jpg_queued_num) {
2237	printk(" queue_state=%ld/%ld/%ld/%ld", zr->jpg_que_tail,
2238	       zr->jpg_dma_tail, zr->jpg_dma_head, zr->jpg_que_head);
2239	//}
2240	if (!noerr) {
2241		printk(": no interrupts detected.");
2242	}
2243	printk("\n");
2244}
2245
2246static void clear_interrupt_counters(struct zoran *zr)
2247{
2248	zr->intr_counter_GIRQ1 = 0;
2249	zr->intr_counter_GIRQ0 = 0;
2250	zr->intr_counter_CodRepIRQ = 0;
2251	zr->intr_counter_JPEGRepIRQ = 0;
2252	zr->field_counter = 0;
2253	zr->IRQ1_in = 0;
2254	zr->IRQ1_out = 0;
2255	zr->JPEG_in = 0;
2256	zr->JPEG_out = 0;
2257	zr->JPEG_0 = 0;
2258	zr->JPEG_1 = 0;
2259	zr->END_event_missed = 0;
2260	zr->JPEG_missed = 0;
2261	zr->JPEG_max_missed = 0;
2262	zr->JPEG_min_missed = 0x7fffffff;
2263}
2264
2265static u32 count_reset_interrupt(struct zoran *zr)
2266{
2267	u32 isr;
2268	if ((isr = btread(ZR36057_ISR) & 0x78000000)) {
2269		if (isr & ZR36057_ISR_GIRQ1) {
2270			btwrite(ZR36057_ISR_GIRQ1, ZR36057_ISR);
2271			zr->intr_counter_GIRQ1++;
2272		}
2273		if (isr & ZR36057_ISR_GIRQ0) {
2274			btwrite(ZR36057_ISR_GIRQ0, ZR36057_ISR);
2275			zr->intr_counter_GIRQ0++;
2276		}
2277		if (isr & ZR36057_ISR_CodRepIRQ) {
2278			btwrite(ZR36057_ISR_CodRepIRQ, ZR36057_ISR);
2279			zr->intr_counter_CodRepIRQ++;
2280		}
2281		if (isr & ZR36057_ISR_JPEGRepIRQ) {
2282			btwrite(ZR36057_ISR_JPEGRepIRQ, ZR36057_ISR);
2283			zr->intr_counter_JPEGRepIRQ++;
2284		}
2285	}
2286	return isr;
2287}
2288
2289static void jpeg_start(struct zoran *zr)
2290{
2291	int reg;
2292	zr->frame_num = 0;
2293
2294	btwrite(ZR36057_JPC_P_Reset, ZR36057_JPC);	// /P_Reset
2295	btand(~ZR36057_MCTCR_CFlush, ZR36057_MCTCR);	// \CFlush
2296	btor(ZR36057_JPC_CodTrnsEn, ZR36057_JPC);	// /CodTrnsEn
2297	btwrite(IRQ_MASK, ZR36057_ISR);	// Clear IRQs
2298	btwrite(IRQ_MASK | ZR36057_ICR_IntPinEn, ZR36057_ICR);	// Enable IRQs
2299
2300	set_frame(zr, 0);	// \FRAME
2301
2302	/* JPEG codec guest ID */
2303	reg =
2304	    (1 << ZR36057_JCGI_JPEGuestID) | (0 <<
2305					      ZR36057_JCGI_JPEGuestReg);
2306	btwrite(reg, ZR36057_JCGI);
2307
2308	btor(ZR36057_JPC_Active, ZR36057_JPC);	// /Active
2309	btor(ZR36057_JMC_Go_en, ZR36057_JMC);	// /Go_en
2310	udelay(30);
2311	set_frame(zr, 1);	// /FRAME
2312}
2313
2314static void zr36057_enable_jpg(struct zoran *zr,
2315			       enum zoran_codec_mode mode)
2316{
2317	static int zero = 0;
2318	static int one = 1;
2319
2320	zr->codec_mode = mode;
2321	switch (mode) {
2322
2323	case BUZ_MODE_MOTION_COMPRESS:
2324		set_videobus_enable(zr, 0);
2325		set_videobus_dir(zr, 0);	// GPIO(zr, 1, 0);
2326		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
2327				   DECODER_ENABLE_OUTPUT, &one);
2328		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEOENCODER,
2329				   ENCODER_SET_INPUT, &zero);
2330		set_videobus_enable(zr, 1);
2331		zr36060_sleep(zr, 0);
2332		zr36060_set_cap(zr, mode);	// Load ZR36060
2333		init_jpeg_queue(zr);
2334		zr36057_set_jpg(zr, mode);	// \P_Reset, ... Video param, FIFO
2335
2336		clear_interrupt_counters(zr);
2337		DEBUG1(printk
2338		       (KERN_INFO "%s: enable_jpg MOTION_COMPRESS\n",
2339			zr->name));
2340		break;
2341
2342	case BUZ_MODE_MOTION_DECOMPRESS:
2343		set_videobus_enable(zr, 0);
2344		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
2345				   DECODER_ENABLE_OUTPUT, &zero);
2346		set_videobus_dir(zr, 1);	// GPIO(zr, 1, 1);
2347		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEOENCODER,
2348				   ENCODER_SET_INPUT, &one);
2349		set_videobus_enable(zr, 1);
2350		zr36060_sleep(zr, 0);
2351		zr36060_set_cap(zr, mode);	// Load ZR36060
2352		init_jpeg_queue(zr);
2353		zr36057_set_jpg(zr, mode);	// \P_Reset, ... Video param, FIFO
2354
2355		clear_interrupt_counters(zr);
2356		DEBUG1(printk
2357		       (KERN_INFO "%s: enable_jpg MOTION_DECOMPRESS\n",
2358			zr->name));
2359		break;
2360
2361	case BUZ_MODE_IDLE:
2362	default:
2363		/* shut down processing */
2364		btand(~(cardjpegint[zr->card] | ZR36057_ICR_JPEGRepIRQ),
2365		      ZR36057_ICR);
2366		btwrite(cardjpegint[zr->card] | ZR36057_ICR_JPEGRepIRQ,
2367			ZR36057_ISR);
2368		btand(~ZR36057_JMC_Go_en, ZR36057_JMC);	// \Go_en
2369
2370		set_current_state(TASK_UNINTERRUPTIBLE);
2371		schedule_timeout(HZ/20);
2372
2373		set_videobus_dir(zr, 0);	// GPIO(zr, 1, 0);
2374		set_frame(zr, 1);	//GPIO(zr, 6, 1);     // /FRAME
2375		btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR);	// /CFlush
2376		btwrite(0, ZR36057_JPC);	// \P_Reset,\CodTrnsEn,\Active
2377		btand(~ZR36057_JMC_VFIFO_FB, ZR36057_JMC);
2378		btand(~ZR36057_JMC_SyncMstr, ZR36057_JMC);
2379		zr36060_reset(zr);
2380		zr36060_sleep(zr, 1);
2381		zr36057_adjust_vfe(zr, mode);
2382		set_videobus_enable(zr, 0);
2383		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
2384				   DECODER_ENABLE_OUTPUT, &one);
2385		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEOENCODER,
2386				   ENCODER_SET_INPUT, &zero);
2387		set_videobus_enable(zr, 1);
2388		DEBUG1(printk
2389		       (KERN_INFO "%s: enable_jpg IDLE\n", zr->name));
2390		break;
2391
2392	}
2393}
2394
2395/*
2396 *   Queue a MJPEG buffer for capture/playback
2397 */
2398
2399static int jpg_qbuf(struct zoran *zr, int frame,
2400		    enum zoran_codec_mode mode)
2401{
2402	unsigned long flags;
2403	int res;
2404
2405	/* Check if buffers are allocated */
2406
2407	if (!zr->jpg_buffers_allocated) {
2408		printk(KERN_ERR
2409		       "%s: jpg_qbuf: buffers not yet allocated\n",
2410		       zr->name);
2411		return -ENOMEM;
2412	}
2413
2414	/* Does the user want to stop streaming? */
2415
2416	if (frame < 0) {
2417		if (zr->codec_mode == mode) {
2418			zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
2419			return 0;
2420		} else {
2421			printk(KERN_ERR
2422			       "%s: jpg_qbuf - stop streaming but not in streaming mode\n",
2423			       zr->name);
2424			return -EINVAL;
2425		}
2426	}
2427
2428	/* No grabbing outside the buffer range! */
2429
2430	if (frame >= zr->jpg_nbufs) {
2431		printk(KERN_ERR "%s: jpg_qbuf: buffer %d out of range\n",
2432		       zr->name, frame);
2433		return -EINVAL;
2434	}
2435
2436	/* what is the codec mode right now? */
2437
2438	if (zr->codec_mode == BUZ_MODE_IDLE) {
2439		/* Ok load up the zr36060 */
2440		zr36057_enable_jpg(zr, mode);
2441	} else if (zr->codec_mode != mode) {
2442		/* wrong codec mode active - invalid */
2443		printk(KERN_ERR "%s: jpg_qbuf - codec in wrong mode\n",
2444		       zr->name);
2445		return -EINVAL;
2446	}
2447
2448	spin_lock_irqsave(&zr->lock, flags);
2449
2450	/* make sure a grab isn't going on currently with this buffer */
2451
2452	switch (zr->jpg_gbuf[frame].state) {
2453
2454	case BUZ_STATE_DONE:
2455		DEBUG1(printk
2456		       (KERN_WARNING
2457			"%s: Warning: queing frame in BUZ_STATE_DONE state\n",
2458			zr->name));
2459	case BUZ_STATE_USER:
2460		/* since there is at least one unused buffer there's room for at least one more pend[] entry */
2461		zr->jpg_pend[zr->jpg_que_head++ & BUZ_MASK_FRAME] = frame;
2462		zr->jpg_gbuf[frame].state = BUZ_STATE_PEND;
2463		zoran_feed_stat_com(zr);
2464		res = 0;
2465		break;
2466
2467	default:
2468	case BUZ_STATE_DMA:
2469	case BUZ_STATE_PEND:
2470		res = -EBUSY;	/* what are you doing? */
2471		break;
2472
2473	}
2474
2475	spin_unlock_irqrestore(&zr->lock, flags);
2476
2477	/* Start the zr36060 when the first frame is queued  */
2478	if (zr->jpg_que_head == 1)
2479		jpeg_start(zr);
2480
2481	return res;
2482}
2483
2484/*
2485 *   Sync on a MJPEG buffer
2486 */
2487
2488static int jpg_sync(struct zoran *zr, struct zoran_sync *bs)
2489{
2490	unsigned long flags;
2491	int frame, timeout;
2492
2493	if (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS
2494	    && zr->codec_mode != BUZ_MODE_MOTION_COMPRESS) {
2495		DEBUG1(printk(KERN_ERR
2496		       "%s: BUZIOCSYNC: - codec not in streaming mode\n",
2497		       zr->name));
2498		return -EINVAL;
2499	}
2500	while (zr->jpg_que_tail == zr->jpg_dma_tail) {
2501		if (zr->jpg_dma_tail == zr->jpg_dma_head)
2502			break;
2503		timeout =
2504		    interruptible_sleep_on_timeout(&zr->jpg_capq, 10 * HZ);
2505		if (!timeout) {
2506			btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
2507			udelay(1);
2508			printk(KERN_ERR
2509			       "%s: timeout: codec isr=0x%02x, csr=0x%02x\n",
2510			       zr->name, zr36060_read_8(zr, 0x008),
2511			       zr36060_read_8(zr, 0x001));
2512			return -ETIME;
2513		} else if (signal_pending(current))
2514			return -ERESTARTSYS;
2515	}
2516
2517	spin_lock_irqsave(&zr->lock, flags);
2518
2519	if (zr->jpg_dma_tail != zr->jpg_dma_head)
2520		frame = zr->jpg_pend[zr->jpg_que_tail++ & BUZ_MASK_FRAME];
2521	else
2522		frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
2523	/* buffer should now be in BUZ_STATE_DONE */
2524
2525#if(DEBUGLEVEL > 0)
2526	if (zr->jpg_gbuf[frame].state != BUZ_STATE_DONE)
2527		printk(KERN_ERR "%s: jpg_sync - internal error\n",
2528		       zr->name);
2529#endif
2530
2531	*bs = zr->jpg_gbuf[frame].bs;
2532	zr->jpg_gbuf[frame].state = BUZ_STATE_USER;
2533
2534	spin_unlock_irqrestore(&zr->lock, flags);
2535
2536	return 0;
2537}
2538
2539/* when this is called the spinlock must be held */
2540static void zoran_feed_stat_com(struct zoran *zr)
2541{
2542	/* move frames from pending queue to DMA */
2543
2544	int frame, i, max_stat_com;
2545
2546	max_stat_com =
2547	    (zr->params.TmpDcm ==
2548	     1) ? BUZ_NUM_STAT_COM : (BUZ_NUM_STAT_COM >> 1);
2549
2550	while ((zr->jpg_dma_head - zr->jpg_dma_tail) < max_stat_com
2551	       && zr->jpg_dma_head < zr->jpg_que_head) {
2552
2553		frame = zr->jpg_pend[zr->jpg_dma_head & BUZ_MASK_FRAME];
2554		if (zr->params.TmpDcm == 1) {
2555			/* fill 1 stat_com entry */
2556			i = (zr->jpg_dma_head -
2557			     zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
2558			if (!(zr->stat_com[i] & 1))
2559				break;
2560			zr->stat_com[i] = zr->jpg_gbuf[frame].frag_tab_bus;
2561		} else {
2562			/* fill 2 stat_com entries */
2563			i = ((zr->jpg_dma_head -
2564			      zr->jpg_err_shift) & 1) * 2;
2565			if (!(zr->stat_com[i] & 1))
2566				break;
2567			zr->stat_com[i] = zr->jpg_gbuf[frame].frag_tab_bus;
2568			zr->stat_com[i + 1] =
2569			    zr->jpg_gbuf[frame].frag_tab_bus;
2570		}
2571		zr->jpg_gbuf[frame].state = BUZ_STATE_DMA;
2572		zr->jpg_dma_head++;
2573
2574	}
2575	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS)
2576		zr->jpg_queued_num++;
2577}
2578
2579/* when this is called the spinlock must be held */
2580static void zoran_reap_stat_com(struct zoran *zr)
2581{
2582	/* move frames from DMA queue to done queue */
2583
2584	int i;
2585	u32 stat_com;
2586	unsigned int seq;
2587	unsigned int dif;
2588	int frame;
2589	struct zoran_gbuffer *gbuf;
2590
2591	/* In motion decompress we don't have a hardware frame counter,
2592	   we just count the interrupts here */
2593
2594	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
2595		zr->jpg_seq_num++;
2596	}
2597	while (zr->jpg_dma_tail < zr->jpg_dma_head) {
2598		if (zr->params.TmpDcm == 1)
2599			i = (zr->jpg_dma_tail -
2600			     zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
2601		else
2602			i = ((zr->jpg_dma_tail -
2603			      zr->jpg_err_shift) & 1) * 2 + 1;
2604
2605		stat_com = zr->stat_com[i];
2606
2607		if ((stat_com & 1) == 0) {
2608			return;
2609		}
2610		frame = zr->jpg_pend[zr->jpg_dma_tail & BUZ_MASK_FRAME];
2611		gbuf = &zr->jpg_gbuf[frame];
2612		do_gettimeofday(&gbuf->bs.timestamp);
2613
2614		if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
2615			gbuf->bs.length = (stat_com & 0x7fffff) >> 1;
2616
2617			/* update sequence number with the help of the counter in stat_com */
2618
2619			seq = ((stat_com >> 24) + zr->jpg_err_seq) & 0xff;
2620			dif = (seq - zr->jpg_seq_num) & 0xff;
2621			zr->jpg_seq_num += dif;
2622		} else {
2623			gbuf->bs.length = 0;
2624		}
2625		gbuf->bs.seq =
2626		    zr->params.TmpDcm ==
2627		    2 ? (zr->jpg_seq_num >> 1) : zr->jpg_seq_num;
2628		gbuf->state = BUZ_STATE_DONE;
2629
2630		zr->jpg_dma_tail++;
2631	}
2632}
2633
2634static void error_handler(struct zoran *zr, u32 astat, u32 stat)
2635{
2636	/* This is JPEG error handling part */
2637	if ((zr->codec_mode != BUZ_MODE_MOTION_COMPRESS)
2638	    && (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS)) {
2639		//printk(KERN_ERR "%s: Internal error: error handling request in mode %d\n", zr->name, zr->codec_mode);
2640		return;
2641	}
2642	if ((stat & 1) == 0
2643	    && zr->codec_mode == BUZ_MODE_MOTION_COMPRESS
2644	    && zr->jpg_dma_tail - zr->jpg_que_tail >= zr->jpg_nbufs) {
2645		/* No free buffers... */
2646		zoran_reap_stat_com(zr);
2647		zoran_feed_stat_com(zr);
2648		wake_up_interruptible(&zr->jpg_capq);
2649		zr->JPEG_missed = 0;
2650		return;
2651	}
2652	if (zr->JPEG_error != 1) {
2653		/*
2654		 * First entry: error just happened during normal operation
2655		 *
2656		 * In BUZ_MODE_MOTION_COMPRESS:
2657		 *
2658		 * Possible glitch in TV signal. In this case we should
2659		 * stop the codec and wait for good quality signal before
2660		 * restarting it to avoid further problems
2661		 *
2662		 * In BUZ_MODE_MOTION_DECOMPRESS:
2663		 *
2664		 * Bad JPEG frame: we have to mark it as processed (codec crashed
2665		 * and was not able to do it itself), and to remove it from queue.
2666		 */
2667		btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
2668		udelay(1);
2669		stat =
2670		    stat | (post_office_read(zr, 7, 0) & 3) << 8 |
2671		    zr36060_read_8(zr, 0x008);
2672		btwrite(0, ZR36057_JPC);
2673		btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR);
2674		zr36060_reset(zr);
2675		zr36060_sleep(zr, 1);
2676		zr->JPEG_error = 1;
2677		zr->num_errors++;
2678		/* Report error */
2679#if(DEBUGLEVEL > 1)
2680		if (zr->num_errors <= 8) {
2681			long frame;
2682			frame =
2683			    zr->jpg_pend[zr->
2684					 jpg_dma_tail & BUZ_MASK_FRAME];
2685			printk(KERN_ERR
2686			       "%s: JPEG error stat=0x%08x(0x%08x) queue_state=%ld/%ld/%ld/%ld seq=%ld frame=%ld. Codec stopped. ",
2687			       zr->name, stat, zr->last_isr,
2688			       zr->jpg_que_tail, zr->jpg_dma_tail,
2689			       zr->jpg_dma_head, zr->jpg_que_head,
2690			       zr->jpg_seq_num, frame);
2691			printk("stat_com frames:");
2692			{
2693				int i, j;
2694				for (j = 0; j < BUZ_NUM_STAT_COM; j++) {
2695					for (i = 0; i < zr->jpg_nbufs; i++) {
2696						if (zr->stat_com[j] ==
2697						    zr->jpg_gbuf[i].
2698						    frag_tab_bus) {
2699							printk("% d->%d",
2700							       j, i);
2701						}
2702					}
2703				}
2704				printk("\n");
2705			}
2706		}
2707#endif
2708		/* Find an entry in stat_com and rotate contents */
2709		{
2710			int i;
2711
2712			if (zr->params.TmpDcm == 1)
2713				i = (zr->jpg_dma_tail -
2714				     zr->
2715				     jpg_err_shift) & BUZ_MASK_STAT_COM;
2716			else
2717				i = ((zr->jpg_dma_tail -
2718				      zr->jpg_err_shift) & 1) * 2;
2719			if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
2720				/* Mimic zr36067 operation */
2721				zr->stat_com[i] |= 1;
2722				if (zr->params.TmpDcm != 1)
2723					zr->stat_com[i + 1] |= 1;
2724				/* Refill */
2725				zoran_reap_stat_com(zr);
2726				zoran_feed_stat_com(zr);
2727				wake_up_interruptible(&zr->jpg_capq);
2728				/* Find an entry in stat_com again after refill */
2729				if (zr->params.TmpDcm == 1)
2730					i = (zr->jpg_dma_tail -
2731					     zr->
2732					     jpg_err_shift) &
2733					    BUZ_MASK_STAT_COM;
2734				else
2735					i = ((zr->jpg_dma_tail -
2736					      zr->jpg_err_shift) & 1) * 2;
2737			}
2738			if (i) {
2739				/* Rotate stat_comm entries to make current entry first */
2740				int j;
2741				u32 bus_addr[BUZ_NUM_STAT_COM];
2742
2743				memcpy(bus_addr, zr->stat_com,
2744				       sizeof(bus_addr));
2745				for (j = 0; j < BUZ_NUM_STAT_COM; j++) {
2746					zr->stat_com[j] =
2747					    bus_addr[(i +
2748						      j) &
2749						     BUZ_MASK_STAT_COM];
2750				}
2751				zr->jpg_err_shift += i;
2752				zr->jpg_err_shift &= BUZ_MASK_STAT_COM;
2753			}
2754			if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)
2755				zr->jpg_err_seq = zr->jpg_seq_num;	/* + 1; */
2756		}
2757	}
2758	/* Now the stat_comm buffer is ready for restart */
2759	{
2760		int status;
2761
2762		status = 0;
2763		if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)
2764			i2c_control_device(&zr->i2c,
2765					   I2C_DRIVERID_VIDEODECODER,
2766					   DECODER_GET_STATUS, &status);
2767		if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS
2768		    || (status & DECODER_STATUS_GOOD)) {
2769	    /********** RESTART code *************/
2770			zr36060_reset(zr);
2771			zr36060_set_cap(zr, zr->codec_mode);
2772			zr36057_set_jpg(zr, zr->codec_mode);
2773			jpeg_start(zr);
2774#if(DEBUGLEVEL > 1)
2775			if (zr->num_errors <= 8)
2776				printk(KERN_INFO "%s: Restart\n",
2777				       zr->name);
2778#endif
2779			zr->JPEG_missed = 0;
2780			zr->JPEG_error = 2;
2781	    /********** End RESTART code ***********/
2782		}
2783	}
2784}
2785
2786static void zoran_irq(int irq, void *dev_id, struct pt_regs *regs)
2787{
2788	u32 stat, astat;
2789	int count;
2790	struct zoran *zr;
2791	unsigned long flags;
2792
2793	zr = (struct zoran *) dev_id;
2794	count = 0;
2795
2796	if (zr->testing) {
2797		/* Testing interrupts */
2798		spin_lock_irqsave(&zr->lock, flags);
2799		while ((stat = count_reset_interrupt(zr))) {
2800			if (count++ > 100) {
2801				btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
2802				printk(KERN_ERR
2803				       "%s: IRQ lockup while testing, isr=0x%08x, cleared int mask\n",
2804				       zr->name, stat);
2805				wake_up_interruptible(&zr->test_q);
2806			}
2807		}
2808		zr->last_isr = stat;
2809		spin_unlock_irqrestore(&zr->lock, flags);
2810		return;
2811	}
2812
2813	spin_lock_irqsave(&zr->lock, flags);
2814	while (1) {
2815		/* get/clear interrupt status bits */
2816		stat = count_reset_interrupt(zr);
2817		astat = stat & IRQ_MASK;
2818		if (!astat) {
2819			break;
2820		}
2821		if (astat & cardvsync[zr->card]) {	// SW
2822
2823			if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS
2824			    || zr->codec_mode ==
2825			    BUZ_MODE_MOTION_COMPRESS) {
2826				/* count missed interrupts */
2827				zr->JPEG_missed++;
2828			}
2829			//post_office_read(zr,1,0);
2830			/* Interrupts may still happen when zr->v4l_memgrab_active is switched off.
2831			   We simply ignore them */
2832
2833			if (zr->v4l_memgrab_active) {
2834
2835				/* A lot more checks should be here ... */
2836				if ((btread(ZR36057_VSSFGR) &
2837				     ZR36057_VSSFGR_SnapShot) == 0)
2838					printk(KERN_WARNING
2839					       "%s: BuzIRQ with SnapShot off ???\n",
2840					       zr->name);
2841
2842				if (zr->v4l_grab_frame != NO_GRAB_ACTIVE) {
2843					/* There is a grab on a frame going on, check if it has finished */
2844
2845					if ((btread(ZR36057_VSSFGR) &
2846					     ZR36057_VSSFGR_FrameGrab) ==
2847					    0) {
2848						/* it is finished, notify the user */
2849
2850						zr->v4l_gbuf[zr->
2851							     v4l_grab_frame].
2852						    state = BUZ_STATE_DONE;
2853						zr->v4l_grab_frame =
2854						    NO_GRAB_ACTIVE;
2855						zr->v4l_grab_seq++;
2856						zr->v4l_pend_tail++;
2857					}
2858				}
2859
2860				if (zr->v4l_grab_frame == NO_GRAB_ACTIVE)
2861					wake_up_interruptible(&zr->
2862							      v4l_capq);
2863
2864				/* Check if there is another grab queued */
2865
2866				if (zr->v4l_grab_frame == NO_GRAB_ACTIVE
2867				    && zr->v4l_pend_tail !=
2868				    zr->v4l_pend_head) {
2869
2870					int frame =
2871					    zr->v4l_pend[zr->
2872							 v4l_pend_tail &
2873							 V4L_MASK_FRAME];
2874					u32 reg;
2875
2876					zr->v4l_grab_frame = frame;
2877
2878					/* Set zr36057 video front end and enable video */
2879
2880					/* Buffer address */
2881
2882					reg =
2883					    zr->v4l_gbuf[frame].
2884					    fbuffer_bus;
2885					btwrite(reg, ZR36057_VDTR);
2886					if (zr->video_interlace)
2887						reg += zr->gbpl;
2888					btwrite(reg, ZR36057_VDBR);
2889
2890					/* video stride, status, and frame grab register */
2891
2892					reg = 0;
2893					if (zr->video_interlace)
2894						reg += zr->gbpl;
2895					reg =
2896					    (reg <<
2897					     ZR36057_VSSFGR_DispStride);
2898					reg |= ZR36057_VSSFGR_VidOvf;
2899					reg |= ZR36057_VSSFGR_SnapShot;
2900					reg |= ZR36057_VSSFGR_FrameGrab;
2901					btwrite(reg, ZR36057_VSSFGR);
2902
2903					btor(ZR36057_VDCR_VidEn,
2904					     ZR36057_VDCR);
2905				}
2906			}
2907		}
2908#if (IRQ_MASK & ZR36057_ISR_CodRepIRQ)
2909		if (astat & ZR36057_ISR_CodRepIRQ) {
2910			zr->intr_counter_CodRepIRQ++;
2911			IDEBUG(printk
2912			       (KERN_DEBUG "%s: ZR36057_ISR_CodRepIRQ\n",
2913				zr->name));
2914			btand(~ZR36057_ICR_CodRepIRQ, ZR36057_ICR);
2915		}
2916#endif				/* (IRQ_MASK & ZR36057_ISR_CodRepIRQ) */
2917
2918#if (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ)
2919		if (astat & ZR36057_ISR_JPEGRepIRQ) {
2920
2921			if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS
2922			    || zr->codec_mode ==
2923			    BUZ_MODE_MOTION_COMPRESS) {
2924#if(DEBUGLEVEL > 1)
2925				if (!zr->frame_num || zr->JPEG_error) {
2926					printk(KERN_INFO
2927					       "%s: first frame ready: state=0x%08x odd_even=%d field_per_buff=%d delay=%d\n",
2928					       zr->name, stat,
2929					       zr->params.odd_even,
2930					       zr->params.field_per_buff,
2931					       zr->JPEG_missed);
2932					{
2933						char sc[] = "0000";
2934						char sv[5];
2935						int i;
2936						strcpy(sv, sc);
2937						for (i = 0; i < 4; i++) {
2938							if (zr->
2939							    stat_com[i] &
2940							    1)
2941								sv[i] =
2942								    '1';
2943						}
2944						sv[4] = 0;
2945						printk(KERN_INFO
2946						       "%s: stat_com=%s queue_state=%ld/%ld/%ld/%ld\n",
2947						       zr->name, sv,
2948						       zr->jpg_que_tail,
2949						       zr->jpg_dma_tail,
2950						       zr->jpg_dma_head,
2951						       zr->jpg_que_head);
2952					}
2953				} else {
2954					if (zr->JPEG_missed > zr->JPEG_max_missed)	// Get statistics
2955						zr->JPEG_max_missed =
2956						    zr->JPEG_missed;
2957					if (zr->JPEG_missed <
2958					    zr->JPEG_min_missed)
2959						zr->JPEG_min_missed =
2960						    zr->JPEG_missed;
2961				}
2962#endif
2963#if(DEBUGLEVEL > 2)
2964				if (zr->frame_num < 6) {
2965					int i;
2966					printk("%s: seq=%ld stat_com:",
2967					       zr->name, zr->jpg_seq_num);
2968					for (i = 0; i < 4; i++) {
2969						printk(" %08x",
2970						       zr->stat_com[i]);
2971					}
2972					printk("\n");
2973				}
2974#endif
2975				zr->frame_num++;
2976				zr->JPEG_missed = 0;
2977				zr->JPEG_error = 0;
2978				zoran_reap_stat_com(zr);
2979				zoran_feed_stat_com(zr);
2980				wake_up_interruptible(&zr->jpg_capq);
2981			}	//else {
2982			//      printk(KERN_ERR "%s: JPEG interrupt while not in motion (de)compress mode!\n", zr->name);
2983			//}
2984		}
2985#endif				/* (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ) */
2986
2987		if ((astat & cardjpegint[zr->card])	/* DATERR interrupt received                 */
2988		    ||zr->JPEG_missed > 25	/* Too many fields missed without processing */
2989		    || zr->JPEG_error == 1	/* We are already in error processing        */
2990		    || ((zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS)
2991			&& (zr->
2992			    frame_num & (zr->JPEG_missed >
2993					 zr->params.field_per_buff)))
2994		    /* fields missed during decompression */
2995		    ) {
2996			error_handler(zr, astat, stat);
2997		}
2998
2999		count++;
3000		if (count > 10) {
3001			printk(KERN_WARNING "%s: irq loop %d\n", zr->name,
3002			       count);
3003			if (count > 20) {
3004				btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
3005				printk(KERN_ERR
3006				       "%s: IRQ lockup, cleared int mask\n",
3007				       zr->name);
3008				break;
3009			}
3010		}
3011		zr->last_isr = stat;
3012	}
3013	spin_unlock_irqrestore(&zr->lock, flags);
3014}
3015
3016/* Check a zoran_params struct for correctness, insert default params */
3017
3018static int zoran_check_params(struct zoran *zr,
3019			      struct zoran_params *params)
3020{
3021	int err = 0, err0 = 0;
3022
3023	/* insert constant params */
3024
3025	params->major_version = MAJOR_VERSION;
3026	params->minor_version = MINOR_VERSION;
3027
3028	/* Check input and norm: must be set by calling VIDIOCSCHAN only! */
3029
3030	params->norm = zr->params.norm;
3031	params->input = zr->params.input;
3032
3033	/* Check decimation, set default values for decimation = 1, 2, 4 */
3034
3035	switch (params->decimation) {
3036	case 1:
3037
3038		params->HorDcm = 1;
3039		params->VerDcm = 1;
3040		params->TmpDcm = 1;
3041		params->field_per_buff = 2;
3042
3043		params->img_x = 0;
3044		params->img_y = 0;
3045		params->img_width = zr->timing->Wa;
3046		params->img_height = zr->timing->Ha / 2;
3047		break;
3048
3049	case 2:
3050
3051		params->HorDcm = 2;
3052		params->VerDcm = 1;
3053		params->TmpDcm = 2;
3054		params->field_per_buff = 1;
3055
3056		params->img_x = 8;
3057		params->img_y = 0;
3058		params->img_width = zr->timing->Wa;
3059		params->img_height = zr->timing->Ha / 2;
3060		break;
3061
3062	case 4:
3063
3064		params->HorDcm = 4;
3065		params->VerDcm = 2;
3066		params->TmpDcm = 2;
3067		params->field_per_buff = 1;
3068
3069		params->img_x = 8;
3070		params->img_y = 0;
3071		params->img_width = zr->timing->Wa;
3072		params->img_height = zr->timing->Ha / 2;
3073		break;
3074
3075	case 0:
3076
3077		/* We have to check the data the user has set */
3078
3079		if (params->HorDcm != 1 && params->HorDcm != 2
3080		    && params->HorDcm != 4)
3081			err0++;
3082		if (params->VerDcm != 1 && params->VerDcm != 2)
3083			err0++;
3084		if (params->TmpDcm != 1 && params->TmpDcm != 2)
3085			err0++;
3086		if (params->field_per_buff != 1
3087		    && params->field_per_buff != 2)
3088			err0++;
3089
3090		if (params->img_x < 0)
3091			err0++;
3092		if (params->img_y < 0)
3093			err0++;
3094		if (params->img_width < 0)
3095			err0++;
3096		if (params->img_height < 0)
3097			err0++;
3098		if (params->img_x + params->img_width > zr->timing->Wa)
3099			err0++;
3100		if (params->img_y + params->img_height >
3101		    zr->timing->Ha / 2)
3102			err0++;
3103		if (params->HorDcm) {
3104			if (params->img_width % (16 * params->HorDcm) != 0)
3105				err0++;
3106			if (params->img_height % (8 * params->VerDcm) != 0)
3107				err0++;
3108		}
3109
3110		if (err0) {
3111			DEBUG1(printk(KERN_ERR
3112			       "%s: SET PARAMS: error in params for decimation = 0\n",
3113			       zr->name));
3114			err++;
3115		}
3116		break;
3117
3118	default:
3119		DEBUG1(printk(KERN_ERR
3120		       "%s: SET PARAMS: decimation = %d, must be 0, 1, 2 or 4\n",
3121		       zr->name, params->decimation));
3122		err++;
3123		break;
3124	}
3125
3126	if (params->quality > 100)
3127		params->quality = 100;
3128	if (params->quality < 5)
3129		params->quality = 5;
3130
3131	if (params->APPn < 0)
3132		params->APPn = 0;
3133	if (params->APPn > 15)
3134		params->APPn = 15;
3135	if (params->APP_len < 0)
3136		params->APP_len = 0;
3137	if (params->APP_len > 60)
3138		params->APP_len = 60;
3139	if (params->COM_len < 0)
3140		params->COM_len = 0;
3141	if (params->COM_len > 60)
3142		params->COM_len = 60;
3143
3144	if (err)
3145		return -EINVAL;
3146
3147	return 0;
3148
3149}
3150static void zoran_open_init_params(struct zoran *zr)
3151{
3152	int i;
3153
3154	/* Per default, map the V4L Buffers */
3155
3156	zr->map_mjpeg_buffers = 0;
3157
3158	/* User must explicitly set a window */
3159
3160	zr->window_set = 0;
3161
3162	zr->window.x = 0;
3163	zr->window.y = 0;
3164	zr->window.width = 0;
3165	zr->window.height = 0;
3166	zr->window.chromakey = 0;
3167	zr->window.flags = 0;
3168	zr->window.clips = NULL;
3169	zr->window.clipcount = 0;
3170
3171	zr->video_interlace = 0;
3172
3173	zr->v4l_memgrab_active = 0;
3174	zr->v4l_overlay_active = 0;
3175
3176	zr->v4l_grab_frame = NO_GRAB_ACTIVE;
3177	zr->v4l_grab_seq = 0;
3178
3179	zr->gwidth = 0;
3180	zr->gheight = 0;
3181	zr->gformat = 0;
3182	zr->gbpl = 0;
3183
3184	/* DMA ring stuff for V4L */
3185
3186	zr->v4l_pend_tail = 0;
3187	zr->v4l_pend_head = 0;
3188	for (i = 0; i < v4l_nbufs; i++) {
3189		zr->v4l_gbuf[i].state = BUZ_STATE_USER;	/* nothing going on */
3190	}
3191
3192	/* Set necessary params and call zoran_check_params to set the defaults */
3193
3194	zr->params.decimation = 1;
3195
3196	zr->params.quality = 50;	/* default compression factor 8 */
3197	if (zr->card != BUZ)
3198		zr->params.odd_even = 1;
3199	else
3200		zr->params.odd_even = 0;
3201
3202	zr->params.APPn = 0;
3203	zr->params.APP_len = 0;	/* No APPn marker */
3204	for (i = 0; i < 60; i++)
3205		zr->params.APP_data[i] = 0;
3206
3207	zr->params.COM_len = 0;	/* No COM marker */
3208	for (i = 0; i < 60; i++)
3209		zr->params.COM_data[i] = 0;
3210
3211	zr->params.VFIFO_FB = 0;
3212
3213	memset(zr->params.reserved, 0, sizeof(zr->params.reserved));
3214
3215	zr->params.jpeg_markers = JPEG_MARKER_DHT | JPEG_MARKER_DQT;
3216
3217	i = zoran_check_params(zr, &zr->params);
3218	if (i)
3219		printk(KERN_ERR
3220		       "%s: zoran_open_init_params internal error\n",
3221		       zr->name);
3222
3223	clear_interrupt_counters(zr);
3224	zr->testing = 0;
3225}
3226
3227/*
3228 *   Open a zoran card. Right now the flags stuff is just playing
3229 */
3230
3231static int zoran_open(struct video_device *dev, int flags)
3232{
3233	struct zoran *zr = (struct zoran *) dev;
3234	//int one = 1;
3235
3236	DEBUG1(printk
3237	       (KERN_INFO "%s: zoran_open, %s pid=[%d]\n", zr->name,
3238		current->comm, current->pid));
3239
3240	switch (flags) {
3241
3242	case 0:
3243		if (zr->user > 1) {
3244			DEBUG1(printk(KERN_WARNING
3245			       "%s: zoran_open: Buz is allready in use\n",
3246			       zr->name));
3247			return -EBUSY;
3248		}
3249		zr->user++;
3250
3251		if (zr->user == 1 && v4l_fbuffer_alloc(zr) < 0) {
3252			zr->user--;
3253			printk(KERN_ERR
3254			       "%s: zoran_open: v4l_fbuffer_alloc failed\n",
3255			       zr->name);
3256			return -ENOMEM;
3257		}
3258
3259		/* default setup */
3260
3261		if (zr->user == 1) {	/* First device open */
3262			zoran_open_init_params(zr);
3263
3264			zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
3265
3266			btwrite(IRQ_MASK, ZR36057_ISR);	// Clears interrupts
3267			btor(ZR36057_ICR_IntPinEn, ZR36057_ICR);
3268			dev->users--;	/* Allow second open */
3269		}
3270
3271		break;
3272
3273	default:
3274		DEBUG1(printk(KERN_WARNING
3275		       "%s: zoran_open: flags = 0x%x not yet supported\n",
3276		       zr->name, flags));
3277		return -EBUSY;
3278		break;
3279
3280	}
3281	MOD_INC_USE_COUNT;
3282	return 0;
3283}
3284
3285static void zoran_close(struct video_device *dev)
3286{
3287	struct zoran *zr = (struct zoran *) dev;
3288	int zero = 0, two = 2;
3289
3290	DEBUG1(printk
3291	       (KERN_INFO "%s: zoran_close, %s pid=[%d]\n", zr->name,
3292		current->comm, current->pid));
3293	/* Clean up JPEG process */
3294
3295	wake_up_interruptible(&zr->jpg_capq);
3296	zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
3297	jpg_fbuffer_free(zr);
3298	zr->jpg_nbufs = 0;
3299
3300	if (zr->user == 1) {	/* Last process */
3301		/* disable interrupts */
3302		btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
3303
3304#if(DEBUGLEVEL > 1)
3305		print_interrupts(zr);
3306#endif
3307		/* Overlay off */
3308		wake_up_interruptible(&zr->v4l_capq);
3309		zr36057_set_memgrab(zr, 0);
3310		if (zr->v4l_overlay_active)
3311			zr36057_overlay(zr, 0);
3312		v4l_fbuffer_free(zr);
3313
3314		if (!pass_through) {	/* Switch to color bar */
3315			set_videobus_enable(zr, 0);
3316			i2c_control_device(&zr->i2c,
3317					   I2C_DRIVERID_VIDEODECODER,
3318					   DECODER_ENABLE_OUTPUT, &zero);
3319			i2c_control_device(&zr->i2c,
3320					   I2C_DRIVERID_VIDEOENCODER,
3321					   ENCODER_SET_INPUT, &two);
3322			set_videobus_enable(zr, 1);
3323		}
3324	}
3325
3326	dev->users++;
3327	zr->user--;
3328
3329	MOD_DEC_USE_COUNT;
3330	DEBUG2(printk(KERN_INFO "%s: zoran_close done\n", zr->name));
3331}
3332
3333
3334static long zoran_read(struct video_device *dev, char *buf,
3335		       unsigned long count, int nonblock)
3336{
3337	return -EINVAL;
3338}
3339
3340static long zoran_write(struct video_device *dev, const char *buf,
3341			unsigned long count, int nonblock)
3342{
3343	return -EINVAL;
3344}
3345
3346/*
3347 *   ioctl routine
3348 */
3349
3350static int do_zoran_ioctl(struct zoran *zr, unsigned int cmd,
3351		       void *arg)
3352{
3353	switch (cmd) {
3354
3355	case VIDIOCGCAP:
3356		{
3357			struct video_capability b;
3358			DEBUG2(printk("%s: ioctl VIDIOCGCAP\n", zr->name));
3359
3360			strncpy(b.name, zr->video_dev.name,
3361				sizeof(b.name));
3362			b.type =
3363			    VID_TYPE_CAPTURE | VID_TYPE_OVERLAY |
3364			    VID_TYPE_CLIPPING | VID_TYPE_FRAMERAM |
3365			    VID_TYPE_SCALES;
3366			/* theoretically we could also flag VID_TYPE_SUBCAPTURE
3367			   but this is not even implemented in the BTTV driver */
3368
3369			if (zr->card == DC10 || zr->card == DC10plus) {
3370				b.channels = 3;	/* composite, svhs, internal */
3371			} else {
3372				b.channels = 2;	/* composite, svhs */
3373			}
3374			b.audios = 0;
3375			b.maxwidth = BUZ_MAX_WIDTH;
3376			b.maxheight = BUZ_MAX_HEIGHT;
3377			b.minwidth = BUZ_MIN_WIDTH;
3378			b.minheight = BUZ_MIN_HEIGHT;
3379			if (copy_to_user(arg, &b, sizeof(b))) {
3380				return -EFAULT;
3381			}
3382			return 0;
3383		}
3384		break;
3385
3386	case VIDIOCGCHAN:
3387		{
3388			struct video_channel v;
3389
3390			if (copy_from_user(&v, arg, sizeof(v))) {
3391				return -EFAULT;
3392			}
3393			DEBUG2(printk
3394			       ("%s: ioctl VIDIOCGCHAN for channel %d\n",
3395				zr->name, v.channel));
3396			switch (v.channel) {
3397			case 0:
3398				strcpy(v.name, "Composite");
3399				break;
3400			case 1:
3401				strcpy(v.name, "SVHS");
3402				break;
3403			case 2:
3404				if (zr->card == DC10
3405				    || zr->card == DC10plus) {
3406					strcpy(v.name, "Internal/comp");
3407					break;
3408				}
3409			default:
3410				DEBUG1(printk(KERN_ERR
3411				       "%s: VIDIOCGCHAN on not existing channel %d\n",
3412				       zr->name, v.channel));
3413				return -EINVAL;
3414			}
3415			v.tuners = 0;
3416			v.flags = 0;
3417			v.type = VIDEO_TYPE_CAMERA;
3418			v.norm = zr->params.norm;
3419			if (copy_to_user(arg, &v, sizeof(v))) {
3420				return -EFAULT;
3421			}
3422			return 0;
3423		}
3424		break;
3425
3426		/* RJ: the documentation at http://roadrunner.swansea.linux.org.uk/v4lapi.shtml says:
3427
3428		 * "The VIDIOCSCHAN ioctl takes an integer argument and switches the capture to this input."
3429		 *                                 ^^^^^^^
3430		 * The famos BTTV driver has it implemented with a struct video_channel argument
3431		 * and we follow it for compatibility reasons
3432		 *
3433		 * BTW: this is the only way the user can set the norm!
3434		 */
3435
3436	case VIDIOCSCHAN:
3437		{
3438			struct video_channel v;
3439			int input;
3440			int on, res;
3441			int encoder_norm;
3442
3443			if (copy_from_user(&v, arg, sizeof(v))) {
3444				return -EFAULT;
3445			}
3446
3447			if (zr->codec_mode != BUZ_MODE_IDLE) {
3448				if (v.norm != zr->params.norm
3449				    || v.channel != zr->params.input) {
3450					DEBUG1(printk(KERN_ERR
3451					       "%s: VIDIOCSCHAN called while the card in capture/playback mode\n",
3452					       zr->name));
3453					return -EINVAL;
3454				} else {
3455					DEBUG1(printk(BUZ_WARNING
3456					       "%s: Warning: VIDIOCSCHAN called while the card in capture/playback mode\n",
3457					       zr->name));
3458				}
3459			}
3460
3461			DEBUG2(printk
3462			       ("%s: ioctl VIDIOCSCHAN: channel=%d, norm=%d\n",
3463				zr->name, v.channel, v.norm));
3464			switch (v.channel) {
3465			case 0:
3466				if (zr->card == BUZ)
3467					input = 3;
3468				else
3469					input = 0;
3470				break;
3471			case 1:
3472				input = 7;
3473				break;
3474			case 2:
3475				if (zr->card == DC10
3476				    || zr->card == DC10plus) {
3477					input = 5;
3478					break;
3479				}
3480			default:
3481				DEBUG1(printk(KERN_ERR
3482				       "%s: VIDIOCSCHAN on not existing channel %d\n",
3483				       zr->name, v.channel));
3484				return -EINVAL;
3485				break;
3486			}
3487
3488			if (lock_norm && v.norm != zr->params.norm) {
3489				if (lock_norm > 1) {
3490					DEBUG1(printk(KERN_WARNING
3491					       "%s: VIDIOCSCHAN: TV standard is locked, can not switch norm.\n",
3492					       zr->name));
3493					return -EINVAL;
3494				} else {
3495					DEBUG1(printk(KERN_WARNING
3496					       "%s: VIDIOCSCHAN: TV standard is locked, norm was not changed.\n",
3497					       zr->name));
3498					v.norm = zr->params.norm;
3499				}
3500			}
3501
3502			if(v.norm >= 2)
3503				return -EINVAL;
3504
3505			if (!cardnorms[zr->card][v.norm]) {
3506				DEBUG1(printk(KERN_ERR
3507				       "%s: VIDIOCSCHAN with not supported norm %d\n",
3508				       zr->name, v.norm));
3509				return -EOPNOTSUPP;
3510				break;
3511			}
3512			encoder_norm = v.norm;
3513
3514			zr->params.norm = v.norm;
3515			zr->params.input = v.channel;
3516			zr->timing = cardnorms[zr->card][zr->params.norm];
3517
3518			/* We switch overlay off and on since a change in the norm
3519			   needs different VFE settings */
3520
3521			on = zr->v4l_overlay_active
3522			    && !zr->v4l_memgrab_active;
3523			if (on)
3524				zr36057_overlay(zr, 0);
3525
3526			set_videobus_enable(zr, 0);
3527			i2c_control_device(&zr->i2c,
3528					   I2C_DRIVERID_VIDEODECODER,
3529					   DECODER_SET_INPUT, &input);
3530			i2c_control_device(&zr->i2c,
3531					   I2C_DRIVERID_VIDEODECODER,
3532					   DECODER_SET_NORM,
3533					   &zr->params.norm);
3534			i2c_control_device(&zr->i2c,
3535					   I2C_DRIVERID_VIDEOENCODER,
3536					   ENCODER_SET_NORM,
3537					   &encoder_norm);
3538			set_videobus_enable(zr, 1);
3539
3540			if (on)
3541				zr36057_overlay(zr, 1);
3542
3543			/* Make sure the changes come into effect */
3544			res = wait_grab_pending(zr);
3545			if (res)
3546				return res;
3547
3548			return 0;
3549		}
3550		break;
3551
3552	case VIDIOCGTUNER:
3553		{
3554			DEBUG1(printk(KERN_ERR
3555			       "%s: ioctl VIDIOCGTUNER not supported\n",
3556			       zr->name));
3557			return -EINVAL;
3558		}
3559		break;
3560
3561	case VIDIOCSTUNER:
3562		{
3563			DEBUG1(printk(KERN_ERR
3564			       "%s: ioctl VIDIOCSTUNER not supported\n",
3565			       zr->name));
3566			return -EINVAL;
3567		}
3568		break;
3569
3570	case VIDIOCGPICT:
3571		{
3572			struct video_picture p = zr->picture;
3573
3574			DEBUG2(printk
3575			       ("%s: ioctl VIDIOCGPICT\n", zr->name));
3576			p.depth = zr->buffer.depth;
3577			switch (zr->buffer.depth) {
3578			case 15:
3579				p.palette = VIDEO_PALETTE_RGB555;
3580				break;
3581
3582			case 16:
3583				p.palette = VIDEO_PALETTE_RGB565;
3584				break;
3585
3586			case 24:
3587				p.palette = VIDEO_PALETTE_RGB24;
3588				break;
3589
3590			case 32:
3591				p.palette = VIDEO_PALETTE_RGB32;
3592				break;
3593			}
3594
3595			if (copy_to_user(arg, &p, sizeof(p))) {
3596				return -EFAULT;
3597			}
3598			return 0;
3599		}
3600		break;
3601
3602	case VIDIOCSPICT:
3603		{
3604			struct video_picture p;
3605
3606			if (copy_from_user(&p, arg, sizeof(p))) {
3607				return -EFAULT;
3608			}
3609			i2c_control_device(&zr->i2c,
3610					   I2C_DRIVERID_VIDEODECODER,
3611					   DECODER_SET_PICTURE, &p);
3612			DEBUG2(printk
3613			       ("%s: ioctl VIDIOCSPICT bri=%d hue=%d col=%d con=%d dep=%d pal=%d\n",
3614				zr->name, p.brightness, p.hue, p.colour,
3615				p.contrast, p.depth, p.palette));
3616			/* The depth and palette values have no meaning to us,
3617			   should we return  -EINVAL if they don't fit ? */
3618			zr->picture = p;
3619			return 0;
3620		}
3621		break;
3622
3623	case VIDIOCCAPTURE:
3624		{
3625			int v, res;
3626
3627			if (copy_from_user(&v, arg, sizeof(v))) {
3628				return -EFAULT;
3629			}
3630			DEBUG2(printk
3631			       ("%s: ioctl VIDIOCCAPTURE: %d\n", zr->name,
3632				v));
3633
3634			/* If there is nothing to do, return immediatly */
3635
3636			if ((v && zr->v4l_overlay_active)
3637			    || (!v && !zr->v4l_overlay_active))
3638				return 0;
3639
3640			if (v == 0) {
3641				zr->v4l_overlay_active = 0;
3642				if (!zr->v4l_memgrab_active)
3643					zr36057_overlay(zr, 0);
3644				/* When a grab is running, the video simply won't be switched on any more */
3645			} else {
3646				if (!zr->buffer_set || !zr->window_set) {
3647					DEBUG1(printk(KERN_ERR
3648					       "%s: VIDIOCCAPTURE: buffer or window not set\n",
3649					       zr->name));
3650					return -EINVAL;
3651				}
3652				zr->v4l_overlay_active = 1;
3653				if (!zr->v4l_memgrab_active)
3654					zr36057_overlay(zr, 1);
3655				/* When a grab is running, the video will be switched on when grab is finished */
3656			}
3657			/* Make sure the changes come into effect */
3658			res = wait_grab_pending(zr);
3659			if (res)
3660				return res;
3661			return 0;
3662		}
3663		break;
3664
3665	case VIDIOCGWIN:
3666		{
3667			DEBUG2(printk("%s: ioctl VIDIOCGWIN\n", zr->name));
3668			if (copy_to_user
3669			    (arg, &zr->window, sizeof(zr->window))) {
3670				return -EFAULT;
3671			}
3672			return 0;
3673		}
3674		break;
3675
3676	case VIDIOCSWIN:
3677		{
3678			struct video_clip *vcp;
3679			struct video_window vw;
3680			struct tvnorm *tvn;
3681			int on, end, res, Wa, Ha;
3682
3683			tvn = zr->timing;
3684
3685			Wa = tvn->Wa;
3686			Ha = tvn->Ha;
3687
3688			if (copy_from_user(&vw, arg, sizeof(vw))) {
3689				return -EFAULT;
3690			}
3691
3692			DEBUG2(printk
3693			       ("%s: ioctl VIDIOCSWIN: x=%d y=%d w=%d h=%d clipcount=%d\n",
3694				zr->name, vw.x, vw.y, vw.width, vw.height,
3695				vw.clipcount));
3696
3697			if (!zr->buffer_set) {
3698				DEBUG1(printk(KERN_ERR
3699				       "%s: VIDIOCSWIN: frame buffer has to be set first\n",
3700				       zr->name));
3701				return -EINVAL;
3702			}
3703
3704			/*
3705			 * The video front end needs 4-byte alinged line sizes, we correct that
3706			 * silently here if necessary
3707			 */
3708
3709			if (zr->buffer.depth == 15
3710			    || zr->buffer.depth == 16) {
3711				end = (vw.x + vw.width) & ~1;	/* round down */
3712				vw.x = (vw.x + 1) & ~1;	/* round up */
3713				vw.width = end - vw.x;
3714			}
3715
3716			if (zr->buffer.depth == 24) {
3717				end = (vw.x + vw.width) & ~3;	/* round down */
3718				vw.x = (vw.x + 3) & ~3;	/* round up */
3719				vw.width = end - vw.x;
3720			}
3721
3722			if (vw.width > Wa)
3723				vw.width = Wa;
3724			if (vw.height > Ha)
3725				vw.height = Ha;
3726
3727			/* Check for vaild parameters */
3728			if (vw.width < BUZ_MIN_WIDTH
3729			    || vw.height < BUZ_MIN_HEIGHT
3730			    || vw.width > BUZ_MAX_WIDTH
3731			    || vw.height > BUZ_MAX_HEIGHT) {
3732				DEBUG1(printk(KERN_ERR
3733				       "%s: VIDIOCSWIN: width = %d or height = %d invalid\n",
3734				       zr->name, vw.width, vw.height));
3735				return -EINVAL;
3736			}
3737
3738			zr->window.x = vw.x;
3739			zr->window.y = vw.y;
3740			zr->window.width = vw.width;
3741			zr->window.height = vw.height;
3742			zr->window.chromakey = 0;
3743			zr->window.flags = 0;	// RJ: Is this intended for interlace on/off ?
3744			zr->window.clips = NULL;
3745
3746			/*
3747			 * If an overlay is running, we have to switch it off
3748			 * and switch it on again in order to get the new settings in effect.
3749			 *
3750			 * We also want to avoid that the overlay mask is written
3751			 * when an overlay is running.
3752			 */
3753
3754			on = zr->v4l_overlay_active
3755			    && !zr->v4l_memgrab_active;
3756			if (on)
3757				zr36057_overlay(zr, 0);
3758
3759			/*
3760			 *   Write the overlay mask if clips are wanted.
3761			 */
3762
3763			if (vw.clipcount < 0 || vw.clipcount > 2048)
3764				return -EINVAL;
3765			if (vw.clipcount) {
3766				vcp =
3767				    vmalloc(sizeof(struct video_clip) *
3768					    (vw.clipcount + 4));
3769				if (vcp == NULL) {
3770					printk(KERN_ERR
3771					       "%s: zoran_ioctl: Alloc of clip mask failed\n",
3772					       zr->name);
3773					return -ENOMEM;
3774				}
3775				if (copy_from_user
3776				    (vcp, vw.clips,
3777				     sizeof(struct video_clip) *
3778				     vw.clipcount)) {
3779					vfree(vcp);
3780					return -EFAULT;
3781				}
3782				write_overlay_mask(zr, vcp, vw.clipcount);
3783				vfree(vcp);
3784			}
3785			zr->window.clipcount = vw.clipcount;
3786
3787			if (on)
3788				zr36057_overlay(zr, 1);
3789			zr->window_set = 1;
3790
3791			/* Make sure the changes come into effect */
3792			res = wait_grab_pending(zr);
3793			if (res)
3794				return res;
3795
3796			return 0;
3797		}
3798		break;
3799
3800	case VIDIOCGFBUF:
3801		{
3802			DEBUG2(printk
3803			       ("%s: ioctl VIDIOCGFBUF\n", zr->name));
3804			if (copy_to_user
3805			    (arg, &zr->buffer, sizeof(zr->buffer))) {
3806				return -EFAULT;
3807			}
3808			return 0;
3809		}
3810		break;
3811
3812	case VIDIOCSFBUF:
3813		{
3814			struct video_buffer v;
3815
3816			/* RJ: Isn't this too restrictive? As long as the user doesn't set
3817			   the base address it shouldn't be too dangerous */
3818
3819			if (!capable(CAP_SYS_ADMIN)) {
3820				DEBUG1(printk(KERN_ERR
3821				       "%s: Only the superuser may issue VIDIOCSFBUF ioctl\n",
3822				       zr->name));
3823				return -EPERM;
3824			}
3825			if (copy_from_user(&v, arg, sizeof(v))) {
3826				return -EFAULT;
3827			}
3828			DEBUG2(printk
3829			       ("%s: ioctl VIDIOCSFBUF: base=0x%x w=%d h=%d depth=%d bpl=%d\n",
3830				zr->name, (u32) v.base, v.width, v.height,
3831				v.depth, v.bytesperline));
3832			if (zr->v4l_overlay_active) {
3833				/* Has the user gotten crazy ... ? */
3834				DEBUG1(printk(KERN_ERR
3835				       "%s: VIDIOCSFBUF not allowed when overlay active\n",
3836				       zr->name));
3837				return -EINVAL;
3838			}
3839			if (v.depth != 15 && v.depth != 16 && v.depth != 24
3840			    && v.depth != 32) {
3841				DEBUG1(printk(KERN_ERR
3842				       "%s: VIDIOCSFBUF: depth=%d not supported\n",
3843				       zr->name, v.depth));
3844				return -EINVAL;
3845			}
3846			if (v.height <= 0 || v.width <= 0
3847			    || v.bytesperline <= 0) {
3848				DEBUG1(printk(KERN_ERR
3849				       "%s: VIDIOCSFBUF: invalid height/width/bpl value\n",
3850				       zr->name));
3851				return -EINVAL;
3852			}
3853			if (v.bytesperline & 3) {
3854				DEBUG1(printk(KERN_ERR
3855				       "%s: VIDIOCSFBUF: bytesperline must be 4-byte aligned\n",
3856				       zr->name));
3857				return -EINVAL;
3858			}
3859			if (v.base) {
3860				zr->buffer.base =
3861				    (void *) ((unsigned long) v.base & ~3);
3862			}
3863			zr->buffer.height = v.height;
3864			zr->buffer.width = v.width;
3865			zr->buffer.depth = v.depth;
3866			zr->buffer.bytesperline = v.bytesperline;
3867
3868			if (zr->buffer.base)
3869				zr->buffer_set = 1;
3870			zr->window_set = 0;	/* The user should set new window parameters */
3871			return 0;
3872		}
3873		break;
3874
3875		/* RJ: what is VIDIOCKEY intended to do ??? */
3876
3877	case VIDIOCKEY:
3878		{
3879			/* Will be handled higher up .. */
3880			DEBUG2(printk("%s: ioctl VIDIOCKEY\n", zr->name));
3881			return 0;
3882		}
3883		break;
3884
3885	case VIDIOCGFREQ:
3886		{
3887			DEBUG1(printk(KERN_ERR
3888			       "%s: ioctl VIDIOCGFREQ not supported\n",
3889			       zr->name));
3890			return -EINVAL;
3891		}
3892		break;
3893
3894	case VIDIOCSFREQ:
3895		{
3896			DEBUG1(printk(KERN_ERR
3897			       "%s: ioctl VIDIOCSFREQ not supported\n",
3898			       zr->name));
3899			return -EINVAL;
3900		}
3901		break;
3902
3903	case VIDIOCGAUDIO:
3904		{
3905			DEBUG1(printk(KERN_ERR
3906			       "%s: ioctl VIDIOCGAUDIO not supported\n",
3907			       zr->name));
3908			return -EINVAL;
3909		}
3910		break;
3911
3912	case VIDIOCSAUDIO:
3913		{
3914			DEBUG1(printk(KERN_ERR
3915			       "%s: ioctl VIDIOCSAUDIO not supported\n",
3916			       zr->name));
3917			return -EINVAL;
3918		}
3919		break;
3920
3921	case VIDIOCSYNC:
3922		{
3923			int v;
3924
3925			if (copy_from_user(&v, arg, sizeof(v))) {
3926				return -EFAULT;
3927			}
3928			DEBUG3(printk
3929			       ("%s: ioctl VIDIOCSYNC %d\n", zr->name, v));
3930			return v4l_sync(zr, v);
3931		}
3932		break;
3933
3934	case VIDIOCMCAPTURE:
3935		{
3936			struct video_mmap vm;
3937
3938			if (copy_from_user
3939			    ((void *) &vm, (void *) arg, sizeof(vm))) {
3940				return -EFAULT;
3941			}
3942			DEBUG2(printk
3943			       ("%s: ioctl VIDIOCMCAPTURE frame=%d geom=%dx%d fmt=%d\n",
3944				zr->name, vm.frame, vm.width, vm.height,
3945				vm.format));
3946			return v4l_grab(zr, &vm);
3947		}
3948		break;
3949
3950	case VIDIOCGMBUF:
3951		{
3952			struct video_mbuf vm;
3953			int i;
3954
3955			DEBUG2(printk
3956			       ("%s: ioctl VIDIOCGMBUF\n", zr->name));
3957			vm.size = v4l_nbufs * v4l_bufsize;
3958			vm.frames = v4l_nbufs;
3959			for (i = 0; i < v4l_nbufs; i++) {
3960				vm.offsets[i] = i * v4l_bufsize;
3961			}
3962
3963			/* The next mmap will map the V4L buffers */
3964			zr->map_mjpeg_buffers = 0;
3965
3966			if (copy_to_user(arg, &vm, sizeof(vm))) {
3967				return -EFAULT;
3968			}
3969			return 0;
3970		}
3971		break;
3972
3973	case VIDIOCGUNIT:
3974		{
3975			struct video_unit vu;
3976
3977			DEBUG2(printk
3978			       ("%s: ioctl VIDIOCGUNIT\n", zr->name));
3979			vu.video = zr->video_dev.minor;
3980			vu.vbi = VIDEO_NO_UNIT;
3981			vu.radio = VIDEO_NO_UNIT;
3982			vu.audio = VIDEO_NO_UNIT;
3983			vu.teletext = VIDEO_NO_UNIT;
3984			if (copy_to_user(arg, &vu, sizeof(vu))) {
3985				return -EFAULT;
3986			}
3987			return 0;
3988		}
3989		break;
3990
3991		/*
3992		 * RJ: In principal we could support subcaptures for V4L grabbing.
3993		 *     Not even the famous BTTV driver has them, however.
3994		 *     If there should be a strong demand, one could consider
3995		 *     to implement them.
3996		 */
3997	case VIDIOCGCAPTURE:
3998		{
3999			DEBUG1(printk(KERN_ERR
4000			       "%s: ioctl VIDIOCGCAPTURE not supported\n",
4001			       zr->name));
4002			return -EINVAL;
4003		}
4004		break;
4005
4006	case VIDIOCSCAPTURE:
4007		{
4008			DEBUG1(printk(KERN_ERR
4009			       "%s: ioctl VIDIOCSCAPTURE not supported\n",
4010			       zr->name));
4011			return -EINVAL;
4012		}
4013		break;
4014
4015	case BUZIOC_G_PARAMS:
4016		{
4017			DEBUG2(printk
4018			       ("%s: ioctl BUZIOC_G_PARAMS\n", zr->name));
4019
4020			if (copy_to_user
4021			    (arg, &(zr->params), sizeof(zr->params))) {
4022				return -EFAULT;
4023			}
4024			return 0;
4025		}
4026		break;
4027
4028	case BUZIOC_S_PARAMS:
4029		{
4030			struct zoran_params bp;
4031			/* int input, on; */
4032
4033			if (zr->codec_mode != BUZ_MODE_IDLE) {
4034				DEBUG1(printk(KERN_ERR
4035				       "%s: BUZIOC_S_PARAMS called but Buz in capture/playback mode\n",
4036				       zr->name));
4037				return -EINVAL;
4038			}
4039
4040			if (copy_from_user(&bp, arg, sizeof(bp))) {
4041				return -EFAULT;
4042			}
4043			DEBUG2(printk
4044			       ("%s: ioctl BUZIOC_S_PARAMS\n", zr->name));
4045
4046			/* Check the params first before overwriting our internal values */
4047
4048			if (zoran_check_params(zr, &bp))
4049				return -EINVAL;
4050
4051			zr->params = bp;
4052
4053			/* Make changes of input and norm go into effect immediatly */
4054
4055			/* We switch overlay off and on since a change in the norm
4056			   needs different VFE settings */
4057
4058			if (copy_to_user(arg, &bp, sizeof(bp))) {
4059				return -EFAULT;
4060			}
4061			return 0;
4062		}
4063		break;
4064
4065	case BUZIOC_REQBUFS:
4066		{
4067			struct zoran_requestbuffers br;
4068
4069			if (zr->jpg_buffers_allocated) {
4070				DEBUG1(printk(KERN_ERR
4071				       "%s: BUZIOC_REQBUFS: buffers allready allocated\n",
4072				       zr->name));
4073				return -EINVAL;
4074			}
4075			if (copy_from_user(&br, arg, sizeof(br))) {
4076				return -EFAULT;
4077			}
4078			DEBUG2(printk
4079			       ("%s: ioctl BUZIOC_REQBUFS count = %lu size=%lu\n",
4080				zr->name, br.count, br.size));
4081
4082			/* Enforce reasonable lower and upper limits */
4083			if (br.count < 4)
4084				br.count = 4;	/* Could be choosen smaller */
4085			if (br.count > BUZ_MAX_FRAME)
4086				br.count = BUZ_MAX_FRAME;
4087			br.size = PAGE_ALIGN(br.size);
4088			if (br.size < 8192)
4089				br.size = 8192;	/* Arbitrary */
4090			/* br.size is limited by 1 page for the stat_com tables to a Maximum of 2 MB */
4091			if (br.size > (512 * 1024))
4092				br.size = (512 * 1024);	/* 512 K should be enough */
4093			if (zr->need_contiguous
4094			    && br.size > MAX_KMALLOC_MEM)
4095				br.size = MAX_KMALLOC_MEM;
4096
4097			zr->jpg_nbufs = br.count;
4098			zr->jpg_bufsize = br.size;
4099
4100			if (jpg_fbuffer_alloc(zr))
4101				return -ENOMEM;
4102
4103			/* The next mmap will map the MJPEG buffers */
4104			zr->map_mjpeg_buffers = 1;
4105
4106			if (copy_to_user(arg, &br, sizeof(br))) {
4107				return -EFAULT;
4108			}
4109			return 0;
4110		}
4111		break;
4112
4113	case BUZIOC_QBUF_CAPT:
4114		{
4115			int nb;
4116
4117			if (copy_from_user
4118			    ((void *) &nb, (void *) arg, sizeof(int))) {
4119				return -EFAULT;
4120			}
4121			DEBUG4(printk
4122			       ("%s: ioctl BUZIOC_QBUF_CAPT %d\n",
4123				zr->name, nb));
4124			return jpg_qbuf(zr, nb, BUZ_MODE_MOTION_COMPRESS);
4125		}
4126		break;
4127
4128	case BUZIOC_QBUF_PLAY:
4129		{
4130			int nb;
4131
4132			if (copy_from_user
4133			    ((void *) &nb, (void *) arg, sizeof(int))) {
4134				return -EFAULT;
4135			}
4136			DEBUG4(printk
4137			       ("%s: ioctl BUZIOC_QBUF_PLAY %d\n",
4138				zr->name, nb));
4139			return jpg_qbuf(zr, nb,
4140					BUZ_MODE_MOTION_DECOMPRESS);
4141		}
4142		break;
4143
4144	case BUZIOC_SYNC:
4145		{
4146			struct zoran_sync bs;
4147			int res;
4148
4149			DEBUG4(printk
4150			       ("%s: ioctl BUZIOC_SYNC\n", zr->name));
4151			res = jpg_sync(zr, &bs);
4152			if (copy_to_user(arg, &bs, sizeof(bs))) {
4153				return -EFAULT;
4154			}
4155			return res;
4156		}
4157		break;
4158
4159	case BUZIOC_G_STATUS:
4160		{
4161			struct zoran_status bs;
4162			int norm, input, status;
4163
4164			if (zr->codec_mode != BUZ_MODE_IDLE) {
4165				DEBUG1(printk(KERN_ERR
4166				       "%s: BUZIOC_G_STATUS called but Buz in capture/playback mode\n",
4167				       zr->name));
4168				return -EINVAL;
4169			}
4170
4171			if (copy_from_user(&bs, arg, sizeof(bs))) {
4172				return -EFAULT;
4173			}
4174			DEBUG2(printk
4175			       ("%s: ioctl BUZIOC_G_STATUS\n", zr->name));
4176
4177			switch (bs.input) {
4178			case 0:
4179				if (zr->card == BUZ)
4180					input = 3;
4181				else
4182					input = 0;
4183				break;
4184			case 1:
4185				input = 7;
4186				break;
4187			default:
4188				DEBUG1(printk(KERN_ERR
4189				       "%s: BUZIOC_G_STATUS on not existing input %d\n",
4190				       zr->name, bs.input));
4191				return -EINVAL;
4192			}
4193
4194			/* Set video norm to VIDEO_MODE_AUTO */
4195
4196			norm = VIDEO_MODE_AUTO;
4197			set_videobus_enable(zr, 0);
4198			i2c_control_device(&zr->i2c,
4199					   I2C_DRIVERID_VIDEODECODER,
4200					   DECODER_SET_INPUT, &input);
4201			i2c_control_device(&zr->i2c,
4202					   I2C_DRIVERID_VIDEODECODER,
4203					   DECODER_SET_NORM, &norm);
4204			set_videobus_enable(zr, 1);
4205
4206			/* sleep 1 second */
4207
4208			set_current_state(TASK_UNINTERRUPTIBLE);
4209			schedule_timeout(HZ);
4210
4211			/* Get status of video decoder */
4212
4213			i2c_control_device(&zr->i2c,
4214					   I2C_DRIVERID_VIDEODECODER,
4215					   DECODER_GET_STATUS, &status);
4216			bs.signal = (status & DECODER_STATUS_GOOD) ? 1 : 0;
4217
4218			if (status & DECODER_STATUS_NTSC)
4219				bs.norm = VIDEO_MODE_NTSC;
4220			else if (status & DECODER_STATUS_SECAM)
4221				bs.norm = VIDEO_MODE_SECAM;
4222			else
4223				bs.norm = VIDEO_MODE_PAL;
4224
4225			bs.color = (status & DECODER_STATUS_COLOR) ? 1 : 0;
4226
4227			/* restore previous input and norm */
4228			if (zr->card == BUZ)
4229				input = zr->params.input == 0 ? 3 : 7;
4230			else
4231				input = zr->params.input == 0 ? 0 : 7;
4232			set_videobus_enable(zr, 0);
4233			i2c_control_device(&zr->i2c,
4234					   I2C_DRIVERID_VIDEODECODER,
4235					   DECODER_SET_INPUT, &input);
4236			i2c_control_device(&zr->i2c,
4237					   I2C_DRIVERID_VIDEODECODER,
4238					   DECODER_SET_NORM,
4239					   &zr->params.norm);
4240			set_videobus_enable(zr, 1);
4241
4242			if (copy_to_user(arg, &bs, sizeof(bs))) {
4243				return -EFAULT;
4244			}
4245			return 0;
4246		}
4247		break;
4248
4249	default:
4250		DEBUG1(printk
4251		       ("%s: UNKNOWN ioctl cmd: 0x%x\n", zr->name, cmd));
4252		return -ENOIOCTLCMD;
4253	}
4254	return 0;
4255}
4256
4257static int zoran_ioctl(struct video_device *dev, unsigned int cmd, void *arg)
4258{
4259	struct zoran *zr = (struct zoran *) dev;
4260	int err;
4261
4262	down(&zr->sem);
4263	err = do_zoran_ioctl(zr, cmd, arg);
4264	up(&zr->sem);
4265
4266	return err;
4267}
4268
4269/*
4270 *   This maps the buffers to user space.
4271 *
4272 *   Depending on the state of zr->map_mjpeg_buffers
4273 *   the V4L or the MJPEG buffers are mapped
4274 *
4275 */
4276
4277static int do_zoran_mmap(struct zoran *zr, const char *adr,
4278		      unsigned long size)
4279{
4280	unsigned long start = (unsigned long) adr;
4281	unsigned long page, pos, todo, fraglen;
4282	int i, j;
4283
4284	DEBUG2(printk
4285	       (KERN_INFO "%s: mmap at 0x%08lx, size %lu\n", zr->name,
4286		start, size));
4287	if (zr->map_mjpeg_buffers) {
4288		/* Map the MJPEG buffers */
4289
4290		if (!zr->jpg_buffers_allocated) {
4291			DEBUG1(printk(KERN_ERR
4292			       "%s: zoran_mmap(MJPEG): buffers not yet allocated\n",
4293			       zr->name));
4294			return -ENOMEM;
4295		}
4296
4297		if (size > zr->jpg_nbufs * zr->jpg_bufsize) {
4298			DEBUG1(printk(KERN_ERR
4299			       "%s: zoran_mmap(MJPEG): Max size is %lu - you wanted %lu\n",
4300			       zr->name, zr->jpg_nbufs * zr->jpg_bufsize,
4301			       size));
4302			return -EINVAL;
4303		}
4304
4305		if (size != zr->jpg_nbufs * zr->jpg_bufsize)
4306			DEBUG1(printk(KERN_WARNING
4307			       "%s: zoran_mmap(MJPEG): Expected %lu - you wanted %lu\n",
4308			       zr->name, zr->jpg_nbufs * zr->jpg_bufsize,
4309			       size));
4310
4311		for (i = 0; i < zr->jpg_nbufs; i++) {
4312			for (j = 0; j < zr->jpg_bufsize / PAGE_SIZE; j++) {
4313				fraglen =
4314				    (zr->jpg_gbuf[i].
4315				     frag_tab[2 * j + 1] & ~1) << 1;
4316				todo = size;
4317				if (todo > fraglen)
4318					todo = fraglen;
4319				pos =
4320				    (unsigned long) zr->jpg_gbuf[i].
4321				    frag_tab[2 * j];
4322				page = virt_to_phys(bus_to_virt(pos));	/* should just be pos on i386 */
4323				if (remap_page_range
4324				    (start, page, todo, PAGE_SHARED)) {
4325					printk(KERN_ERR
4326					       "%s: zoran_mmap(V4L): remap_page_range failed\n",
4327					       zr->name);
4328					return -EAGAIN;
4329				}
4330				size -= todo;
4331				start += todo;
4332				if (size == 0)
4333					break;
4334				if (zr->jpg_gbuf[i].
4335				    frag_tab[2 * j + 1] & 1)
4336					break;	/* was last fragment */
4337			}
4338			if (size == 0)
4339				break;
4340		}
4341	} else {
4342		/* Map the V4L buffers */
4343
4344		if (size > v4l_nbufs * v4l_bufsize) {
4345			DEBUG1(printk(KERN_ERR
4346			       "%s: zoran_mmap(V4L): Max size is %d - you wanted %ld\n",
4347			       zr->name, v4l_nbufs * v4l_bufsize, size));
4348			return -EINVAL;
4349		}
4350
4351		if (size != v4l_nbufs * v4l_bufsize)
4352			DEBUG1(printk(KERN_WARNING
4353			       "%s: zoran_mmap(V4L): Expected %d - you wanted %ld\n",
4354			       zr->name, v4l_nbufs * v4l_bufsize, size));
4355
4356		for (i = 0; i < v4l_nbufs; i++) {
4357			todo = size;
4358			if (todo > v4l_bufsize)
4359				todo = v4l_bufsize;
4360			page = zr->v4l_gbuf[i].fbuffer_phys;
4361			DEBUG2(printk
4362			       ("V4L remap page range %d 0x%lx %ld to 0x%lx\n",
4363				i, page, todo, start));
4364			if (remap_page_range
4365			    (start, page, todo, PAGE_SHARED)) {
4366				printk(KERN_ERR
4367				       "%s: zoran_mmap(V4L): remap_page_range failed\n",
4368				       zr->name);
4369				return -EAGAIN;
4370			}
4371			size -= todo;
4372			start += todo;
4373			if (size == 0)
4374				break;
4375		}
4376	}
4377	return 0;
4378}
4379
4380static int zoran_mmap(struct video_device *dev, const char *adr,
4381		      unsigned long size)
4382{
4383	int err;
4384	struct zoran *zr = (struct zoran *) dev;
4385
4386	down(&zr->sem);
4387	err = do_zoran_mmap(zr, adr, size);
4388	up(&zr->sem);
4389
4390	return err;
4391}
4392
4393static int zoran_init_done(struct video_device *dev)
4394{
4395	return 0;
4396}
4397
4398static struct video_device zoran_template = {
4399	owner:		THIS_MODULE,
4400	name:		ZORAN_NAME,
4401	type:		VID_TYPE_CAPTURE | VID_TYPE_OVERLAY | VID_TYPE_CLIPPING |
4402			VID_TYPE_FRAMERAM | VID_TYPE_SCALES | VID_TYPE_SUBCAPTURE,
4403	hardware:	ZORAN_HARDWARE,
4404	open:		zoran_open,
4405	close:		zoran_close,
4406	read:		zoran_read,
4407	write:		zoran_write,
4408	ioctl:		zoran_ioctl,
4409	mmap:		zoran_mmap,
4410	initialize:	zoran_init_done,
4411};
4412
4413/*
4414 * initialize video front end
4415 */
4416static void zr36057_init_vfe(struct zoran *zr)
4417{
4418	u32 reg;
4419	reg = btread(ZR36057_VFESPFR);
4420	reg |= ZR36057_VFESPFR_LittleEndian;
4421	reg &= ~ZR36057_VFESPFR_VCLKPol;
4422	reg |= ZR36057_VFESPFR_ExtFl;
4423	reg |= ZR36057_VFESPFR_TopField;
4424	btwrite(reg, ZR36057_VFESPFR);
4425	reg = btread(ZR36057_VDCR);
4426	if (triton || zr->revision <= 1)
4427		reg &= ~ZR36057_VDCR_Triton;
4428	else
4429		reg |= ZR36057_VDCR_Triton;
4430	btwrite(reg, ZR36057_VDCR);
4431}
4432
4433static void test_interrupts(struct zoran *zr)
4434{
4435	int timeout, icr;
4436
4437	clear_interrupt_counters(zr);
4438	zr->testing = 1;
4439	icr = btread(ZR36057_ICR);
4440	btwrite(0x78000000 | ZR36057_ICR_IntPinEn, ZR36057_ICR);
4441	timeout = interruptible_sleep_on_timeout(&zr->test_q, 1 * HZ);
4442	btwrite(0, ZR36057_ICR);
4443	btwrite(0x78000000, ZR36057_ISR);
4444	zr->testing = 0;
4445	printk(KERN_INFO "%s: Testing interrupts...\n", zr->name);
4446	if (timeout) {
4447		printk(": time spent: %d\n", 1 * HZ - timeout);
4448	}
4449	print_interrupts(zr);
4450	btwrite(icr, ZR36057_ICR);
4451}
4452
4453static int zr36057_init(int i)
4454{
4455	struct zoran *zr = &zoran[i];
4456	unsigned long mem;
4457	unsigned mem_needed;
4458	int j;
4459	int two = 2;
4460	int zero = 0;
4461
4462	printk(KERN_INFO "%s: Initializing card[%d], zr=%x\n", zr->name, i, (int) zr);
4463
4464	/* default setup of all parameters which will persist beetween opens */
4465
4466	zr->user = 0;
4467
4468	init_waitqueue_head(&zr->v4l_capq);
4469	init_waitqueue_head(&zr->jpg_capq);
4470	init_waitqueue_head(&zr->test_q);
4471
4472	zr->map_mjpeg_buffers = 0;	/* Map V4L buffers by default */
4473
4474	zr->jpg_nbufs = 0;
4475	zr->jpg_bufsize = 0;
4476	zr->jpg_buffers_allocated = 0;
4477
4478	zr->buffer_set = 0;	/* Flag if frame buffer has been set */
4479	zr->buffer.base = (void *) vidmem;
4480	zr->buffer.width = 0;
4481	zr->buffer.height = 0;
4482	zr->buffer.depth = 0;
4483	zr->buffer.bytesperline = 0;
4484
4485	zr->params.norm = default_norm = (default_norm < 3 ? default_norm : VIDEO_MODE_PAL);	/* Avoid nonsense settings from user */
4486	if (!(zr->timing = cardnorms[zr->card][zr->params.norm])) {
4487		printk(KERN_WARNING
4488		       "%s: default TV statdard not supported by hardware. PAL will be used.\n",
4489		       zr->name);
4490		zr->params.norm = VIDEO_MODE_PAL;
4491		zr->timing = cardnorms[zr->card][zr->params.norm];
4492	}
4493	zr->params.input = default_input = (default_input ? 1 : 0);	/* Avoid nonsense settings from user */
4494	zr->video_interlace = 0;
4495
4496	/* Should the following be reset at every open ? */
4497
4498	zr->picture.colour = 32768;
4499	zr->picture.brightness = 32768;
4500	zr->picture.hue = 32768;
4501	zr->picture.contrast = 32768;
4502	zr->picture.whiteness = 0;
4503	zr->picture.depth = 0;
4504	zr->picture.palette = 0;
4505
4506	for (j = 0; j < VIDEO_MAX_FRAME; j++) {
4507		zr->v4l_gbuf[i].fbuffer = 0;
4508		zr->v4l_gbuf[i].fbuffer_phys = 0;
4509		zr->v4l_gbuf[i].fbuffer_bus = 0;
4510	}
4511
4512	zr->stat_com = 0;
4513
4514	/* default setup (will be repeated at every open) */
4515
4516	zoran_open_init_params(zr);
4517
4518	/* allocate memory *before* doing anything to the hardware in case allocation fails */
4519
4520	/* STAT_COM table and overlay mask */
4521
4522	mem_needed = (BUZ_NUM_STAT_COM + ((BUZ_MAX_WIDTH + 31) / 32) * BUZ_MAX_HEIGHT) * 4;
4523	mem = (unsigned long) kmalloc(mem_needed, GFP_KERNEL);
4524	if (!mem) {
4525		printk(KERN_ERR "%s: zr36057_init: kmalloc (STAT_COM + ovl.mask) failed\n", zr->name);
4526		return -ENOMEM;
4527	}
4528	memset((void *) mem, 0, mem_needed);
4529
4530	zr->stat_com = (u32 *) mem;
4531	for (j = 0; j < BUZ_NUM_STAT_COM; j++) {
4532		zr->stat_com[j] = 1;	/* mark as unavailable to zr36057 */
4533	}
4534	zr->overlay_mask = (u32 *) (mem + BUZ_NUM_STAT_COM * 4);
4535
4536	/* Initialize zr->jpg_gbuf */
4537
4538	for (j = 0; j < BUZ_MAX_FRAME; j++) {
4539		zr->jpg_gbuf[j].frag_tab = 0;
4540		zr->jpg_gbuf[j].frag_tab_bus = 0;
4541		zr->jpg_gbuf[j].state = BUZ_STATE_USER;
4542		zr->jpg_gbuf[j].bs.frame = j;
4543	}
4544
4545	/*
4546	 *   Now add the template and register the device unit.
4547	 */
4548	memcpy(&zr->video_dev, &zoran_template, sizeof(zoran_template));
4549	strcpy(zr->video_dev.name, zr->name);
4550	if (video_register_device(&zr->video_dev, VFL_TYPE_GRABBER, video_nr) < 0) {
4551		i2c_unregister_bus(&zr->i2c);
4552		kfree((void *) zr->stat_com);
4553		return -1;
4554	}
4555
4556	/* Enable bus-mastering */
4557	pci_set_master(zr->pci_dev);
4558
4559	if (zr->card == BUZ)
4560		j = zr->params.input == 0 ? 3 : 7;
4561	else
4562		j = zr->params.input == 0 ? 0 : 7;
4563	set_videobus_enable(zr, 0);
4564	i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
4565			   DECODER_SET_INPUT, &j);
4566	i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
4567			   DECODER_SET_NORM, &zr->params.norm);
4568	i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEOENCODER,
4569			   ENCODER_SET_NORM, &zr->params.norm);
4570	set_videobus_enable(zr, 1);
4571
4572	/* toggle JPEG codec sleep to sync PLL */
4573	zr36060_sleep(zr, 1);
4574	zr36060_sleep(zr, 0);
4575
4576	/* set individual interrupt enables (without GIRQ1)
4577	   but don't global enable until zoran_open() */
4578
4579	//btwrite(IRQ_MASK & ~ZR36057_ISR_GIRQ1, ZR36057_ICR);  // SW
4580	// It looks like using only JPEGRepIRQEn is not always reliable,
4581	// may be when JPEG codec crashes it won't generate IRQ? So,
4582	btwrite(IRQ_MASK, ZR36057_ICR);	// Enable Vsync interrupts too. SM
4583
4584	zr36057_init_vfe(zr);
4585
4586	zr->zoran_proc = NULL;
4587	zr->initialized = 1;
4588
4589	zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
4590#if (DEBUGLEVEL > 2)
4591	detect_guest_activity(zr);
4592#endif
4593	test_interrupts(zr);
4594	btwrite(IRQ_MASK, ZR36057_ICR);	// Enable Vsync interrupts too. SM
4595	if (!pass_through) {
4596		set_videobus_enable(zr, 0);
4597		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEODECODER,
4598				   DECODER_ENABLE_OUTPUT, &zero);
4599		i2c_control_device(&zr->i2c, I2C_DRIVERID_VIDEOENCODER,
4600				   ENCODER_SET_INPUT, &two);
4601		set_videobus_enable(zr, 1);
4602	}
4603	return 0;
4604}
4605
4606#include "zoran_procfs.c"
4607
4608static void release_dc10(void)
4609{
4610	u8 command;
4611	int i;
4612	struct zoran *zr;
4613
4614	for (i = 0; i < zoran_num; i++) {
4615		zr = &zoran[i];
4616
4617		if (!zr->initialized)
4618			continue;
4619
4620		/* unregister i2c_bus */
4621		i2c_unregister_bus((&zr->i2c));
4622
4623		/* disable PCI bus-mastering */
4624		pci_read_config_byte(zr->pci_dev, PCI_COMMAND, &command);
4625		command &= ~PCI_COMMAND_MASTER;
4626		pci_write_config_byte(zr->pci_dev, PCI_COMMAND, command);
4627
4628		/* put chip into reset */
4629		btwrite(0, ZR36057_SPGPPCR);
4630
4631		free_irq(zr->pci_dev->irq, zr);
4632
4633		/* unmap and free memory */
4634
4635		kfree((void *) zr->stat_com);
4636
4637		zoran_proc_cleanup(i);
4638		iounmap(zr->zr36057_mem);
4639
4640		video_unregister_device(&zr->video_dev);
4641	}
4642}
4643
4644/*
4645 *   Scan for a Buz card (actually for the PCI contoler ZR36057),
4646 *   request the irq and map the io memory
4647 */
4648
4649static int find_zr36057(void)
4650{
4651	unsigned char latency, need_latency;
4652	struct zoran *zr;
4653	struct pci_dev *dev = NULL;
4654	int result;
4655
4656	zoran_num = 0;
4657
4658	while (zoran_num < BUZ_MAX
4659	       && (dev =
4660		   pci_find_device(PCI_VENDOR_ID_ZORAN,
4661				   PCI_DEVICE_ID_ZORAN_36057,
4662				   dev)) != NULL) {
4663		zr = &zoran[zoran_num];
4664		zr->pci_dev = dev;
4665		zr->zr36057_mem = NULL;
4666		zr->id = zoran_num;
4667		sprintf(zr->name, "MJPEG[%u]", zr->id);
4668
4669		spin_lock_init(&zr->lock);
4670		init_MUTEX(&zr->sem);
4671
4672		if (pci_enable_device(dev))
4673			continue;
4674
4675		zr->zr36057_adr = pci_resource_start(zr->pci_dev, 0);
4676		pci_read_config_byte(zr->pci_dev, PCI_CLASS_REVISION,
4677				     &zr->revision);
4678		if (zr->revision < 2) {
4679			printk(KERN_INFO
4680			       "%s: Zoran ZR36057 (rev %d) irq: %d, memory: 0x%08x.\n",
4681			       zr->name, zr->revision, zr->pci_dev->irq,
4682			       zr->zr36057_adr);
4683		} else {
4684			unsigned short ss_vendor_id, ss_id;
4685			ss_vendor_id = zr->pci_dev->subsystem_vendor;
4686			ss_id = zr->pci_dev->subsystem_device;
4687			printk(KERN_INFO
4688			       "%s: Zoran ZR36067 (rev %d) irq: %d, memory: 0x%08x\n",
4689			       zr->name, zr->revision, zr->pci_dev->irq,
4690			       zr->zr36057_adr);
4691			printk(KERN_INFO
4692			       "%s: subsystem vendor=0x%04x id=0x%04x\n",
4693			       zr->name, ss_vendor_id, ss_id);
4694		}
4695
4696		zr->zr36057_mem = ioremap_nocache(zr->zr36057_adr, 0x1000);
4697		if (!zr->zr36057_mem) {
4698			printk(KERN_ERR "%s: ioremap failed\n", zr->name);
4699		}
4700
4701		result = request_irq(zr->pci_dev->irq, zoran_irq, SA_SHIRQ | SA_INTERRUPT, zr->name, (void *) zr);
4702		if (result < 0) {
4703			if (result == -EINVAL) {
4704				printk(KERN_ERR
4705				       "%s: Bad irq number or handler\n",
4706				       zr->name);
4707			} else if (result == -EBUSY) {
4708				printk(KERN_ERR
4709				       "%s: IRQ %d busy, change your PnP config in BIOS\n",
4710				       zr->name, zr->pci_dev->irq);
4711			} else {
4712				printk(KERN_ERR
4713				       "%s: Can't assign irq, error code %d\n",
4714				       zr->name, result);
4715			}
4716			iounmap(zr->zr36057_mem);
4717			continue;
4718		}
4719
4720		/* set PCI latency timer */
4721		pci_read_config_byte(zr->pci_dev, PCI_LATENCY_TIMER, &latency);
4722		need_latency = zr->revision > 1 ? 32 : 48;
4723		if (latency != need_latency) {
4724			printk(KERN_INFO "%s: Changing PCI latency from %d to %d.\n",  zr->name, latency, need_latency);
4725			pci_write_config_byte(zr->pci_dev, PCI_LATENCY_TIMER,  need_latency);
4726		}
4727
4728		btwrite(0, ZR36057_SPGPPCR);
4729		mdelay(1);
4730		btwrite(ZR36057_SPGPPCR_SoftReset, ZR36057_SPGPPCR);
4731		mdelay(1);
4732
4733		/* assert P_Reset */
4734		btwrite(0, ZR36057_JPC);
4735
4736		/* set up GPIO direction - all output */
4737		btwrite(ZR36057_SPGPPCR_SoftReset | 0, ZR36057_SPGPPCR);
4738		btwrite((0x81 << 24) | 0x8888, ZR36057_GPPGCR1);
4739
4740		/* i2c */
4741		memcpy(&zr->i2c, &zoran_i2c_bus_template,
4742		       sizeof(struct i2c_bus));
4743		strcpy(zr->i2c.name, zr->name);
4744		zr->i2c.data = zr;
4745		printk(KERN_INFO "%s: Initializing i2c bus...\n", zr->name);
4746		if (i2c_register_bus(&zr->i2c) < 0) {
4747			/* put chip into reset */
4748			btwrite(0, ZR36057_SPGPPCR);
4749			free_irq(zr->pci_dev->irq, zr);
4750			iounmap(zr->zr36057_mem);
4751			printk(KERN_ERR "%s: Can't initialize i2c bus\n", zr->name);
4752			continue;
4753		}
4754
4755		if (zr->card != DC10 && zr->card != DC10plus
4756		    && zr->card != LML33 && zr->card != BUZ) {
4757			/* unregister i2c_bus */
4758			i2c_unregister_bus((&zr->i2c));
4759			/* put chip into reset */
4760			btwrite(0, ZR36057_SPGPPCR);
4761			free_irq(zr->pci_dev->irq, zr);
4762			iounmap(zr->zr36057_mem);
4763			printk(KERN_ERR "%s: Card not supported\n",
4764			       zr->name);
4765			continue;
4766		}
4767		printk(KERN_INFO "%s card detected\n", zr->name);
4768		if (zr->card == LML33) {
4769			GPIO(zr, 2, 1);	// Set Composite input/output
4770		}
4771
4772		/* reset JPEG codec */
4773		zr36060_sleep(zr, 1);
4774		zr36060_reset(zr);
4775
4776		/* video bus enabled */
4777
4778		/* display codec revision */
4779		if (zr36060_read_8(zr, 0x022) == 0x33) {
4780			printk(KERN_INFO "%s: Zoran ZR36060 (rev %d)\n",
4781			       zr->name, zr36060_read_8(zr, 0x023));
4782		} else {
4783			/* unregister i2c_bus */
4784			i2c_unregister_bus((&zr->i2c));
4785			/* put chip into reset */
4786			btwrite(0, ZR36057_SPGPPCR);
4787			free_irq(zr->pci_dev->irq, zr);
4788			iounmap(zr->zr36057_mem);
4789			printk(KERN_ERR "%s: Zoran ZR36060 not found\n",
4790			       zr->name);
4791			continue;
4792		}
4793
4794		zoran_num++;
4795	}
4796	if (zoran_num == 0) {
4797		printk(KERN_INFO "No known MJPEG cards found.\n");
4798	}
4799	return zoran_num;
4800}
4801
4802static void handle_chipset(void)
4803{
4804	if(pci_pci_problems & PCIPCI_FAIL)
4805		printk(KERN_WARNING "Chipset may not support reliable PCI-PCI DMA.\n");
4806
4807	if(pci_pci_problems & PCIPCI_TRITON)
4808	{
4809		printk(KERN_WARNING "Enabling Triton support.\n");
4810		triton = 1;
4811	}
4812
4813	if(pci_pci_problems & PCIPCI_NATOMA)
4814	{
4815		printk(KERN_WARNING "Enabling Natoma workaround.\n");
4816		natoma = 1;
4817	}
4818}
4819
4820static int init_dc10_cards(void)
4821{
4822	int i;
4823
4824	memset(zoran, 0, sizeof(zoran));
4825	printk(KERN_INFO
4826	       "Zoran ZR36060 + ZR36057/67 MJPEG board driver version %d.%d\n",
4827	       MAJOR_VERSION, MINOR_VERSION);
4828
4829	/* Look for cards */
4830
4831	if (find_zr36057() < 0) {
4832		return -EIO;
4833	}
4834	if (zoran_num == 0)
4835		return 0;	//-ENXIO;
4836
4837	printk(KERN_INFO "MJPEG: %d card(s) found\n", zoran_num);
4838
4839	/* check the parameters we have been given, adjust if necessary */
4840
4841	if (v4l_nbufs < 0)
4842		v4l_nbufs = 0;
4843	if (v4l_nbufs > VIDEO_MAX_FRAME)
4844		v4l_nbufs = VIDEO_MAX_FRAME;
4845	/* The user specfies the in KB, we want them in byte (and page aligned) */
4846	v4l_bufsize = PAGE_ALIGN(v4l_bufsize * 1024);
4847	if (v4l_bufsize < 32768)
4848		v4l_bufsize = 32768;
4849	/* 2 MB is arbitrary but sufficient for the maximum possible images */
4850	if (v4l_bufsize > 2048 * 1024)
4851		v4l_bufsize = 2048 * 1024;
4852
4853	printk(KERN_INFO "MJPEG: using %d V4L buffers of size %d KB\n",
4854	       v4l_nbufs, v4l_bufsize >> 10);
4855
4856	/* Use parameter for vidmem or try to find a video card */
4857
4858	if (vidmem) {
4859		printk(KERN_INFO
4860		       "MJPEG: Using supplied video memory base address @ 0x%lx\n",
4861		       vidmem);
4862	}
4863	/* check if we have a Triton or Natome chipset */
4864
4865	handle_chipset();
4866
4867	/* take care of Natoma chipset and a revision 1 zr36057 */
4868
4869	for (i = 0; i < zoran_num; i++) {
4870		if (natoma && zoran[i].revision <= 1) {
4871			zoran[i].need_contiguous = 1;
4872			printk(KERN_INFO
4873			       "%s: ZR36057/Natoma bug, max. buffer size is 128K\n",
4874			       zoran[i].name);
4875		} else {
4876			zoran[i].need_contiguous = 0;
4877		}
4878	}
4879
4880	/* initialize the Buzs */
4881
4882	/* We have to know which ones must be released if an error occurs */
4883	for (i = 0; i < zoran_num; i++)
4884		zoran[i].initialized = 0;
4885
4886	for (i = 0; i < zoran_num; i++) {
4887		if (zr36057_init(i) < 0) {
4888			release_dc10();
4889			return -EIO;
4890		}
4891		zoran_proc_init(i);
4892	}
4893
4894	return 0;
4895}
4896
4897static void unload_dc10_cards(void)
4898{
4899	release_dc10();
4900}
4901
4902
4903module_init(init_dc10_cards);
4904module_exit(unload_dc10_cards);
4905MODULE_LICENSE("GPL");
4906