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