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