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 card_show(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_RO(card);
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    VBI		 VIDIOC_STREAMON             VIDIOC_STREAMOFF
628 		 VIDIOC_QBUF 1)              bttv_release
629 		 bttv_read, bttv_poll 1) 3)
630 
631    1) The resource must be allocated when we enter buffer prepare functions
632       and remain allocated while buffers are in the DMA queue.
633    2) This is a single frame read.
634    3) This is a continuous read, implies VIDIOC_STREAMON.
635 
636    Note this driver permits video input and standard changes regardless if
637    resources are allocated.
638 */
639 
640 #define VBI_RESOURCES (RESOURCE_VBI)
641 #define VIDEO_RESOURCES (RESOURCE_VIDEO_READ | \
642 			 RESOURCE_VIDEO_STREAM)
643 
644 int check_alloc_btres_lock(struct bttv *btv, int bit)
645 {
646 	int xbits; /* mutual exclusive resources */
647 
648 	xbits = bit;
649 	if (bit & (RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM))
650 		xbits |= RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM;
651 
652 	/* is it free? */
653 	if (btv->resources & xbits) {
654 		/* no, someone else uses it */
655 		goto fail;
656 	}
657 
658 	if ((bit & VIDEO_RESOURCES)
659 	    && 0 == (btv->resources & VIDEO_RESOURCES)) {
660 		/* Do crop - use current, don't - use default parameters. */
661 		__s32 top = btv->crop[!!btv->do_crop].rect.top;
662 
663 		if (btv->vbi_end > top)
664 			goto fail;
665 
666 		/* We cannot capture the same line as video and VBI data.
667 		   Claim scan lines crop[].rect.top to bottom. */
668 		btv->crop_start = top;
669 	} else if (bit & VBI_RESOURCES) {
670 		__s32 end = btv->vbi_fmt.end;
671 
672 		if (end > btv->crop_start)
673 			goto fail;
674 
675 		/* Claim scan lines above btv->vbi_fmt.end. */
676 		btv->vbi_end = end;
677 	}
678 
679 	/* it's free, grab it */
680 	btv->resources |= bit;
681 	return 1;
682 
683  fail:
684 	return 0;
685 }
686 
687 static
688 int check_btres(struct bttv *btv, int bit)
689 {
690 	return (btv->resources & bit);
691 }
692 
693 static
694 int locked_btres(struct bttv *btv, int bit)
695 {
696 	return (btv->resources & bit);
697 }
698 
699 /* Call with btv->lock down. */
700 static void
701 disclaim_vbi_lines(struct bttv *btv)
702 {
703 	btv->vbi_end = 0;
704 }
705 
706 /* Call with btv->lock down. */
707 static void
708 disclaim_video_lines(struct bttv *btv)
709 {
710 	const struct bttv_tvnorm *tvnorm;
711 	u8 crop;
712 
713 	tvnorm = &bttv_tvnorms[btv->tvnorm];
714 	btv->crop_start = tvnorm->cropcap.bounds.top
715 		+ tvnorm->cropcap.bounds.height;
716 
717 	/* VBI capturing ends at VDELAY, start of video capturing, no
718 	   matter how many lines the VBI RISC program expects. When video
719 	   capturing is off, it shall no longer "preempt" VBI capturing,
720 	   so we set VDELAY to maximum. */
721 	crop = btread(BT848_E_CROP) | 0xc0;
722 	btwrite(crop, BT848_E_CROP);
723 	btwrite(0xfe, BT848_E_VDELAY_LO);
724 	btwrite(crop, BT848_O_CROP);
725 	btwrite(0xfe, BT848_O_VDELAY_LO);
726 }
727 
728 void free_btres_lock(struct bttv *btv, int bits)
729 {
730 	if ((btv->resources & bits) != bits) {
731 		/* trying to free resources not allocated by us ... */
732 		pr_err("BUG! (btres)\n");
733 	}
734 	btv->resources &= ~bits;
735 
736 	bits = btv->resources;
737 
738 	if (0 == (bits & VIDEO_RESOURCES))
739 		disclaim_video_lines(btv);
740 
741 	if (0 == (bits & VBI_RESOURCES))
742 		disclaim_vbi_lines(btv);
743 }
744 
745 /* ----------------------------------------------------------------------- */
746 /* If Bt848a or Bt849, use PLL for PAL/SECAM and crystal for NTSC          */
747 
748 /* Frequency = (F_input / PLL_X) * PLL_I.PLL_F/PLL_C
749    PLL_X = Reference pre-divider (0=1, 1=2)
750    PLL_C = Post divider (0=6, 1=4)
751    PLL_I = Integer input
752    PLL_F = Fractional input
753 
754    F_input = 28.636363 MHz:
755    PAL (CLKx2 = 35.46895 MHz): PLL_X = 1, PLL_I = 0x0E, PLL_F = 0xDCF9, PLL_C = 0
756 */
757 
758 static void set_pll_freq(struct bttv *btv, unsigned int fin, unsigned int fout)
759 {
760 	unsigned char fl, fh, fi;
761 
762 	/* prevent overflows */
763 	fin/=4;
764 	fout/=4;
765 
766 	fout*=12;
767 	fi=fout/fin;
768 
769 	fout=(fout%fin)*256;
770 	fh=fout/fin;
771 
772 	fout=(fout%fin)*256;
773 	fl=fout/fin;
774 
775 	btwrite(fl, BT848_PLL_F_LO);
776 	btwrite(fh, BT848_PLL_F_HI);
777 	btwrite(fi|BT848_PLL_X, BT848_PLL_XCI);
778 }
779 
780 static void set_pll(struct bttv *btv)
781 {
782 	int i;
783 
784 	if (!btv->pll.pll_crystal)
785 		return;
786 
787 	if (btv->pll.pll_ofreq == btv->pll.pll_current) {
788 		dprintk("%d: PLL: no change required\n", btv->c.nr);
789 		return;
790 	}
791 
792 	if (btv->pll.pll_ifreq == btv->pll.pll_ofreq) {
793 		/* no PLL needed */
794 		if (btv->pll.pll_current == 0)
795 			return;
796 		if (bttv_verbose)
797 			pr_info("%d: PLL can sleep, using XTAL (%d)\n",
798 				btv->c.nr, btv->pll.pll_ifreq);
799 		btwrite(0x00,BT848_TGCTRL);
800 		btwrite(0x00,BT848_PLL_XCI);
801 		btv->pll.pll_current = 0;
802 		return;
803 	}
804 
805 	if (bttv_verbose)
806 		pr_info("%d: Setting PLL: %d => %d (needs up to 100ms)\n",
807 			btv->c.nr,
808 			btv->pll.pll_ifreq, btv->pll.pll_ofreq);
809 	set_pll_freq(btv, btv->pll.pll_ifreq, btv->pll.pll_ofreq);
810 
811 	for (i=0; i<10; i++) {
812 		/*  Let other people run while the PLL stabilizes */
813 		msleep(10);
814 
815 		if (btread(BT848_DSTATUS) & BT848_DSTATUS_PLOCK) {
816 			btwrite(0,BT848_DSTATUS);
817 		} else {
818 			btwrite(0x08,BT848_TGCTRL);
819 			btv->pll.pll_current = btv->pll.pll_ofreq;
820 			if (bttv_verbose)
821 				pr_info("PLL set ok\n");
822 			return;
823 		}
824 	}
825 	btv->pll.pll_current = -1;
826 	if (bttv_verbose)
827 		pr_info("Setting PLL failed\n");
828 	return;
829 }
830 
831 /* used to switch between the bt848's analog/digital video capture modes */
832 static void bt848A_set_timing(struct bttv *btv)
833 {
834 	int i, len;
835 	int table_idx = bttv_tvnorms[btv->tvnorm].sram;
836 	int fsc       = bttv_tvnorms[btv->tvnorm].Fsc;
837 
838 	if (btv->input == btv->dig) {
839 		dprintk("%d: load digital timing table (table_idx=%d)\n",
840 			btv->c.nr,table_idx);
841 
842 		/* timing change...reset timing generator address */
843 		btwrite(0x00, BT848_TGCTRL);
844 		btwrite(0x02, BT848_TGCTRL);
845 		btwrite(0x00, BT848_TGCTRL);
846 
847 		len=SRAM_Table[table_idx][0];
848 		for(i = 1; i <= len; i++)
849 			btwrite(SRAM_Table[table_idx][i],BT848_TGLB);
850 		btv->pll.pll_ofreq = 27000000;
851 
852 		set_pll(btv);
853 		btwrite(0x11, BT848_TGCTRL);
854 		btwrite(0x41, BT848_DVSIF);
855 	} else {
856 		btv->pll.pll_ofreq = fsc;
857 		set_pll(btv);
858 		btwrite(0x0, BT848_DVSIF);
859 	}
860 }
861 
862 /* ----------------------------------------------------------------------- */
863 
864 static void bt848_bright(struct bttv *btv, int bright)
865 {
866 	int value;
867 
868 	// printk("set bright: %d\n", bright); // DEBUG
869 	btv->bright = bright;
870 
871 	/* We want -128 to 127 we get 0-65535 */
872 	value = (bright >> 8) - 128;
873 	btwrite(value & 0xff, BT848_BRIGHT);
874 }
875 
876 static void bt848_hue(struct bttv *btv, int hue)
877 {
878 	int value;
879 
880 	btv->hue = hue;
881 
882 	/* -128 to 127 */
883 	value = (hue >> 8) - 128;
884 	btwrite(value & 0xff, BT848_HUE);
885 }
886 
887 static void bt848_contrast(struct bttv *btv, int cont)
888 {
889 	int value,hibit;
890 
891 	btv->contrast = cont;
892 
893 	/* 0-511 */
894 	value = (cont  >> 7);
895 	hibit = (value >> 6) & 4;
896 	btwrite(value & 0xff, BT848_CONTRAST_LO);
897 	btaor(hibit, ~4, BT848_E_CONTROL);
898 	btaor(hibit, ~4, BT848_O_CONTROL);
899 }
900 
901 static void bt848_sat(struct bttv *btv, int color)
902 {
903 	int val_u,val_v,hibits;
904 
905 	btv->saturation = color;
906 
907 	/* 0-511 for the color */
908 	val_u   = ((color * btv->opt_uv_ratio) / 50) >> 7;
909 	val_v   = (((color * (100 - btv->opt_uv_ratio) / 50) >>7)*180L)/254;
910 	hibits  = (val_u >> 7) & 2;
911 	hibits |= (val_v >> 8) & 1;
912 	btwrite(val_u & 0xff, BT848_SAT_U_LO);
913 	btwrite(val_v & 0xff, BT848_SAT_V_LO);
914 	btaor(hibits, ~3, BT848_E_CONTROL);
915 	btaor(hibits, ~3, BT848_O_CONTROL);
916 }
917 
918 /* ----------------------------------------------------------------------- */
919 
920 static int
921 video_mux(struct bttv *btv, unsigned int input)
922 {
923 	int mux,mask2;
924 
925 	if (input >= bttv_tvcards[btv->c.type].video_inputs)
926 		return -EINVAL;
927 
928 	/* needed by RemoteVideo MX */
929 	mask2 = bttv_tvcards[btv->c.type].gpiomask2;
930 	if (mask2)
931 		gpio_inout(mask2,mask2);
932 
933 	if (input == btv->svhs)  {
934 		btor(BT848_CONTROL_COMP, BT848_E_CONTROL);
935 		btor(BT848_CONTROL_COMP, BT848_O_CONTROL);
936 	} else {
937 		btand(~BT848_CONTROL_COMP, BT848_E_CONTROL);
938 		btand(~BT848_CONTROL_COMP, BT848_O_CONTROL);
939 	}
940 	mux = bttv_muxsel(btv, input);
941 	btaor(mux<<5, ~(3<<5), BT848_IFORM);
942 	dprintk("%d: video mux: input=%d mux=%d\n", btv->c.nr, input, mux);
943 
944 	/* card specific hook */
945 	if(bttv_tvcards[btv->c.type].muxsel_hook)
946 		bttv_tvcards[btv->c.type].muxsel_hook (btv, input);
947 	return 0;
948 }
949 
950 static char *audio_modes[] = {
951 	"audio: tuner", "audio: radio", "audio: extern",
952 	"audio: intern", "audio: mute"
953 };
954 
955 static void
956 audio_mux_gpio(struct bttv *btv, int input, int mute)
957 {
958 	int gpio_val, signal, mute_gpio;
959 
960 	gpio_inout(bttv_tvcards[btv->c.type].gpiomask,
961 		   bttv_tvcards[btv->c.type].gpiomask);
962 	signal = btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC;
963 
964 	/* automute */
965 	mute_gpio = mute || (btv->opt_automute && (!signal || !btv->users)
966 				&& !btv->has_radio_tuner);
967 
968 	if (mute_gpio)
969 		gpio_val = bttv_tvcards[btv->c.type].gpiomute;
970 	else
971 		gpio_val = bttv_tvcards[btv->c.type].gpiomux[input];
972 
973 	switch (btv->c.type) {
974 	case BTTV_BOARD_VOODOOTV_FM:
975 	case BTTV_BOARD_VOODOOTV_200:
976 		gpio_val = bttv_tda9880_setnorm(btv, gpio_val);
977 		break;
978 
979 	default:
980 		gpio_bits(bttv_tvcards[btv->c.type].gpiomask, gpio_val);
981 	}
982 
983 	if (bttv_gpio)
984 		bttv_gpio_tracking(btv, audio_modes[mute_gpio ? 4 : input]);
985 }
986 
987 static int
988 audio_mute(struct bttv *btv, int mute)
989 {
990 	struct v4l2_ctrl *ctrl;
991 
992 	audio_mux_gpio(btv, btv->audio_input, mute);
993 
994 	if (btv->sd_msp34xx) {
995 		ctrl = v4l2_ctrl_find(btv->sd_msp34xx->ctrl_handler, V4L2_CID_AUDIO_MUTE);
996 		if (ctrl)
997 			v4l2_ctrl_s_ctrl(ctrl, mute);
998 	}
999 	if (btv->sd_tvaudio) {
1000 		ctrl = v4l2_ctrl_find(btv->sd_tvaudio->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1001 		if (ctrl)
1002 			v4l2_ctrl_s_ctrl(ctrl, mute);
1003 	}
1004 	if (btv->sd_tda7432) {
1005 		ctrl = v4l2_ctrl_find(btv->sd_tda7432->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1006 		if (ctrl)
1007 			v4l2_ctrl_s_ctrl(ctrl, mute);
1008 	}
1009 	return 0;
1010 }
1011 
1012 static int
1013 audio_input(struct bttv *btv, int input)
1014 {
1015 	audio_mux_gpio(btv, input, btv->mute);
1016 
1017 	if (btv->sd_msp34xx) {
1018 		u32 in;
1019 
1020 		/* Note: the inputs tuner/radio/extern/intern are translated
1021 		   to msp routings. This assumes common behavior for all msp3400
1022 		   based TV cards. When this assumption fails, then the
1023 		   specific MSP routing must be added to the card table.
1024 		   For now this is sufficient. */
1025 		switch (input) {
1026 		case TVAUDIO_INPUT_RADIO:
1027 			/* Some boards need the msp do to the radio demod */
1028 			if (btv->radio_uses_msp_demodulator) {
1029 				in = MSP_INPUT_DEFAULT;
1030 				break;
1031 			}
1032 			in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1033 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1034 			break;
1035 		case TVAUDIO_INPUT_EXTERN:
1036 			in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
1037 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1038 			break;
1039 		case TVAUDIO_INPUT_INTERN:
1040 			/* Yes, this is the same input as for RADIO. I doubt
1041 			   if this is ever used. The only board with an INTERN
1042 			   input is the BTTV_BOARD_AVERMEDIA98. I wonder how
1043 			   that was tested. My guess is that the whole INTERN
1044 			   input does not work. */
1045 			in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1046 				    MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1047 			break;
1048 		case TVAUDIO_INPUT_TUNER:
1049 		default:
1050 			/* This is the only card that uses TUNER2, and afaik,
1051 			   is the only difference between the VOODOOTV_FM
1052 			   and VOODOOTV_200 */
1053 			if (btv->c.type == BTTV_BOARD_VOODOOTV_200)
1054 				in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER2, \
1055 					MSP_DSP_IN_TUNER, MSP_DSP_IN_TUNER);
1056 			else
1057 				in = MSP_INPUT_DEFAULT;
1058 			break;
1059 		}
1060 		v4l2_subdev_call(btv->sd_msp34xx, audio, s_routing,
1061 			       in, MSP_OUTPUT_DEFAULT, 0);
1062 	}
1063 	if (btv->sd_tvaudio) {
1064 		v4l2_subdev_call(btv->sd_tvaudio, audio, s_routing,
1065 				 input, 0, 0);
1066 	}
1067 	return 0;
1068 }
1069 
1070 static void
1071 bttv_crop_calc_limits(struct bttv_crop *c)
1072 {
1073 	/* Scale factor min. 1:1, max. 16:1. Min. image size
1074 	   48 x 32. Scaled width must be a multiple of 4. */
1075 
1076 	if (1) {
1077 		/* For bug compatibility with VIDIOCGCAP and image
1078 		   size checks in earlier driver versions. */
1079 		c->min_scaled_width = 48;
1080 		c->min_scaled_height = 32;
1081 	} else {
1082 		c->min_scaled_width =
1083 			(max_t(unsigned int, 48, c->rect.width >> 4) + 3) & ~3;
1084 		c->min_scaled_height =
1085 			max_t(unsigned int, 32, c->rect.height >> 4);
1086 	}
1087 
1088 	c->max_scaled_width  = c->rect.width & ~3;
1089 	c->max_scaled_height = c->rect.height;
1090 }
1091 
1092 static void
1093 bttv_crop_reset(struct bttv_crop *c, unsigned int norm)
1094 {
1095 	c->rect = bttv_tvnorms[norm].cropcap.defrect;
1096 	bttv_crop_calc_limits(c);
1097 }
1098 
1099 /* Call with btv->lock down. */
1100 static int
1101 set_tvnorm(struct bttv *btv, unsigned int norm)
1102 {
1103 	const struct bttv_tvnorm *tvnorm;
1104 	v4l2_std_id id;
1105 
1106 	WARN_ON(norm >= BTTV_TVNORMS);
1107 	WARN_ON(btv->tvnorm >= BTTV_TVNORMS);
1108 
1109 	tvnorm = &bttv_tvnorms[norm];
1110 
1111 	if (memcmp(&bttv_tvnorms[btv->tvnorm].cropcap, &tvnorm->cropcap,
1112 		    sizeof (tvnorm->cropcap))) {
1113 		bttv_crop_reset(&btv->crop[0], norm);
1114 		btv->crop[1] = btv->crop[0]; /* current = default */
1115 
1116 		if (0 == (btv->resources & VIDEO_RESOURCES)) {
1117 			btv->crop_start = tvnorm->cropcap.bounds.top
1118 				+ tvnorm->cropcap.bounds.height;
1119 		}
1120 	}
1121 
1122 	btv->tvnorm = norm;
1123 
1124 	btwrite(tvnorm->adelay, BT848_ADELAY);
1125 	btwrite(tvnorm->bdelay, BT848_BDELAY);
1126 	btaor(tvnorm->iform,~(BT848_IFORM_NORM|BT848_IFORM_XTBOTH),
1127 	      BT848_IFORM);
1128 	btwrite(tvnorm->vbipack, BT848_VBI_PACK_SIZE);
1129 	btwrite(1, BT848_VBI_PACK_DEL);
1130 	bt848A_set_timing(btv);
1131 
1132 	switch (btv->c.type) {
1133 	case BTTV_BOARD_VOODOOTV_FM:
1134 	case BTTV_BOARD_VOODOOTV_200:
1135 		bttv_tda9880_setnorm(btv, gpio_read());
1136 		break;
1137 	}
1138 	id = tvnorm->v4l2_id;
1139 	bttv_call_all(btv, video, s_std, id);
1140 
1141 	return 0;
1142 }
1143 
1144 /* Call with btv->lock down. */
1145 static void
1146 set_input(struct bttv *btv, unsigned int input, unsigned int norm)
1147 {
1148 	unsigned long flags;
1149 
1150 	btv->input = input;
1151 	if (irq_iswitch) {
1152 		spin_lock_irqsave(&btv->s_lock,flags);
1153 		if (btv->curr.frame_irq) {
1154 			/* active capture -> delayed input switch */
1155 			btv->new_input = input;
1156 		} else {
1157 			video_mux(btv,input);
1158 		}
1159 		spin_unlock_irqrestore(&btv->s_lock,flags);
1160 	} else {
1161 		video_mux(btv,input);
1162 	}
1163 	btv->audio_input = (btv->tuner_type != TUNER_ABSENT && input == 0) ?
1164 				TVAUDIO_INPUT_TUNER : TVAUDIO_INPUT_EXTERN;
1165 	audio_input(btv, btv->audio_input);
1166 	set_tvnorm(btv, norm);
1167 }
1168 
1169 void init_irqreg(struct bttv *btv)
1170 {
1171 	/* clear status */
1172 	btwrite(0xfffffUL, BT848_INT_STAT);
1173 
1174 	if (bttv_tvcards[btv->c.type].no_video) {
1175 		/* i2c only */
1176 		btwrite(BT848_INT_I2CDONE,
1177 			BT848_INT_MASK);
1178 	} else {
1179 		/* full video */
1180 		btwrite((btv->triton1)  |
1181 			(btv->gpioirq ? BT848_INT_GPINT : 0) |
1182 			BT848_INT_SCERR |
1183 			(fdsr ? BT848_INT_FDSR : 0) |
1184 			BT848_INT_RISCI | BT848_INT_OCERR |
1185 			BT848_INT_FMTCHG|BT848_INT_HLOCK|
1186 			BT848_INT_I2CDONE,
1187 			BT848_INT_MASK);
1188 	}
1189 }
1190 
1191 static void init_bt848(struct bttv *btv)
1192 {
1193 	if (bttv_tvcards[btv->c.type].no_video) {
1194 		/* very basic init only */
1195 		init_irqreg(btv);
1196 		return;
1197 	}
1198 
1199 	btwrite(0x00, BT848_CAP_CTL);
1200 	btwrite(BT848_COLOR_CTL_GAMMA, BT848_COLOR_CTL);
1201 	btwrite(BT848_IFORM_XTAUTO | BT848_IFORM_AUTO, BT848_IFORM);
1202 
1203 	/* set planar and packed mode trigger points and         */
1204 	/* set rising edge of inverted GPINTR pin as irq trigger */
1205 	btwrite(BT848_GPIO_DMA_CTL_PKTP_32|
1206 		BT848_GPIO_DMA_CTL_PLTP1_16|
1207 		BT848_GPIO_DMA_CTL_PLTP23_16|
1208 		BT848_GPIO_DMA_CTL_GPINTC|
1209 		BT848_GPIO_DMA_CTL_GPINTI,
1210 		BT848_GPIO_DMA_CTL);
1211 
1212 	btwrite(0x20, BT848_E_VSCALE_HI);
1213 	btwrite(0x20, BT848_O_VSCALE_HI);
1214 
1215 	v4l2_ctrl_handler_setup(&btv->ctrl_handler);
1216 
1217 	/* interrupt */
1218 	init_irqreg(btv);
1219 }
1220 
1221 static void bttv_reinit_bt848(struct bttv *btv)
1222 {
1223 	unsigned long flags;
1224 
1225 	if (bttv_verbose)
1226 		pr_info("%d: reset, reinitialize\n", btv->c.nr);
1227 	spin_lock_irqsave(&btv->s_lock,flags);
1228 	btv->errors=0;
1229 	bttv_set_dma(btv,0);
1230 	spin_unlock_irqrestore(&btv->s_lock,flags);
1231 
1232 	init_bt848(btv);
1233 	btv->pll.pll_current = -1;
1234 	set_input(btv, btv->input, btv->tvnorm);
1235 }
1236 
1237 static int bttv_s_ctrl(struct v4l2_ctrl *c)
1238 {
1239 	struct bttv *btv = container_of(c->handler, struct bttv, ctrl_handler);
1240 	int val;
1241 
1242 	switch (c->id) {
1243 	case V4L2_CID_BRIGHTNESS:
1244 		bt848_bright(btv, c->val);
1245 		break;
1246 	case V4L2_CID_HUE:
1247 		bt848_hue(btv, c->val);
1248 		break;
1249 	case V4L2_CID_CONTRAST:
1250 		bt848_contrast(btv, c->val);
1251 		break;
1252 	case V4L2_CID_SATURATION:
1253 		bt848_sat(btv, c->val);
1254 		break;
1255 	case V4L2_CID_COLOR_KILLER:
1256 		if (c->val) {
1257 			btor(BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1258 			btor(BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1259 		} else {
1260 			btand(~BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1261 			btand(~BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1262 		}
1263 		break;
1264 	case V4L2_CID_AUDIO_MUTE:
1265 		audio_mute(btv, c->val);
1266 		btv->mute = c->val;
1267 		break;
1268 	case V4L2_CID_AUDIO_VOLUME:
1269 		btv->volume_gpio(btv, c->val);
1270 		break;
1271 
1272 	case V4L2_CID_CHROMA_AGC:
1273 		val = c->val ? BT848_SCLOOP_CAGC : 0;
1274 		btwrite(val, BT848_E_SCLOOP);
1275 		btwrite(val, BT848_O_SCLOOP);
1276 		break;
1277 	case V4L2_CID_PRIVATE_COMBFILTER:
1278 		btv->opt_combfilter = c->val;
1279 		break;
1280 	case V4L2_CID_PRIVATE_LUMAFILTER:
1281 		if (c->val) {
1282 			btand(~BT848_CONTROL_LDEC, BT848_E_CONTROL);
1283 			btand(~BT848_CONTROL_LDEC, BT848_O_CONTROL);
1284 		} else {
1285 			btor(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1286 			btor(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1287 		}
1288 		break;
1289 	case V4L2_CID_PRIVATE_AUTOMUTE:
1290 		btv->opt_automute = c->val;
1291 		break;
1292 	case V4L2_CID_PRIVATE_AGC_CRUSH:
1293 		btwrite(BT848_ADC_RESERVED |
1294 				(c->val ? BT848_ADC_CRUSH : 0),
1295 				BT848_ADC);
1296 		break;
1297 	case V4L2_CID_PRIVATE_VCR_HACK:
1298 		btv->opt_vcr_hack = c->val;
1299 		break;
1300 	case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1301 		btwrite(c->val, BT848_WC_UP);
1302 		break;
1303 	case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1304 		btwrite(c->val, BT848_WC_DOWN);
1305 		break;
1306 	case V4L2_CID_PRIVATE_UV_RATIO:
1307 		btv->opt_uv_ratio = c->val;
1308 		bt848_sat(btv, btv->saturation);
1309 		break;
1310 	case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1311 		btaor((c->val << 7), ~BT848_OFORM_RANGE, BT848_OFORM);
1312 		break;
1313 	case V4L2_CID_PRIVATE_CORING:
1314 		btaor((c->val << 5), ~BT848_OFORM_CORE32, BT848_OFORM);
1315 		break;
1316 	default:
1317 		return -EINVAL;
1318 	}
1319 	return 0;
1320 }
1321 
1322 /* ----------------------------------------------------------------------- */
1323 
1324 static const struct v4l2_ctrl_ops bttv_ctrl_ops = {
1325 	.s_ctrl = bttv_s_ctrl,
1326 };
1327 
1328 static struct v4l2_ctrl_config bttv_ctrl_combfilter = {
1329 	.ops = &bttv_ctrl_ops,
1330 	.id = V4L2_CID_PRIVATE_COMBFILTER,
1331 	.name = "Comb Filter",
1332 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1333 	.min = 0,
1334 	.max = 1,
1335 	.step = 1,
1336 	.def = 1,
1337 };
1338 
1339 static struct v4l2_ctrl_config bttv_ctrl_automute = {
1340 	.ops = &bttv_ctrl_ops,
1341 	.id = V4L2_CID_PRIVATE_AUTOMUTE,
1342 	.name = "Auto Mute",
1343 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1344 	.min = 0,
1345 	.max = 1,
1346 	.step = 1,
1347 	.def = 1,
1348 };
1349 
1350 static struct v4l2_ctrl_config bttv_ctrl_lumafilter = {
1351 	.ops = &bttv_ctrl_ops,
1352 	.id = V4L2_CID_PRIVATE_LUMAFILTER,
1353 	.name = "Luma Decimation Filter",
1354 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1355 	.min = 0,
1356 	.max = 1,
1357 	.step = 1,
1358 	.def = 1,
1359 };
1360 
1361 static struct v4l2_ctrl_config bttv_ctrl_agc_crush = {
1362 	.ops = &bttv_ctrl_ops,
1363 	.id = V4L2_CID_PRIVATE_AGC_CRUSH,
1364 	.name = "AGC Crush",
1365 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1366 	.min = 0,
1367 	.max = 1,
1368 	.step = 1,
1369 	.def = 1,
1370 };
1371 
1372 static struct v4l2_ctrl_config bttv_ctrl_vcr_hack = {
1373 	.ops = &bttv_ctrl_ops,
1374 	.id = V4L2_CID_PRIVATE_VCR_HACK,
1375 	.name = "VCR Hack",
1376 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1377 	.min = 0,
1378 	.max = 1,
1379 	.step = 1,
1380 	.def = 1,
1381 };
1382 
1383 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_lower = {
1384 	.ops = &bttv_ctrl_ops,
1385 	.id = V4L2_CID_PRIVATE_WHITECRUSH_LOWER,
1386 	.name = "Whitecrush Lower",
1387 	.type = V4L2_CTRL_TYPE_INTEGER,
1388 	.min = 0,
1389 	.max = 255,
1390 	.step = 1,
1391 	.def = 0x7f,
1392 };
1393 
1394 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_upper = {
1395 	.ops = &bttv_ctrl_ops,
1396 	.id = V4L2_CID_PRIVATE_WHITECRUSH_UPPER,
1397 	.name = "Whitecrush Upper",
1398 	.type = V4L2_CTRL_TYPE_INTEGER,
1399 	.min = 0,
1400 	.max = 255,
1401 	.step = 1,
1402 	.def = 0xcf,
1403 };
1404 
1405 static struct v4l2_ctrl_config bttv_ctrl_uv_ratio = {
1406 	.ops = &bttv_ctrl_ops,
1407 	.id = V4L2_CID_PRIVATE_UV_RATIO,
1408 	.name = "UV Ratio",
1409 	.type = V4L2_CTRL_TYPE_INTEGER,
1410 	.min = 0,
1411 	.max = 100,
1412 	.step = 1,
1413 	.def = 50,
1414 };
1415 
1416 static struct v4l2_ctrl_config bttv_ctrl_full_luma = {
1417 	.ops = &bttv_ctrl_ops,
1418 	.id = V4L2_CID_PRIVATE_FULL_LUMA_RANGE,
1419 	.name = "Full Luma Range",
1420 	.type = V4L2_CTRL_TYPE_BOOLEAN,
1421 	.min = 0,
1422 	.max = 1,
1423 	.step = 1,
1424 };
1425 
1426 static struct v4l2_ctrl_config bttv_ctrl_coring = {
1427 	.ops = &bttv_ctrl_ops,
1428 	.id = V4L2_CID_PRIVATE_CORING,
1429 	.name = "Coring",
1430 	.type = V4L2_CTRL_TYPE_INTEGER,
1431 	.min = 0,
1432 	.max = 3,
1433 	.step = 1,
1434 };
1435 
1436 
1437 /* ----------------------------------------------------------------------- */
1438 
1439 void bttv_gpio_tracking(struct bttv *btv, char *comment)
1440 {
1441 	unsigned int outbits, data;
1442 	outbits = btread(BT848_GPIO_OUT_EN);
1443 	data    = btread(BT848_GPIO_DATA);
1444 	pr_debug("%d: gpio: en=%08x, out=%08x in=%08x [%s]\n",
1445 		 btv->c.nr, outbits, data & outbits, data & ~outbits, comment);
1446 }
1447 
1448 static const struct bttv_format*
1449 format_by_fourcc(int fourcc)
1450 {
1451 	unsigned int i;
1452 
1453 	for (i = 0; i < FORMATS; i++) {
1454 		if (-1 == formats[i].fourcc)
1455 			continue;
1456 		if (formats[i].fourcc == fourcc)
1457 			return formats+i;
1458 	}
1459 	return NULL;
1460 }
1461 
1462 /* ----------------------------------------------------------------------- */
1463 /* video4linux (1) interface                                               */
1464 
1465 static int queue_setup(struct vb2_queue *q, unsigned int *num_buffers,
1466 		       unsigned int *num_planes, unsigned int sizes[],
1467 		       struct device *alloc_devs[])
1468 {
1469 	struct bttv *btv = vb2_get_drv_priv(q);
1470 	unsigned int size = btv->fmt->depth * btv->width * btv->height >> 3;
1471 
1472 	if (*num_planes)
1473 		return sizes[0] < size ? -EINVAL : 0;
1474 	*num_planes = 1;
1475 	sizes[0] = size;
1476 
1477 	return 0;
1478 }
1479 
1480 static void buf_queue(struct vb2_buffer *vb)
1481 {
1482 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1483 	struct vb2_queue *vq = vb->vb2_queue;
1484 	struct bttv *btv = vb2_get_drv_priv(vq);
1485 	struct bttv_buffer *buf = container_of(vbuf, struct bttv_buffer, vbuf);
1486 	unsigned long flags;
1487 
1488 	spin_lock_irqsave(&btv->s_lock, flags);
1489 	if (list_empty(&btv->capture)) {
1490 		btv->loop_irq = BT848_RISC_VIDEO;
1491 		if (vb2_is_streaming(&btv->vbiq))
1492 			btv->loop_irq |= BT848_RISC_VBI;
1493 		bttv_set_dma(btv, BT848_CAP_CTL_CAPTURE_ODD |
1494 			     BT848_CAP_CTL_CAPTURE_EVEN);
1495 	}
1496 	list_add_tail(&buf->list, &btv->capture);
1497 	spin_unlock_irqrestore(&btv->s_lock, flags);
1498 }
1499 
1500 static int buf_prepare(struct vb2_buffer *vb)
1501 {
1502 	struct vb2_queue *vq = vb->vb2_queue;
1503 	struct bttv *btv = vb2_get_drv_priv(vq);
1504 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1505 	struct bttv_buffer *buf = container_of(vbuf, struct bttv_buffer, vbuf);
1506 	unsigned int size = (btv->fmt->depth * btv->width * btv->height) >> 3;
1507 
1508 	if (vb2_plane_size(vb, 0) < size)
1509 		return -EINVAL;
1510 	vb2_set_plane_payload(vb, 0, size);
1511 
1512 	if (btv->field != V4L2_FIELD_ALTERNATE) {
1513 		buf->vbuf.field = btv->field;
1514 	} else if (btv->field_last == V4L2_FIELD_TOP) {
1515 		buf->vbuf.field = V4L2_FIELD_BOTTOM;
1516 		btv->field_last = V4L2_FIELD_BOTTOM;
1517 	} else {
1518 		buf->vbuf.field = V4L2_FIELD_TOP;
1519 		btv->field_last = V4L2_FIELD_TOP;
1520 	}
1521 
1522 	/* Allocate memory for risc struct and create the risc program. */
1523 	return bttv_buffer_risc(btv, buf);
1524 }
1525 
1526 static void buf_cleanup(struct vb2_buffer *vb)
1527 {
1528 	struct vb2_queue *vq = vb->vb2_queue;
1529 	struct bttv *btv = vb2_get_drv_priv(vq);
1530 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1531 	struct bttv_buffer *buf = container_of(vbuf, struct bttv_buffer, vbuf);
1532 
1533 	btcx_riscmem_free(btv->c.pci, &buf->top);
1534 	btcx_riscmem_free(btv->c.pci, &buf->bottom);
1535 }
1536 
1537 static int start_streaming(struct vb2_queue *q, unsigned int count)
1538 {
1539 	int ret = 1;
1540 	int seqnr = 0;
1541 	struct bttv_buffer *buf;
1542 	struct bttv *btv = vb2_get_drv_priv(q);
1543 
1544 	ret = check_alloc_btres_lock(btv, RESOURCE_VIDEO_STREAM);
1545 	if (ret == 0) {
1546 		if (btv->field_count)
1547 			seqnr++;
1548 		while (!list_empty(&btv->capture)) {
1549 			buf = list_entry(btv->capture.next,
1550 					 struct bttv_buffer, list);
1551 			list_del(&buf->list);
1552 			buf->vbuf.sequence = (btv->field_count >> 1) + seqnr++;
1553 			vb2_buffer_done(&buf->vbuf.vb2_buf,
1554 					VB2_BUF_STATE_QUEUED);
1555 		}
1556 		return !ret;
1557 	}
1558 	if (!vb2_is_streaming(&btv->vbiq)) {
1559 		init_irqreg(btv);
1560 		btv->field_count = 0;
1561 	}
1562 	btv->framedrop = 0;
1563 
1564 	return 0;
1565 }
1566 
1567 static void stop_streaming(struct vb2_queue *q)
1568 {
1569 	unsigned long flags;
1570 	struct bttv *btv = vb2_get_drv_priv(q);
1571 
1572 	vb2_wait_for_all_buffers(q);
1573 	spin_lock_irqsave(&btv->s_lock, flags);
1574 	free_btres_lock(btv, RESOURCE_VIDEO_STREAM);
1575 	if (!vb2_is_streaming(&btv->vbiq)) {
1576 		/* stop field counter */
1577 		btand(~BT848_INT_VSYNC, BT848_INT_MASK);
1578 	}
1579 	spin_unlock_irqrestore(&btv->s_lock, flags);
1580 }
1581 
1582 static const struct vb2_ops bttv_video_qops = {
1583 	.queue_setup    = queue_setup,
1584 	.buf_queue      = buf_queue,
1585 	.buf_prepare    = buf_prepare,
1586 	.buf_cleanup    = buf_cleanup,
1587 	.start_streaming = start_streaming,
1588 	.stop_streaming = stop_streaming,
1589 	.wait_prepare   = vb2_ops_wait_prepare,
1590 	.wait_finish    = vb2_ops_wait_finish,
1591 };
1592 
1593 static void radio_enable(struct bttv *btv)
1594 {
1595 	/* Switch to the radio tuner */
1596 	if (!btv->has_radio_tuner) {
1597 		btv->has_radio_tuner = 1;
1598 		bttv_call_all(btv, tuner, s_radio);
1599 		btv->audio_input = TVAUDIO_INPUT_RADIO;
1600 		audio_input(btv, btv->audio_input);
1601 	}
1602 }
1603 
1604 static int bttv_s_std(struct file *file, void *priv, v4l2_std_id id)
1605 {
1606 	struct bttv *btv = video_drvdata(file);
1607 	unsigned int i;
1608 
1609 	for (i = 0; i < BTTV_TVNORMS; i++)
1610 		if (id & bttv_tvnorms[i].v4l2_id)
1611 			break;
1612 	if (i == BTTV_TVNORMS)
1613 		return -EINVAL;
1614 	btv->std = id;
1615 	set_tvnorm(btv, i);
1616 	return 0;
1617 }
1618 
1619 static int bttv_g_std(struct file *file, void *priv, v4l2_std_id *id)
1620 {
1621 	struct bttv *btv = video_drvdata(file);
1622 
1623 	*id = btv->std;
1624 	return 0;
1625 }
1626 
1627 static int bttv_querystd(struct file *file, void *f, v4l2_std_id *id)
1628 {
1629 	struct bttv *btv = video_drvdata(file);
1630 
1631 	if (btread(BT848_DSTATUS) & BT848_DSTATUS_NUML)
1632 		*id &= V4L2_STD_625_50;
1633 	else
1634 		*id &= V4L2_STD_525_60;
1635 	return 0;
1636 }
1637 
1638 static int bttv_enum_input(struct file *file, void *priv,
1639 					struct v4l2_input *i)
1640 {
1641 	struct bttv *btv = video_drvdata(file);
1642 
1643 	if (i->index >= bttv_tvcards[btv->c.type].video_inputs)
1644 		return -EINVAL;
1645 
1646 	i->type     = V4L2_INPUT_TYPE_CAMERA;
1647 	i->audioset = 0;
1648 
1649 	if (btv->tuner_type != TUNER_ABSENT && i->index == 0) {
1650 		sprintf(i->name, "Television");
1651 		i->type  = V4L2_INPUT_TYPE_TUNER;
1652 		i->tuner = 0;
1653 	} else if (i->index == btv->svhs) {
1654 		sprintf(i->name, "S-Video");
1655 	} else {
1656 		sprintf(i->name, "Composite%d", i->index);
1657 	}
1658 
1659 	if (i->index == btv->input) {
1660 		__u32 dstatus = btread(BT848_DSTATUS);
1661 		if (0 == (dstatus & BT848_DSTATUS_PRES))
1662 			i->status |= V4L2_IN_ST_NO_SIGNAL;
1663 		if (0 == (dstatus & BT848_DSTATUS_HLOC))
1664 			i->status |= V4L2_IN_ST_NO_H_LOCK;
1665 	}
1666 
1667 	i->std = BTTV_NORMS;
1668 	return 0;
1669 }
1670 
1671 static int bttv_g_input(struct file *file, void *priv, unsigned int *i)
1672 {
1673 	struct bttv *btv = video_drvdata(file);
1674 
1675 	*i = btv->input;
1676 
1677 	return 0;
1678 }
1679 
1680 static int bttv_s_input(struct file *file, void *priv, unsigned int i)
1681 {
1682 	struct bttv *btv = video_drvdata(file);
1683 
1684 	if (i >= bttv_tvcards[btv->c.type].video_inputs)
1685 		return -EINVAL;
1686 
1687 	set_input(btv, i, btv->tvnorm);
1688 	return 0;
1689 }
1690 
1691 static int bttv_s_tuner(struct file *file, void *priv,
1692 					const struct v4l2_tuner *t)
1693 {
1694 	struct bttv *btv = video_drvdata(file);
1695 
1696 	if (t->index)
1697 		return -EINVAL;
1698 
1699 	bttv_call_all(btv, tuner, s_tuner, t);
1700 
1701 	if (btv->audio_mode_gpio) {
1702 		struct v4l2_tuner copy = *t;
1703 
1704 		btv->audio_mode_gpio(btv, &copy, 1);
1705 	}
1706 	return 0;
1707 }
1708 
1709 static int bttv_g_frequency(struct file *file, void *priv,
1710 					struct v4l2_frequency *f)
1711 {
1712 	struct bttv *btv = video_drvdata(file);
1713 
1714 	if (f->tuner)
1715 		return -EINVAL;
1716 
1717 	if (f->type == V4L2_TUNER_RADIO)
1718 		radio_enable(btv);
1719 	f->frequency = f->type == V4L2_TUNER_RADIO ?
1720 				btv->radio_freq : btv->tv_freq;
1721 
1722 	return 0;
1723 }
1724 
1725 static void bttv_set_frequency(struct bttv *btv, const struct v4l2_frequency *f)
1726 {
1727 	struct v4l2_frequency new_freq = *f;
1728 
1729 	bttv_call_all(btv, tuner, s_frequency, f);
1730 	/* s_frequency may clamp the frequency, so get the actual
1731 	   frequency before assigning radio/tv_freq. */
1732 	bttv_call_all(btv, tuner, g_frequency, &new_freq);
1733 	if (new_freq.type == V4L2_TUNER_RADIO) {
1734 		radio_enable(btv);
1735 		btv->radio_freq = new_freq.frequency;
1736 		if (btv->has_tea575x) {
1737 			btv->tea.freq = btv->radio_freq;
1738 			snd_tea575x_set_freq(&btv->tea);
1739 		}
1740 	} else {
1741 		btv->tv_freq = new_freq.frequency;
1742 	}
1743 }
1744 
1745 static int bttv_s_frequency(struct file *file, void *priv,
1746 					const struct v4l2_frequency *f)
1747 {
1748 	struct bttv *btv = video_drvdata(file);
1749 
1750 	if (f->tuner)
1751 		return -EINVAL;
1752 
1753 	bttv_set_frequency(btv, f);
1754 	return 0;
1755 }
1756 
1757 static int bttv_log_status(struct file *file, void *f)
1758 {
1759 	struct video_device *vdev = video_devdata(file);
1760 	struct bttv *btv = video_drvdata(file);
1761 
1762 	v4l2_ctrl_handler_log_status(vdev->ctrl_handler, btv->c.v4l2_dev.name);
1763 	bttv_call_all(btv, core, log_status);
1764 	return 0;
1765 }
1766 
1767 #ifdef CONFIG_VIDEO_ADV_DEBUG
1768 static int bttv_g_register(struct file *file, void *f,
1769 					struct v4l2_dbg_register *reg)
1770 {
1771 	struct bttv *btv = video_drvdata(file);
1772 
1773 	/* bt848 has a 12-bit register space */
1774 	reg->reg &= 0xfff;
1775 	reg->val = btread(reg->reg);
1776 	reg->size = 1;
1777 
1778 	return 0;
1779 }
1780 
1781 static int bttv_s_register(struct file *file, void *f,
1782 					const struct v4l2_dbg_register *reg)
1783 {
1784 	struct bttv *btv = video_drvdata(file);
1785 
1786 	/* bt848 has a 12-bit register space */
1787 	btwrite(reg->val, reg->reg & 0xfff);
1788 
1789 	return 0;
1790 }
1791 #endif
1792 
1793 /* Given cropping boundaries b and the scaled width and height of a
1794    single field or frame, which must not exceed hardware limits, this
1795    function adjusts the cropping parameters c. */
1796 static void
1797 bttv_crop_adjust	(struct bttv_crop *             c,
1798 			 const struct v4l2_rect *	b,
1799 			 __s32                          width,
1800 			 __s32                          height,
1801 			 enum v4l2_field                field)
1802 {
1803 	__s32 frame_height = height << !V4L2_FIELD_HAS_BOTH(field);
1804 	__s32 max_left;
1805 	__s32 max_top;
1806 
1807 	if (width < c->min_scaled_width) {
1808 		/* Max. hor. scale factor 16:1. */
1809 		c->rect.width = width * 16;
1810 	} else if (width > c->max_scaled_width) {
1811 		/* Min. hor. scale factor 1:1. */
1812 		c->rect.width = width;
1813 
1814 		max_left = b->left + b->width - width;
1815 		max_left = min(max_left, (__s32) MAX_HDELAY);
1816 		if (c->rect.left > max_left)
1817 			c->rect.left = max_left;
1818 	}
1819 
1820 	if (height < c->min_scaled_height) {
1821 		/* Max. vert. scale factor 16:1, single fields 8:1. */
1822 		c->rect.height = height * 16;
1823 	} else if (frame_height > c->max_scaled_height) {
1824 		/* Min. vert. scale factor 1:1.
1825 		   Top and height count field lines times two. */
1826 		c->rect.height = (frame_height + 1) & ~1;
1827 
1828 		max_top = b->top + b->height - c->rect.height;
1829 		if (c->rect.top > max_top)
1830 			c->rect.top = max_top;
1831 	}
1832 
1833 	bttv_crop_calc_limits(c);
1834 }
1835 
1836 /* Returns an error if scaling to a frame or single field with the given
1837    width and height is not possible with the current cropping parameters
1838    and width aligned according to width_mask. If adjust_size is TRUE the
1839    function may adjust the width and/or height instead, rounding width
1840    to (width + width_bias) & width_mask. If adjust_crop is TRUE it may
1841    also adjust the current cropping parameters to get closer to the
1842    desired image size. */
1843 static int
1844 limit_scaled_size_lock(struct bttv *btv, __s32 *width, __s32 *height,
1845 		       enum v4l2_field field, unsigned int width_mask,
1846 		       unsigned int width_bias, int adjust_size,
1847 		       int adjust_crop)
1848 {
1849 	const struct v4l2_rect *b;
1850 	struct bttv_crop *c;
1851 	__s32 min_width;
1852 	__s32 min_height;
1853 	__s32 max_width;
1854 	__s32 max_height;
1855 	int rc;
1856 
1857 	WARN_ON((int)width_mask >= 0 ||
1858 		width_bias >= (unsigned int)(-width_mask));
1859 
1860 	/* Make sure tvnorm, vbi_end and the current cropping parameters
1861 	   remain consistent until we're done. */
1862 
1863 	b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
1864 
1865 	/* Do crop - use current, don't - use default parameters. */
1866 	c = &btv->crop[!!btv->do_crop];
1867 
1868 	if (btv->do_crop
1869 	    && adjust_size
1870 	    && adjust_crop
1871 	    && !locked_btres(btv, VIDEO_RESOURCES)) {
1872 		min_width = 48;
1873 		min_height = 32;
1874 
1875 		/* We cannot scale up. When the scaled image is larger
1876 		   than crop.rect we adjust the crop.rect as required
1877 		   by the V4L2 spec, hence cropcap.bounds are our limit. */
1878 		max_width = min_t(unsigned int, b->width, MAX_HACTIVE);
1879 		max_height = b->height;
1880 
1881 		/* We cannot capture the same line as video and VBI data.
1882 		   Note btv->vbi_end is really a minimum, see
1883 		   bttv_vbi_try_fmt(). */
1884 		if (btv->vbi_end > b->top) {
1885 			max_height -= btv->vbi_end - b->top;
1886 			rc = -EBUSY;
1887 			if (min_height > max_height)
1888 				goto fail;
1889 		}
1890 	} else {
1891 		rc = -EBUSY;
1892 		if (btv->vbi_end > c->rect.top)
1893 			goto fail;
1894 
1895 		min_width  = c->min_scaled_width;
1896 		min_height = c->min_scaled_height;
1897 		max_width  = c->max_scaled_width;
1898 		max_height = c->max_scaled_height;
1899 
1900 		adjust_crop = 0;
1901 	}
1902 
1903 	min_width = (min_width - width_mask - 1) & width_mask;
1904 	max_width = max_width & width_mask;
1905 
1906 	/* Max. scale factor is 16:1 for frames, 8:1 for fields. */
1907 	/* Min. scale factor is 1:1. */
1908 	max_height >>= !V4L2_FIELD_HAS_BOTH(field);
1909 
1910 	if (adjust_size) {
1911 		*width = clamp(*width, min_width, max_width);
1912 		*height = clamp(*height, min_height, max_height);
1913 
1914 		/* Round after clamping to avoid overflow. */
1915 		*width = (*width + width_bias) & width_mask;
1916 
1917 		if (adjust_crop) {
1918 			bttv_crop_adjust(c, b, *width, *height, field);
1919 
1920 			if (btv->vbi_end > c->rect.top) {
1921 				/* Move the crop window out of the way. */
1922 				c->rect.top = btv->vbi_end;
1923 			}
1924 		}
1925 	} else {
1926 		rc = -EINVAL;
1927 		if (*width  < min_width ||
1928 		    *height < min_height ||
1929 		    *width  > max_width ||
1930 		    *height > max_height ||
1931 		    0 != (*width & ~width_mask))
1932 			goto fail;
1933 	}
1934 
1935 	rc = 0; /* success */
1936 
1937  fail:
1938 
1939 	return rc;
1940 }
1941 
1942 static int bttv_switch_type(struct bttv *btv, enum v4l2_buf_type type)
1943 {
1944 	int res;
1945 	struct vb2_queue *q;
1946 
1947 	switch (type) {
1948 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1949 		q = &btv->capq;
1950 		res = RESOURCE_VIDEO_STREAM;
1951 		break;
1952 	case V4L2_BUF_TYPE_VBI_CAPTURE:
1953 		q = &btv->vbiq;
1954 		res = RESOURCE_VBI;
1955 		break;
1956 	default:
1957 		WARN_ON(1);
1958 		return -EINVAL;
1959 	}
1960 
1961 	if (check_btres(btv, res))
1962 		return -EBUSY;
1963 	if (vb2_is_busy(q))
1964 		return -EBUSY;
1965 	btv->type = type;
1966 
1967 	return 0;
1968 }
1969 
1970 static void
1971 pix_format_set_size     (struct v4l2_pix_format *       f,
1972 			 const struct bttv_format *     fmt,
1973 			 unsigned int                   width,
1974 			 unsigned int                   height)
1975 {
1976 	f->width = width;
1977 	f->height = height;
1978 
1979 	if (fmt->flags & FORMAT_FLAGS_PLANAR) {
1980 		f->bytesperline = width; /* Y plane */
1981 		f->sizeimage = (width * height * fmt->depth) >> 3;
1982 	} else {
1983 		f->bytesperline = (width * fmt->depth) >> 3;
1984 		f->sizeimage = height * f->bytesperline;
1985 	}
1986 }
1987 
1988 static int bttv_g_fmt_vid_cap(struct file *file, void *priv,
1989 					struct v4l2_format *f)
1990 {
1991 	struct bttv *btv = video_drvdata(file);
1992 
1993 	pix_format_set_size(&f->fmt.pix, btv->fmt, btv->width, btv->height);
1994 	f->fmt.pix.field = btv->field;
1995 	f->fmt.pix.pixelformat  = btv->fmt->fourcc;
1996 	f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
1997 
1998 	return 0;
1999 }
2000 
2001 static void bttv_get_width_mask_vid_cap(const struct bttv_format *fmt,
2002 					unsigned int *width_mask,
2003 					unsigned int *width_bias)
2004 {
2005 	if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2006 		*width_mask = ~15; /* width must be a multiple of 16 pixels */
2007 		*width_bias = 8;   /* nearest */
2008 	} else {
2009 		*width_mask = ~3; /* width must be a multiple of 4 pixels */
2010 		*width_bias = 2;  /* nearest */
2011 	}
2012 }
2013 
2014 static int bttv_try_fmt_vid_cap(struct file *file, void *priv,
2015 						struct v4l2_format *f)
2016 {
2017 	const struct bttv_format *fmt;
2018 	struct bttv *btv = video_drvdata(file);
2019 	enum v4l2_field field;
2020 	__s32 width, height;
2021 	__s32 height2;
2022 	unsigned int width_mask, width_bias;
2023 	int rc;
2024 
2025 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2026 	if (NULL == fmt)
2027 		return -EINVAL;
2028 
2029 	field = f->fmt.pix.field;
2030 
2031 	switch (field) {
2032 	case V4L2_FIELD_TOP:
2033 	case V4L2_FIELD_BOTTOM:
2034 	case V4L2_FIELD_ALTERNATE:
2035 	case V4L2_FIELD_INTERLACED:
2036 		break;
2037 	case V4L2_FIELD_SEQ_BT:
2038 	case V4L2_FIELD_SEQ_TB:
2039 		if (!(fmt->flags & FORMAT_FLAGS_PLANAR)) {
2040 			field = V4L2_FIELD_SEQ_TB;
2041 			break;
2042 		}
2043 		fallthrough;
2044 	default: /* FIELD_ANY case */
2045 		height2 = btv->crop[!!btv->do_crop].rect.height >> 1;
2046 		field = (f->fmt.pix.height > height2)
2047 			? V4L2_FIELD_INTERLACED
2048 			: V4L2_FIELD_BOTTOM;
2049 		break;
2050 	}
2051 
2052 	width = f->fmt.pix.width;
2053 	height = f->fmt.pix.height;
2054 
2055 	bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2056 	rc = limit_scaled_size_lock(btv, &width, &height, field, width_mask,
2057 				    width_bias, 1, 0);
2058 	if (0 != rc)
2059 		return rc;
2060 
2061 	/* update data for the application */
2062 	f->fmt.pix.field = field;
2063 	pix_format_set_size(&f->fmt.pix, fmt, width, height);
2064 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
2065 
2066 	return 0;
2067 }
2068 
2069 static int bttv_s_fmt_vid_cap(struct file *file, void *priv,
2070 			      struct v4l2_format *f)
2071 {
2072 	int retval;
2073 	const struct bttv_format *fmt;
2074 	struct bttv *btv = video_drvdata(file);
2075 	__s32 width, height;
2076 	unsigned int width_mask, width_bias;
2077 	enum v4l2_field field;
2078 
2079 	retval = bttv_switch_type(btv, f->type);
2080 	if (0 != retval)
2081 		return retval;
2082 
2083 	retval = bttv_try_fmt_vid_cap(file, priv, f);
2084 	if (0 != retval)
2085 		return retval;
2086 
2087 	width = f->fmt.pix.width;
2088 	height = f->fmt.pix.height;
2089 	field = f->fmt.pix.field;
2090 
2091 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2092 	bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2093 	retval = limit_scaled_size_lock(btv, &width, &height, f->fmt.pix.field,
2094 					width_mask, width_bias, 1, 1);
2095 	if (0 != retval)
2096 		return retval;
2097 
2098 	f->fmt.pix.field = field;
2099 
2100 	/* update our state information */
2101 	btv->fmt = fmt;
2102 	btv->width = f->fmt.pix.width;
2103 	btv->height = f->fmt.pix.height;
2104 	btv->field = f->fmt.pix.field;
2105 	/*
2106 	 * When field is V4L2_FIELD_ALTERNATE, buffers will be either
2107 	 * V4L2_FIELD_TOP or V4L2_FIELD_BOTTOM depending on the value of
2108 	 * field_last. Initialize field_last to V4L2_FIELD_BOTTOM so that
2109 	 * streaming starts with a V4L2_FIELD_TOP buffer.
2110 	 */
2111 	btv->field_last = V4L2_FIELD_BOTTOM;
2112 
2113 	return 0;
2114 }
2115 
2116 static int bttv_querycap(struct file *file, void  *priv,
2117 				struct v4l2_capability *cap)
2118 {
2119 	struct bttv *btv = video_drvdata(file);
2120 
2121 	if (0 == v4l2)
2122 		return -EINVAL;
2123 
2124 	strscpy(cap->driver, "bttv", sizeof(cap->driver));
2125 	strscpy(cap->card, btv->video_dev.name, sizeof(cap->card));
2126 	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
2127 			    V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
2128 	if (video_is_registered(&btv->vbi_dev))
2129 		cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
2130 	if (video_is_registered(&btv->radio_dev)) {
2131 		cap->capabilities |= V4L2_CAP_RADIO;
2132 		if (btv->has_tea575x)
2133 			cap->capabilities |= V4L2_CAP_HW_FREQ_SEEK;
2134 	}
2135 
2136 	/*
2137 	 * No need to lock here: those vars are initialized during board
2138 	 * probe and remains untouched during the rest of the driver lifecycle
2139 	 */
2140 	if (btv->has_saa6588)
2141 		cap->capabilities |= V4L2_CAP_RDS_CAPTURE;
2142 	if (btv->tuner_type != TUNER_ABSENT)
2143 		cap->capabilities |= V4L2_CAP_TUNER;
2144 	return 0;
2145 }
2146 
2147 static int bttv_enum_fmt_vid_cap(struct file *file, void  *priv,
2148 				 struct v4l2_fmtdesc *f)
2149 {
2150 	int index = -1, i;
2151 
2152 	for (i = 0; i < FORMATS; i++) {
2153 		if (formats[i].fourcc != -1)
2154 			index++;
2155 		if ((unsigned int)index == f->index)
2156 			break;
2157 	}
2158 	if (FORMATS == i)
2159 		return -EINVAL;
2160 
2161 	f->pixelformat = formats[i].fourcc;
2162 
2163 	return 0;
2164 }
2165 
2166 static int bttv_g_parm(struct file *file, void *f,
2167 				struct v4l2_streamparm *parm)
2168 {
2169 	struct bttv *btv = video_drvdata(file);
2170 
2171 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2172 		return -EINVAL;
2173 	parm->parm.capture.readbuffers = gbuffers;
2174 	v4l2_video_std_frame_period(bttv_tvnorms[btv->tvnorm].v4l2_id,
2175 				    &parm->parm.capture.timeperframe);
2176 
2177 	return 0;
2178 }
2179 
2180 static int bttv_g_tuner(struct file *file, void *priv,
2181 				struct v4l2_tuner *t)
2182 {
2183 	struct bttv *btv = video_drvdata(file);
2184 
2185 	if (0 != t->index)
2186 		return -EINVAL;
2187 
2188 	t->rxsubchans = V4L2_TUNER_SUB_MONO;
2189 	t->capability = V4L2_TUNER_CAP_NORM;
2190 	bttv_call_all(btv, tuner, g_tuner, t);
2191 	strscpy(t->name, "Television", sizeof(t->name));
2192 	t->type       = V4L2_TUNER_ANALOG_TV;
2193 	if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
2194 		t->signal = 0xffff;
2195 
2196 	if (btv->audio_mode_gpio)
2197 		btv->audio_mode_gpio(btv, t, 0);
2198 
2199 	return 0;
2200 }
2201 
2202 static int bttv_g_pixelaspect(struct file *file, void *priv,
2203 			      int type, struct v4l2_fract *f)
2204 {
2205 	struct bttv *btv = video_drvdata(file);
2206 
2207 	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2208 		return -EINVAL;
2209 
2210 	/* defrect and bounds are set via g_selection */
2211 	*f = bttv_tvnorms[btv->tvnorm].cropcap.pixelaspect;
2212 	return 0;
2213 }
2214 
2215 static int bttv_g_selection(struct file *file, void *f, struct v4l2_selection *sel)
2216 {
2217 	struct bttv *btv = video_drvdata(file);
2218 
2219 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2220 		return -EINVAL;
2221 
2222 	switch (sel->target) {
2223 	case V4L2_SEL_TGT_CROP:
2224 		sel->r = btv->crop[!!btv->do_crop].rect;
2225 		break;
2226 	case V4L2_SEL_TGT_CROP_DEFAULT:
2227 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.defrect;
2228 		break;
2229 	case V4L2_SEL_TGT_CROP_BOUNDS:
2230 		sel->r = bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2231 		break;
2232 	default:
2233 		return -EINVAL;
2234 	}
2235 
2236 	return 0;
2237 }
2238 
2239 static int bttv_s_selection(struct file *file, void *f, struct v4l2_selection *sel)
2240 {
2241 	struct bttv *btv = video_drvdata(file);
2242 	const struct v4l2_rect *b;
2243 	int retval;
2244 	struct bttv_crop c;
2245 	__s32 b_left;
2246 	__s32 b_top;
2247 	__s32 b_right;
2248 	__s32 b_bottom;
2249 
2250 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2251 		return -EINVAL;
2252 
2253 	if (sel->target != V4L2_SEL_TGT_CROP)
2254 		return -EINVAL;
2255 
2256 	/* Make sure tvnorm, vbi_end and the current cropping
2257 	   parameters remain consistent until we're done. Note
2258 	   read() may change vbi_end in check_alloc_btres_lock(). */
2259 	retval = -EBUSY;
2260 
2261 	if (locked_btres(btv, VIDEO_RESOURCES))
2262 		return retval;
2263 
2264 	b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2265 
2266 	b_left = b->left;
2267 	b_right = b_left + b->width;
2268 	b_bottom = b->top + b->height;
2269 
2270 	b_top = max(b->top, btv->vbi_end);
2271 	if (b_top + 32 >= b_bottom) {
2272 		return retval;
2273 	}
2274 
2275 	/* Min. scaled size 48 x 32. */
2276 	c.rect.left = clamp_t(s32, sel->r.left, b_left, b_right - 48);
2277 	c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
2278 
2279 	c.rect.width = clamp_t(s32, sel->r.width,
2280 			     48, b_right - c.rect.left);
2281 
2282 	c.rect.top = clamp_t(s32, sel->r.top, b_top, b_bottom - 32);
2283 	/* Top and height must be a multiple of two. */
2284 	c.rect.top = (c.rect.top + 1) & ~1;
2285 
2286 	c.rect.height = clamp_t(s32, sel->r.height,
2287 			      32, b_bottom - c.rect.top);
2288 	c.rect.height = (c.rect.height + 1) & ~1;
2289 
2290 	bttv_crop_calc_limits(&c);
2291 
2292 	sel->r = c.rect;
2293 
2294 	btv->crop[1] = c;
2295 
2296 	btv->do_crop = 1;
2297 
2298 	if (btv->width < c.min_scaled_width)
2299 		btv->width = c.min_scaled_width;
2300 	else if (btv->width > c.max_scaled_width)
2301 		btv->width = c.max_scaled_width;
2302 
2303 	if (btv->height < c.min_scaled_height)
2304 		btv->height = c.min_scaled_height;
2305 	else if (btv->height > c.max_scaled_height)
2306 		btv->height = c.max_scaled_height;
2307 
2308 	return 0;
2309 }
2310 
2311 static const struct v4l2_file_operations bttv_fops =
2312 {
2313 	.owner		  = THIS_MODULE,
2314 	.open		  = v4l2_fh_open,
2315 	.release	  = vb2_fop_release,
2316 	.unlocked_ioctl	  = video_ioctl2,
2317 	.read		  = vb2_fop_read,
2318 	.mmap		  = vb2_fop_mmap,
2319 	.poll		  = vb2_fop_poll,
2320 };
2321 
2322 static const struct v4l2_ioctl_ops bttv_ioctl_ops = {
2323 	.vidioc_querycap                = bttv_querycap,
2324 	.vidioc_enum_fmt_vid_cap        = bttv_enum_fmt_vid_cap,
2325 	.vidioc_g_fmt_vid_cap           = bttv_g_fmt_vid_cap,
2326 	.vidioc_try_fmt_vid_cap         = bttv_try_fmt_vid_cap,
2327 	.vidioc_s_fmt_vid_cap           = bttv_s_fmt_vid_cap,
2328 	.vidioc_g_fmt_vbi_cap           = bttv_g_fmt_vbi_cap,
2329 	.vidioc_try_fmt_vbi_cap         = bttv_try_fmt_vbi_cap,
2330 	.vidioc_s_fmt_vbi_cap           = bttv_s_fmt_vbi_cap,
2331 	.vidioc_g_pixelaspect           = bttv_g_pixelaspect,
2332 	.vidioc_reqbufs                 = vb2_ioctl_reqbufs,
2333 	.vidioc_create_bufs             = vb2_ioctl_create_bufs,
2334 	.vidioc_querybuf                = vb2_ioctl_querybuf,
2335 	.vidioc_qbuf                    = vb2_ioctl_qbuf,
2336 	.vidioc_dqbuf                   = vb2_ioctl_dqbuf,
2337 	.vidioc_streamon                = vb2_ioctl_streamon,
2338 	.vidioc_streamoff               = vb2_ioctl_streamoff,
2339 	.vidioc_s_std                   = bttv_s_std,
2340 	.vidioc_g_std                   = bttv_g_std,
2341 	.vidioc_enum_input              = bttv_enum_input,
2342 	.vidioc_g_input                 = bttv_g_input,
2343 	.vidioc_s_input                 = bttv_s_input,
2344 	.vidioc_g_tuner                 = bttv_g_tuner,
2345 	.vidioc_s_tuner                 = bttv_s_tuner,
2346 	.vidioc_g_selection             = bttv_g_selection,
2347 	.vidioc_s_selection             = bttv_s_selection,
2348 	.vidioc_g_parm                  = bttv_g_parm,
2349 	.vidioc_g_frequency             = bttv_g_frequency,
2350 	.vidioc_s_frequency             = bttv_s_frequency,
2351 	.vidioc_log_status		= bttv_log_status,
2352 	.vidioc_querystd		= bttv_querystd,
2353 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
2354 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
2355 #ifdef CONFIG_VIDEO_ADV_DEBUG
2356 	.vidioc_g_register		= bttv_g_register,
2357 	.vidioc_s_register		= bttv_s_register,
2358 #endif
2359 };
2360 
2361 static struct video_device bttv_video_template = {
2362 	.fops         = &bttv_fops,
2363 	.ioctl_ops    = &bttv_ioctl_ops,
2364 	.tvnorms      = BTTV_NORMS,
2365 };
2366 
2367 /* ----------------------------------------------------------------------- */
2368 /* radio interface                                                         */
2369 
2370 static int radio_open(struct file *file)
2371 {
2372 	struct video_device *vdev = video_devdata(file);
2373 	struct bttv *btv = video_drvdata(file);
2374 	int ret = v4l2_fh_open(file);
2375 
2376 	if (ret)
2377 		return ret;
2378 
2379 	dprintk("open dev=%s\n", video_device_node_name(vdev));
2380 	dprintk("%d: open called (radio)\n", btv->c.nr);
2381 
2382 	btv->radio_user++;
2383 	audio_mute(btv, btv->mute);
2384 
2385 	return 0;
2386 }
2387 
2388 static int radio_release(struct file *file)
2389 {
2390 	struct bttv *btv = video_drvdata(file);
2391 	struct saa6588_command cmd;
2392 
2393 	btv->radio_user--;
2394 
2395 	bttv_call_all(btv, core, command, SAA6588_CMD_CLOSE, &cmd);
2396 
2397 	if (btv->radio_user == 0)
2398 		btv->has_radio_tuner = 0;
2399 
2400 	v4l2_fh_release(file);
2401 
2402 	return 0;
2403 }
2404 
2405 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
2406 {
2407 	struct bttv *btv = video_drvdata(file);
2408 
2409 	if (0 != t->index)
2410 		return -EINVAL;
2411 	strscpy(t->name, "Radio", sizeof(t->name));
2412 	t->type = V4L2_TUNER_RADIO;
2413 	radio_enable(btv);
2414 
2415 	bttv_call_all(btv, tuner, g_tuner, t);
2416 
2417 	if (btv->audio_mode_gpio)
2418 		btv->audio_mode_gpio(btv, t, 0);
2419 
2420 	if (btv->has_tea575x)
2421 		return snd_tea575x_g_tuner(&btv->tea, t);
2422 
2423 	return 0;
2424 }
2425 
2426 static int radio_s_tuner(struct file *file, void *priv,
2427 					const struct v4l2_tuner *t)
2428 {
2429 	struct bttv *btv = video_drvdata(file);
2430 
2431 	if (0 != t->index)
2432 		return -EINVAL;
2433 
2434 	radio_enable(btv);
2435 	bttv_call_all(btv, tuner, s_tuner, t);
2436 	return 0;
2437 }
2438 
2439 static int radio_s_hw_freq_seek(struct file *file, void *priv,
2440 					const struct v4l2_hw_freq_seek *a)
2441 {
2442 	struct bttv *btv = video_drvdata(file);
2443 
2444 	if (btv->has_tea575x)
2445 		return snd_tea575x_s_hw_freq_seek(file, &btv->tea, a);
2446 
2447 	return -ENOTTY;
2448 }
2449 
2450 static int radio_enum_freq_bands(struct file *file, void *priv,
2451 					 struct v4l2_frequency_band *band)
2452 {
2453 	struct bttv *btv = video_drvdata(file);
2454 
2455 	if (btv->has_tea575x)
2456 		return snd_tea575x_enum_freq_bands(&btv->tea, band);
2457 
2458 	return -ENOTTY;
2459 }
2460 
2461 static ssize_t radio_read(struct file *file, char __user *data,
2462 			 size_t count, loff_t *ppos)
2463 {
2464 	struct bttv *btv = video_drvdata(file);
2465 	struct saa6588_command cmd;
2466 
2467 	cmd.block_count = count / 3;
2468 	cmd.nonblocking = file->f_flags & O_NONBLOCK;
2469 	cmd.buffer = data;
2470 	cmd.instance = file;
2471 	cmd.result = -ENODEV;
2472 	radio_enable(btv);
2473 
2474 	bttv_call_all(btv, core, command, SAA6588_CMD_READ, &cmd);
2475 
2476 	return cmd.result;
2477 }
2478 
2479 static __poll_t radio_poll(struct file *file, poll_table *wait)
2480 {
2481 	struct bttv *btv = video_drvdata(file);
2482 	struct saa6588_command cmd;
2483 	__poll_t rc = v4l2_ctrl_poll(file, wait);
2484 
2485 	radio_enable(btv);
2486 	cmd.instance = file;
2487 	cmd.event_list = wait;
2488 	cmd.poll_mask = 0;
2489 	bttv_call_all(btv, core, command, SAA6588_CMD_POLL, &cmd);
2490 
2491 	return rc | cmd.poll_mask;
2492 }
2493 
2494 static const struct v4l2_file_operations radio_fops =
2495 {
2496 	.owner	  = THIS_MODULE,
2497 	.open	  = radio_open,
2498 	.read     = radio_read,
2499 	.release  = radio_release,
2500 	.unlocked_ioctl = video_ioctl2,
2501 	.poll     = radio_poll,
2502 };
2503 
2504 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2505 	.vidioc_querycap        = bttv_querycap,
2506 	.vidioc_log_status	= bttv_log_status,
2507 	.vidioc_g_tuner         = radio_g_tuner,
2508 	.vidioc_s_tuner         = radio_s_tuner,
2509 	.vidioc_g_frequency     = bttv_g_frequency,
2510 	.vidioc_s_frequency     = bttv_s_frequency,
2511 	.vidioc_s_hw_freq_seek	= radio_s_hw_freq_seek,
2512 	.vidioc_enum_freq_bands	= radio_enum_freq_bands,
2513 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2514 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2515 };
2516 
2517 static struct video_device radio_template = {
2518 	.fops      = &radio_fops,
2519 	.ioctl_ops = &radio_ioctl_ops,
2520 };
2521 
2522 /* ----------------------------------------------------------------------- */
2523 /* some debug code                                                         */
2524 
2525 static int bttv_risc_decode(u32 risc)
2526 {
2527 	static char *instr[16] = {
2528 		[ BT848_RISC_WRITE     >> 28 ] = "write",
2529 		[ BT848_RISC_SKIP      >> 28 ] = "skip",
2530 		[ BT848_RISC_WRITEC    >> 28 ] = "writec",
2531 		[ BT848_RISC_JUMP      >> 28 ] = "jump",
2532 		[ BT848_RISC_SYNC      >> 28 ] = "sync",
2533 		[ BT848_RISC_WRITE123  >> 28 ] = "write123",
2534 		[ BT848_RISC_SKIP123   >> 28 ] = "skip123",
2535 		[ BT848_RISC_WRITE1S23 >> 28 ] = "write1s23",
2536 	};
2537 	static int incr[16] = {
2538 		[ BT848_RISC_WRITE     >> 28 ] = 2,
2539 		[ BT848_RISC_JUMP      >> 28 ] = 2,
2540 		[ BT848_RISC_SYNC      >> 28 ] = 2,
2541 		[ BT848_RISC_WRITE123  >> 28 ] = 5,
2542 		[ BT848_RISC_SKIP123   >> 28 ] = 2,
2543 		[ BT848_RISC_WRITE1S23 >> 28 ] = 3,
2544 	};
2545 	static char *bits[] = {
2546 		"be0",  "be1",  "be2",  "be3/resync",
2547 		"set0", "set1", "set2", "set3",
2548 		"clr0", "clr1", "clr2", "clr3",
2549 		"irq",  "res",  "eol",  "sol",
2550 	};
2551 	int i;
2552 
2553 	pr_cont("0x%08x [ %s", risc,
2554 	       instr[risc >> 28] ? instr[risc >> 28] : "INVALID");
2555 	for (i = ARRAY_SIZE(bits)-1; i >= 0; i--)
2556 		if (risc & (1 << (i + 12)))
2557 			pr_cont(" %s", bits[i]);
2558 	pr_cont(" count=%d ]\n", risc & 0xfff);
2559 	return incr[risc >> 28] ? incr[risc >> 28] : 1;
2560 }
2561 
2562 static void bttv_risc_disasm(struct bttv *btv,
2563 			     struct btcx_riscmem *risc)
2564 {
2565 	unsigned int i,j,n;
2566 
2567 	pr_info("%s: risc disasm: %p [dma=0x%08lx]\n",
2568 		btv->c.v4l2_dev.name, risc->cpu, (unsigned long)risc->dma);
2569 	for (i = 0; i < (risc->size >> 2); i += n) {
2570 		pr_info("%s:   0x%lx: ",
2571 			btv->c.v4l2_dev.name,
2572 			(unsigned long)(risc->dma + (i<<2)));
2573 		n = bttv_risc_decode(le32_to_cpu(risc->cpu[i]));
2574 		for (j = 1; j < n; j++)
2575 			pr_info("%s:   0x%lx: 0x%08x [ arg #%d ]\n",
2576 				btv->c.v4l2_dev.name,
2577 				(unsigned long)(risc->dma + ((i+j)<<2)),
2578 				risc->cpu[i+j], j);
2579 		if (0 == risc->cpu[i])
2580 			break;
2581 	}
2582 }
2583 
2584 static void bttv_print_riscaddr(struct bttv *btv)
2585 {
2586 	pr_info("  main: %08llx\n", (unsigned long long)btv->main.dma);
2587 	pr_info("  vbi : o=%08llx e=%08llx\n",
2588 		btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
2589 		btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
2590 	pr_info("  cap : o=%08llx e=%08llx\n",
2591 		btv->curr.top
2592 		? (unsigned long long)btv->curr.top->top.dma : 0,
2593 		btv->curr.bottom
2594 		? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
2595 	bttv_risc_disasm(btv, &btv->main);
2596 }
2597 
2598 /* ----------------------------------------------------------------------- */
2599 /* irq handler                                                             */
2600 
2601 static char *irq_name[] = {
2602 	"FMTCHG",  // format change detected (525 vs. 625)
2603 	"VSYNC",   // vertical sync (new field)
2604 	"HSYNC",   // horizontal sync
2605 	"OFLOW",   // chroma/luma AGC overflow
2606 	"HLOCK",   // horizontal lock changed
2607 	"VPRES",   // video presence changed
2608 	"6", "7",
2609 	"I2CDONE", // hw irc operation finished
2610 	"GPINT",   // gpio port triggered irq
2611 	"10",
2612 	"RISCI",   // risc instruction triggered irq
2613 	"FBUS",    // pixel data fifo dropped data (high pci bus latencies)
2614 	"FTRGT",   // pixel data fifo overrun
2615 	"FDSR",    // fifo data stream resyncronisation
2616 	"PPERR",   // parity error (data transfer)
2617 	"RIPERR",  // parity error (read risc instructions)
2618 	"PABORT",  // pci abort
2619 	"OCERR",   // risc instruction error
2620 	"SCERR",   // syncronisation error
2621 };
2622 
2623 static void bttv_print_irqbits(u32 print, u32 mark)
2624 {
2625 	unsigned int i;
2626 
2627 	pr_cont("bits:");
2628 	for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
2629 		if (print & (1 << i))
2630 			pr_cont(" %s", irq_name[i]);
2631 		if (mark & (1 << i))
2632 			pr_cont("*");
2633 	}
2634 }
2635 
2636 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
2637 {
2638 	pr_warn("%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
2639 		btv->c.nr,
2640 		(unsigned long)btv->main.dma,
2641 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_VBI+1]),
2642 		(unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_FIELD+1]),
2643 		(unsigned long)rc);
2644 
2645 	if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
2646 		pr_notice("%d: Oh, there (temporarily?) is no input signal. Ok, then this is harmless, don't worry ;)\n",
2647 			  btv->c.nr);
2648 		return;
2649 	}
2650 	pr_notice("%d: Uhm. Looks like we have unusual high IRQ latencies\n",
2651 		  btv->c.nr);
2652 	pr_notice("%d: Lets try to catch the culprit red-handed ...\n",
2653 		  btv->c.nr);
2654 	dump_stack();
2655 }
2656 
2657 static int
2658 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
2659 {
2660 	struct bttv_buffer *item;
2661 
2662 	memset(set,0,sizeof(*set));
2663 
2664 	/* capture request ? */
2665 	if (!list_empty(&btv->capture)) {
2666 		set->frame_irq = BT848_RISC_VIDEO;
2667 		item = list_entry(btv->capture.next, struct bttv_buffer, list);
2668 
2669 		if (V4L2_FIELD_HAS_TOP(item->vbuf.field))
2670 			set->top    = item;
2671 		if (V4L2_FIELD_HAS_BOTTOM(item->vbuf.field))
2672 			set->bottom = item;
2673 
2674 		/* capture request for other field ? */
2675 		if (!V4L2_FIELD_HAS_BOTH(item->vbuf.field) &&
2676 		    item->list.next != &btv->capture) {
2677 			item = list_entry(item->list.next,
2678 					  struct bttv_buffer, list);
2679 			/* Mike Isely <isely@pobox.com> - Only check
2680 			 * and set up the bottom field in the logic
2681 			 * below.  Don't ever do the top field.  This
2682 			 * of course means that if we set up the
2683 			 * bottom field in the above code that we'll
2684 			 * actually skip a field.  But that's OK.
2685 			 * Having processed only a single buffer this
2686 			 * time, then the next time around the first
2687 			 * available buffer should be for a top field.
2688 			 * That will then cause us here to set up a
2689 			 * top then a bottom field in the normal way.
2690 			 * The alternative to this understanding is
2691 			 * that we set up the second available buffer
2692 			 * as a top field, but that's out of order
2693 			 * since this driver always processes the top
2694 			 * field first - the effect will be the two
2695 			 * buffers being returned in the wrong order,
2696 			 * with the second buffer also being delayed
2697 			 * by one field time (owing to the fifo nature
2698 			 * of videobuf).  Worse still, we'll be stuck
2699 			 * doing fields out of order now every time
2700 			 * until something else causes a field to be
2701 			 * dropped.  By effectively forcing a field to
2702 			 * drop this way then we always get back into
2703 			 * sync within a single frame time.  (Out of
2704 			 * order fields can screw up deinterlacing
2705 			 * algorithms.) */
2706 			if (!V4L2_FIELD_HAS_BOTH(item->vbuf.field)) {
2707 				if (!set->bottom &&
2708 				    item->vbuf.field == V4L2_FIELD_BOTTOM)
2709 					set->bottom = item;
2710 				if (set->top && set->bottom) {
2711 					/*
2712 					 * The buffer set has a top buffer and
2713 					 * a bottom buffer and they are not
2714 					 * copies of each other.
2715 					 */
2716 					set->top_irq = BT848_RISC_TOP;
2717 				}
2718 			}
2719 		}
2720 	}
2721 
2722 	dprintk("%d: next set: top=%p bottom=%p [irq=%d,%d]\n",
2723 		btv->c.nr, set->top, set->bottom,
2724 		set->frame_irq, set->top_irq);
2725 	return 0;
2726 }
2727 
2728 static void
2729 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
2730 		      struct bttv_buffer_set *curr, unsigned int state)
2731 {
2732 	u64 ts = ktime_get_ns();
2733 
2734 	if (wakeup->top == wakeup->bottom) {
2735 		if (NULL != wakeup->top && curr->top != wakeup->top) {
2736 			if (irq_debug > 1)
2737 				pr_debug("%d: wakeup: both=%p\n",
2738 					 btv->c.nr, wakeup->top);
2739 			wakeup->top->vbuf.vb2_buf.timestamp = ts;
2740 			wakeup->top->vbuf.sequence = btv->field_count >> 1;
2741 			vb2_buffer_done(&wakeup->top->vbuf.vb2_buf, state);
2742 			if (btv->field_count == 0)
2743 				btor(BT848_INT_VSYNC, BT848_INT_MASK);
2744 		}
2745 	} else {
2746 		if (NULL != wakeup->top && curr->top != wakeup->top) {
2747 			if (irq_debug > 1)
2748 				pr_debug("%d: wakeup: top=%p\n",
2749 					 btv->c.nr, wakeup->top);
2750 			wakeup->top->vbuf.vb2_buf.timestamp = ts;
2751 			wakeup->top->vbuf.sequence = btv->field_count >> 1;
2752 			vb2_buffer_done(&wakeup->top->vbuf.vb2_buf, state);
2753 			if (btv->field_count == 0)
2754 				btor(BT848_INT_VSYNC, BT848_INT_MASK);
2755 		}
2756 		if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
2757 			if (irq_debug > 1)
2758 				pr_debug("%d: wakeup: bottom=%p\n",
2759 					 btv->c.nr, wakeup->bottom);
2760 			wakeup->bottom->vbuf.vb2_buf.timestamp = ts;
2761 			wakeup->bottom->vbuf.sequence = btv->field_count >> 1;
2762 			vb2_buffer_done(&wakeup->bottom->vbuf.vb2_buf, state);
2763 			if (btv->field_count == 0)
2764 				btor(BT848_INT_VSYNC, BT848_INT_MASK);
2765 		}
2766 	}
2767 }
2768 
2769 static void
2770 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
2771 				unsigned int state)
2772 {
2773 	if (NULL == wakeup)
2774 		return;
2775 	wakeup->vbuf.vb2_buf.timestamp = ktime_get_ns();
2776 	wakeup->vbuf.sequence = btv->field_count >> 1;
2777 	vb2_buffer_done(&wakeup->vbuf.vb2_buf, state);
2778 	if (btv->field_count == 0)
2779 		btor(BT848_INT_VSYNC, BT848_INT_MASK);
2780 }
2781 
2782 static void bttv_irq_timeout(struct timer_list *t)
2783 {
2784 	struct bttv *btv = from_timer(btv, t, timeout);
2785 	struct bttv_buffer_set old,new;
2786 	struct bttv_buffer *ovbi;
2787 	struct bttv_buffer *item;
2788 	unsigned long flags;
2789 	int seqnr = 0;
2790 
2791 	if (bttv_verbose) {
2792 		pr_info("%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
2793 			btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
2794 			btread(BT848_RISC_COUNT));
2795 		bttv_print_irqbits(btread(BT848_INT_STAT),0);
2796 		pr_cont("\n");
2797 	}
2798 
2799 	spin_lock_irqsave(&btv->s_lock,flags);
2800 
2801 	/* deactivate stuff */
2802 	memset(&new,0,sizeof(new));
2803 	old  = btv->curr;
2804 	ovbi = btv->cvbi;
2805 	btv->curr = new;
2806 	btv->cvbi = NULL;
2807 	btv->loop_irq = 0;
2808 	bttv_buffer_activate_video(btv, &new);
2809 	bttv_buffer_activate_vbi(btv,   NULL);
2810 	bttv_set_dma(btv, 0);
2811 
2812 	/* wake up */
2813 	bttv_irq_wakeup_video(btv, &old, &new, VB2_BUF_STATE_DONE);
2814 	bttv_irq_wakeup_vbi(btv, ovbi, VB2_BUF_STATE_DONE);
2815 
2816 	/* cancel all outstanding capture / vbi requests */
2817 	if (btv->field_count)
2818 		seqnr++;
2819 	while (!list_empty(&btv->capture)) {
2820 		item = list_entry(btv->capture.next, struct bttv_buffer, list);
2821 		list_del(&item->list);
2822 		item->vbuf.vb2_buf.timestamp = ktime_get_ns();
2823 		item->vbuf.sequence = (btv->field_count >> 1) + seqnr++;
2824 		vb2_buffer_done(&item->vbuf.vb2_buf, VB2_BUF_STATE_ERROR);
2825 	}
2826 	while (!list_empty(&btv->vcapture)) {
2827 		item = list_entry(btv->vcapture.next, struct bttv_buffer, list);
2828 		list_del(&item->list);
2829 		item->vbuf.vb2_buf.timestamp = ktime_get_ns();
2830 		item->vbuf.sequence = (btv->field_count >> 1) + seqnr++;
2831 		vb2_buffer_done(&item->vbuf.vb2_buf, VB2_BUF_STATE_ERROR);
2832 	}
2833 
2834 	btv->errors++;
2835 	spin_unlock_irqrestore(&btv->s_lock,flags);
2836 }
2837 
2838 static void
2839 bttv_irq_wakeup_top(struct bttv *btv)
2840 {
2841 	struct bttv_buffer *wakeup = btv->curr.top;
2842 
2843 	if (NULL == wakeup)
2844 		return;
2845 
2846 	spin_lock(&btv->s_lock);
2847 	btv->curr.top_irq = 0;
2848 	btv->curr.top = NULL;
2849 	bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
2850 	wakeup->vbuf.vb2_buf.timestamp = ktime_get_ns();
2851 	wakeup->vbuf.sequence = btv->field_count >> 1;
2852 	vb2_buffer_done(&wakeup->vbuf.vb2_buf, VB2_BUF_STATE_DONE);
2853 	if (btv->field_count == 0)
2854 		btor(BT848_INT_VSYNC, BT848_INT_MASK);
2855 	spin_unlock(&btv->s_lock);
2856 }
2857 
2858 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
2859 {
2860 	if (rc < risc->dma)
2861 		return 0;
2862 	if (rc > risc->dma + risc->size)
2863 		return 0;
2864 	return 1;
2865 }
2866 
2867 static void
2868 bttv_irq_switch_video(struct bttv *btv)
2869 {
2870 	struct bttv_buffer_set new;
2871 	struct bttv_buffer_set old;
2872 	dma_addr_t rc;
2873 
2874 	spin_lock(&btv->s_lock);
2875 
2876 	/* new buffer set */
2877 	bttv_irq_next_video(btv, &new);
2878 	rc = btread(BT848_RISC_COUNT);
2879 	if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
2880 	    (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
2881 		btv->framedrop++;
2882 		if (debug_latency)
2883 			bttv_irq_debug_low_latency(btv, rc);
2884 		spin_unlock(&btv->s_lock);
2885 		return;
2886 	}
2887 
2888 	/* switch over */
2889 	old = btv->curr;
2890 	btv->curr = new;
2891 	btv->loop_irq &= ~BT848_RISC_VIDEO;
2892 	bttv_buffer_activate_video(btv, &new);
2893 	bttv_set_dma(btv, 0);
2894 
2895 	/* switch input */
2896 	if (UNSET != btv->new_input) {
2897 		video_mux(btv,btv->new_input);
2898 		btv->new_input = UNSET;
2899 	}
2900 
2901 	/* wake up finished buffers */
2902 	bttv_irq_wakeup_video(btv, &old, &new, VB2_BUF_STATE_DONE);
2903 	spin_unlock(&btv->s_lock);
2904 }
2905 
2906 static void
2907 bttv_irq_switch_vbi(struct bttv *btv)
2908 {
2909 	struct bttv_buffer *new = NULL;
2910 	struct bttv_buffer *old;
2911 	u32 rc;
2912 
2913 	spin_lock(&btv->s_lock);
2914 
2915 	if (!list_empty(&btv->vcapture))
2916 		new = list_entry(btv->vcapture.next, struct bttv_buffer, list);
2917 	old = btv->cvbi;
2918 
2919 	rc = btread(BT848_RISC_COUNT);
2920 	if (NULL != old && (is_active(&old->top,    rc) ||
2921 			    is_active(&old->bottom, rc))) {
2922 		btv->framedrop++;
2923 		if (debug_latency)
2924 			bttv_irq_debug_low_latency(btv, rc);
2925 		spin_unlock(&btv->s_lock);
2926 		return;
2927 	}
2928 
2929 	/* switch */
2930 	btv->cvbi = new;
2931 	btv->loop_irq &= ~BT848_RISC_VBI;
2932 	bttv_buffer_activate_vbi(btv, new);
2933 	bttv_set_dma(btv, 0);
2934 
2935 	bttv_irq_wakeup_vbi(btv, old, VB2_BUF_STATE_DONE);
2936 	spin_unlock(&btv->s_lock);
2937 }
2938 
2939 static irqreturn_t bttv_irq(int irq, void *dev_id)
2940 {
2941 	u32 stat,astat;
2942 	u32 dstat;
2943 	int count;
2944 	struct bttv *btv;
2945 	int handled = 0;
2946 
2947 	btv=(struct bttv *)dev_id;
2948 
2949 	count=0;
2950 	while (1) {
2951 		/* get/clear interrupt status bits */
2952 		stat=btread(BT848_INT_STAT);
2953 		astat=stat&btread(BT848_INT_MASK);
2954 		if (!astat)
2955 			break;
2956 		handled = 1;
2957 		btwrite(stat,BT848_INT_STAT);
2958 
2959 		/* get device status bits */
2960 		dstat=btread(BT848_DSTATUS);
2961 
2962 		if (irq_debug) {
2963 			pr_debug("%d: irq loop=%d fc=%d riscs=%x, riscc=%08x, ",
2964 				 btv->c.nr, count, btv->field_count,
2965 				 stat>>28, btread(BT848_RISC_COUNT));
2966 			bttv_print_irqbits(stat,astat);
2967 			if (stat & BT848_INT_HLOCK)
2968 				pr_cont("   HLOC => %s",
2969 					dstat & BT848_DSTATUS_HLOC
2970 					? "yes" : "no");
2971 			if (stat & BT848_INT_VPRES)
2972 				pr_cont("   PRES => %s",
2973 					dstat & BT848_DSTATUS_PRES
2974 					? "yes" : "no");
2975 			if (stat & BT848_INT_FMTCHG)
2976 				pr_cont("   NUML => %s",
2977 					dstat & BT848_DSTATUS_NUML
2978 					? "625" : "525");
2979 			pr_cont("\n");
2980 		}
2981 
2982 		if (astat&BT848_INT_VSYNC)
2983 			btv->field_count++;
2984 
2985 		if ((astat & BT848_INT_GPINT) && btv->remote) {
2986 			bttv_input_irq(btv);
2987 		}
2988 
2989 		if (astat & BT848_INT_I2CDONE) {
2990 			btv->i2c_done = stat;
2991 			wake_up(&btv->i2c_queue);
2992 		}
2993 
2994 		if ((astat & BT848_INT_RISCI) && (stat & BT848_INT_RISCS_VBI))
2995 			bttv_irq_switch_vbi(btv);
2996 
2997 		if ((astat & BT848_INT_RISCI) && (stat & BT848_INT_RISCS_TOP))
2998 			bttv_irq_wakeup_top(btv);
2999 
3000 		if ((astat & BT848_INT_RISCI) && (stat & BT848_INT_RISCS_VIDEO))
3001 			bttv_irq_switch_video(btv);
3002 
3003 		if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3004 			/* trigger automute */
3005 			audio_mux_gpio(btv, btv->audio_input, btv->mute);
3006 
3007 		if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3008 			pr_info("%d: %s%s @ %08x,",
3009 				btv->c.nr,
3010 				(astat & BT848_INT_SCERR) ? "SCERR" : "",
3011 				(astat & BT848_INT_OCERR) ? "OCERR" : "",
3012 				btread(BT848_RISC_COUNT));
3013 			bttv_print_irqbits(stat,astat);
3014 			pr_cont("\n");
3015 			if (bttv_debug)
3016 				bttv_print_riscaddr(btv);
3017 		}
3018 		if (fdsr && astat & BT848_INT_FDSR) {
3019 			pr_info("%d: FDSR @ %08x\n",
3020 				btv->c.nr, btread(BT848_RISC_COUNT));
3021 			if (bttv_debug)
3022 				bttv_print_riscaddr(btv);
3023 		}
3024 
3025 		count++;
3026 		if (count > 4) {
3027 
3028 			if (count > 8 || !(astat & BT848_INT_GPINT)) {
3029 				btwrite(0, BT848_INT_MASK);
3030 
3031 				pr_err("%d: IRQ lockup, cleared int mask [",
3032 				       btv->c.nr);
3033 			} else {
3034 				pr_err("%d: IRQ lockup, clearing GPINT from int mask [",
3035 				       btv->c.nr);
3036 
3037 				btwrite(btread(BT848_INT_MASK) & (-1 ^ BT848_INT_GPINT),
3038 						BT848_INT_MASK);
3039 			}
3040 
3041 			bttv_print_irqbits(stat,astat);
3042 
3043 			pr_cont("]\n");
3044 		}
3045 	}
3046 	btv->irq_total++;
3047 	if (handled)
3048 		btv->irq_me++;
3049 	return IRQ_RETVAL(handled);
3050 }
3051 
3052 
3053 /* ----------------------------------------------------------------------- */
3054 /* initialization                                                          */
3055 
3056 static int vdev_init(struct bttv *btv, struct video_device *vfd,
3057 		     const struct video_device *template,
3058 		     const char *type_name)
3059 {
3060 	int err;
3061 	struct vb2_queue *q;
3062 	*vfd = *template;
3063 	vfd->v4l2_dev = &btv->c.v4l2_dev;
3064 	vfd->release = video_device_release_empty;
3065 	video_set_drvdata(vfd, btv);
3066 	snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3067 		 btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3068 		 type_name, bttv_tvcards[btv->c.type].name);
3069 	if (btv->tuner_type == TUNER_ABSENT) {
3070 		v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
3071 		v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
3072 		v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
3073 		v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
3074 	}
3075 
3076 	if (strcmp(type_name, "radio") == 0)
3077 		return 0;
3078 
3079 	if (strcmp(type_name, "video") == 0) {
3080 		q = &btv->capq;
3081 		q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3082 		q->ops = &bttv_video_qops;
3083 	} else if (strcmp(type_name, "vbi") == 0) {
3084 		q = &btv->vbiq;
3085 		q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
3086 		q->ops = &bttv_vbi_qops;
3087 	} else {
3088 		return -EINVAL;
3089 	}
3090 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
3091 	q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ | VB2_DMABUF;
3092 	q->mem_ops = &vb2_dma_sg_memops;
3093 	q->drv_priv = btv;
3094 	q->gfp_flags = __GFP_DMA32;
3095 	q->buf_struct_size = sizeof(struct bttv_buffer);
3096 	q->lock = &btv->lock;
3097 	q->min_buffers_needed = 2;
3098 	q->dev = &btv->c.pci->dev;
3099 	err = vb2_queue_init(q);
3100 	if (err)
3101 		return err;
3102 	vfd->queue = q;
3103 
3104 	return 0;
3105 }
3106 
3107 static void bttv_unregister_video(struct bttv *btv)
3108 {
3109 	video_unregister_device(&btv->video_dev);
3110 	video_unregister_device(&btv->vbi_dev);
3111 	video_unregister_device(&btv->radio_dev);
3112 }
3113 
3114 /* register video4linux devices */
3115 static int bttv_register_video(struct bttv *btv)
3116 {
3117 	/* video */
3118 	vdev_init(btv, &btv->video_dev, &bttv_video_template, "video");
3119 	btv->video_dev.device_caps = V4L2_CAP_VIDEO_CAPTURE |
3120 				     V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
3121 	if (btv->tuner_type != TUNER_ABSENT)
3122 		btv->video_dev.device_caps |= V4L2_CAP_TUNER;
3123 
3124 	if (video_register_device(&btv->video_dev, VFL_TYPE_VIDEO,
3125 				  video_nr[btv->c.nr]) < 0)
3126 		goto err;
3127 	pr_info("%d: registered device %s\n",
3128 		btv->c.nr, video_device_node_name(&btv->video_dev));
3129 	if (device_create_file(&btv->video_dev.dev,
3130 				     &dev_attr_card)<0) {
3131 		pr_err("%d: device_create_file 'card' failed\n", btv->c.nr);
3132 		goto err;
3133 	}
3134 
3135 	/* vbi */
3136 	vdev_init(btv, &btv->vbi_dev, &bttv_video_template, "vbi");
3137 	btv->vbi_dev.device_caps = V4L2_CAP_VBI_CAPTURE | V4L2_CAP_READWRITE |
3138 				   V4L2_CAP_STREAMING;
3139 	if (btv->tuner_type != TUNER_ABSENT)
3140 		btv->vbi_dev.device_caps |= V4L2_CAP_TUNER;
3141 
3142 	if (video_register_device(&btv->vbi_dev, VFL_TYPE_VBI,
3143 				  vbi_nr[btv->c.nr]) < 0)
3144 		goto err;
3145 	pr_info("%d: registered device %s\n",
3146 		btv->c.nr, video_device_node_name(&btv->vbi_dev));
3147 
3148 	if (!btv->has_radio)
3149 		return 0;
3150 	/* radio */
3151 	vdev_init(btv, &btv->radio_dev, &radio_template, "radio");
3152 	btv->radio_dev.device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
3153 	if (btv->has_saa6588)
3154 		btv->radio_dev.device_caps |= V4L2_CAP_READWRITE |
3155 					      V4L2_CAP_RDS_CAPTURE;
3156 	if (btv->has_tea575x)
3157 		btv->radio_dev.device_caps |= V4L2_CAP_HW_FREQ_SEEK;
3158 	btv->radio_dev.ctrl_handler = &btv->radio_ctrl_handler;
3159 	if (video_register_device(&btv->radio_dev, VFL_TYPE_RADIO,
3160 				  radio_nr[btv->c.nr]) < 0)
3161 		goto err;
3162 	pr_info("%d: registered device %s\n",
3163 		btv->c.nr, video_device_node_name(&btv->radio_dev));
3164 
3165 	/* all done */
3166 	return 0;
3167 
3168  err:
3169 	bttv_unregister_video(btv);
3170 	return -1;
3171 }
3172 
3173 
3174 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
3175 /* response on cards with no firmware is not enabled by OF */
3176 static void pci_set_command(struct pci_dev *dev)
3177 {
3178 #if defined(__powerpc__)
3179 	unsigned int cmd;
3180 
3181 	pci_read_config_dword(dev, PCI_COMMAND, &cmd);
3182 	cmd = (cmd | PCI_COMMAND_MEMORY );
3183 	pci_write_config_dword(dev, PCI_COMMAND, cmd);
3184 #endif
3185 }
3186 
3187 static int bttv_probe(struct pci_dev *dev, const struct pci_device_id *pci_id)
3188 {
3189 	struct v4l2_frequency init_freq = {
3190 		.tuner = 0,
3191 		.type = V4L2_TUNER_ANALOG_TV,
3192 		.frequency = 980,
3193 	};
3194 	int result;
3195 	unsigned char lat;
3196 	struct bttv *btv;
3197 	struct v4l2_ctrl_handler *hdl;
3198 
3199 	if (bttv_num == BTTV_MAX)
3200 		return -ENOMEM;
3201 	pr_info("Bt8xx card found (%d)\n", bttv_num);
3202 	bttvs[bttv_num] = btv = kzalloc(sizeof(*btv), GFP_KERNEL);
3203 	if (btv == NULL) {
3204 		pr_err("out of memory\n");
3205 		return -ENOMEM;
3206 	}
3207 	btv->c.nr  = bttv_num;
3208 	snprintf(btv->c.v4l2_dev.name, sizeof(btv->c.v4l2_dev.name),
3209 			"bttv%d", btv->c.nr);
3210 
3211 	/* initialize structs / fill in defaults */
3212 	mutex_init(&btv->lock);
3213 	spin_lock_init(&btv->s_lock);
3214 	spin_lock_init(&btv->gpio_lock);
3215 	init_waitqueue_head(&btv->i2c_queue);
3216 	INIT_LIST_HEAD(&btv->c.subs);
3217 	INIT_LIST_HEAD(&btv->capture);
3218 	INIT_LIST_HEAD(&btv->vcapture);
3219 
3220 	timer_setup(&btv->timeout, bttv_irq_timeout, 0);
3221 
3222 	btv->i2c_rc = -1;
3223 	btv->tuner_type  = UNSET;
3224 	btv->new_input   = UNSET;
3225 	btv->has_radio=radio[btv->c.nr];
3226 
3227 	/* pci stuff (init, get irq/mmio, ... */
3228 	btv->c.pci = dev;
3229 	btv->id  = dev->device;
3230 	if (pci_enable_device(dev)) {
3231 		pr_warn("%d: Can't enable device\n", btv->c.nr);
3232 		result = -EIO;
3233 		goto free_mem;
3234 	}
3235 	if (dma_set_mask(&dev->dev, DMA_BIT_MASK(32))) {
3236 		pr_warn("%d: No suitable DMA available\n", btv->c.nr);
3237 		result = -EIO;
3238 		goto free_mem;
3239 	}
3240 	if (!request_mem_region(pci_resource_start(dev,0),
3241 				pci_resource_len(dev,0),
3242 				btv->c.v4l2_dev.name)) {
3243 		pr_warn("%d: can't request iomem (0x%llx)\n",
3244 			btv->c.nr,
3245 			(unsigned long long)pci_resource_start(dev, 0));
3246 		result = -EBUSY;
3247 		goto free_mem;
3248 	}
3249 	pci_set_master(dev);
3250 	pci_set_command(dev);
3251 
3252 	result = v4l2_device_register(&dev->dev, &btv->c.v4l2_dev);
3253 	if (result < 0) {
3254 		pr_warn("%d: v4l2_device_register() failed\n", btv->c.nr);
3255 		goto fail0;
3256 	}
3257 	hdl = &btv->ctrl_handler;
3258 	v4l2_ctrl_handler_init(hdl, 20);
3259 	btv->c.v4l2_dev.ctrl_handler = hdl;
3260 	v4l2_ctrl_handler_init(&btv->radio_ctrl_handler, 6);
3261 
3262 	btv->revision = dev->revision;
3263 	pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
3264 	pr_info("%d: Bt%d (rev %d) at %s, irq: %d, latency: %d, mmio: 0x%llx\n",
3265 		bttv_num, btv->id, btv->revision, pci_name(dev),
3266 		btv->c.pci->irq, lat,
3267 		(unsigned long long)pci_resource_start(dev, 0));
3268 	schedule();
3269 
3270 	btv->bt848_mmio = ioremap(pci_resource_start(dev, 0), 0x1000);
3271 	if (NULL == btv->bt848_mmio) {
3272 		pr_err("%d: ioremap() failed\n", btv->c.nr);
3273 		result = -EIO;
3274 		goto fail1;
3275 	}
3276 
3277 	/* identify card */
3278 	bttv_idcard(btv);
3279 
3280 	/* disable irqs, register irq handler */
3281 	btwrite(0, BT848_INT_MASK);
3282 	result = request_irq(btv->c.pci->irq, bttv_irq,
3283 	    IRQF_SHARED, btv->c.v4l2_dev.name, (void *)btv);
3284 	if (result < 0) {
3285 		pr_err("%d: can't get IRQ %d\n",
3286 		       bttv_num, btv->c.pci->irq);
3287 		goto fail1;
3288 	}
3289 
3290 	if (0 != bttv_handle_chipset(btv)) {
3291 		result = -EIO;
3292 		goto fail2;
3293 	}
3294 
3295 	/* init options from insmod args */
3296 	btv->opt_combfilter = combfilter;
3297 	bttv_ctrl_combfilter.def = combfilter;
3298 	bttv_ctrl_lumafilter.def = lumafilter;
3299 	btv->opt_automute   = automute;
3300 	bttv_ctrl_automute.def = automute;
3301 	bttv_ctrl_agc_crush.def = agc_crush;
3302 	btv->opt_vcr_hack   = vcr_hack;
3303 	bttv_ctrl_vcr_hack.def = vcr_hack;
3304 	bttv_ctrl_whitecrush_upper.def = whitecrush_upper;
3305 	bttv_ctrl_whitecrush_lower.def = whitecrush_lower;
3306 	btv->opt_uv_ratio   = uv_ratio;
3307 	bttv_ctrl_uv_ratio.def = uv_ratio;
3308 	bttv_ctrl_full_luma.def = full_luma_range;
3309 	bttv_ctrl_coring.def = coring;
3310 
3311 	/* fill struct bttv with some useful defaults */
3312 	btv->fmt = format_by_fourcc(V4L2_PIX_FMT_BGR24);
3313 	btv->width = 320;
3314 	btv->height = 240;
3315 	btv->field = V4L2_FIELD_INTERLACED;
3316 	btv->input = 0;
3317 	btv->tvnorm = 0; /* Index into bttv_tvnorms[] i.e. PAL. */
3318 	bttv_vbi_fmt_reset(&btv->vbi_fmt, btv->tvnorm);
3319 	btv->vbi_count[0] = VBI_DEFLINES;
3320 	btv->vbi_count[1] = VBI_DEFLINES;
3321 	btv->do_crop = 0;
3322 
3323 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3324 			V4L2_CID_BRIGHTNESS, 0, 0xff00, 0x100, 32768);
3325 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3326 			V4L2_CID_CONTRAST, 0, 0xff80, 0x80, 0x6c00);
3327 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3328 			V4L2_CID_SATURATION, 0, 0xff80, 0x80, 32768);
3329 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3330 			V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
3331 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3332 			V4L2_CID_HUE, 0, 0xff00, 0x100, 32768);
3333 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3334 			V4L2_CID_CHROMA_AGC, 0, 1, 1, !!chroma_agc);
3335 	v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3336 		V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
3337 	if (btv->volume_gpio)
3338 		v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3339 			V4L2_CID_AUDIO_VOLUME, 0, 0xff00, 0x100, 0xff00);
3340 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_combfilter, NULL);
3341 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_automute, NULL);
3342 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_lumafilter, NULL);
3343 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_agc_crush, NULL);
3344 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_vcr_hack, NULL);
3345 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_lower, NULL);
3346 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_upper, NULL);
3347 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_uv_ratio, NULL);
3348 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_full_luma, NULL);
3349 	v4l2_ctrl_new_custom(hdl, &bttv_ctrl_coring, NULL);
3350 
3351 	/* initialize hardware */
3352 	if (bttv_gpio)
3353 		bttv_gpio_tracking(btv,"pre-init");
3354 
3355 	bttv_risc_init_main(btv);
3356 	init_bt848(btv);
3357 
3358 	/* gpio */
3359 	btwrite(0x00, BT848_GPIO_REG_INP);
3360 	btwrite(0x00, BT848_GPIO_OUT_EN);
3361 	if (bttv_verbose)
3362 		bttv_gpio_tracking(btv,"init");
3363 
3364 	/* needs to be done before i2c is registered */
3365 	bttv_init_card1(btv);
3366 
3367 	/* register i2c + gpio */
3368 	init_bttv_i2c(btv);
3369 
3370 	/* some card-specific stuff (needs working i2c) */
3371 	bttv_init_card2(btv);
3372 	bttv_init_tuner(btv);
3373 	if (btv->tuner_type != TUNER_ABSENT) {
3374 		bttv_set_frequency(btv, &init_freq);
3375 		btv->radio_freq = 90500 * 16; /* 90.5Mhz default */
3376 	}
3377 	btv->std = V4L2_STD_PAL;
3378 	init_irqreg(btv);
3379 	if (!bttv_tvcards[btv->c.type].no_video)
3380 		v4l2_ctrl_handler_setup(hdl);
3381 	if (hdl->error) {
3382 		result = hdl->error;
3383 		goto fail2;
3384 	}
3385 	/* mute device */
3386 	audio_mute(btv, 1);
3387 
3388 	/* register video4linux + input */
3389 	if (!bttv_tvcards[btv->c.type].no_video) {
3390 		v4l2_ctrl_add_handler(&btv->radio_ctrl_handler, hdl,
3391 				v4l2_ctrl_radio_filter, false);
3392 		if (btv->radio_ctrl_handler.error) {
3393 			result = btv->radio_ctrl_handler.error;
3394 			goto fail2;
3395 		}
3396 		set_input(btv, btv->input, btv->tvnorm);
3397 		bttv_crop_reset(&btv->crop[0], btv->tvnorm);
3398 		btv->crop[1] = btv->crop[0]; /* current = default */
3399 		disclaim_vbi_lines(btv);
3400 		disclaim_video_lines(btv);
3401 		bttv_register_video(btv);
3402 	}
3403 
3404 	/* add subdevices and autoload dvb-bt8xx if needed */
3405 	if (bttv_tvcards[btv->c.type].has_dvb) {
3406 		bttv_sub_add_device(&btv->c, "dvb");
3407 		request_modules(btv);
3408 	}
3409 
3410 	if (!disable_ir) {
3411 		init_bttv_i2c_ir(btv);
3412 		bttv_input_init(btv);
3413 	}
3414 
3415 	/* everything is fine */
3416 	bttv_num++;
3417 	return 0;
3418 
3419 fail2:
3420 	free_irq(btv->c.pci->irq,btv);
3421 
3422 fail1:
3423 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
3424 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
3425 	v4l2_device_unregister(&btv->c.v4l2_dev);
3426 
3427 fail0:
3428 	if (btv->bt848_mmio)
3429 		iounmap(btv->bt848_mmio);
3430 	release_mem_region(pci_resource_start(btv->c.pci,0),
3431 			   pci_resource_len(btv->c.pci,0));
3432 	pci_disable_device(btv->c.pci);
3433 
3434 free_mem:
3435 	bttvs[btv->c.nr] = NULL;
3436 	kfree(btv);
3437 	return result;
3438 }
3439 
3440 static void bttv_remove(struct pci_dev *pci_dev)
3441 {
3442 	struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
3443 	struct bttv *btv = to_bttv(v4l2_dev);
3444 
3445 	if (bttv_verbose)
3446 		pr_info("%d: unloading\n", btv->c.nr);
3447 
3448 	if (bttv_tvcards[btv->c.type].has_dvb)
3449 		flush_request_modules(btv);
3450 
3451 	/* shutdown everything (DMA+IRQs) */
3452 	btand(~15, BT848_GPIO_DMA_CTL);
3453 	btwrite(0, BT848_INT_MASK);
3454 	btwrite(~0x0, BT848_INT_STAT);
3455 	btwrite(0x0, BT848_GPIO_OUT_EN);
3456 	if (bttv_gpio)
3457 		bttv_gpio_tracking(btv,"cleanup");
3458 
3459 	/* tell gpio modules we are leaving ... */
3460 	btv->shutdown=1;
3461 	bttv_input_fini(btv);
3462 	bttv_sub_del_devices(&btv->c);
3463 
3464 	/* unregister i2c_bus + input */
3465 	fini_bttv_i2c(btv);
3466 
3467 	/* unregister video4linux */
3468 	bttv_unregister_video(btv);
3469 
3470 	/* free allocated memory */
3471 	v4l2_ctrl_handler_free(&btv->ctrl_handler);
3472 	v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
3473 	btcx_riscmem_free(btv->c.pci,&btv->main);
3474 
3475 	/* free resources */
3476 	free_irq(btv->c.pci->irq,btv);
3477 	iounmap(btv->bt848_mmio);
3478 	release_mem_region(pci_resource_start(btv->c.pci,0),
3479 			   pci_resource_len(btv->c.pci,0));
3480 	pci_disable_device(btv->c.pci);
3481 
3482 	v4l2_device_unregister(&btv->c.v4l2_dev);
3483 	bttvs[btv->c.nr] = NULL;
3484 	kfree(btv);
3485 
3486 	return;
3487 }
3488 
3489 static int __maybe_unused bttv_suspend(struct device *dev)
3490 {
3491 	struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
3492 	struct bttv *btv = to_bttv(v4l2_dev);
3493 	struct bttv_buffer_set idle;
3494 	unsigned long flags;
3495 
3496 	dprintk("%d: suspend\n", btv->c.nr);
3497 
3498 	/* stop dma + irqs */
3499 	spin_lock_irqsave(&btv->s_lock,flags);
3500 	memset(&idle, 0, sizeof(idle));
3501 	btv->state.video = btv->curr;
3502 	btv->state.vbi   = btv->cvbi;
3503 	btv->state.loop_irq = btv->loop_irq;
3504 	btv->curr = idle;
3505 	btv->loop_irq = 0;
3506 	bttv_buffer_activate_video(btv, &idle);
3507 	bttv_buffer_activate_vbi(btv, NULL);
3508 	bttv_set_dma(btv, 0);
3509 	btwrite(0, BT848_INT_MASK);
3510 	spin_unlock_irqrestore(&btv->s_lock,flags);
3511 
3512 	/* save bt878 state */
3513 	btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
3514 	btv->state.gpio_data   = gpio_read();
3515 
3516 	btv->state.disabled = 1;
3517 	return 0;
3518 }
3519 
3520 static int __maybe_unused bttv_resume(struct device *dev)
3521 {
3522 	struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
3523 	struct bttv *btv = to_bttv(v4l2_dev);
3524 	unsigned long flags;
3525 
3526 	dprintk("%d: resume\n", btv->c.nr);
3527 
3528 	btv->state.disabled = 0;
3529 
3530 	/* restore bt878 state */
3531 	bttv_reinit_bt848(btv);
3532 	gpio_inout(0xffffff, btv->state.gpio_enable);
3533 	gpio_write(btv->state.gpio_data);
3534 
3535 	/* restart dma */
3536 	spin_lock_irqsave(&btv->s_lock,flags);
3537 	btv->curr = btv->state.video;
3538 	btv->cvbi = btv->state.vbi;
3539 	btv->loop_irq = btv->state.loop_irq;
3540 	bttv_buffer_activate_video(btv, &btv->curr);
3541 	bttv_buffer_activate_vbi(btv, btv->cvbi);
3542 	bttv_set_dma(btv, 0);
3543 	spin_unlock_irqrestore(&btv->s_lock,flags);
3544 	return 0;
3545 }
3546 
3547 static const struct pci_device_id bttv_pci_tbl[] = {
3548 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT848), 0},
3549 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT849), 0},
3550 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT878), 0},
3551 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT879), 0},
3552 	{PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_FUSION879), 0},
3553 	{0,}
3554 };
3555 
3556 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
3557 
3558 static SIMPLE_DEV_PM_OPS(bttv_pm_ops,
3559 			 bttv_suspend,
3560 			 bttv_resume);
3561 
3562 static struct pci_driver bttv_pci_driver = {
3563 	.name      = "bttv",
3564 	.id_table  = bttv_pci_tbl,
3565 	.probe     = bttv_probe,
3566 	.remove    = bttv_remove,
3567 	.driver.pm = &bttv_pm_ops,
3568 };
3569 
3570 static int __init bttv_init_module(void)
3571 {
3572 	int ret;
3573 
3574 	bttv_num = 0;
3575 
3576 	pr_info("driver version %s loaded\n", BTTV_VERSION);
3577 	if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
3578 		gbuffers = 2;
3579 	if (gbufsize > BTTV_MAX_FBUF)
3580 		gbufsize = BTTV_MAX_FBUF;
3581 	gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
3582 	if (bttv_verbose)
3583 		pr_info("using %d buffers with %dk (%d pages) each for capture\n",
3584 			gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
3585 
3586 	bttv_check_chipset();
3587 
3588 	ret = bus_register(&bttv_sub_bus_type);
3589 	if (ret < 0) {
3590 		pr_warn("bus_register error: %d\n", ret);
3591 		return ret;
3592 	}
3593 	ret = pci_register_driver(&bttv_pci_driver);
3594 	if (ret < 0)
3595 		bus_unregister(&bttv_sub_bus_type);
3596 
3597 	return ret;
3598 }
3599 
3600 static void __exit bttv_cleanup_module(void)
3601 {
3602 	pci_unregister_driver(&bttv_pci_driver);
3603 	bus_unregister(&bttv_sub_bus_type);
3604 }
3605 
3606 module_init(bttv_init_module);
3607 module_exit(bttv_cleanup_module);
3608