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