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