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