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