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