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