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