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