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