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