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