1/*
2 * Zoran zr36057/zr36067 PCI controller driver, for the
3 * Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
4 * Media Labs LML33/LML33R10.
5 *
6 * This part handles device access (PCI/I2C/codec/...)
7 *
8 * Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
9 *
10 * Currently maintained by:
11 *   Ronald Bultje    <rbultje@ronald.bitfreak.net>
12 *   Laurent Pinchart <laurent.pinchart@skynet.be>
13 *   Mailinglist      <mjpeg-users@lists.sf.net>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 */
29
30#include <linux/types.h>
31#include <linux/kernel.h>
32#include <linux/module.h>
33#include <linux/vmalloc.h>
34
35#include <linux/interrupt.h>
36#include <linux/proc_fs.h>
37#include <linux/i2c.h>
38#include <linux/i2c-algo-bit.h>
39#include <linux/videodev2.h>
40#include <media/v4l2-common.h>
41#include <linux/spinlock.h>
42#include <linux/sem.h>
43
44#include <linux/pci.h>
45#include <linux/delay.h>
46#include <linux/wait.h>
47
48#include <asm/byteorder.h>
49#include <asm/io.h>
50
51#include "videocodec.h"
52#include "zoran.h"
53#include "zoran_device.h"
54#include "zoran_card.h"
55
56#define IRQ_MASK ( ZR36057_ISR_GIRQ0 | \
57		   ZR36057_ISR_GIRQ1 | \
58		   ZR36057_ISR_JPEGRepIRQ )
59
60static bool lml33dpath;		/* default = 0
61				 * 1 will use digital path in capture
62				 * mode instead of analog. It can be
63				 * used for picture adjustments using
64				 * tool like xawtv while watching image
65				 * on TV monitor connected to the output.
66				 * However, due to absence of 75 Ohm
67				 * load on Bt819 input, there will be
68				 * some image imperfections */
69
70module_param(lml33dpath, bool, 0644);
71MODULE_PARM_DESC(lml33dpath,
72		 "Use digital path capture mode (on LML33 cards)");
73
74static void
75zr36057_init_vfe (struct zoran *zr);
76
77/*
78 * General Purpose I/O and Guest bus access
79 */
80
81/*
82 * This is a bit tricky. When a board lacks a GPIO function, the corresponding
83 * GPIO bit number in the card_info structure is set to 0.
84 */
85
86void
87GPIO (struct zoran *zr,
88      int           bit,
89      unsigned int  value)
90{
91	u32 reg;
92	u32 mask;
93
94	/* Make sure the bit number is legal
95	 * A bit number of -1 (lacking) gives a mask of 0,
96	 * making it harmless */
97	mask = (1 << (24 + bit)) & 0xff000000;
98	reg = btread(ZR36057_GPPGCR1) & ~mask;
99	if (value) {
100		reg |= mask;
101	}
102	btwrite(reg, ZR36057_GPPGCR1);
103	udelay(1);
104}
105
106/*
107 * Wait til post office is no longer busy
108 */
109
110int
111post_office_wait (struct zoran *zr)
112{
113	u32 por;
114
115//      while (((por = btread(ZR36057_POR)) & (ZR36057_POR_POPen | ZR36057_POR_POTime)) == ZR36057_POR_POPen) {
116	while ((por = btread(ZR36057_POR)) & ZR36057_POR_POPen) {
117		/* wait for something to happen */
118	}
119	if ((por & ZR36057_POR_POTime) && !zr->card.gws_not_connected) {
120		/* In LML33/BUZ \GWS line is not connected, so it has always timeout set */
121		dprintk(1, KERN_INFO "%s: pop timeout %08x\n", ZR_DEVNAME(zr),
122			por);
123		return -1;
124	}
125
126	return 0;
127}
128
129int
130post_office_write (struct zoran *zr,
131		   unsigned int  guest,
132		   unsigned int  reg,
133		   unsigned int  value)
134{
135	u32 por;
136
137	por =
138	    ZR36057_POR_PODir | ZR36057_POR_POTime | ((guest & 7) << 20) |
139	    ((reg & 7) << 16) | (value & 0xFF);
140	btwrite(por, ZR36057_POR);
141
142	return post_office_wait(zr);
143}
144
145int
146post_office_read (struct zoran *zr,
147		  unsigned int  guest,
148		  unsigned int  reg)
149{
150	u32 por;
151
152	por = ZR36057_POR_POTime | ((guest & 7) << 20) | ((reg & 7) << 16);
153	btwrite(por, ZR36057_POR);
154	if (post_office_wait(zr) < 0) {
155		return -1;
156	}
157
158	return btread(ZR36057_POR) & 0xFF;
159}
160
161/*
162 * detect guests
163 */
164
165static void
166dump_guests (struct zoran *zr)
167{
168	if (zr36067_debug > 2) {
169		int i, guest[8];
170
171		for (i = 1; i < 8; i++) {	// Don't read jpeg codec here
172			guest[i] = post_office_read(zr, i, 0);
173		}
174
175		printk(KERN_INFO "%s: Guests:", ZR_DEVNAME(zr));
176
177		for (i = 1; i < 8; i++) {
178			printk(" 0x%02x", guest[i]);
179		}
180		printk("\n");
181	}
182}
183
184static inline unsigned long
185get_time (void)
186{
187	struct timeval tv;
188
189	do_gettimeofday(&tv);
190	return (1000000 * tv.tv_sec + tv.tv_usec);
191}
192
193void
194detect_guest_activity (struct zoran *zr)
195{
196	int timeout, i, j, res, guest[8], guest0[8], change[8][3];
197	unsigned long t0, t1;
198
199	dump_guests(zr);
200	printk(KERN_INFO "%s: Detecting guests activity, please wait...\n",
201	       ZR_DEVNAME(zr));
202	for (i = 1; i < 8; i++) {	// Don't read jpeg codec here
203		guest0[i] = guest[i] = post_office_read(zr, i, 0);
204	}
205
206	timeout = 0;
207	j = 0;
208	t0 = get_time();
209	while (timeout < 10000) {
210		udelay(10);
211		timeout++;
212		for (i = 1; (i < 8) && (j < 8); i++) {
213			res = post_office_read(zr, i, 0);
214			if (res != guest[i]) {
215				t1 = get_time();
216				change[j][0] = (t1 - t0);
217				t0 = t1;
218				change[j][1] = i;
219				change[j][2] = res;
220				j++;
221				guest[i] = res;
222			}
223		}
224		if (j >= 8)
225			break;
226	}
227	printk(KERN_INFO "%s: Guests:", ZR_DEVNAME(zr));
228
229	for (i = 1; i < 8; i++) {
230		printk(" 0x%02x", guest0[i]);
231	}
232	printk("\n");
233	if (j == 0) {
234		printk(KERN_INFO "%s: No activity detected.\n", ZR_DEVNAME(zr));
235		return;
236	}
237	for (i = 0; i < j; i++) {
238		printk(KERN_INFO "%s: %6d: %d => 0x%02x\n", ZR_DEVNAME(zr),
239		       change[i][0], change[i][1], change[i][2]);
240	}
241}
242
243/*
244 * JPEG Codec access
245 */
246
247void
248jpeg_codec_sleep (struct zoran *zr,
249		  int           sleep)
250{
251	GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_SLEEP], !sleep);
252	if (!sleep) {
253		dprintk(3,
254			KERN_DEBUG
255			"%s: jpeg_codec_sleep() - wake GPIO=0x%08x\n",
256			ZR_DEVNAME(zr), btread(ZR36057_GPPGCR1));
257		udelay(500);
258	} else {
259		dprintk(3,
260			KERN_DEBUG
261			"%s: jpeg_codec_sleep() - sleep GPIO=0x%08x\n",
262			ZR_DEVNAME(zr), btread(ZR36057_GPPGCR1));
263		udelay(2);
264	}
265}
266
267int
268jpeg_codec_reset (struct zoran *zr)
269{
270	/* Take the codec out of sleep */
271	jpeg_codec_sleep(zr, 0);
272
273	if (zr->card.gpcs[GPCS_JPEG_RESET] != 0xff) {
274		post_office_write(zr, zr->card.gpcs[GPCS_JPEG_RESET], 0,
275				  0);
276		udelay(2);
277	} else {
278		GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_RESET], 0);
279		udelay(2);
280		GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_RESET], 1);
281		udelay(2);
282	}
283
284	return 0;
285}
286
287/*
288 *   Set the registers for the size we have specified. Don't bother
289 *   trying to understand this without the ZR36057 manual in front of
290 *   you [AC].
291 *
292 *   PS: The manual is free for download in .pdf format from
293 *   www.zoran.com - nicely done those folks.
294 */
295
296static void
297zr36057_adjust_vfe (struct zoran          *zr,
298		    enum zoran_codec_mode  mode)
299{
300	u32 reg;
301
302	switch (mode) {
303	case BUZ_MODE_MOTION_DECOMPRESS:
304		btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
305		reg = btread(ZR36057_VFEHCR);
306		if ((reg & (1 << 10)) && zr->card.type != LML33R10) {
307			reg += ((1 << 10) | 1);
308		}
309		btwrite(reg, ZR36057_VFEHCR);
310		break;
311	case BUZ_MODE_MOTION_COMPRESS:
312	case BUZ_MODE_IDLE:
313	default:
314		if ((zr->norm & V4L2_STD_NTSC) ||
315		    (zr->card.type == LML33R10 &&
316		     (zr->norm & V4L2_STD_PAL)))
317			btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
318		else
319			btor(ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
320		reg = btread(ZR36057_VFEHCR);
321		if (!(reg & (1 << 10)) && zr->card.type != LML33R10) {
322			reg -= ((1 << 10) | 1);
323		}
324		btwrite(reg, ZR36057_VFEHCR);
325		break;
326	}
327}
328
329/*
330 * set geometry
331 */
332
333static void
334zr36057_set_vfe (struct zoran              *zr,
335		 int                        video_width,
336		 int                        video_height,
337		 const struct zoran_format *format)
338{
339	struct tvnorm *tvn;
340	unsigned HStart, HEnd, VStart, VEnd;
341	unsigned DispMode;
342	unsigned VidWinWid, VidWinHt;
343	unsigned hcrop1, hcrop2, vcrop1, vcrop2;
344	unsigned Wa, We, Ha, He;
345	unsigned X, Y, HorDcm, VerDcm;
346	u32 reg;
347	unsigned mask_line_size;
348
349	tvn = zr->timing;
350
351	Wa = tvn->Wa;
352	Ha = tvn->Ha;
353
354	dprintk(2, KERN_INFO "%s: set_vfe() - width = %d, height = %d\n",
355		ZR_DEVNAME(zr), video_width, video_height);
356
357	if (video_width < BUZ_MIN_WIDTH ||
358	    video_height < BUZ_MIN_HEIGHT ||
359	    video_width > Wa || video_height > Ha) {
360		dprintk(1, KERN_ERR "%s: set_vfe: w=%d h=%d not valid\n",
361			ZR_DEVNAME(zr), video_width, video_height);
362		return;
363	}
364
365	/**** zr36057 ****/
366
367	/* horizontal */
368	VidWinWid = video_width;
369	X = DIV_ROUND_UP(VidWinWid * 64, tvn->Wa);
370	We = (VidWinWid * 64) / X;
371	HorDcm = 64 - X;
372	hcrop1 = 2 * ((tvn->Wa - We) / 4);
373	hcrop2 = tvn->Wa - We - hcrop1;
374	HStart = tvn->HStart ? tvn->HStart : 1;
375	/* (Ronald) Original comment:
376	 * "| 1 Doesn't have any effect, tested on both a DC10 and a DC10+"
377	 * this is false. It inverses chroma values on the LML33R10 (so Cr
378	 * suddenly is shown as Cb and reverse, really cool effect if you
379	 * want to see blue faces, not useful otherwise). So don't use |1.
380	 * However, the DC10 has '0' as HStart, but does need |1, so we
381	 * use a dirty check...
382	 */
383	HEnd = HStart + tvn->Wa - 1;
384	HStart += hcrop1;
385	HEnd -= hcrop2;
386	reg = ((HStart & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HStart)
387	    | ((HEnd & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HEnd);
388	if (zr->card.vfe_pol.hsync_pol)
389		reg |= ZR36057_VFEHCR_HSPol;
390	btwrite(reg, ZR36057_VFEHCR);
391
392	/* Vertical */
393	DispMode = !(video_height > BUZ_MAX_HEIGHT / 2);
394	VidWinHt = DispMode ? video_height : video_height / 2;
395	Y = DIV_ROUND_UP(VidWinHt * 64 * 2, tvn->Ha);
396	He = (VidWinHt * 64) / Y;
397	VerDcm = 64 - Y;
398	vcrop1 = (tvn->Ha / 2 - He) / 2;
399	vcrop2 = tvn->Ha / 2 - He - vcrop1;
400	VStart = tvn->VStart;
401	VEnd = VStart + tvn->Ha / 2;	// - 1; FIXME SnapShot times out with -1 in 768*576 on the DC10 - LP
402	VStart += vcrop1;
403	VEnd -= vcrop2;
404	reg = ((VStart & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VStart)
405	    | ((VEnd & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VEnd);
406	if (zr->card.vfe_pol.vsync_pol)
407		reg |= ZR36057_VFEVCR_VSPol;
408	btwrite(reg, ZR36057_VFEVCR);
409
410	/* scaler and pixel format */
411	reg = 0;
412	reg |= (HorDcm << ZR36057_VFESPFR_HorDcm);
413	reg |= (VerDcm << ZR36057_VFESPFR_VerDcm);
414	reg |= (DispMode << ZR36057_VFESPFR_DispMode);
415	/* RJ: I don't know, why the following has to be the opposite
416	 * of the corresponding ZR36060 setting, but only this way
417	 * we get the correct colors when uncompressing to the screen  */
418	//reg |= ZR36057_VFESPFR_VCLKPol; /**/
419	/* RJ: Don't know if that is needed for NTSC also */
420	if (!(zr->norm & V4L2_STD_NTSC))
421		reg |= ZR36057_VFESPFR_ExtFl;	// NEEDED!!!!!!! Wolfgang
422	reg |= ZR36057_VFESPFR_TopField;
423	if (HorDcm >= 48) {
424		reg |= 3 << ZR36057_VFESPFR_HFilter;	/* 5 tap filter */
425	} else if (HorDcm >= 32) {
426		reg |= 2 << ZR36057_VFESPFR_HFilter;	/* 4 tap filter */
427	} else if (HorDcm >= 16) {
428		reg |= 1 << ZR36057_VFESPFR_HFilter;	/* 3 tap filter */
429	}
430	reg |= format->vfespfr;
431	btwrite(reg, ZR36057_VFESPFR);
432
433	/* display configuration */
434	reg = (16 << ZR36057_VDCR_MinPix)
435	    | (VidWinHt << ZR36057_VDCR_VidWinHt)
436	    | (VidWinWid << ZR36057_VDCR_VidWinWid);
437	if (pci_pci_problems & PCIPCI_TRITON)
438		// || zr->revision < 1) // Revision 1 has also Triton support
439		reg &= ~ZR36057_VDCR_Triton;
440	else
441		reg |= ZR36057_VDCR_Triton;
442	btwrite(reg, ZR36057_VDCR);
443
444	/* (Ronald) don't write this if overlay_mask = NULL */
445	if (zr->overlay_mask) {
446		/* Write overlay clipping mask data, but don't enable overlay clipping */
447		/* RJ: since this makes only sense on the screen, we use
448		 * zr->overlay_settings.width instead of video_width */
449
450		mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
451		reg = virt_to_bus(zr->overlay_mask);
452		btwrite(reg, ZR36057_MMTR);
453		reg = virt_to_bus(zr->overlay_mask + mask_line_size);
454		btwrite(reg, ZR36057_MMBR);
455		reg =
456		    mask_line_size - (zr->overlay_settings.width +
457				      31) / 32;
458		if (DispMode == 0)
459			reg += mask_line_size;
460		reg <<= ZR36057_OCR_MaskStride;
461		btwrite(reg, ZR36057_OCR);
462	}
463
464	zr36057_adjust_vfe(zr, zr->codec_mode);
465}
466
467/*
468 * Switch overlay on or off
469 */
470
471void
472zr36057_overlay (struct zoran *zr,
473		 int           on)
474{
475	u32 reg;
476
477	if (on) {
478		/* do the necessary settings ... */
479		btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);	/* switch it off first */
480
481		zr36057_set_vfe(zr,
482				zr->overlay_settings.width,
483				zr->overlay_settings.height,
484				zr->overlay_settings.format);
485
486		/* Start and length of each line MUST be 4-byte aligned.
487		 * This should be already checked before the call to this routine.
488		 * All error messages are internal driver checking only! */
489
490		/* video display top and bottom registers */
491		reg = (long) zr->vbuf_base +
492		    zr->overlay_settings.x *
493		    ((zr->overlay_settings.format->depth + 7) / 8) +
494		    zr->overlay_settings.y *
495		    zr->vbuf_bytesperline;
496		btwrite(reg, ZR36057_VDTR);
497		if (reg & 3)
498			dprintk(1,
499				KERN_ERR
500				"%s: zr36057_overlay() - video_address not aligned\n",
501				ZR_DEVNAME(zr));
502		if (zr->overlay_settings.height > BUZ_MAX_HEIGHT / 2)
503			reg += zr->vbuf_bytesperline;
504		btwrite(reg, ZR36057_VDBR);
505
506		/* video stride, status, and frame grab register */
507		reg = zr->vbuf_bytesperline -
508		    zr->overlay_settings.width *
509		    ((zr->overlay_settings.format->depth + 7) / 8);
510		if (zr->overlay_settings.height > BUZ_MAX_HEIGHT / 2)
511			reg += zr->vbuf_bytesperline;
512		if (reg & 3)
513			dprintk(1,
514				KERN_ERR
515				"%s: zr36057_overlay() - video_stride not aligned\n",
516				ZR_DEVNAME(zr));
517		reg = (reg << ZR36057_VSSFGR_DispStride);
518		reg |= ZR36057_VSSFGR_VidOvf;	/* clear overflow status */
519		btwrite(reg, ZR36057_VSSFGR);
520
521		/* Set overlay clipping */
522		if (zr->overlay_settings.clipcount > 0)
523			btor(ZR36057_OCR_OvlEnable, ZR36057_OCR);
524
525		/* ... and switch it on */
526		btor(ZR36057_VDCR_VidEn, ZR36057_VDCR);
527	} else {
528		/* Switch it off */
529		btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
530	}
531}
532
533/*
534 * The overlay mask has one bit for each pixel on a scan line,
535 *  and the maximum window size is BUZ_MAX_WIDTH * BUZ_MAX_HEIGHT pixels.
536 */
537
538void write_overlay_mask(struct zoran_fh *fh, struct v4l2_clip *vp, int count)
539{
540	struct zoran *zr = fh->zr;
541	unsigned mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
542	u32 *mask;
543	int x, y, width, height;
544	unsigned i, j, k;
545
546	/* fill mask with one bits */
547	memset(fh->overlay_mask, ~0, mask_line_size * 4 * BUZ_MAX_HEIGHT);
548
549	for (i = 0; i < count; ++i) {
550		/* pick up local copy of clip */
551		x = vp[i].c.left;
552		y = vp[i].c.top;
553		width = vp[i].c.width;
554		height = vp[i].c.height;
555
556		/* trim clips that extend beyond the window */
557		if (x < 0) {
558			width += x;
559			x = 0;
560		}
561		if (y < 0) {
562			height += y;
563			y = 0;
564		}
565		if (x + width > fh->overlay_settings.width) {
566			width = fh->overlay_settings.width - x;
567		}
568		if (y + height > fh->overlay_settings.height) {
569			height = fh->overlay_settings.height - y;
570		}
571
572		/* ignore degenerate clips */
573		if (height <= 0) {
574			continue;
575		}
576		if (width <= 0) {
577			continue;
578		}
579
580		/* apply clip for each scan line */
581		for (j = 0; j < height; ++j) {
582			/* reset bit for each pixel */
583			/* this can be optimized later if need be */
584			mask = fh->overlay_mask + (y + j) * mask_line_size;
585			for (k = 0; k < width; ++k) {
586				mask[(x + k) / 32] &=
587				    ~((u32) 1 << (x + k) % 32);
588			}
589		}
590	}
591}
592
593/* Enable/Disable uncompressed memory grabbing of the 36057 */
594
595void
596zr36057_set_memgrab (struct zoran *zr,
597		     int           mode)
598{
599	if (mode) {
600		/* We only check SnapShot and not FrameGrab here.  SnapShot==1
601		 * means a capture is already in progress, but FrameGrab==1
602		 * doesn't necessary mean that.  It's more correct to say a 1
603		 * to 0 transition indicates a capture completed.  If a
604		 * capture is pending when capturing is tuned off, FrameGrab
605		 * will be stuck at 1 until capturing is turned back on.
606		 */
607		if (btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_SnapShot)
608			dprintk(1,
609				KERN_WARNING
610				"%s: zr36057_set_memgrab(1) with SnapShot on!?\n",
611				ZR_DEVNAME(zr));
612
613		/* switch on VSync interrupts */
614		btwrite(IRQ_MASK, ZR36057_ISR);	// Clear Interrupts
615		btor(zr->card.vsync_int, ZR36057_ICR);	// SW
616
617		/* enable SnapShot */
618		btor(ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
619
620		/* Set zr36057 video front end  and enable video */
621		zr36057_set_vfe(zr, zr->v4l_settings.width,
622				zr->v4l_settings.height,
623				zr->v4l_settings.format);
624
625		zr->v4l_memgrab_active = 1;
626	} else {
627		/* switch off VSync interrupts */
628		btand(~zr->card.vsync_int, ZR36057_ICR);	// SW
629
630		zr->v4l_memgrab_active = 0;
631		zr->v4l_grab_frame = NO_GRAB_ACTIVE;
632
633		/* reenable grabbing to screen if it was running */
634		if (zr->v4l_overlay_active) {
635			zr36057_overlay(zr, 1);
636		} else {
637			btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
638			btand(~ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
639		}
640	}
641}
642
643int
644wait_grab_pending (struct zoran *zr)
645{
646	unsigned long flags;
647
648	/* wait until all pending grabs are finished */
649
650	if (!zr->v4l_memgrab_active)
651		return 0;
652
653	wait_event_interruptible(zr->v4l_capq,
654			(zr->v4l_pend_tail == zr->v4l_pend_head));
655	if (signal_pending(current))
656		return -ERESTARTSYS;
657
658	spin_lock_irqsave(&zr->spinlock, flags);
659	zr36057_set_memgrab(zr, 0);
660	spin_unlock_irqrestore(&zr->spinlock, flags);
661
662	return 0;
663}
664
665/*****************************************************************************
666 *                                                                           *
667 *  Set up the Buz-specific MJPEG part                                       *
668 *                                                                           *
669 *****************************************************************************/
670
671static inline void
672set_frame (struct zoran *zr,
673	   int           val)
674{
675	GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_FRAME], val);
676}
677
678static void
679set_videobus_dir (struct zoran *zr,
680		  int           val)
681{
682	switch (zr->card.type) {
683	case LML33:
684	case LML33R10:
685		if (!lml33dpath)
686			GPIO(zr, 5, val);
687		else
688			GPIO(zr, 5, 1);
689		break;
690	default:
691		GPIO(zr, zr->card.gpio[ZR_GPIO_VID_DIR],
692		     zr->card.gpio_pol[ZR_GPIO_VID_DIR] ? !val : val);
693		break;
694	}
695}
696
697static void
698init_jpeg_queue (struct zoran *zr)
699{
700	int i;
701
702	/* re-initialize DMA ring stuff */
703	zr->jpg_que_head = 0;
704	zr->jpg_dma_head = 0;
705	zr->jpg_dma_tail = 0;
706	zr->jpg_que_tail = 0;
707	zr->jpg_seq_num = 0;
708	zr->JPEG_error = 0;
709	zr->num_errors = 0;
710	zr->jpg_err_seq = 0;
711	zr->jpg_err_shift = 0;
712	zr->jpg_queued_num = 0;
713	for (i = 0; i < zr->jpg_buffers.num_buffers; i++) {
714		zr->jpg_buffers.buffer[i].state = BUZ_STATE_USER;	/* nothing going on */
715	}
716	for (i = 0; i < BUZ_NUM_STAT_COM; i++) {
717		zr->stat_com[i] = cpu_to_le32(1);	/* mark as unavailable to zr36057 */
718	}
719}
720
721static void
722zr36057_set_jpg (struct zoran          *zr,
723		 enum zoran_codec_mode  mode)
724{
725	struct tvnorm *tvn;
726	u32 reg;
727
728	tvn = zr->timing;
729
730	/* assert P_Reset, disable code transfer, deassert Active */
731	btwrite(0, ZR36057_JPC);
732
733	/* MJPEG compression mode */
734	switch (mode) {
735
736	case BUZ_MODE_MOTION_COMPRESS:
737	default:
738		reg = ZR36057_JMC_MJPGCmpMode;
739		break;
740
741	case BUZ_MODE_MOTION_DECOMPRESS:
742		reg = ZR36057_JMC_MJPGExpMode;
743		reg |= ZR36057_JMC_SyncMstr;
744		/* RJ: The following is experimental - improves the output to screen */
745		//if(zr->jpg_settings.VFIFO_FB) reg |= ZR36057_JMC_VFIFO_FB; // No, it doesn't. SM
746		break;
747
748	case BUZ_MODE_STILL_COMPRESS:
749		reg = ZR36057_JMC_JPGCmpMode;
750		break;
751
752	case BUZ_MODE_STILL_DECOMPRESS:
753		reg = ZR36057_JMC_JPGExpMode;
754		break;
755
756	}
757	reg |= ZR36057_JMC_JPG;
758	if (zr->jpg_settings.field_per_buff == 1)
759		reg |= ZR36057_JMC_Fld_per_buff;
760	btwrite(reg, ZR36057_JMC);
761
762	/* vertical */
763	btor(ZR36057_VFEVCR_VSPol, ZR36057_VFEVCR);
764	reg = (6 << ZR36057_VSP_VsyncSize) |
765	      (tvn->Ht << ZR36057_VSP_FrmTot);
766	btwrite(reg, ZR36057_VSP);
767	reg = ((zr->jpg_settings.img_y + tvn->VStart) << ZR36057_FVAP_NAY) |
768	      (zr->jpg_settings.img_height << ZR36057_FVAP_PAY);
769	btwrite(reg, ZR36057_FVAP);
770
771	/* horizontal */
772	if (zr->card.vfe_pol.hsync_pol)
773		btor(ZR36057_VFEHCR_HSPol, ZR36057_VFEHCR);
774	else
775		btand(~ZR36057_VFEHCR_HSPol, ZR36057_VFEHCR);
776	reg = ((tvn->HSyncStart) << ZR36057_HSP_HsyncStart) |
777	      (tvn->Wt << ZR36057_HSP_LineTot);
778	btwrite(reg, ZR36057_HSP);
779	reg = ((zr->jpg_settings.img_x +
780		tvn->HStart + 4) << ZR36057_FHAP_NAX) |
781	      (zr->jpg_settings.img_width << ZR36057_FHAP_PAX);
782	btwrite(reg, ZR36057_FHAP);
783
784	/* field process parameters */
785	if (zr->jpg_settings.odd_even)
786		reg = ZR36057_FPP_Odd_Even;
787	else
788		reg = 0;
789
790	btwrite(reg, ZR36057_FPP);
791
792	/* Set proper VCLK Polarity, else colors will be wrong during playback */
793	//btor(ZR36057_VFESPFR_VCLKPol, ZR36057_VFESPFR);
794
795	/* code base address */
796	reg = virt_to_bus(zr->stat_com);
797	btwrite(reg, ZR36057_JCBA);
798
799	/* FIFO threshold (FIFO is 160. double words) */
800	/* NOTE: decimal values here */
801	switch (mode) {
802
803	case BUZ_MODE_STILL_COMPRESS:
804	case BUZ_MODE_MOTION_COMPRESS:
805		if (zr->card.type != BUZ)
806			reg = 140;
807		else
808			reg = 60;
809		break;
810
811	case BUZ_MODE_STILL_DECOMPRESS:
812	case BUZ_MODE_MOTION_DECOMPRESS:
813		reg = 20;
814		break;
815
816	default:
817		reg = 80;
818		break;
819
820	}
821	btwrite(reg, ZR36057_JCFT);
822	zr36057_adjust_vfe(zr, mode);
823
824}
825
826void
827print_interrupts (struct zoran *zr)
828{
829	int res, noerr = 0;
830
831	printk(KERN_INFO "%s: interrupts received:", ZR_DEVNAME(zr));
832	if ((res = zr->field_counter) < -1 || res > 1) {
833		printk(" FD:%d", res);
834	}
835	if ((res = zr->intr_counter_GIRQ1) != 0) {
836		printk(" GIRQ1:%d", res);
837		noerr++;
838	}
839	if ((res = zr->intr_counter_GIRQ0) != 0) {
840		printk(" GIRQ0:%d", res);
841		noerr++;
842	}
843	if ((res = zr->intr_counter_CodRepIRQ) != 0) {
844		printk(" CodRepIRQ:%d", res);
845		noerr++;
846	}
847	if ((res = zr->intr_counter_JPEGRepIRQ) != 0) {
848		printk(" JPEGRepIRQ:%d", res);
849		noerr++;
850	}
851	if (zr->JPEG_max_missed) {
852		printk(" JPEG delays: max=%d min=%d", zr->JPEG_max_missed,
853		       zr->JPEG_min_missed);
854	}
855	if (zr->END_event_missed) {
856		printk(" ENDs missed: %d", zr->END_event_missed);
857	}
858	//if (zr->jpg_queued_num) {
859	printk(" queue_state=%ld/%ld/%ld/%ld", zr->jpg_que_tail,
860	       zr->jpg_dma_tail, zr->jpg_dma_head, zr->jpg_que_head);
861	//}
862	if (!noerr) {
863		printk(": no interrupts detected.");
864	}
865	printk("\n");
866}
867
868void
869clear_interrupt_counters (struct zoran *zr)
870{
871	zr->intr_counter_GIRQ1 = 0;
872	zr->intr_counter_GIRQ0 = 0;
873	zr->intr_counter_CodRepIRQ = 0;
874	zr->intr_counter_JPEGRepIRQ = 0;
875	zr->field_counter = 0;
876	zr->IRQ1_in = 0;
877	zr->IRQ1_out = 0;
878	zr->JPEG_in = 0;
879	zr->JPEG_out = 0;
880	zr->JPEG_0 = 0;
881	zr->JPEG_1 = 0;
882	zr->END_event_missed = 0;
883	zr->JPEG_missed = 0;
884	zr->JPEG_max_missed = 0;
885	zr->JPEG_min_missed = 0x7fffffff;
886}
887
888static u32
889count_reset_interrupt (struct zoran *zr)
890{
891	u32 isr;
892
893	if ((isr = btread(ZR36057_ISR) & 0x78000000)) {
894		if (isr & ZR36057_ISR_GIRQ1) {
895			btwrite(ZR36057_ISR_GIRQ1, ZR36057_ISR);
896			zr->intr_counter_GIRQ1++;
897		}
898		if (isr & ZR36057_ISR_GIRQ0) {
899			btwrite(ZR36057_ISR_GIRQ0, ZR36057_ISR);
900			zr->intr_counter_GIRQ0++;
901		}
902		if (isr & ZR36057_ISR_CodRepIRQ) {
903			btwrite(ZR36057_ISR_CodRepIRQ, ZR36057_ISR);
904			zr->intr_counter_CodRepIRQ++;
905		}
906		if (isr & ZR36057_ISR_JPEGRepIRQ) {
907			btwrite(ZR36057_ISR_JPEGRepIRQ, ZR36057_ISR);
908			zr->intr_counter_JPEGRepIRQ++;
909		}
910	}
911	return isr;
912}
913
914void
915jpeg_start (struct zoran *zr)
916{
917	int reg;
918
919	zr->frame_num = 0;
920
921	/* deassert P_reset, disable code transfer, deassert Active */
922	btwrite(ZR36057_JPC_P_Reset, ZR36057_JPC);
923	/* stop flushing the internal code buffer */
924	btand(~ZR36057_MCTCR_CFlush, ZR36057_MCTCR);
925	/* enable code transfer */
926	btor(ZR36057_JPC_CodTrnsEn, ZR36057_JPC);
927
928	/* clear IRQs */
929	btwrite(IRQ_MASK, ZR36057_ISR);
930	/* enable the JPEG IRQs */
931	btwrite(zr->card.jpeg_int |
932			ZR36057_ICR_JPEGRepIRQ |
933			ZR36057_ICR_IntPinEn,
934		ZR36057_ICR);
935
936	set_frame(zr, 0);	// \FRAME
937
938	/* set the JPEG codec guest ID */
939	reg = (zr->card.gpcs[1] << ZR36057_JCGI_JPEGuestID) |
940	       (0 << ZR36057_JCGI_JPEGuestReg);
941	btwrite(reg, ZR36057_JCGI);
942
943	if (zr->card.video_vfe == CODEC_TYPE_ZR36016 &&
944	    zr->card.video_codec == CODEC_TYPE_ZR36050) {
945		/* Enable processing on the ZR36016 */
946		if (zr->vfe)
947			zr36016_write(zr->vfe, 0, 1);
948
949		/* load the address of the GO register in the ZR36050 latch */
950		post_office_write(zr, 0, 0, 0);
951	}
952
953	/* assert Active */
954	btor(ZR36057_JPC_Active, ZR36057_JPC);
955
956	/* enable the Go generation */
957	btor(ZR36057_JMC_Go_en, ZR36057_JMC);
958	udelay(30);
959
960	set_frame(zr, 1);	// /FRAME
961
962	dprintk(3, KERN_DEBUG "%s: jpeg_start\n", ZR_DEVNAME(zr));
963}
964
965void
966zr36057_enable_jpg (struct zoran          *zr,
967		    enum zoran_codec_mode  mode)
968{
969	struct vfe_settings cap;
970	int field_size =
971	    zr->jpg_buffers.buffer_size / zr->jpg_settings.field_per_buff;
972
973	zr->codec_mode = mode;
974
975	cap.x = zr->jpg_settings.img_x;
976	cap.y = zr->jpg_settings.img_y;
977	cap.width = zr->jpg_settings.img_width;
978	cap.height = zr->jpg_settings.img_height;
979	cap.decimation =
980	    zr->jpg_settings.HorDcm | (zr->jpg_settings.VerDcm << 8);
981	cap.quality = zr->jpg_settings.jpg_comp.quality;
982
983	switch (mode) {
984
985	case BUZ_MODE_MOTION_COMPRESS: {
986		struct jpeg_app_marker app;
987		struct jpeg_com_marker com;
988
989		/* In motion compress mode, the decoder output must be enabled, and
990		 * the video bus direction set to input.
991		 */
992		set_videobus_dir(zr, 0);
993		decoder_call(zr, video, s_stream, 1);
994		encoder_call(zr, video, s_routing, 0, 0, 0);
995
996		/* Take the JPEG codec and the VFE out of sleep */
997		jpeg_codec_sleep(zr, 0);
998
999		/* set JPEG app/com marker */
1000		app.appn = zr->jpg_settings.jpg_comp.APPn;
1001		app.len = zr->jpg_settings.jpg_comp.APP_len;
1002		memcpy(app.data, zr->jpg_settings.jpg_comp.APP_data, 60);
1003		zr->codec->control(zr->codec, CODEC_S_JPEG_APP_DATA,
1004				   sizeof(struct jpeg_app_marker), &app);
1005
1006		com.len = zr->jpg_settings.jpg_comp.COM_len;
1007		memcpy(com.data, zr->jpg_settings.jpg_comp.COM_data, 60);
1008		zr->codec->control(zr->codec, CODEC_S_JPEG_COM_DATA,
1009				   sizeof(struct jpeg_com_marker), &com);
1010
1011		/* Setup the JPEG codec */
1012		zr->codec->control(zr->codec, CODEC_S_JPEG_TDS_BYTE,
1013				   sizeof(int), &field_size);
1014		zr->codec->set_video(zr->codec, zr->timing, &cap,
1015				     &zr->card.vfe_pol);
1016		zr->codec->set_mode(zr->codec, CODEC_DO_COMPRESSION);
1017
1018		/* Setup the VFE */
1019		if (zr->vfe) {
1020			zr->vfe->control(zr->vfe, CODEC_S_JPEG_TDS_BYTE,
1021					 sizeof(int), &field_size);
1022			zr->vfe->set_video(zr->vfe, zr->timing, &cap,
1023					   &zr->card.vfe_pol);
1024			zr->vfe->set_mode(zr->vfe, CODEC_DO_COMPRESSION);
1025		}
1026
1027		init_jpeg_queue(zr);
1028		zr36057_set_jpg(zr, mode);	// \P_Reset, ... Video param, FIFO
1029
1030		clear_interrupt_counters(zr);
1031		dprintk(2, KERN_INFO "%s: enable_jpg(MOTION_COMPRESS)\n",
1032			ZR_DEVNAME(zr));
1033		break;
1034	}
1035
1036	case BUZ_MODE_MOTION_DECOMPRESS:
1037		/* In motion decompression mode, the decoder output must be disabled, and
1038		 * the video bus direction set to output.
1039		 */
1040		decoder_call(zr, video, s_stream, 0);
1041		set_videobus_dir(zr, 1);
1042		encoder_call(zr, video, s_routing, 1, 0, 0);
1043
1044		/* Take the JPEG codec and the VFE out of sleep */
1045		jpeg_codec_sleep(zr, 0);
1046		/* Setup the VFE */
1047		if (zr->vfe) {
1048			zr->vfe->set_video(zr->vfe, zr->timing, &cap,
1049					   &zr->card.vfe_pol);
1050			zr->vfe->set_mode(zr->vfe, CODEC_DO_EXPANSION);
1051		}
1052		/* Setup the JPEG codec */
1053		zr->codec->set_video(zr->codec, zr->timing, &cap,
1054				     &zr->card.vfe_pol);
1055		zr->codec->set_mode(zr->codec, CODEC_DO_EXPANSION);
1056
1057		init_jpeg_queue(zr);
1058		zr36057_set_jpg(zr, mode);	// \P_Reset, ... Video param, FIFO
1059
1060		clear_interrupt_counters(zr);
1061		dprintk(2, KERN_INFO "%s: enable_jpg(MOTION_DECOMPRESS)\n",
1062			ZR_DEVNAME(zr));
1063		break;
1064
1065	case BUZ_MODE_IDLE:
1066	default:
1067		/* shut down processing */
1068		btand(~(zr->card.jpeg_int | ZR36057_ICR_JPEGRepIRQ),
1069		      ZR36057_ICR);
1070		btwrite(zr->card.jpeg_int | ZR36057_ICR_JPEGRepIRQ,
1071			ZR36057_ISR);
1072		btand(~ZR36057_JMC_Go_en, ZR36057_JMC);	// \Go_en
1073
1074		msleep(50);
1075
1076		set_videobus_dir(zr, 0);
1077		set_frame(zr, 1);	// /FRAME
1078		btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR);	// /CFlush
1079		btwrite(0, ZR36057_JPC);	// \P_Reset,\CodTrnsEn,\Active
1080		btand(~ZR36057_JMC_VFIFO_FB, ZR36057_JMC);
1081		btand(~ZR36057_JMC_SyncMstr, ZR36057_JMC);
1082		jpeg_codec_reset(zr);
1083		jpeg_codec_sleep(zr, 1);
1084		zr36057_adjust_vfe(zr, mode);
1085
1086		decoder_call(zr, video, s_stream, 1);
1087		encoder_call(zr, video, s_routing, 0, 0, 0);
1088
1089		dprintk(2, KERN_INFO "%s: enable_jpg(IDLE)\n", ZR_DEVNAME(zr));
1090		break;
1091
1092	}
1093}
1094
1095/* when this is called the spinlock must be held */
1096void
1097zoran_feed_stat_com (struct zoran *zr)
1098{
1099	/* move frames from pending queue to DMA */
1100
1101	int frame, i, max_stat_com;
1102
1103	max_stat_com =
1104	    (zr->jpg_settings.TmpDcm ==
1105	     1) ? BUZ_NUM_STAT_COM : (BUZ_NUM_STAT_COM >> 1);
1106
1107	while ((zr->jpg_dma_head - zr->jpg_dma_tail) < max_stat_com &&
1108	       zr->jpg_dma_head < zr->jpg_que_head) {
1109
1110		frame = zr->jpg_pend[zr->jpg_dma_head & BUZ_MASK_FRAME];
1111		if (zr->jpg_settings.TmpDcm == 1) {
1112			/* fill 1 stat_com entry */
1113			i = (zr->jpg_dma_head -
1114			     zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
1115			if (!(zr->stat_com[i] & cpu_to_le32(1)))
1116				break;
1117			zr->stat_com[i] =
1118			    cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
1119		} else {
1120			/* fill 2 stat_com entries */
1121			i = ((zr->jpg_dma_head -
1122			      zr->jpg_err_shift) & 1) * 2;
1123			if (!(zr->stat_com[i] & cpu_to_le32(1)))
1124				break;
1125			zr->stat_com[i] =
1126			    cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
1127			zr->stat_com[i + 1] =
1128			    cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
1129		}
1130		zr->jpg_buffers.buffer[frame].state = BUZ_STATE_DMA;
1131		zr->jpg_dma_head++;
1132
1133	}
1134	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS)
1135		zr->jpg_queued_num++;
1136}
1137
1138/* when this is called the spinlock must be held */
1139static void
1140zoran_reap_stat_com (struct zoran *zr)
1141{
1142	/* move frames from DMA queue to done queue */
1143
1144	int i;
1145	u32 stat_com;
1146	unsigned int seq;
1147	unsigned int dif;
1148	struct zoran_buffer *buffer;
1149	int frame;
1150
1151	/* In motion decompress we don't have a hardware frame counter,
1152	 * we just count the interrupts here */
1153
1154	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
1155		zr->jpg_seq_num++;
1156	}
1157	while (zr->jpg_dma_tail < zr->jpg_dma_head) {
1158		if (zr->jpg_settings.TmpDcm == 1)
1159			i = (zr->jpg_dma_tail -
1160			     zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
1161		else
1162			i = ((zr->jpg_dma_tail -
1163			      zr->jpg_err_shift) & 1) * 2 + 1;
1164
1165		stat_com = le32_to_cpu(zr->stat_com[i]);
1166
1167		if ((stat_com & 1) == 0) {
1168			return;
1169		}
1170		frame = zr->jpg_pend[zr->jpg_dma_tail & BUZ_MASK_FRAME];
1171		buffer = &zr->jpg_buffers.buffer[frame];
1172		v4l2_get_timestamp(&buffer->bs.timestamp);
1173
1174		if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
1175			buffer->bs.length = (stat_com & 0x7fffff) >> 1;
1176
1177			/* update sequence number with the help of the counter in stat_com */
1178
1179			seq = ((stat_com >> 24) + zr->jpg_err_seq) & 0xff;
1180			dif = (seq - zr->jpg_seq_num) & 0xff;
1181			zr->jpg_seq_num += dif;
1182		} else {
1183			buffer->bs.length = 0;
1184		}
1185		buffer->bs.seq =
1186		    zr->jpg_settings.TmpDcm ==
1187		    2 ? (zr->jpg_seq_num >> 1) : zr->jpg_seq_num;
1188		buffer->state = BUZ_STATE_DONE;
1189
1190		zr->jpg_dma_tail++;
1191	}
1192}
1193
1194static void zoran_restart(struct zoran *zr)
1195{
1196	/* Now the stat_comm buffer is ready for restart */
1197	unsigned int status = 0;
1198	int mode;
1199
1200	if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
1201		decoder_call(zr, video, g_input_status, &status);
1202		mode = CODEC_DO_COMPRESSION;
1203	} else {
1204		status = V4L2_IN_ST_NO_SIGNAL;
1205		mode = CODEC_DO_EXPANSION;
1206	}
1207	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
1208	    !(status & V4L2_IN_ST_NO_SIGNAL)) {
1209		/********** RESTART code *************/
1210		jpeg_codec_reset(zr);
1211		zr->codec->set_mode(zr->codec, mode);
1212		zr36057_set_jpg(zr, zr->codec_mode);
1213		jpeg_start(zr);
1214
1215		if (zr->num_errors <= 8)
1216			dprintk(2, KERN_INFO "%s: Restart\n",
1217				ZR_DEVNAME(zr));
1218
1219		zr->JPEG_missed = 0;
1220		zr->JPEG_error = 2;
1221		/********** End RESTART code ***********/
1222	}
1223}
1224
1225static void
1226error_handler (struct zoran *zr,
1227	       u32           astat,
1228	       u32           stat)
1229{
1230	int i;
1231
1232	/* This is JPEG error handling part */
1233	if (zr->codec_mode != BUZ_MODE_MOTION_COMPRESS &&
1234	    zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS) {
1235		return;
1236	}
1237
1238	if ((stat & 1) == 0 &&
1239	    zr->codec_mode == BUZ_MODE_MOTION_COMPRESS &&
1240	    zr->jpg_dma_tail - zr->jpg_que_tail >= zr->jpg_buffers.num_buffers) {
1241		/* No free buffers... */
1242		zoran_reap_stat_com(zr);
1243		zoran_feed_stat_com(zr);
1244		wake_up_interruptible(&zr->jpg_capq);
1245		zr->JPEG_missed = 0;
1246		return;
1247	}
1248
1249	if (zr->JPEG_error == 1) {
1250		zoran_restart(zr);
1251		return;
1252	}
1253
1254	/*
1255	 * First entry: error just happened during normal operation
1256	 *
1257	 * In BUZ_MODE_MOTION_COMPRESS:
1258	 *
1259	 * Possible glitch in TV signal. In this case we should
1260	 * stop the codec and wait for good quality signal before
1261	 * restarting it to avoid further problems
1262	 *
1263	 * In BUZ_MODE_MOTION_DECOMPRESS:
1264	 *
1265	 * Bad JPEG frame: we have to mark it as processed (codec crashed
1266	 * and was not able to do it itself), and to remove it from queue.
1267	 */
1268	btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
1269	udelay(1);
1270	stat = stat | (post_office_read(zr, 7, 0) & 3) << 8;
1271	btwrite(0, ZR36057_JPC);
1272	btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR);
1273	jpeg_codec_reset(zr);
1274	jpeg_codec_sleep(zr, 1);
1275	zr->JPEG_error = 1;
1276	zr->num_errors++;
1277
1278	/* Report error */
1279	if (zr36067_debug > 1 && zr->num_errors <= 8) {
1280		long frame;
1281		int j;
1282
1283		frame = zr->jpg_pend[zr->jpg_dma_tail & BUZ_MASK_FRAME];
1284		printk(KERN_ERR
1285		       "%s: JPEG error stat=0x%08x(0x%08x) queue_state=%ld/%ld/%ld/%ld seq=%ld frame=%ld. Codec stopped. ",
1286		       ZR_DEVNAME(zr), stat, zr->last_isr,
1287		       zr->jpg_que_tail, zr->jpg_dma_tail,
1288		       zr->jpg_dma_head, zr->jpg_que_head,
1289		       zr->jpg_seq_num, frame);
1290		printk(KERN_INFO "stat_com frames:");
1291		for (j = 0; j < BUZ_NUM_STAT_COM; j++) {
1292			for (i = 0; i < zr->jpg_buffers.num_buffers; i++) {
1293				if (le32_to_cpu(zr->stat_com[j]) == zr->jpg_buffers.buffer[i].jpg.frag_tab_bus)
1294					printk(KERN_CONT "% d->%d", j, i);
1295			}
1296		}
1297		printk(KERN_CONT "\n");
1298	}
1299	/* Find an entry in stat_com and rotate contents */
1300	if (zr->jpg_settings.TmpDcm == 1)
1301		i = (zr->jpg_dma_tail - zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
1302	else
1303		i = ((zr->jpg_dma_tail - zr->jpg_err_shift) & 1) * 2;
1304	if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
1305		/* Mimic zr36067 operation */
1306		zr->stat_com[i] |= cpu_to_le32(1);
1307		if (zr->jpg_settings.TmpDcm != 1)
1308			zr->stat_com[i + 1] |= cpu_to_le32(1);
1309		/* Refill */
1310		zoran_reap_stat_com(zr);
1311		zoran_feed_stat_com(zr);
1312		wake_up_interruptible(&zr->jpg_capq);
1313		/* Find an entry in stat_com again after refill */
1314		if (zr->jpg_settings.TmpDcm == 1)
1315			i = (zr->jpg_dma_tail - zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
1316		else
1317			i = ((zr->jpg_dma_tail - zr->jpg_err_shift) & 1) * 2;
1318	}
1319	if (i) {
1320		/* Rotate stat_comm entries to make current entry first */
1321		int j;
1322		__le32 bus_addr[BUZ_NUM_STAT_COM];
1323
1324		/* Here we are copying the stat_com array, which
1325		 * is already in little endian format, so
1326		 * no endian conversions here
1327		 */
1328		memcpy(bus_addr, zr->stat_com, sizeof(bus_addr));
1329
1330		for (j = 0; j < BUZ_NUM_STAT_COM; j++)
1331			zr->stat_com[j] = bus_addr[(i + j) & BUZ_MASK_STAT_COM];
1332
1333		zr->jpg_err_shift += i;
1334		zr->jpg_err_shift &= BUZ_MASK_STAT_COM;
1335	}
1336	if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)
1337		zr->jpg_err_seq = zr->jpg_seq_num;	/* + 1; */
1338	zoran_restart(zr);
1339}
1340
1341irqreturn_t
1342zoran_irq (int             irq,
1343	   void           *dev_id)
1344{
1345	u32 stat, astat;
1346	int count;
1347	struct zoran *zr;
1348	unsigned long flags;
1349
1350	zr = dev_id;
1351	count = 0;
1352
1353	if (zr->testing) {
1354		/* Testing interrupts */
1355		spin_lock_irqsave(&zr->spinlock, flags);
1356		while ((stat = count_reset_interrupt(zr))) {
1357			if (count++ > 100) {
1358				btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
1359				dprintk(1,
1360					KERN_ERR
1361					"%s: IRQ lockup while testing, isr=0x%08x, cleared int mask\n",
1362					ZR_DEVNAME(zr), stat);
1363				wake_up_interruptible(&zr->test_q);
1364			}
1365		}
1366		zr->last_isr = stat;
1367		spin_unlock_irqrestore(&zr->spinlock, flags);
1368		return IRQ_HANDLED;
1369	}
1370
1371	spin_lock_irqsave(&zr->spinlock, flags);
1372	while (1) {
1373		/* get/clear interrupt status bits */
1374		stat = count_reset_interrupt(zr);
1375		astat = stat & IRQ_MASK;
1376		if (!astat) {
1377			break;
1378		}
1379		dprintk(4,
1380			KERN_DEBUG
1381			"zoran_irq: astat: 0x%08x, mask: 0x%08x\n",
1382			astat, btread(ZR36057_ICR));
1383		if (astat & zr->card.vsync_int) {	// SW
1384
1385			if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
1386			    zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
1387				/* count missed interrupts */
1388				zr->JPEG_missed++;
1389			}
1390			//post_office_read(zr,1,0);
1391			/* Interrupts may still happen when
1392			 * zr->v4l_memgrab_active is switched off.
1393			 * We simply ignore them */
1394
1395			if (zr->v4l_memgrab_active) {
1396				/* A lot more checks should be here ... */
1397				if ((btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_SnapShot) == 0)
1398					dprintk(1,
1399						KERN_WARNING
1400						"%s: BuzIRQ with SnapShot off ???\n",
1401						ZR_DEVNAME(zr));
1402
1403				if (zr->v4l_grab_frame != NO_GRAB_ACTIVE) {
1404					/* There is a grab on a frame going on, check if it has finished */
1405					if ((btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_FrameGrab) == 0) {
1406						/* it is finished, notify the user */
1407
1408						zr->v4l_buffers.buffer[zr->v4l_grab_frame].state = BUZ_STATE_DONE;
1409						zr->v4l_buffers.buffer[zr->v4l_grab_frame].bs.seq = zr->v4l_grab_seq;
1410						v4l2_get_timestamp(&zr->v4l_buffers.buffer[zr->v4l_grab_frame].bs.timestamp);
1411						zr->v4l_grab_frame = NO_GRAB_ACTIVE;
1412						zr->v4l_pend_tail++;
1413					}
1414				}
1415
1416				if (zr->v4l_grab_frame == NO_GRAB_ACTIVE)
1417					wake_up_interruptible(&zr->v4l_capq);
1418
1419				/* Check if there is another grab queued */
1420
1421				if (zr->v4l_grab_frame == NO_GRAB_ACTIVE &&
1422				    zr->v4l_pend_tail != zr->v4l_pend_head) {
1423					int frame = zr->v4l_pend[zr->v4l_pend_tail & V4L_MASK_FRAME];
1424					u32 reg;
1425
1426					zr->v4l_grab_frame = frame;
1427
1428					/* Set zr36057 video front end and enable video */
1429
1430					/* Buffer address */
1431
1432					reg = zr->v4l_buffers.buffer[frame].v4l.fbuffer_bus;
1433					btwrite(reg, ZR36057_VDTR);
1434					if (zr->v4l_settings.height > BUZ_MAX_HEIGHT / 2)
1435						reg += zr->v4l_settings.bytesperline;
1436					btwrite(reg, ZR36057_VDBR);
1437
1438					/* video stride, status, and frame grab register */
1439					reg = 0;
1440					if (zr->v4l_settings.height > BUZ_MAX_HEIGHT / 2)
1441						reg += zr->v4l_settings.bytesperline;
1442					reg = (reg << ZR36057_VSSFGR_DispStride);
1443					reg |= ZR36057_VSSFGR_VidOvf;
1444					reg |= ZR36057_VSSFGR_SnapShot;
1445					reg |= ZR36057_VSSFGR_FrameGrab;
1446					btwrite(reg, ZR36057_VSSFGR);
1447
1448					btor(ZR36057_VDCR_VidEn,
1449					     ZR36057_VDCR);
1450				}
1451			}
1452
1453			/* even if we don't grab, we do want to increment
1454			 * the sequence counter to see lost frames */
1455			zr->v4l_grab_seq++;
1456		}
1457#if (IRQ_MASK & ZR36057_ISR_CodRepIRQ)
1458		if (astat & ZR36057_ISR_CodRepIRQ) {
1459			zr->intr_counter_CodRepIRQ++;
1460			IDEBUG(printk(KERN_DEBUG "%s: ZR36057_ISR_CodRepIRQ\n",
1461				ZR_DEVNAME(zr)));
1462			btand(~ZR36057_ICR_CodRepIRQ, ZR36057_ICR);
1463		}
1464#endif				/* (IRQ_MASK & ZR36057_ISR_CodRepIRQ) */
1465
1466#if (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ)
1467		if ((astat & ZR36057_ISR_JPEGRepIRQ) &&
1468		    (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
1469		     zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)) {
1470			if (zr36067_debug > 1 && (!zr->frame_num || zr->JPEG_error)) {
1471				char sv[BUZ_NUM_STAT_COM + 1];
1472				int i;
1473
1474				printk(KERN_INFO
1475				       "%s: first frame ready: state=0x%08x odd_even=%d field_per_buff=%d delay=%d\n",
1476				       ZR_DEVNAME(zr), stat,
1477				       zr->jpg_settings.odd_even,
1478				       zr->jpg_settings.field_per_buff,
1479				       zr->JPEG_missed);
1480
1481				for (i = 0; i < BUZ_NUM_STAT_COM; i++)
1482					sv[i] = le32_to_cpu(zr->stat_com[i]) & 1 ? '1' : '0';
1483				sv[BUZ_NUM_STAT_COM] = 0;
1484				printk(KERN_INFO
1485				       "%s: stat_com=%s queue_state=%ld/%ld/%ld/%ld\n",
1486				       ZR_DEVNAME(zr), sv,
1487				       zr->jpg_que_tail,
1488				       zr->jpg_dma_tail,
1489				       zr->jpg_dma_head,
1490				       zr->jpg_que_head);
1491			} else {
1492				/* Get statistics */
1493				if (zr->JPEG_missed > zr->JPEG_max_missed)
1494					zr->JPEG_max_missed = zr->JPEG_missed;
1495				if (zr->JPEG_missed < zr->JPEG_min_missed)
1496					zr->JPEG_min_missed = zr->JPEG_missed;
1497			}
1498
1499			if (zr36067_debug > 2 && zr->frame_num < 6) {
1500				int i;
1501
1502				printk(KERN_INFO "%s: seq=%ld stat_com:",
1503				       ZR_DEVNAME(zr), zr->jpg_seq_num);
1504				for (i = 0; i < 4; i++) {
1505					printk(KERN_CONT " %08x",
1506					       le32_to_cpu(zr->stat_com[i]));
1507				}
1508				printk(KERN_CONT "\n");
1509			}
1510			zr->frame_num++;
1511			zr->JPEG_missed = 0;
1512			zr->JPEG_error = 0;
1513			zoran_reap_stat_com(zr);
1514			zoran_feed_stat_com(zr);
1515			wake_up_interruptible(&zr->jpg_capq);
1516		}
1517#endif				/* (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ) */
1518
1519		/* DATERR, too many fields missed, error processing */
1520		if ((astat & zr->card.jpeg_int) ||
1521		    zr->JPEG_missed > 25 ||
1522		    zr->JPEG_error == 1	||
1523		    ((zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) &&
1524		     (zr->frame_num && (zr->JPEG_missed > zr->jpg_settings.field_per_buff)))) {
1525			error_handler(zr, astat, stat);
1526		}
1527
1528		count++;
1529		if (count > 10) {
1530			dprintk(2, KERN_WARNING "%s: irq loop %d\n",
1531				ZR_DEVNAME(zr), count);
1532			if (count > 20) {
1533				btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
1534				dprintk(2,
1535					KERN_ERR
1536					"%s: IRQ lockup, cleared int mask\n",
1537					ZR_DEVNAME(zr));
1538				break;
1539			}
1540		}
1541		zr->last_isr = stat;
1542	}
1543	spin_unlock_irqrestore(&zr->spinlock, flags);
1544
1545	return IRQ_HANDLED;
1546}
1547
1548void
1549zoran_set_pci_master (struct zoran *zr,
1550		      int           set_master)
1551{
1552	if (set_master) {
1553		pci_set_master(zr->pci_dev);
1554	} else {
1555		u16 command;
1556
1557		pci_read_config_word(zr->pci_dev, PCI_COMMAND, &command);
1558		command &= ~PCI_COMMAND_MASTER;
1559		pci_write_config_word(zr->pci_dev, PCI_COMMAND, command);
1560	}
1561}
1562
1563void
1564zoran_init_hardware (struct zoran *zr)
1565{
1566	/* Enable bus-mastering */
1567	zoran_set_pci_master(zr, 1);
1568
1569	/* Initialize the board */
1570	if (zr->card.init) {
1571		zr->card.init(zr);
1572	}
1573
1574	decoder_call(zr, core, init, 0);
1575	decoder_call(zr, video, s_std, zr->norm);
1576	decoder_call(zr, video, s_routing,
1577		zr->card.input[zr->input].muxsel, 0, 0);
1578
1579	encoder_call(zr, core, init, 0);
1580	encoder_call(zr, video, s_std_output, zr->norm);
1581	encoder_call(zr, video, s_routing, 0, 0, 0);
1582
1583	/* toggle JPEG codec sleep to sync PLL */
1584	jpeg_codec_sleep(zr, 1);
1585	jpeg_codec_sleep(zr, 0);
1586
1587	/* set individual interrupt enables (without GIRQ1)
1588	 * but don't global enable until zoran_open() */
1589
1590	//btwrite(IRQ_MASK & ~ZR36057_ISR_GIRQ1, ZR36057_ICR);  // SW
1591	// It looks like using only JPEGRepIRQEn is not always reliable,
1592	// may be when JPEG codec crashes it won't generate IRQ? So,
1593	 /*CP*/			//        btwrite(IRQ_MASK, ZR36057_ICR); // Enable Vsync interrupts too. SM    WHY ? LP
1594	    zr36057_init_vfe(zr);
1595
1596	zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1597
1598	btwrite(IRQ_MASK, ZR36057_ISR);	// Clears interrupts
1599}
1600
1601void
1602zr36057_restart (struct zoran *zr)
1603{
1604	btwrite(0, ZR36057_SPGPPCR);
1605	mdelay(1);
1606	btor(ZR36057_SPGPPCR_SoftReset, ZR36057_SPGPPCR);
1607	mdelay(1);
1608
1609	/* assert P_Reset */
1610	btwrite(0, ZR36057_JPC);
1611	/* set up GPIO direction - all output */
1612	btwrite(ZR36057_SPGPPCR_SoftReset | 0, ZR36057_SPGPPCR);
1613
1614	/* set up GPIO pins and guest bus timing */
1615	btwrite((0x81 << 24) | 0x8888, ZR36057_GPPGCR1);
1616}
1617
1618/*
1619 * initialize video front end
1620 */
1621
1622static void
1623zr36057_init_vfe (struct zoran *zr)
1624{
1625	u32 reg;
1626
1627	reg = btread(ZR36057_VFESPFR);
1628	reg |= ZR36057_VFESPFR_LittleEndian;
1629	reg &= ~ZR36057_VFESPFR_VCLKPol;
1630	reg |= ZR36057_VFESPFR_ExtFl;
1631	reg |= ZR36057_VFESPFR_TopField;
1632	btwrite(reg, ZR36057_VFESPFR);
1633	reg = btread(ZR36057_VDCR);
1634	if (pci_pci_problems & PCIPCI_TRITON)
1635		// || zr->revision < 1) // Revision 1 has also Triton support
1636		reg &= ~ZR36057_VDCR_Triton;
1637	else
1638		reg |= ZR36057_VDCR_Triton;
1639	btwrite(reg, ZR36057_VDCR);
1640}
1641