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