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