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