1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 
4     bttv - Bt848 frame grabber driver
5 
6     Copyright (C) 1996,97,98 Ralph  Metzler <rjkm@thp.uni-koeln.de>
7 			   & Marcus Metzler <mocm@thp.uni-koeln.de>
8     (c) 1999-2002 Gerd Knorr <kraxel@bytesex.org>
9 
10     some v4l2 code lines are taken from Justin's bttv2 driver which is
11     (c) 2000 Justin Schoeman <justin@suntiger.ee.up.ac.za>
12 
13     V4L1 removal from:
14     (c) 2005-2006 Nickolay V. Shmyrev <nshmyrev@yandex.ru>
15 
16     Fixes to be fully V4L2 compliant by
17     (c) 2006 Mauro Carvalho Chehab <mchehab@kernel.org>
18 
19     Cropping and overscan support
20     Copyright (C) 2005, 2006 Michael H. Schimek <mschimek@gmx.at>
21     Sponsored by OPQ Systems AB
22 
23 */
24 
25 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
26 
27 #include <linux/init.h>
28 #include <linux/module.h>
29 #include <linux/delay.h>
30 #include <linux/slab.h>
31 #include <linux/errno.h>
32 #include <linux/fs.h>
33 #include <linux/kernel.h>
34 #include <linux/sched.h>
35 #include <linux/interrupt.h>
36 #include <linux/kdev_t.h>
37 #include "bttvp.h"
38 #include <media/v4l2-common.h>
39 #include <media/v4l2-ioctl.h>
40 #include <media/v4l2-event.h>
41 #include <media/i2c/tvaudio.h>
42 #include <media/drv-intf/msp3400.h>
43 
44 #include <linux/dma-mapping.h>
45 
46 #include <asm/io.h>
47 #include <asm/byteorder.h>
48 
49 #include <media/i2c/saa6588.h>
50 
51 #define BTTV_VERSION "0.9.19"
52 
53 unsigned int bttv_num;			/* number of Bt848s in use */
54 struct bttv *bttvs[BTTV_MAX];
55 
56 unsigned int bttv_debug;
57 unsigned int bttv_verbose = 1;
58 unsigned int bttv_gpio;
59 
60 /* config variables */
61 #ifdef __BIG_ENDIAN
62 static unsigned int bigendian=1;
63 #else
64 static unsigned int bigendian;
65 #endif
66 static unsigned int radio[BTTV_MAX];
67 static unsigned int irq_debug;
68 static unsigned int gbuffers = 8;
69 static unsigned int gbufsize = 0x208000;
70 static unsigned int reset_crop = 1;
71 
72 static int video_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
73 static int radio_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
74 static int vbi_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
75 static int debug_latency;
76 static int disable_ir;
77 
78 static unsigned int fdsr;
79 
80 /* options */
81 static unsigned int combfilter;
82 static unsigned int lumafilter;
83 static unsigned int automute    = 1;
84 static unsigned int chroma_agc;
85 static unsigned int agc_crush   = 1;
86 static unsigned int whitecrush_upper = 0xCF;
87 static unsigned int whitecrush_lower = 0x7F;
88 static unsigned int vcr_hack;
89 static unsigned int irq_iswitch;
90 static unsigned int uv_ratio    = 50;
91 static unsigned int full_luma_range;
92 static unsigned int coring;
93 
94 /* API features (turn on/off stuff for testing) */
95 static unsigned int v4l2        = 1;
96 
97 /* insmod args */
98 module_param(bttv_verbose,      int, 0644);
99 module_param(bttv_gpio,         int, 0644);
100 module_param(bttv_debug,        int, 0644);
101 module_param(irq_debug,         int, 0644);
102 module_param(debug_latency,     int, 0644);
103 module_param(disable_ir,        int, 0444);
104 
105 module_param(fdsr,              int, 0444);
106 module_param(gbuffers,          int, 0444);
107 module_param(gbufsize,          int, 0444);
108 module_param(reset_crop,        int, 0444);
109 
110 module_param(v4l2,              int, 0644);
111 module_param(bigendian,         int, 0644);
112 module_param(irq_iswitch,       int, 0644);
113 module_param(combfilter,        int, 0444);
114 module_param(lumafilter,        int, 0444);
115 module_param(automute,          int, 0444);
116 module_param(chroma_agc,        int, 0444);
117 module_param(agc_crush,         int, 0444);
118 module_param(whitecrush_upper,  int, 0444);
119 module_param(whitecrush_lower,  int, 0444);
120 module_param(vcr_hack,          int, 0444);
121 module_param(uv_ratio,          int, 0444);
122 module_param(full_luma_range,   int, 0444);
123 module_param(coring,            int, 0444);
124 
125 module_param_array(radio,       int, NULL, 0444);
126 module_param_array(video_nr,    int, NULL, 0444);
127 module_param_array(radio_nr,    int, NULL, 0444);
128 module_param_array(vbi_nr,      int, NULL, 0444);
129 
130 MODULE_PARM_DESC(radio, "The TV card supports radio, default is 0 (no)");
131 MODULE_PARM_DESC(bigendian, "byte order of the framebuffer, default is native endian");
132 MODULE_PARM_DESC(bttv_verbose, "verbose startup messages, default is 1 (yes)");
133 MODULE_PARM_DESC(bttv_gpio, "log gpio changes, default is 0 (no)");
134 MODULE_PARM_DESC(bttv_debug, "debug messages, default is 0 (no)");
135 MODULE_PARM_DESC(irq_debug, "irq handler debug messages, default is 0 (no)");
136 MODULE_PARM_DESC(disable_ir, "disable infrared remote support");
137 MODULE_PARM_DESC(gbuffers, "number of capture buffers. range 2-32, default 8");
138 MODULE_PARM_DESC(gbufsize, "size of the capture buffers, default is 0x208000");
139 MODULE_PARM_DESC(reset_crop, "reset cropping parameters at open(), default is 1 (yes) for compatibility with older applications");
140 MODULE_PARM_DESC(automute, "mute audio on bad/missing video signal, default is 1 (yes)");
141 MODULE_PARM_DESC(chroma_agc, "enables the AGC of chroma signal, default is 0 (no)");
142 MODULE_PARM_DESC(agc_crush, "enables the luminance AGC crush, default is 1 (yes)");
143 MODULE_PARM_DESC(whitecrush_upper, "sets the white crush upper value, default is 207");
144 MODULE_PARM_DESC(whitecrush_lower, "sets the white crush lower value, default is 127");
145 MODULE_PARM_DESC(vcr_hack, "enables the VCR hack (improves synch on poor VCR tapes), default is 0 (no)");
146 MODULE_PARM_DESC(irq_iswitch, "switch inputs in irq handler");
147 MODULE_PARM_DESC(uv_ratio, "ratio between u and v gains, default is 50");
148 MODULE_PARM_DESC(full_luma_range, "use the full luma range, default is 0 (no)");
149 MODULE_PARM_DESC(coring, "set the luma coring level, default is 0 (no)");
150 MODULE_PARM_DESC(video_nr, "video device numbers");
151 MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
152 MODULE_PARM_DESC(radio_nr, "radio device numbers");
153 
154 MODULE_DESCRIPTION("bttv - v4l/v4l2 driver module for bt848/878 based cards");
155 MODULE_AUTHOR("Ralph Metzler & Marcus Metzler & Gerd Knorr");
156 MODULE_LICENSE("GPL");
157 MODULE_VERSION(BTTV_VERSION);
158 
159 #define V4L2_CID_PRIVATE_COMBFILTER		(V4L2_CID_USER_BTTV_BASE + 0)
160 #define V4L2_CID_PRIVATE_AUTOMUTE		(V4L2_CID_USER_BTTV_BASE + 1)
161 #define V4L2_CID_PRIVATE_LUMAFILTER		(V4L2_CID_USER_BTTV_BASE + 2)
162 #define V4L2_CID_PRIVATE_AGC_CRUSH		(V4L2_CID_USER_BTTV_BASE + 3)
163 #define V4L2_CID_PRIVATE_VCR_HACK		(V4L2_CID_USER_BTTV_BASE + 4)
164 #define V4L2_CID_PRIVATE_WHITECRUSH_LOWER	(V4L2_CID_USER_BTTV_BASE + 5)
165 #define V4L2_CID_PRIVATE_WHITECRUSH_UPPER	(V4L2_CID_USER_BTTV_BASE + 6)
166 #define V4L2_CID_PRIVATE_UV_RATIO		(V4L2_CID_USER_BTTV_BASE + 7)
167 #define V4L2_CID_PRIVATE_FULL_LUMA_RANGE	(V4L2_CID_USER_BTTV_BASE + 8)
168 #define V4L2_CID_PRIVATE_CORING			(V4L2_CID_USER_BTTV_BASE + 9)
169 
170 /* ----------------------------------------------------------------------- */
171 /* sysfs                                                                   */
172 
173 static ssize_t show_card(struct device *cd,
174 			 struct device_attribute *attr, char *buf)
175 {
176 	struct video_device *vfd = to_video_device(cd);
177 	struct bttv *btv = video_get_drvdata(vfd);
178 	return sprintf(buf, "%d\n", btv ? btv->c.type : UNSET);
179 }
180 static DEVICE_ATTR(card, S_IRUGO, show_card, NULL);
181 
182 /* ----------------------------------------------------------------------- */
183 /* dvb auto-load setup                                                     */
184 #if defined(CONFIG_MODULES) && defined(MODULE)
185 static void request_module_async(struct work_struct *work)
186 {
187 	request_module("dvb-bt8xx");
188 }
189 
190 static void request_modules(struct bttv *dev)
191 {
192 	INIT_WORK(&dev->request_module_wk, request_module_async);
193 	schedule_work(&dev->request_module_wk);
194 }
195 
196 static void flush_request_modules(struct bttv *dev)
197 {
198 	flush_work(&dev->request_module_wk);
199 }
200 #else
201 #define request_modules(dev)
202 #define flush_request_modules(dev) do {} while(0)
203 #endif /* CONFIG_MODULES */
204 
205 
206 /* ----------------------------------------------------------------------- */
207 /* static data                                                             */
208 
209 /* special timing tables from conexant... */
210 static u8 SRAM_Table[][60] =
211 {
212 	/* PAL digital input over GPIO[7:0] */
213 	{
214 		45, // 45 bytes following
215 		0x36,0x11,0x01,0x00,0x90,0x02,0x05,0x10,0x04,0x16,
216 		0x12,0x05,0x11,0x00,0x04,0x12,0xC0,0x00,0x31,0x00,
217 		0x06,0x51,0x08,0x03,0x89,0x08,0x07,0xC0,0x44,0x00,
218 		0x81,0x01,0x01,0xA9,0x0D,0x02,0x02,0x50,0x03,0x37,
219 		0x37,0x00,0xAF,0x21,0x00
220 	},
221 	/* NTSC digital input over GPIO[7:0] */
222 	{
223 		51, // 51 bytes following
224 		0x0C,0xC0,0x00,0x00,0x90,0x02,0x03,0x10,0x03,0x06,
225 		0x10,0x04,0x12,0x12,0x05,0x02,0x13,0x04,0x19,0x00,
226 		0x04,0x39,0x00,0x06,0x59,0x08,0x03,0x83,0x08,0x07,
227 		0x03,0x50,0x00,0xC0,0x40,0x00,0x86,0x01,0x01,0xA6,
228 		0x0D,0x02,0x03,0x11,0x01,0x05,0x37,0x00,0xAC,0x21,
229 		0x00,
230 	},
231 	// TGB_NTSC392 // quartzsight
232 	// This table has been modified to be used for Fusion Rev D
233 	{
234 		0x2A, // size of table = 42
235 		0x06, 0x08, 0x04, 0x0a, 0xc0, 0x00, 0x18, 0x08, 0x03, 0x24,
236 		0x08, 0x07, 0x02, 0x90, 0x02, 0x08, 0x10, 0x04, 0x0c, 0x10,
237 		0x05, 0x2c, 0x11, 0x04, 0x55, 0x48, 0x00, 0x05, 0x50, 0x00,
238 		0xbf, 0x0c, 0x02, 0x2f, 0x3d, 0x00, 0x2f, 0x3f, 0x00, 0xc3,
239 		0x20, 0x00
240 	}
241 };
242 
243 /* minhdelayx1	first video pixel we can capture on a line and
244    hdelayx1	start of active video, both relative to rising edge of
245 		/HRESET pulse (0H) in 1 / fCLKx1.
246    swidth	width of active video and
247    totalwidth	total line width, both in 1 / fCLKx1.
248    sqwidth	total line width in square pixels.
249    vdelay	start of active video in 2 * field lines relative to
250 		trailing edge of /VRESET pulse (VDELAY register).
251    sheight	height of active video in 2 * field lines.
252    extraheight	Added to sheight for cropcap.bounds.height only
253    videostart0	ITU-R frame line number of the line corresponding
254 		to vdelay in the first field. */
255 #define CROPCAP(minhdelayx1, hdelayx1, swidth, totalwidth, sqwidth,	 \
256 		vdelay, sheight, extraheight, videostart0)		 \
257 	.cropcap.bounds.left = minhdelayx1,				 \
258 	/* * 2 because vertically we count field lines times two, */	 \
259 	/* e.g. 23 * 2 to 23 * 2 + 576 in PAL-BGHI defrect. */		 \
260 	.cropcap.bounds.top = (videostart0) * 2 - (vdelay) + MIN_VDELAY, \
261 	/* 4 is a safety margin at the end of the line. */		 \
262 	.cropcap.bounds.width = (totalwidth) - (minhdelayx1) - 4,	 \
263 	.cropcap.bounds.height = (sheight) + (extraheight) + (vdelay) -	 \
264 				 MIN_VDELAY,				 \
265 	.cropcap.defrect.left = hdelayx1,				 \
266 	.cropcap.defrect.top = (videostart0) * 2,			 \
267 	.cropcap.defrect.width = swidth,				 \
268 	.cropcap.defrect.height = sheight,				 \
269 	.cropcap.pixelaspect.numerator = totalwidth,			 \
270 	.cropcap.pixelaspect.denominator = sqwidth,
271 
272 const struct bttv_tvnorm bttv_tvnorms[] = {
273 	/* PAL-BDGHI */
274 	/* max. active video is actually 922, but 924 is divisible by 4 and 3! */
275 	/* actually, max active PAL with HSCALE=0 is 948, NTSC is 768 - nil */
276 	{
277 		.v4l2_id        = V4L2_STD_PAL,
278 		.name           = "PAL",
279 		.Fsc            = 35468950,
280 		.swidth         = 924,
281 		.sheight        = 576,
282 		.totalwidth     = 1135,
283 		.adelay         = 0x7f,
284 		.bdelay         = 0x72,
285 		.iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
286 		.scaledtwidth   = 1135,
287 		.hdelayx1       = 186,
288 		.hactivex1      = 924,
289 		.vdelay         = 0x20,
290 		.vbipack        = 255, /* min (2048 / 4, 0x1ff) & 0xff */
291 		.sram           = 0,
292 		/* ITU-R frame line number of the first VBI line
293 		   we can capture, of the first and second field.
294 		   The last line is determined by cropcap.bounds. */
295 		.vbistart       = { 7, 320 },
296 		CROPCAP(/* minhdelayx1 */ 68,
297 			/* hdelayx1 */ 186,
298 			/* Should be (768 * 1135 + 944 / 2) / 944.
299 			   cropcap.defrect is used for image width
300 			   checks, so we keep the old value 924. */
301 			/* swidth */ 924,
302 			/* totalwidth */ 1135,
303 			/* sqwidth */ 944,
304 			/* vdelay */ 0x20,
305 			/* sheight */ 576,
306 			/* bt878 (and bt848?) can capture another
307 			   line below active video. */
308 			/* extraheight */ 2,
309 			/* videostart0 */ 23)
310 	},{
311 		.v4l2_id        = V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_KR,
312 		.name           = "NTSC",
313 		.Fsc            = 28636363,
314 		.swidth         = 768,
315 		.sheight        = 480,
316 		.totalwidth     = 910,
317 		.adelay         = 0x68,
318 		.bdelay         = 0x5d,
319 		.iform          = (BT848_IFORM_NTSC|BT848_IFORM_XT0),
320 		.scaledtwidth   = 910,
321 		.hdelayx1       = 128,
322 		.hactivex1      = 910,
323 		.vdelay         = 0x1a,
324 		.vbipack        = 144, /* min (1600 / 4, 0x1ff) & 0xff */
325 		.sram           = 1,
326 		.vbistart	= { 10, 273 },
327 		CROPCAP(/* minhdelayx1 */ 68,
328 			/* hdelayx1 */ 128,
329 			/* Should be (640 * 910 + 780 / 2) / 780? */
330 			/* swidth */ 768,
331 			/* totalwidth */ 910,
332 			/* sqwidth */ 780,
333 			/* vdelay */ 0x1a,
334 			/* sheight */ 480,
335 			/* extraheight */ 0,
336 			/* videostart0 */ 23)
337 	},{
338 		.v4l2_id        = V4L2_STD_SECAM,
339 		.name           = "SECAM",
340 		.Fsc            = 35468950,
341 		.swidth         = 924,
342 		.sheight        = 576,
343 		.totalwidth     = 1135,
344 		.adelay         = 0x7f,
345 		.bdelay         = 0xb0,
346 		.iform          = (BT848_IFORM_SECAM|BT848_IFORM_XT1),
347 		.scaledtwidth   = 1135,
348 		.hdelayx1       = 186,
349 		.hactivex1      = 922,
350 		.vdelay         = 0x20,
351 		.vbipack        = 255,
352 		.sram           = 0, /* like PAL, correct? */
353 		.vbistart	= { 7, 320 },
354 		CROPCAP(/* minhdelayx1 */ 68,
355 			/* hdelayx1 */ 186,
356 			/* swidth */ 924,
357 			/* totalwidth */ 1135,
358 			/* sqwidth */ 944,
359 			/* vdelay */ 0x20,
360 			/* sheight */ 576,
361 			/* extraheight */ 0,
362 			/* videostart0 */ 23)
363 	},{
364 		.v4l2_id        = V4L2_STD_PAL_Nc,
365 		.name           = "PAL-Nc",
366 		.Fsc            = 28636363,
367 		.swidth         = 640,
368 		.sheight        = 576,
369 		.totalwidth     = 910,
370 		.adelay         = 0x68,
371 		.bdelay         = 0x5d,
372 		.iform          = (BT848_IFORM_PAL_NC|BT848_IFORM_XT0),
373 		.scaledtwidth   = 780,
374 		.hdelayx1       = 130,
375 		.hactivex1      = 734,
376 		.vdelay         = 0x1a,
377 		.vbipack        = 144,
378 		.sram           = -1,
379 		.vbistart	= { 7, 320 },
380 		CROPCAP(/* minhdelayx1 */ 68,
381 			/* hdelayx1 */ 130,
382 			/* swidth */ (640 * 910 + 780 / 2) / 780,
383 			/* totalwidth */ 910,
384 			/* sqwidth */ 780,
385 			/* vdelay */ 0x1a,
386 			/* sheight */ 576,
387 			/* extraheight */ 0,
388 			/* videostart0 */ 23)
389 	},{
390 		.v4l2_id        = V4L2_STD_PAL_M,
391 		.name           = "PAL-M",
392 		.Fsc            = 28636363,
393 		.swidth         = 640,
394 		.sheight        = 480,
395 		.totalwidth     = 910,
396 		.adelay         = 0x68,
397 		.bdelay         = 0x5d,
398 		.iform          = (BT848_IFORM_PAL_M|BT848_IFORM_XT0),
399 		.scaledtwidth   = 780,
400 		.hdelayx1       = 135,
401 		.hactivex1      = 754,
402 		.vdelay         = 0x1a,
403 		.vbipack        = 144,
404 		.sram           = -1,
405 		.vbistart	= { 10, 273 },
406 		CROPCAP(/* minhdelayx1 */ 68,
407 			/* hdelayx1 */ 135,
408 			/* swidth */ (640 * 910 + 780 / 2) / 780,
409 			/* totalwidth */ 910,
410 			/* sqwidth */ 780,
411 			/* vdelay */ 0x1a,
412 			/* sheight */ 480,
413 			/* extraheight */ 0,
414 			/* videostart0 */ 23)
415 	},{
416 		.v4l2_id        = V4L2_STD_PAL_N,
417 		.name           = "PAL-N",
418 		.Fsc            = 35468950,
419 		.swidth         = 768,
420 		.sheight        = 576,
421 		.totalwidth     = 1135,
422 		.adelay         = 0x7f,
423 		.bdelay         = 0x72,
424 		.iform          = (BT848_IFORM_PAL_N|BT848_IFORM_XT1),
425 		.scaledtwidth   = 944,
426 		.hdelayx1       = 186,
427 		.hactivex1      = 922,
428 		.vdelay         = 0x20,
429 		.vbipack        = 144,
430 		.sram           = -1,
431 		.vbistart       = { 7, 320 },
432 		CROPCAP(/* minhdelayx1 */ 68,
433 			/* hdelayx1 */ 186,
434 			/* swidth */ (768 * 1135 + 944 / 2) / 944,
435 			/* totalwidth */ 1135,
436 			/* sqwidth */ 944,
437 			/* vdelay */ 0x20,
438 			/* sheight */ 576,
439 			/* extraheight */ 0,
440 			/* videostart0 */ 23)
441 	},{
442 		.v4l2_id        = V4L2_STD_NTSC_M_JP,
443 		.name           = "NTSC-JP",
444 		.Fsc            = 28636363,
445 		.swidth         = 640,
446 		.sheight        = 480,
447 		.totalwidth     = 910,
448 		.adelay         = 0x68,
449 		.bdelay         = 0x5d,
450 		.iform          = (BT848_IFORM_NTSC_J|BT848_IFORM_XT0),
451 		.scaledtwidth   = 780,
452 		.hdelayx1       = 135,
453 		.hactivex1      = 754,
454 		.vdelay         = 0x16,
455 		.vbipack        = 144,
456 		.sram           = -1,
457 		.vbistart       = { 10, 273 },
458 		CROPCAP(/* minhdelayx1 */ 68,
459 			/* hdelayx1 */ 135,
460 			/* swidth */ (640 * 910 + 780 / 2) / 780,
461 			/* totalwidth */ 910,
462 			/* sqwidth */ 780,
463 			/* vdelay */ 0x16,
464 			/* sheight */ 480,
465 			/* extraheight */ 0,
466 			/* videostart0 */ 23)
467 	},{
468 		/* that one hopefully works with the strange timing
469 		 * which video recorders produce when playing a NTSC
470 		 * tape on a PAL TV ... */
471 		.v4l2_id        = V4L2_STD_PAL_60,
472 		.name           = "PAL-60",
473 		.Fsc            = 35468950,
474 		.swidth         = 924,
475 		.sheight        = 480,
476 		.totalwidth     = 1135,
477 		.adelay         = 0x7f,
478 		.bdelay         = 0x72,
479 		.iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
480 		.scaledtwidth   = 1135,
481 		.hdelayx1       = 186,
482 		.hactivex1      = 924,
483 		.vdelay         = 0x1a,
484 		.vbipack        = 255,
485 		.vtotal         = 524,
486 		.sram           = -1,
487 		.vbistart	= { 10, 273 },
488 		CROPCAP(/* minhdelayx1 */ 68,
489 			/* hdelayx1 */ 186,
490 			/* swidth */ 924,
491 			/* totalwidth */ 1135,
492 			/* sqwidth */ 944,
493 			/* vdelay */ 0x1a,
494 			/* sheight */ 480,
495 			/* extraheight */ 0,
496 			/* videostart0 */ 23)
497 	}
498 };
499 static const unsigned int BTTV_TVNORMS = ARRAY_SIZE(bttv_tvnorms);
500 
501 /* ----------------------------------------------------------------------- */
502 /* bttv format list
503    packed pixel formats must come first */
504 static const struct bttv_format formats[] = {
505 	{
506 		.name     = "8 bpp, gray",
507 		.fourcc   = V4L2_PIX_FMT_GREY,
508 		.btformat = BT848_COLOR_FMT_Y8,
509 		.depth    = 8,
510 		.flags    = FORMAT_FLAGS_PACKED,
511 	},{
512 		.name     = "8 bpp, dithered color",
513 		.fourcc   = V4L2_PIX_FMT_HI240,
514 		.btformat = BT848_COLOR_FMT_RGB8,
515 		.depth    = 8,
516 		.flags    = FORMAT_FLAGS_PACKED | FORMAT_FLAGS_DITHER,
517 	},{
518 		.name     = "15 bpp RGB, le",
519 		.fourcc   = V4L2_PIX_FMT_RGB555,
520 		.btformat = BT848_COLOR_FMT_RGB15,
521 		.depth    = 16,
522 		.flags    = FORMAT_FLAGS_PACKED,
523 	},{
524 		.name     = "15 bpp RGB, be",
525 		.fourcc   = V4L2_PIX_FMT_RGB555X,
526 		.btformat = BT848_COLOR_FMT_RGB15,
527 		.btswap   = 0x03, /* byteswap */
528 		.depth    = 16,
529 		.flags    = FORMAT_FLAGS_PACKED,
530 	},{
531 		.name     = "16 bpp RGB, le",
532 		.fourcc   = V4L2_PIX_FMT_RGB565,
533 		.btformat = BT848_COLOR_FMT_RGB16,
534 		.depth    = 16,
535 		.flags    = FORMAT_FLAGS_PACKED,
536 	},{
537 		.name     = "16 bpp RGB, be",
538 		.fourcc   = V4L2_PIX_FMT_RGB565X,
539 		.btformat = BT848_COLOR_FMT_RGB16,
540 		.btswap   = 0x03, /* byteswap */
541 		.depth    = 16,
542 		.flags    = FORMAT_FLAGS_PACKED,
543 	},{
544 		.name     = "24 bpp RGB, le",
545 		.fourcc   = V4L2_PIX_FMT_BGR24,
546 		.btformat = BT848_COLOR_FMT_RGB24,
547 		.depth    = 24,
548 		.flags    = FORMAT_FLAGS_PACKED,
549 	},{
550 		.name     = "32 bpp RGB, le",
551 		.fourcc   = V4L2_PIX_FMT_BGR32,
552 		.btformat = BT848_COLOR_FMT_RGB32,
553 		.depth    = 32,
554 		.flags    = FORMAT_FLAGS_PACKED,
555 	},{
556 		.name     = "32 bpp RGB, be",
557 		.fourcc   = V4L2_PIX_FMT_RGB32,
558 		.btformat = BT848_COLOR_FMT_RGB32,
559 		.btswap   = 0x0f, /* byte+word swap */
560 		.depth    = 32,
561 		.flags    = FORMAT_FLAGS_PACKED,
562 	},{
563 		.name     = "4:2:2, packed, YUYV",
564 		.fourcc   = V4L2_PIX_FMT_YUYV,
565 		.btformat = BT848_COLOR_FMT_YUY2,
566 		.depth    = 16,
567 		.flags    = FORMAT_FLAGS_PACKED,
568 	},{
569 		.name     = "4:2:2, packed, UYVY",
570 		.fourcc   = V4L2_PIX_FMT_UYVY,
571 		.btformat = BT848_COLOR_FMT_YUY2,
572 		.btswap   = 0x03, /* byteswap */
573 		.depth    = 16,
574 		.flags    = FORMAT_FLAGS_PACKED,
575 	},{
576 		.name     = "4:2:2, planar, Y-Cb-Cr",
577 		.fourcc   = V4L2_PIX_FMT_YUV422P,
578 		.btformat = BT848_COLOR_FMT_YCrCb422,
579 		.depth    = 16,
580 		.flags    = FORMAT_FLAGS_PLANAR,
581 		.hshift   = 1,
582 		.vshift   = 0,
583 	},{
584 		.name     = "4:2:0, planar, Y-Cb-Cr",
585 		.fourcc   = V4L2_PIX_FMT_YUV420,
586 		.btformat = BT848_COLOR_FMT_YCrCb422,
587 		.depth    = 12,
588 		.flags    = FORMAT_FLAGS_PLANAR,
589 		.hshift   = 1,
590 		.vshift   = 1,
591 	},{
592 		.name     = "4:2:0, planar, Y-Cr-Cb",
593 		.fourcc   = V4L2_PIX_FMT_YVU420,
594 		.btformat = BT848_COLOR_FMT_YCrCb422,
595 		.depth    = 12,
596 		.flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
597 		.hshift   = 1,
598 		.vshift   = 1,
599 	},{
600 		.name     = "4:1:1, planar, Y-Cb-Cr",
601 		.fourcc   = V4L2_PIX_FMT_YUV411P,
602 		.btformat = BT848_COLOR_FMT_YCrCb411,
603 		.depth    = 12,
604 		.flags    = FORMAT_FLAGS_PLANAR,
605 		.hshift   = 2,
606 		.vshift   = 0,
607 	},{
608 		.name     = "4:1:0, planar, Y-Cb-Cr",
609 		.fourcc   = V4L2_PIX_FMT_YUV410,
610 		.btformat = BT848_COLOR_FMT_YCrCb411,
611 		.depth    = 9,
612 		.flags    = FORMAT_FLAGS_PLANAR,
613 		.hshift   = 2,
614 		.vshift   = 2,
615 	},{
616 		.name     = "4:1:0, planar, Y-Cr-Cb",
617 		.fourcc   = V4L2_PIX_FMT_YVU410,
618 		.btformat = BT848_COLOR_FMT_YCrCb411,
619 		.depth    = 9,
620 		.flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
621 		.hshift   = 2,
622 		.vshift   = 2,
623 	},{
624 		.name     = "raw scanlines",
625 		.fourcc   = -1,
626 		.btformat = BT848_COLOR_FMT_RAW,
627 		.depth    = 8,
628 		.flags    = FORMAT_FLAGS_RAW,
629 	}
630 };
631 static const unsigned int FORMATS = ARRAY_SIZE(formats);
632 
633 /* ----------------------------------------------------------------------- */
634 /* resource management                                                     */
635 
636 /*
637    RESOURCE_    allocated by                freed by
638 
639    VIDEO_READ   bttv_read 1)                bttv_read 2)
640 
641    VIDEO_STREAM VIDIOC_STREAMON             VIDIOC_STREAMOFF
642 		 VIDIOC_QBUF 1)              bttv_release
643 		 VIDIOCMCAPTURE 1)
644 
645    OVERLAY	 VIDIOCCAPTURE on            VIDIOCCAPTURE off
646 		 VIDIOC_OVERLAY on           VIDIOC_OVERLAY off
647 		 3)                          bttv_release
648 
649    VBI		 VIDIOC_STREAMON             VIDIOC_STREAMOFF
650 		 VIDIOC_QBUF 1)              bttv_release
651 		 bttv_read, bttv_poll 1) 4)
652 
653    1) The resource must be allocated when we enter buffer prepare functions
654       and remain allocated while buffers are in the DMA queue.
655    2) This is a single frame read.
656    3) VIDIOC_S_FBUF and VIDIOC_S_FMT (OVERLAY) still work when
657       RESOURCE_OVERLAY is allocated.
658    4) This is a continuous read, implies VIDIOC_STREAMON.
659 
660    Note this driver permits video input and standard changes regardless if
661    resources are allocated.
662 */
663 
664 #define VBI_RESOURCES (RESOURCE_VBI)
665 #define VIDEO_RESOURCES (RESOURCE_VIDEO_READ | \
666 			 RESOURCE_VIDEO_STREAM | \
667 			 RESOURCE_OVERLAY)
668 
669 static
670 int check_alloc_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bit)
671 {
672 	int xbits; /* mutual exclusive resources */
673 
674 	if (fh->resources & bit)
675 		/* have it already allocated */
676 		return 1;
677 
678 	xbits = bit;
679 	if (bit & (RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM))
680 		xbits |= RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM;
681 
682 	/* is it free? */
683 	if (btv->resources & xbits) {
684 		/* no, someone else uses it */
685 		goto fail;
686 	}
687 
688 	if ((bit & VIDEO_RESOURCES)
689 	    && 0 == (btv->resources & VIDEO_RESOURCES)) {
690 		/* Do crop - use current, don't - use default parameters. */
691 		__s32 top = btv->crop[!!fh->do_crop].rect.top;
692 
693 		if (btv->vbi_end > top)
694 			goto fail;
695 
696 		/* We cannot capture the same line as video and VBI data.
697 		   Claim scan lines crop[].rect.top to bottom. */
698 		btv->crop_start = top;
699 	} else if (bit & VBI_RESOURCES) {
700 		__s32 end = fh->vbi_fmt.end;
701 
702 		if (end > btv->crop_start)
703 			goto fail;
704 
705 		/* Claim scan lines above fh->vbi_fmt.end. */
706 		btv->vbi_end = end;
707 	}
708 
709 	/* it's free, grab it */
710 	fh->resources  |= bit;
711 	btv->resources |= bit;
712 	return 1;
713 
714  fail:
715 	return 0;
716 }
717 
718 static
719 int check_btres(struct bttv_fh *fh, int bit)
720 {
721 	return (fh->resources & bit);
722 }
723 
724 static
725 int locked_btres(struct bttv *btv, int bit)
726 {
727 	return (btv->resources & bit);
728 }
729 
730 /* Call with btv->lock down. */
731 static void
732 disclaim_vbi_lines(struct bttv *btv)
733 {
734 	btv->vbi_end = 0;
735 }
736 
737 /* Call with btv->lock down. */
738 static void
739 disclaim_video_lines(struct bttv *btv)
740 {
741 	const struct bttv_tvnorm *tvnorm;
742 	u8 crop;
743 
744 	tvnorm = &bttv_tvnorms[btv->tvnorm];
745 	btv->crop_start = tvnorm->cropcap.bounds.top
746 		+ tvnorm->cropcap.bounds.height;
747 
748 	/* VBI capturing ends at VDELAY, start of video capturing, no
749 	   matter how many lines the VBI RISC program expects. When video
750 	   capturing is off, it shall no longer "preempt" VBI capturing,
751 	   so we set VDELAY to maximum. */
752 	crop = btread(BT848_E_CROP) | 0xc0;
753 	btwrite(crop, BT848_E_CROP);
754 	btwrite(0xfe, BT848_E_VDELAY_LO);
755 	btwrite(crop, BT848_O_CROP);
756 	btwrite(0xfe, BT848_O_VDELAY_LO);
757 }
758 
759 static
760 void free_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bits)
761 {
762 	if ((fh->resources & bits) != bits) {
763 		/* trying to free resources not allocated by us ... */
764 		pr_err("BUG! (btres)\n");
765 	}
766 	fh->resources  &= ~bits;
767 	btv->resources &= ~bits;
768 
769 	bits = btv->resources;
770 
771 	if (0 == (bits & VIDEO_RESOURCES))
772 		disclaim_video_lines(btv);
773 
774 	if (0 == (bits & VBI_RESOURCES))
775 		disclaim_vbi_lines(btv);
776 }
777 
778 /* ----------------------------------------------------------------------- */
779 /* If Bt848a or Bt849, use PLL for PAL/SECAM and crystal for NTSC          */
780 
781 /* Frequency = (F_input / PLL_X) * PLL_I.PLL_F/PLL_C
782    PLL_X = Reference pre-divider (0=1, 1=2)
783    PLL_C = Post divider (0=6, 1=4)
784    PLL_I = Integer input
785    PLL_F = Fractional input
786 
787    F_input = 28.636363 MHz:
788    PAL (CLKx2 = 35.46895 MHz): PLL_X = 1, PLL_I = 0x0E, PLL_F = 0xDCF9, PLL_C = 0
789 */
790 
791 static void set_pll_freq(struct bttv *btv, unsigned int fin, unsigned int fout)
792 {
793 	unsigned char fl, fh, fi;
794 
795 	/* prevent overflows */
796 	fin/=4;
797 	fout/=4;
798 
799 	fout*=12;
800 	fi=fout/fin;
801 
802 	fout=(fout%fin)*256;
803 	fh=fout/fin;
804 
805 	fout=(fout%fin)*256;
806 	fl=fout/fin;
807 
808 	btwrite(fl, BT848_PLL_F_LO);
809 	btwrite(fh, BT848_PLL_F_HI);
810 	btwrite(fi|BT848_PLL_X, BT848_PLL_XCI);
811 }
812 
813 static void set_pll(struct bttv *btv)
814 {
815 	int i;
816 
817 	if (!btv->pll.pll_crystal)
818 		return;
819 
820 	if (btv->pll.pll_ofreq == btv->pll.pll_current) {
821 		dprintk("%d: PLL: no change required\n", btv->c.nr);
822 		return;
823 	}
824 
825 	if (btv->pll.pll_ifreq == btv->pll.pll_ofreq) {
826 		/* no PLL needed */
827 		if (btv->pll.pll_current == 0)
828 			return;
829 		if (bttv_verbose)
830 			pr_info("%d: PLL can sleep, using XTAL (%d)\n",
831 				btv->c.nr, btv->pll.pll_ifreq);
832 		btwrite(0x00,BT848_TGCTRL);
833 		btwrite(0x00,BT848_PLL_XCI);
834 		btv->pll.pll_current = 0;
835 		return;
836 	}
837 
838 	if (bttv_verbose)
839 		pr_info("%d: Setting PLL: %d => %d (needs up to 100ms)\n",
840 			btv->c.nr,
841 			btv->pll.pll_ifreq, btv->pll.pll_ofreq);
842 	set_pll_freq(btv, btv->pll.pll_ifreq, btv->pll.pll_ofreq);
843 
844 	for (i=0; i<10; i++) {
845 		/*  Let other people run while the PLL stabilizes */
846 		msleep(10);
847 
848 		if (btread(BT848_DSTATUS) & BT848_DSTATUS_PLOCK) {
849 			btwrite(0,BT848_DSTATUS);
850 		} else {
851 			btwrite(0x08,BT848_TGCTRL);
852 			btv->pll.pll_current = btv->pll.pll_ofreq;
853 			if (bttv_verbose)
854 				pr_info("PLL set ok\n");
855 			return;
856 		}
857 	}
858 	btv->pll.pll_current = -1;
859 	if (bttv_verbose)
860 		pr_info("Setting PLL failed\n");
861 	return;
862 }
863 
864 /* used to switch between the bt848's analog/digital video capture modes */
865 static void bt848A_set_timing(struct bttv *btv)
866 {
867 	int i, len;
868 	int table_idx = bttv_tvnorms[btv->tvnorm].sram;
869 	int fsc       = bttv_tvnorms[btv->tvnorm].Fsc;
870 
871 	if (btv->input == btv->dig) {
872 		dprintk("%d: load digital timing table (table_idx=%d)\n",
873 			btv->c.nr,table_idx);
874 
875 		/* timing change...reset timing generator address */
876 		btwrite(0x00, BT848_TGCTRL);
877 		btwrite(0x02, BT848_TGCTRL);
878 		btwrite(0x00, BT848_TGCTRL);
879 
880 		len=SRAM_Table[table_idx][0];
881 		for(i = 1; i <= len; i++)
882 			btwrite(SRAM_Table[table_idx][i],BT848_TGLB);
883 		btv->pll.pll_ofreq = 27000000;
884 
885 		set_pll(btv);
886 		btwrite(0x11, BT848_TGCTRL);
887 		btwrite(0x41, BT848_DVSIF);
888 	} else {
889 		btv->pll.pll_ofreq = fsc;
890 		set_pll(btv);
891 		btwrite(0x0, BT848_DVSIF);
892 	}
893 }
894 
895 /* ----------------------------------------------------------------------- */
896 
897 static void bt848_bright(struct bttv *btv, int bright)
898 {
899 	int value;
900 
901 	// printk("set bright: %d\n", bright); // DEBUG
902 	btv->bright = bright;
903 
904 	/* We want -128 to 127 we get 0-65535 */
905 	value = (bright >> 8) - 128;
906 	btwrite(value & 0xff, BT848_BRIGHT);
907 }
908 
909 static void bt848_hue(struct bttv *btv, int hue)
910 {
911 	int value;
912 
913 	btv->hue = hue;
914 
915 	/* -128 to 127 */
916 	value = (hue >> 8) - 128;
917 	btwrite(value & 0xff, BT848_HUE);
918 }
919 
920 static void bt848_contrast(struct bttv *btv, int cont)
921 {
922 	int value,hibit;
923 
924 	btv->contrast = cont;
925 
926 	/* 0-511 */
927 	value = (cont  >> 7);
928 	hibit = (value >> 6) & 4;
929 	btwrite(value & 0xff, BT848_CONTRAST_LO);
930 	btaor(hibit, ~4, BT848_E_CONTROL);
931 	btaor(hibit, ~4, BT848_O_CONTROL);
932 }
933 
934 static void bt848_sat(struct bttv *btv, int color)
935 {
936 	int val_u,val_v,hibits;
937 
938 	btv->saturation = color;
939 
940 	/* 0-511 for the color */
941 	val_u   = ((color * btv->opt_uv_ratio) / 50) >> 7;
942 	val_v   = (((color * (100 - btv->opt_uv_ratio) / 50) >>7)*180L)/254;
943 	hibits  = (val_u >> 7) & 2;
944 	hibits |= (val_v >> 8) & 1;
945 	btwrite(val_u & 0xff, BT848_SAT_U_LO);
946 	btwrite(val_v & 0xff, BT848_SAT_V_LO);
947 	btaor(hibits, ~3, BT848_E_CONTROL);
948 	btaor(hibits, ~3, BT848_O_CONTROL);
949 }
950 
951 /* ----------------------------------------------------------------------- */
952 
953 static int
954 video_mux(struct bttv *btv, unsigned int input)
955 {
956 	int mux,mask2;
957 
958 	if (input >= bttv_tvcards[btv->c.type].video_inputs)
959 		return -EINVAL;
960 
961 	/* needed by RemoteVideo MX */
962 	mask2 = bttv_tvcards[btv->c.type].gpiomask2;
963 	if (mask2)
964 		gpio_inout(mask2,mask2);
965 
966 	if (input == btv->svhs)  {
967 		btor(BT848_CONTROL_COMP, BT848_E_CONTROL);
968 		btor(BT848_CONTROL_COMP, BT848_O_CONTROL);
969 	} else {
970 		btand(~BT848_CONTROL_COMP, BT848_E_CONTROL);
971 		btand(~BT848_CONTROL_COMP, BT848_O_CONTROL);
972 	}
973 	mux = bttv_muxsel(btv, input);
974 	btaor(mux<<5, ~(3<<5), BT848_IFORM);
975 	dprintk("%d: video mux: input=%d mux=%d\n", btv->c.nr, input, mux);
976 
977 	/* card specific hook */
978 	if(bttv_tvcards[btv->c.type].muxsel_hook)
979 		bttv_tvcards[btv->c.type].muxsel_hook (btv, input);
980 	return 0;
981 }
982 
983 static char *audio_modes[] = {
984 	"audio: tuner", "audio: radio", "audio: extern",
985 	"audio: intern", "audio: mute"
986 };
987 
988 static void
989 audio_mux_gpio(struct bttv *btv, int input, int mute)
990 {
991 	int gpio_val, signal, mute_gpio;
992 
993 	gpio_inout(bttv_tvcards[btv->c.type].gpiomask,
994 		   bttv_tvcards[btv->c.type].gpiomask);
995 	signal = btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC;
996 
997 	/* automute */
998 	mute_gpio = mute || (btv->opt_automute && (!signal || !btv->users)
999 				&& !btv->has_radio_tuner);
1000 
1001 	if (mute_gpio)
1002 		gpio_val = bttv_tvcards[btv->c.type].gpiomute;
1003 	else
1004 		gpio_val = bttv_tvcards[btv->c.type].gpiomux[input];
1005 
1006 	switch (btv->c.type) {
1007 	case BTTV_BOARD_VOODOOTV_FM:
1008 	case BTTV_BOARD_VOODOOTV_200:
1009 		gpio_val = bttv_tda9880_setnorm(btv, gpio_val);
1010 		break;
1011 
1012 	default:
1013 		gpio_bits(bttv_tvcards[btv->c.type].gpiomask, gpio_val);
1014 	}
1015 
1016 	if (bttv_gpio)
1017 		bttv_gpio_tracking(btv, audio_modes[mute_gpio ? 4 : input]);
1018 }
1019 
1020 static int
1021 audio_mute(struct bttv *btv, int mute)
1022 {
1023 	struct v4l2_ctrl *ctrl;
1024 
1025 	audio_mux_gpio(btv, btv->audio_input, mute);
1026 
1027 	if (btv->sd_msp34xx) {
1028 		ctrl = v4l2_ctrl_find(btv->sd_msp34xx->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1029 		if (ctrl)
1030 			v4l2_ctrl_s_ctrl(ctrl, mute);
1031 	}
1032 	if (btv->sd_tvaudio) {
1033 		ctrl = v4l2_ctrl_find(btv->sd_tvaudio->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1034 		if (ctrl)
1035 			v4l2_ctrl_s_ctrl(ctrl, mute);
1036 	}
1037 	if (btv->sd_tda7432) {
1038 		ctrl = v4l2_ctrl_find(btv->sd_tda7432->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1039 		if (ctrl)
1040 			v4l2_ctrl_s_ctrl(ctrl, mute);
1041 	}
1042 	return 0;
1043 }
1044 
1045 static int
1046 audio_input(struct bttv *btv, int input)
1047 {
1048 	audio_mux_gpio(btv, input, btv->mute);
1049 
1050 	if (btv->sd_msp34xx) {
1051 		u32 in;
1052 
1053 		/* Note: the inputs tuner/radio/extern/intern are translated
1054 		   to msp routings. This assumes common behavior for all msp3400
1055 		   based TV cards. When this assumption fails, then the
1056 		   specific MSP routing must be added to the card table.
1057 		   For now this is sufficient. */
1058 		switch (input) {
1059 		case TVAUDIO_INPUT_RADIO:
1060 			/* Some boards need the msp do to the radio demod */
1061 			if (btv->radio_uses_msp_demodulator) {
1062 				in = MSP_INPUT_DEFAULT;
1063 				break;
1064 			}
1065 			in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1066 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1067 			break;
1068 		case TVAUDIO_INPUT_EXTERN:
1069 			in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
1070 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1071 			break;
1072 		case TVAUDIO_INPUT_INTERN:
1073 			/* Yes, this is the same input as for RADIO. I doubt
1074 			   if this is ever used. The only board with an INTERN
1075 			   input is the BTTV_BOARD_AVERMEDIA98. I wonder how
1076 			   that was tested. My guess is that the whole INTERN
1077 			   input does not work. */
1078 			in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1079 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1080 			break;
1081 		case TVAUDIO_INPUT_TUNER:
1082 		default:
1083 			/* This is the only card that uses TUNER2, and afaik,
1084 			   is the only difference between the VOODOOTV_FM
1085 			   and VOODOOTV_200 */
1086 			if (btv->c.type == BTTV_BOARD_VOODOOTV_200)
1087 				in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER2, \
1088 					MSP_DSP_IN_TUNER, MSP_DSP_IN_TUNER);
1089 			else
1090 				in = MSP_INPUT_DEFAULT;
1091 			break;
1092 		}
1093 		v4l2_subdev_call(btv->sd_msp34xx, audio, s_routing,
1094 			       in, MSP_OUTPUT_DEFAULT, 0);
1095 	}
1096 	if (btv->sd_tvaudio) {
1097 		v4l2_subdev_call(btv->sd_tvaudio, audio, s_routing,
1098 				 input, 0, 0);
1099 	}
1100 	return 0;
1101 }
1102 
1103 static void
1104 bttv_crop_calc_limits(struct bttv_crop *c)
1105 {
1106 	/* Scale factor min. 1:1, max. 16:1. Min. image size
1107 	   48 x 32. Scaled width must be a multiple of 4. */
1108 
1109 	if (1) {
1110 		/* For bug compatibility with VIDIOCGCAP and image
1111 		   size checks in earlier driver versions. */
1112 		c->min_scaled_width = 48;
1113 		c->min_scaled_height = 32;
1114 	} else {
1115 		c->min_scaled_width =
1116 			(max_t(unsigned int, 48, c->rect.width >> 4) + 3) & ~3;
1117 		c->min_scaled_height =
1118 			max_t(unsigned int, 32, c->rect.height >> 4);
1119 	}
1120 
1121 	c->max_scaled_width  = c->rect.width & ~3;
1122 	c->max_scaled_height = c->rect.height;
1123 }
1124 
1125 static void
1126 bttv_crop_reset(struct bttv_crop *c, unsigned int norm)
1127 {
1128 	c->rect = bttv_tvnorms[norm].cropcap.defrect;
1129 	bttv_crop_calc_limits(c);
1130 }
1131 
1132 /* Call with btv->lock down. */
1133 static int
1134 set_tvnorm(struct bttv *btv, unsigned int norm)
1135 {
1136 	const struct bttv_tvnorm *tvnorm;
1137 	v4l2_std_id id;
1138 
1139 	BUG_ON(norm >= BTTV_TVNORMS);
1140 	BUG_ON(btv->tvnorm >= BTTV_TVNORMS);
1141 
1142 	tvnorm = &bttv_tvnorms[norm];
1143 
1144 	if (memcmp(&bttv_tvnorms[btv->tvnorm].cropcap, &tvnorm->cropcap,
1145 		    sizeof (tvnorm->cropcap))) {
1146 		bttv_crop_reset(&btv->crop[0], norm);
1147 		btv->crop[1] = btv->crop[0]; /* current = default */
1148 
1149 		if (0 == (btv->resources & VIDEO_RESOURCES)) {
1150 			btv->crop_start = tvnorm->cropcap.bounds.top
1151 				+ tvnorm->cropcap.bounds.height;
1152 		}
1153 	}
1154 
1155 	btv->tvnorm = norm;
1156 
1157 	btwrite(tvnorm->adelay, BT848_ADELAY);
1158 	btwrite(tvnorm->bdelay, BT848_BDELAY);
1159 	btaor(tvnorm->iform,~(BT848_IFORM_NORM|BT848_IFORM_XTBOTH),
1160 	      BT848_IFORM);
1161 	btwrite(tvnorm->vbipack, BT848_VBI_PACK_SIZE);
1162 	btwrite(1, BT848_VBI_PACK_DEL);
1163 	bt848A_set_timing(btv);
1164 
1165 	switch (btv->c.type) {
1166 	case BTTV_BOARD_VOODOOTV_FM:
1167 	case BTTV_BOARD_VOODOOTV_200:
1168 		bttv_tda9880_setnorm(btv, gpio_read());
1169 		break;
1170 	}
1171 	id = tvnorm->v4l2_id;
1172 	bttv_call_all(btv, video, s_std, id);
1173 
1174 	return 0;
1175 }
1176 
1177 /* Call with btv->lock down. */
1178 static void
1179 set_input(struct bttv *btv, unsigned int input, unsigned int norm)
1180 {
1181 	unsigned long flags;
1182 
1183 	btv->input = input;
1184 	if (irq_iswitch) {
1185 		spin_lock_irqsave(&btv->s_lock,flags);
1186 		if (btv->curr.frame_irq) {
1187 			/* active capture -> delayed input switch */
1188 			btv->new_input = input;
1189 		} else {
1190 			video_mux(btv,input);
1191 		}
1192 		spin_unlock_irqrestore(&btv->s_lock,flags);
1193 	} else {
1194 		video_mux(btv,input);
1195 	}
1196 	btv->audio_input = (btv->tuner_type != TUNER_ABSENT && input == 0) ?
1197 				TVAUDIO_INPUT_TUNER : TVAUDIO_INPUT_EXTERN;
1198 	audio_input(btv, btv->audio_input);
1199 	set_tvnorm(btv, norm);
1200 }
1201 
1202 static void init_irqreg(struct bttv *btv)
1203 {
1204 	/* clear status */
1205 	btwrite(0xfffffUL, BT848_INT_STAT);
1206 
1207 	if (bttv_tvcards[btv->c.type].no_video) {
1208 		/* i2c only */
1209 		btwrite(BT848_INT_I2CDONE,
1210 			BT848_INT_MASK);
1211 	} else {
1212 		/* full video */
1213 		btwrite((btv->triton1)  |
1214 			(btv->gpioirq ? BT848_INT_GPINT : 0) |
1215 			BT848_INT_SCERR |
1216 			(fdsr ? BT848_INT_FDSR : 0) |
1217 			BT848_INT_RISCI | BT848_INT_OCERR |
1218 			BT848_INT_FMTCHG|BT848_INT_HLOCK|
1219 			BT848_INT_I2CDONE,
1220 			BT848_INT_MASK);
1221 	}
1222 }
1223 
1224 static void init_bt848(struct bttv *btv)
1225 {
1226 	if (bttv_tvcards[btv->c.type].no_video) {
1227 		/* very basic init only */
1228 		init_irqreg(btv);
1229 		return;
1230 	}
1231 
1232 	btwrite(0x00, BT848_CAP_CTL);
1233 	btwrite(BT848_COLOR_CTL_GAMMA, BT848_COLOR_CTL);
1234 	btwrite(BT848_IFORM_XTAUTO | BT848_IFORM_AUTO, BT848_IFORM);
1235 
1236 	/* set planar and packed mode trigger points and         */
1237 	/* set rising edge of inverted GPINTR pin as irq trigger */
1238 	btwrite(BT848_GPIO_DMA_CTL_PKTP_32|
1239 		BT848_GPIO_DMA_CTL_PLTP1_16|
1240 		BT848_GPIO_DMA_CTL_PLTP23_16|
1241 		BT848_GPIO_DMA_CTL_GPINTC|
1242 		BT848_GPIO_DMA_CTL_GPINTI,
1243 		BT848_GPIO_DMA_CTL);
1244 
1245 	btwrite(0x20, BT848_E_VSCALE_HI);
1246 	btwrite(0x20, BT848_O_VSCALE_HI);
1247 
1248 	v4l2_ctrl_handler_setup(&btv->ctrl_handler);
1249 
1250 	/* interrupt */
1251 	init_irqreg(btv);
1252 }
1253 
1254 static void bttv_reinit_bt848(struct bttv *btv)
1255 {
1256 	unsigned long flags;
1257 
1258 	if (bttv_verbose)
1259 		pr_info("%d: reset, reinitialize\n", btv->c.nr);
1260 	spin_lock_irqsave(&btv->s_lock,flags);
1261 	btv->errors=0;
1262 	bttv_set_dma(btv,0);
1263 	spin_unlock_irqrestore(&btv->s_lock,flags);
1264 
1265 	init_bt848(btv);
1266 	btv->pll.pll_current = -1;
1267 	set_input(btv, btv->input, btv->tvnorm);
1268 }
1269 
1270 static int bttv_s_ctrl(struct v4l2_ctrl *c)
1271 {
1272 	struct bttv *btv = container_of(c->handler, struct bttv, ctrl_handler);
1273 	int val;
1274 
1275 	switch (c->id) {
1276 	case V4L2_CID_BRIGHTNESS:
1277 		bt848_bright(btv, c->val);
1278 		break;
1279 	case V4L2_CID_HUE:
1280 		bt848_hue(btv, c->val);
1281 		break;
1282 	case V4L2_CID_CONTRAST:
1283 		bt848_contrast(btv, c->val);
1284 		break;
1285 	case V4L2_CID_SATURATION:
1286 		bt848_sat(btv, c->val);
1287 		break;
1288 	case V4L2_CID_COLOR_KILLER:
1289 		if (c->val) {
1290 			btor(BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1291 			btor(BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1292 		} else {
1293 			btand(~BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1294 			btand(~BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1295 		}
1296 		break;
1297 	case V4L2_CID_AUDIO_MUTE:
1298 		audio_mute(btv, c->val);
1299 		btv->mute = c->val;
1300 		break;
1301 	case V4L2_CID_AUDIO_VOLUME:
1302 		btv->volume_gpio(btv, c->val);
1303 		break;
1304 
1305 	case V4L2_CID_CHROMA_AGC:
1306 		val = c->val ? BT848_SCLOOP_CAGC : 0;
1307 		btwrite(val, BT848_E_SCLOOP);
1308 		btwrite(val, BT848_O_SCLOOP);
1309 		break;
1310 	case V4L2_CID_PRIVATE_COMBFILTER:
1311 		btv->opt_combfilter = c->val;
1312 		break;
1313 	case V4L2_CID_PRIVATE_LUMAFILTER:
1314 		if (c->val) {
1315 			btand(~BT848_CONTROL_LDEC, BT848_E_CONTROL);
1316 			btand(~BT848_CONTROL_LDEC, BT848_O_CONTROL);
1317 		} else {
1318 			btor(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1319 			btor(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1320 		}
1321 		break;
1322 	case V4L2_CID_PRIVATE_AUTOMUTE:
1323 		btv->opt_automute = c->val;
1324 		break;
1325 	case V4L2_CID_PRIVATE_AGC_CRUSH:
1326 		btwrite(BT848_ADC_RESERVED |
1327 				(c->val ? BT848_ADC_CRUSH : 0),
1328 				BT848_ADC);
1329 		break;
1330 	case V4L2_CID_PRIVATE_VCR_HACK:
1331 		btv->opt_vcr_hack = c->val;
1332 		break;
1333 	case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1334 		btwrite(c->val, BT848_WC_UP);
1335 		break;
1336 	case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1337 		btwrite(c->val, BT848_WC_DOWN);
1338 		break;
1339 	case V4L2_CID_PRIVATE_UV_RATIO:
1340 		btv->opt_uv_ratio = c->val;
1341 		bt848_sat(btv, btv->saturation);
1342 		break;
1343 	case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1344 		btaor((c->val << 7), ~BT848_OFORM_RANGE, BT848_OFORM);
1345 		break;
1346 	case V4L2_CID_PRIVATE_CORING:
1347 		btaor((c->val << 5), ~BT848_OFORM_CORE32, BT848_OFORM);
1348 		break;
1349 	default:
1350 		return -EINVAL;
1351 	}
1352 	return 0;
1353 }
1354 
1355 /* ----------------------------------------------------------------------- */
1356 
1357 static const struct v4l2_ctrl_ops bttv_ctrl_ops = {
1358 	.s_ctrl = bttv_s_ctrl,
1359 };
1360 
1361 static struct v4l2_ctrl_config bttv_ctrl_combfilter = {
1362 	.ops = &bttv_ctrl_ops,
1363 	.id = V4L2_CID_PRIVATE_COMBFILTER,
1364 	.name = "Comb Filter",
1365 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1366 	.min = 0,
1367 	.max = 1,
1368 	.step = 1,
1369 	.def = 1,
1370 };
1371 
1372 static struct v4l2_ctrl_config bttv_ctrl_automute = {
1373 	.ops = &bttv_ctrl_ops,
1374 	.id = V4L2_CID_PRIVATE_AUTOMUTE,
1375 	.name = "Auto Mute",
1376 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1377 	.min = 0,
1378 	.max = 1,
1379 	.step = 1,
1380 	.def = 1,
1381 };
1382 
1383 static struct v4l2_ctrl_config bttv_ctrl_lumafilter = {
1384 	.ops = &bttv_ctrl_ops,
1385 	.id = V4L2_CID_PRIVATE_LUMAFILTER,
1386 	.name = "Luma Decimation Filter",
1387 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1388 	.min = 0,
1389 	.max = 1,
1390 	.step = 1,
1391 	.def = 1,
1392 };
1393 
1394 static struct v4l2_ctrl_config bttv_ctrl_agc_crush = {
1395 	.ops = &bttv_ctrl_ops,
1396 	.id = V4L2_CID_PRIVATE_AGC_CRUSH,
1397 	.name = "AGC Crush",
1398 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1399 	.min = 0,
1400 	.max = 1,
1401 	.step = 1,
1402 	.def = 1,
1403 };
1404 
1405 static struct v4l2_ctrl_config bttv_ctrl_vcr_hack = {
1406 	.ops = &bttv_ctrl_ops,
1407 	.id = V4L2_CID_PRIVATE_VCR_HACK,
1408 	.name = "VCR Hack",
1409 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1410 	.min = 0,
1411 	.max = 1,
1412 	.step = 1,
1413 	.def = 1,
1414 };
1415 
1416 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_lower = {
1417 	.ops = &bttv_ctrl_ops,
1418 	.id = V4L2_CID_PRIVATE_WHITECRUSH_LOWER,
1419 	.name = "Whitecrush Lower",
1420 	.type = V4L2_CTRL_TYPE_INTEGER,
1421 	.min = 0,
1422 	.max = 255,
1423 	.step = 1,
1424 	.def = 0x7f,
1425 };
1426 
1427 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_upper = {
1428 	.ops = &bttv_ctrl_ops,
1429 	.id = V4L2_CID_PRIVATE_WHITECRUSH_UPPER,
1430 	.name = "Whitecrush Upper",
1431 	.type = V4L2_CTRL_TYPE_INTEGER,
1432 	.min = 0,
1433 	.max = 255,
1434 	.step = 1,
1435 	.def = 0xcf,
1436 };
1437 
1438 static struct v4l2_ctrl_config bttv_ctrl_uv_ratio = {
1439 	.ops = &bttv_ctrl_ops,
1440 	.id = V4L2_CID_PRIVATE_UV_RATIO,
1441 	.name = "UV Ratio",
1442 	.type = V4L2_CTRL_TYPE_INTEGER,
1443 	.min = 0,
1444 	.max = 100,
1445 	.step = 1,
1446 	.def = 50,
1447 };
1448 
1449 static struct v4l2_ctrl_config bttv_ctrl_full_luma = {
1450 	.ops = &bttv_ctrl_ops,
1451 	.id = V4L2_CID_PRIVATE_FULL_LUMA_RANGE,
1452 	.name = "Full Luma Range",
1453 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1454 	.min = 0,
1455 	.max = 1,
1456 	.step = 1,
1457 };
1458 
1459 static struct v4l2_ctrl_config bttv_ctrl_coring = {
1460 	.ops = &bttv_ctrl_ops,
1461 	.id = V4L2_CID_PRIVATE_CORING,
1462 	.name = "Coring",
1463 	.type = V4L2_CTRL_TYPE_INTEGER,
1464 	.min = 0,
1465 	.max = 3,
1466 	.step = 1,
1467 };
1468 
1469 
1470 /* ----------------------------------------------------------------------- */
1471 
1472 void bttv_gpio_tracking(struct bttv *btv, char *comment)
1473 {
1474 	unsigned int outbits, data;
1475 	outbits = btread(BT848_GPIO_OUT_EN);
1476 	data    = btread(BT848_GPIO_DATA);
1477 	pr_debug("%d: gpio: en=%08x, out=%08x in=%08x [%s]\n",
1478 		 btv->c.nr, outbits, data & outbits, data & ~outbits, comment);
1479 }
1480 
1481 static void bttv_field_count(struct bttv *btv)
1482 {
1483 	int need_count = 0;
1484 
1485 	if (btv->users)
1486 		need_count++;
1487 
1488 	if (need_count) {
1489 		/* start field counter */
1490 		btor(BT848_INT_VSYNC,BT848_INT_MASK);
1491 	} else {
1492 		/* stop field counter */
1493 		btand(~BT848_INT_VSYNC,BT848_INT_MASK);
1494 		btv->field_count = 0;
1495 	}
1496 }
1497 
1498 static const struct bttv_format*
1499 format_by_fourcc(int fourcc)
1500 {
1501 	unsigned int i;
1502 
1503 	for (i = 0; i < FORMATS; i++) {
1504 		if (-1 == formats[i].fourcc)
1505 			continue;
1506 		if (formats[i].fourcc == fourcc)
1507 			return formats+i;
1508 	}
1509 	return NULL;
1510 }
1511 
1512 /* ----------------------------------------------------------------------- */
1513 /* misc helpers                                                            */
1514 
1515 static int
1516 bttv_switch_overlay(struct bttv *btv, struct bttv_fh *fh,
1517 		    struct bttv_buffer *new)
1518 {
1519 	struct bttv_buffer *old;
1520 	unsigned long flags;
1521 
1522 	dprintk("switch_overlay: enter [new=%p]\n", new);
1523 	if (new)
1524 		new->vb.state = VIDEOBUF_DONE;
1525 	spin_lock_irqsave(&btv->s_lock,flags);
1526 	old = btv->screen;
1527 	btv->screen = new;
1528 	btv->loop_irq |= 1;
1529 	bttv_set_dma(btv, 0x03);
1530 	spin_unlock_irqrestore(&btv->s_lock,flags);
1531 	if (NULL != old) {
1532 		dprintk("switch_overlay: old=%p state is %d\n",
1533 			old, old->vb.state);
1534 		bttv_dma_free(&fh->cap,btv, old);
1535 		kfree(old);
1536 	}
1537 	if (NULL == new)
1538 		free_btres_lock(btv,fh,RESOURCE_OVERLAY);
1539 	dprintk("switch_overlay: done\n");
1540 	return 0;
1541 }
1542 
1543 /* ----------------------------------------------------------------------- */
1544 /* video4linux (1) interface                                               */
1545 
1546 static int bttv_prepare_buffer(struct videobuf_queue *q,struct bttv *btv,
1547 			       struct bttv_buffer *buf,
1548 			       const struct bttv_format *fmt,
1549 			       unsigned int width, unsigned int height,
1550 			       enum v4l2_field field)
1551 {
1552 	struct bttv_fh *fh = q->priv_data;
1553 	int redo_dma_risc = 0;
1554 	struct bttv_crop c;
1555 	int norm;
1556 	int rc;
1557 
1558 	/* check settings */
1559 	if (NULL == fmt)
1560 		return -EINVAL;
1561 	if (fmt->btformat == BT848_COLOR_FMT_RAW) {
1562 		width  = RAW_BPL;
1563 		height = RAW_LINES*2;
1564 		if (width*height > buf->vb.bsize)
1565 			return -EINVAL;
1566 		buf->vb.size = buf->vb.bsize;
1567 
1568 		/* Make sure tvnorm and vbi_end remain consistent
1569 		   until we're done. */
1570 
1571 		norm = btv->tvnorm;
1572 
1573 		/* In this mode capturing always starts at defrect.top
1574 		   (default VDELAY), ignoring cropping parameters. */
1575 		if (btv->vbi_end > bttv_tvnorms[norm].cropcap.defrect.top) {
1576 			return -EINVAL;
1577 		}
1578 
1579 		c.rect = bttv_tvnorms[norm].cropcap.defrect;
1580 	} else {
1581 		norm = btv->tvnorm;
1582 		c = btv->crop[!!fh->do_crop];
1583 
1584 		if (width < c.min_scaled_width ||
1585 		    width > c.max_scaled_width ||
1586 		    height < c.min_scaled_height)
1587 			return -EINVAL;
1588 
1589 		switch (field) {
1590 		case V4L2_FIELD_TOP:
1591 		case V4L2_FIELD_BOTTOM:
1592 		case V4L2_FIELD_ALTERNATE:
1593 			/* btv->crop counts frame lines. Max. scale
1594 			   factor is 16:1 for frames, 8:1 for fields. */
1595 			if (height * 2 > c.max_scaled_height)
1596 				return -EINVAL;
1597 			break;
1598 
1599 		default:
1600 			if (height > c.max_scaled_height)
1601 				return -EINVAL;
1602 			break;
1603 		}
1604 
1605 		buf->vb.size = (width * height * fmt->depth) >> 3;
1606 		if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
1607 			return -EINVAL;
1608 	}
1609 
1610 	/* alloc + fill struct bttv_buffer (if changed) */
1611 	if (buf->vb.width != width || buf->vb.height != height ||
1612 	    buf->vb.field != field ||
1613 	    buf->tvnorm != norm || buf->fmt != fmt ||
1614 	    buf->crop.top != c.rect.top ||
1615 	    buf->crop.left != c.rect.left ||
1616 	    buf->crop.width != c.rect.width ||
1617 	    buf->crop.height != c.rect.height) {
1618 		buf->vb.width  = width;
1619 		buf->vb.height = height;
1620 		buf->vb.field  = field;
1621 		buf->tvnorm    = norm;
1622 		buf->fmt       = fmt;
1623 		buf->crop      = c.rect;
1624 		redo_dma_risc = 1;
1625 	}
1626 
1627 	/* alloc risc memory */
1628 	if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
1629 		redo_dma_risc = 1;
1630 		if (0 != (rc = videobuf_iolock(q,&buf->vb,&btv->fbuf)))
1631 			goto fail;
1632 	}
1633 
1634 	if (redo_dma_risc)
1635 		if (0 != (rc = bttv_buffer_risc(btv,buf)))
1636 			goto fail;
1637 
1638 	buf->vb.state = VIDEOBUF_PREPARED;
1639 	return 0;
1640 
1641  fail:
1642 	bttv_dma_free(q,btv,buf);
1643 	return rc;
1644 }
1645 
1646 static int
1647 buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
1648 {
1649 	struct bttv_fh *fh = q->priv_data;
1650 
1651 	*size = fh->fmt->depth*fh->width*fh->height >> 3;
1652 	if (0 == *count)
1653 		*count = gbuffers;
1654 	if (*size * *count > gbuffers * gbufsize)
1655 		*count = (gbuffers * gbufsize) / *size;
1656 	return 0;
1657 }
1658 
1659 static int
1660 buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
1661 	       enum v4l2_field field)
1662 {
1663 	struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1664 	struct bttv_fh *fh = q->priv_data;
1665 
1666 	return bttv_prepare_buffer(q,fh->btv, buf, fh->fmt,
1667 				   fh->width, fh->height, field);
1668 }
1669 
1670 static void
1671 buffer_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
1672 {
1673 	struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1674 	struct bttv_fh *fh = q->priv_data;
1675 	struct bttv    *btv = fh->btv;
1676 
1677 	buf->vb.state = VIDEOBUF_QUEUED;
1678 	list_add_tail(&buf->vb.queue,&btv->capture);
1679 	if (!btv->curr.frame_irq) {
1680 		btv->loop_irq |= 1;
1681 		bttv_set_dma(btv, 0x03);
1682 	}
1683 }
1684 
1685 static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
1686 {
1687 	struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1688 	struct bttv_fh *fh = q->priv_data;
1689 
1690 	bttv_dma_free(q,fh->btv,buf);
1691 }
1692 
1693 static const struct videobuf_queue_ops bttv_video_qops = {
1694 	.buf_setup    = buffer_setup,
1695 	.buf_prepare  = buffer_prepare,
1696 	.buf_queue    = buffer_queue,
1697 	.buf_release  = buffer_release,
1698 };
1699 
1700 static void radio_enable(struct bttv *btv)
1701 {
1702 	/* Switch to the radio tuner */
1703 	if (!btv->has_radio_tuner) {
1704 		btv->has_radio_tuner = 1;
1705 		bttv_call_all(btv, tuner, s_radio);
1706 		btv->audio_input = TVAUDIO_INPUT_RADIO;
1707 		audio_input(btv, btv->audio_input);
1708 	}
1709 }
1710 
1711 static int bttv_s_std(struct file *file, void *priv, v4l2_std_id id)
1712 {
1713 	struct bttv_fh *fh  = priv;
1714 	struct bttv *btv = fh->btv;
1715 	unsigned int i;
1716 
1717 	for (i = 0; i < BTTV_TVNORMS; i++)
1718 		if (id & bttv_tvnorms[i].v4l2_id)
1719 			break;
1720 	if (i == BTTV_TVNORMS)
1721 		return -EINVAL;
1722 	btv->std = id;
1723 	set_tvnorm(btv, i);
1724 	return 0;
1725 }
1726 
1727 static int bttv_g_std(struct file *file, void *priv, v4l2_std_id *id)
1728 {
1729 	struct bttv_fh *fh  = priv;
1730 	struct bttv *btv = fh->btv;
1731 
1732 	*id = btv->std;
1733 	return 0;
1734 }
1735 
1736 static int bttv_querystd(struct file *file, void *f, v4l2_std_id *id)
1737 {
1738 	struct bttv_fh *fh = f;
1739 	struct bttv *btv = fh->btv;
1740 
1741 	if (btread(BT848_DSTATUS) & BT848_DSTATUS_NUML)
1742 		*id &= V4L2_STD_625_50;
1743 	else
1744 		*id &= V4L2_STD_525_60;
1745 	return 0;
1746 }
1747 
1748 static int bttv_enum_input(struct file *file, void *priv,
1749 					struct v4l2_input *i)
1750 {
1751 	struct bttv_fh *fh = priv;
1752 	struct bttv *btv = fh->btv;
1753 
1754 	if (i->index >= bttv_tvcards[btv->c.type].video_inputs)
1755 		return -EINVAL;
1756 
1757 	i->type     = V4L2_INPUT_TYPE_CAMERA;
1758 	i->audioset = 0;
1759 
1760 	if (btv->tuner_type != TUNER_ABSENT && i->index == 0) {
1761 		sprintf(i->name, "Television");
1762 		i->type  = V4L2_INPUT_TYPE_TUNER;
1763 		i->tuner = 0;
1764 	} else if (i->index == btv->svhs) {
1765 		sprintf(i->name, "S-Video");
1766 	} else {
1767 		sprintf(i->name, "Composite%d", i->index);
1768 	}
1769 
1770 	if (i->index == btv->input) {
1771 		__u32 dstatus = btread(BT848_DSTATUS);
1772 		if (0 == (dstatus & BT848_DSTATUS_PRES))
1773 			i->status |= V4L2_IN_ST_NO_SIGNAL;
1774 		if (0 == (dstatus & BT848_DSTATUS_HLOC))
1775 			i->status |= V4L2_IN_ST_NO_H_LOCK;
1776 	}
1777 
1778 	i->std = BTTV_NORMS;
1779 	return 0;
1780 }
1781 
1782 static int bttv_g_input(struct file *file, void *priv, unsigned int *i)
1783 {
1784 	struct bttv_fh *fh = priv;
1785 	struct bttv *btv = fh->btv;
1786 
1787 	*i = btv->input;
1788 
1789 	return 0;
1790 }
1791 
1792 static int bttv_s_input(struct file *file, void *priv, unsigned int i)
1793 {
1794 	struct bttv_fh *fh  = priv;
1795 	struct bttv *btv = fh->btv;
1796 
1797 	if (i >= bttv_tvcards[btv->c.type].video_inputs)
1798 		return -EINVAL;
1799 
1800 	set_input(btv, i, btv->tvnorm);
1801 	return 0;
1802 }
1803 
1804 static int bttv_s_tuner(struct file *file, void *priv,
1805 					const struct v4l2_tuner *t)
1806 {
1807 	struct bttv_fh *fh  = priv;
1808 	struct bttv *btv = fh->btv;
1809 
1810 	if (t->index)
1811 		return -EINVAL;
1812 
1813 	bttv_call_all(btv, tuner, s_tuner, t);
1814 
1815 	if (btv->audio_mode_gpio) {
1816 		struct v4l2_tuner copy = *t;
1817 
1818 		btv->audio_mode_gpio(btv, &copy, 1);
1819 	}
1820 	return 0;
1821 }
1822 
1823 static int bttv_g_frequency(struct file *file, void *priv,
1824 					struct v4l2_frequency *f)
1825 {
1826 	struct bttv_fh *fh  = priv;
1827 	struct bttv *btv = fh->btv;
1828 
1829 	if (f->tuner)
1830 		return -EINVAL;
1831 
1832 	if (f->type == V4L2_TUNER_RADIO)
1833 		radio_enable(btv);
1834 	f->frequency = f->type == V4L2_TUNER_RADIO ?
1835 				btv->radio_freq : btv->tv_freq;
1836 
1837 	return 0;
1838 }
1839 
1840 static void bttv_set_frequency(struct bttv *btv, const struct v4l2_frequency *f)
1841 {
1842 	struct v4l2_frequency new_freq = *f;
1843 
1844 	bttv_call_all(btv, tuner, s_frequency, f);
1845 	/* s_frequency may clamp the frequency, so get the actual
1846 	   frequency before assigning radio/tv_freq. */
1847 	bttv_call_all(btv, tuner, g_frequency, &new_freq);
1848 	if (new_freq.type == V4L2_TUNER_RADIO) {
1849 		radio_enable(btv);
1850 		btv->radio_freq = new_freq.frequency;
1851 		if (btv->has_tea575x) {
1852 			btv->tea.freq = btv->radio_freq;
1853 			snd_tea575x_set_freq(&btv->tea);
1854 		}
1855 	} else {
1856 		btv->tv_freq = new_freq.frequency;
1857 	}
1858 }
1859 
1860 static int bttv_s_frequency(struct file *file, void *priv,
1861 					const struct v4l2_frequency *f)
1862 {
1863 	struct bttv_fh *fh  = priv;
1864 	struct bttv *btv = fh->btv;
1865 
1866 	if (f->tuner)
1867 		return -EINVAL;
1868 
1869 	bttv_set_frequency(btv, f);
1870 	return 0;
1871 }
1872 
1873 static int bttv_log_status(struct file *file, void *f)
1874 {
1875 	struct video_device *vdev = video_devdata(file);
1876 	struct bttv_fh *fh  = f;
1877 	struct bttv *btv = fh->btv;
1878 
1879 	v4l2_ctrl_handler_log_status(vdev->ctrl_handler, btv->c.v4l2_dev.name);
1880 	bttv_call_all(btv, core, log_status);
1881 	return 0;
1882 }
1883 
1884 #ifdef CONFIG_VIDEO_ADV_DEBUG
1885 static int bttv_g_register(struct file *file, void *f,
1886 					struct v4l2_dbg_register *reg)
1887 {
1888 	struct bttv_fh *fh = f;
1889 	struct bttv *btv = fh->btv;
1890 
1891 	/* bt848 has a 12-bit register space */
1892 	reg->reg &= 0xfff;
1893 	reg->val = btread(reg->reg);
1894 	reg->size = 1;
1895 
1896 	return 0;
1897 }
1898 
1899 static int bttv_s_register(struct file *file, void *f,
1900 					const struct v4l2_dbg_register *reg)
1901 {
1902 	struct bttv_fh *fh = f;
1903 	struct bttv *btv = fh->btv;
1904 
1905 	/* bt848 has a 12-bit register space */
1906 	btwrite(reg->val, reg->reg & 0xfff);
1907 
1908 	return 0;
1909 }
1910 #endif
1911 
1912 /* Given cropping boundaries b and the scaled width and height of a
1913    single field or frame, which must not exceed hardware limits, this
1914    function adjusts the cropping parameters c. */
1915 static void
1916 bttv_crop_adjust	(struct bttv_crop *             c,
1917 			 const struct v4l2_rect *	b,
1918 			 __s32                          width,
1919 			 __s32                          height,
1920 			 enum v4l2_field                field)
1921 {
1922 	__s32 frame_height = height << !V4L2_FIELD_HAS_BOTH(field);
1923 	__s32 max_left;
1924 	__s32 max_top;
1925 
1926 	if (width < c->min_scaled_width) {
1927 		/* Max. hor. scale factor 16:1. */
1928 		c->rect.width = width * 16;
1929 	} else if (width > c->max_scaled_width) {
1930 		/* Min. hor. scale factor 1:1. */
1931 		c->rect.width = width;
1932 
1933 		max_left = b->left + b->width - width;
1934 		max_left = min(max_left, (__s32) MAX_HDELAY);
1935 		if (c->rect.left > max_left)
1936 			c->rect.left = max_left;
1937 	}
1938 
1939 	if (height < c->min_scaled_height) {
1940 		/* Max. vert. scale factor 16:1, single fields 8:1. */
1941 		c->rect.height = height * 16;
1942 	} else if (frame_height > c->max_scaled_height) {
1943 		/* Min. vert. scale factor 1:1.
1944 		   Top and height count field lines times two. */
1945 		c->rect.height = (frame_height + 1) & ~1;
1946 
1947 		max_top = b->top + b->height - c->rect.height;
1948 		if (c->rect.top > max_top)
1949 			c->rect.top = max_top;
1950 	}
1951 
1952 	bttv_crop_calc_limits(c);
1953 }
1954 
1955 /* Returns an error if scaling to a frame or single field with the given
1956    width and height is not possible with the current cropping parameters
1957    and width aligned according to width_mask. If adjust_size is TRUE the
1958    function may adjust the width and/or height instead, rounding width
1959    to (width + width_bias) & width_mask. If adjust_crop is TRUE it may
1960    also adjust the current cropping parameters to get closer to the
1961    desired image size. */
1962 static int
1963 limit_scaled_size_lock       (struct bttv_fh *               fh,
1964 			 __s32 *                        width,
1965 			 __s32 *                        height,
1966 			 enum v4l2_field                field,
1967 			 unsigned int			width_mask,
1968 			 unsigned int			width_bias,
1969 			 int                            adjust_size,
1970 			 int                            adjust_crop)
1971 {
1972 	struct bttv *btv = fh->btv;
1973 	const struct v4l2_rect *b;
1974 	struct bttv_crop *c;
1975 	__s32 min_width;
1976 	__s32 min_height;
1977 	__s32 max_width;
1978 	__s32 max_height;
1979 	int rc;
1980 
1981 	BUG_ON((int) width_mask >= 0 ||
1982 	       width_bias >= (unsigned int) -width_mask);
1983 
1984 	/* Make sure tvnorm, vbi_end and the current cropping parameters
1985 	   remain consistent until we're done. */
1986 
1987 	b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
1988 
1989 	/* Do crop - use current, don't - use default parameters. */
1990 	c = &btv->crop[!!fh->do_crop];
1991 
1992 	if (fh->do_crop
1993 	    && adjust_size
1994 	    && adjust_crop
1995 	    && !locked_btres(btv, VIDEO_RESOURCES)) {
1996 		min_width = 48;
1997 		min_height = 32;
1998 
1999 		/* We cannot scale up. When the scaled image is larger
2000 		   than crop.rect we adjust the crop.rect as required
2001 		   by the V4L2 spec, hence cropcap.bounds are our limit. */
2002 		max_width = min_t(unsigned int, b->width, MAX_HACTIVE);
2003 		max_height = b->height;
2004 
2005 		/* We cannot capture the same line as video and VBI data.
2006 		   Note btv->vbi_end is really a minimum, see
2007 		   bttv_vbi_try_fmt(). */
2008 		if (btv->vbi_end > b->top) {
2009 			max_height -= btv->vbi_end - b->top;
2010 			rc = -EBUSY;
2011 			if (min_height > max_height)
2012 				goto fail;
2013 		}
2014 	} else {
2015 		rc = -EBUSY;
2016 		if (btv->vbi_end > c->rect.top)
2017 			goto fail;
2018 
2019 		min_width  = c->min_scaled_width;
2020 		min_height = c->min_scaled_height;
2021 		max_width  = c->max_scaled_width;
2022 		max_height = c->max_scaled_height;
2023 
2024 		adjust_crop = 0;
2025 	}
2026 
2027 	min_width = (min_width - width_mask - 1) & width_mask;
2028 	max_width = max_width & width_mask;
2029 
2030 	/* Max. scale factor is 16:1 for frames, 8:1 for fields. */
2031 	/* Min. scale factor is 1:1. */
2032 	max_height >>= !V4L2_FIELD_HAS_BOTH(field);
2033 
2034 	if (adjust_size) {
2035 		*width = clamp(*width, min_width, max_width);
2036 		*height = clamp(*height, min_height, max_height);
2037 
2038 		/* Round after clamping to avoid overflow. */
2039 		*width = (*width + width_bias) & width_mask;
2040 
2041 		if (adjust_crop) {
2042 			bttv_crop_adjust(c, b, *width, *height, field);
2043 
2044 			if (btv->vbi_end > c->rect.top) {
2045 				/* Move the crop window out of the way. */
2046 				c->rect.top = btv->vbi_end;
2047 			}
2048 		}
2049 	} else {
2050 		rc = -EINVAL;
2051 		if (*width  < min_width ||
2052 		    *height < min_height ||
2053 		    *width  > max_width ||
2054 		    *height > max_height ||
2055 		    0 != (*width & ~width_mask))
2056 			goto fail;
2057 	}
2058 
2059 	rc = 0; /* success */
2060 
2061  fail:
2062 
2063 	return rc;
2064 }
2065 
2066 /* Returns an error if the given overlay window dimensions are not
2067    possible with the current cropping parameters. If adjust_size is
2068    TRUE the function may adjust the window width and/or height
2069    instead, however it always rounds the horizontal position and
2070    width as btcx_align() does. If adjust_crop is TRUE the function
2071    may also adjust the current cropping parameters to get closer
2072    to the desired window size. */
2073 static int
2074 verify_window_lock(struct bttv_fh *fh, struct v4l2_window *win,
2075 			 int adjust_size, int adjust_crop)
2076 {
2077 	enum v4l2_field field;
2078 	unsigned int width_mask;
2079 	int rc;
2080 
2081 	if (win->w.width < 48)
2082 		win->w.width = 48;
2083 	if (win->w.height < 32)
2084 		win->w.height = 32;
2085 	if (win->clipcount > 2048)
2086 		win->clipcount = 2048;
2087 
2088 	win->chromakey = 0;
2089 	win->global_alpha = 0;
2090 	field = win->field;
2091 
2092 	switch (field) {
2093 	case V4L2_FIELD_TOP:
2094 	case V4L2_FIELD_BOTTOM:
2095 	case V4L2_FIELD_INTERLACED:
2096 		break;
2097 	default:
2098 		field = V4L2_FIELD_ANY;
2099 		break;
2100 	}
2101 	if (V4L2_FIELD_ANY == field) {
2102 		__s32 height2;
2103 
2104 		height2 = fh->btv->crop[!!fh->do_crop].rect.height >> 1;
2105 		field = (win->w.height > height2)
2106 			? V4L2_FIELD_INTERLACED
2107 			: V4L2_FIELD_TOP;
2108 	}
2109 	win->field = field;
2110 
2111 	if (NULL == fh->ovfmt)
2112 		return -EINVAL;
2113 	/* 4-byte alignment. */
2114 	width_mask = ~0;
2115 	switch (fh->ovfmt->depth) {
2116 	case 8:
2117 	case 24:
2118 		width_mask = ~3;
2119 		break;
2120 	case 16:
2121 		width_mask = ~1;
2122 		break;
2123 	case 32:
2124 		break;
2125 	default:
2126 		BUG();
2127 	}
2128 
2129 	win->w.width -= win->w.left & ~width_mask;
2130 	win->w.left = (win->w.left - width_mask - 1) & width_mask;
2131 
2132 	rc = limit_scaled_size_lock(fh, &win->w.width, &win->w.height,
2133 			       field, width_mask,
2134 			       /* width_bias: round down */ 0,
2135 			       adjust_size, adjust_crop);
2136 	if (0 != rc)
2137 		return rc;
2138 	return 0;
2139 }
2140 
2141 static int setup_window_lock(struct bttv_fh *fh, struct bttv *btv,
2142 			struct v4l2_window *win, int fixup)
2143 {
2144 	struct v4l2_clip *clips = NULL;
2145 	int n,size,retval = 0;
2146 
2147 	if (NULL == fh->ovfmt)
2148 		return -EINVAL;
2149 	if (!(fh->ovfmt->flags & FORMAT_FLAGS_PACKED))
2150 		return -EINVAL;
2151 	retval = verify_window_lock(fh, win,
2152 			       /* adjust_size */ fixup,
2153 			       /* adjust_crop */ fixup);
2154 	if (0 != retval)
2155 		return retval;
2156 
2157 	/* copy clips  --  luckily v4l1 + v4l2 are binary
2158 	   compatible here ...*/
2159 	n = win->clipcount;
2160 	size = sizeof(*clips)*(n+4);
2161 	clips = kmalloc(size,GFP_KERNEL);
2162 	if (NULL == clips)
2163 		return -ENOMEM;
2164 	if (n > 0) {
2165 		if (copy_from_user(clips,win->clips,sizeof(struct v4l2_clip)*n)) {
2166 			kfree(clips);
2167 			return -EFAULT;
2168 		}
2169 	}
2170 
2171 	/* clip against screen */
2172 	if (NULL != btv->fbuf.base)
2173 		n = btcx_screen_clips(btv->fbuf.fmt.width, btv->fbuf.fmt.height,
2174 				      &win->w, clips, n);
2175 	btcx_sort_clips(clips,n);
2176 
2177 	/* 4-byte alignments */
2178 	switch (fh->ovfmt->depth) {
2179 	case 8:
2180 	case 24:
2181 		btcx_align(&win->w, clips, n, 3);
2182 		break;
2183 	case 16:
2184 		btcx_align(&win->w, clips, n, 1);
2185 		break;
2186 	case 32:
2187 		/* no alignment fixups needed */
2188 		break;
2189 	default:
2190 		BUG();
2191 	}
2192 
2193 	kfree(fh->ov.clips);
2194 	fh->ov.clips    = clips;
2195 	fh->ov.nclips   = n;
2196 
2197 	fh->ov.w        = win->w;
2198 	fh->ov.field    = win->field;
2199 	fh->ov.setup_ok = 1;
2200 
2201 	btv->init.ov.w.width   = win->w.width;
2202 	btv->init.ov.w.height  = win->w.height;
2203 	btv->init.ov.field     = win->field;
2204 
2205 	/* update overlay if needed */
2206 	retval = 0;
2207 	if (check_btres(fh, RESOURCE_OVERLAY)) {
2208 		struct bttv_buffer *new;
2209 
2210 		new = videobuf_sg_alloc(sizeof(*new));
2211 		new->crop = btv->crop[!!fh->do_crop].rect;
2212 		bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2213 		retval = bttv_switch_overlay(btv,fh,new);
2214 	}
2215 	return retval;
2216 }
2217 
2218 /* ----------------------------------------------------------------------- */
2219 
2220 static struct videobuf_queue* bttv_queue(struct bttv_fh *fh)
2221 {
2222 	struct videobuf_queue* q = NULL;
2223 
2224 	switch (fh->type) {
2225 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2226 		q = &fh->cap;
2227 		break;
2228 	case V4L2_BUF_TYPE_VBI_CAPTURE:
2229 		q = &fh->vbi;
2230 		break;
2231 	default:
2232 		BUG();
2233 	}
2234 	return q;
2235 }
2236 
2237 static int bttv_resource(struct bttv_fh *fh)
2238 {
2239 	int res = 0;
2240 
2241 	switch (fh->type) {
2242 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2243 		res = RESOURCE_VIDEO_STREAM;
2244 		break;
2245 	case V4L2_BUF_TYPE_VBI_CAPTURE:
2246 		res = RESOURCE_VBI;
2247 		break;
2248 	default:
2249 		BUG();
2250 	}
2251 	return res;
2252 }
2253 
2254 static int bttv_switch_type(struct bttv_fh *fh, enum v4l2_buf_type type)
2255 {
2256 	struct videobuf_queue *q = bttv_queue(fh);
2257 	int res = bttv_resource(fh);
2258 
2259 	if (check_btres(fh,res))
2260 		return -EBUSY;
2261 	if (videobuf_queue_is_busy(q))
2262 		return -EBUSY;
2263 	fh->type = type;
2264 	return 0;
2265 }
2266 
2267 static void
2268 pix_format_set_size     (struct v4l2_pix_format *       f,
2269 			 const struct bttv_format *     fmt,
2270 			 unsigned int                   width,
2271 			 unsigned int                   height)
2272 {
2273 	f->width = width;
2274 	f->height = height;
2275 
2276 	if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2277 		f->bytesperline = width; /* Y plane */
2278 		f->sizeimage = (width * height * fmt->depth) >> 3;
2279 	} else {
2280 		f->bytesperline = (width * fmt->depth) >> 3;
2281 		f->sizeimage = height * f->bytesperline;
2282 	}
2283 }
2284 
2285 static int bttv_g_fmt_vid_cap(struct file *file, void *priv,
2286 					struct v4l2_format *f)
2287 {
2288 	struct bttv_fh *fh  = priv;
2289 
2290 	pix_format_set_size(&f->fmt.pix, fh->fmt,
2291 				fh->width, fh->height);
2292 	f->fmt.pix.field        = fh->cap.field;
2293 	f->fmt.pix.pixelformat  = fh->fmt->fourcc;
2294 	f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
2295 
2296 	return 0;
2297 }
2298 
2299 static int bttv_g_fmt_vid_overlay(struct file *file, void *priv,
2300 					struct v4l2_format *f)
2301 {
2302 	struct bttv_fh *fh  = priv;
2303 
2304 	f->fmt.win.w     = fh->ov.w;
2305 	f->fmt.win.field = fh->ov.field;
2306 
2307 	return 0;
2308 }
2309 
2310 static void bttv_get_width_mask_vid_cap(const struct bttv_format *fmt,
2311 					unsigned int *width_mask,
2312 					unsigned int *width_bias)
2313 {
2314 	if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2315 		*width_mask = ~15; /* width must be a multiple of 16 pixels */
2316 		*width_bias = 8;   /* nearest */
2317 	} else {
2318 		*width_mask = ~3; /* width must be a multiple of 4 pixels */
2319 		*width_bias = 2;  /* nearest */
2320 	}
2321 }
2322 
2323 static int bttv_try_fmt_vid_cap(struct file *file, void *priv,
2324 						struct v4l2_format *f)
2325 {
2326 	const struct bttv_format *fmt;
2327 	struct bttv_fh *fh = priv;
2328 	struct bttv *btv = fh->btv;
2329 	enum v4l2_field field;
2330 	__s32 width, height;
2331 	__s32 height2;
2332 	unsigned int width_mask, width_bias;
2333 	int rc;
2334 
2335 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2336 	if (NULL == fmt)
2337 		return -EINVAL;
2338 
2339 	field = f->fmt.pix.field;
2340 
2341 	switch (field) {
2342 	case V4L2_FIELD_TOP:
2343 	case V4L2_FIELD_BOTTOM:
2344 	case V4L2_FIELD_ALTERNATE:
2345 	case V4L2_FIELD_INTERLACED:
2346 		break;
2347 	case V4L2_FIELD_SEQ_BT:
2348 	case V4L2_FIELD_SEQ_TB:
2349 		if (!(fmt->flags & FORMAT_FLAGS_PLANAR)) {
2350 			field = V4L2_FIELD_SEQ_TB;
2351 			break;
2352 		}
2353 		/* fall through */
2354 	default: /* FIELD_ANY case */
2355 		height2 = btv->crop[!!fh->do_crop].rect.height >> 1;
2356 		field = (f->fmt.pix.height > height2)
2357 			? V4L2_FIELD_INTERLACED
2358 			: V4L2_FIELD_BOTTOM;
2359 		break;
2360 	}
2361 
2362 	width = f->fmt.pix.width;
2363 	height = f->fmt.pix.height;
2364 
2365 	bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2366 	rc = limit_scaled_size_lock(fh, &width, &height, field,
2367 			       width_mask, width_bias,
2368 			       /* adjust_size */ 1,
2369 			       /* adjust_crop */ 0);
2370 	if (0 != rc)
2371 		return rc;
2372 
2373 	/* update data for the application */
2374 	f->fmt.pix.field = field;
2375 	pix_format_set_size(&f->fmt.pix, fmt, width, height);
2376 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
2377 
2378 	return 0;
2379 }
2380 
2381 static int bttv_try_fmt_vid_overlay(struct file *file, void *priv,
2382 						struct v4l2_format *f)
2383 {
2384 	struct bttv_fh *fh = priv;
2385 
2386 	verify_window_lock(fh, &f->fmt.win,
2387 			/* adjust_size */ 1,
2388 			/* adjust_crop */ 0);
2389 	return 0;
2390 }
2391 
2392 static int bttv_s_fmt_vid_cap(struct file *file, void *priv,
2393 				struct v4l2_format *f)
2394 {
2395 	int retval;
2396 	const struct bttv_format *fmt;
2397 	struct bttv_fh *fh = priv;
2398 	struct bttv *btv = fh->btv;
2399 	__s32 width, height;
2400 	unsigned int width_mask, width_bias;
2401 	enum v4l2_field field;
2402 
2403 	retval = bttv_switch_type(fh, f->type);
2404 	if (0 != retval)
2405 		return retval;
2406 
2407 	retval = bttv_try_fmt_vid_cap(file, priv, f);
2408 	if (0 != retval)
2409 		return retval;
2410 
2411 	width = f->fmt.pix.width;
2412 	height = f->fmt.pix.height;
2413 	field = f->fmt.pix.field;
2414 
2415 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2416 	bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2417 	retval = limit_scaled_size_lock(fh, &width, &height, f->fmt.pix.field,
2418 			       width_mask, width_bias,
2419 			       /* adjust_size */ 1,
2420 			       /* adjust_crop */ 1);
2421 	if (0 != retval)
2422 		return retval;
2423 
2424 	f->fmt.pix.field = field;
2425 
2426 	/* update our state information */
2427 	fh->fmt              = fmt;
2428 	fh->cap.field        = f->fmt.pix.field;
2429 	fh->cap.last         = V4L2_FIELD_NONE;
2430 	fh->width            = f->fmt.pix.width;
2431 	fh->height           = f->fmt.pix.height;
2432 	btv->init.fmt        = fmt;
2433 	btv->init.width      = f->fmt.pix.width;
2434 	btv->init.height     = f->fmt.pix.height;
2435 
2436 	return 0;
2437 }
2438 
2439 static int bttv_s_fmt_vid_overlay(struct file *file, void *priv,
2440 				struct v4l2_format *f)
2441 {
2442 	struct bttv_fh *fh = priv;
2443 	struct bttv *btv = fh->btv;
2444 
2445 	if (no_overlay > 0) {
2446 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2447 		return -EINVAL;
2448 	}
2449 
2450 	return setup_window_lock(fh, btv, &f->fmt.win, 1);
2451 }
2452 
2453 static int bttv_querycap(struct file *file, void  *priv,
2454 				struct v4l2_capability *cap)
2455 {
2456 	struct video_device *vdev = video_devdata(file);
2457 	struct bttv_fh *fh = priv;
2458 	struct bttv *btv = fh->btv;
2459 
2460 	if (0 == v4l2)
2461 		return -EINVAL;
2462 
2463 	strscpy(cap->driver, "bttv", sizeof(cap->driver));
2464 	strscpy(cap->card, btv->video_dev.name, sizeof(cap->card));
2465 	snprintf(cap->bus_info, sizeof(cap->bus_info),
2466 		 "PCI:%s", pci_name(btv->c.pci));
2467 	cap->capabilities =
2468 		V4L2_CAP_VIDEO_CAPTURE |
2469 		V4L2_CAP_READWRITE |
2470 		V4L2_CAP_STREAMING |
2471 		V4L2_CAP_DEVICE_CAPS;
2472 	if (no_overlay <= 0)
2473 		cap->capabilities |= V4L2_CAP_VIDEO_OVERLAY;
2474 	if (video_is_registered(&btv->vbi_dev))
2475 		cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
2476 	if (video_is_registered(&btv->radio_dev))
2477 		cap->capabilities |= V4L2_CAP_RADIO;
2478 
2479 	/*
2480 	 * No need to lock here: those vars are initialized during board
2481 	 * probe and remains untouched during the rest of the driver lifecycle
2482 	 */
2483 	if (btv->has_saa6588)
2484 		cap->capabilities |= V4L2_CAP_RDS_CAPTURE;
2485 	if (btv->tuner_type != TUNER_ABSENT)
2486 		cap->capabilities |= V4L2_CAP_TUNER;
2487 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
2488 		cap->device_caps = cap->capabilities &
2489 			(V4L2_CAP_VIDEO_CAPTURE |
2490 			 V4L2_CAP_READWRITE |
2491 			 V4L2_CAP_STREAMING |
2492 			 V4L2_CAP_VIDEO_OVERLAY |
2493 			 V4L2_CAP_TUNER);
2494 	else if (vdev->vfl_type == VFL_TYPE_VBI)
2495 		cap->device_caps = cap->capabilities &
2496 			(V4L2_CAP_VBI_CAPTURE |
2497 			 V4L2_CAP_READWRITE |
2498 			 V4L2_CAP_STREAMING |
2499 			 V4L2_CAP_TUNER);
2500 	else {
2501 		cap->device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
2502 		if (btv->has_saa6588)
2503 			cap->device_caps |= V4L2_CAP_READWRITE |
2504 						V4L2_CAP_RDS_CAPTURE;
2505 		if (btv->has_tea575x)
2506 			cap->device_caps |= V4L2_CAP_HW_FREQ_SEEK;
2507 	}
2508 	return 0;
2509 }
2510 
2511 static int bttv_enum_fmt_cap_ovr(struct v4l2_fmtdesc *f)
2512 {
2513 	int index = -1, i;
2514 
2515 	for (i = 0; i < FORMATS; i++) {
2516 		if (formats[i].fourcc != -1)
2517 			index++;
2518 		if ((unsigned int)index == f->index)
2519 			break;
2520 	}
2521 	if (FORMATS == i)
2522 		return -EINVAL;
2523 
2524 	f->pixelformat = formats[i].fourcc;
2525 	strscpy(f->description, formats[i].name, sizeof(f->description));
2526 
2527 	return i;
2528 }
2529 
2530 static int bttv_enum_fmt_vid_cap(struct file *file, void  *priv,
2531 				struct v4l2_fmtdesc *f)
2532 {
2533 	int rc = bttv_enum_fmt_cap_ovr(f);
2534 
2535 	if (rc < 0)
2536 		return rc;
2537 
2538 	return 0;
2539 }
2540 
2541 static int bttv_enum_fmt_vid_overlay(struct file *file, void  *priv,
2542 					struct v4l2_fmtdesc *f)
2543 {
2544 	int rc;
2545 
2546 	if (no_overlay > 0) {
2547 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2548 		return -EINVAL;
2549 	}
2550 
2551 	rc = bttv_enum_fmt_cap_ovr(f);
2552 
2553 	if (rc < 0)
2554 		return rc;
2555 
2556 	if (!(formats[rc].flags & FORMAT_FLAGS_PACKED))
2557 		return -EINVAL;
2558 
2559 	return 0;
2560 }
2561 
2562 static int bttv_g_fbuf(struct file *file, void *f,
2563 				struct v4l2_framebuffer *fb)
2564 {
2565 	struct bttv_fh *fh = f;
2566 	struct bttv *btv = fh->btv;
2567 
2568 	*fb = btv->fbuf;
2569 	fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
2570 	fb->flags = V4L2_FBUF_FLAG_PRIMARY;
2571 	if (fh->ovfmt)
2572 		fb->fmt.pixelformat  = fh->ovfmt->fourcc;
2573 	return 0;
2574 }
2575 
2576 static int bttv_overlay(struct file *file, void *f, unsigned int on)
2577 {
2578 	struct bttv_fh *fh = f;
2579 	struct bttv *btv = fh->btv;
2580 	struct bttv_buffer *new;
2581 	int retval = 0;
2582 
2583 	if (on) {
2584 		/* verify args */
2585 		if (unlikely(!btv->fbuf.base)) {
2586 			return -EINVAL;
2587 		}
2588 		if (unlikely(!fh->ov.setup_ok)) {
2589 			dprintk("%d: overlay: !setup_ok\n", btv->c.nr);
2590 			retval = -EINVAL;
2591 		}
2592 		if (retval)
2593 			return retval;
2594 	}
2595 
2596 	if (!check_alloc_btres_lock(btv, fh, RESOURCE_OVERLAY))
2597 		return -EBUSY;
2598 
2599 	if (on) {
2600 		fh->ov.tvnorm = btv->tvnorm;
2601 		new = videobuf_sg_alloc(sizeof(*new));
2602 		new->crop = btv->crop[!!fh->do_crop].rect;
2603 		bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2604 	} else {
2605 		new = NULL;
2606 	}
2607 
2608 	/* switch over */
2609 	retval = bttv_switch_overlay(btv, fh, new);
2610 	return retval;
2611 }
2612 
2613 static int bttv_s_fbuf(struct file *file, void *f,
2614 				const struct v4l2_framebuffer *fb)
2615 {
2616 	struct bttv_fh *fh = f;
2617 	struct bttv *btv = fh->btv;
2618 	const struct bttv_format *fmt;
2619 	int retval;
2620 
2621 	if (!capable(CAP_SYS_ADMIN) &&
2622 		!capable(CAP_SYS_RAWIO))
2623 		return -EPERM;
2624 
2625 	/* check args */
2626 	fmt = format_by_fourcc(fb->fmt.pixelformat);
2627 	if (NULL == fmt)
2628 		return -EINVAL;
2629 	if (0 == (fmt->flags & FORMAT_FLAGS_PACKED))
2630 		return -EINVAL;
2631 
2632 	retval = -EINVAL;
2633 	if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2634 		__s32 width = fb->fmt.width;
2635 		__s32 height = fb->fmt.height;
2636 
2637 		retval = limit_scaled_size_lock(fh, &width, &height,
2638 					   V4L2_FIELD_INTERLACED,
2639 					   /* width_mask */ ~3,
2640 					   /* width_bias */ 2,
2641 					   /* adjust_size */ 0,
2642 					   /* adjust_crop */ 0);
2643 		if (0 != retval)
2644 			return retval;
2645 	}
2646 
2647 	/* ok, accept it */
2648 	btv->fbuf.base       = fb->base;
2649 	btv->fbuf.fmt.width  = fb->fmt.width;
2650 	btv->fbuf.fmt.height = fb->fmt.height;
2651 	if (0 != fb->fmt.bytesperline)
2652 		btv->fbuf.fmt.bytesperline = fb->fmt.bytesperline;
2653 	else
2654 		btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fmt->depth/8;
2655 
2656 	retval = 0;
2657 	fh->ovfmt = fmt;
2658 	btv->init.ovfmt = fmt;
2659 	if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2660 		fh->ov.w.left   = 0;
2661 		fh->ov.w.top    = 0;
2662 		fh->ov.w.width  = fb->fmt.width;
2663 		fh->ov.w.height = fb->fmt.height;
2664 		btv->init.ov.w.width  = fb->fmt.width;
2665 		btv->init.ov.w.height = fb->fmt.height;
2666 
2667 		kfree(fh->ov.clips);
2668 		fh->ov.clips = NULL;
2669 		fh->ov.nclips = 0;
2670 
2671 		if (check_btres(fh, RESOURCE_OVERLAY)) {
2672 			struct bttv_buffer *new;
2673 
2674 			new = videobuf_sg_alloc(sizeof(*new));
2675 			new->crop = btv->crop[!!fh->do_crop].rect;
2676 			bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2677 			retval = bttv_switch_overlay(btv, fh, new);
2678 		}
2679 	}
2680 	return retval;
2681 }
2682 
2683 static int bttv_reqbufs(struct file *file, void *priv,
2684 				struct v4l2_requestbuffers *p)
2685 {
2686 	struct bttv_fh *fh = priv;
2687 	return videobuf_reqbufs(bttv_queue(fh), p);
2688 }
2689 
2690 static int bttv_querybuf(struct file *file, void *priv,
2691 				struct v4l2_buffer *b)
2692 {
2693 	struct bttv_fh *fh = priv;
2694 	return videobuf_querybuf(bttv_queue(fh), b);
2695 }
2696 
2697 static int bttv_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2698 {
2699 	struct bttv_fh *fh = priv;
2700 	struct bttv *btv = fh->btv;
2701 	int res = bttv_resource(fh);
2702 
2703 	if (!check_alloc_btres_lock(btv, fh, res))
2704 		return -EBUSY;
2705 
2706 	return videobuf_qbuf(bttv_queue(fh), b);
2707 }
2708 
2709 static int bttv_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2710 {
2711 	struct bttv_fh *fh = priv;
2712 	return videobuf_dqbuf(bttv_queue(fh), b,
2713 			file->f_flags & O_NONBLOCK);
2714 }
2715 
2716 static int bttv_streamon(struct file *file, void *priv,
2717 					enum v4l2_buf_type type)
2718 {
2719 	struct bttv_fh *fh = priv;
2720 	struct bttv *btv = fh->btv;
2721 	int res = bttv_resource(fh);
2722 
2723 	if (!check_alloc_btres_lock(btv, fh, res))
2724 		return -EBUSY;
2725 	return videobuf_streamon(bttv_queue(fh));
2726 }
2727 
2728 
2729 static int bttv_streamoff(struct file *file, void *priv,
2730 					enum v4l2_buf_type type)
2731 {
2732 	struct bttv_fh *fh = priv;
2733 	struct bttv *btv = fh->btv;
2734 	int retval;
2735 	int res = bttv_resource(fh);
2736 
2737 
2738 	retval = videobuf_streamoff(bttv_queue(fh));
2739 	if (retval < 0)
2740 		return retval;
2741 	free_btres_lock(btv, fh, res);
2742 	return 0;
2743 }
2744 
2745 static int bttv_g_parm(struct file *file, void *f,
2746 				struct v4l2_streamparm *parm)
2747 {
2748 	struct bttv_fh *fh = f;
2749 	struct bttv *btv = fh->btv;
2750 
2751 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2752 		return -EINVAL;
2753 	parm->parm.capture.readbuffers = gbuffers;
2754 	v4l2_video_std_frame_period(bttv_tvnorms[btv->tvnorm].v4l2_id,
2755 				    &parm->parm.capture.timeperframe);
2756 
2757 	return 0;
2758 }
2759 
2760 static int bttv_g_tuner(struct file *file, void *priv,
2761 				struct v4l2_tuner *t)
2762 {
2763 	struct bttv_fh *fh = priv;
2764 	struct bttv *btv = fh->btv;
2765 
2766 	if (0 != t->index)
2767 		return -EINVAL;
2768 
2769 	t->rxsubchans = V4L2_TUNER_SUB_MONO;
2770 	t->capability = V4L2_TUNER_CAP_NORM;
2771 	bttv_call_all(btv, tuner, g_tuner, t);
2772 	strscpy(t->name, "Television", sizeof(t->name));
2773 	t->type       = V4L2_TUNER_ANALOG_TV;
2774 	if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
2775 		t->signal = 0xffff;
2776 
2777 	if (btv->audio_mode_gpio)
2778 		btv->audio_mode_gpio(btv, t, 0);
2779 
2780 	return 0;
2781 }
2782 
2783 static int bttv_g_pixelaspect(struct file *file, void *priv,
2784 			      int type, struct v4l2_fract *f)
2785 {
2786 	struct bttv_fh *fh = priv;
2787 	struct bttv *btv = fh->btv;
2788 
2789 	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2790 		return -EINVAL;
2791 
2792 	/* defrect and bounds are set via g_selection */
2793 	*f = bttv_tvnorms[btv->tvnorm].cropcap.pixelaspect;
2794 	return 0;
2795 }
2796 
2797 static int bttv_g_selection(struct file *file, void *f, struct v4l2_selection *sel)
2798 {
2799 	struct bttv_fh *fh = f;
2800 	struct bttv *btv = fh->btv;
2801 
2802 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2803 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2804 		return -EINVAL;
2805 
2806 	switch (sel->target) {
2807 	case V4L2_SEL_TGT_CROP:
2808 		/*
2809 		 * No fh->do_crop = 1; because btv->crop[1] may be
2810 		 * inconsistent with fh->width or fh->height and apps
2811 		 * do not expect a change here.
2812 		 */
2813 		sel->r = btv->crop[!!fh->do_crop].rect;
2814 		break;
2815 	case V4L2_SEL_TGT_CROP_DEFAULT:
2816 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.defrect;
2817 		break;
2818 	case V4L2_SEL_TGT_CROP_BOUNDS:
2819 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2820 		break;
2821 	default:
2822 		return -EINVAL;
2823 	}
2824 
2825 	return 0;
2826 }
2827 
2828 static int bttv_s_selection(struct file *file, void *f, struct v4l2_selection *sel)
2829 {
2830 	struct bttv_fh *fh = f;
2831 	struct bttv *btv = fh->btv;
2832 	const struct v4l2_rect *b;
2833 	int retval;
2834 	struct bttv_crop c;
2835 	__s32 b_left;
2836 	__s32 b_top;
2837 	__s32 b_right;
2838 	__s32 b_bottom;
2839 
2840 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2841 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2842 		return -EINVAL;
2843 
2844 	if (sel->target != V4L2_SEL_TGT_CROP)
2845 		return -EINVAL;
2846 
2847 	/* Make sure tvnorm, vbi_end and the current cropping
2848 	   parameters remain consistent until we're done. Note
2849 	   read() may change vbi_end in check_alloc_btres_lock(). */
2850 	retval = -EBUSY;
2851 
2852 	if (locked_btres(fh->btv, VIDEO_RESOURCES)) {
2853 		return retval;
2854 	}
2855 
2856 	b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2857 
2858 	b_left = b->left;
2859 	b_right = b_left + b->width;
2860 	b_bottom = b->top + b->height;
2861 
2862 	b_top = max(b->top, btv->vbi_end);
2863 	if (b_top + 32 >= b_bottom) {
2864 		return retval;
2865 	}
2866 
2867 	/* Min. scaled size 48 x 32. */
2868 	c.rect.left = clamp_t(s32, sel->r.left, b_left, b_right - 48);
2869 	c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
2870 
2871 	c.rect.width = clamp_t(s32, sel->r.width,
2872 			     48, b_right - c.rect.left);
2873 
2874 	c.rect.top = clamp_t(s32, sel->r.top, b_top, b_bottom - 32);
2875 	/* Top and height must be a multiple of two. */
2876 	c.rect.top = (c.rect.top + 1) & ~1;
2877 
2878 	c.rect.height = clamp_t(s32, sel->r.height,
2879 			      32, b_bottom - c.rect.top);
2880 	c.rect.height = (c.rect.height + 1) & ~1;
2881 
2882 	bttv_crop_calc_limits(&c);
2883 
2884 	sel->r = c.rect;
2885 
2886 	btv->crop[1] = c;
2887 
2888 	fh->do_crop = 1;
2889 
2890 	if (fh->width < c.min_scaled_width) {
2891 		fh->width = c.min_scaled_width;
2892 		btv->init.width = c.min_scaled_width;
2893 	} else if (fh->width > c.max_scaled_width) {
2894 		fh->width = c.max_scaled_width;
2895 		btv->init.width = c.max_scaled_width;
2896 	}
2897 
2898 	if (fh->height < c.min_scaled_height) {
2899 		fh->height = c.min_scaled_height;
2900 		btv->init.height = c.min_scaled_height;
2901 	} else if (fh->height > c.max_scaled_height) {
2902 		fh->height = c.max_scaled_height;
2903 		btv->init.height = c.max_scaled_height;
2904 	}
2905 
2906 	return 0;
2907 }
2908 
2909 static ssize_t bttv_read(struct file *file, char __user *data,
2910 			 size_t count, loff_t *ppos)
2911 {
2912 	struct bttv_fh *fh = file->private_data;
2913 	int retval = 0;
2914 
2915 	if (fh->btv->errors)
2916 		bttv_reinit_bt848(fh->btv);
2917 	dprintk("%d: read count=%d type=%s\n",
2918 		fh->btv->c.nr, (int)count, v4l2_type_names[fh->type]);
2919 
2920 	switch (fh->type) {
2921 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2922 		if (!check_alloc_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ)) {
2923 			/* VIDEO_READ in use by another fh,
2924 			   or VIDEO_STREAM by any fh. */
2925 			return -EBUSY;
2926 		}
2927 		retval = videobuf_read_one(&fh->cap, data, count, ppos,
2928 					   file->f_flags & O_NONBLOCK);
2929 		free_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ);
2930 		break;
2931 	case V4L2_BUF_TYPE_VBI_CAPTURE:
2932 		if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2933 			return -EBUSY;
2934 		retval = videobuf_read_stream(&fh->vbi, data, count, ppos, 1,
2935 					      file->f_flags & O_NONBLOCK);
2936 		break;
2937 	default:
2938 		BUG();
2939 	}
2940 	return retval;
2941 }
2942 
2943 static __poll_t bttv_poll(struct file *file, poll_table *wait)
2944 {
2945 	struct bttv_fh *fh = file->private_data;
2946 	struct bttv_buffer *buf;
2947 	enum v4l2_field field;
2948 	__poll_t rc = 0;
2949 	__poll_t req_events = poll_requested_events(wait);
2950 
2951 	if (v4l2_event_pending(&fh->fh))
2952 		rc = EPOLLPRI;
2953 	else if (req_events & EPOLLPRI)
2954 		poll_wait(file, &fh->fh.wait, wait);
2955 
2956 	if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
2957 		return rc;
2958 
2959 	if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
2960 		if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2961 			return rc | EPOLLERR;
2962 		return rc | videobuf_poll_stream(file, &fh->vbi, wait);
2963 	}
2964 
2965 	if (check_btres(fh,RESOURCE_VIDEO_STREAM)) {
2966 		/* streaming capture */
2967 		if (list_empty(&fh->cap.stream))
2968 			return rc | EPOLLERR;
2969 		buf = list_entry(fh->cap.stream.next,struct bttv_buffer,vb.stream);
2970 	} else {
2971 		/* read() capture */
2972 		if (NULL == fh->cap.read_buf) {
2973 			/* need to capture a new frame */
2974 			if (locked_btres(fh->btv,RESOURCE_VIDEO_STREAM))
2975 				return rc | EPOLLERR;
2976 			fh->cap.read_buf = videobuf_sg_alloc(fh->cap.msize);
2977 			if (NULL == fh->cap.read_buf)
2978 				return rc | EPOLLERR;
2979 			fh->cap.read_buf->memory = V4L2_MEMORY_USERPTR;
2980 			field = videobuf_next_field(&fh->cap);
2981 			if (0 != fh->cap.ops->buf_prepare(&fh->cap,fh->cap.read_buf,field)) {
2982 				kfree (fh->cap.read_buf);
2983 				fh->cap.read_buf = NULL;
2984 				return rc | EPOLLERR;
2985 			}
2986 			fh->cap.ops->buf_queue(&fh->cap,fh->cap.read_buf);
2987 			fh->cap.read_off = 0;
2988 		}
2989 		buf = (struct bttv_buffer*)fh->cap.read_buf;
2990 	}
2991 
2992 	poll_wait(file, &buf->vb.done, wait);
2993 	if (buf->vb.state == VIDEOBUF_DONE ||
2994 	    buf->vb.state == VIDEOBUF_ERROR)
2995 		rc = rc | EPOLLIN|EPOLLRDNORM;
2996 	return rc;
2997 }
2998 
2999 static int bttv_open(struct file *file)
3000 {
3001 	struct video_device *vdev = video_devdata(file);
3002 	struct bttv *btv = video_drvdata(file);
3003 	struct bttv_fh *fh;
3004 	enum v4l2_buf_type type = 0;
3005 
3006 	dprintk("open dev=%s\n", video_device_node_name(vdev));
3007 
3008 	if (vdev->vfl_type == VFL_TYPE_GRABBER) {
3009 		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3010 	} else if (vdev->vfl_type == VFL_TYPE_VBI) {
3011 		type = V4L2_BUF_TYPE_VBI_CAPTURE;
3012 	} else {
3013 		WARN_ON(1);
3014 		return -ENODEV;
3015 	}
3016 
3017 	dprintk("%d: open called (type=%s)\n",
3018 		btv->c.nr, v4l2_type_names[type]);
3019 
3020 	/* allocate per filehandle data */
3021 	fh = kmalloc(sizeof(*fh), GFP_KERNEL);
3022 	if (unlikely(!fh))
3023 		return -ENOMEM;
3024 	btv->users++;
3025 	file->private_data = fh;
3026 
3027 	*fh = btv->init;
3028 	v4l2_fh_init(&fh->fh, vdev);
3029 
3030 	fh->type = type;
3031 	fh->ov.setup_ok = 0;
3032 
3033 	videobuf_queue_sg_init(&fh->cap, &bttv_video_qops,
3034 			    &btv->c.pci->dev, &btv->s_lock,
3035 			    V4L2_BUF_TYPE_VIDEO_CAPTURE,
3036 			    V4L2_FIELD_INTERLACED,
3037 			    sizeof(struct bttv_buffer),
3038 			    fh, &btv->lock);
3039 	videobuf_queue_sg_init(&fh->vbi, &bttv_vbi_qops,
3040 			    &btv->c.pci->dev, &btv->s_lock,
3041 			    V4L2_BUF_TYPE_VBI_CAPTURE,
3042 			    V4L2_FIELD_SEQ_TB,
3043 			    sizeof(struct bttv_buffer),
3044 			    fh, &btv->lock);
3045 	set_tvnorm(btv,btv->tvnorm);
3046 	set_input(btv, btv->input, btv->tvnorm);
3047 	audio_mute(btv, btv->mute);
3048 
3049 	/* The V4L2 spec requires one global set of cropping parameters
3050 	   which only change on request. These are stored in btv->crop[1].
3051 	   However for compatibility with V4L apps and cropping unaware
3052 	   V4L2 apps we now reset the cropping parameters as seen through
3053 	   this fh, which is to say VIDIOC_G_SELECTION and scaling limit checks
3054 	   will use btv->crop[0], the default cropping parameters for the
3055 	   current video standard, and VIDIOC_S_FMT will not implicitly
3056 	   change the cropping parameters until VIDIOC_S_SELECTION has been
3057 	   called. */
3058 	fh->do_crop = !reset_crop; /* module parameter */
3059 
3060 	/* Likewise there should be one global set of VBI capture
3061 	   parameters, but for compatibility with V4L apps and earlier
3062 	   driver versions each fh has its own parameters. */
3063 	bttv_vbi_fmt_reset(&fh->vbi_fmt, btv->tvnorm);
3064 
3065 	bttv_field_count(btv);
3066 	v4l2_fh_add(&fh->fh);
3067 	return 0;
3068 }
3069 
3070 static int bttv_release(struct file *file)
3071 {
3072 	struct bttv_fh *fh = file->private_data;
3073 	struct bttv *btv = fh->btv;
3074 
3075 	/* turn off overlay */
3076 	if (check_btres(fh, RESOURCE_OVERLAY))
3077 		bttv_switch_overlay(btv,fh,NULL);
3078 
3079 	/* stop video capture */
3080 	if (check_btres(fh, RESOURCE_VIDEO_STREAM)) {
3081 		videobuf_streamoff(&fh->cap);
3082 		free_btres_lock(btv,fh,RESOURCE_VIDEO_STREAM);
3083 	}
3084 	if (fh->cap.read_buf) {
3085 		buffer_release(&fh->cap,fh->cap.read_buf);
3086 		kfree(fh->cap.read_buf);
3087 	}
3088 	if (check_btres(fh, RESOURCE_VIDEO_READ)) {
3089 		free_btres_lock(btv, fh, RESOURCE_VIDEO_READ);
3090 	}
3091 
3092 	/* stop vbi capture */
3093 	if (check_btres(fh, RESOURCE_VBI)) {
3094 		videobuf_stop(&fh->vbi);
3095 		free_btres_lock(btv,fh,RESOURCE_VBI);
3096 	}
3097 
3098 	/* free stuff */
3099 
3100 	videobuf_mmap_free(&fh->cap);
3101 	videobuf_mmap_free(&fh->vbi);
3102 	file->private_data = NULL;
3103 
3104 	btv->users--;
3105 	bttv_field_count(btv);
3106 
3107 	if (!btv->users)
3108 		audio_mute(btv, btv->mute);
3109 
3110 	v4l2_fh_del(&fh->fh);
3111 	v4l2_fh_exit(&fh->fh);
3112 	kfree(fh);
3113 	return 0;
3114 }
3115 
3116 static int
3117 bttv_mmap(struct file *file, struct vm_area_struct *vma)
3118 {
3119 	struct bttv_fh *fh = file->private_data;
3120 
3121 	dprintk("%d: mmap type=%s 0x%lx+%ld\n",
3122 		fh->btv->c.nr, v4l2_type_names[fh->type],
3123 		vma->vm_start, vma->vm_end - vma->vm_start);
3124 	return videobuf_mmap_mapper(bttv_queue(fh),vma);
3125 }
3126 
3127 static const struct v4l2_file_operations bttv_fops =
3128 {
3129 	.owner		  = THIS_MODULE,
3130 	.open		  = bttv_open,
3131 	.release	  = bttv_release,
3132 	.unlocked_ioctl	  = video_ioctl2,
3133 	.read		  = bttv_read,
3134 	.mmap		  = bttv_mmap,
3135 	.poll		  = bttv_poll,
3136 };
3137 
3138 static const struct v4l2_ioctl_ops bttv_ioctl_ops = {
3139 	.vidioc_querycap                = bttv_querycap,
3140 	.vidioc_enum_fmt_vid_cap        = bttv_enum_fmt_vid_cap,
3141 	.vidioc_g_fmt_vid_cap           = bttv_g_fmt_vid_cap,
3142 	.vidioc_try_fmt_vid_cap         = bttv_try_fmt_vid_cap,
3143 	.vidioc_s_fmt_vid_cap           = bttv_s_fmt_vid_cap,
3144 	.vidioc_enum_fmt_vid_overlay    = bttv_enum_fmt_vid_overlay,
3145 	.vidioc_g_fmt_vid_overlay       = bttv_g_fmt_vid_overlay,
3146 	.vidioc_try_fmt_vid_overlay     = bttv_try_fmt_vid_overlay,
3147 	.vidioc_s_fmt_vid_overlay       = bttv_s_fmt_vid_overlay,
3148 	.vidioc_g_fmt_vbi_cap           = bttv_g_fmt_vbi_cap,
3149 	.vidioc_try_fmt_vbi_cap         = bttv_try_fmt_vbi_cap,
3150 	.vidioc_s_fmt_vbi_cap           = bttv_s_fmt_vbi_cap,
3151 	.vidioc_g_pixelaspect           = bttv_g_pixelaspect,
3152 	.vidioc_reqbufs                 = bttv_reqbufs,
3153 	.vidioc_querybuf                = bttv_querybuf,
3154 	.vidioc_qbuf                    = bttv_qbuf,
3155 	.vidioc_dqbuf                   = bttv_dqbuf,
3156 	.vidioc_s_std                   = bttv_s_std,
3157 	.vidioc_g_std                   = bttv_g_std,
3158 	.vidioc_enum_input              = bttv_enum_input,
3159 	.vidioc_g_input                 = bttv_g_input,
3160 	.vidioc_s_input                 = bttv_s_input,
3161 	.vidioc_streamon                = bttv_streamon,
3162 	.vidioc_streamoff               = bttv_streamoff,
3163 	.vidioc_g_tuner                 = bttv_g_tuner,
3164 	.vidioc_s_tuner                 = bttv_s_tuner,
3165 	.vidioc_g_selection             = bttv_g_selection,
3166 	.vidioc_s_selection             = bttv_s_selection,
3167 	.vidioc_g_fbuf                  = bttv_g_fbuf,
3168 	.vidioc_s_fbuf                  = bttv_s_fbuf,
3169 	.vidioc_overlay                 = bttv_overlay,
3170 	.vidioc_g_parm                  = bttv_g_parm,
3171 	.vidioc_g_frequency             = bttv_g_frequency,
3172 	.vidioc_s_frequency             = bttv_s_frequency,
3173 	.vidioc_log_status		= bttv_log_status,
3174 	.vidioc_querystd		= bttv_querystd,
3175 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
3176 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
3177 #ifdef CONFIG_VIDEO_ADV_DEBUG
3178 	.vidioc_g_register		= bttv_g_register,
3179 	.vidioc_s_register		= bttv_s_register,
3180 #endif
3181 };
3182 
3183 static struct video_device bttv_video_template = {
3184 	.fops         = &bttv_fops,
3185 	.ioctl_ops    = &bttv_ioctl_ops,
3186 	.tvnorms      = BTTV_NORMS,
3187 };
3188 
3189 /* ----------------------------------------------------------------------- */
3190 /* radio interface                                                         */
3191 
3192 static int radio_open(struct file *file)
3193 {
3194 	struct video_device *vdev = video_devdata(file);
3195 	struct bttv *btv = video_drvdata(file);
3196 	struct bttv_fh *fh;
3197 
3198 	dprintk("open dev=%s\n", video_device_node_name(vdev));
3199 
3200 	dprintk("%d: open called (radio)\n", btv->c.nr);
3201 
3202 	/* allocate per filehandle data */
3203 	fh = kmalloc(sizeof(*fh), GFP_KERNEL);
3204 	if (unlikely(!fh))
3205 		return -ENOMEM;
3206 	file->private_data = fh;
3207 	*fh = btv->init;
3208 	v4l2_fh_init(&fh->fh, vdev);
3209 
3210 	btv->radio_user++;
3211 	audio_mute(btv, btv->mute);
3212 
3213 	v4l2_fh_add(&fh->fh);
3214 
3215 	return 0;
3216 }
3217 
3218 static int radio_release(struct file *file)
3219 {
3220 	struct bttv_fh *fh = file->private_data;
3221 	struct bttv *btv = fh->btv;
3222 	struct saa6588_command cmd;
3223 
3224 	file->private_data = NULL;
3225 	v4l2_fh_del(&fh->fh);
3226 	v4l2_fh_exit(&fh->fh);
3227 	kfree(fh);
3228 
3229 	btv->radio_user--;
3230 
3231 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_CLOSE, &cmd);
3232 
3233 	if (btv->radio_user == 0)
3234 		btv->has_radio_tuner = 0;
3235 	return 0;
3236 }
3237 
3238 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
3239 {
3240 	struct bttv_fh *fh = priv;
3241 	struct bttv *btv = fh->btv;
3242 
3243 	if (0 != t->index)
3244 		return -EINVAL;
3245 	strscpy(t->name, "Radio", sizeof(t->name));
3246 	t->type = V4L2_TUNER_RADIO;
3247 	radio_enable(btv);
3248 
3249 	bttv_call_all(btv, tuner, g_tuner, t);
3250 
3251 	if (btv->audio_mode_gpio)
3252 		btv->audio_mode_gpio(btv, t, 0);
3253 
3254 	if (btv->has_tea575x)
3255 		return snd_tea575x_g_tuner(&btv->tea, t);
3256 
3257 	return 0;
3258 }
3259 
3260 static int radio_s_tuner(struct file *file, void *priv,
3261 					const struct v4l2_tuner *t)
3262 {
3263 	struct bttv_fh *fh = priv;
3264 	struct bttv *btv = fh->btv;
3265 
3266 	if (0 != t->index)
3267 		return -EINVAL;
3268 
3269 	radio_enable(btv);
3270 	bttv_call_all(btv, tuner, s_tuner, t);
3271 	return 0;
3272 }
3273 
3274 static int radio_s_hw_freq_seek(struct file *file, void *priv,
3275 					const struct v4l2_hw_freq_seek *a)
3276 {
3277 	struct bttv_fh *fh = priv;
3278 	struct bttv *btv = fh->btv;
3279 
3280 	if (btv->has_tea575x)
3281 		return snd_tea575x_s_hw_freq_seek(file, &btv->tea, a);
3282 
3283 	return -ENOTTY;
3284 }
3285 
3286 static int radio_enum_freq_bands(struct file *file, void *priv,
3287 					 struct v4l2_frequency_band *band)
3288 {
3289 	struct bttv_fh *fh = priv;
3290 	struct bttv *btv = fh->btv;
3291 
3292 	if (btv->has_tea575x)
3293 		return snd_tea575x_enum_freq_bands(&btv->tea, band);
3294 
3295 	return -ENOTTY;
3296 }
3297 
3298 static ssize_t radio_read(struct file *file, char __user *data,
3299 			 size_t count, loff_t *ppos)
3300 {
3301 	struct bttv_fh *fh = file->private_data;
3302 	struct bttv *btv = fh->btv;
3303 	struct saa6588_command cmd;
3304 
3305 	cmd.block_count = count / 3;
3306 	cmd.nonblocking = file->f_flags & O_NONBLOCK;
3307 	cmd.buffer = data;
3308 	cmd.instance = file;
3309 	cmd.result = -ENODEV;
3310 	radio_enable(btv);
3311 
3312 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_READ, &cmd);
3313 
3314 	return cmd.result;
3315 }
3316 
3317 static __poll_t radio_poll(struct file *file, poll_table *wait)
3318 {
3319 	struct bttv_fh *fh = file->private_data;
3320 	struct bttv *btv = fh->btv;
3321 	__poll_t req_events = poll_requested_events(wait);
3322 	struct saa6588_command cmd;
3323 	__poll_t res = 0;
3324 
3325 	if (v4l2_event_pending(&fh->fh))
3326 		res = EPOLLPRI;
3327 	else if (req_events & EPOLLPRI)
3328 		poll_wait(file, &fh->fh.wait, wait);
3329 	radio_enable(btv);
3330 	cmd.instance = file;
3331 	cmd.event_list = wait;
3332 	cmd.poll_mask = res;
3333 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_POLL, &cmd);
3334 
3335 	return cmd.poll_mask;
3336 }
3337 
3338 static const struct v4l2_file_operations radio_fops =
3339 {
3340 	.owner	  = THIS_MODULE,
3341 	.open	  = radio_open,
3342 	.read     = radio_read,
3343 	.release  = radio_release,
3344 	.unlocked_ioctl = video_ioctl2,
3345 	.poll     = radio_poll,
3346 };
3347 
3348 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
3349 	.vidioc_querycap        = bttv_querycap,
3350 	.vidioc_log_status	= bttv_log_status,
3351 	.vidioc_g_tuner         = radio_g_tuner,
3352 	.vidioc_s_tuner         = radio_s_tuner,
3353 	.vidioc_g_frequency     = bttv_g_frequency,
3354 	.vidioc_s_frequency     = bttv_s_frequency,
3355 	.vidioc_s_hw_freq_seek	= radio_s_hw_freq_seek,
3356 	.vidioc_enum_freq_bands	= radio_enum_freq_bands,
3357 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
3358 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
3359 };
3360 
3361 static struct video_device radio_template = {
3362 	.fops      = &radio_fops,
3363 	.ioctl_ops = &radio_ioctl_ops,
3364 };
3365 
3366 /* ----------------------------------------------------------------------- */
3367 /* some debug code                                                         */
3368 
3369 static int bttv_risc_decode(u32 risc)
3370 {
3371 	static char *instr[16] = {
3372 		[ BT848_RISC_WRITE     >> 28 ] = "write",
3373 		[ BT848_RISC_SKIP      >> 28 ] = "skip",
3374 		[ BT848_RISC_WRITEC    >> 28 ] = "writec",
3375 		[ BT848_RISC_JUMP      >> 28 ] = "jump",
3376 		[ BT848_RISC_SYNC      >> 28 ] = "sync",
3377 		[ BT848_RISC_WRITE123  >> 28 ] = "write123",
3378 		[ BT848_RISC_SKIP123   >> 28 ] = "skip123",
3379 		[ BT848_RISC_WRITE1S23 >> 28 ] = "write1s23",
3380 	};
3381 	static int incr[16] = {
3382 		[ BT848_RISC_WRITE     >> 28 ] = 2,
3383 		[ BT848_RISC_JUMP      >> 28 ] = 2,
3384 		[ BT848_RISC_SYNC      >> 28 ] = 2,
3385 		[ BT848_RISC_WRITE123  >> 28 ] = 5,
3386 		[ BT848_RISC_SKIP123   >> 28 ] = 2,
3387 		[ BT848_RISC_WRITE1S23 >> 28 ] = 3,
3388 	};
3389 	static char *bits[] = {
3390 		"be0",  "be1",  "be2",  "be3/resync",
3391 		"set0", "set1", "set2", "set3",
3392 		"clr0", "clr1", "clr2", "clr3",
3393 		"irq",  "res",  "eol",  "sol",
3394 	};
3395 	int i;
3396 
3397 	pr_cont("0x%08x [ %s", risc,
3398 	       instr[risc >> 28] ? instr[risc >> 28] : "INVALID");
3399 	for (i = ARRAY_SIZE(bits)-1; i >= 0; i--)
3400 		if (risc & (1 << (i + 12)))
3401 			pr_cont(" %s", bits[i]);
3402 	pr_cont(" count=%d ]\n", risc & 0xfff);
3403 	return incr[risc >> 28] ? incr[risc >> 28] : 1;
3404 }
3405 
3406 static void bttv_risc_disasm(struct bttv *btv,
3407 			     struct btcx_riscmem *risc)
3408 {
3409 	unsigned int i,j,n;
3410 
3411 	pr_info("%s: risc disasm: %p [dma=0x%08lx]\n",
3412 		btv->c.v4l2_dev.name, risc->cpu, (unsigned long)risc->dma);
3413 	for (i = 0; i < (risc->size >> 2); i += n) {
3414 		pr_info("%s:   0x%lx: ",
3415 			btv->c.v4l2_dev.name,
3416 			(unsigned long)(risc->dma + (i<<2)));
3417 		n = bttv_risc_decode(le32_to_cpu(risc->cpu[i]));
3418 		for (j = 1; j < n; j++)
3419 			pr_info("%s:   0x%lx: 0x%08x [ arg #%d ]\n",
3420 				btv->c.v4l2_dev.name,
3421 				(unsigned long)(risc->dma + ((i+j)<<2)),
3422 				risc->cpu[i+j], j);
3423 		if (0 == risc->cpu[i])
3424 			break;
3425 	}
3426 }
3427 
3428 static void bttv_print_riscaddr(struct bttv *btv)
3429 {
3430 	pr_info("  main: %08llx\n", (unsigned long long)btv->main.dma);
3431 	pr_info("  vbi : o=%08llx e=%08llx\n",
3432 		btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
3433 		btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
3434 	pr_info("  cap : o=%08llx e=%08llx\n",
3435 		btv->curr.top
3436 		? (unsigned long long)btv->curr.top->top.dma : 0,
3437 		btv->curr.bottom
3438 		? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
3439 	pr_info("  scr : o=%08llx e=%08llx\n",
3440 		btv->screen ? (unsigned long long)btv->screen->top.dma : 0,
3441 		btv->screen ? (unsigned long long)btv->screen->bottom.dma : 0);
3442 	bttv_risc_disasm(btv, &btv->main);
3443 }
3444 
3445 /* ----------------------------------------------------------------------- */
3446 /* irq handler                                                             */
3447 
3448 static char *irq_name[] = {
3449 	"FMTCHG",  // format change detected (525 vs. 625)
3450 	"VSYNC",   // vertical sync (new field)
3451 	"HSYNC",   // horizontal sync
3452 	"OFLOW",   // chroma/luma AGC overflow
3453 	"HLOCK",   // horizontal lock changed
3454 	"VPRES",   // video presence changed
3455 	"6", "7",
3456 	"I2CDONE", // hw irc operation finished
3457 	"GPINT",   // gpio port triggered irq
3458 	"10",
3459 	"RISCI",   // risc instruction triggered irq
3460 	"FBUS",    // pixel data fifo dropped data (high pci bus latencies)
3461 	"FTRGT",   // pixel data fifo overrun
3462 	"FDSR",    // fifo data stream resyncronisation
3463 	"PPERR",   // parity error (data transfer)
3464 	"RIPERR",  // parity error (read risc instructions)
3465 	"PABORT",  // pci abort
3466 	"OCERR",   // risc instruction error
3467 	"SCERR",   // syncronisation error
3468 };
3469 
3470 static void bttv_print_irqbits(u32 print, u32 mark)
3471 {
3472 	unsigned int i;
3473 
3474 	pr_cont("bits:");
3475 	for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
3476 		if (print & (1 << i))
3477 			pr_cont(" %s", irq_name[i]);
3478 		if (mark & (1 << i))
3479 			pr_cont("*");
3480 	}
3481 }
3482 
3483 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
3484 {
3485 	pr_warn("%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
3486 		btv->c.nr,
3487 		(unsigned long)btv->main.dma,
3488 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_VBI+1]),
3489 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_FIELD+1]),
3490 		(unsigned long)rc);
3491 
3492 	if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
3493 		pr_notice("%d: Oh, there (temporarily?) is no input signal. Ok, then this is harmless, don't worry ;)\n",
3494 			  btv->c.nr);
3495 		return;
3496 	}
3497 	pr_notice("%d: Uhm. Looks like we have unusual high IRQ latencies\n",
3498 		  btv->c.nr);
3499 	pr_notice("%d: Lets try to catch the culprit red-handed ...\n",
3500 		  btv->c.nr);
3501 	dump_stack();
3502 }
3503 
3504 static int
3505 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
3506 {
3507 	struct bttv_buffer *item;
3508 
3509 	memset(set,0,sizeof(*set));
3510 
3511 	/* capture request ? */
3512 	if (!list_empty(&btv->capture)) {
3513 		set->frame_irq = 1;
3514 		item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3515 		if (V4L2_FIELD_HAS_TOP(item->vb.field))
3516 			set->top    = item;
3517 		if (V4L2_FIELD_HAS_BOTTOM(item->vb.field))
3518 			set->bottom = item;
3519 
3520 		/* capture request for other field ? */
3521 		if (!V4L2_FIELD_HAS_BOTH(item->vb.field) &&
3522 		    (item->vb.queue.next != &btv->capture)) {
3523 			item = list_entry(item->vb.queue.next, struct bttv_buffer, vb.queue);
3524 			/* Mike Isely <isely@pobox.com> - Only check
3525 			 * and set up the bottom field in the logic
3526 			 * below.  Don't ever do the top field.  This
3527 			 * of course means that if we set up the
3528 			 * bottom field in the above code that we'll
3529 			 * actually skip a field.  But that's OK.
3530 			 * Having processed only a single buffer this
3531 			 * time, then the next time around the first
3532 			 * available buffer should be for a top field.
3533 			 * That will then cause us here to set up a
3534 			 * top then a bottom field in the normal way.
3535 			 * The alternative to this understanding is
3536 			 * that we set up the second available buffer
3537 			 * as a top field, but that's out of order
3538 			 * since this driver always processes the top
3539 			 * field first - the effect will be the two
3540 			 * buffers being returned in the wrong order,
3541 			 * with the second buffer also being delayed
3542 			 * by one field time (owing to the fifo nature
3543 			 * of videobuf).  Worse still, we'll be stuck
3544 			 * doing fields out of order now every time
3545 			 * until something else causes a field to be
3546 			 * dropped.  By effectively forcing a field to
3547 			 * drop this way then we always get back into
3548 			 * sync within a single frame time.  (Out of
3549 			 * order fields can screw up deinterlacing
3550 			 * algorithms.) */
3551 			if (!V4L2_FIELD_HAS_BOTH(item->vb.field)) {
3552 				if (NULL == set->bottom &&
3553 				    V4L2_FIELD_BOTTOM == item->vb.field) {
3554 					set->bottom = item;
3555 				}
3556 				if (NULL != set->top  &&  NULL != set->bottom)
3557 					set->top_irq = 2;
3558 			}
3559 		}
3560 	}
3561 
3562 	/* screen overlay ? */
3563 	if (NULL != btv->screen) {
3564 		if (V4L2_FIELD_HAS_BOTH(btv->screen->vb.field)) {
3565 			if (NULL == set->top && NULL == set->bottom) {
3566 				set->top    = btv->screen;
3567 				set->bottom = btv->screen;
3568 			}
3569 		} else {
3570 			if (V4L2_FIELD_TOP == btv->screen->vb.field &&
3571 			    NULL == set->top) {
3572 				set->top = btv->screen;
3573 			}
3574 			if (V4L2_FIELD_BOTTOM == btv->screen->vb.field &&
3575 			    NULL == set->bottom) {
3576 				set->bottom = btv->screen;
3577 			}
3578 		}
3579 	}
3580 
3581 	dprintk("%d: next set: top=%p bottom=%p [screen=%p,irq=%d,%d]\n",
3582 		btv->c.nr, set->top, set->bottom,
3583 		btv->screen, set->frame_irq, set->top_irq);
3584 	return 0;
3585 }
3586 
3587 static void
3588 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
3589 		      struct bttv_buffer_set *curr, unsigned int state)
3590 {
3591 	u64 ts = ktime_get_ns();
3592 
3593 	if (wakeup->top == wakeup->bottom) {
3594 		if (NULL != wakeup->top && curr->top != wakeup->top) {
3595 			if (irq_debug > 1)
3596 				pr_debug("%d: wakeup: both=%p\n",
3597 					 btv->c.nr, wakeup->top);
3598 			wakeup->top->vb.ts = ts;
3599 			wakeup->top->vb.field_count = btv->field_count;
3600 			wakeup->top->vb.state = state;
3601 			wake_up(&wakeup->top->vb.done);
3602 		}
3603 	} else {
3604 		if (NULL != wakeup->top && curr->top != wakeup->top) {
3605 			if (irq_debug > 1)
3606 				pr_debug("%d: wakeup: top=%p\n",
3607 					 btv->c.nr, wakeup->top);
3608 			wakeup->top->vb.ts = ts;
3609 			wakeup->top->vb.field_count = btv->field_count;
3610 			wakeup->top->vb.state = state;
3611 			wake_up(&wakeup->top->vb.done);
3612 		}
3613 		if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
3614 			if (irq_debug > 1)
3615 				pr_debug("%d: wakeup: bottom=%p\n",
3616 					 btv->c.nr, wakeup->bottom);
3617 			wakeup->bottom->vb.ts = ts;
3618 			wakeup->bottom->vb.field_count = btv->field_count;
3619 			wakeup->bottom->vb.state = state;
3620 			wake_up(&wakeup->bottom->vb.done);
3621 		}
3622 	}
3623 }
3624 
3625 static void
3626 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
3627 		    unsigned int state)
3628 {
3629 	if (NULL == wakeup)
3630 		return;
3631 
3632 	wakeup->vb.ts = ktime_get_ns();
3633 	wakeup->vb.field_count = btv->field_count;
3634 	wakeup->vb.state = state;
3635 	wake_up(&wakeup->vb.done);
3636 }
3637 
3638 static void bttv_irq_timeout(struct timer_list *t)
3639 {
3640 	struct bttv *btv = from_timer(btv, t, timeout);
3641 	struct bttv_buffer_set old,new;
3642 	struct bttv_buffer *ovbi;
3643 	struct bttv_buffer *item;
3644 	unsigned long flags;
3645 
3646 	if (bttv_verbose) {
3647 		pr_info("%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
3648 			btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
3649 			btread(BT848_RISC_COUNT));
3650 		bttv_print_irqbits(btread(BT848_INT_STAT),0);
3651 		pr_cont("\n");
3652 	}
3653 
3654 	spin_lock_irqsave(&btv->s_lock,flags);
3655 
3656 	/* deactivate stuff */
3657 	memset(&new,0,sizeof(new));
3658 	old  = btv->curr;
3659 	ovbi = btv->cvbi;
3660 	btv->curr = new;
3661 	btv->cvbi = NULL;
3662 	btv->loop_irq = 0;
3663 	bttv_buffer_activate_video(btv, &new);
3664 	bttv_buffer_activate_vbi(btv,   NULL);
3665 	bttv_set_dma(btv, 0);
3666 
3667 	/* wake up */
3668 	bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_ERROR);
3669 	bttv_irq_wakeup_vbi(btv, ovbi, VIDEOBUF_ERROR);
3670 
3671 	/* cancel all outstanding capture / vbi requests */
3672 	while (!list_empty(&btv->capture)) {
3673 		item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3674 		list_del(&item->vb.queue);
3675 		item->vb.state = VIDEOBUF_ERROR;
3676 		wake_up(&item->vb.done);
3677 	}
3678 	while (!list_empty(&btv->vcapture)) {
3679 		item = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3680 		list_del(&item->vb.queue);
3681 		item->vb.state = VIDEOBUF_ERROR;
3682 		wake_up(&item->vb.done);
3683 	}
3684 
3685 	btv->errors++;
3686 	spin_unlock_irqrestore(&btv->s_lock,flags);
3687 }
3688 
3689 static void
3690 bttv_irq_wakeup_top(struct bttv *btv)
3691 {
3692 	struct bttv_buffer *wakeup = btv->curr.top;
3693 
3694 	if (NULL == wakeup)
3695 		return;
3696 
3697 	spin_lock(&btv->s_lock);
3698 	btv->curr.top_irq = 0;
3699 	btv->curr.top = NULL;
3700 	bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
3701 
3702 	wakeup->vb.ts = ktime_get_ns();
3703 	wakeup->vb.field_count = btv->field_count;
3704 	wakeup->vb.state = VIDEOBUF_DONE;
3705 	wake_up(&wakeup->vb.done);
3706 	spin_unlock(&btv->s_lock);
3707 }
3708 
3709 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
3710 {
3711 	if (rc < risc->dma)
3712 		return 0;
3713 	if (rc > risc->dma + risc->size)
3714 		return 0;
3715 	return 1;
3716 }
3717 
3718 static void
3719 bttv_irq_switch_video(struct bttv *btv)
3720 {
3721 	struct bttv_buffer_set new;
3722 	struct bttv_buffer_set old;
3723 	dma_addr_t rc;
3724 
3725 	spin_lock(&btv->s_lock);
3726 
3727 	/* new buffer set */
3728 	bttv_irq_next_video(btv, &new);
3729 	rc = btread(BT848_RISC_COUNT);
3730 	if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
3731 	    (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
3732 		btv->framedrop++;
3733 		if (debug_latency)
3734 			bttv_irq_debug_low_latency(btv, rc);
3735 		spin_unlock(&btv->s_lock);
3736 		return;
3737 	}
3738 
3739 	/* switch over */
3740 	old = btv->curr;
3741 	btv->curr = new;
3742 	btv->loop_irq &= ~1;
3743 	bttv_buffer_activate_video(btv, &new);
3744 	bttv_set_dma(btv, 0);
3745 
3746 	/* switch input */
3747 	if (UNSET != btv->new_input) {
3748 		video_mux(btv,btv->new_input);
3749 		btv->new_input = UNSET;
3750 	}
3751 
3752 	/* wake up finished buffers */
3753 	bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_DONE);
3754 	spin_unlock(&btv->s_lock);
3755 }
3756 
3757 static void
3758 bttv_irq_switch_vbi(struct bttv *btv)
3759 {
3760 	struct bttv_buffer *new = NULL;
3761 	struct bttv_buffer *old;
3762 	u32 rc;
3763 
3764 	spin_lock(&btv->s_lock);
3765 
3766 	if (!list_empty(&btv->vcapture))
3767 		new = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3768 	old = btv->cvbi;
3769 
3770 	rc = btread(BT848_RISC_COUNT);
3771 	if (NULL != old && (is_active(&old->top,    rc) ||
3772 			    is_active(&old->bottom, rc))) {
3773 		btv->framedrop++;
3774 		if (debug_latency)
3775 			bttv_irq_debug_low_latency(btv, rc);
3776 		spin_unlock(&btv->s_lock);
3777 		return;
3778 	}
3779 
3780 	/* switch */
3781 	btv->cvbi = new;
3782 	btv->loop_irq &= ~4;
3783 	bttv_buffer_activate_vbi(btv, new);
3784 	bttv_set_dma(btv, 0);
3785 
3786 	bttv_irq_wakeup_vbi(btv, old, VIDEOBUF_DONE);
3787 	spin_unlock(&btv->s_lock);
3788 }
3789 
3790 static irqreturn_t bttv_irq(int irq, void *dev_id)
3791 {
3792 	u32 stat,astat;
3793 	u32 dstat;
3794 	int count;
3795 	struct bttv *btv;
3796 	int handled = 0;
3797 
3798 	btv=(struct bttv *)dev_id;
3799 
3800 	count=0;
3801 	while (1) {
3802 		/* get/clear interrupt status bits */
3803 		stat=btread(BT848_INT_STAT);
3804 		astat=stat&btread(BT848_INT_MASK);
3805 		if (!astat)
3806 			break;
3807 		handled = 1;
3808 		btwrite(stat,BT848_INT_STAT);
3809 
3810 		/* get device status bits */
3811 		dstat=btread(BT848_DSTATUS);
3812 
3813 		if (irq_debug) {
3814 			pr_debug("%d: irq loop=%d fc=%d riscs=%x, riscc=%08x, ",
3815 				 btv->c.nr, count, btv->field_count,
3816 				 stat>>28, btread(BT848_RISC_COUNT));
3817 			bttv_print_irqbits(stat,astat);
3818 			if (stat & BT848_INT_HLOCK)
3819 				pr_cont("   HLOC => %s",
3820 					dstat & BT848_DSTATUS_HLOC
3821 					? "yes" : "no");
3822 			if (stat & BT848_INT_VPRES)
3823 				pr_cont("   PRES => %s",
3824 					dstat & BT848_DSTATUS_PRES
3825 					? "yes" : "no");
3826 			if (stat & BT848_INT_FMTCHG)
3827 				pr_cont("   NUML => %s",
3828 					dstat & BT848_DSTATUS_NUML
3829 					? "625" : "525");
3830 			pr_cont("\n");
3831 		}
3832 
3833 		if (astat&BT848_INT_VSYNC)
3834 			btv->field_count++;
3835 
3836 		if ((astat & BT848_INT_GPINT) && btv->remote) {
3837 			bttv_input_irq(btv);
3838 		}
3839 
3840 		if (astat & BT848_INT_I2CDONE) {
3841 			btv->i2c_done = stat;
3842 			wake_up(&btv->i2c_queue);
3843 		}
3844 
3845 		if ((astat & BT848_INT_RISCI)  &&  (stat & (4<<28)))
3846 			bttv_irq_switch_vbi(btv);
3847 
3848 		if ((astat & BT848_INT_RISCI)  &&  (stat & (2<<28)))
3849 			bttv_irq_wakeup_top(btv);
3850 
3851 		if ((astat & BT848_INT_RISCI)  &&  (stat & (1<<28)))
3852 			bttv_irq_switch_video(btv);
3853 
3854 		if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3855 			/* trigger automute */
3856 			audio_mux_gpio(btv, btv->audio_input, btv->mute);
3857 
3858 		if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3859 			pr_info("%d: %s%s @ %08x,",
3860 				btv->c.nr,
3861 				(astat & BT848_INT_SCERR) ? "SCERR" : "",
3862 				(astat & BT848_INT_OCERR) ? "OCERR" : "",
3863 				btread(BT848_RISC_COUNT));
3864 			bttv_print_irqbits(stat,astat);
3865 			pr_cont("\n");
3866 			if (bttv_debug)
3867 				bttv_print_riscaddr(btv);
3868 		}
3869 		if (fdsr && astat & BT848_INT_FDSR) {
3870 			pr_info("%d: FDSR @ %08x\n",
3871 				btv->c.nr, btread(BT848_RISC_COUNT));
3872 			if (bttv_debug)
3873 				bttv_print_riscaddr(btv);
3874 		}
3875 
3876 		count++;
3877 		if (count > 4) {
3878 
3879 			if (count > 8 || !(astat & BT848_INT_GPINT)) {
3880 				btwrite(0, BT848_INT_MASK);
3881 
3882 				pr_err("%d: IRQ lockup, cleared int mask [",
3883 				       btv->c.nr);
3884 			} else {
3885 				pr_err("%d: IRQ lockup, clearing GPINT from int mask [",
3886 				       btv->c.nr);
3887 
3888 				btwrite(btread(BT848_INT_MASK) & (-1 ^ BT848_INT_GPINT),
3889 						BT848_INT_MASK);
3890 			}
3891 
3892 			bttv_print_irqbits(stat,astat);
3893 
3894 			pr_cont("]\n");
3895 		}
3896 	}
3897 	btv->irq_total++;
3898 	if (handled)
3899 		btv->irq_me++;
3900 	return IRQ_RETVAL(handled);
3901 }
3902 
3903 
3904 /* ----------------------------------------------------------------------- */
3905 /* initialization                                                          */
3906 
3907 static void vdev_init(struct bttv *btv,
3908 		      struct video_device *vfd,
3909 		      const struct video_device *template,
3910 		      const char *type_name)
3911 {
3912 	*vfd = *template;
3913 	vfd->v4l2_dev = &btv->c.v4l2_dev;
3914 	vfd->release = video_device_release_empty;
3915 	video_set_drvdata(vfd, btv);
3916 	snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3917 		 btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3918 		 type_name, bttv_tvcards[btv->c.type].name);
3919 	if (btv->tuner_type == TUNER_ABSENT) {
3920 		v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
3921 		v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
3922 		v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
3923 		v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
3924 	}
3925 }
3926 
3927 static void bttv_unregister_video(struct bttv *btv)
3928 {
3929 	video_unregister_device(&btv->video_dev);
3930 	video_unregister_device(&btv->vbi_dev);
3931 	video_unregister_device(&btv->radio_dev);
3932 }
3933 
3934 /* register video4linux devices */
3935 static int bttv_register_video(struct bttv *btv)
3936 {
3937 	if (no_overlay > 0)
3938 		pr_notice("Overlay support disabled\n");
3939 
3940 	/* video */
3941 	vdev_init(btv, &btv->video_dev, &bttv_video_template, "video");
3942 
3943 	if (video_register_device(&btv->video_dev, VFL_TYPE_GRABBER,
3944 				  video_nr[btv->c.nr]) < 0)
3945 		goto err;
3946 	pr_info("%d: registered device %s\n",
3947 		btv->c.nr, video_device_node_name(&btv->video_dev));
3948 	if (device_create_file(&btv->video_dev.dev,
3949 				     &dev_attr_card)<0) {
3950 		pr_err("%d: device_create_file 'card' failed\n", btv->c.nr);
3951 		goto err;
3952 	}
3953 
3954 	/* vbi */
3955 	vdev_init(btv, &btv->vbi_dev, &bttv_video_template, "vbi");
3956 
3957 	if (video_register_device(&btv->vbi_dev, VFL_TYPE_VBI,
3958 				  vbi_nr[btv->c.nr]) < 0)
3959 		goto err;
3960 	pr_info("%d: registered device %s\n",
3961 		btv->c.nr, video_device_node_name(&btv->vbi_dev));
3962 
3963 	if (!btv->has_radio)
3964 		return 0;
3965 	/* radio */
3966 	vdev_init(btv, &btv->radio_dev, &radio_template, "radio");
3967 	btv->radio_dev.ctrl_handler = &btv->radio_ctrl_handler;
3968 	if (video_register_device(&btv->radio_dev, VFL_TYPE_RADIO,
3969 				  radio_nr[btv->c.nr]) < 0)
3970 		goto err;
3971 	pr_info("%d: registered device %s\n",
3972 		btv->c.nr, video_device_node_name(&btv->radio_dev));
3973 
3974 	/* all done */
3975 	return 0;
3976 
3977  err:
3978 	bttv_unregister_video(btv);
3979 	return -1;
3980 }
3981 
3982 
3983 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
3984 /* response on cards with no firmware is not enabled by OF */
3985 static void pci_set_command(struct pci_dev *dev)
3986 {
3987 #if defined(__powerpc__)
3988 	unsigned int cmd;
3989 
3990 	pci_read_config_dword(dev, PCI_COMMAND, &cmd);
3991 	cmd = (cmd | PCI_COMMAND_MEMORY );
3992 	pci_write_config_dword(dev, PCI_COMMAND, cmd);
3993 #endif
3994 }
3995 
3996 static int bttv_probe(struct pci_dev *dev, const struct pci_device_id *pci_id)
3997 {
3998 	struct v4l2_frequency init_freq = {
3999 		.tuner = 0,
4000 		.type = V4L2_TUNER_ANALOG_TV,
4001 		.frequency = 980,
4002 	};
4003 	int result;
4004 	unsigned char lat;
4005 	struct bttv *btv;
4006 	struct v4l2_ctrl_handler *hdl;
4007 
4008 	if (bttv_num == BTTV_MAX)
4009 		return -ENOMEM;
4010 	pr_info("Bt8xx card found (%d)\n", bttv_num);
4011 	bttvs[bttv_num] = btv = kzalloc(sizeof(*btv), GFP_KERNEL);
4012 	if (btv == NULL) {
4013 		pr_err("out of memory\n");
4014 		return -ENOMEM;
4015 	}
4016 	btv->c.nr  = bttv_num;
4017 	snprintf(btv->c.v4l2_dev.name, sizeof(btv->c.v4l2_dev.name),
4018 			"bttv%d", btv->c.nr);
4019 
4020 	/* initialize structs / fill in defaults */
4021 	mutex_init(&btv->lock);
4022 	spin_lock_init(&btv->s_lock);
4023 	spin_lock_init(&btv->gpio_lock);
4024 	init_waitqueue_head(&btv->i2c_queue);
4025 	INIT_LIST_HEAD(&btv->c.subs);
4026 	INIT_LIST_HEAD(&btv->capture);
4027 	INIT_LIST_HEAD(&btv->vcapture);
4028 
4029 	timer_setup(&btv->timeout, bttv_irq_timeout, 0);
4030 
4031 	btv->i2c_rc = -1;
4032 	btv->tuner_type  = UNSET;
4033 	btv->new_input   = UNSET;
4034 	btv->has_radio=radio[btv->c.nr];
4035 
4036 	/* pci stuff (init, get irq/mmio, ... */
4037 	btv->c.pci = dev;
4038 	btv->id  = dev->device;
4039 	if (pci_enable_device(dev)) {
4040 		pr_warn("%d: Can't enable device\n", btv->c.nr);
4041 		return -EIO;
4042 	}
4043 	if (pci_set_dma_mask(dev, DMA_BIT_MASK(32))) {
4044 		pr_warn("%d: No suitable DMA available\n", btv->c.nr);
4045 		return -EIO;
4046 	}
4047 	if (!request_mem_region(pci_resource_start(dev,0),
4048 				pci_resource_len(dev,0),
4049 				btv->c.v4l2_dev.name)) {
4050 		pr_warn("%d: can't request iomem (0x%llx)\n",
4051 			btv->c.nr,
4052 			(unsigned long long)pci_resource_start(dev, 0));
4053 		return -EBUSY;
4054 	}
4055 	pci_set_master(dev);
4056 	pci_set_command(dev);
4057 
4058 	result = v4l2_device_register(&dev->dev, &btv->c.v4l2_dev);
4059 	if (result < 0) {
4060 		pr_warn("%d: v4l2_device_register() failed\n", btv->c.nr);
4061 		goto fail0;
4062 	}
4063 	hdl = &btv->ctrl_handler;
4064 	v4l2_ctrl_handler_init(hdl, 20);
4065 	btv->c.v4l2_dev.ctrl_handler = hdl;
4066 	v4l2_ctrl_handler_init(&btv->radio_ctrl_handler, 6);
4067 
4068 	btv->revision = dev->revision;
4069 	pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4070 	pr_info("%d: Bt%d (rev %d) at %s, irq: %d, latency: %d, mmio: 0x%llx\n",
4071 		bttv_num, btv->id, btv->revision, pci_name(dev),
4072 		btv->c.pci->irq, lat,
4073 		(unsigned long long)pci_resource_start(dev, 0));
4074 	schedule();
4075 
4076 	btv->bt848_mmio = ioremap(pci_resource_start(dev, 0), 0x1000);
4077 	if (NULL == btv->bt848_mmio) {
4078 		pr_err("%d: ioremap() failed\n", btv->c.nr);
4079 		result = -EIO;
4080 		goto fail1;
4081 	}
4082 
4083 	/* identify card */
4084 	bttv_idcard(btv);
4085 
4086 	/* disable irqs, register irq handler */
4087 	btwrite(0, BT848_INT_MASK);
4088 	result = request_irq(btv->c.pci->irq, bttv_irq,
4089 	    IRQF_SHARED, btv->c.v4l2_dev.name, (void *)btv);
4090 	if (result < 0) {
4091 		pr_err("%d: can't get IRQ %d\n",
4092 		       bttv_num, btv->c.pci->irq);
4093 		goto fail1;
4094 	}
4095 
4096 	if (0 != bttv_handle_chipset(btv)) {
4097 		result = -EIO;
4098 		goto fail2;
4099 	}
4100 
4101 	/* init options from insmod args */
4102 	btv->opt_combfilter = combfilter;
4103 	bttv_ctrl_combfilter.def = combfilter;
4104 	bttv_ctrl_lumafilter.def = lumafilter;
4105 	btv->opt_automute   = automute;
4106 	bttv_ctrl_automute.def = automute;
4107 	bttv_ctrl_agc_crush.def = agc_crush;
4108 	btv->opt_vcr_hack   = vcr_hack;
4109 	bttv_ctrl_vcr_hack.def = vcr_hack;
4110 	bttv_ctrl_whitecrush_upper.def = whitecrush_upper;
4111 	bttv_ctrl_whitecrush_lower.def = whitecrush_lower;
4112 	btv->opt_uv_ratio   = uv_ratio;
4113 	bttv_ctrl_uv_ratio.def = uv_ratio;
4114 	bttv_ctrl_full_luma.def = full_luma_range;
4115 	bttv_ctrl_coring.def = coring;
4116 
4117 	/* fill struct bttv with some useful defaults */
4118 	btv->init.btv         = btv;
4119 	btv->init.ov.w.width  = 320;
4120 	btv->init.ov.w.height = 240;
4121 	btv->init.fmt         = format_by_fourcc(V4L2_PIX_FMT_BGR24);
4122 	btv->init.width       = 320;
4123 	btv->init.height      = 240;
4124 	btv->init.ov.w.width  = 320;
4125 	btv->init.ov.w.height = 240;
4126 	btv->init.ov.field    = V4L2_FIELD_INTERLACED;
4127 	btv->input = 0;
4128 
4129 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4130 			V4L2_CID_BRIGHTNESS, 0, 0xff00, 0x100, 32768);
4131 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4132 			V4L2_CID_CONTRAST, 0, 0xff80, 0x80, 0x6c00);
4133 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4134 			V4L2_CID_SATURATION, 0, 0xff80, 0x80, 32768);
4135 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4136 			V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
4137 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4138 			V4L2_CID_HUE, 0, 0xff00, 0x100, 32768);
4139 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4140 			V4L2_CID_CHROMA_AGC, 0, 1, 1, !!chroma_agc);
4141 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4142 		V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
4143 	if (btv->volume_gpio)
4144 		v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4145 			V4L2_CID_AUDIO_VOLUME, 0, 0xff00, 0x100, 0xff00);
4146 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_combfilter, NULL);
4147 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_automute, NULL);
4148 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_lumafilter, NULL);
4149 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_agc_crush, NULL);
4150 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_vcr_hack, NULL);
4151 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_lower, NULL);
4152 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_upper, NULL);
4153 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_uv_ratio, NULL);
4154 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_full_luma, NULL);
4155 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_coring, NULL);
4156 
4157 	/* initialize hardware */
4158 	if (bttv_gpio)
4159 		bttv_gpio_tracking(btv,"pre-init");
4160 
4161 	bttv_risc_init_main(btv);
4162 	init_bt848(btv);
4163 
4164 	/* gpio */
4165 	btwrite(0x00, BT848_GPIO_REG_INP);
4166 	btwrite(0x00, BT848_GPIO_OUT_EN);
4167 	if (bttv_verbose)
4168 		bttv_gpio_tracking(btv,"init");
4169 
4170 	/* needs to be done before i2c is registered */
4171 	bttv_init_card1(btv);
4172 
4173 	/* register i2c + gpio */
4174 	init_bttv_i2c(btv);
4175 
4176 	/* some card-specific stuff (needs working i2c) */
4177 	bttv_init_card2(btv);
4178 	bttv_init_tuner(btv);
4179 	if (btv->tuner_type != TUNER_ABSENT) {
4180 		bttv_set_frequency(btv, &init_freq);
4181 		btv->radio_freq = 90500 * 16; /* 90.5Mhz default */
4182 	}
4183 	btv->std = V4L2_STD_PAL;
4184 	init_irqreg(btv);
4185 	if (!bttv_tvcards[btv->c.type].no_video)
4186 		v4l2_ctrl_handler_setup(hdl);
4187 	if (hdl->error) {
4188 		result = hdl->error;
4189 		goto fail2;
4190 	}
4191 	/* mute device */
4192 	audio_mute(btv, 1);
4193 
4194 	/* register video4linux + input */
4195 	if (!bttv_tvcards[btv->c.type].no_video) {
4196 		v4l2_ctrl_add_handler(&btv->radio_ctrl_handler, hdl,
4197 				v4l2_ctrl_radio_filter, false);
4198 		if (btv->radio_ctrl_handler.error) {
4199 			result = btv->radio_ctrl_handler.error;
4200 			goto fail2;
4201 		}
4202 		set_input(btv, 0, btv->tvnorm);
4203 		bttv_crop_reset(&btv->crop[0], btv->tvnorm);
4204 		btv->crop[1] = btv->crop[0]; /* current = default */
4205 		disclaim_vbi_lines(btv);
4206 		disclaim_video_lines(btv);
4207 		bttv_register_video(btv);
4208 	}
4209 
4210 	/* add subdevices and autoload dvb-bt8xx if needed */
4211 	if (bttv_tvcards[btv->c.type].has_dvb) {
4212 		bttv_sub_add_device(&btv->c, "dvb");
4213 		request_modules(btv);
4214 	}
4215 
4216 	if (!disable_ir) {
4217 		init_bttv_i2c_ir(btv);
4218 		bttv_input_init(btv);
4219 	}
4220 
4221 	/* everything is fine */
4222 	bttv_num++;
4223 	return 0;
4224 
4225 fail2:
4226 	free_irq(btv->c.pci->irq,btv);
4227 
4228 fail1:
4229 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
4230 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
4231 	v4l2_device_unregister(&btv->c.v4l2_dev);
4232 
4233 fail0:
4234 	if (btv->bt848_mmio)
4235 		iounmap(btv->bt848_mmio);
4236 	release_mem_region(pci_resource_start(btv->c.pci,0),
4237 			   pci_resource_len(btv->c.pci,0));
4238 	pci_disable_device(btv->c.pci);
4239 	return result;
4240 }
4241 
4242 static void bttv_remove(struct pci_dev *pci_dev)
4243 {
4244 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4245 	struct bttv *btv = to_bttv(v4l2_dev);
4246 
4247 	if (bttv_verbose)
4248 		pr_info("%d: unloading\n", btv->c.nr);
4249 
4250 	if (bttv_tvcards[btv->c.type].has_dvb)
4251 		flush_request_modules(btv);
4252 
4253 	/* shutdown everything (DMA+IRQs) */
4254 	btand(~15, BT848_GPIO_DMA_CTL);
4255 	btwrite(0, BT848_INT_MASK);
4256 	btwrite(~0x0, BT848_INT_STAT);
4257 	btwrite(0x0, BT848_GPIO_OUT_EN);
4258 	if (bttv_gpio)
4259 		bttv_gpio_tracking(btv,"cleanup");
4260 
4261 	/* tell gpio modules we are leaving ... */
4262 	btv->shutdown=1;
4263 	bttv_input_fini(btv);
4264 	bttv_sub_del_devices(&btv->c);
4265 
4266 	/* unregister i2c_bus + input */
4267 	fini_bttv_i2c(btv);
4268 
4269 	/* unregister video4linux */
4270 	bttv_unregister_video(btv);
4271 
4272 	/* free allocated memory */
4273 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
4274 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
4275 	btcx_riscmem_free(btv->c.pci,&btv->main);
4276 
4277 	/* free resources */
4278 	free_irq(btv->c.pci->irq,btv);
4279 	iounmap(btv->bt848_mmio);
4280 	release_mem_region(pci_resource_start(btv->c.pci,0),
4281 			   pci_resource_len(btv->c.pci,0));
4282 	pci_disable_device(btv->c.pci);
4283 
4284 	v4l2_device_unregister(&btv->c.v4l2_dev);
4285 	bttvs[btv->c.nr] = NULL;
4286 	kfree(btv);
4287 
4288 	return;
4289 }
4290 
4291 #ifdef CONFIG_PM
4292 static int bttv_suspend(struct pci_dev *pci_dev, pm_message_t state)
4293 {
4294 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4295 	struct bttv *btv = to_bttv(v4l2_dev);
4296 	struct bttv_buffer_set idle;
4297 	unsigned long flags;
4298 
4299 	dprintk("%d: suspend %d\n", btv->c.nr, state.event);
4300 
4301 	/* stop dma + irqs */
4302 	spin_lock_irqsave(&btv->s_lock,flags);
4303 	memset(&idle, 0, sizeof(idle));
4304 	btv->state.video = btv->curr;
4305 	btv->state.vbi   = btv->cvbi;
4306 	btv->state.loop_irq = btv->loop_irq;
4307 	btv->curr = idle;
4308 	btv->loop_irq = 0;
4309 	bttv_buffer_activate_video(btv, &idle);
4310 	bttv_buffer_activate_vbi(btv, NULL);
4311 	bttv_set_dma(btv, 0);
4312 	btwrite(0, BT848_INT_MASK);
4313 	spin_unlock_irqrestore(&btv->s_lock,flags);
4314 
4315 	/* save bt878 state */
4316 	btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
4317 	btv->state.gpio_data   = gpio_read();
4318 
4319 	/* save pci state */
4320 	pci_save_state(pci_dev);
4321 	if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) {
4322 		pci_disable_device(pci_dev);
4323 		btv->state.disabled = 1;
4324 	}
4325 	return 0;
4326 }
4327 
4328 static int bttv_resume(struct pci_dev *pci_dev)
4329 {
4330 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4331 	struct bttv *btv = to_bttv(v4l2_dev);
4332 	unsigned long flags;
4333 	int err;
4334 
4335 	dprintk("%d: resume\n", btv->c.nr);
4336 
4337 	/* restore pci state */
4338 	if (btv->state.disabled) {
4339 		err=pci_enable_device(pci_dev);
4340 		if (err) {
4341 			pr_warn("%d: Can't enable device\n", btv->c.nr);
4342 			return err;
4343 		}
4344 		btv->state.disabled = 0;
4345 	}
4346 	err=pci_set_power_state(pci_dev, PCI_D0);
4347 	if (err) {
4348 		pci_disable_device(pci_dev);
4349 		pr_warn("%d: Can't enable device\n", btv->c.nr);
4350 		btv->state.disabled = 1;
4351 		return err;
4352 	}
4353 
4354 	pci_restore_state(pci_dev);
4355 
4356 	/* restore bt878 state */
4357 	bttv_reinit_bt848(btv);
4358 	gpio_inout(0xffffff, btv->state.gpio_enable);
4359 	gpio_write(btv->state.gpio_data);
4360 
4361 	/* restart dma */
4362 	spin_lock_irqsave(&btv->s_lock,flags);
4363 	btv->curr = btv->state.video;
4364 	btv->cvbi = btv->state.vbi;
4365 	btv->loop_irq = btv->state.loop_irq;
4366 	bttv_buffer_activate_video(btv, &btv->curr);
4367 	bttv_buffer_activate_vbi(btv, btv->cvbi);
4368 	bttv_set_dma(btv, 0);
4369 	spin_unlock_irqrestore(&btv->s_lock,flags);
4370 	return 0;
4371 }
4372 #endif
4373 
4374 static const struct pci_device_id bttv_pci_tbl[] = {
4375 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT848), 0},
4376 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT849), 0},
4377 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT878), 0},
4378 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT879), 0},
4379 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_FUSION879), 0},
4380 	{0,}
4381 };
4382 
4383 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
4384 
4385 static struct pci_driver bttv_pci_driver = {
4386 	.name     = "bttv",
4387 	.id_table = bttv_pci_tbl,
4388 	.probe    = bttv_probe,
4389 	.remove   = bttv_remove,
4390 #ifdef CONFIG_PM
4391 	.suspend  = bttv_suspend,
4392 	.resume   = bttv_resume,
4393 #endif
4394 };
4395 
4396 static int __init bttv_init_module(void)
4397 {
4398 	int ret;
4399 
4400 	bttv_num = 0;
4401 
4402 	pr_info("driver version %s loaded\n", BTTV_VERSION);
4403 	if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
4404 		gbuffers = 2;
4405 	if (gbufsize > BTTV_MAX_FBUF)
4406 		gbufsize = BTTV_MAX_FBUF;
4407 	gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
4408 	if (bttv_verbose)
4409 		pr_info("using %d buffers with %dk (%d pages) each for capture\n",
4410 			gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
4411 
4412 	bttv_check_chipset();
4413 
4414 	ret = bus_register(&bttv_sub_bus_type);
4415 	if (ret < 0) {
4416 		pr_warn("bus_register error: %d\n", ret);
4417 		return ret;
4418 	}
4419 	ret = pci_register_driver(&bttv_pci_driver);
4420 	if (ret < 0)
4421 		bus_unregister(&bttv_sub_bus_type);
4422 
4423 	return ret;
4424 }
4425 
4426 static void __exit bttv_cleanup_module(void)
4427 {
4428 	pci_unregister_driver(&bttv_pci_driver);
4429 	bus_unregister(&bttv_sub_bus_type);
4430 }
4431 
4432 module_init(bttv_init_module);
4433 module_exit(bttv_cleanup_module);
4434