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 bttv_fh *fh = priv;
2457 	struct bttv *btv = fh->btv;
2458 
2459 	if (0 == v4l2)
2460 		return -EINVAL;
2461 
2462 	strscpy(cap->driver, "bttv", sizeof(cap->driver));
2463 	strscpy(cap->card, btv->video_dev.name, sizeof(cap->card));
2464 	snprintf(cap->bus_info, sizeof(cap->bus_info),
2465 		 "PCI:%s", pci_name(btv->c.pci));
2466 	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
2467 			    V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
2468 	if (no_overlay <= 0)
2469 		cap->capabilities |= V4L2_CAP_VIDEO_OVERLAY;
2470 	if (video_is_registered(&btv->vbi_dev))
2471 		cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
2472 	if (video_is_registered(&btv->radio_dev)) {
2473 		cap->capabilities |= V4L2_CAP_RADIO;
2474 		if (btv->has_tea575x)
2475 			cap->capabilities |= V4L2_CAP_HW_FREQ_SEEK;
2476 	}
2477 
2478 	/*
2479 	 * No need to lock here: those vars are initialized during board
2480 	 * probe and remains untouched during the rest of the driver lifecycle
2481 	 */
2482 	if (btv->has_saa6588)
2483 		cap->capabilities |= V4L2_CAP_RDS_CAPTURE;
2484 	if (btv->tuner_type != TUNER_ABSENT)
2485 		cap->capabilities |= V4L2_CAP_TUNER;
2486 	return 0;
2487 }
2488 
2489 static int bttv_enum_fmt_cap_ovr(struct v4l2_fmtdesc *f)
2490 {
2491 	int index = -1, i;
2492 
2493 	for (i = 0; i < FORMATS; i++) {
2494 		if (formats[i].fourcc != -1)
2495 			index++;
2496 		if ((unsigned int)index == f->index)
2497 			break;
2498 	}
2499 	if (FORMATS == i)
2500 		return -EINVAL;
2501 
2502 	f->pixelformat = formats[i].fourcc;
2503 	strscpy(f->description, formats[i].name, sizeof(f->description));
2504 
2505 	return i;
2506 }
2507 
2508 static int bttv_enum_fmt_vid_cap(struct file *file, void  *priv,
2509 				struct v4l2_fmtdesc *f)
2510 {
2511 	int rc = bttv_enum_fmt_cap_ovr(f);
2512 
2513 	if (rc < 0)
2514 		return rc;
2515 
2516 	return 0;
2517 }
2518 
2519 static int bttv_enum_fmt_vid_overlay(struct file *file, void  *priv,
2520 					struct v4l2_fmtdesc *f)
2521 {
2522 	int rc;
2523 
2524 	if (no_overlay > 0) {
2525 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2526 		return -EINVAL;
2527 	}
2528 
2529 	rc = bttv_enum_fmt_cap_ovr(f);
2530 
2531 	if (rc < 0)
2532 		return rc;
2533 
2534 	if (!(formats[rc].flags & FORMAT_FLAGS_PACKED))
2535 		return -EINVAL;
2536 
2537 	return 0;
2538 }
2539 
2540 static int bttv_g_fbuf(struct file *file, void *f,
2541 				struct v4l2_framebuffer *fb)
2542 {
2543 	struct bttv_fh *fh = f;
2544 	struct bttv *btv = fh->btv;
2545 
2546 	*fb = btv->fbuf;
2547 	fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
2548 	fb->flags = V4L2_FBUF_FLAG_PRIMARY;
2549 	if (fh->ovfmt)
2550 		fb->fmt.pixelformat  = fh->ovfmt->fourcc;
2551 	return 0;
2552 }
2553 
2554 static int bttv_overlay(struct file *file, void *f, unsigned int on)
2555 {
2556 	struct bttv_fh *fh = f;
2557 	struct bttv *btv = fh->btv;
2558 	struct bttv_buffer *new;
2559 	int retval = 0;
2560 
2561 	if (on) {
2562 		/* verify args */
2563 		if (unlikely(!btv->fbuf.base)) {
2564 			return -EINVAL;
2565 		}
2566 		if (unlikely(!fh->ov.setup_ok)) {
2567 			dprintk("%d: overlay: !setup_ok\n", btv->c.nr);
2568 			retval = -EINVAL;
2569 		}
2570 		if (retval)
2571 			return retval;
2572 	}
2573 
2574 	if (!check_alloc_btres_lock(btv, fh, RESOURCE_OVERLAY))
2575 		return -EBUSY;
2576 
2577 	if (on) {
2578 		fh->ov.tvnorm = btv->tvnorm;
2579 		new = videobuf_sg_alloc(sizeof(*new));
2580 		new->crop = btv->crop[!!fh->do_crop].rect;
2581 		bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2582 	} else {
2583 		new = NULL;
2584 	}
2585 
2586 	/* switch over */
2587 	retval = bttv_switch_overlay(btv, fh, new);
2588 	return retval;
2589 }
2590 
2591 static int bttv_s_fbuf(struct file *file, void *f,
2592 				const struct v4l2_framebuffer *fb)
2593 {
2594 	struct bttv_fh *fh = f;
2595 	struct bttv *btv = fh->btv;
2596 	const struct bttv_format *fmt;
2597 	int retval;
2598 
2599 	if (!capable(CAP_SYS_ADMIN) &&
2600 		!capable(CAP_SYS_RAWIO))
2601 		return -EPERM;
2602 
2603 	/* check args */
2604 	fmt = format_by_fourcc(fb->fmt.pixelformat);
2605 	if (NULL == fmt)
2606 		return -EINVAL;
2607 	if (0 == (fmt->flags & FORMAT_FLAGS_PACKED))
2608 		return -EINVAL;
2609 
2610 	retval = -EINVAL;
2611 	if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2612 		__s32 width = fb->fmt.width;
2613 		__s32 height = fb->fmt.height;
2614 
2615 		retval = limit_scaled_size_lock(fh, &width, &height,
2616 					   V4L2_FIELD_INTERLACED,
2617 					   /* width_mask */ ~3,
2618 					   /* width_bias */ 2,
2619 					   /* adjust_size */ 0,
2620 					   /* adjust_crop */ 0);
2621 		if (0 != retval)
2622 			return retval;
2623 	}
2624 
2625 	/* ok, accept it */
2626 	btv->fbuf.base       = fb->base;
2627 	btv->fbuf.fmt.width  = fb->fmt.width;
2628 	btv->fbuf.fmt.height = fb->fmt.height;
2629 	if (0 != fb->fmt.bytesperline)
2630 		btv->fbuf.fmt.bytesperline = fb->fmt.bytesperline;
2631 	else
2632 		btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fmt->depth/8;
2633 
2634 	retval = 0;
2635 	fh->ovfmt = fmt;
2636 	btv->init.ovfmt = fmt;
2637 	if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2638 		fh->ov.w.left   = 0;
2639 		fh->ov.w.top    = 0;
2640 		fh->ov.w.width  = fb->fmt.width;
2641 		fh->ov.w.height = fb->fmt.height;
2642 		btv->init.ov.w.width  = fb->fmt.width;
2643 		btv->init.ov.w.height = fb->fmt.height;
2644 
2645 		kfree(fh->ov.clips);
2646 		fh->ov.clips = NULL;
2647 		fh->ov.nclips = 0;
2648 
2649 		if (check_btres(fh, RESOURCE_OVERLAY)) {
2650 			struct bttv_buffer *new;
2651 
2652 			new = videobuf_sg_alloc(sizeof(*new));
2653 			new->crop = btv->crop[!!fh->do_crop].rect;
2654 			bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2655 			retval = bttv_switch_overlay(btv, fh, new);
2656 		}
2657 	}
2658 	return retval;
2659 }
2660 
2661 static int bttv_reqbufs(struct file *file, void *priv,
2662 				struct v4l2_requestbuffers *p)
2663 {
2664 	struct bttv_fh *fh = priv;
2665 	return videobuf_reqbufs(bttv_queue(fh), p);
2666 }
2667 
2668 static int bttv_querybuf(struct file *file, void *priv,
2669 				struct v4l2_buffer *b)
2670 {
2671 	struct bttv_fh *fh = priv;
2672 	return videobuf_querybuf(bttv_queue(fh), b);
2673 }
2674 
2675 static int bttv_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2676 {
2677 	struct bttv_fh *fh = priv;
2678 	struct bttv *btv = fh->btv;
2679 	int res = bttv_resource(fh);
2680 
2681 	if (!check_alloc_btres_lock(btv, fh, res))
2682 		return -EBUSY;
2683 
2684 	return videobuf_qbuf(bttv_queue(fh), b);
2685 }
2686 
2687 static int bttv_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2688 {
2689 	struct bttv_fh *fh = priv;
2690 	return videobuf_dqbuf(bttv_queue(fh), b,
2691 			file->f_flags & O_NONBLOCK);
2692 }
2693 
2694 static int bttv_streamon(struct file *file, void *priv,
2695 					enum v4l2_buf_type type)
2696 {
2697 	struct bttv_fh *fh = priv;
2698 	struct bttv *btv = fh->btv;
2699 	int res = bttv_resource(fh);
2700 
2701 	if (!check_alloc_btres_lock(btv, fh, res))
2702 		return -EBUSY;
2703 	return videobuf_streamon(bttv_queue(fh));
2704 }
2705 
2706 
2707 static int bttv_streamoff(struct file *file, void *priv,
2708 					enum v4l2_buf_type type)
2709 {
2710 	struct bttv_fh *fh = priv;
2711 	struct bttv *btv = fh->btv;
2712 	int retval;
2713 	int res = bttv_resource(fh);
2714 
2715 
2716 	retval = videobuf_streamoff(bttv_queue(fh));
2717 	if (retval < 0)
2718 		return retval;
2719 	free_btres_lock(btv, fh, res);
2720 	return 0;
2721 }
2722 
2723 static int bttv_g_parm(struct file *file, void *f,
2724 				struct v4l2_streamparm *parm)
2725 {
2726 	struct bttv_fh *fh = f;
2727 	struct bttv *btv = fh->btv;
2728 
2729 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2730 		return -EINVAL;
2731 	parm->parm.capture.readbuffers = gbuffers;
2732 	v4l2_video_std_frame_period(bttv_tvnorms[btv->tvnorm].v4l2_id,
2733 				    &parm->parm.capture.timeperframe);
2734 
2735 	return 0;
2736 }
2737 
2738 static int bttv_g_tuner(struct file *file, void *priv,
2739 				struct v4l2_tuner *t)
2740 {
2741 	struct bttv_fh *fh = priv;
2742 	struct bttv *btv = fh->btv;
2743 
2744 	if (0 != t->index)
2745 		return -EINVAL;
2746 
2747 	t->rxsubchans = V4L2_TUNER_SUB_MONO;
2748 	t->capability = V4L2_TUNER_CAP_NORM;
2749 	bttv_call_all(btv, tuner, g_tuner, t);
2750 	strscpy(t->name, "Television", sizeof(t->name));
2751 	t->type       = V4L2_TUNER_ANALOG_TV;
2752 	if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
2753 		t->signal = 0xffff;
2754 
2755 	if (btv->audio_mode_gpio)
2756 		btv->audio_mode_gpio(btv, t, 0);
2757 
2758 	return 0;
2759 }
2760 
2761 static int bttv_g_pixelaspect(struct file *file, void *priv,
2762 			      int type, struct v4l2_fract *f)
2763 {
2764 	struct bttv_fh *fh = priv;
2765 	struct bttv *btv = fh->btv;
2766 
2767 	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2768 		return -EINVAL;
2769 
2770 	/* defrect and bounds are set via g_selection */
2771 	*f = bttv_tvnorms[btv->tvnorm].cropcap.pixelaspect;
2772 	return 0;
2773 }
2774 
2775 static int bttv_g_selection(struct file *file, void *f, struct v4l2_selection *sel)
2776 {
2777 	struct bttv_fh *fh = f;
2778 	struct bttv *btv = fh->btv;
2779 
2780 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2781 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2782 		return -EINVAL;
2783 
2784 	switch (sel->target) {
2785 	case V4L2_SEL_TGT_CROP:
2786 		/*
2787 		 * No fh->do_crop = 1; because btv->crop[1] may be
2788 		 * inconsistent with fh->width or fh->height and apps
2789 		 * do not expect a change here.
2790 		 */
2791 		sel->r = btv->crop[!!fh->do_crop].rect;
2792 		break;
2793 	case V4L2_SEL_TGT_CROP_DEFAULT:
2794 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.defrect;
2795 		break;
2796 	case V4L2_SEL_TGT_CROP_BOUNDS:
2797 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2798 		break;
2799 	default:
2800 		return -EINVAL;
2801 	}
2802 
2803 	return 0;
2804 }
2805 
2806 static int bttv_s_selection(struct file *file, void *f, struct v4l2_selection *sel)
2807 {
2808 	struct bttv_fh *fh = f;
2809 	struct bttv *btv = fh->btv;
2810 	const struct v4l2_rect *b;
2811 	int retval;
2812 	struct bttv_crop c;
2813 	__s32 b_left;
2814 	__s32 b_top;
2815 	__s32 b_right;
2816 	__s32 b_bottom;
2817 
2818 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2819 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2820 		return -EINVAL;
2821 
2822 	if (sel->target != V4L2_SEL_TGT_CROP)
2823 		return -EINVAL;
2824 
2825 	/* Make sure tvnorm, vbi_end and the current cropping
2826 	   parameters remain consistent until we're done. Note
2827 	   read() may change vbi_end in check_alloc_btres_lock(). */
2828 	retval = -EBUSY;
2829 
2830 	if (locked_btres(fh->btv, VIDEO_RESOURCES)) {
2831 		return retval;
2832 	}
2833 
2834 	b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2835 
2836 	b_left = b->left;
2837 	b_right = b_left + b->width;
2838 	b_bottom = b->top + b->height;
2839 
2840 	b_top = max(b->top, btv->vbi_end);
2841 	if (b_top + 32 >= b_bottom) {
2842 		return retval;
2843 	}
2844 
2845 	/* Min. scaled size 48 x 32. */
2846 	c.rect.left = clamp_t(s32, sel->r.left, b_left, b_right - 48);
2847 	c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
2848 
2849 	c.rect.width = clamp_t(s32, sel->r.width,
2850 			     48, b_right - c.rect.left);
2851 
2852 	c.rect.top = clamp_t(s32, sel->r.top, b_top, b_bottom - 32);
2853 	/* Top and height must be a multiple of two. */
2854 	c.rect.top = (c.rect.top + 1) & ~1;
2855 
2856 	c.rect.height = clamp_t(s32, sel->r.height,
2857 			      32, b_bottom - c.rect.top);
2858 	c.rect.height = (c.rect.height + 1) & ~1;
2859 
2860 	bttv_crop_calc_limits(&c);
2861 
2862 	sel->r = c.rect;
2863 
2864 	btv->crop[1] = c;
2865 
2866 	fh->do_crop = 1;
2867 
2868 	if (fh->width < c.min_scaled_width) {
2869 		fh->width = c.min_scaled_width;
2870 		btv->init.width = c.min_scaled_width;
2871 	} else if (fh->width > c.max_scaled_width) {
2872 		fh->width = c.max_scaled_width;
2873 		btv->init.width = c.max_scaled_width;
2874 	}
2875 
2876 	if (fh->height < c.min_scaled_height) {
2877 		fh->height = c.min_scaled_height;
2878 		btv->init.height = c.min_scaled_height;
2879 	} else if (fh->height > c.max_scaled_height) {
2880 		fh->height = c.max_scaled_height;
2881 		btv->init.height = c.max_scaled_height;
2882 	}
2883 
2884 	return 0;
2885 }
2886 
2887 static ssize_t bttv_read(struct file *file, char __user *data,
2888 			 size_t count, loff_t *ppos)
2889 {
2890 	struct bttv_fh *fh = file->private_data;
2891 	int retval = 0;
2892 
2893 	if (fh->btv->errors)
2894 		bttv_reinit_bt848(fh->btv);
2895 	dprintk("%d: read count=%d type=%s\n",
2896 		fh->btv->c.nr, (int)count, v4l2_type_names[fh->type]);
2897 
2898 	switch (fh->type) {
2899 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2900 		if (!check_alloc_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ)) {
2901 			/* VIDEO_READ in use by another fh,
2902 			   or VIDEO_STREAM by any fh. */
2903 			return -EBUSY;
2904 		}
2905 		retval = videobuf_read_one(&fh->cap, data, count, ppos,
2906 					   file->f_flags & O_NONBLOCK);
2907 		free_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ);
2908 		break;
2909 	case V4L2_BUF_TYPE_VBI_CAPTURE:
2910 		if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2911 			return -EBUSY;
2912 		retval = videobuf_read_stream(&fh->vbi, data, count, ppos, 1,
2913 					      file->f_flags & O_NONBLOCK);
2914 		break;
2915 	default:
2916 		BUG();
2917 	}
2918 	return retval;
2919 }
2920 
2921 static __poll_t bttv_poll(struct file *file, poll_table *wait)
2922 {
2923 	struct bttv_fh *fh = file->private_data;
2924 	struct bttv_buffer *buf;
2925 	enum v4l2_field field;
2926 	__poll_t rc = 0;
2927 	__poll_t req_events = poll_requested_events(wait);
2928 
2929 	if (v4l2_event_pending(&fh->fh))
2930 		rc = EPOLLPRI;
2931 	else if (req_events & EPOLLPRI)
2932 		poll_wait(file, &fh->fh.wait, wait);
2933 
2934 	if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
2935 		return rc;
2936 
2937 	if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
2938 		if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2939 			return rc | EPOLLERR;
2940 		return rc | videobuf_poll_stream(file, &fh->vbi, wait);
2941 	}
2942 
2943 	if (check_btres(fh,RESOURCE_VIDEO_STREAM)) {
2944 		/* streaming capture */
2945 		if (list_empty(&fh->cap.stream))
2946 			return rc | EPOLLERR;
2947 		buf = list_entry(fh->cap.stream.next,struct bttv_buffer,vb.stream);
2948 	} else {
2949 		/* read() capture */
2950 		if (NULL == fh->cap.read_buf) {
2951 			/* need to capture a new frame */
2952 			if (locked_btres(fh->btv,RESOURCE_VIDEO_STREAM))
2953 				return rc | EPOLLERR;
2954 			fh->cap.read_buf = videobuf_sg_alloc(fh->cap.msize);
2955 			if (NULL == fh->cap.read_buf)
2956 				return rc | EPOLLERR;
2957 			fh->cap.read_buf->memory = V4L2_MEMORY_USERPTR;
2958 			field = videobuf_next_field(&fh->cap);
2959 			if (0 != fh->cap.ops->buf_prepare(&fh->cap,fh->cap.read_buf,field)) {
2960 				kfree (fh->cap.read_buf);
2961 				fh->cap.read_buf = NULL;
2962 				return rc | EPOLLERR;
2963 			}
2964 			fh->cap.ops->buf_queue(&fh->cap,fh->cap.read_buf);
2965 			fh->cap.read_off = 0;
2966 		}
2967 		buf = (struct bttv_buffer*)fh->cap.read_buf;
2968 	}
2969 
2970 	poll_wait(file, &buf->vb.done, wait);
2971 	if (buf->vb.state == VIDEOBUF_DONE ||
2972 	    buf->vb.state == VIDEOBUF_ERROR)
2973 		rc = rc | EPOLLIN|EPOLLRDNORM;
2974 	return rc;
2975 }
2976 
2977 static int bttv_open(struct file *file)
2978 {
2979 	struct video_device *vdev = video_devdata(file);
2980 	struct bttv *btv = video_drvdata(file);
2981 	struct bttv_fh *fh;
2982 	enum v4l2_buf_type type = 0;
2983 
2984 	dprintk("open dev=%s\n", video_device_node_name(vdev));
2985 
2986 	if (vdev->vfl_type == VFL_TYPE_GRABBER) {
2987 		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2988 	} else if (vdev->vfl_type == VFL_TYPE_VBI) {
2989 		type = V4L2_BUF_TYPE_VBI_CAPTURE;
2990 	} else {
2991 		WARN_ON(1);
2992 		return -ENODEV;
2993 	}
2994 
2995 	dprintk("%d: open called (type=%s)\n",
2996 		btv->c.nr, v4l2_type_names[type]);
2997 
2998 	/* allocate per filehandle data */
2999 	fh = kmalloc(sizeof(*fh), GFP_KERNEL);
3000 	if (unlikely(!fh))
3001 		return -ENOMEM;
3002 	btv->users++;
3003 	file->private_data = fh;
3004 
3005 	*fh = btv->init;
3006 	v4l2_fh_init(&fh->fh, vdev);
3007 
3008 	fh->type = type;
3009 	fh->ov.setup_ok = 0;
3010 
3011 	videobuf_queue_sg_init(&fh->cap, &bttv_video_qops,
3012 			    &btv->c.pci->dev, &btv->s_lock,
3013 			    V4L2_BUF_TYPE_VIDEO_CAPTURE,
3014 			    V4L2_FIELD_INTERLACED,
3015 			    sizeof(struct bttv_buffer),
3016 			    fh, &btv->lock);
3017 	videobuf_queue_sg_init(&fh->vbi, &bttv_vbi_qops,
3018 			    &btv->c.pci->dev, &btv->s_lock,
3019 			    V4L2_BUF_TYPE_VBI_CAPTURE,
3020 			    V4L2_FIELD_SEQ_TB,
3021 			    sizeof(struct bttv_buffer),
3022 			    fh, &btv->lock);
3023 	set_tvnorm(btv,btv->tvnorm);
3024 	set_input(btv, btv->input, btv->tvnorm);
3025 	audio_mute(btv, btv->mute);
3026 
3027 	/* The V4L2 spec requires one global set of cropping parameters
3028 	   which only change on request. These are stored in btv->crop[1].
3029 	   However for compatibility with V4L apps and cropping unaware
3030 	   V4L2 apps we now reset the cropping parameters as seen through
3031 	   this fh, which is to say VIDIOC_G_SELECTION and scaling limit checks
3032 	   will use btv->crop[0], the default cropping parameters for the
3033 	   current video standard, and VIDIOC_S_FMT will not implicitly
3034 	   change the cropping parameters until VIDIOC_S_SELECTION has been
3035 	   called. */
3036 	fh->do_crop = !reset_crop; /* module parameter */
3037 
3038 	/* Likewise there should be one global set of VBI capture
3039 	   parameters, but for compatibility with V4L apps and earlier
3040 	   driver versions each fh has its own parameters. */
3041 	bttv_vbi_fmt_reset(&fh->vbi_fmt, btv->tvnorm);
3042 
3043 	bttv_field_count(btv);
3044 	v4l2_fh_add(&fh->fh);
3045 	return 0;
3046 }
3047 
3048 static int bttv_release(struct file *file)
3049 {
3050 	struct bttv_fh *fh = file->private_data;
3051 	struct bttv *btv = fh->btv;
3052 
3053 	/* turn off overlay */
3054 	if (check_btres(fh, RESOURCE_OVERLAY))
3055 		bttv_switch_overlay(btv,fh,NULL);
3056 
3057 	/* stop video capture */
3058 	if (check_btres(fh, RESOURCE_VIDEO_STREAM)) {
3059 		videobuf_streamoff(&fh->cap);
3060 		free_btres_lock(btv,fh,RESOURCE_VIDEO_STREAM);
3061 	}
3062 	if (fh->cap.read_buf) {
3063 		buffer_release(&fh->cap,fh->cap.read_buf);
3064 		kfree(fh->cap.read_buf);
3065 	}
3066 	if (check_btres(fh, RESOURCE_VIDEO_READ)) {
3067 		free_btres_lock(btv, fh, RESOURCE_VIDEO_READ);
3068 	}
3069 
3070 	/* stop vbi capture */
3071 	if (check_btres(fh, RESOURCE_VBI)) {
3072 		videobuf_stop(&fh->vbi);
3073 		free_btres_lock(btv,fh,RESOURCE_VBI);
3074 	}
3075 
3076 	/* free stuff */
3077 
3078 	videobuf_mmap_free(&fh->cap);
3079 	videobuf_mmap_free(&fh->vbi);
3080 	file->private_data = NULL;
3081 
3082 	btv->users--;
3083 	bttv_field_count(btv);
3084 
3085 	if (!btv->users)
3086 		audio_mute(btv, btv->mute);
3087 
3088 	v4l2_fh_del(&fh->fh);
3089 	v4l2_fh_exit(&fh->fh);
3090 	kfree(fh);
3091 	return 0;
3092 }
3093 
3094 static int
3095 bttv_mmap(struct file *file, struct vm_area_struct *vma)
3096 {
3097 	struct bttv_fh *fh = file->private_data;
3098 
3099 	dprintk("%d: mmap type=%s 0x%lx+%ld\n",
3100 		fh->btv->c.nr, v4l2_type_names[fh->type],
3101 		vma->vm_start, vma->vm_end - vma->vm_start);
3102 	return videobuf_mmap_mapper(bttv_queue(fh),vma);
3103 }
3104 
3105 static const struct v4l2_file_operations bttv_fops =
3106 {
3107 	.owner		  = THIS_MODULE,
3108 	.open		  = bttv_open,
3109 	.release	  = bttv_release,
3110 	.unlocked_ioctl	  = video_ioctl2,
3111 	.read		  = bttv_read,
3112 	.mmap		  = bttv_mmap,
3113 	.poll		  = bttv_poll,
3114 };
3115 
3116 static const struct v4l2_ioctl_ops bttv_ioctl_ops = {
3117 	.vidioc_querycap                = bttv_querycap,
3118 	.vidioc_enum_fmt_vid_cap        = bttv_enum_fmt_vid_cap,
3119 	.vidioc_g_fmt_vid_cap           = bttv_g_fmt_vid_cap,
3120 	.vidioc_try_fmt_vid_cap         = bttv_try_fmt_vid_cap,
3121 	.vidioc_s_fmt_vid_cap           = bttv_s_fmt_vid_cap,
3122 	.vidioc_enum_fmt_vid_overlay    = bttv_enum_fmt_vid_overlay,
3123 	.vidioc_g_fmt_vid_overlay       = bttv_g_fmt_vid_overlay,
3124 	.vidioc_try_fmt_vid_overlay     = bttv_try_fmt_vid_overlay,
3125 	.vidioc_s_fmt_vid_overlay       = bttv_s_fmt_vid_overlay,
3126 	.vidioc_g_fmt_vbi_cap           = bttv_g_fmt_vbi_cap,
3127 	.vidioc_try_fmt_vbi_cap         = bttv_try_fmt_vbi_cap,
3128 	.vidioc_s_fmt_vbi_cap           = bttv_s_fmt_vbi_cap,
3129 	.vidioc_g_pixelaspect           = bttv_g_pixelaspect,
3130 	.vidioc_reqbufs                 = bttv_reqbufs,
3131 	.vidioc_querybuf                = bttv_querybuf,
3132 	.vidioc_qbuf                    = bttv_qbuf,
3133 	.vidioc_dqbuf                   = bttv_dqbuf,
3134 	.vidioc_s_std                   = bttv_s_std,
3135 	.vidioc_g_std                   = bttv_g_std,
3136 	.vidioc_enum_input              = bttv_enum_input,
3137 	.vidioc_g_input                 = bttv_g_input,
3138 	.vidioc_s_input                 = bttv_s_input,
3139 	.vidioc_streamon                = bttv_streamon,
3140 	.vidioc_streamoff               = bttv_streamoff,
3141 	.vidioc_g_tuner                 = bttv_g_tuner,
3142 	.vidioc_s_tuner                 = bttv_s_tuner,
3143 	.vidioc_g_selection             = bttv_g_selection,
3144 	.vidioc_s_selection             = bttv_s_selection,
3145 	.vidioc_g_fbuf                  = bttv_g_fbuf,
3146 	.vidioc_s_fbuf                  = bttv_s_fbuf,
3147 	.vidioc_overlay                 = bttv_overlay,
3148 	.vidioc_g_parm                  = bttv_g_parm,
3149 	.vidioc_g_frequency             = bttv_g_frequency,
3150 	.vidioc_s_frequency             = bttv_s_frequency,
3151 	.vidioc_log_status		= bttv_log_status,
3152 	.vidioc_querystd		= bttv_querystd,
3153 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
3154 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
3155 #ifdef CONFIG_VIDEO_ADV_DEBUG
3156 	.vidioc_g_register		= bttv_g_register,
3157 	.vidioc_s_register		= bttv_s_register,
3158 #endif
3159 };
3160 
3161 static struct video_device bttv_video_template = {
3162 	.fops         = &bttv_fops,
3163 	.ioctl_ops    = &bttv_ioctl_ops,
3164 	.tvnorms      = BTTV_NORMS,
3165 };
3166 
3167 /* ----------------------------------------------------------------------- */
3168 /* radio interface                                                         */
3169 
3170 static int radio_open(struct file *file)
3171 {
3172 	struct video_device *vdev = video_devdata(file);
3173 	struct bttv *btv = video_drvdata(file);
3174 	struct bttv_fh *fh;
3175 
3176 	dprintk("open dev=%s\n", video_device_node_name(vdev));
3177 
3178 	dprintk("%d: open called (radio)\n", btv->c.nr);
3179 
3180 	/* allocate per filehandle data */
3181 	fh = kmalloc(sizeof(*fh), GFP_KERNEL);
3182 	if (unlikely(!fh))
3183 		return -ENOMEM;
3184 	file->private_data = fh;
3185 	*fh = btv->init;
3186 	v4l2_fh_init(&fh->fh, vdev);
3187 
3188 	btv->radio_user++;
3189 	audio_mute(btv, btv->mute);
3190 
3191 	v4l2_fh_add(&fh->fh);
3192 
3193 	return 0;
3194 }
3195 
3196 static int radio_release(struct file *file)
3197 {
3198 	struct bttv_fh *fh = file->private_data;
3199 	struct bttv *btv = fh->btv;
3200 	struct saa6588_command cmd;
3201 
3202 	file->private_data = NULL;
3203 	v4l2_fh_del(&fh->fh);
3204 	v4l2_fh_exit(&fh->fh);
3205 	kfree(fh);
3206 
3207 	btv->radio_user--;
3208 
3209 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_CLOSE, &cmd);
3210 
3211 	if (btv->radio_user == 0)
3212 		btv->has_radio_tuner = 0;
3213 	return 0;
3214 }
3215 
3216 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
3217 {
3218 	struct bttv_fh *fh = priv;
3219 	struct bttv *btv = fh->btv;
3220 
3221 	if (0 != t->index)
3222 		return -EINVAL;
3223 	strscpy(t->name, "Radio", sizeof(t->name));
3224 	t->type = V4L2_TUNER_RADIO;
3225 	radio_enable(btv);
3226 
3227 	bttv_call_all(btv, tuner, g_tuner, t);
3228 
3229 	if (btv->audio_mode_gpio)
3230 		btv->audio_mode_gpio(btv, t, 0);
3231 
3232 	if (btv->has_tea575x)
3233 		return snd_tea575x_g_tuner(&btv->tea, t);
3234 
3235 	return 0;
3236 }
3237 
3238 static int radio_s_tuner(struct file *file, void *priv,
3239 					const struct v4l2_tuner *t)
3240 {
3241 	struct bttv_fh *fh = priv;
3242 	struct bttv *btv = fh->btv;
3243 
3244 	if (0 != t->index)
3245 		return -EINVAL;
3246 
3247 	radio_enable(btv);
3248 	bttv_call_all(btv, tuner, s_tuner, t);
3249 	return 0;
3250 }
3251 
3252 static int radio_s_hw_freq_seek(struct file *file, void *priv,
3253 					const struct v4l2_hw_freq_seek *a)
3254 {
3255 	struct bttv_fh *fh = priv;
3256 	struct bttv *btv = fh->btv;
3257 
3258 	if (btv->has_tea575x)
3259 		return snd_tea575x_s_hw_freq_seek(file, &btv->tea, a);
3260 
3261 	return -ENOTTY;
3262 }
3263 
3264 static int radio_enum_freq_bands(struct file *file, void *priv,
3265 					 struct v4l2_frequency_band *band)
3266 {
3267 	struct bttv_fh *fh = priv;
3268 	struct bttv *btv = fh->btv;
3269 
3270 	if (btv->has_tea575x)
3271 		return snd_tea575x_enum_freq_bands(&btv->tea, band);
3272 
3273 	return -ENOTTY;
3274 }
3275 
3276 static ssize_t radio_read(struct file *file, char __user *data,
3277 			 size_t count, loff_t *ppos)
3278 {
3279 	struct bttv_fh *fh = file->private_data;
3280 	struct bttv *btv = fh->btv;
3281 	struct saa6588_command cmd;
3282 
3283 	cmd.block_count = count / 3;
3284 	cmd.nonblocking = file->f_flags & O_NONBLOCK;
3285 	cmd.buffer = data;
3286 	cmd.instance = file;
3287 	cmd.result = -ENODEV;
3288 	radio_enable(btv);
3289 
3290 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_READ, &cmd);
3291 
3292 	return cmd.result;
3293 }
3294 
3295 static __poll_t radio_poll(struct file *file, poll_table *wait)
3296 {
3297 	struct bttv_fh *fh = file->private_data;
3298 	struct bttv *btv = fh->btv;
3299 	__poll_t req_events = poll_requested_events(wait);
3300 	struct saa6588_command cmd;
3301 	__poll_t res = 0;
3302 
3303 	if (v4l2_event_pending(&fh->fh))
3304 		res = EPOLLPRI;
3305 	else if (req_events & EPOLLPRI)
3306 		poll_wait(file, &fh->fh.wait, wait);
3307 	radio_enable(btv);
3308 	cmd.instance = file;
3309 	cmd.event_list = wait;
3310 	cmd.poll_mask = res;
3311 	bttv_call_all(btv, core, ioctl, SAA6588_CMD_POLL, &cmd);
3312 
3313 	return cmd.poll_mask;
3314 }
3315 
3316 static const struct v4l2_file_operations radio_fops =
3317 {
3318 	.owner	  = THIS_MODULE,
3319 	.open	  = radio_open,
3320 	.read     = radio_read,
3321 	.release  = radio_release,
3322 	.unlocked_ioctl = video_ioctl2,
3323 	.poll     = radio_poll,
3324 };
3325 
3326 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
3327 	.vidioc_querycap        = bttv_querycap,
3328 	.vidioc_log_status	= bttv_log_status,
3329 	.vidioc_g_tuner         = radio_g_tuner,
3330 	.vidioc_s_tuner         = radio_s_tuner,
3331 	.vidioc_g_frequency     = bttv_g_frequency,
3332 	.vidioc_s_frequency     = bttv_s_frequency,
3333 	.vidioc_s_hw_freq_seek	= radio_s_hw_freq_seek,
3334 	.vidioc_enum_freq_bands	= radio_enum_freq_bands,
3335 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
3336 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
3337 };
3338 
3339 static struct video_device radio_template = {
3340 	.fops      = &radio_fops,
3341 	.ioctl_ops = &radio_ioctl_ops,
3342 };
3343 
3344 /* ----------------------------------------------------------------------- */
3345 /* some debug code                                                         */
3346 
3347 static int bttv_risc_decode(u32 risc)
3348 {
3349 	static char *instr[16] = {
3350 		[ BT848_RISC_WRITE     >> 28 ] = "write",
3351 		[ BT848_RISC_SKIP      >> 28 ] = "skip",
3352 		[ BT848_RISC_WRITEC    >> 28 ] = "writec",
3353 		[ BT848_RISC_JUMP      >> 28 ] = "jump",
3354 		[ BT848_RISC_SYNC      >> 28 ] = "sync",
3355 		[ BT848_RISC_WRITE123  >> 28 ] = "write123",
3356 		[ BT848_RISC_SKIP123   >> 28 ] = "skip123",
3357 		[ BT848_RISC_WRITE1S23 >> 28 ] = "write1s23",
3358 	};
3359 	static int incr[16] = {
3360 		[ BT848_RISC_WRITE     >> 28 ] = 2,
3361 		[ BT848_RISC_JUMP      >> 28 ] = 2,
3362 		[ BT848_RISC_SYNC      >> 28 ] = 2,
3363 		[ BT848_RISC_WRITE123  >> 28 ] = 5,
3364 		[ BT848_RISC_SKIP123   >> 28 ] = 2,
3365 		[ BT848_RISC_WRITE1S23 >> 28 ] = 3,
3366 	};
3367 	static char *bits[] = {
3368 		"be0",  "be1",  "be2",  "be3/resync",
3369 		"set0", "set1", "set2", "set3",
3370 		"clr0", "clr1", "clr2", "clr3",
3371 		"irq",  "res",  "eol",  "sol",
3372 	};
3373 	int i;
3374 
3375 	pr_cont("0x%08x [ %s", risc,
3376 	       instr[risc >> 28] ? instr[risc >> 28] : "INVALID");
3377 	for (i = ARRAY_SIZE(bits)-1; i >= 0; i--)
3378 		if (risc & (1 << (i + 12)))
3379 			pr_cont(" %s", bits[i]);
3380 	pr_cont(" count=%d ]\n", risc & 0xfff);
3381 	return incr[risc >> 28] ? incr[risc >> 28] : 1;
3382 }
3383 
3384 static void bttv_risc_disasm(struct bttv *btv,
3385 			     struct btcx_riscmem *risc)
3386 {
3387 	unsigned int i,j,n;
3388 
3389 	pr_info("%s: risc disasm: %p [dma=0x%08lx]\n",
3390 		btv->c.v4l2_dev.name, risc->cpu, (unsigned long)risc->dma);
3391 	for (i = 0; i < (risc->size >> 2); i += n) {
3392 		pr_info("%s:   0x%lx: ",
3393 			btv->c.v4l2_dev.name,
3394 			(unsigned long)(risc->dma + (i<<2)));
3395 		n = bttv_risc_decode(le32_to_cpu(risc->cpu[i]));
3396 		for (j = 1; j < n; j++)
3397 			pr_info("%s:   0x%lx: 0x%08x [ arg #%d ]\n",
3398 				btv->c.v4l2_dev.name,
3399 				(unsigned long)(risc->dma + ((i+j)<<2)),
3400 				risc->cpu[i+j], j);
3401 		if (0 == risc->cpu[i])
3402 			break;
3403 	}
3404 }
3405 
3406 static void bttv_print_riscaddr(struct bttv *btv)
3407 {
3408 	pr_info("  main: %08llx\n", (unsigned long long)btv->main.dma);
3409 	pr_info("  vbi : o=%08llx e=%08llx\n",
3410 		btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
3411 		btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
3412 	pr_info("  cap : o=%08llx e=%08llx\n",
3413 		btv->curr.top
3414 		? (unsigned long long)btv->curr.top->top.dma : 0,
3415 		btv->curr.bottom
3416 		? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
3417 	pr_info("  scr : o=%08llx e=%08llx\n",
3418 		btv->screen ? (unsigned long long)btv->screen->top.dma : 0,
3419 		btv->screen ? (unsigned long long)btv->screen->bottom.dma : 0);
3420 	bttv_risc_disasm(btv, &btv->main);
3421 }
3422 
3423 /* ----------------------------------------------------------------------- */
3424 /* irq handler                                                             */
3425 
3426 static char *irq_name[] = {
3427 	"FMTCHG",  // format change detected (525 vs. 625)
3428 	"VSYNC",   // vertical sync (new field)
3429 	"HSYNC",   // horizontal sync
3430 	"OFLOW",   // chroma/luma AGC overflow
3431 	"HLOCK",   // horizontal lock changed
3432 	"VPRES",   // video presence changed
3433 	"6", "7",
3434 	"I2CDONE", // hw irc operation finished
3435 	"GPINT",   // gpio port triggered irq
3436 	"10",
3437 	"RISCI",   // risc instruction triggered irq
3438 	"FBUS",    // pixel data fifo dropped data (high pci bus latencies)
3439 	"FTRGT",   // pixel data fifo overrun
3440 	"FDSR",    // fifo data stream resyncronisation
3441 	"PPERR",   // parity error (data transfer)
3442 	"RIPERR",  // parity error (read risc instructions)
3443 	"PABORT",  // pci abort
3444 	"OCERR",   // risc instruction error
3445 	"SCERR",   // syncronisation error
3446 };
3447 
3448 static void bttv_print_irqbits(u32 print, u32 mark)
3449 {
3450 	unsigned int i;
3451 
3452 	pr_cont("bits:");
3453 	for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
3454 		if (print & (1 << i))
3455 			pr_cont(" %s", irq_name[i]);
3456 		if (mark & (1 << i))
3457 			pr_cont("*");
3458 	}
3459 }
3460 
3461 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
3462 {
3463 	pr_warn("%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
3464 		btv->c.nr,
3465 		(unsigned long)btv->main.dma,
3466 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_VBI+1]),
3467 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_FIELD+1]),
3468 		(unsigned long)rc);
3469 
3470 	if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
3471 		pr_notice("%d: Oh, there (temporarily?) is no input signal. Ok, then this is harmless, don't worry ;)\n",
3472 			  btv->c.nr);
3473 		return;
3474 	}
3475 	pr_notice("%d: Uhm. Looks like we have unusual high IRQ latencies\n",
3476 		  btv->c.nr);
3477 	pr_notice("%d: Lets try to catch the culprit red-handed ...\n",
3478 		  btv->c.nr);
3479 	dump_stack();
3480 }
3481 
3482 static int
3483 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
3484 {
3485 	struct bttv_buffer *item;
3486 
3487 	memset(set,0,sizeof(*set));
3488 
3489 	/* capture request ? */
3490 	if (!list_empty(&btv->capture)) {
3491 		set->frame_irq = 1;
3492 		item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3493 		if (V4L2_FIELD_HAS_TOP(item->vb.field))
3494 			set->top    = item;
3495 		if (V4L2_FIELD_HAS_BOTTOM(item->vb.field))
3496 			set->bottom = item;
3497 
3498 		/* capture request for other field ? */
3499 		if (!V4L2_FIELD_HAS_BOTH(item->vb.field) &&
3500 		    (item->vb.queue.next != &btv->capture)) {
3501 			item = list_entry(item->vb.queue.next, struct bttv_buffer, vb.queue);
3502 			/* Mike Isely <isely@pobox.com> - Only check
3503 			 * and set up the bottom field in the logic
3504 			 * below.  Don't ever do the top field.  This
3505 			 * of course means that if we set up the
3506 			 * bottom field in the above code that we'll
3507 			 * actually skip a field.  But that's OK.
3508 			 * Having processed only a single buffer this
3509 			 * time, then the next time around the first
3510 			 * available buffer should be for a top field.
3511 			 * That will then cause us here to set up a
3512 			 * top then a bottom field in the normal way.
3513 			 * The alternative to this understanding is
3514 			 * that we set up the second available buffer
3515 			 * as a top field, but that's out of order
3516 			 * since this driver always processes the top
3517 			 * field first - the effect will be the two
3518 			 * buffers being returned in the wrong order,
3519 			 * with the second buffer also being delayed
3520 			 * by one field time (owing to the fifo nature
3521 			 * of videobuf).  Worse still, we'll be stuck
3522 			 * doing fields out of order now every time
3523 			 * until something else causes a field to be
3524 			 * dropped.  By effectively forcing a field to
3525 			 * drop this way then we always get back into
3526 			 * sync within a single frame time.  (Out of
3527 			 * order fields can screw up deinterlacing
3528 			 * algorithms.) */
3529 			if (!V4L2_FIELD_HAS_BOTH(item->vb.field)) {
3530 				if (NULL == set->bottom &&
3531 				    V4L2_FIELD_BOTTOM == item->vb.field) {
3532 					set->bottom = item;
3533 				}
3534 				if (NULL != set->top  &&  NULL != set->bottom)
3535 					set->top_irq = 2;
3536 			}
3537 		}
3538 	}
3539 
3540 	/* screen overlay ? */
3541 	if (NULL != btv->screen) {
3542 		if (V4L2_FIELD_HAS_BOTH(btv->screen->vb.field)) {
3543 			if (NULL == set->top && NULL == set->bottom) {
3544 				set->top    = btv->screen;
3545 				set->bottom = btv->screen;
3546 			}
3547 		} else {
3548 			if (V4L2_FIELD_TOP == btv->screen->vb.field &&
3549 			    NULL == set->top) {
3550 				set->top = btv->screen;
3551 			}
3552 			if (V4L2_FIELD_BOTTOM == btv->screen->vb.field &&
3553 			    NULL == set->bottom) {
3554 				set->bottom = btv->screen;
3555 			}
3556 		}
3557 	}
3558 
3559 	dprintk("%d: next set: top=%p bottom=%p [screen=%p,irq=%d,%d]\n",
3560 		btv->c.nr, set->top, set->bottom,
3561 		btv->screen, set->frame_irq, set->top_irq);
3562 	return 0;
3563 }
3564 
3565 static void
3566 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
3567 		      struct bttv_buffer_set *curr, unsigned int state)
3568 {
3569 	u64 ts = ktime_get_ns();
3570 
3571 	if (wakeup->top == wakeup->bottom) {
3572 		if (NULL != wakeup->top && curr->top != wakeup->top) {
3573 			if (irq_debug > 1)
3574 				pr_debug("%d: wakeup: both=%p\n",
3575 					 btv->c.nr, wakeup->top);
3576 			wakeup->top->vb.ts = ts;
3577 			wakeup->top->vb.field_count = btv->field_count;
3578 			wakeup->top->vb.state = state;
3579 			wake_up(&wakeup->top->vb.done);
3580 		}
3581 	} else {
3582 		if (NULL != wakeup->top && curr->top != wakeup->top) {
3583 			if (irq_debug > 1)
3584 				pr_debug("%d: wakeup: top=%p\n",
3585 					 btv->c.nr, wakeup->top);
3586 			wakeup->top->vb.ts = ts;
3587 			wakeup->top->vb.field_count = btv->field_count;
3588 			wakeup->top->vb.state = state;
3589 			wake_up(&wakeup->top->vb.done);
3590 		}
3591 		if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
3592 			if (irq_debug > 1)
3593 				pr_debug("%d: wakeup: bottom=%p\n",
3594 					 btv->c.nr, wakeup->bottom);
3595 			wakeup->bottom->vb.ts = ts;
3596 			wakeup->bottom->vb.field_count = btv->field_count;
3597 			wakeup->bottom->vb.state = state;
3598 			wake_up(&wakeup->bottom->vb.done);
3599 		}
3600 	}
3601 }
3602 
3603 static void
3604 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
3605 		    unsigned int state)
3606 {
3607 	if (NULL == wakeup)
3608 		return;
3609 
3610 	wakeup->vb.ts = ktime_get_ns();
3611 	wakeup->vb.field_count = btv->field_count;
3612 	wakeup->vb.state = state;
3613 	wake_up(&wakeup->vb.done);
3614 }
3615 
3616 static void bttv_irq_timeout(struct timer_list *t)
3617 {
3618 	struct bttv *btv = from_timer(btv, t, timeout);
3619 	struct bttv_buffer_set old,new;
3620 	struct bttv_buffer *ovbi;
3621 	struct bttv_buffer *item;
3622 	unsigned long flags;
3623 
3624 	if (bttv_verbose) {
3625 		pr_info("%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
3626 			btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
3627 			btread(BT848_RISC_COUNT));
3628 		bttv_print_irqbits(btread(BT848_INT_STAT),0);
3629 		pr_cont("\n");
3630 	}
3631 
3632 	spin_lock_irqsave(&btv->s_lock,flags);
3633 
3634 	/* deactivate stuff */
3635 	memset(&new,0,sizeof(new));
3636 	old  = btv->curr;
3637 	ovbi = btv->cvbi;
3638 	btv->curr = new;
3639 	btv->cvbi = NULL;
3640 	btv->loop_irq = 0;
3641 	bttv_buffer_activate_video(btv, &new);
3642 	bttv_buffer_activate_vbi(btv,   NULL);
3643 	bttv_set_dma(btv, 0);
3644 
3645 	/* wake up */
3646 	bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_ERROR);
3647 	bttv_irq_wakeup_vbi(btv, ovbi, VIDEOBUF_ERROR);
3648 
3649 	/* cancel all outstanding capture / vbi requests */
3650 	while (!list_empty(&btv->capture)) {
3651 		item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3652 		list_del(&item->vb.queue);
3653 		item->vb.state = VIDEOBUF_ERROR;
3654 		wake_up(&item->vb.done);
3655 	}
3656 	while (!list_empty(&btv->vcapture)) {
3657 		item = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3658 		list_del(&item->vb.queue);
3659 		item->vb.state = VIDEOBUF_ERROR;
3660 		wake_up(&item->vb.done);
3661 	}
3662 
3663 	btv->errors++;
3664 	spin_unlock_irqrestore(&btv->s_lock,flags);
3665 }
3666 
3667 static void
3668 bttv_irq_wakeup_top(struct bttv *btv)
3669 {
3670 	struct bttv_buffer *wakeup = btv->curr.top;
3671 
3672 	if (NULL == wakeup)
3673 		return;
3674 
3675 	spin_lock(&btv->s_lock);
3676 	btv->curr.top_irq = 0;
3677 	btv->curr.top = NULL;
3678 	bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
3679 
3680 	wakeup->vb.ts = ktime_get_ns();
3681 	wakeup->vb.field_count = btv->field_count;
3682 	wakeup->vb.state = VIDEOBUF_DONE;
3683 	wake_up(&wakeup->vb.done);
3684 	spin_unlock(&btv->s_lock);
3685 }
3686 
3687 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
3688 {
3689 	if (rc < risc->dma)
3690 		return 0;
3691 	if (rc > risc->dma + risc->size)
3692 		return 0;
3693 	return 1;
3694 }
3695 
3696 static void
3697 bttv_irq_switch_video(struct bttv *btv)
3698 {
3699 	struct bttv_buffer_set new;
3700 	struct bttv_buffer_set old;
3701 	dma_addr_t rc;
3702 
3703 	spin_lock(&btv->s_lock);
3704 
3705 	/* new buffer set */
3706 	bttv_irq_next_video(btv, &new);
3707 	rc = btread(BT848_RISC_COUNT);
3708 	if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
3709 	    (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
3710 		btv->framedrop++;
3711 		if (debug_latency)
3712 			bttv_irq_debug_low_latency(btv, rc);
3713 		spin_unlock(&btv->s_lock);
3714 		return;
3715 	}
3716 
3717 	/* switch over */
3718 	old = btv->curr;
3719 	btv->curr = new;
3720 	btv->loop_irq &= ~1;
3721 	bttv_buffer_activate_video(btv, &new);
3722 	bttv_set_dma(btv, 0);
3723 
3724 	/* switch input */
3725 	if (UNSET != btv->new_input) {
3726 		video_mux(btv,btv->new_input);
3727 		btv->new_input = UNSET;
3728 	}
3729 
3730 	/* wake up finished buffers */
3731 	bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_DONE);
3732 	spin_unlock(&btv->s_lock);
3733 }
3734 
3735 static void
3736 bttv_irq_switch_vbi(struct bttv *btv)
3737 {
3738 	struct bttv_buffer *new = NULL;
3739 	struct bttv_buffer *old;
3740 	u32 rc;
3741 
3742 	spin_lock(&btv->s_lock);
3743 
3744 	if (!list_empty(&btv->vcapture))
3745 		new = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3746 	old = btv->cvbi;
3747 
3748 	rc = btread(BT848_RISC_COUNT);
3749 	if (NULL != old && (is_active(&old->top,    rc) ||
3750 			    is_active(&old->bottom, rc))) {
3751 		btv->framedrop++;
3752 		if (debug_latency)
3753 			bttv_irq_debug_low_latency(btv, rc);
3754 		spin_unlock(&btv->s_lock);
3755 		return;
3756 	}
3757 
3758 	/* switch */
3759 	btv->cvbi = new;
3760 	btv->loop_irq &= ~4;
3761 	bttv_buffer_activate_vbi(btv, new);
3762 	bttv_set_dma(btv, 0);
3763 
3764 	bttv_irq_wakeup_vbi(btv, old, VIDEOBUF_DONE);
3765 	spin_unlock(&btv->s_lock);
3766 }
3767 
3768 static irqreturn_t bttv_irq(int irq, void *dev_id)
3769 {
3770 	u32 stat,astat;
3771 	u32 dstat;
3772 	int count;
3773 	struct bttv *btv;
3774 	int handled = 0;
3775 
3776 	btv=(struct bttv *)dev_id;
3777 
3778 	count=0;
3779 	while (1) {
3780 		/* get/clear interrupt status bits */
3781 		stat=btread(BT848_INT_STAT);
3782 		astat=stat&btread(BT848_INT_MASK);
3783 		if (!astat)
3784 			break;
3785 		handled = 1;
3786 		btwrite(stat,BT848_INT_STAT);
3787 
3788 		/* get device status bits */
3789 		dstat=btread(BT848_DSTATUS);
3790 
3791 		if (irq_debug) {
3792 			pr_debug("%d: irq loop=%d fc=%d riscs=%x, riscc=%08x, ",
3793 				 btv->c.nr, count, btv->field_count,
3794 				 stat>>28, btread(BT848_RISC_COUNT));
3795 			bttv_print_irqbits(stat,astat);
3796 			if (stat & BT848_INT_HLOCK)
3797 				pr_cont("   HLOC => %s",
3798 					dstat & BT848_DSTATUS_HLOC
3799 					? "yes" : "no");
3800 			if (stat & BT848_INT_VPRES)
3801 				pr_cont("   PRES => %s",
3802 					dstat & BT848_DSTATUS_PRES
3803 					? "yes" : "no");
3804 			if (stat & BT848_INT_FMTCHG)
3805 				pr_cont("   NUML => %s",
3806 					dstat & BT848_DSTATUS_NUML
3807 					? "625" : "525");
3808 			pr_cont("\n");
3809 		}
3810 
3811 		if (astat&BT848_INT_VSYNC)
3812 			btv->field_count++;
3813 
3814 		if ((astat & BT848_INT_GPINT) && btv->remote) {
3815 			bttv_input_irq(btv);
3816 		}
3817 
3818 		if (astat & BT848_INT_I2CDONE) {
3819 			btv->i2c_done = stat;
3820 			wake_up(&btv->i2c_queue);
3821 		}
3822 
3823 		if ((astat & BT848_INT_RISCI)  &&  (stat & (4<<28)))
3824 			bttv_irq_switch_vbi(btv);
3825 
3826 		if ((astat & BT848_INT_RISCI)  &&  (stat & (2<<28)))
3827 			bttv_irq_wakeup_top(btv);
3828 
3829 		if ((astat & BT848_INT_RISCI)  &&  (stat & (1<<28)))
3830 			bttv_irq_switch_video(btv);
3831 
3832 		if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3833 			/* trigger automute */
3834 			audio_mux_gpio(btv, btv->audio_input, btv->mute);
3835 
3836 		if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3837 			pr_info("%d: %s%s @ %08x,",
3838 				btv->c.nr,
3839 				(astat & BT848_INT_SCERR) ? "SCERR" : "",
3840 				(astat & BT848_INT_OCERR) ? "OCERR" : "",
3841 				btread(BT848_RISC_COUNT));
3842 			bttv_print_irqbits(stat,astat);
3843 			pr_cont("\n");
3844 			if (bttv_debug)
3845 				bttv_print_riscaddr(btv);
3846 		}
3847 		if (fdsr && astat & BT848_INT_FDSR) {
3848 			pr_info("%d: FDSR @ %08x\n",
3849 				btv->c.nr, btread(BT848_RISC_COUNT));
3850 			if (bttv_debug)
3851 				bttv_print_riscaddr(btv);
3852 		}
3853 
3854 		count++;
3855 		if (count > 4) {
3856 
3857 			if (count > 8 || !(astat & BT848_INT_GPINT)) {
3858 				btwrite(0, BT848_INT_MASK);
3859 
3860 				pr_err("%d: IRQ lockup, cleared int mask [",
3861 				       btv->c.nr);
3862 			} else {
3863 				pr_err("%d: IRQ lockup, clearing GPINT from int mask [",
3864 				       btv->c.nr);
3865 
3866 				btwrite(btread(BT848_INT_MASK) & (-1 ^ BT848_INT_GPINT),
3867 						BT848_INT_MASK);
3868 			}
3869 
3870 			bttv_print_irqbits(stat,astat);
3871 
3872 			pr_cont("]\n");
3873 		}
3874 	}
3875 	btv->irq_total++;
3876 	if (handled)
3877 		btv->irq_me++;
3878 	return IRQ_RETVAL(handled);
3879 }
3880 
3881 
3882 /* ----------------------------------------------------------------------- */
3883 /* initialization                                                          */
3884 
3885 static void vdev_init(struct bttv *btv,
3886 		      struct video_device *vfd,
3887 		      const struct video_device *template,
3888 		      const char *type_name)
3889 {
3890 	*vfd = *template;
3891 	vfd->v4l2_dev = &btv->c.v4l2_dev;
3892 	vfd->release = video_device_release_empty;
3893 	video_set_drvdata(vfd, btv);
3894 	snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3895 		 btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3896 		 type_name, bttv_tvcards[btv->c.type].name);
3897 	if (btv->tuner_type == TUNER_ABSENT) {
3898 		v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
3899 		v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
3900 		v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
3901 		v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
3902 	}
3903 }
3904 
3905 static void bttv_unregister_video(struct bttv *btv)
3906 {
3907 	video_unregister_device(&btv->video_dev);
3908 	video_unregister_device(&btv->vbi_dev);
3909 	video_unregister_device(&btv->radio_dev);
3910 }
3911 
3912 /* register video4linux devices */
3913 static int bttv_register_video(struct bttv *btv)
3914 {
3915 	if (no_overlay > 0)
3916 		pr_notice("Overlay support disabled\n");
3917 
3918 	/* video */
3919 	vdev_init(btv, &btv->video_dev, &bttv_video_template, "video");
3920 	btv->video_dev.device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TUNER |
3921 				     V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
3922 	if (btv->tuner_type != TUNER_ABSENT)
3923 		btv->video_dev.device_caps |= V4L2_CAP_TUNER;
3924 	if (no_overlay <= 0)
3925 		btv->video_dev.device_caps |= V4L2_CAP_VIDEO_OVERLAY;
3926 
3927 	if (video_register_device(&btv->video_dev, VFL_TYPE_GRABBER,
3928 				  video_nr[btv->c.nr]) < 0)
3929 		goto err;
3930 	pr_info("%d: registered device %s\n",
3931 		btv->c.nr, video_device_node_name(&btv->video_dev));
3932 	if (device_create_file(&btv->video_dev.dev,
3933 				     &dev_attr_card)<0) {
3934 		pr_err("%d: device_create_file 'card' failed\n", btv->c.nr);
3935 		goto err;
3936 	}
3937 
3938 	/* vbi */
3939 	vdev_init(btv, &btv->vbi_dev, &bttv_video_template, "vbi");
3940 	btv->vbi_dev.device_caps = V4L2_CAP_VBI_CAPTURE | V4L2_CAP_READWRITE |
3941 				   V4L2_CAP_STREAMING | V4L2_CAP_TUNER;
3942 	if (btv->tuner_type != TUNER_ABSENT)
3943 		btv->vbi_dev.device_caps |= V4L2_CAP_TUNER;
3944 
3945 	if (video_register_device(&btv->vbi_dev, VFL_TYPE_VBI,
3946 				  vbi_nr[btv->c.nr]) < 0)
3947 		goto err;
3948 	pr_info("%d: registered device %s\n",
3949 		btv->c.nr, video_device_node_name(&btv->vbi_dev));
3950 
3951 	if (!btv->has_radio)
3952 		return 0;
3953 	/* radio */
3954 	vdev_init(btv, &btv->radio_dev, &radio_template, "radio");
3955 	btv->radio_dev.device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
3956 	if (btv->has_saa6588)
3957 		btv->radio_dev.device_caps |= V4L2_CAP_READWRITE |
3958 					      V4L2_CAP_RDS_CAPTURE;
3959 	if (btv->has_tea575x)
3960 		btv->radio_dev.device_caps |= V4L2_CAP_HW_FREQ_SEEK;
3961 	btv->radio_dev.ctrl_handler = &btv->radio_ctrl_handler;
3962 	if (video_register_device(&btv->radio_dev, VFL_TYPE_RADIO,
3963 				  radio_nr[btv->c.nr]) < 0)
3964 		goto err;
3965 	pr_info("%d: registered device %s\n",
3966 		btv->c.nr, video_device_node_name(&btv->radio_dev));
3967 
3968 	/* all done */
3969 	return 0;
3970 
3971  err:
3972 	bttv_unregister_video(btv);
3973 	return -1;
3974 }
3975 
3976 
3977 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
3978 /* response on cards with no firmware is not enabled by OF */
3979 static void pci_set_command(struct pci_dev *dev)
3980 {
3981 #if defined(__powerpc__)
3982 	unsigned int cmd;
3983 
3984 	pci_read_config_dword(dev, PCI_COMMAND, &cmd);
3985 	cmd = (cmd | PCI_COMMAND_MEMORY );
3986 	pci_write_config_dword(dev, PCI_COMMAND, cmd);
3987 #endif
3988 }
3989 
3990 static int bttv_probe(struct pci_dev *dev, const struct pci_device_id *pci_id)
3991 {
3992 	struct v4l2_frequency init_freq = {
3993 		.tuner = 0,
3994 		.type = V4L2_TUNER_ANALOG_TV,
3995 		.frequency = 980,
3996 	};
3997 	int result;
3998 	unsigned char lat;
3999 	struct bttv *btv;
4000 	struct v4l2_ctrl_handler *hdl;
4001 
4002 	if (bttv_num == BTTV_MAX)
4003 		return -ENOMEM;
4004 	pr_info("Bt8xx card found (%d)\n", bttv_num);
4005 	bttvs[bttv_num] = btv = kzalloc(sizeof(*btv), GFP_KERNEL);
4006 	if (btv == NULL) {
4007 		pr_err("out of memory\n");
4008 		return -ENOMEM;
4009 	}
4010 	btv->c.nr  = bttv_num;
4011 	snprintf(btv->c.v4l2_dev.name, sizeof(btv->c.v4l2_dev.name),
4012 			"bttv%d", btv->c.nr);
4013 
4014 	/* initialize structs / fill in defaults */
4015 	mutex_init(&btv->lock);
4016 	spin_lock_init(&btv->s_lock);
4017 	spin_lock_init(&btv->gpio_lock);
4018 	init_waitqueue_head(&btv->i2c_queue);
4019 	INIT_LIST_HEAD(&btv->c.subs);
4020 	INIT_LIST_HEAD(&btv->capture);
4021 	INIT_LIST_HEAD(&btv->vcapture);
4022 
4023 	timer_setup(&btv->timeout, bttv_irq_timeout, 0);
4024 
4025 	btv->i2c_rc = -1;
4026 	btv->tuner_type  = UNSET;
4027 	btv->new_input   = UNSET;
4028 	btv->has_radio=radio[btv->c.nr];
4029 
4030 	/* pci stuff (init, get irq/mmio, ... */
4031 	btv->c.pci = dev;
4032 	btv->id  = dev->device;
4033 	if (pci_enable_device(dev)) {
4034 		pr_warn("%d: Can't enable device\n", btv->c.nr);
4035 		return -EIO;
4036 	}
4037 	if (pci_set_dma_mask(dev, DMA_BIT_MASK(32))) {
4038 		pr_warn("%d: No suitable DMA available\n", btv->c.nr);
4039 		return -EIO;
4040 	}
4041 	if (!request_mem_region(pci_resource_start(dev,0),
4042 				pci_resource_len(dev,0),
4043 				btv->c.v4l2_dev.name)) {
4044 		pr_warn("%d: can't request iomem (0x%llx)\n",
4045 			btv->c.nr,
4046 			(unsigned long long)pci_resource_start(dev, 0));
4047 		return -EBUSY;
4048 	}
4049 	pci_set_master(dev);
4050 	pci_set_command(dev);
4051 
4052 	result = v4l2_device_register(&dev->dev, &btv->c.v4l2_dev);
4053 	if (result < 0) {
4054 		pr_warn("%d: v4l2_device_register() failed\n", btv->c.nr);
4055 		goto fail0;
4056 	}
4057 	hdl = &btv->ctrl_handler;
4058 	v4l2_ctrl_handler_init(hdl, 20);
4059 	btv->c.v4l2_dev.ctrl_handler = hdl;
4060 	v4l2_ctrl_handler_init(&btv->radio_ctrl_handler, 6);
4061 
4062 	btv->revision = dev->revision;
4063 	pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4064 	pr_info("%d: Bt%d (rev %d) at %s, irq: %d, latency: %d, mmio: 0x%llx\n",
4065 		bttv_num, btv->id, btv->revision, pci_name(dev),
4066 		btv->c.pci->irq, lat,
4067 		(unsigned long long)pci_resource_start(dev, 0));
4068 	schedule();
4069 
4070 	btv->bt848_mmio = ioremap(pci_resource_start(dev, 0), 0x1000);
4071 	if (NULL == btv->bt848_mmio) {
4072 		pr_err("%d: ioremap() failed\n", btv->c.nr);
4073 		result = -EIO;
4074 		goto fail1;
4075 	}
4076 
4077 	/* identify card */
4078 	bttv_idcard(btv);
4079 
4080 	/* disable irqs, register irq handler */
4081 	btwrite(0, BT848_INT_MASK);
4082 	result = request_irq(btv->c.pci->irq, bttv_irq,
4083 	    IRQF_SHARED, btv->c.v4l2_dev.name, (void *)btv);
4084 	if (result < 0) {
4085 		pr_err("%d: can't get IRQ %d\n",
4086 		       bttv_num, btv->c.pci->irq);
4087 		goto fail1;
4088 	}
4089 
4090 	if (0 != bttv_handle_chipset(btv)) {
4091 		result = -EIO;
4092 		goto fail2;
4093 	}
4094 
4095 	/* init options from insmod args */
4096 	btv->opt_combfilter = combfilter;
4097 	bttv_ctrl_combfilter.def = combfilter;
4098 	bttv_ctrl_lumafilter.def = lumafilter;
4099 	btv->opt_automute   = automute;
4100 	bttv_ctrl_automute.def = automute;
4101 	bttv_ctrl_agc_crush.def = agc_crush;
4102 	btv->opt_vcr_hack   = vcr_hack;
4103 	bttv_ctrl_vcr_hack.def = vcr_hack;
4104 	bttv_ctrl_whitecrush_upper.def = whitecrush_upper;
4105 	bttv_ctrl_whitecrush_lower.def = whitecrush_lower;
4106 	btv->opt_uv_ratio   = uv_ratio;
4107 	bttv_ctrl_uv_ratio.def = uv_ratio;
4108 	bttv_ctrl_full_luma.def = full_luma_range;
4109 	bttv_ctrl_coring.def = coring;
4110 
4111 	/* fill struct bttv with some useful defaults */
4112 	btv->init.btv         = btv;
4113 	btv->init.ov.w.width  = 320;
4114 	btv->init.ov.w.height = 240;
4115 	btv->init.fmt         = format_by_fourcc(V4L2_PIX_FMT_BGR24);
4116 	btv->init.width       = 320;
4117 	btv->init.height      = 240;
4118 	btv->init.ov.w.width  = 320;
4119 	btv->init.ov.w.height = 240;
4120 	btv->init.ov.field    = V4L2_FIELD_INTERLACED;
4121 	btv->input = 0;
4122 
4123 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4124 			V4L2_CID_BRIGHTNESS, 0, 0xff00, 0x100, 32768);
4125 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4126 			V4L2_CID_CONTRAST, 0, 0xff80, 0x80, 0x6c00);
4127 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4128 			V4L2_CID_SATURATION, 0, 0xff80, 0x80, 32768);
4129 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4130 			V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
4131 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4132 			V4L2_CID_HUE, 0, 0xff00, 0x100, 32768);
4133 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4134 			V4L2_CID_CHROMA_AGC, 0, 1, 1, !!chroma_agc);
4135 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4136 		V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
4137 	if (btv->volume_gpio)
4138 		v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
4139 			V4L2_CID_AUDIO_VOLUME, 0, 0xff00, 0x100, 0xff00);
4140 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_combfilter, NULL);
4141 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_automute, NULL);
4142 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_lumafilter, NULL);
4143 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_agc_crush, NULL);
4144 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_vcr_hack, NULL);
4145 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_lower, NULL);
4146 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_upper, NULL);
4147 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_uv_ratio, NULL);
4148 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_full_luma, NULL);
4149 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_coring, NULL);
4150 
4151 	/* initialize hardware */
4152 	if (bttv_gpio)
4153 		bttv_gpio_tracking(btv,"pre-init");
4154 
4155 	bttv_risc_init_main(btv);
4156 	init_bt848(btv);
4157 
4158 	/* gpio */
4159 	btwrite(0x00, BT848_GPIO_REG_INP);
4160 	btwrite(0x00, BT848_GPIO_OUT_EN);
4161 	if (bttv_verbose)
4162 		bttv_gpio_tracking(btv,"init");
4163 
4164 	/* needs to be done before i2c is registered */
4165 	bttv_init_card1(btv);
4166 
4167 	/* register i2c + gpio */
4168 	init_bttv_i2c(btv);
4169 
4170 	/* some card-specific stuff (needs working i2c) */
4171 	bttv_init_card2(btv);
4172 	bttv_init_tuner(btv);
4173 	if (btv->tuner_type != TUNER_ABSENT) {
4174 		bttv_set_frequency(btv, &init_freq);
4175 		btv->radio_freq = 90500 * 16; /* 90.5Mhz default */
4176 	}
4177 	btv->std = V4L2_STD_PAL;
4178 	init_irqreg(btv);
4179 	if (!bttv_tvcards[btv->c.type].no_video)
4180 		v4l2_ctrl_handler_setup(hdl);
4181 	if (hdl->error) {
4182 		result = hdl->error;
4183 		goto fail2;
4184 	}
4185 	/* mute device */
4186 	audio_mute(btv, 1);
4187 
4188 	/* register video4linux + input */
4189 	if (!bttv_tvcards[btv->c.type].no_video) {
4190 		v4l2_ctrl_add_handler(&btv->radio_ctrl_handler, hdl,
4191 				v4l2_ctrl_radio_filter, false);
4192 		if (btv->radio_ctrl_handler.error) {
4193 			result = btv->radio_ctrl_handler.error;
4194 			goto fail2;
4195 		}
4196 		set_input(btv, 0, btv->tvnorm);
4197 		bttv_crop_reset(&btv->crop[0], btv->tvnorm);
4198 		btv->crop[1] = btv->crop[0]; /* current = default */
4199 		disclaim_vbi_lines(btv);
4200 		disclaim_video_lines(btv);
4201 		bttv_register_video(btv);
4202 	}
4203 
4204 	/* add subdevices and autoload dvb-bt8xx if needed */
4205 	if (bttv_tvcards[btv->c.type].has_dvb) {
4206 		bttv_sub_add_device(&btv->c, "dvb");
4207 		request_modules(btv);
4208 	}
4209 
4210 	if (!disable_ir) {
4211 		init_bttv_i2c_ir(btv);
4212 		bttv_input_init(btv);
4213 	}
4214 
4215 	/* everything is fine */
4216 	bttv_num++;
4217 	return 0;
4218 
4219 fail2:
4220 	free_irq(btv->c.pci->irq,btv);
4221 
4222 fail1:
4223 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
4224 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
4225 	v4l2_device_unregister(&btv->c.v4l2_dev);
4226 
4227 fail0:
4228 	if (btv->bt848_mmio)
4229 		iounmap(btv->bt848_mmio);
4230 	release_mem_region(pci_resource_start(btv->c.pci,0),
4231 			   pci_resource_len(btv->c.pci,0));
4232 	pci_disable_device(btv->c.pci);
4233 	return result;
4234 }
4235 
4236 static void bttv_remove(struct pci_dev *pci_dev)
4237 {
4238 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4239 	struct bttv *btv = to_bttv(v4l2_dev);
4240 
4241 	if (bttv_verbose)
4242 		pr_info("%d: unloading\n", btv->c.nr);
4243 
4244 	if (bttv_tvcards[btv->c.type].has_dvb)
4245 		flush_request_modules(btv);
4246 
4247 	/* shutdown everything (DMA+IRQs) */
4248 	btand(~15, BT848_GPIO_DMA_CTL);
4249 	btwrite(0, BT848_INT_MASK);
4250 	btwrite(~0x0, BT848_INT_STAT);
4251 	btwrite(0x0, BT848_GPIO_OUT_EN);
4252 	if (bttv_gpio)
4253 		bttv_gpio_tracking(btv,"cleanup");
4254 
4255 	/* tell gpio modules we are leaving ... */
4256 	btv->shutdown=1;
4257 	bttv_input_fini(btv);
4258 	bttv_sub_del_devices(&btv->c);
4259 
4260 	/* unregister i2c_bus + input */
4261 	fini_bttv_i2c(btv);
4262 
4263 	/* unregister video4linux */
4264 	bttv_unregister_video(btv);
4265 
4266 	/* free allocated memory */
4267 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
4268 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
4269 	btcx_riscmem_free(btv->c.pci,&btv->main);
4270 
4271 	/* free resources */
4272 	free_irq(btv->c.pci->irq,btv);
4273 	iounmap(btv->bt848_mmio);
4274 	release_mem_region(pci_resource_start(btv->c.pci,0),
4275 			   pci_resource_len(btv->c.pci,0));
4276 	pci_disable_device(btv->c.pci);
4277 
4278 	v4l2_device_unregister(&btv->c.v4l2_dev);
4279 	bttvs[btv->c.nr] = NULL;
4280 	kfree(btv);
4281 
4282 	return;
4283 }
4284 
4285 #ifdef CONFIG_PM
4286 static int bttv_suspend(struct pci_dev *pci_dev, pm_message_t state)
4287 {
4288 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4289 	struct bttv *btv = to_bttv(v4l2_dev);
4290 	struct bttv_buffer_set idle;
4291 	unsigned long flags;
4292 
4293 	dprintk("%d: suspend %d\n", btv->c.nr, state.event);
4294 
4295 	/* stop dma + irqs */
4296 	spin_lock_irqsave(&btv->s_lock,flags);
4297 	memset(&idle, 0, sizeof(idle));
4298 	btv->state.video = btv->curr;
4299 	btv->state.vbi   = btv->cvbi;
4300 	btv->state.loop_irq = btv->loop_irq;
4301 	btv->curr = idle;
4302 	btv->loop_irq = 0;
4303 	bttv_buffer_activate_video(btv, &idle);
4304 	bttv_buffer_activate_vbi(btv, NULL);
4305 	bttv_set_dma(btv, 0);
4306 	btwrite(0, BT848_INT_MASK);
4307 	spin_unlock_irqrestore(&btv->s_lock,flags);
4308 
4309 	/* save bt878 state */
4310 	btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
4311 	btv->state.gpio_data   = gpio_read();
4312 
4313 	/* save pci state */
4314 	pci_save_state(pci_dev);
4315 	if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) {
4316 		pci_disable_device(pci_dev);
4317 		btv->state.disabled = 1;
4318 	}
4319 	return 0;
4320 }
4321 
4322 static int bttv_resume(struct pci_dev *pci_dev)
4323 {
4324 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
4325 	struct bttv *btv = to_bttv(v4l2_dev);
4326 	unsigned long flags;
4327 	int err;
4328 
4329 	dprintk("%d: resume\n", btv->c.nr);
4330 
4331 	/* restore pci state */
4332 	if (btv->state.disabled) {
4333 		err=pci_enable_device(pci_dev);
4334 		if (err) {
4335 			pr_warn("%d: Can't enable device\n", btv->c.nr);
4336 			return err;
4337 		}
4338 		btv->state.disabled = 0;
4339 	}
4340 	err=pci_set_power_state(pci_dev, PCI_D0);
4341 	if (err) {
4342 		pci_disable_device(pci_dev);
4343 		pr_warn("%d: Can't enable device\n", btv->c.nr);
4344 		btv->state.disabled = 1;
4345 		return err;
4346 	}
4347 
4348 	pci_restore_state(pci_dev);
4349 
4350 	/* restore bt878 state */
4351 	bttv_reinit_bt848(btv);
4352 	gpio_inout(0xffffff, btv->state.gpio_enable);
4353 	gpio_write(btv->state.gpio_data);
4354 
4355 	/* restart dma */
4356 	spin_lock_irqsave(&btv->s_lock,flags);
4357 	btv->curr = btv->state.video;
4358 	btv->cvbi = btv->state.vbi;
4359 	btv->loop_irq = btv->state.loop_irq;
4360 	bttv_buffer_activate_video(btv, &btv->curr);
4361 	bttv_buffer_activate_vbi(btv, btv->cvbi);
4362 	bttv_set_dma(btv, 0);
4363 	spin_unlock_irqrestore(&btv->s_lock,flags);
4364 	return 0;
4365 }
4366 #endif
4367 
4368 static const struct pci_device_id bttv_pci_tbl[] = {
4369 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT848), 0},
4370 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT849), 0},
4371 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT878), 0},
4372 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT879), 0},
4373 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_FUSION879), 0},
4374 	{0,}
4375 };
4376 
4377 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
4378 
4379 static struct pci_driver bttv_pci_driver = {
4380 	.name     = "bttv",
4381 	.id_table = bttv_pci_tbl,
4382 	.probe    = bttv_probe,
4383 	.remove   = bttv_remove,
4384 #ifdef CONFIG_PM
4385 	.suspend  = bttv_suspend,
4386 	.resume   = bttv_resume,
4387 #endif
4388 };
4389 
4390 static int __init bttv_init_module(void)
4391 {
4392 	int ret;
4393 
4394 	bttv_num = 0;
4395 
4396 	pr_info("driver version %s loaded\n", BTTV_VERSION);
4397 	if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
4398 		gbuffers = 2;
4399 	if (gbufsize > BTTV_MAX_FBUF)
4400 		gbufsize = BTTV_MAX_FBUF;
4401 	gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
4402 	if (bttv_verbose)
4403 		pr_info("using %d buffers with %dk (%d pages) each for capture\n",
4404 			gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
4405 
4406 	bttv_check_chipset();
4407 
4408 	ret = bus_register(&bttv_sub_bus_type);
4409 	if (ret < 0) {
4410 		pr_warn("bus_register error: %d\n", ret);
4411 		return ret;
4412 	}
4413 	ret = pci_register_driver(&bttv_pci_driver);
4414 	if (ret < 0)
4415 		bus_unregister(&bttv_sub_bus_type);
4416 
4417 	return ret;
4418 }
4419 
4420 static void __exit bttv_cleanup_module(void)
4421 {
4422 	pci_unregister_driver(&bttv_pci_driver);
4423 	bus_unregister(&bttv_sub_bus_type);
4424 }
4425 
4426 module_init(bttv_init_module);
4427 module_exit(bttv_cleanup_module);
4428