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