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