VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[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         bt848_bright(btv,   btv->bright);
1055         bt848_hue(btv,      btv->hue);
1056         bt848_contrast(btv, btv->contrast);
1057         bt848_sat(btv,      btv->saturation);
1058
1059         if (btv->opt_lumafilter) {
1060                 btwrite(0, BT848_E_CONTROL);
1061                 btwrite(0, BT848_O_CONTROL);
1062         } else {
1063                 btwrite(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1064                 btwrite(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1065         }
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         retval = verify_window(&bttv_tvnorms[btv->tvnorm],win,fixup);
1865         if (0 != retval)
1866                 return retval;
1867
1868         /* copy clips  --  luckily v4l1 + v4l2 are binary
1869            compatible here ...*/
1870         n = win->clipcount;
1871         size = sizeof(*clips)*(n+4);
1872         clips = kmalloc(size,GFP_KERNEL);
1873         if (NULL == clips)
1874                 return -ENOMEM;
1875         if (n > 0) {
1876                 if (copy_from_user(clips,win->clips,sizeof(struct v4l2_clip)*n)) {
1877                         kfree(clips);
1878                         return -EFAULT;
1879                 }
1880         }
1881         /* clip against screen */
1882         if (NULL != btv->fbuf.base)
1883                 n = btcx_screen_clips(btv->fbuf.fmt.width, btv->fbuf.fmt.height,
1884                                       &win->w, clips, n);
1885         btcx_sort_clips(clips,n);
1886
1887         /* 4-byte alignments */
1888         switch (fh->ovfmt->depth) {
1889         case 8:
1890         case 24:
1891                 btcx_align(&win->w, clips, n, 3);
1892                 break;
1893         case 16:
1894                 btcx_align(&win->w, clips, n, 1);
1895                 break;
1896         case 32:
1897                 /* no alignment fixups needed */
1898                 break;
1899         default:
1900                 BUG();
1901         }
1902         
1903         down(&fh->cap.lock);
1904         if (fh->ov.clips)
1905                 kfree(fh->ov.clips);
1906         fh->ov.clips    = clips;
1907         fh->ov.nclips   = n;
1908         
1909         fh->ov.w        = win->w;
1910         fh->ov.field    = win->field;
1911         fh->ov.setup_ok = 1;
1912         btv->init.ov.w.width   = win->w.width;
1913         btv->init.ov.w.height  = win->w.height;
1914         btv->init.ov.field     = win->field;
1915         
1916         /* update overlay if needed */
1917         retval = 0;
1918         if (check_btres(fh, RESOURCE_OVERLAY)) {
1919                 struct bttv_buffer *new;
1920                 
1921                 new = videobuf_alloc(sizeof(*new));
1922                 bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
1923                 retval = bttv_switch_overlay(btv,fh,new);
1924         }
1925         up(&fh->cap.lock);
1926         return retval;
1927 }
1928
1929 /* ----------------------------------------------------------------------- */
1930
1931 static struct videobuf_queue* bttv_queue(struct bttv_fh *fh)
1932 {
1933         struct videobuf_queue* q = NULL;
1934         
1935         switch (fh->type) {
1936         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1937                 q = &fh->cap;
1938                 break;
1939         case V4L2_BUF_TYPE_VBI_CAPTURE:
1940                 q = &fh->vbi;
1941                 break;
1942         default:
1943                 BUG();
1944         }
1945         return q;
1946 }
1947
1948 static int bttv_resource(struct bttv_fh *fh)
1949 {
1950         int res = 0;
1951         
1952         switch (fh->type) {
1953         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1954                 res = RESOURCE_VIDEO;
1955                 break;
1956         case V4L2_BUF_TYPE_VBI_CAPTURE:
1957                 res = RESOURCE_VBI;
1958                 break;
1959         default:
1960                 BUG();
1961         }
1962         return res;
1963 }
1964
1965 static int bttv_switch_type(struct bttv_fh *fh, enum v4l2_buf_type type)
1966 {
1967         struct videobuf_queue *q = bttv_queue(fh);
1968         int res = bttv_resource(fh);
1969
1970         if (check_btres(fh,res))
1971                 return -EBUSY;
1972         if (videobuf_queue_is_busy(q))
1973                 return -EBUSY;
1974         fh->type = type;
1975         return 0;
1976 }
1977
1978 static int bttv_g_fmt(struct bttv_fh *fh, struct v4l2_format *f)
1979 {
1980         switch (f->type) {
1981         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1982                 memset(&f->fmt.pix,0,sizeof(struct v4l2_pix_format));
1983                 f->fmt.pix.width        = fh->width;
1984                 f->fmt.pix.height       = fh->height;
1985                 f->fmt.pix.field        = fh->cap.field;
1986                 f->fmt.pix.pixelformat  = fh->fmt->fourcc;
1987                 f->fmt.pix.bytesperline =
1988                         (f->fmt.pix.width * fh->fmt->depth) >> 3;
1989                 f->fmt.pix.sizeimage =
1990                         f->fmt.pix.height * f->fmt.pix.bytesperline;
1991                 return 0;
1992         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
1993                 memset(&f->fmt.win,0,sizeof(struct v4l2_window));
1994                 f->fmt.win.w     = fh->ov.w;
1995                 f->fmt.win.field = fh->ov.field;
1996                 return 0;
1997         case V4L2_BUF_TYPE_VBI_CAPTURE:
1998                 bttv_vbi_get_fmt(fh,f);
1999                 return 0;
2000         default:
2001                 return -EINVAL;
2002         }
2003 }
2004
2005 static int bttv_try_fmt(struct bttv_fh *fh, struct bttv *btv,
2006                         struct v4l2_format *f)
2007 {
2008         switch (f->type) {
2009         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2010         {
2011                 const struct bttv_format *fmt;
2012                 enum v4l2_field field;
2013                 unsigned int maxw,maxh;
2014
2015                 fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2016                 if (NULL == fmt)
2017                         return -EINVAL;
2018
2019                 /* fixup format */
2020                 maxw  = bttv_tvnorms[btv->tvnorm].swidth;
2021                 maxh  = bttv_tvnorms[btv->tvnorm].sheight;
2022                 field = f->fmt.pix.field;
2023                 if (V4L2_FIELD_ANY == field)
2024                         field = (f->fmt.pix.height > maxh/2)
2025                                 ? V4L2_FIELD_INTERLACED
2026                                 : V4L2_FIELD_BOTTOM;
2027                 if (V4L2_FIELD_SEQ_BT == field)
2028                         field = V4L2_FIELD_SEQ_TB;
2029                 switch (field) {
2030                 case V4L2_FIELD_TOP:
2031                 case V4L2_FIELD_BOTTOM:
2032                 case V4L2_FIELD_ALTERNATE:
2033                         maxh = maxh/2;
2034                         break;
2035                 case V4L2_FIELD_INTERLACED:
2036                         break;
2037                 case V4L2_FIELD_SEQ_TB:
2038                         if (fmt->flags & FORMAT_FLAGS_PLANAR)
2039                                 return -EINVAL;
2040                         break;
2041                 default:
2042                         return -EINVAL;
2043                 }
2044
2045                 /* update data for the application */
2046                 f->fmt.pix.field = field;
2047                 if (f->fmt.pix.width  < 48)
2048                         f->fmt.pix.width  = 48;
2049                 if (f->fmt.pix.height < 32)
2050                         f->fmt.pix.height = 32;
2051                 if (f->fmt.pix.width  > maxw)
2052                         f->fmt.pix.width = maxw;
2053                 if (f->fmt.pix.height > maxh)
2054                         f->fmt.pix.height = maxh;
2055                 f->fmt.pix.bytesperline =
2056                         (f->fmt.pix.width * fmt->depth) >> 3;
2057                 f->fmt.pix.sizeimage =
2058                         f->fmt.pix.height * f->fmt.pix.bytesperline;
2059                 
2060                 return 0;
2061         }
2062         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2063                 return verify_window(&bttv_tvnorms[btv->tvnorm],
2064                                      &f->fmt.win, 1);
2065         case V4L2_BUF_TYPE_VBI_CAPTURE:
2066                 bttv_vbi_try_fmt(fh,f);
2067                 return 0;
2068         default:
2069                 return -EINVAL;
2070         }
2071 }
2072
2073 static int bttv_s_fmt(struct bttv_fh *fh, struct bttv *btv,
2074                       struct v4l2_format *f)
2075 {
2076         int retval;
2077         
2078         switch (f->type) {
2079         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2080         {
2081                 const struct bttv_format *fmt;
2082
2083                 retval = bttv_switch_type(fh,f->type);
2084                 if (0 != retval)
2085                         return retval;
2086                 retval = bttv_try_fmt(fh,btv,f);
2087                 if (0 != retval)
2088                         return retval;
2089                 fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2090                 
2091                 /* update our state informations */
2092                 down(&fh->cap.lock);
2093                 fh->fmt              = fmt;
2094                 fh->cap.field        = f->fmt.pix.field;
2095                 fh->cap.last         = V4L2_FIELD_NONE;
2096                 fh->width            = f->fmt.pix.width;
2097                 fh->height           = f->fmt.pix.height;
2098                 btv->init.fmt        = fmt;
2099                 btv->init.width      = f->fmt.pix.width;
2100                 btv->init.height     = f->fmt.pix.height;
2101                 up(&fh->cap.lock);
2102                 
2103                 return 0;
2104         }
2105         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2106                 return setup_window(fh, btv, &f->fmt.win, 1);
2107         case V4L2_BUF_TYPE_VBI_CAPTURE:
2108                 retval = bttv_switch_type(fh,f->type);
2109                 if (0 != retval)
2110                         return retval;
2111                 if (locked_btres(fh->btv, RESOURCE_VBI))
2112                         return -EBUSY;
2113                 bttv_vbi_try_fmt(fh,f);
2114                 bttv_vbi_setlines(fh,btv,f->fmt.vbi.count[0]);
2115                 bttv_vbi_get_fmt(fh,f);
2116                 return 0;
2117         default:
2118                 return -EINVAL;
2119         }
2120 }
2121
2122 static int bttv_do_ioctl(struct inode *inode, struct file *file,
2123                          unsigned int cmd, void *arg)
2124 {
2125         struct bttv_fh *fh  = file->private_data;
2126         struct bttv    *btv = fh->btv;
2127         unsigned long flags;
2128         int retval = 0;
2129
2130         if (bttv_debug > 1) {
2131                 switch (_IOC_TYPE(cmd)) {
2132                 case 'v':
2133                         printk("bttv%d: ioctl 0x%x (v4l1, VIDIOC%s)\n",
2134                                btv->c.nr, cmd, (_IOC_NR(cmd) < V4L1_IOCTLS) ?
2135                                v4l1_ioctls[_IOC_NR(cmd)] : "???");
2136                         break;
2137                 case 'V':
2138                         printk("bttv%d: ioctl 0x%x (v4l2, %s)\n",
2139                                btv->c.nr, cmd,  v4l2_ioctl_names[_IOC_NR(cmd)]);
2140                         break;
2141                 default:
2142                         printk("bttv%d: ioctl 0x%x (???)\n",
2143                                btv->c.nr, cmd);
2144                 }
2145         }
2146         if (btv->errors)
2147                 bttv_reinit_bt848(btv);
2148
2149 #ifdef VIDIOC_G_PRIORITY
2150         switch (cmd) {
2151         case VIDIOCSFREQ:
2152         case VIDIOCSTUNER:
2153         case VIDIOCSCHAN:
2154         case VIDIOC_S_CTRL:
2155         case VIDIOC_S_STD:
2156         case VIDIOC_S_INPUT:
2157         case VIDIOC_S_TUNER:
2158         case VIDIOC_S_FREQUENCY:
2159                 retval = v4l2_prio_check(&btv->prio,&fh->prio);
2160                 if (0 != retval)
2161                         return retval;
2162         };
2163 #endif
2164         switch (cmd) {
2165
2166         /* ***  v4l1  *** ************************************************ */
2167         case VIDIOCGCAP:
2168         {
2169                 struct video_capability *cap = arg;
2170
2171                 memset(cap,0,sizeof(*cap));
2172                 strcpy(cap->name,btv->video_dev->name);
2173                 if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
2174                         /* vbi */
2175                         cap->type = VID_TYPE_TUNER|VID_TYPE_TELETEXT;
2176                 } else {
2177                         /* others */
2178                         cap->type = VID_TYPE_CAPTURE|
2179                                 VID_TYPE_TUNER|
2180                                 VID_TYPE_OVERLAY|
2181                                 VID_TYPE_CLIPPING|
2182                                 VID_TYPE_SCALES;
2183                         cap->maxwidth  = bttv_tvnorms[btv->tvnorm].swidth;
2184                         cap->maxheight = bttv_tvnorms[btv->tvnorm].sheight;
2185                         cap->minwidth  = 48;
2186                         cap->minheight = 32;
2187                 }
2188                 cap->channels  = bttv_tvcards[btv->c.type].video_inputs;
2189                 cap->audios    = bttv_tvcards[btv->c.type].audio_inputs;
2190                 return 0;
2191         }
2192
2193         case VIDIOCGPICT:
2194         {
2195                 struct video_picture *pic = arg;
2196
2197                 memset(pic,0,sizeof(*pic));
2198                 pic->brightness = btv->bright;
2199                 pic->contrast   = btv->contrast;
2200                 pic->hue        = btv->hue;
2201                 pic->colour     = btv->saturation;
2202                 if (fh->fmt) {
2203                         pic->depth   = fh->fmt->depth;
2204                         pic->palette = fh->fmt->palette;
2205                 }
2206                 return 0;
2207         }
2208         case VIDIOCSPICT:
2209         {
2210                 struct video_picture *pic = arg;
2211                 const struct bttv_format *fmt;
2212                 
2213                 fmt = format_by_palette(pic->palette);
2214                 if (NULL == fmt)
2215                         return -EINVAL;
2216                 down(&fh->cap.lock);
2217                 if (fmt->depth != pic->depth) {
2218                         retval = -EINVAL;
2219                         goto fh_unlock_and_return;
2220                 }
2221                 fh->ovfmt   = fmt;
2222                 fh->fmt     = fmt;
2223                 btv->init.ovfmt   = fmt;
2224                 btv->init.fmt     = fmt;
2225                 if (bigendian) {
2226                         /* dirty hack time:  swap bytes for overlay if the
2227                            display adaptor is big endian (insmod option) */
2228                         if (fmt->palette == VIDEO_PALETTE_RGB555 ||
2229                             fmt->palette == VIDEO_PALETTE_RGB565 ||
2230                             fmt->palette == VIDEO_PALETTE_RGB32) {
2231                                 fh->ovfmt = fmt+1;
2232                         }
2233                 }
2234                 bt848_bright(btv,pic->brightness);
2235                 bt848_contrast(btv,pic->contrast);
2236                 bt848_hue(btv,pic->hue);
2237                 bt848_sat(btv,pic->colour);
2238                 up(&fh->cap.lock);
2239                 return 0;
2240         }
2241
2242         case VIDIOCGWIN:
2243         {
2244                 struct video_window *win = arg;
2245
2246                 memset(win,0,sizeof(*win));
2247                 win->x      = fh->ov.w.left;
2248                 win->y      = fh->ov.w.top;
2249                 win->width  = fh->ov.w.width;
2250                 win->height = fh->ov.w.height;
2251                 return 0;
2252         }
2253         case VIDIOCSWIN:
2254         {
2255                 struct video_window *win = arg;
2256                 struct v4l2_window w2;
2257
2258                 w2.field = V4L2_FIELD_ANY;
2259                 w2.w.left    = win->x;
2260                 w2.w.top     = win->y;
2261                 w2.w.width   = win->width;
2262                 w2.w.height  = win->height;
2263                 w2.clipcount = win->clipcount;
2264                 w2.clips     = (struct v4l2_clip __user *)win->clips;
2265                 retval = setup_window(fh, btv, &w2, 0);
2266                 if (0 == retval) {
2267                         /* on v4l1 this ioctl affects the read() size too */
2268                         fh->width  = fh->ov.w.width;
2269                         fh->height = fh->ov.w.height;
2270                         btv->init.width  = fh->ov.w.width;
2271                         btv->init.height = fh->ov.w.height;
2272                 }
2273                 return retval;
2274         }
2275
2276         case VIDIOCGFBUF:
2277         {
2278                 struct video_buffer *fbuf = arg;
2279
2280                 fbuf->base          = btv->fbuf.base;
2281                 fbuf->width         = btv->fbuf.fmt.width;
2282                 fbuf->height        = btv->fbuf.fmt.height;
2283                 fbuf->bytesperline  = btv->fbuf.fmt.bytesperline;
2284                 if (fh->ovfmt)
2285                         fbuf->depth = fh->ovfmt->depth;
2286                 return 0;
2287         }
2288         case VIDIOCSFBUF:
2289         {
2290                 struct video_buffer *fbuf = arg;
2291                 const struct bttv_format *fmt;
2292                 unsigned long end;
2293
2294                 if(!capable(CAP_SYS_ADMIN) &&
2295                    !capable(CAP_SYS_RAWIO))
2296                         return -EPERM;
2297                 end = (unsigned long)fbuf->base +
2298                         fbuf->height * fbuf->bytesperline;
2299                 down(&fh->cap.lock);
2300                 retval = -EINVAL;
2301
2302                 switch (fbuf->depth) {
2303                 case 8:
2304                         fmt = format_by_palette(VIDEO_PALETTE_HI240);
2305                         break;
2306                 case 16:
2307                         fmt = format_by_palette(VIDEO_PALETTE_RGB565);
2308                         break;
2309                 case 24:
2310                         fmt = format_by_palette(VIDEO_PALETTE_RGB24);
2311                         break;
2312                 case 32:
2313                         fmt = format_by_palette(VIDEO_PALETTE_RGB32);
2314                         break;
2315                 case 15:
2316                         fbuf->depth = 16;
2317                         fmt = format_by_palette(VIDEO_PALETTE_RGB555);
2318                         break;
2319                 default:
2320                         fmt = NULL;
2321                         break;
2322                 }
2323                 if (NULL == fmt)
2324                         goto fh_unlock_and_return;
2325
2326                 fh->ovfmt = fmt;
2327                 fh->fmt   = fmt;
2328                 btv->init.ovfmt = fmt;
2329                 btv->init.fmt   = fmt;
2330                 btv->fbuf.base             = fbuf->base;
2331                 btv->fbuf.fmt.width        = fbuf->width;
2332                 btv->fbuf.fmt.height       = fbuf->height;
2333                 if (fbuf->bytesperline)
2334                         btv->fbuf.fmt.bytesperline = fbuf->bytesperline;
2335                 else
2336                         btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fbuf->depth/8;
2337                 up(&fh->cap.lock);
2338                 return 0;
2339         }
2340
2341         case VIDIOCCAPTURE:
2342         case VIDIOC_OVERLAY:
2343         {
2344                 struct bttv_buffer *new;
2345                 int *on = arg;
2346
2347                 if (*on) {
2348                         /* verify args */
2349                         if (NULL == btv->fbuf.base)
2350                                 return -EINVAL;
2351                         if (!fh->ov.setup_ok) {
2352                                 dprintk("bttv%d: overlay: !setup_ok\n",btv->c.nr);
2353                                 return -EINVAL;
2354                         }
2355                 }
2356
2357                 if (!check_alloc_btres(btv,fh,RESOURCE_OVERLAY))
2358                         return -EBUSY;
2359                 
2360                 down(&fh->cap.lock);
2361                 if (*on) {
2362                         fh->ov.tvnorm = btv->tvnorm;
2363                         new = videobuf_alloc(sizeof(*new));
2364                         bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2365                 } else {
2366                         new = NULL;
2367                 }
2368
2369                 /* switch over */
2370                 retval = bttv_switch_overlay(btv,fh,new);
2371                 up(&fh->cap.lock);
2372                 return retval;
2373         }
2374
2375         case VIDIOCGMBUF:
2376         {
2377                 struct video_mbuf *mbuf = arg;
2378                 unsigned int i;
2379
2380                 down(&fh->cap.lock);
2381                 retval = videobuf_mmap_setup(file,&fh->cap,gbuffers,gbufsize,
2382                                              V4L2_MEMORY_MMAP);
2383                 if (retval < 0)
2384                         goto fh_unlock_and_return;
2385                 memset(mbuf,0,sizeof(*mbuf));
2386                 mbuf->frames = gbuffers;
2387                 mbuf->size   = gbuffers * gbufsize;
2388                 for (i = 0; i < gbuffers; i++)
2389                         mbuf->offsets[i] = i * gbufsize;
2390                 up(&fh->cap.lock);
2391                 return 0;
2392         }
2393         case VIDIOCMCAPTURE:
2394         {
2395                 struct video_mmap *vm = arg;
2396                 struct bttv_buffer *buf;
2397                 enum v4l2_field field;
2398
2399                 if (vm->frame >= VIDEO_MAX_FRAME)
2400                         return -EINVAL;
2401
2402                 down(&fh->cap.lock);
2403                 retval = -EINVAL;
2404                 buf = (struct bttv_buffer *)fh->cap.bufs[vm->frame];
2405                 if (NULL == buf)
2406                         goto fh_unlock_and_return;
2407                 if (0 == buf->vb.baddr)
2408                         goto fh_unlock_and_return;
2409                 if (buf->vb.state == STATE_QUEUED ||
2410                     buf->vb.state == STATE_ACTIVE)
2411                         goto fh_unlock_and_return;
2412                 
2413                 field = (vm->height > bttv_tvnorms[btv->tvnorm].sheight/2)
2414                         ? V4L2_FIELD_INTERLACED
2415                         : V4L2_FIELD_BOTTOM;
2416                 retval = bttv_prepare_buffer(btv,buf,
2417                                              format_by_palette(vm->format),
2418                                              vm->width,vm->height,field);
2419                 if (0 != retval)
2420                         goto fh_unlock_and_return;
2421                 spin_lock_irqsave(&btv->s_lock,flags);
2422                 buffer_queue(file,&buf->vb);
2423                 spin_unlock_irqrestore(&btv->s_lock,flags);
2424                 up(&fh->cap.lock);
2425                 return 0;
2426         }
2427         case VIDIOCSYNC:
2428         {
2429                 int *frame = arg;
2430                 struct bttv_buffer *buf;
2431
2432                 if (*frame >= VIDEO_MAX_FRAME)
2433                         return -EINVAL;
2434
2435                 down(&fh->cap.lock);
2436                 retval = -EINVAL;
2437                 buf = (struct bttv_buffer *)fh->cap.bufs[*frame];
2438                 if (NULL == buf)
2439                         goto fh_unlock_and_return;
2440                 retval = videobuf_waiton(&buf->vb,0,1);
2441                 if (0 != retval)
2442                         goto fh_unlock_and_return;
2443                 switch (buf->vb.state) {
2444                 case STATE_ERROR:
2445                         retval = -EIO;
2446                         /* fall through */
2447                 case STATE_DONE:
2448                         videobuf_dma_pci_sync(btv->c.pci,&buf->vb.dma);
2449                         bttv_dma_free(btv,buf);
2450                         break;
2451                 default:
2452                         retval = -EINVAL;
2453                         break;
2454                 }
2455                 up(&fh->cap.lock);
2456                 return retval;
2457         }
2458
2459         case VIDIOCGVBIFMT:
2460         {
2461                 struct vbi_format *fmt = (void *) arg;
2462                 struct v4l2_format fmt2;
2463
2464                 if (fh->type != V4L2_BUF_TYPE_VBI_CAPTURE) {
2465                         retval = bttv_switch_type(fh,V4L2_BUF_TYPE_VBI_CAPTURE);
2466                         if (0 != retval)
2467                                 return retval;
2468                 }
2469                 bttv_vbi_get_fmt(fh, &fmt2);
2470
2471                 memset(fmt,0,sizeof(*fmt));
2472                 fmt->sampling_rate    = fmt2.fmt.vbi.sampling_rate;
2473                 fmt->samples_per_line = fmt2.fmt.vbi.samples_per_line;
2474                 fmt->sample_format    = VIDEO_PALETTE_RAW;
2475                 fmt->start[0]         = fmt2.fmt.vbi.start[0];
2476                 fmt->count[0]         = fmt2.fmt.vbi.count[0];
2477                 fmt->start[1]         = fmt2.fmt.vbi.start[1];
2478                 fmt->count[1]         = fmt2.fmt.vbi.count[1];
2479                 if (fmt2.fmt.vbi.flags & VBI_UNSYNC)
2480                         fmt->flags   |= V4L2_VBI_UNSYNC;
2481                 if (fmt2.fmt.vbi.flags & VBI_INTERLACED)
2482                         fmt->flags   |= V4L2_VBI_INTERLACED;
2483                 return 0;
2484         }
2485         case VIDIOCSVBIFMT:
2486         {
2487                 struct vbi_format *fmt = (void *) arg;
2488                 struct v4l2_format fmt2;
2489
2490                 retval = bttv_switch_type(fh,V4L2_BUF_TYPE_VBI_CAPTURE);
2491                 if (0 != retval)
2492                         return retval;
2493                 bttv_vbi_get_fmt(fh, &fmt2);
2494
2495                 if (fmt->sampling_rate    != fmt2.fmt.vbi.sampling_rate     ||
2496                     fmt->samples_per_line != fmt2.fmt.vbi.samples_per_line  ||
2497                     fmt->sample_format    != VIDEO_PALETTE_RAW              ||
2498                     fmt->start[0]         != fmt2.fmt.vbi.start[0]          ||
2499                     fmt->start[1]         != fmt2.fmt.vbi.start[1]          ||
2500                     fmt->count[0]         != fmt->count[1]                  ||
2501                     fmt->count[0]         <  1                              ||
2502                     fmt->count[0]         >  32 /* VBI_MAXLINES */)
2503                         return -EINVAL;
2504
2505                 bttv_vbi_setlines(fh,btv,fmt->count[0]);
2506                 return 0;
2507         }
2508
2509         case BTTV_VERSION:
2510         case VIDIOCGFREQ:
2511         case VIDIOCSFREQ:
2512         case VIDIOCGTUNER:
2513         case VIDIOCSTUNER:
2514         case VIDIOCGCHAN:
2515         case VIDIOCSCHAN:
2516         case VIDIOCGAUDIO:
2517         case VIDIOCSAUDIO:
2518                 return bttv_common_ioctls(btv,cmd,arg);
2519
2520         /* ***  v4l2  *** ************************************************ */
2521         case VIDIOC_QUERYCAP:
2522         {
2523                 struct v4l2_capability *cap = arg;
2524
2525                 if (0 == v4l2)
2526                         return -EINVAL;
2527                 strcpy(cap->driver,"bttv");
2528                 strlcpy(cap->card,btv->video_dev->name,sizeof(cap->card));
2529                 sprintf(cap->bus_info,"PCI:%s",pci_name(btv->c.pci));
2530                 cap->version = BTTV_VERSION_CODE;
2531                 cap->capabilities =
2532                         V4L2_CAP_VIDEO_CAPTURE |
2533                         V4L2_CAP_VIDEO_OVERLAY |
2534                         V4L2_CAP_VBI_CAPTURE |
2535                         V4L2_CAP_TUNER |
2536                         V4L2_CAP_READWRITE | 
2537                         V4L2_CAP_STREAMING;
2538                 return 0;
2539         }
2540
2541         case VIDIOC_ENUM_FMT:
2542         {
2543                 struct v4l2_fmtdesc *f = arg;
2544                 enum v4l2_buf_type type;
2545                 unsigned int i;
2546                 int index;
2547
2548                 type  = f->type;
2549                 if (V4L2_BUF_TYPE_VBI_CAPTURE == type) {
2550                         /* vbi */
2551                         index = f->index;
2552                         if (0 != index)
2553                                 return -EINVAL;
2554                         memset(f,0,sizeof(*f));
2555                         f->index       = index;
2556                         f->type        = type;
2557                         f->pixelformat = V4L2_PIX_FMT_GREY;
2558                         strcpy(f->description,"vbi data");
2559                         return 0;
2560                 }
2561
2562                 /* video capture + overlay */
2563                 index = -1;
2564                 for (i = 0; i < BTTV_FORMATS; i++) {
2565                         if (bttv_formats[i].fourcc != -1)
2566                                 index++;
2567                         if ((unsigned int)index == f->index)
2568                                 break;
2569                 }
2570                 if (BTTV_FORMATS == i)
2571                         return -EINVAL;
2572
2573                 switch (f->type) {
2574                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2575                         break;
2576                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2577                         if (!(bttv_formats[i].flags & FORMAT_FLAGS_PACKED))
2578                                 return -EINVAL;
2579                         break;
2580                 default:
2581                         return -EINVAL;
2582                 }
2583                 memset(f,0,sizeof(*f));
2584                 f->index       = index;
2585                 f->type        = type;
2586                 f->pixelformat = bttv_formats[i].fourcc;
2587                 strlcpy(f->description,bttv_formats[i].name,sizeof(f->description));
2588                 return 0;
2589         }
2590
2591         case VIDIOC_TRY_FMT:
2592         {
2593                 struct v4l2_format *f = arg;
2594                 return bttv_try_fmt(fh,btv,f);
2595         }
2596         case VIDIOC_G_FMT:
2597         {
2598                 struct v4l2_format *f = arg;
2599                 return bttv_g_fmt(fh,f);
2600         }
2601         case VIDIOC_S_FMT:
2602         {
2603                 struct v4l2_format *f = arg;
2604                 return bttv_s_fmt(fh,btv,f);
2605         }
2606
2607         case VIDIOC_G_FBUF:
2608         {
2609                 struct v4l2_framebuffer *fb = arg;
2610
2611                 *fb = btv->fbuf;
2612                 fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
2613                 if (fh->ovfmt)
2614                         fb->fmt.pixelformat  = fh->ovfmt->fourcc;
2615                 return 0;
2616         }
2617         case VIDIOC_S_FBUF:
2618         {
2619                 struct v4l2_framebuffer *fb = arg;
2620                 const struct bttv_format *fmt;
2621                 
2622                 if(!capable(CAP_SYS_ADMIN) &&
2623                    !capable(CAP_SYS_RAWIO))
2624                         return -EPERM;
2625
2626                 /* check args */
2627                 fmt = format_by_fourcc(fb->fmt.pixelformat);
2628                 if (NULL == fmt)
2629                         return -EINVAL;
2630                 if (0 == (fmt->flags & FORMAT_FLAGS_PACKED))
2631                         return -EINVAL;
2632
2633                 down(&fh->cap.lock);
2634                 retval = -EINVAL;
2635                 if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2636                         if (fb->fmt.width > bttv_tvnorms[btv->tvnorm].swidth)
2637                                 goto fh_unlock_and_return;
2638                         if (fb->fmt.height > bttv_tvnorms[btv->tvnorm].sheight)
2639                                 goto fh_unlock_and_return;
2640                 }
2641
2642                 /* ok, accept it */
2643                 btv->fbuf.base       = fb->base;
2644                 btv->fbuf.fmt.width  = fb->fmt.width;
2645                 btv->fbuf.fmt.height = fb->fmt.height;
2646                 if (0 != fb->fmt.bytesperline)
2647                         btv->fbuf.fmt.bytesperline = fb->fmt.bytesperline;
2648                 else
2649                         btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fmt->depth/8;
2650                 
2651                 retval = 0;
2652                 fh->ovfmt = fmt;
2653                 btv->init.ovfmt = fmt;
2654                 if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2655                         fh->ov.w.left   = 0;
2656                         fh->ov.w.top    = 0;
2657                         fh->ov.w.width  = fb->fmt.width;
2658                         fh->ov.w.height = fb->fmt.height;
2659                         btv->init.ov.w.width  = fb->fmt.width;
2660                         btv->init.ov.w.height = fb->fmt.height;
2661                         if (fh->ov.clips)
2662                                 kfree(fh->ov.clips);
2663                         fh->ov.clips = NULL;
2664                         fh->ov.nclips = 0;
2665
2666                         if (check_btres(fh, RESOURCE_OVERLAY)) {
2667                                 struct bttv_buffer *new;
2668                 
2669                                 new = videobuf_alloc(sizeof(*new));
2670                                 bttv_overlay_risc(btv,&fh->ov,fh->ovfmt,new);
2671                                 retval = bttv_switch_overlay(btv,fh,new);
2672                         }
2673                 }
2674                 up(&fh->cap.lock);
2675                 return retval;
2676         }
2677
2678         case VIDIOC_REQBUFS:
2679                 return videobuf_reqbufs(file,bttv_queue(fh),arg);
2680
2681         case VIDIOC_QUERYBUF:
2682                 return videobuf_querybuf(bttv_queue(fh),arg);
2683
2684         case VIDIOC_QBUF:
2685                 return videobuf_qbuf(file,bttv_queue(fh),arg);
2686
2687         case VIDIOC_DQBUF:
2688                 return videobuf_dqbuf(file,bttv_queue(fh),arg);
2689
2690         case VIDIOC_STREAMON:
2691         {
2692                 int res = bttv_resource(fh);
2693
2694                 if (!check_alloc_btres(btv,fh,res))
2695                         return -EBUSY;
2696                 return videobuf_streamon(file,bttv_queue(fh));
2697         }
2698         case VIDIOC_STREAMOFF:
2699         {
2700                 int res = bttv_resource(fh);
2701
2702                 retval = videobuf_streamoff(file,bttv_queue(fh));
2703                 if (retval < 0)
2704                         return retval;
2705                 free_btres(btv,fh,res);
2706                 return 0;
2707         }
2708
2709         case VIDIOC_QUERYCTRL:
2710         {
2711                 struct v4l2_queryctrl *c = arg;
2712                 int i;
2713
2714                 if ((c->id <  V4L2_CID_BASE ||
2715                      c->id >= V4L2_CID_LASTP1) &&
2716                     (c->id <  V4L2_CID_PRIVATE_BASE ||
2717                      c->id >= V4L2_CID_PRIVATE_LASTP1))
2718                         return -EINVAL;
2719                 for (i = 0; i < BTTV_CTLS; i++)
2720                         if (bttv_ctls[i].id == c->id)
2721                                 break;
2722                 if (i == BTTV_CTLS) {
2723                         *c = no_ctl;
2724                         return 0;
2725                 }
2726                 *c = bttv_ctls[i];
2727                 if (i >= 4 && i <= 8) {
2728                         struct video_audio va;
2729                         memset(&va,0,sizeof(va));
2730                         bttv_call_i2c_clients(btv, VIDIOCGAUDIO, &va);
2731                         if (btv->audio_hook)
2732                                 btv->audio_hook(btv,&va,0);
2733                         switch (bttv_ctls[i].id) {
2734                         case V4L2_CID_AUDIO_VOLUME:
2735                                 if (!(va.flags & VIDEO_AUDIO_VOLUME))
2736                                         *c = no_ctl;
2737                                 break;
2738                         case V4L2_CID_AUDIO_BALANCE:
2739                                 if (!(va.flags & VIDEO_AUDIO_BALANCE))
2740                                         *c = no_ctl;
2741                                 break;
2742                         case V4L2_CID_AUDIO_BASS:
2743                                 if (!(va.flags & VIDEO_AUDIO_BASS))
2744                                         *c = no_ctl;
2745                                 break;
2746                         case V4L2_CID_AUDIO_TREBLE:
2747                                 if (!(va.flags & VIDEO_AUDIO_TREBLE))
2748                                         *c = no_ctl;
2749                                 break;
2750                         }
2751                 }
2752                 return 0;
2753         }
2754         case VIDIOC_G_CTRL:
2755                 return get_control(btv,arg);
2756         case VIDIOC_S_CTRL:
2757                 return set_control(btv,arg);
2758         case VIDIOC_G_PARM:
2759         {
2760                 struct v4l2_streamparm *parm = arg;
2761                 struct v4l2_standard s;
2762                 if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2763                         return -EINVAL;
2764                 memset(parm,0,sizeof(*parm));
2765                 v4l2_video_std_construct(&s, bttv_tvnorms[btv->tvnorm].v4l2_id,
2766                                          bttv_tvnorms[btv->tvnorm].name);
2767                 parm->parm.capture.timeperframe = s.frameperiod;
2768                 return 0;
2769         }
2770
2771 #ifdef VIDIOC_G_PRIORITY
2772         case VIDIOC_G_PRIORITY:
2773         {
2774                 enum v4l2_priority *p = arg;
2775
2776                 *p = v4l2_prio_max(&btv->prio);
2777                 return 0;
2778         }
2779         case VIDIOC_S_PRIORITY:
2780         {
2781                 enum v4l2_priority *prio = arg;
2782
2783                 return v4l2_prio_change(&btv->prio, &fh->prio, *prio);
2784         }
2785 #endif
2786
2787         
2788         case VIDIOC_ENUMSTD:
2789         case VIDIOC_G_STD:
2790         case VIDIOC_S_STD:
2791         case VIDIOC_ENUMINPUT:
2792         case VIDIOC_G_INPUT:
2793         case VIDIOC_S_INPUT:
2794         case VIDIOC_G_TUNER:
2795         case VIDIOC_S_TUNER:
2796         case VIDIOC_G_FREQUENCY:
2797         case VIDIOC_S_FREQUENCY:
2798                 return bttv_common_ioctls(btv,cmd,arg);
2799
2800         default:
2801                 return -ENOIOCTLCMD;
2802         }
2803         return 0;
2804
2805  fh_unlock_and_return:
2806         up(&fh->cap.lock);
2807         return retval;
2808 }
2809
2810 static int bttv_ioctl(struct inode *inode, struct file *file,
2811                       unsigned int cmd, unsigned long arg)
2812 {
2813         struct bttv_fh *fh  = file->private_data;
2814
2815         switch (cmd) {
2816         case BTTV_VBISIZE:
2817                 bttv_switch_type(fh,V4L2_BUF_TYPE_VBI_CAPTURE);
2818                 return fh->lines * 2 * 2048;
2819         default:
2820                 return video_usercopy(inode, file, cmd, arg, bttv_do_ioctl);
2821         }
2822 }
2823
2824 static ssize_t bttv_read(struct file *file, char __user *data,
2825                          size_t count, loff_t *ppos)
2826 {
2827         struct bttv_fh *fh = file->private_data;
2828         int retval = 0;
2829
2830         if (fh->btv->errors)
2831                 bttv_reinit_bt848(fh->btv);
2832         dprintk("bttv%d: read count=%d type=%s\n",
2833                 fh->btv->c.nr,(int)count,v4l2_type_names[fh->type]);
2834
2835         switch (fh->type) {
2836         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2837                 if (locked_btres(fh->btv,RESOURCE_VIDEO))
2838                         return -EBUSY;
2839                 retval = videobuf_read_one(file, &fh->cap, data, count, ppos);
2840                 break;
2841         case V4L2_BUF_TYPE_VBI_CAPTURE:
2842                 if (!check_alloc_btres(fh->btv,fh,RESOURCE_VBI))
2843                         return -EBUSY;
2844                 retval = videobuf_read_stream(file, &fh->vbi, data, count, ppos, 1);
2845                 break;
2846         default:
2847                 BUG();
2848         }
2849         return retval;
2850 }
2851
2852 static unsigned int bttv_poll(struct file *file, poll_table *wait)
2853 {
2854         struct bttv_fh *fh = file->private_data;
2855         struct bttv_buffer *buf;
2856         enum v4l2_field field;
2857
2858         if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
2859                 if (!check_alloc_btres(fh->btv,fh,RESOURCE_VBI))
2860                         return -EBUSY;
2861                 return videobuf_poll_stream(file, &fh->vbi, wait);
2862         }
2863
2864         if (check_btres(fh,RESOURCE_VIDEO)) {
2865                 /* streaming capture */
2866                 if (list_empty(&fh->cap.stream))
2867                         return POLLERR;
2868                 buf = list_entry(fh->cap.stream.next,struct bttv_buffer,vb.stream);
2869         } else {
2870                 /* read() capture */
2871                 down(&fh->cap.lock);
2872                 if (NULL == fh->cap.read_buf) {
2873                         /* need to capture a new frame */
2874                         if (locked_btres(fh->btv,RESOURCE_VIDEO)) {
2875                                 up(&fh->cap.lock);
2876                                 return POLLERR;
2877                         }
2878                         fh->cap.read_buf = videobuf_alloc(fh->cap.msize);
2879                         if (NULL == fh->cap.read_buf) {
2880                                 up(&fh->cap.lock);
2881                                 return POLLERR;
2882                         }
2883                         fh->cap.read_buf->memory = V4L2_MEMORY_USERPTR;
2884                         field = videobuf_next_field(&fh->cap);
2885                         if (0 != fh->cap.ops->buf_prepare(file,fh->cap.read_buf,field)) {
2886                                 up(&fh->cap.lock);
2887                                 return POLLERR;
2888                         }
2889                         fh->cap.ops->buf_queue(file,fh->cap.read_buf);
2890                         fh->cap.read_off = 0;
2891                 }
2892                 up(&fh->cap.lock);
2893                 buf = (struct bttv_buffer*)fh->cap.read_buf;
2894         }
2895         
2896         poll_wait(file, &buf->vb.done, wait);
2897         if (buf->vb.state == STATE_DONE ||
2898             buf->vb.state == STATE_ERROR)
2899                 return POLLIN|POLLRDNORM;
2900         return 0;
2901 }
2902
2903 static int bttv_open(struct inode *inode, struct file *file)
2904 {
2905         int minor = iminor(inode);
2906         struct bttv *btv = NULL;
2907         struct bttv_fh *fh;
2908         enum v4l2_buf_type type = 0;
2909         unsigned int i;
2910
2911         dprintk(KERN_DEBUG "bttv: open minor=%d\n",minor);
2912
2913         for (i = 0; i < bttv_num; i++) {
2914                 if (bttvs[i].video_dev &&
2915                     bttvs[i].video_dev->minor == minor) {
2916                         btv = &bttvs[i];
2917                         type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2918                         break;
2919                 }
2920                 if (bttvs[i].vbi_dev &&
2921                     bttvs[i].vbi_dev->minor == minor) {
2922                         btv = &bttvs[i];
2923                         type = V4L2_BUF_TYPE_VBI_CAPTURE;
2924                         break;
2925                 }
2926         }
2927         if (NULL == btv)
2928                 return -ENODEV;
2929
2930         dprintk(KERN_DEBUG "bttv%d: open called (type=%s)\n",
2931                 btv->c.nr,v4l2_type_names[type]);
2932
2933         /* allocate per filehandle data */
2934         fh = kmalloc(sizeof(*fh),GFP_KERNEL);
2935         if (NULL == fh)
2936                 return -ENOMEM;
2937         file->private_data = fh;
2938         *fh = btv->init;
2939         fh->type = type;
2940         fh->ov.setup_ok = 0;
2941 #ifdef VIDIOC_G_PRIORITY
2942         v4l2_prio_open(&btv->prio,&fh->prio);
2943 #endif
2944
2945         videobuf_queue_init(&fh->cap, &bttv_video_qops,
2946                             btv->c.pci, &btv->s_lock,
2947                             V4L2_BUF_TYPE_VIDEO_CAPTURE,
2948                             V4L2_FIELD_INTERLACED,
2949                             sizeof(struct bttv_buffer));
2950         videobuf_queue_init(&fh->vbi, &bttv_vbi_qops,
2951                             btv->c.pci, &btv->s_lock,
2952                             V4L2_BUF_TYPE_VBI_CAPTURE,
2953                             V4L2_FIELD_SEQ_TB,
2954                             sizeof(struct bttv_buffer));
2955         i2c_vidiocschan(btv);
2956
2957         btv->users++;
2958         if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type)
2959                 bttv_vbi_setlines(fh,btv,16);
2960         bttv_field_count(btv);
2961         return 0;
2962 }
2963
2964 static int bttv_release(struct inode *inode, struct file *file)
2965 {
2966         struct bttv_fh *fh = file->private_data;
2967         struct bttv *btv = fh->btv;
2968
2969         /* turn off overlay */
2970         if (check_btres(fh, RESOURCE_OVERLAY))
2971                 bttv_switch_overlay(btv,fh,NULL);
2972         
2973         /* stop video capture */
2974         if (check_btres(fh, RESOURCE_VIDEO)) {
2975                 videobuf_streamoff(file,&fh->cap);
2976                 free_btres(btv,fh,RESOURCE_VIDEO);
2977         }
2978         if (fh->cap.read_buf) {
2979                 buffer_release(file,fh->cap.read_buf);
2980                 kfree(fh->cap.read_buf);
2981         }
2982
2983         /* stop vbi capture */
2984         if (check_btres(fh, RESOURCE_VBI)) {
2985                 if (fh->vbi.streaming)
2986                         videobuf_streamoff(file,&fh->vbi);
2987                 if (fh->vbi.reading)
2988                         videobuf_read_stop(file,&fh->vbi);
2989                 free_btres(btv,fh,RESOURCE_VBI);
2990         }
2991
2992 #ifdef VIDIOC_G_PRIORITY
2993         v4l2_prio_close(&btv->prio,&fh->prio);
2994 #endif
2995         file->private_data = NULL;
2996         kfree(fh);
2997
2998         btv->users--;
2999         bttv_field_count(btv);
3000         return 0;
3001 }
3002
3003 static int
3004 bttv_mmap(struct file *file, struct vm_area_struct *vma)
3005 {
3006         struct bttv_fh *fh = file->private_data;
3007
3008         dprintk("bttv%d: mmap type=%s 0x%lx+%ld\n",
3009                 fh->btv->c.nr, v4l2_type_names[fh->type],
3010                 vma->vm_start, vma->vm_end - vma->vm_start);
3011         return videobuf_mmap_mapper(vma,bttv_queue(fh));
3012 }
3013
3014 static struct file_operations bttv_fops =
3015 {
3016         .owner    = THIS_MODULE,
3017         .open     = bttv_open,
3018         .release  = bttv_release,
3019         .ioctl    = bttv_ioctl,
3020         .llseek   = no_llseek,
3021         .read     = bttv_read,
3022         .mmap     = bttv_mmap,
3023         .poll     = bttv_poll,
3024 };
3025
3026 static struct video_device bttv_video_template =
3027 {
3028         .name     = "UNSET",
3029         .type     = VID_TYPE_CAPTURE|VID_TYPE_TUNER|VID_TYPE_OVERLAY|
3030                     VID_TYPE_CLIPPING|VID_TYPE_SCALES,
3031         .hardware = VID_HARDWARE_BT848,
3032         .fops     = &bttv_fops,
3033         .minor    = -1,
3034 };
3035
3036 struct video_device bttv_vbi_template =
3037 {
3038         .name     = "bt848/878 vbi",
3039         .type     = VID_TYPE_TUNER|VID_TYPE_TELETEXT,
3040         .hardware = VID_HARDWARE_BT848,
3041         .fops     = &bttv_fops,
3042         .minor    = -1,
3043 };
3044
3045 /* ----------------------------------------------------------------------- */
3046 /* radio interface                                                         */
3047
3048 static int radio_open(struct inode *inode, struct file *file)
3049 {
3050         int minor = iminor(inode);
3051         struct bttv *btv = NULL;
3052         unsigned int i;
3053
3054         dprintk("bttv: open minor=%d\n",minor);
3055
3056         for (i = 0; i < bttv_num; i++) {
3057                 if (bttvs[i].radio_dev->minor == minor) {
3058                         btv = &bttvs[i];
3059                         break;
3060                 }
3061         }
3062         if (NULL == btv)
3063                 return -ENODEV;
3064
3065         dprintk("bttv%d: open called (radio)\n",btv->c.nr);
3066         down(&btv->lock);
3067         if (btv->radio_user) {
3068                 up(&btv->lock);
3069                 return -EBUSY;
3070         }
3071         btv->radio_user++;
3072         file->private_data = btv;
3073
3074         i2c_vidiocschan(btv);
3075         bttv_call_i2c_clients(btv,AUDC_SET_RADIO,&btv->tuner_type);
3076         audio_mux(btv,AUDIO_RADIO);
3077
3078         up(&btv->lock);
3079         return 0;
3080 }
3081
3082 static int radio_release(struct inode *inode, struct file *file)
3083 {
3084         struct bttv    *btv = file->private_data;
3085
3086         btv->radio_user--;
3087         return 0;
3088 }
3089
3090 static int radio_do_ioctl(struct inode *inode, struct file *file,
3091                           unsigned int cmd, void *arg)
3092 {
3093         struct bttv    *btv = file->private_data;
3094
3095         switch (cmd) {
3096         case VIDIOCGCAP:
3097         {
3098                 struct video_capability *cap = arg;
3099
3100                 memset(cap,0,sizeof(*cap));
3101                 strcpy(cap->name,btv->radio_dev->name);
3102                 cap->type = VID_TYPE_TUNER;
3103                 cap->channels = 1;
3104                 cap->audios = 1;
3105                 return 0;
3106         }
3107
3108         case VIDIOCGTUNER:
3109         {
3110                 struct video_tuner *v = arg;
3111
3112                 if(v->tuner)
3113                         return -EINVAL;
3114                 memset(v,0,sizeof(*v));
3115                 strcpy(v->name, "Radio");
3116                 /* japan:          76.0 MHz -  89.9 MHz
3117                    western europe: 87.5 MHz - 108.0 MHz
3118                    russia:         65.0 MHz - 108.0 MHz */
3119                 v->rangelow=(int)(65*16);
3120                 v->rangehigh=(int)(108*16);
3121                 bttv_call_i2c_clients(btv,cmd,v);
3122                 return 0;
3123         }
3124         case VIDIOCSTUNER:
3125                 /* nothing to do */
3126                 return 0;
3127         
3128         case BTTV_VERSION:
3129         case VIDIOCGFREQ:
3130         case VIDIOCSFREQ:
3131         case VIDIOCGAUDIO:
3132         case VIDIOCSAUDIO:
3133                 return bttv_common_ioctls(btv,cmd,arg);
3134
3135         default:
3136                 return -ENOIOCTLCMD;
3137         }
3138         return 0;
3139 }
3140
3141 static int radio_ioctl(struct inode *inode, struct file *file,
3142                        unsigned int cmd, unsigned long arg)
3143 {
3144         return video_usercopy(inode, file, cmd, arg, radio_do_ioctl);
3145 }
3146
3147 static struct file_operations radio_fops =
3148 {
3149         .owner    = THIS_MODULE,
3150         .open     = radio_open,
3151         .release  = radio_release,
3152         .ioctl    = radio_ioctl,
3153         .llseek   = no_llseek,
3154 };
3155
3156 static struct video_device radio_template =
3157 {
3158         .name     = "bt848/878 radio",
3159         .type     = VID_TYPE_TUNER,
3160         .hardware = VID_HARDWARE_BT848,
3161         .fops     = &radio_fops,
3162         .minor    = -1,
3163 };
3164
3165 /* ----------------------------------------------------------------------- */
3166 /* irq handler                                                             */
3167
3168 static char *irq_name[] = {
3169         "FMTCHG",  // format change detected (525 vs. 625)
3170         "VSYNC",   // vertical sync (new field)
3171         "HSYNC",   // horizontal sync
3172         "OFLOW",   // chroma/luma AGC overflow
3173         "HLOCK",   // horizontal lock changed
3174         "VPRES",   // video presence changed
3175         "6", "7",
3176         "I2CDONE", // hw irc operation finished
3177         "GPINT",   // gpio port triggered irq
3178         "10",
3179         "RISCI",   // risc instruction triggered irq
3180         "FBUS",    // pixel data fifo dropped data (high pci bus latencies)
3181         "FTRGT",   // pixel data fifo overrun
3182         "FDSR",    // fifo data stream resyncronisation
3183         "PPERR",   // parity error (data transfer)
3184         "RIPERR",  // parity error (read risc instructions)
3185         "PABORT",  // pci abort
3186         "OCERR",   // risc instruction error
3187         "SCERR",   // syncronisation error
3188 };
3189
3190 static void bttv_print_irqbits(u32 print, u32 mark)
3191 {
3192         unsigned int i;
3193         
3194         printk("bits:");
3195         for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
3196                 if (print & (1 << i))
3197                         printk(" %s",irq_name[i]);
3198                 if (mark & (1 << i))
3199                         printk("*");
3200         }
3201 }
3202
3203 static void bttv_print_riscaddr(struct bttv *btv)
3204 {
3205         printk("  main: %08Lx\n",
3206                (unsigned long long)btv->main.dma);
3207         printk("  vbi : o=%08Lx e=%08Lx\n",
3208                btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
3209                btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
3210         printk("  cap : o=%08Lx e=%08Lx\n",
3211                btv->curr.top    ? (unsigned long long)btv->curr.top->top.dma : 0,
3212                btv->curr.bottom ? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
3213         printk("  scr : o=%08Lx e=%08Lx\n",
3214                btv->screen ? (unsigned long long)btv->screen->top.dma  : 0,
3215                btv->screen ? (unsigned long long)btv->screen->bottom.dma : 0);
3216 }
3217
3218 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
3219 {
3220         printk("bttv%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
3221                btv->c.nr,
3222                (unsigned long)btv->main.dma,
3223                (unsigned long)btv->main.cpu[RISC_SLOT_O_VBI+1],
3224                (unsigned long)btv->main.cpu[RISC_SLOT_O_FIELD+1],
3225                (unsigned long)rc);
3226
3227         if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
3228                 printk("bttv%d: Oh, there (temporarely?) is no input signal. "
3229                        "Ok, then this is harmless, don't worry ;)\n",
3230                        btv->c.nr);
3231                 return;
3232         }
3233         printk("bttv%d: Uhm. Looks like we have unusual high IRQ latencies.\n",
3234                btv->c.nr);
3235         printk("bttv%d: Lets try to catch the culpit red-handed ...\n",
3236                btv->c.nr);
3237         dump_stack();
3238 }
3239
3240 static int
3241 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
3242 {
3243         struct bttv_buffer *item;
3244
3245         memset(set,0,sizeof(*set));
3246
3247         /* capture request ? */
3248         if (!list_empty(&btv->capture)) {
3249                 set->irqflags = 1;
3250                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3251                 if (V4L2_FIELD_HAS_TOP(item->vb.field))
3252                         set->top    = item;
3253                 if (V4L2_FIELD_HAS_BOTTOM(item->vb.field))
3254                         set->bottom = item;
3255
3256                 /* capture request for other field ? */
3257                 if (!V4L2_FIELD_HAS_BOTH(item->vb.field) &&
3258                     (item->vb.queue.next != &btv->capture)) {
3259                         item = list_entry(item->vb.queue.next, struct bttv_buffer, vb.queue);
3260                         if (!V4L2_FIELD_HAS_BOTH(item->vb.field)) {
3261                                 if (NULL == set->top &&
3262                                     V4L2_FIELD_TOP == item->vb.field) {
3263                                         set->top = item;
3264                                 }
3265                                 if (NULL == set->bottom &&
3266                                     V4L2_FIELD_BOTTOM == item->vb.field) {
3267                                         set->bottom = item;
3268                                 }
3269                                 if (NULL != set->top  &&  NULL != set->bottom)
3270                                         set->topirq = 2;
3271                         }
3272                 }
3273         }
3274
3275         /* screen overlay ? */
3276         if (NULL != btv->screen) {
3277                 if (V4L2_FIELD_HAS_BOTH(btv->screen->vb.field)) {
3278                         if (NULL == set->top && NULL == set->bottom) {
3279                                 set->top    = btv->screen;
3280                                 set->bottom = btv->screen;
3281                         }
3282                 } else {
3283                         if (V4L2_FIELD_TOP == btv->screen->vb.field &&
3284                             NULL == set->top) {
3285                                 set->top = btv->screen;
3286                         }
3287                         if (V4L2_FIELD_BOTTOM == btv->screen->vb.field &&
3288                             NULL == set->bottom) {
3289                                 set->bottom = btv->screen;
3290                         }
3291                 }
3292         }
3293
3294         dprintk("bttv%d: next set: top=%p bottom=%p [screen=%p,irq=%d,%d]\n",
3295                 btv->c.nr,set->top, set->bottom,
3296                 btv->screen,set->irqflags,set->topirq);
3297         return 0;
3298 }
3299
3300 static void
3301 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
3302                       struct bttv_buffer_set *curr, unsigned int state)
3303 {
3304         struct timeval ts;
3305
3306         do_gettimeofday(&ts);
3307
3308         if (wakeup->top == wakeup->bottom) {
3309                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3310                         if (irq_debug > 1)
3311                                 printk("bttv%d: wakeup: both=%p\n",btv->c.nr,wakeup->top);
3312                         wakeup->top->vb.ts = ts;
3313                         wakeup->top->vb.field_count = btv->field_count;
3314                         wakeup->top->vb.state = state;
3315                         wake_up(&wakeup->top->vb.done);
3316                 }
3317         } else {
3318                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3319                         if (irq_debug > 1)
3320                                 printk("bttv%d: wakeup: top=%p\n",btv->c.nr,wakeup->top);
3321                         wakeup->top->vb.ts = ts;
3322                         wakeup->top->vb.field_count = btv->field_count;
3323                         wakeup->top->vb.state = state;
3324                         wake_up(&wakeup->top->vb.done);
3325                 }
3326                 if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
3327                         if (irq_debug > 1)
3328                                 printk("bttv%d: wakeup: bottom=%p\n",btv->c.nr,wakeup->bottom);
3329                         wakeup->bottom->vb.ts = ts;
3330                         wakeup->bottom->vb.field_count = btv->field_count;
3331                         wakeup->bottom->vb.state = state;
3332                         wake_up(&wakeup->bottom->vb.done);
3333                 }
3334         }
3335 }
3336
3337 static void
3338 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
3339                     unsigned int state)
3340 {
3341         struct timeval ts;
3342
3343         if (NULL == wakeup)
3344                 return;
3345
3346         do_gettimeofday(&ts);
3347         wakeup->vb.ts = ts;
3348         wakeup->vb.field_count = btv->field_count;
3349         wakeup->vb.state = state;
3350         wake_up(&wakeup->vb.done);
3351 }
3352
3353 static void bttv_irq_timeout(unsigned long data)
3354 {
3355         struct bttv *btv = (struct bttv *)data;
3356         struct bttv_buffer_set old,new;
3357         struct bttv_buffer *ovbi;
3358         struct bttv_buffer *item;
3359         unsigned long flags;
3360         
3361         if (bttv_verbose) {
3362                 printk(KERN_INFO "bttv%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
3363                        btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
3364                        btread(BT848_RISC_COUNT));
3365                 bttv_print_irqbits(btread(BT848_INT_STAT),0);
3366                 printk("\n");
3367         }
3368
3369         spin_lock_irqsave(&btv->s_lock,flags);
3370         
3371         /* deactivate stuff */
3372         memset(&new,0,sizeof(new));
3373         old  = btv->curr;
3374         ovbi = btv->cvbi;
3375         btv->curr = new;
3376         btv->cvbi = NULL;
3377         bttv_buffer_activate_video(btv, &new);
3378         bttv_buffer_activate_vbi(btv,   NULL);
3379         bttv_set_dma(btv, 0, 0);
3380
3381         /* wake up */
3382         bttv_irq_wakeup_video(btv, &old, &new, STATE_ERROR);
3383         bttv_irq_wakeup_vbi(btv, ovbi, STATE_ERROR);
3384
3385         /* cancel all outstanding capture / vbi requests */
3386         while (!list_empty(&btv->capture)) {
3387                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3388                 list_del(&item->vb.queue);
3389                 item->vb.state = STATE_ERROR;
3390                 wake_up(&item->vb.done);
3391         }
3392         while (!list_empty(&btv->vcapture)) {
3393                 item = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3394                 list_del(&item->vb.queue);
3395                 item->vb.state = STATE_ERROR;
3396                 wake_up(&item->vb.done);
3397         }
3398         
3399         btv->errors++;
3400         spin_unlock_irqrestore(&btv->s_lock,flags);
3401 }
3402
3403 static void
3404 bttv_irq_wakeup_top(struct bttv *btv)
3405 {
3406         struct bttv_buffer *wakeup = btv->curr.top;
3407
3408         if (NULL == wakeup)
3409                 return;
3410
3411         spin_lock(&btv->s_lock);
3412         btv->curr.topirq = 0;
3413         btv->curr.top = NULL;
3414         bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
3415
3416         do_gettimeofday(&wakeup->vb.ts);
3417         wakeup->vb.field_count = btv->field_count;
3418         wakeup->vb.state = STATE_DONE;
3419         wake_up(&wakeup->vb.done);
3420         spin_unlock(&btv->s_lock);
3421 }
3422
3423 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
3424 {
3425         if (rc < risc->dma)
3426                 return 0;
3427         if (rc > risc->dma + risc->size)
3428                 return 0;
3429         return 1;
3430 }
3431
3432 static void
3433 bttv_irq_switch_video(struct bttv *btv)
3434 {
3435         struct bttv_buffer_set new;
3436         struct bttv_buffer_set old;
3437         dma_addr_t rc;
3438
3439         spin_lock(&btv->s_lock);
3440
3441         /* new buffer set */
3442         bttv_irq_next_video(btv, &new);
3443         rc = btread(BT848_RISC_COUNT);
3444         if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
3445             (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
3446                 btv->framedrop++;
3447                 if (debug_latency)
3448                         bttv_irq_debug_low_latency(btv, rc);
3449                 spin_unlock(&btv->s_lock);
3450                 return;
3451         }
3452         
3453         /* switch over */
3454         old = btv->curr;
3455         btv->curr = new;
3456         bttv_buffer_activate_video(btv, &new);
3457         bttv_set_dma(btv, 0, new.irqflags);
3458
3459         /* switch input */
3460         if (UNSET != btv->new_input) {
3461                 video_mux(btv,btv->new_input);
3462                 btv->new_input = UNSET;
3463         }
3464
3465         /* wake up finished buffers */
3466         bttv_irq_wakeup_video(btv, &old, &new, STATE_DONE);
3467         spin_unlock(&btv->s_lock);
3468 }
3469
3470 static void
3471 bttv_irq_switch_vbi(struct bttv *btv)
3472 {
3473         struct bttv_buffer *new = NULL;
3474         struct bttv_buffer *old;
3475         u32 rc;
3476
3477         spin_lock(&btv->s_lock);
3478
3479         if (!list_empty(&btv->vcapture))
3480                 new = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3481         old = btv->cvbi;
3482
3483         rc = btread(BT848_RISC_COUNT);
3484         if (NULL != old && (is_active(&old->top,    rc) ||
3485                             is_active(&old->bottom, rc))) {
3486                 btv->framedrop++;
3487                 if (debug_latency)
3488                         bttv_irq_debug_low_latency(btv, rc);
3489                 spin_unlock(&btv->s_lock);
3490                 return;
3491         }
3492
3493         /* switch */
3494         btv->cvbi = new;
3495         bttv_buffer_activate_vbi(btv, new);
3496         bttv_set_dma(btv, 0, btv->curr.irqflags);
3497
3498         bttv_irq_wakeup_vbi(btv, old, STATE_DONE);
3499         spin_unlock(&btv->s_lock);
3500 }
3501
3502 static irqreturn_t bttv_irq(int irq, void *dev_id, struct pt_regs * regs)
3503 {
3504         u32 stat,astat;
3505         u32 dstat;
3506         int count;
3507         struct bttv *btv;
3508         int handled = 0;
3509
3510         btv=(struct bttv *)dev_id;
3511         count=0;
3512         while (1) {
3513                 /* get/clear interrupt status bits */
3514                 stat=btread(BT848_INT_STAT);
3515                 astat=stat&btread(BT848_INT_MASK);
3516                 if (!astat)
3517                         break;
3518                 handled = 1;
3519                 btwrite(stat,BT848_INT_STAT);
3520
3521                 /* get device status bits */
3522                 dstat=btread(BT848_DSTATUS);
3523
3524                 if (irq_debug) {
3525                         printk(KERN_DEBUG "bttv%d: irq loop=%d fc=%d "
3526                                "riscs=%x, riscc=%08x, ",
3527                                btv->c.nr, count, btv->field_count,
3528                                stat>>28, btread(BT848_RISC_COUNT));
3529                         bttv_print_irqbits(stat,astat);
3530                         if (stat & BT848_INT_HLOCK)
3531                                 printk("   HLOC => %s", (dstat & BT848_DSTATUS_HLOC)
3532                                        ? "yes" : "no");
3533                         if (stat & BT848_INT_VPRES)
3534                                 printk("   PRES => %s", (dstat & BT848_DSTATUS_PRES)
3535                                        ? "yes" : "no");
3536                         if (stat & BT848_INT_FMTCHG)
3537                                 printk("   NUML => %s", (dstat & BT848_DSTATUS_NUML)
3538                                        ? "625" : "525");
3539                         printk("\n");
3540                 }
3541
3542                 if (astat&BT848_INT_VSYNC) 
3543                         btv->field_count++;
3544
3545                 if (astat & BT848_INT_GPINT) {
3546                         wake_up(&btv->gpioq);
3547                         bttv_gpio_irq(&btv->c);
3548                 }
3549
3550                 if (astat & BT848_INT_I2CDONE) {
3551                         btv->i2c_done = stat;
3552                         wake_up(&btv->i2c_queue);
3553                 }
3554
3555                 if ((astat & BT848_INT_RISCI)  &&  (stat & (4<<28)))
3556                         bttv_irq_switch_vbi(btv);
3557
3558                 if ((astat & BT848_INT_RISCI)  &&  (stat & (2<<28)))
3559                         bttv_irq_wakeup_top(btv);
3560
3561                 if ((astat & BT848_INT_RISCI)  &&  (stat & (1<<28)))
3562                         bttv_irq_switch_video(btv);
3563
3564                 if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3565                         audio_mux(btv, -1);
3566
3567                 if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3568                         printk(KERN_INFO "bttv%d: %s%s @ %08x,",btv->c.nr,
3569                                (astat & BT848_INT_SCERR) ? "SCERR" : "",
3570                                (astat & BT848_INT_OCERR) ? "OCERR" : "",
3571                                btread(BT848_RISC_COUNT));
3572                         bttv_print_irqbits(stat,astat);
3573                         printk("\n");
3574                         if (bttv_debug)
3575                                 bttv_print_riscaddr(btv);
3576                 }
3577                 if (fdsr && astat & BT848_INT_FDSR) {
3578                         printk(KERN_INFO "bttv%d: FDSR @ %08x\n",
3579                                btv->c.nr,btread(BT848_RISC_COUNT));
3580                         if (bttv_debug)
3581                                 bttv_print_riscaddr(btv);
3582                 }
3583
3584                 count++;
3585                 if (count > 4) {
3586                         btwrite(0, BT848_INT_MASK);
3587                         printk(KERN_ERR 
3588                                "bttv%d: IRQ lockup, cleared int mask [", btv->c.nr);
3589                         bttv_print_irqbits(stat,astat);
3590                         printk("]\n");
3591                 }
3592         }
3593         btv->irq_total++;
3594         if (handled)
3595                 btv->irq_me++;
3596         return IRQ_RETVAL(handled);
3597 }
3598
3599
3600 /* ----------------------------------------------------------------------- */
3601 /* initialitation                                                          */
3602
3603 static struct video_device *vdev_init(struct bttv *btv,
3604                                       struct video_device *template,
3605                                       char *type)
3606 {
3607         struct video_device *vfd;
3608
3609         vfd = video_device_alloc();
3610         if (NULL == vfd)
3611                 return NULL;
3612         *vfd = *template;
3613         vfd->minor   = -1;
3614         vfd->dev     = &btv->c.pci->dev;
3615         vfd->release = video_device_release;
3616         snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3617                  btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3618                  type, bttv_tvcards[btv->c.type].name);
3619         return vfd;
3620 }
3621
3622 static void bttv_unregister_video(struct bttv *btv)
3623 {
3624         if (btv->video_dev) {
3625                 if (-1 != btv->video_dev->minor)
3626                         video_unregister_device(btv->video_dev);
3627                 else
3628                         video_device_release(btv->video_dev);
3629                 btv->video_dev = NULL;
3630         }
3631         if (btv->vbi_dev) {
3632                 if (-1 != btv->vbi_dev->minor)
3633                         video_unregister_device(btv->vbi_dev);
3634                 else
3635                         video_device_release(btv->vbi_dev);
3636                 btv->vbi_dev = NULL;
3637         }
3638         if (btv->radio_dev) {
3639                 if (-1 != btv->radio_dev->minor)
3640                         video_unregister_device(btv->radio_dev);
3641                 else
3642                         video_device_release(btv->radio_dev);
3643                 btv->radio_dev = NULL;
3644         }
3645 }
3646
3647 /* register video4linux devices */
3648 static int __devinit bttv_register_video(struct bttv *btv)
3649 {
3650         /* video */
3651         btv->video_dev = vdev_init(btv, &bttv_video_template, "video");
3652         if (NULL == btv->video_dev)
3653                 goto err;
3654         if (video_register_device(btv->video_dev,VFL_TYPE_GRABBER,video_nr)<0)
3655                 goto err;
3656         printk(KERN_INFO "bttv%d: registered device video%d\n",
3657                btv->c.nr,btv->video_dev->minor & 0x1f);
3658         video_device_create_file(btv->video_dev, &class_device_attr_card);
3659
3660         /* vbi */
3661         btv->vbi_dev = vdev_init(btv, &bttv_vbi_template, "vbi");
3662         if (NULL == btv->vbi_dev)
3663                 goto err;
3664         if (video_register_device(btv->vbi_dev,VFL_TYPE_VBI,vbi_nr)<0)
3665                 goto err;
3666         printk(KERN_INFO "bttv%d: registered device vbi%d\n",
3667                btv->c.nr,btv->vbi_dev->minor & 0x1f);
3668
3669         if (!btv->has_radio)
3670                 return 0;
3671         /* radio */
3672         btv->radio_dev = vdev_init(btv, &radio_template, "radio");
3673         if (NULL == btv->radio_dev)
3674                 goto err;
3675         if (video_register_device(btv->radio_dev, VFL_TYPE_RADIO,radio_nr)<0)
3676                 goto err;
3677         printk(KERN_INFO "bttv%d: registered device radio%d\n",
3678                btv->c.nr,btv->radio_dev->minor & 0x1f);
3679
3680         /* all done */
3681         return 0;
3682
3683  err:
3684         bttv_unregister_video(btv);
3685         return -1;
3686 }
3687
3688
3689 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
3690 /* response on cards with no firmware is not enabled by OF */
3691 static void pci_set_command(struct pci_dev *dev)
3692 {
3693 #if defined(__powerpc__)
3694         unsigned int cmd;
3695         
3696         pci_read_config_dword(dev, PCI_COMMAND, &cmd);
3697         cmd = (cmd | PCI_COMMAND_MEMORY ); 
3698         pci_write_config_dword(dev, PCI_COMMAND, cmd);
3699 #endif
3700 }
3701
3702 static int __devinit bttv_probe(struct pci_dev *dev,
3703                                 const struct pci_device_id *pci_id)
3704 {
3705         int result;
3706         unsigned char lat;
3707         struct bttv *btv;
3708
3709         if (bttv_num == BTTV_MAX)
3710                 return -ENOMEM;
3711         printk(KERN_INFO "bttv: Bt8xx card found (%d).\n", bttv_num);
3712         btv=&bttvs[bttv_num];
3713         memset(btv,0,sizeof(*btv));
3714         btv->c.nr  = bttv_num;
3715         sprintf(btv->c.name,"bttv%d",btv->c.nr);
3716
3717         /* initialize structs / fill in defaults */
3718         init_MUTEX(&btv->lock);
3719         init_MUTEX(&btv->reslock);
3720         btv->s_lock    = SPIN_LOCK_UNLOCKED;
3721         btv->gpio_lock = SPIN_LOCK_UNLOCKED;
3722         init_waitqueue_head(&btv->gpioq);
3723         init_waitqueue_head(&btv->i2c_queue);
3724         INIT_LIST_HEAD(&btv->c.subs);
3725         INIT_LIST_HEAD(&btv->capture);
3726         INIT_LIST_HEAD(&btv->vcapture);
3727 #ifdef VIDIOC_G_PRIORITY
3728         v4l2_prio_init(&btv->prio);
3729 #endif
3730
3731         init_timer(&btv->timeout);
3732         btv->timeout.function = bttv_irq_timeout;
3733         btv->timeout.data     = (unsigned long)btv;
3734         
3735         btv->i2c_rc = -1;
3736         btv->tuner_type  = UNSET;
3737         btv->pinnacle_id = UNSET;
3738         btv->new_input   = UNSET;
3739         btv->gpioirq     = 1;
3740         btv->has_radio=radio[btv->c.nr];
3741         
3742         /* pci stuff (init, get irq/mmio, ... */
3743         btv->c.pci = dev;
3744         btv->id  = dev->device;
3745         if (pci_enable_device(dev)) {
3746                 printk(KERN_WARNING "bttv%d: Can't enable device.\n",
3747                        btv->c.nr);
3748                 return -EIO;
3749         }
3750         if (pci_set_dma_mask(dev, 0xffffffff)) {
3751                 printk(KERN_WARNING "bttv%d: No suitable DMA available.\n",
3752                        btv->c.nr);
3753                 return -EIO;
3754         }
3755         if (!request_mem_region(pci_resource_start(dev,0),
3756                                 pci_resource_len(dev,0),
3757                                 btv->c.name)) {
3758                 printk(KERN_WARNING "bttv%d: can't request iomem (0x%lx).\n",
3759                        btv->c.nr, pci_resource_start(dev,0));
3760                 return -EBUSY;
3761         }
3762         pci_set_master(dev);
3763         pci_set_command(dev);
3764         pci_set_drvdata(dev,btv);
3765         if (!pci_dma_supported(dev,0xffffffff)) {
3766                 printk("bttv%d: Oops: no 32bit PCI DMA ???\n", btv->c.nr);
3767                 result = -EIO;
3768                 goto fail1;
3769         }
3770
3771         pci_read_config_byte(dev, PCI_CLASS_REVISION, &btv->revision);
3772         pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
3773         printk(KERN_INFO "bttv%d: Bt%d (rev %d) at %s, ",
3774                bttv_num,btv->id, btv->revision, pci_name(dev));
3775         printk("irq: %d, latency: %d, mmio: 0x%lx\n",
3776                btv->c.pci->irq, lat, pci_resource_start(dev,0));
3777         schedule();
3778         
3779         btv->bt848_mmio=ioremap(pci_resource_start(dev,0), 0x1000);
3780         if (NULL == ioremap(pci_resource_start(dev,0), 0x1000)) {
3781                 printk("bttv%d: ioremap() failed\n", btv->c.nr);
3782                 result = -EIO;
3783                 goto fail1;
3784         }
3785
3786         /* identify card */
3787         bttv_idcard(btv);
3788
3789         /* disable irqs, register irq handler */
3790         btwrite(0, BT848_INT_MASK);
3791         result = request_irq(btv->c.pci->irq, bttv_irq,
3792                              SA_SHIRQ | SA_INTERRUPT,btv->c.name,(void *)btv);
3793         if (result < 0) {
3794                 printk(KERN_ERR "bttv%d: can't get IRQ %d\n",
3795                        bttv_num,btv->c.pci->irq);
3796                 goto fail1;
3797         }
3798
3799         if (0 != bttv_handle_chipset(btv)) {
3800                 result = -EIO;
3801                 goto fail2;
3802         }
3803
3804         /* init options from insmod args */
3805         btv->opt_combfilter = combfilter;
3806         btv->opt_lumafilter = lumafilter;
3807         btv->opt_automute   = automute;
3808         btv->opt_chroma_agc = chroma_agc;
3809         btv->opt_adc_crush  = adc_crush;
3810         btv->opt_vcr_hack   = vcr_hack;
3811         btv->opt_whitecrush_upper  = whitecrush_upper;
3812         btv->opt_whitecrush_lower  = whitecrush_lower;
3813         
3814         /* fill struct bttv with some useful defaults */
3815         btv->init.btv         = btv;
3816         btv->init.ov.w.width  = 320;
3817         btv->init.ov.w.height = 240;
3818         btv->init.fmt         = format_by_palette(VIDEO_PALETTE_RGB24);
3819         btv->init.width       = 320;
3820         btv->init.height      = 240;
3821         btv->init.lines       = 16;
3822         btv->input = 0;
3823
3824         /* initialize hardware */
3825         if (bttv_gpio)
3826                 bttv_gpio_tracking(btv,"pre-init");
3827
3828         bttv_risc_init_main(btv);
3829         init_bt848(btv);
3830
3831         /* gpio */
3832         btwrite(0x00, BT848_GPIO_REG_INP);
3833         btwrite(0x00, BT848_GPIO_OUT_EN);
3834         if (bttv_verbose)
3835                 bttv_gpio_tracking(btv,"init");
3836
3837         /* needs to be done before i2c is registered */
3838         bttv_init_card1(btv);
3839
3840         /* register i2c + gpio */
3841         init_bttv_i2c(btv);
3842
3843         /* some card-specific stuff (needs working i2c) */
3844         bttv_init_card2(btv);
3845         init_irqreg(btv);
3846
3847         /* register video4linux + input */
3848         if (!bttv_tvcards[btv->c.type].no_video) {
3849                 bttv_register_video(btv);
3850                 bt848_bright(btv,32768);
3851                 bt848_contrast(btv,32768);
3852                 bt848_hue(btv,32768);
3853                 bt848_sat(btv,32768);
3854                 audio_mux(btv,AUDIO_MUTE);
3855                 set_input(btv,0);
3856         }
3857
3858         /* add subdevices */
3859         if (btv->has_remote)
3860                 bttv_sub_add_device(&btv->c, "remote");
3861         if (bttv_tvcards[btv->c.type].has_dvb)
3862                 bttv_sub_add_device(&btv->c, "dvb");
3863
3864         /* everything is fine */
3865         bttv_num++;
3866         return 0;
3867
3868  fail2:
3869         free_irq(btv->c.pci->irq,btv);
3870         
3871  fail1:
3872         if (btv->bt848_mmio)
3873                 iounmap(btv->bt848_mmio);
3874         release_mem_region(pci_resource_start(btv->c.pci,0),
3875                            pci_resource_len(btv->c.pci,0));
3876         pci_set_drvdata(dev,NULL);
3877         return result;
3878 }
3879
3880 static void __devexit bttv_remove(struct pci_dev *pci_dev)
3881 {
3882         struct bttv *btv = pci_get_drvdata(pci_dev);
3883
3884         if (bttv_verbose)
3885                 printk("bttv%d: unloading\n",btv->c.nr);
3886
3887         /* shutdown everything (DMA+IRQs) */
3888         btand(~15, BT848_GPIO_DMA_CTL);
3889         btwrite(0, BT848_INT_MASK);
3890         btwrite(~0x0, BT848_INT_STAT);
3891         btwrite(0x0, BT848_GPIO_OUT_EN);
3892         if (bttv_gpio)
3893                 bttv_gpio_tracking(btv,"cleanup");
3894
3895         /* tell gpio modules we are leaving ... */
3896         btv->shutdown=1;
3897         wake_up(&btv->gpioq);
3898         bttv_sub_del_devices(&btv->c);
3899         
3900         /* unregister i2c_bus + input */
3901         fini_bttv_i2c(btv);
3902
3903         /* unregister video4linux */
3904         bttv_unregister_video(btv);
3905
3906         /* free allocated memory */
3907         btcx_riscmem_free(btv->c.pci,&btv->main);
3908
3909         /* free ressources */
3910         free_irq(btv->c.pci->irq,btv);
3911         iounmap(btv->bt848_mmio);
3912         release_mem_region(pci_resource_start(btv->c.pci,0),
3913                            pci_resource_len(btv->c.pci,0));
3914
3915         pci_set_drvdata(pci_dev, NULL);
3916         return;
3917 }
3918
3919 static int bttv_suspend(struct pci_dev *pci_dev, u32 state)
3920 {
3921         struct bttv *btv = pci_get_drvdata(pci_dev);
3922         struct bttv_buffer_set idle;
3923         unsigned long flags;
3924
3925         printk("bttv%d: suspend %d\n", btv->c.nr, state);
3926
3927         /* stop dma + irqs */
3928         spin_lock_irqsave(&btv->s_lock,flags);
3929         memset(&idle, 0, sizeof(idle));
3930         btv->state.video = btv->curr;
3931         btv->state.vbi   = btv->cvbi;
3932         btv->curr = idle;
3933         bttv_buffer_activate_video(btv, &idle);
3934         bttv_buffer_activate_vbi(btv, NULL);
3935         bttv_set_dma(btv, 0, 0);
3936         btwrite(0, BT848_INT_MASK);
3937         spin_unlock_irqrestore(&btv->s_lock,flags);
3938
3939         /* save bt878 state */
3940         btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
3941         btv->state.gpio_data   = gpio_read();
3942
3943         /* save pci state */
3944         pci_save_state(pci_dev, btv->state.pci_cfg);
3945         if (0 != pci_set_power_state(pci_dev, state)) {
3946                 pci_disable_device(pci_dev);
3947                 btv->state.disabled = 1;
3948         }
3949         return 0;
3950 }
3951
3952 static int bttv_resume(struct pci_dev *pci_dev)
3953 {
3954         struct bttv *btv = pci_get_drvdata(pci_dev);
3955         unsigned long flags;
3956
3957         printk("bttv%d: resume\n", btv->c.nr);
3958
3959         /* restore pci state */
3960         if (btv->state.disabled) {
3961                 pci_enable_device(pci_dev);
3962                 btv->state.disabled = 0;
3963         }
3964         pci_set_power_state(pci_dev, 0);
3965         pci_restore_state(pci_dev, btv->state.pci_cfg);
3966
3967         /* restore bt878 state */
3968         bttv_reinit_bt848(btv);
3969         gpio_inout(0xffffff, btv->state.gpio_enable);
3970         gpio_write(btv->state.gpio_data);
3971
3972         /* restart dma */
3973         spin_lock_irqsave(&btv->s_lock,flags);
3974         btv->curr = btv->state.video;
3975         btv->cvbi = btv->state.vbi;
3976         bttv_buffer_activate_video(btv, &btv->curr);
3977         bttv_buffer_activate_vbi(btv, btv->cvbi);
3978         bttv_set_dma(btv, 0, btv->curr.irqflags);
3979         spin_unlock_irqrestore(&btv->s_lock,flags);
3980         return 0;
3981 }
3982
3983 static struct pci_device_id bttv_pci_tbl[] = {
3984         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT848,
3985          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
3986         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT849,
3987          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
3988         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT878,
3989          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
3990         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT879,
3991          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
3992         {0,}
3993 };
3994
3995 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
3996
3997 static struct pci_driver bttv_pci_driver = {
3998         .name     = "bttv",
3999         .id_table = bttv_pci_tbl,
4000         .probe    = bttv_probe,
4001         .remove   = __devexit_p(bttv_remove),
4002
4003         .suspend    = bttv_suspend,
4004         .resume     = bttv_resume,
4005 };
4006
4007 static int bttv_init_module(void)
4008 {
4009         int rc;
4010         bttv_num = 0;
4011
4012         printk(KERN_INFO "bttv: driver version %d.%d.%d loaded\n",
4013                (BTTV_VERSION_CODE >> 16) & 0xff,
4014                (BTTV_VERSION_CODE >> 8) & 0xff,
4015                BTTV_VERSION_CODE & 0xff);
4016 #ifdef SNAPSHOT
4017         printk(KERN_INFO "bttv: snapshot date %04d-%02d-%02d\n",
4018                SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100);
4019 #endif
4020         if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
4021                 gbuffers = 2;
4022         if (gbufsize < 0 || gbufsize > BTTV_MAX_FBUF)
4023                 gbufsize = BTTV_MAX_FBUF;
4024         gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
4025         if (bttv_verbose)
4026                 printk(KERN_INFO "bttv: using %d buffers with %dk (%d pages) each for capture\n",
4027                        gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
4028
4029         bttv_check_chipset();
4030
4031         bus_register(&bttv_sub_bus_type);
4032         rc = pci_module_init(&bttv_pci_driver);
4033         if (-ENODEV == rc) {
4034                 /* plenty of people trying to use bttv for the cx2388x ... */
4035                 if (NULL != pci_find_device(0x14f1, 0x8800, NULL))
4036                         printk("bttv doesn't support your Conexant 2388x card.\n");
4037         }
4038         return rc;
4039 }
4040
4041 static void bttv_cleanup_module(void)
4042 {
4043         pci_unregister_driver(&bttv_pci_driver);
4044         bus_unregister(&bttv_sub_bus_type);
4045         return;
4046 }
4047
4048 module_init(bttv_init_module);
4049 module_exit(bttv_cleanup_module);
4050
4051 /*
4052  * Local variables:
4053  * c-basic-offset: 8
4054  * End:
4055  */