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