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