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