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