V4L/DVB (6708): pvrusb2: Expand comment in device attributes description
[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         switch (c->id) {
1438         case V4L2_CID_BRIGHTNESS:
1439                 c->value = btv->bright;
1440                 break;
1441         case V4L2_CID_HUE:
1442                 c->value = btv->hue;
1443                 break;
1444         case V4L2_CID_CONTRAST:
1445                 c->value = btv->contrast;
1446                 break;
1447         case V4L2_CID_SATURATION:
1448                 c->value = btv->saturation;
1449                 break;
1450
1451         case V4L2_CID_AUDIO_MUTE:
1452         case V4L2_CID_AUDIO_VOLUME:
1453         case V4L2_CID_AUDIO_BALANCE:
1454         case V4L2_CID_AUDIO_BASS:
1455         case V4L2_CID_AUDIO_TREBLE:
1456                 bttv_call_i2c_clients(btv,VIDIOC_G_CTRL,c);
1457                 break;
1458
1459         case V4L2_CID_PRIVATE_CHROMA_AGC:
1460                 c->value = btv->opt_chroma_agc;
1461                 break;
1462         case V4L2_CID_PRIVATE_COMBFILTER:
1463                 c->value = btv->opt_combfilter;
1464                 break;
1465         case V4L2_CID_PRIVATE_LUMAFILTER:
1466                 c->value = btv->opt_lumafilter;
1467                 break;
1468         case V4L2_CID_PRIVATE_AUTOMUTE:
1469                 c->value = btv->opt_automute;
1470                 break;
1471         case V4L2_CID_PRIVATE_AGC_CRUSH:
1472                 c->value = btv->opt_adc_crush;
1473                 break;
1474         case V4L2_CID_PRIVATE_VCR_HACK:
1475                 c->value = btv->opt_vcr_hack;
1476                 break;
1477         case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1478                 c->value = btv->opt_whitecrush_upper;
1479                 break;
1480         case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1481                 c->value = btv->opt_whitecrush_lower;
1482                 break;
1483         case V4L2_CID_PRIVATE_UV_RATIO:
1484                 c->value = btv->opt_uv_ratio;
1485                 break;
1486         case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1487                 c->value = btv->opt_full_luma_range;
1488                 break;
1489         case V4L2_CID_PRIVATE_CORING:
1490                 c->value = btv->opt_coring;
1491                 break;
1492         default:
1493                 return -EINVAL;
1494         }
1495         return 0;
1496 }
1497
1498 static int set_control(struct bttv *btv, struct v4l2_control *c)
1499 {
1500         int val;
1501
1502         switch (c->id) {
1503         case V4L2_CID_BRIGHTNESS:
1504                 bt848_bright(btv,c->value);
1505                 break;
1506         case V4L2_CID_HUE:
1507                 bt848_hue(btv,c->value);
1508                 break;
1509         case V4L2_CID_CONTRAST:
1510                 bt848_contrast(btv,c->value);
1511                 break;
1512         case V4L2_CID_SATURATION:
1513                 bt848_sat(btv,c->value);
1514                 break;
1515         case V4L2_CID_AUDIO_MUTE:
1516                 audio_mute(btv, c->value);
1517                 /* fall through */
1518         case V4L2_CID_AUDIO_VOLUME:
1519                 if (btv->volume_gpio) {
1520                         btv->volume_gpio (btv, c->value);
1521                 }
1522                 bttv_call_i2c_clients(btv,VIDIOC_S_CTRL,c);
1523                 break;
1524         case V4L2_CID_AUDIO_BALANCE:
1525         case V4L2_CID_AUDIO_BASS:
1526         case V4L2_CID_AUDIO_TREBLE:
1527                 bttv_call_i2c_clients(btv,VIDIOC_S_CTRL,c);
1528                 break;
1529
1530         case V4L2_CID_PRIVATE_CHROMA_AGC:
1531                 btv->opt_chroma_agc = c->value;
1532                 val = btv->opt_chroma_agc ? BT848_SCLOOP_CAGC : 0;
1533                 btwrite(val, BT848_E_SCLOOP);
1534                 btwrite(val, BT848_O_SCLOOP);
1535                 break;
1536         case V4L2_CID_PRIVATE_COMBFILTER:
1537                 btv->opt_combfilter = c->value;
1538                 break;
1539         case V4L2_CID_PRIVATE_LUMAFILTER:
1540                 btv->opt_lumafilter = c->value;
1541                 if (btv->opt_lumafilter) {
1542                         btand(~BT848_CONTROL_LDEC, BT848_E_CONTROL);
1543                         btand(~BT848_CONTROL_LDEC, BT848_O_CONTROL);
1544                 } else {
1545                         btor(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1546                         btor(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1547                 }
1548                 break;
1549         case V4L2_CID_PRIVATE_AUTOMUTE:
1550                 btv->opt_automute = c->value;
1551                 break;
1552         case V4L2_CID_PRIVATE_AGC_CRUSH:
1553                 btv->opt_adc_crush = c->value;
1554                 btwrite(BT848_ADC_RESERVED | (btv->opt_adc_crush ? BT848_ADC_CRUSH : 0),
1555                         BT848_ADC);
1556                 break;
1557         case V4L2_CID_PRIVATE_VCR_HACK:
1558                 btv->opt_vcr_hack = c->value;
1559                 break;
1560         case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1561                 btv->opt_whitecrush_upper = c->value;
1562                 btwrite(c->value, BT848_WC_UP);
1563                 break;
1564         case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1565                 btv->opt_whitecrush_lower = c->value;
1566                 btwrite(c->value, BT848_WC_DOWN);
1567                 break;
1568         case V4L2_CID_PRIVATE_UV_RATIO:
1569                 btv->opt_uv_ratio = c->value;
1570                 bt848_sat(btv, btv->saturation);
1571                 break;
1572         case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1573                 btv->opt_full_luma_range = c->value;
1574                 btaor((c->value<<7), ~BT848_OFORM_RANGE, BT848_OFORM);
1575                 break;
1576         case V4L2_CID_PRIVATE_CORING:
1577                 btv->opt_coring = c->value;
1578                 btaor((c->value<<5), ~BT848_OFORM_CORE32, BT848_OFORM);
1579                 break;
1580         default:
1581                 return -EINVAL;
1582         }
1583         return 0;
1584 }
1585
1586 /* ----------------------------------------------------------------------- */
1587
1588 void bttv_gpio_tracking(struct bttv *btv, char *comment)
1589 {
1590         unsigned int outbits, data;
1591         outbits = btread(BT848_GPIO_OUT_EN);
1592         data    = btread(BT848_GPIO_DATA);
1593         printk(KERN_DEBUG "bttv%d: gpio: en=%08x, out=%08x in=%08x [%s]\n",
1594                btv->c.nr,outbits,data & outbits, data & ~outbits, comment);
1595 }
1596
1597 static void bttv_field_count(struct bttv *btv)
1598 {
1599         int need_count = 0;
1600
1601         if (btv->users)
1602                 need_count++;
1603
1604         if (need_count) {
1605                 /* start field counter */
1606                 btor(BT848_INT_VSYNC,BT848_INT_MASK);
1607         } else {
1608                 /* stop field counter */
1609                 btand(~BT848_INT_VSYNC,BT848_INT_MASK);
1610                 btv->field_count = 0;
1611         }
1612 }
1613
1614 static const struct bttv_format*
1615 format_by_fourcc(int fourcc)
1616 {
1617         unsigned int i;
1618
1619         for (i = 0; i < BTTV_FORMATS; i++) {
1620                 if (-1 == bttv_formats[i].fourcc)
1621                         continue;
1622                 if (bttv_formats[i].fourcc == fourcc)
1623                         return bttv_formats+i;
1624         }
1625         return NULL;
1626 }
1627
1628 /* ----------------------------------------------------------------------- */
1629 /* misc helpers                                                            */
1630
1631 static int
1632 bttv_switch_overlay(struct bttv *btv, struct bttv_fh *fh,
1633                     struct bttv_buffer *new)
1634 {
1635         struct bttv_buffer *old;
1636         unsigned long flags;
1637         int retval = 0;
1638
1639         dprintk("switch_overlay: enter [new=%p]\n",new);
1640         if (new)
1641                 new->vb.state = VIDEOBUF_DONE;
1642         spin_lock_irqsave(&btv->s_lock,flags);
1643         old = btv->screen;
1644         btv->screen = new;
1645         btv->loop_irq |= 1;
1646         bttv_set_dma(btv, 0x03);
1647         spin_unlock_irqrestore(&btv->s_lock,flags);
1648         if (NULL != old) {
1649                 dprintk("switch_overlay: old=%p state is %d\n",old,old->vb.state);
1650                 bttv_dma_free(&fh->cap,btv, old);
1651                 kfree(old);
1652         }
1653         if (NULL == new)
1654                 free_btres(btv,fh,RESOURCE_OVERLAY);
1655         dprintk("switch_overlay: done\n");
1656         return retval;
1657 }
1658
1659 /* ----------------------------------------------------------------------- */
1660 /* video4linux (1) interface                                               */
1661
1662 static int bttv_prepare_buffer(struct videobuf_queue *q,struct bttv *btv,
1663                                struct bttv_buffer *buf,
1664                                const struct bttv_format *fmt,
1665                                unsigned int width, unsigned int height,
1666                                enum v4l2_field field)
1667 {
1668         struct bttv_fh *fh = q->priv_data;
1669         int redo_dma_risc = 0;
1670         struct bttv_crop c;
1671         int norm;
1672         int rc;
1673
1674         /* check settings */
1675         if (NULL == fmt)
1676                 return -EINVAL;
1677         if (fmt->btformat == BT848_COLOR_FMT_RAW) {
1678                 width  = RAW_BPL;
1679                 height = RAW_LINES*2;
1680                 if (width*height > buf->vb.bsize)
1681                         return -EINVAL;
1682                 buf->vb.size = buf->vb.bsize;
1683
1684                 /* Make sure tvnorm and vbi_end remain consistent
1685                    until we're done. */
1686                 mutex_lock(&btv->lock);
1687
1688                 norm = btv->tvnorm;
1689
1690                 /* In this mode capturing always starts at defrect.top
1691                    (default VDELAY), ignoring cropping parameters. */
1692                 if (btv->vbi_end > bttv_tvnorms[norm].cropcap.defrect.top) {
1693                         mutex_unlock(&btv->lock);
1694                         return -EINVAL;
1695                 }
1696
1697                 mutex_unlock(&btv->lock);
1698
1699                 c.rect = bttv_tvnorms[norm].cropcap.defrect;
1700         } else {
1701                 mutex_lock(&btv->lock);
1702
1703                 norm = btv->tvnorm;
1704                 c = btv->crop[!!fh->do_crop];
1705
1706                 mutex_unlock(&btv->lock);
1707
1708                 if (width < c.min_scaled_width ||
1709                     width > c.max_scaled_width ||
1710                     height < c.min_scaled_height)
1711                         return -EINVAL;
1712
1713                 switch (field) {
1714                 case V4L2_FIELD_TOP:
1715                 case V4L2_FIELD_BOTTOM:
1716                 case V4L2_FIELD_ALTERNATE:
1717                         /* btv->crop counts frame lines. Max. scale
1718                            factor is 16:1 for frames, 8:1 for fields. */
1719                         if (height * 2 > c.max_scaled_height)
1720                                 return -EINVAL;
1721                         break;
1722
1723                 default:
1724                         if (height > c.max_scaled_height)
1725                                 return -EINVAL;
1726                         break;
1727                 }
1728
1729                 buf->vb.size = (width * height * fmt->depth) >> 3;
1730                 if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
1731                         return -EINVAL;
1732         }
1733
1734         /* alloc + fill struct bttv_buffer (if changed) */
1735         if (buf->vb.width != width || buf->vb.height != height ||
1736             buf->vb.field != field ||
1737             buf->tvnorm != norm || buf->fmt != fmt ||
1738             buf->crop.top != c.rect.top ||
1739             buf->crop.left != c.rect.left ||
1740             buf->crop.width != c.rect.width ||
1741             buf->crop.height != c.rect.height) {
1742                 buf->vb.width  = width;
1743                 buf->vb.height = height;
1744                 buf->vb.field  = field;
1745                 buf->tvnorm    = norm;
1746                 buf->fmt       = fmt;
1747                 buf->crop      = c.rect;
1748                 redo_dma_risc = 1;
1749         }
1750
1751         /* alloc risc memory */
1752         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
1753                 redo_dma_risc = 1;
1754                 if (0 != (rc = videobuf_iolock(q,&buf->vb,&btv->fbuf)))
1755                         goto fail;
1756         }
1757
1758         if (redo_dma_risc)
1759                 if (0 != (rc = bttv_buffer_risc(btv,buf)))
1760                         goto fail;
1761
1762         buf->vb.state = VIDEOBUF_PREPARED;
1763         return 0;
1764
1765  fail:
1766         bttv_dma_free(q,btv,buf);
1767         return rc;
1768 }
1769
1770 static int
1771 buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
1772 {
1773         struct bttv_fh *fh = q->priv_data;
1774
1775         *size = fh->fmt->depth*fh->width*fh->height >> 3;
1776         if (0 == *count)
1777                 *count = gbuffers;
1778         while (*size * *count > gbuffers * gbufsize)
1779                 (*count)--;
1780         return 0;
1781 }
1782
1783 static int
1784 buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
1785                enum v4l2_field field)
1786 {
1787         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1788         struct bttv_fh *fh = q->priv_data;
1789
1790         return bttv_prepare_buffer(q,fh->btv, buf, fh->fmt,
1791                                    fh->width, fh->height, field);
1792 }
1793
1794 static void
1795 buffer_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
1796 {
1797         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1798         struct bttv_fh *fh = q->priv_data;
1799         struct bttv    *btv = fh->btv;
1800
1801         buf->vb.state = VIDEOBUF_QUEUED;
1802         list_add_tail(&buf->vb.queue,&btv->capture);
1803         if (!btv->curr.frame_irq) {
1804                 btv->loop_irq |= 1;
1805                 bttv_set_dma(btv, 0x03);
1806         }
1807 }
1808
1809 static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
1810 {
1811         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1812         struct bttv_fh *fh = q->priv_data;
1813
1814         bttv_dma_free(q,fh->btv,buf);
1815 }
1816
1817 static struct videobuf_queue_ops bttv_video_qops = {
1818         .buf_setup    = buffer_setup,
1819         .buf_prepare  = buffer_prepare,
1820         .buf_queue    = buffer_queue,
1821         .buf_release  = buffer_release,
1822 };
1823
1824 static int bttv_common_ioctls(struct bttv *btv, unsigned int cmd, void *arg)
1825 {
1826         switch (cmd) {
1827         case VIDIOC_ENUMSTD:
1828         {
1829                 struct v4l2_standard *e = arg;
1830                 unsigned int index = e->index;
1831
1832                 if (index >= BTTV_TVNORMS)
1833                         return -EINVAL;
1834                 v4l2_video_std_construct(e, bttv_tvnorms[e->index].v4l2_id,
1835                                          bttv_tvnorms[e->index].name);
1836                 e->index = index;
1837                 return 0;
1838         }
1839         case VIDIOC_G_STD:
1840         {
1841                 v4l2_std_id *id = arg;
1842                 *id = bttv_tvnorms[btv->tvnorm].v4l2_id;
1843                 return 0;
1844         }
1845         case VIDIOC_S_STD:
1846         {
1847                 v4l2_std_id *id = arg;
1848                 unsigned int i;
1849
1850                 for (i = 0; i < BTTV_TVNORMS; i++)
1851                         if (*id & bttv_tvnorms[i].v4l2_id)
1852                                 break;
1853                 if (i == BTTV_TVNORMS)
1854                         return -EINVAL;
1855
1856                 mutex_lock(&btv->lock);
1857                 set_tvnorm(btv,i);
1858                 mutex_unlock(&btv->lock);
1859                 return 0;
1860         }
1861         case VIDIOC_QUERYSTD:
1862         {
1863                 v4l2_std_id *id = arg;
1864
1865                 if (btread(BT848_DSTATUS) & BT848_DSTATUS_NUML)
1866                         *id = V4L2_STD_625_50;
1867                 else
1868                         *id = V4L2_STD_525_60;
1869                 return 0;
1870         }
1871
1872         case VIDIOC_ENUMINPUT:
1873         {
1874                 struct v4l2_input *i = arg;
1875                 unsigned int n;
1876
1877                 n = i->index;
1878                 if (n >= bttv_tvcards[btv->c.type].video_inputs)
1879                         return -EINVAL;
1880                 memset(i,0,sizeof(*i));
1881                 i->index    = n;
1882                 i->type     = V4L2_INPUT_TYPE_CAMERA;
1883                 i->audioset = 1;
1884                 if (i->index == bttv_tvcards[btv->c.type].tuner) {
1885                         sprintf(i->name, "Television");
1886                         i->type  = V4L2_INPUT_TYPE_TUNER;
1887                         i->tuner = 0;
1888                 } else if (i->index == btv->svhs) {
1889                         sprintf(i->name, "S-Video");
1890                 } else {
1891                         sprintf(i->name,"Composite%d",i->index);
1892                 }
1893                 if (i->index == btv->input) {
1894                         __u32 dstatus = btread(BT848_DSTATUS);
1895                         if (0 == (dstatus & BT848_DSTATUS_PRES))
1896                                 i->status |= V4L2_IN_ST_NO_SIGNAL;
1897                         if (0 == (dstatus & BT848_DSTATUS_HLOC))
1898                                 i->status |= V4L2_IN_ST_NO_H_LOCK;
1899                 }
1900                 for (n = 0; n < BTTV_TVNORMS; n++)
1901                         i->std |= bttv_tvnorms[n].v4l2_id;
1902                 return 0;
1903         }
1904         case VIDIOC_G_INPUT:
1905         {
1906                 int *i = arg;
1907                 *i = btv->input;
1908                 return 0;
1909         }
1910         case VIDIOC_S_INPUT:
1911         {
1912                 unsigned int *i = arg;
1913
1914                 if (*i > bttv_tvcards[btv->c.type].video_inputs)
1915                         return -EINVAL;
1916                 mutex_lock(&btv->lock);
1917                 set_input(btv, *i, btv->tvnorm);
1918                 mutex_unlock(&btv->lock);
1919                 return 0;
1920         }
1921
1922         case VIDIOC_S_TUNER:
1923         {
1924                 struct v4l2_tuner *t = arg;
1925
1926                 if (UNSET == bttv_tvcards[btv->c.type].tuner)
1927                         return -EINVAL;
1928                 if (0 != t->index)
1929                         return -EINVAL;
1930                 mutex_lock(&btv->lock);
1931                 bttv_call_i2c_clients(btv, VIDIOC_S_TUNER, t);
1932
1933                 if (btv->audio_mode_gpio) {
1934                         btv->audio_mode_gpio (btv,t,1);
1935                 }
1936                 mutex_unlock(&btv->lock);
1937                 return 0;
1938         }
1939
1940         case VIDIOC_G_FREQUENCY:
1941         {
1942                 struct v4l2_frequency *f = arg;
1943
1944                 memset(f,0,sizeof(*f));
1945                 f->type = V4L2_TUNER_ANALOG_TV;
1946                 f->frequency = btv->freq;
1947                 return 0;
1948         }
1949         case VIDIOC_S_FREQUENCY:
1950         {
1951                 struct v4l2_frequency *f = arg;
1952
1953                 if (unlikely(f->tuner != 0))
1954                         return -EINVAL;
1955                 if (unlikely (f->type != V4L2_TUNER_ANALOG_TV))
1956                         return -EINVAL;
1957                 mutex_lock(&btv->lock);
1958                 btv->freq = f->frequency;
1959                 bttv_call_i2c_clients(btv,VIDIOC_S_FREQUENCY,f);
1960                 if (btv->has_matchbox && btv->radio_user)
1961                         tea5757_set_freq(btv,btv->freq);
1962                 mutex_unlock(&btv->lock);
1963                 return 0;
1964         }
1965         case VIDIOC_LOG_STATUS:
1966         {
1967                 printk(KERN_INFO "bttv%d: =================  START STATUS CARD #%d  =================\n", btv->c.nr, btv->c.nr);
1968                 bttv_call_i2c_clients(btv, VIDIOC_LOG_STATUS, NULL);
1969                 printk(KERN_INFO "bttv%d: ==================  END STATUS CARD #%d  ==================\n", btv->c.nr, btv->c.nr);
1970                 return 0;
1971         }
1972         case VIDIOC_G_CTRL:
1973                 return get_control(btv,arg);
1974         case VIDIOC_S_CTRL:
1975                 return set_control(btv,arg);
1976 #ifdef CONFIG_VIDEO_ADV_DEBUG
1977         case VIDIOC_DBG_G_REGISTER:
1978         case VIDIOC_DBG_S_REGISTER:
1979         {
1980                 struct v4l2_register *reg = arg;
1981                 if (!capable(CAP_SYS_ADMIN))
1982                         return -EPERM;
1983                 if (!v4l2_chip_match_host(reg->match_type, reg->match_chip))
1984                         return -EINVAL;
1985                 /* bt848 has a 12-bit register space */
1986                 reg->reg &= 0xfff;
1987                 if (cmd == VIDIOC_DBG_G_REGISTER)
1988                         reg->val = btread(reg->reg);
1989                 else
1990                         btwrite(reg->val, reg->reg);
1991                 return 0;
1992         }
1993 #endif
1994
1995         default:
1996                 return -ENOIOCTLCMD;
1997
1998         }
1999         return 0;
2000 }
2001
2002 /* Given cropping boundaries b and the scaled width and height of a
2003    single field or frame, which must not exceed hardware limits, this
2004    function adjusts the cropping parameters c. */
2005 static void
2006 bttv_crop_adjust        (struct bttv_crop *             c,
2007                          const struct v4l2_rect *       b,
2008                          __s32                          width,
2009                          __s32                          height,
2010                          enum v4l2_field                field)
2011 {
2012         __s32 frame_height = height << !V4L2_FIELD_HAS_BOTH(field);
2013         __s32 max_left;
2014         __s32 max_top;
2015
2016         if (width < c->min_scaled_width) {
2017                 /* Max. hor. scale factor 16:1. */
2018                 c->rect.width = width * 16;
2019         } else if (width > c->max_scaled_width) {
2020                 /* Min. hor. scale factor 1:1. */
2021                 c->rect.width = width;
2022
2023                 max_left = b->left + b->width - width;
2024                 max_left = min(max_left, (__s32) MAX_HDELAY);
2025                 if (c->rect.left > max_left)
2026                         c->rect.left = max_left;
2027         }
2028
2029         if (height < c->min_scaled_height) {
2030                 /* Max. vert. scale factor 16:1, single fields 8:1. */
2031                 c->rect.height = height * 16;
2032         } else if (frame_height > c->max_scaled_height) {
2033                 /* Min. vert. scale factor 1:1.
2034                    Top and height count field lines times two. */
2035                 c->rect.height = (frame_height + 1) & ~1;
2036
2037                 max_top = b->top + b->height - c->rect.height;
2038                 if (c->rect.top > max_top)
2039                         c->rect.top = max_top;
2040         }
2041
2042         bttv_crop_calc_limits(c);
2043 }
2044
2045 /* Returns an error if scaling to a frame or single field with the given
2046    width and height is not possible with the current cropping parameters
2047    and width aligned according to width_mask. If adjust_size is TRUE the
2048    function may adjust the width and/or height instead, rounding width
2049    to (width + width_bias) & width_mask. If adjust_crop is TRUE it may
2050    also adjust the current cropping parameters to get closer to the
2051    desired image size. */
2052 static int
2053 limit_scaled_size       (struct bttv_fh *               fh,
2054                          __s32 *                        width,
2055                          __s32 *                        height,
2056                          enum v4l2_field                field,
2057                          unsigned int                   width_mask,
2058                          unsigned int                   width_bias,
2059                          int                            adjust_size,
2060                          int                            adjust_crop)
2061 {
2062         struct bttv *btv = fh->btv;
2063         const struct v4l2_rect *b;
2064         struct bttv_crop *c;
2065         __s32 min_width;
2066         __s32 min_height;
2067         __s32 max_width;
2068         __s32 max_height;
2069         int rc;
2070
2071         BUG_ON((int) width_mask >= 0 ||
2072                width_bias >= (unsigned int) -width_mask);
2073
2074         /* Make sure tvnorm, vbi_end and the current cropping parameters
2075            remain consistent until we're done. */
2076         mutex_lock(&btv->lock);
2077
2078         b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2079
2080         /* Do crop - use current, don't - use default parameters. */
2081         c = &btv->crop[!!fh->do_crop];
2082
2083         if (fh->do_crop
2084             && adjust_size
2085             && adjust_crop
2086             && !locked_btres(btv, VIDEO_RESOURCES)) {
2087                 min_width = 48;
2088                 min_height = 32;
2089
2090                 /* We cannot scale up. When the scaled image is larger
2091                    than crop.rect we adjust the crop.rect as required
2092                    by the V4L2 spec, hence cropcap.bounds are our limit. */
2093                 max_width = min(b->width, (__s32) MAX_HACTIVE);
2094                 max_height = b->height;
2095
2096                 /* We cannot capture the same line as video and VBI data.
2097                    Note btv->vbi_end is really a minimum, see
2098                    bttv_vbi_try_fmt(). */
2099                 if (btv->vbi_end > b->top) {
2100                         max_height -= btv->vbi_end - b->top;
2101                         rc = -EBUSY;
2102                         if (min_height > max_height)
2103                                 goto fail;
2104                 }
2105         } else {
2106                 rc = -EBUSY;
2107                 if (btv->vbi_end > c->rect.top)
2108                         goto fail;
2109
2110                 min_width  = c->min_scaled_width;
2111                 min_height = c->min_scaled_height;
2112                 max_width  = c->max_scaled_width;
2113                 max_height = c->max_scaled_height;
2114
2115                 adjust_crop = 0;
2116         }
2117
2118         min_width = (min_width - width_mask - 1) & width_mask;
2119         max_width = max_width & width_mask;
2120
2121         /* Max. scale factor is 16:1 for frames, 8:1 for fields. */
2122         min_height = min_height;
2123         /* Min. scale factor is 1:1. */
2124         max_height >>= !V4L2_FIELD_HAS_BOTH(field);
2125
2126         if (adjust_size) {
2127                 *width = clamp(*width, min_width, max_width);
2128                 *height = clamp(*height, min_height, max_height);
2129
2130                 /* Round after clamping to avoid overflow. */
2131                 *width = (*width + width_bias) & width_mask;
2132
2133                 if (adjust_crop) {
2134                         bttv_crop_adjust(c, b, *width, *height, field);
2135
2136                         if (btv->vbi_end > c->rect.top) {
2137                                 /* Move the crop window out of the way. */
2138                                 c->rect.top = btv->vbi_end;
2139                         }
2140                 }
2141         } else {
2142                 rc = -EINVAL;
2143                 if (*width  < min_width ||
2144                     *height < min_height ||
2145                     *width  > max_width ||
2146                     *height > max_height ||
2147                     0 != (*width & ~width_mask))
2148                         goto fail;
2149         }
2150
2151         rc = 0; /* success */
2152
2153  fail:
2154         mutex_unlock(&btv->lock);
2155
2156         return rc;
2157 }
2158
2159 /* Returns an error if the given overlay window dimensions are not
2160    possible with the current cropping parameters. If adjust_size is
2161    TRUE the function may adjust the window width and/or height
2162    instead, however it always rounds the horizontal position and
2163    width as btcx_align() does. If adjust_crop is TRUE the function
2164    may also adjust the current cropping parameters to get closer
2165    to the desired window size. */
2166 static int
2167 verify_window           (struct bttv_fh *               fh,
2168                          struct v4l2_window *           win,
2169                          int                            adjust_size,
2170                          int                            adjust_crop)
2171 {
2172         enum v4l2_field field;
2173         unsigned int width_mask;
2174         int rc;
2175
2176         if (win->w.width  < 48 || win->w.height < 32)
2177                 return -EINVAL;
2178         if (win->clipcount > 2048)
2179                 return -EINVAL;
2180
2181         field = win->field;
2182
2183         if (V4L2_FIELD_ANY == field) {
2184                 __s32 height2;
2185
2186                 height2 = fh->btv->crop[!!fh->do_crop].rect.height >> 1;
2187                 field = (win->w.height > height2)
2188                         ? V4L2_FIELD_INTERLACED
2189                         : V4L2_FIELD_TOP;
2190         }
2191         switch (field) {
2192         case V4L2_FIELD_TOP:
2193         case V4L2_FIELD_BOTTOM:
2194         case V4L2_FIELD_INTERLACED:
2195                 break;
2196         default:
2197                 return -EINVAL;
2198         }
2199
2200         /* 4-byte alignment. */
2201         if (NULL == fh->ovfmt)
2202                 return -EINVAL;
2203         width_mask = ~0;
2204         switch (fh->ovfmt->depth) {
2205         case 8:
2206         case 24:
2207                 width_mask = ~3;
2208                 break;
2209         case 16:
2210                 width_mask = ~1;
2211                 break;
2212         case 32:
2213                 break;
2214         default:
2215                 BUG();
2216         }
2217
2218         win->w.width -= win->w.left & ~width_mask;
2219         win->w.left = (win->w.left - width_mask - 1) & width_mask;
2220
2221         rc = limit_scaled_size(fh, &win->w.width, &win->w.height,
2222                                field, width_mask,
2223                                /* width_bias: round down */ 0,
2224                                adjust_size, adjust_crop);
2225         if (0 != rc)
2226                 return rc;
2227
2228         win->field = field;
2229         return 0;
2230 }
2231
2232 static int setup_window(struct bttv_fh *fh, struct bttv *btv,
2233                         struct v4l2_window *win, int fixup)
2234 {
2235         struct v4l2_clip *clips = NULL;
2236         int n,size,retval = 0;
2237
2238         if (NULL == fh->ovfmt)
2239                 return -EINVAL;
2240         if (!(fh->ovfmt->flags & FORMAT_FLAGS_PACKED))
2241                 return -EINVAL;
2242         retval = verify_window(fh, win,
2243                                /* adjust_size */ fixup,
2244                                /* adjust_crop */ fixup);
2245         if (0 != retval)
2246                 return retval;
2247
2248         /* copy clips  --  luckily v4l1 + v4l2 are binary
2249            compatible here ...*/
2250         n = win->clipcount;
2251         size = sizeof(*clips)*(n+4);
2252         clips = kmalloc(size,GFP_KERNEL);
2253         if (NULL == clips)
2254                 return -ENOMEM;
2255         if (n > 0) {
2256                 if (copy_from_user(clips,win->clips,sizeof(struct v4l2_clip)*n)) {
2257                         kfree(clips);
2258                         return -EFAULT;
2259                 }
2260         }
2261         /* clip against screen */
2262         if (NULL != btv->fbuf.base)
2263                 n = btcx_screen_clips(btv->fbuf.fmt.width, btv->fbuf.fmt.height,
2264                                       &win->w, clips, n);
2265         btcx_sort_clips(clips,n);
2266
2267         /* 4-byte alignments */
2268         switch (fh->ovfmt->depth) {
2269         case 8:
2270         case 24:
2271                 btcx_align(&win->w, clips, n, 3);
2272                 break;
2273         case 16:
2274                 btcx_align(&win->w, clips, n, 1);
2275                 break;
2276         case 32:
2277                 /* no alignment fixups needed */
2278                 break;
2279         default:
2280                 BUG();
2281         }
2282
2283         mutex_lock(&fh->cap.lock);
2284                 kfree(fh->ov.clips);
2285         fh->ov.clips    = clips;
2286         fh->ov.nclips   = n;
2287
2288         fh->ov.w        = win->w;
2289         fh->ov.field    = win->field;
2290         fh->ov.setup_ok = 1;
2291         btv->init.ov.w.width   = win->w.width;
2292         btv->init.ov.w.height  = win->w.height;
2293         btv->init.ov.field     = win->field;
2294
2295         /* update overlay if needed */
2296         retval = 0;
2297         if (check_btres(fh, RESOURCE_OVERLAY)) {
2298                 struct bttv_buffer *new;
2299
2300                 new = videobuf_pci_alloc(sizeof(*new));
2301                 new->crop = btv->crop[!!fh->do_crop].rect;
2302                 bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2303                 retval = bttv_switch_overlay(btv,fh,new);
2304         }
2305         mutex_unlock(&fh->cap.lock);
2306         return retval;
2307 }
2308
2309 /* ----------------------------------------------------------------------- */
2310
2311 static struct videobuf_queue* bttv_queue(struct bttv_fh *fh)
2312 {
2313         struct videobuf_queue* q = NULL;
2314
2315         switch (fh->type) {
2316         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2317                 q = &fh->cap;
2318                 break;
2319         case V4L2_BUF_TYPE_VBI_CAPTURE:
2320                 q = &fh->vbi;
2321                 break;
2322         default:
2323                 BUG();
2324         }
2325         return q;
2326 }
2327
2328 static int bttv_resource(struct bttv_fh *fh)
2329 {
2330         int res = 0;
2331
2332         switch (fh->type) {
2333         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2334                 res = RESOURCE_VIDEO_STREAM;
2335                 break;
2336         case V4L2_BUF_TYPE_VBI_CAPTURE:
2337                 res = RESOURCE_VBI;
2338                 break;
2339         default:
2340                 BUG();
2341         }
2342         return res;
2343 }
2344
2345 static int bttv_switch_type(struct bttv_fh *fh, enum v4l2_buf_type type)
2346 {
2347         struct videobuf_queue *q = bttv_queue(fh);
2348         int res = bttv_resource(fh);
2349
2350         if (check_btres(fh,res))
2351                 return -EBUSY;
2352         if (videobuf_queue_is_busy(q))
2353                 return -EBUSY;
2354         fh->type = type;
2355         return 0;
2356 }
2357
2358 static void
2359 pix_format_set_size     (struct v4l2_pix_format *       f,
2360                          const struct bttv_format *     fmt,
2361                          unsigned int                   width,
2362                          unsigned int                   height)
2363 {
2364         f->width = width;
2365         f->height = height;
2366
2367         if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2368                 f->bytesperline = width; /* Y plane */
2369                 f->sizeimage = (width * height * fmt->depth) >> 3;
2370         } else {
2371                 f->bytesperline = (width * fmt->depth) >> 3;
2372                 f->sizeimage = height * f->bytesperline;
2373         }
2374 }
2375
2376 static int bttv_g_fmt(struct bttv_fh *fh, struct v4l2_format *f)
2377 {
2378         switch (f->type) {
2379         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2380                 memset(&f->fmt.pix,0,sizeof(struct v4l2_pix_format));
2381                 pix_format_set_size (&f->fmt.pix, fh->fmt,
2382                                      fh->width, fh->height);
2383                 f->fmt.pix.field        = fh->cap.field;
2384                 f->fmt.pix.pixelformat  = fh->fmt->fourcc;
2385                 return 0;
2386         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2387                 memset(&f->fmt.win,0,sizeof(struct v4l2_window));
2388                 f->fmt.win.w     = fh->ov.w;
2389                 f->fmt.win.field = fh->ov.field;
2390                 return 0;
2391         case V4L2_BUF_TYPE_VBI_CAPTURE:
2392                 bttv_vbi_get_fmt(fh, &f->fmt.vbi);
2393                 return 0;
2394         default:
2395                 return -EINVAL;
2396         }
2397 }
2398
2399 static int bttv_try_fmt(struct bttv_fh *fh, struct bttv *btv,
2400                         struct v4l2_format *f, int adjust_crop)
2401 {
2402         switch (f->type) {
2403         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2404         {
2405                 const struct bttv_format *fmt;
2406                 enum v4l2_field field;
2407                 __s32 width, height;
2408                 int rc;
2409
2410                 fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2411                 if (NULL == fmt)
2412                         return -EINVAL;
2413
2414                 field = f->fmt.pix.field;
2415                 if (V4L2_FIELD_ANY == field) {
2416                         __s32 height2;
2417
2418                         height2 = btv->crop[!!fh->do_crop].rect.height >> 1;
2419                         field = (f->fmt.pix.height > height2)
2420                                 ? V4L2_FIELD_INTERLACED
2421                                 : V4L2_FIELD_BOTTOM;
2422                 }
2423                 if (V4L2_FIELD_SEQ_BT == field)
2424                         field = V4L2_FIELD_SEQ_TB;
2425                 switch (field) {
2426                 case V4L2_FIELD_TOP:
2427                 case V4L2_FIELD_BOTTOM:
2428                 case V4L2_FIELD_ALTERNATE:
2429                 case V4L2_FIELD_INTERLACED:
2430                         break;
2431                 case V4L2_FIELD_SEQ_TB:
2432                         if (fmt->flags & FORMAT_FLAGS_PLANAR)
2433                                 return -EINVAL;
2434                         break;
2435                 default:
2436                         return -EINVAL;
2437                 }
2438
2439                 width = f->fmt.pix.width;
2440                 height = f->fmt.pix.height;
2441
2442                 rc = limit_scaled_size(fh, &width, &height, field,
2443                                        /* width_mask: 4 pixels */ ~3,
2444                                        /* width_bias: nearest */ 2,
2445                                        /* adjust_size */ 1,
2446                                        adjust_crop);
2447                 if (0 != rc)
2448                         return rc;
2449
2450                 /* update data for the application */
2451                 f->fmt.pix.field = field;
2452                 pix_format_set_size(&f->fmt.pix, fmt, width, height);
2453
2454                 return 0;
2455         }
2456         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2457                 return verify_window(fh, &f->fmt.win,
2458                                      /* adjust_size */ 1,
2459                                      /* adjust_crop */ 0);
2460         case V4L2_BUF_TYPE_VBI_CAPTURE:
2461                 return bttv_vbi_try_fmt(fh, &f->fmt.vbi);
2462         default:
2463                 return -EINVAL;
2464         }
2465 }
2466
2467 static int bttv_s_fmt(struct bttv_fh *fh, struct bttv *btv,
2468                       struct v4l2_format *f)
2469 {
2470         int retval;
2471
2472         switch (f->type) {
2473         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2474         {
2475                 const struct bttv_format *fmt;
2476
2477                 retval = bttv_switch_type(fh,f->type);
2478                 if (0 != retval)
2479                         return retval;
2480                 retval = bttv_try_fmt(fh,btv,f, /* adjust_crop */ 1);
2481                 if (0 != retval)
2482                         return retval;
2483                 fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2484
2485                 /* update our state informations */
2486                 mutex_lock(&fh->cap.lock);
2487                 fh->fmt              = fmt;
2488                 fh->cap.field        = f->fmt.pix.field;
2489                 fh->cap.last         = V4L2_FIELD_NONE;
2490                 fh->width            = f->fmt.pix.width;
2491                 fh->height           = f->fmt.pix.height;
2492                 btv->init.fmt        = fmt;
2493                 btv->init.width      = f->fmt.pix.width;
2494                 btv->init.height     = f->fmt.pix.height;
2495                 mutex_unlock(&fh->cap.lock);
2496
2497                 return 0;
2498         }
2499         case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2500                 if (no_overlay > 0) {
2501                         printk ("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2502                         return -EINVAL;
2503                 }
2504                 return setup_window(fh, btv, &f->fmt.win, 1);
2505         case V4L2_BUF_TYPE_VBI_CAPTURE:
2506                 retval = bttv_switch_type(fh,f->type);
2507                 if (0 != retval)
2508                         return retval;
2509                 return bttv_vbi_set_fmt(fh, &f->fmt.vbi);
2510         default:
2511                 return -EINVAL;
2512         }
2513 }
2514
2515 static int bttv_do_ioctl(struct inode *inode, struct file *file,
2516                          unsigned int cmd, void *arg)
2517 {
2518         struct bttv_fh *fh  = file->private_data;
2519         struct bttv    *btv = fh->btv;
2520         int retval = 0;
2521
2522         if (bttv_debug > 1)
2523                 v4l_print_ioctl(btv->c.name, cmd);
2524
2525         if (btv->errors)
2526                 bttv_reinit_bt848(btv);
2527
2528         switch (cmd) {
2529         case VIDIOC_S_CTRL:
2530         case VIDIOC_S_STD:
2531         case VIDIOC_S_INPUT:
2532         case VIDIOC_S_TUNER:
2533         case VIDIOC_S_FREQUENCY:
2534                 retval = v4l2_prio_check(&btv->prio,&fh->prio);
2535                 if (0 != retval)
2536                         return retval;
2537         };
2538
2539         switch (cmd) {
2540 #ifdef CONFIG_VIDEO_V4L1_COMPAT
2541         case VIDIOCGMBUF:
2542         {
2543                 struct video_mbuf *mbuf = arg;
2544                 unsigned int i;
2545
2546                 retval = videobuf_mmap_setup(&fh->cap,gbuffers,gbufsize,
2547                                              V4L2_MEMORY_MMAP);
2548                 if (retval < 0)
2549                         return retval;
2550
2551                 gbuffers = retval;
2552                 memset(mbuf,0,sizeof(*mbuf));
2553                 mbuf->frames = gbuffers;
2554                 mbuf->size   = gbuffers * gbufsize;
2555                 for (i = 0; i < gbuffers; i++)
2556                         mbuf->offsets[i] = i * gbufsize;
2557                 return 0;
2558         }
2559 #endif
2560
2561         /* ***  v4l2  *** ************************************************ */
2562         case VIDIOC_QUERYCAP:
2563         {
2564                 struct v4l2_capability *cap = arg;
2565
2566                 if (0 == v4l2)
2567                         return -EINVAL;
2568                 memset(cap, 0, sizeof (*cap));
2569                 strlcpy(cap->driver, "bttv", sizeof (cap->driver));
2570                 strlcpy(cap->card, btv->video_dev->name, sizeof (cap->card));
2571                 snprintf(cap->bus_info, sizeof (cap->bus_info),
2572                          "PCI:%s", pci_name(btv->c.pci));
2573                 cap->version = BTTV_VERSION_CODE;
2574                 cap->capabilities =
2575                         V4L2_CAP_VIDEO_CAPTURE |
2576                         V4L2_CAP_VBI_CAPTURE |
2577                         V4L2_CAP_READWRITE |
2578                         V4L2_CAP_STREAMING;
2579                 if (no_overlay <= 0)
2580                         cap->capabilities |= V4L2_CAP_VIDEO_OVERLAY;
2581
2582                 if (bttv_tvcards[btv->c.type].tuner != UNSET &&
2583                     bttv_tvcards[btv->c.type].tuner != TUNER_ABSENT)
2584                         cap->capabilities |= V4L2_CAP_TUNER;
2585                 return 0;
2586         }
2587         case VIDIOC_ENUM_FMT:
2588         {
2589                 struct v4l2_fmtdesc *f = arg;
2590                 enum v4l2_buf_type type;
2591                 unsigned int i;
2592                 int index;
2593
2594                 type  = f->type;
2595                 if (V4L2_BUF_TYPE_VBI_CAPTURE == type) {
2596                         /* vbi */
2597                         index = f->index;
2598                         if (0 != index)
2599                                 return -EINVAL;
2600                         memset(f,0,sizeof(*f));
2601                         f->index       = index;
2602                         f->type        = type;
2603                         f->pixelformat = V4L2_PIX_FMT_GREY;
2604                         strcpy(f->description,"vbi data");
2605                         return 0;
2606                 }
2607
2608                 /* video capture + overlay */
2609                 index = -1;
2610                 for (i = 0; i < BTTV_FORMATS; i++) {
2611                         if (bttv_formats[i].fourcc != -1)
2612                                 index++;
2613                         if ((unsigned int)index == f->index)
2614                                 break;
2615                 }
2616                 if (BTTV_FORMATS == i)
2617                         return -EINVAL;
2618
2619                 switch (f->type) {
2620                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2621                         break;
2622                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2623                         if (!(bttv_formats[i].flags & FORMAT_FLAGS_PACKED))
2624                                 return -EINVAL;
2625                         break;
2626                 default:
2627                         return -EINVAL;
2628                 }
2629                 memset(f,0,sizeof(*f));
2630                 f->index       = index;
2631                 f->type        = type;
2632                 f->pixelformat = bttv_formats[i].fourcc;
2633                 strlcpy(f->description,bttv_formats[i].name,sizeof(f->description));
2634                 return 0;
2635         }
2636         case VIDIOC_TRY_FMT:
2637         {
2638                 struct v4l2_format *f = arg;
2639                 return bttv_try_fmt(fh,btv,f, /* adjust_crop */ 0);
2640         }
2641         case VIDIOC_G_FMT:
2642         {
2643                 struct v4l2_format *f = arg;
2644                 return bttv_g_fmt(fh,f);
2645         }
2646         case VIDIOC_S_FMT:
2647         {
2648                 struct v4l2_format *f = arg;
2649                 return bttv_s_fmt(fh,btv,f);
2650         }
2651
2652         case VIDIOC_G_FBUF:
2653         {
2654                 struct v4l2_framebuffer *fb = arg;
2655
2656                 *fb = btv->fbuf;
2657                 fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
2658                 if (fh->ovfmt)
2659                         fb->fmt.pixelformat  = fh->ovfmt->fourcc;
2660                 return 0;
2661         }
2662         case VIDIOC_OVERLAY:
2663         {
2664                 struct bttv_buffer *new;
2665                 int *on = arg;
2666
2667                 if (*on) {
2668                         /* verify args */
2669                         if (NULL == btv->fbuf.base)
2670                                 return -EINVAL;
2671                         if (!fh->ov.setup_ok) {
2672                                 dprintk("bttv%d: overlay: !setup_ok\n",btv->c.nr);
2673                                 return -EINVAL;
2674                         }
2675                 }
2676
2677                 if (!check_alloc_btres(btv,fh,RESOURCE_OVERLAY))
2678                         return -EBUSY;
2679
2680                 mutex_lock(&fh->cap.lock);
2681                 if (*on) {
2682                         fh->ov.tvnorm = btv->tvnorm;
2683                         new = videobuf_pci_alloc(sizeof(*new));
2684                         bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2685                 } else {
2686                         new = NULL;
2687                 }
2688
2689                 /* switch over */
2690                 retval = bttv_switch_overlay(btv,fh,new);
2691                 mutex_unlock(&fh->cap.lock);
2692                 return retval;
2693         }
2694         case VIDIOC_S_FBUF:
2695         {
2696                 struct v4l2_framebuffer *fb = arg;
2697                 const struct bttv_format *fmt;
2698
2699                 if(!capable(CAP_SYS_ADMIN) &&
2700                    !capable(CAP_SYS_RAWIO))
2701                         return -EPERM;
2702
2703                 /* check args */
2704                 fmt = format_by_fourcc(fb->fmt.pixelformat);
2705                 if (NULL == fmt)
2706                         return -EINVAL;
2707                 if (0 == (fmt->flags & FORMAT_FLAGS_PACKED))
2708                         return -EINVAL;
2709
2710                 retval = -EINVAL;
2711                 if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2712                         __s32 width = fb->fmt.width;
2713                         __s32 height = fb->fmt.height;
2714
2715                         retval = limit_scaled_size(fh, &width, &height,
2716                                                    V4L2_FIELD_INTERLACED,
2717                                                    /* width_mask */ ~3,
2718                                                    /* width_bias */ 2,
2719                                                    /* adjust_size */ 0,
2720                                                    /* adjust_crop */ 0);
2721                         if (0 != retval)
2722                                 return retval;
2723                 }
2724
2725                 /* ok, accept it */
2726                 mutex_lock(&fh->cap.lock);
2727                 btv->fbuf.base       = fb->base;
2728                 btv->fbuf.fmt.width  = fb->fmt.width;
2729                 btv->fbuf.fmt.height = fb->fmt.height;
2730                 if (0 != fb->fmt.bytesperline)
2731                         btv->fbuf.fmt.bytesperline = fb->fmt.bytesperline;
2732                 else
2733                         btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fmt->depth/8;
2734
2735                 retval = 0;
2736                 fh->ovfmt = fmt;
2737                 btv->init.ovfmt = fmt;
2738                 if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2739                         fh->ov.w.left   = 0;
2740                         fh->ov.w.top    = 0;
2741                         fh->ov.w.width  = fb->fmt.width;
2742                         fh->ov.w.height = fb->fmt.height;
2743                         btv->init.ov.w.width  = fb->fmt.width;
2744                         btv->init.ov.w.height = fb->fmt.height;
2745                                 kfree(fh->ov.clips);
2746                         fh->ov.clips = NULL;
2747                         fh->ov.nclips = 0;
2748
2749                         if (check_btres(fh, RESOURCE_OVERLAY)) {
2750                                 struct bttv_buffer *new;
2751
2752                                 new = videobuf_pci_alloc(sizeof(*new));
2753                                 new->crop = btv->crop[!!fh->do_crop].rect;
2754                                 bttv_overlay_risc(btv,&fh->ov,fh->ovfmt,new);
2755                                 retval = bttv_switch_overlay(btv,fh,new);
2756                         }
2757                 }
2758                 mutex_unlock(&fh->cap.lock);
2759                 return retval;
2760         }
2761         case VIDIOC_REQBUFS:
2762                 return videobuf_reqbufs(bttv_queue(fh),arg);
2763         case VIDIOC_QUERYBUF:
2764                 return videobuf_querybuf(bttv_queue(fh),arg);
2765         case VIDIOC_QBUF:
2766         {
2767                 int res = bttv_resource(fh);
2768
2769                 if (!check_alloc_btres(btv, fh, res))
2770                         return -EBUSY;
2771                 return videobuf_qbuf(bttv_queue(fh),arg);
2772         }
2773         case VIDIOC_DQBUF:
2774                 return videobuf_dqbuf(bttv_queue(fh),arg,
2775                                       file->f_flags & O_NONBLOCK);
2776         case VIDIOC_STREAMON:
2777         {
2778                 int res = bttv_resource(fh);
2779
2780                 if (!check_alloc_btres(btv,fh,res))
2781                         return -EBUSY;
2782                 return videobuf_streamon(bttv_queue(fh));
2783         }
2784         case VIDIOC_STREAMOFF:
2785         {
2786                 int res = bttv_resource(fh);
2787
2788                 retval = videobuf_streamoff(bttv_queue(fh));
2789                 if (retval < 0)
2790                         return retval;
2791                 free_btres(btv,fh,res);
2792                 return 0;
2793         }
2794
2795         case VIDIOC_QUERYCTRL:
2796         {
2797                 struct v4l2_queryctrl *c = arg;
2798                 int i;
2799
2800                 if ((c->id <  V4L2_CID_BASE ||
2801                      c->id >= V4L2_CID_LASTP1) &&
2802                     (c->id <  V4L2_CID_PRIVATE_BASE ||
2803                      c->id >= V4L2_CID_PRIVATE_LASTP1))
2804                         return -EINVAL;
2805                 for (i = 0; i < BTTV_CTLS; i++)
2806                         if (bttv_ctls[i].id == c->id)
2807                                 break;
2808                 if (i == BTTV_CTLS) {
2809                         *c = no_ctl;
2810                         return 0;
2811                 }
2812                 *c = bttv_ctls[i];
2813
2814                 if (!btv->volume_gpio &&
2815                     (bttv_ctls[i].id == V4L2_CID_AUDIO_VOLUME))
2816                 *c = no_ctl;
2817
2818                 return 0;
2819         }
2820         case VIDIOC_G_PARM:
2821         {
2822                 struct v4l2_streamparm *parm = arg;
2823                 struct v4l2_standard s;
2824                 if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2825                         return -EINVAL;
2826                 memset(parm,0,sizeof(*parm));
2827                 v4l2_video_std_construct(&s, bttv_tvnorms[btv->tvnorm].v4l2_id,
2828                                          bttv_tvnorms[btv->tvnorm].name);
2829                 parm->parm.capture.timeperframe = s.frameperiod;
2830                 return 0;
2831         }
2832         case VIDIOC_G_TUNER:
2833         {
2834                 struct v4l2_tuner *t = arg;
2835
2836                 if (UNSET == bttv_tvcards[btv->c.type].tuner)
2837                         return -EINVAL;
2838                 if (0 != t->index)
2839                         return -EINVAL;
2840                 mutex_lock(&btv->lock);
2841                 memset(t,0,sizeof(*t));
2842                 t->rxsubchans = V4L2_TUNER_SUB_MONO;
2843                 bttv_call_i2c_clients(btv, VIDIOC_G_TUNER, t);
2844                 strcpy(t->name, "Television");
2845                 t->capability = V4L2_TUNER_CAP_NORM;
2846                 t->type       = V4L2_TUNER_ANALOG_TV;
2847                 if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
2848                         t->signal = 0xffff;
2849
2850                 if (btv->audio_mode_gpio) {
2851                         btv->audio_mode_gpio (btv,t,0);
2852                 }
2853
2854                 mutex_unlock(&btv->lock);
2855                 return 0;
2856         }
2857
2858         case VIDIOC_G_PRIORITY:
2859         {
2860                 enum v4l2_priority *p = arg;
2861
2862                 *p = v4l2_prio_max(&btv->prio);
2863                 return 0;
2864         }
2865         case VIDIOC_S_PRIORITY:
2866         {
2867                 enum v4l2_priority *prio = arg;
2868
2869                 return v4l2_prio_change(&btv->prio, &fh->prio, *prio);
2870         }
2871
2872         case VIDIOC_CROPCAP:
2873         {
2874                 struct v4l2_cropcap *cap = arg;
2875                 enum v4l2_buf_type type;
2876
2877                 type = cap->type;
2878
2879                 if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2880                     type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2881                         return -EINVAL;
2882
2883                 *cap = bttv_tvnorms[btv->tvnorm].cropcap;
2884                 cap->type = type;
2885
2886                 return 0;
2887         }
2888         case VIDIOC_G_CROP:
2889         {
2890                 struct v4l2_crop * crop = arg;
2891
2892                 if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2893                     crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2894                         return -EINVAL;
2895
2896                 /* No fh->do_crop = 1; because btv->crop[1] may be
2897                    inconsistent with fh->width or fh->height and apps
2898                    do not expect a change here. */
2899
2900                 crop->c = btv->crop[!!fh->do_crop].rect;
2901
2902                 return 0;
2903         }
2904         case VIDIOC_S_CROP:
2905         {
2906                 struct v4l2_crop *crop = arg;
2907                 const struct v4l2_rect *b;
2908                 struct bttv_crop c;
2909                 __s32 b_left;
2910                 __s32 b_top;
2911                 __s32 b_right;
2912                 __s32 b_bottom;
2913
2914                 if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2915                     crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
2916                         return -EINVAL;
2917
2918                 retval = v4l2_prio_check(&btv->prio,&fh->prio);
2919                 if (0 != retval)
2920                         return retval;
2921
2922                 /* Make sure tvnorm, vbi_end and the current cropping
2923                    parameters remain consistent until we're done. Note
2924                    read() may change vbi_end in check_alloc_btres(). */
2925                 mutex_lock(&btv->lock);
2926
2927                 retval = -EBUSY;
2928
2929                 if (locked_btres(fh->btv, VIDEO_RESOURCES))
2930                         goto btv_unlock_and_return;
2931
2932                 b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2933
2934                 b_left = b->left;
2935                 b_right = b_left + b->width;
2936                 b_bottom = b->top + b->height;
2937
2938                 b_top = max(b->top, btv->vbi_end);
2939                 if (b_top + 32 >= b_bottom)
2940                         goto btv_unlock_and_return;
2941
2942                 /* Min. scaled size 48 x 32. */
2943                 c.rect.left = clamp(crop->c.left, b_left, b_right - 48);
2944                 c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
2945
2946                 c.rect.width = clamp(crop->c.width,
2947                                      48, b_right - c.rect.left);
2948
2949                 c.rect.top = clamp(crop->c.top, b_top, b_bottom - 32);
2950                 /* Top and height must be a multiple of two. */
2951                 c.rect.top = (c.rect.top + 1) & ~1;
2952
2953                 c.rect.height = clamp(crop->c.height,
2954                                       32, b_bottom - c.rect.top);
2955                 c.rect.height = (c.rect.height + 1) & ~1;
2956
2957                 bttv_crop_calc_limits(&c);
2958
2959                 btv->crop[1] = c;
2960
2961                 mutex_unlock(&btv->lock);
2962
2963                 fh->do_crop = 1;
2964
2965                 mutex_lock(&fh->cap.lock);
2966
2967                 if (fh->width < c.min_scaled_width) {
2968                         fh->width = c.min_scaled_width;
2969                         btv->init.width = c.min_scaled_width;
2970                 } else if (fh->width > c.max_scaled_width) {
2971                         fh->width = c.max_scaled_width;
2972                         btv->init.width = c.max_scaled_width;
2973                 }
2974
2975                 if (fh->height < c.min_scaled_height) {
2976                         fh->height = c.min_scaled_height;
2977                         btv->init.height = c.min_scaled_height;
2978                 } else if (fh->height > c.max_scaled_height) {
2979                         fh->height = c.max_scaled_height;
2980                         btv->init.height = c.max_scaled_height;
2981                 }
2982
2983                 mutex_unlock(&fh->cap.lock);
2984
2985                 return 0;
2986         }
2987
2988         case VIDIOC_ENUMSTD:
2989         case VIDIOC_G_STD:
2990         case VIDIOC_S_STD:
2991         case VIDIOC_ENUMINPUT:
2992         case VIDIOC_G_INPUT:
2993         case VIDIOC_S_INPUT:
2994         case VIDIOC_S_TUNER:
2995         case VIDIOC_G_FREQUENCY:
2996         case VIDIOC_S_FREQUENCY:
2997         case VIDIOC_LOG_STATUS:
2998         case VIDIOC_G_CTRL:
2999         case VIDIOC_S_CTRL:
3000         case VIDIOC_DBG_G_REGISTER:
3001         case VIDIOC_DBG_S_REGISTER:
3002                 return bttv_common_ioctls(btv,cmd,arg);
3003         default:
3004                 return v4l_compat_translate_ioctl(inode,file,cmd,arg,
3005                                                   bttv_do_ioctl);
3006         }
3007         return 0;
3008
3009  fh_unlock_and_return:
3010         mutex_unlock(&fh->cap.lock);
3011         return retval;
3012
3013  btv_unlock_and_return:
3014         mutex_unlock(&btv->lock);
3015         return retval;
3016 }
3017
3018 static int bttv_ioctl(struct inode *inode, struct file *file,
3019                       unsigned int cmd, unsigned long arg)
3020 {
3021         return video_usercopy(inode, file, cmd, arg, bttv_do_ioctl);
3022 }
3023
3024 static ssize_t bttv_read(struct file *file, char __user *data,
3025                          size_t count, loff_t *ppos)
3026 {
3027         struct bttv_fh *fh = file->private_data;
3028         int retval = 0;
3029
3030         if (fh->btv->errors)
3031                 bttv_reinit_bt848(fh->btv);
3032         dprintk("bttv%d: read count=%d type=%s\n",
3033                 fh->btv->c.nr,(int)count,v4l2_type_names[fh->type]);
3034
3035         switch (fh->type) {
3036         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
3037                 if (!check_alloc_btres(fh->btv, fh, RESOURCE_VIDEO_READ)) {
3038                         /* VIDEO_READ in use by another fh,
3039                            or VIDEO_STREAM by any fh. */
3040                         return -EBUSY;
3041                 }
3042                 retval = videobuf_read_one(&fh->cap, data, count, ppos,
3043                                            file->f_flags & O_NONBLOCK);
3044                 free_btres(fh->btv, fh, RESOURCE_VIDEO_READ);
3045                 break;
3046         case V4L2_BUF_TYPE_VBI_CAPTURE:
3047                 if (!check_alloc_btres(fh->btv,fh,RESOURCE_VBI))
3048                         return -EBUSY;
3049                 retval = videobuf_read_stream(&fh->vbi, data, count, ppos, 1,
3050                                               file->f_flags & O_NONBLOCK);
3051                 break;
3052         default:
3053                 BUG();
3054         }
3055         return retval;
3056 }
3057
3058 static unsigned int bttv_poll(struct file *file, poll_table *wait)
3059 {
3060         struct bttv_fh *fh = file->private_data;
3061         struct bttv_buffer *buf;
3062         enum v4l2_field field;
3063
3064         if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
3065                 if (!check_alloc_btres(fh->btv,fh,RESOURCE_VBI))
3066                         return POLLERR;
3067                 return videobuf_poll_stream(file, &fh->vbi, wait);
3068         }
3069
3070         if (check_btres(fh,RESOURCE_VIDEO_STREAM)) {
3071                 /* streaming capture */
3072                 if (list_empty(&fh->cap.stream))
3073                         return POLLERR;
3074                 buf = list_entry(fh->cap.stream.next,struct bttv_buffer,vb.stream);
3075         } else {
3076                 /* read() capture */
3077                 mutex_lock(&fh->cap.lock);
3078                 if (NULL == fh->cap.read_buf) {
3079                         /* need to capture a new frame */
3080                         if (locked_btres(fh->btv,RESOURCE_VIDEO_STREAM)) {
3081                                 mutex_unlock(&fh->cap.lock);
3082                                 return POLLERR;
3083                         }
3084                         fh->cap.read_buf = videobuf_pci_alloc(fh->cap.msize);
3085                         if (NULL == fh->cap.read_buf) {
3086                                 mutex_unlock(&fh->cap.lock);
3087                                 return POLLERR;
3088                         }
3089                         fh->cap.read_buf->memory = V4L2_MEMORY_USERPTR;
3090                         field = videobuf_next_field(&fh->cap);
3091                         if (0 != fh->cap.ops->buf_prepare(&fh->cap,fh->cap.read_buf,field)) {
3092                                 kfree (fh->cap.read_buf);
3093                                 fh->cap.read_buf = NULL;
3094                                 mutex_unlock(&fh->cap.lock);
3095                                 return POLLERR;
3096                         }
3097                         fh->cap.ops->buf_queue(&fh->cap,fh->cap.read_buf);
3098                         fh->cap.read_off = 0;
3099                 }
3100                 mutex_unlock(&fh->cap.lock);
3101                 buf = (struct bttv_buffer*)fh->cap.read_buf;
3102         }
3103
3104         poll_wait(file, &buf->vb.done, wait);
3105         if (buf->vb.state == VIDEOBUF_DONE ||
3106             buf->vb.state == VIDEOBUF_ERROR)
3107                 return POLLIN|POLLRDNORM;
3108         return 0;
3109 }
3110
3111 static int bttv_open(struct inode *inode, struct file *file)
3112 {
3113         int minor = iminor(inode);
3114         struct bttv *btv = NULL;
3115         struct bttv_fh *fh;
3116         enum v4l2_buf_type type = 0;
3117         unsigned int i;
3118
3119         dprintk(KERN_DEBUG "bttv: open minor=%d\n",minor);
3120
3121         for (i = 0; i < bttv_num; i++) {
3122                 if (bttvs[i].video_dev &&
3123                     bttvs[i].video_dev->minor == minor) {
3124                         btv = &bttvs[i];
3125                         type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3126                         break;
3127                 }
3128                 if (bttvs[i].vbi_dev &&
3129                     bttvs[i].vbi_dev->minor == minor) {
3130                         btv = &bttvs[i];
3131                         type = V4L2_BUF_TYPE_VBI_CAPTURE;
3132                         break;
3133                 }
3134         }
3135         if (NULL == btv)
3136                 return -ENODEV;
3137
3138         dprintk(KERN_DEBUG "bttv%d: open called (type=%s)\n",
3139                 btv->c.nr,v4l2_type_names[type]);
3140
3141         /* allocate per filehandle data */
3142         fh = kmalloc(sizeof(*fh),GFP_KERNEL);
3143         if (NULL == fh)
3144                 return -ENOMEM;
3145         file->private_data = fh;
3146         *fh = btv->init;
3147         fh->type = type;
3148         fh->ov.setup_ok = 0;
3149         v4l2_prio_open(&btv->prio,&fh->prio);
3150
3151         videobuf_queue_pci_init(&fh->cap, &bttv_video_qops,
3152                             btv->c.pci, &btv->s_lock,
3153                             V4L2_BUF_TYPE_VIDEO_CAPTURE,
3154                             V4L2_FIELD_INTERLACED,
3155                             sizeof(struct bttv_buffer),
3156                             fh);
3157         videobuf_queue_pci_init(&fh->vbi, &bttv_vbi_qops,
3158                             btv->c.pci, &btv->s_lock,
3159                             V4L2_BUF_TYPE_VBI_CAPTURE,
3160                             V4L2_FIELD_SEQ_TB,
3161                             sizeof(struct bttv_buffer),
3162                             fh);
3163         set_tvnorm(btv,btv->tvnorm);
3164
3165         btv->users++;
3166
3167         /* The V4L2 spec requires one global set of cropping parameters
3168            which only change on request. These are stored in btv->crop[1].
3169            However for compatibility with V4L apps and cropping unaware
3170            V4L2 apps we now reset the cropping parameters as seen through
3171            this fh, which is to say VIDIOC_G_CROP and scaling limit checks
3172            will use btv->crop[0], the default cropping parameters for the
3173            current video standard, and VIDIOC_S_FMT will not implicitely
3174            change the cropping parameters until VIDIOC_S_CROP has been
3175            called. */
3176         fh->do_crop = !reset_crop; /* module parameter */
3177
3178         /* Likewise there should be one global set of VBI capture
3179            parameters, but for compatibility with V4L apps and earlier
3180            driver versions each fh has its own parameters. */
3181         bttv_vbi_fmt_reset(&fh->vbi_fmt, btv->tvnorm);
3182
3183         bttv_field_count(btv);
3184         return 0;
3185 }
3186
3187 static int bttv_release(struct inode *inode, struct file *file)
3188 {
3189         struct bttv_fh *fh = file->private_data;
3190         struct bttv *btv = fh->btv;
3191
3192         /* turn off overlay */
3193         if (check_btres(fh, RESOURCE_OVERLAY))
3194                 bttv_switch_overlay(btv,fh,NULL);
3195
3196         /* stop video capture */
3197         if (check_btres(fh, RESOURCE_VIDEO_STREAM)) {
3198                 videobuf_streamoff(&fh->cap);
3199                 free_btres(btv,fh,RESOURCE_VIDEO_STREAM);
3200         }
3201         if (fh->cap.read_buf) {
3202                 buffer_release(&fh->cap,fh->cap.read_buf);
3203                 kfree(fh->cap.read_buf);
3204         }
3205         if (check_btres(fh, RESOURCE_VIDEO_READ)) {
3206                 free_btres(btv, fh, RESOURCE_VIDEO_READ);
3207         }
3208
3209         /* stop vbi capture */
3210         if (check_btres(fh, RESOURCE_VBI)) {
3211                 videobuf_stop(&fh->vbi);
3212                 free_btres(btv,fh,RESOURCE_VBI);
3213         }
3214
3215         /* free stuff */
3216         videobuf_mmap_free(&fh->cap);
3217         videobuf_mmap_free(&fh->vbi);
3218         v4l2_prio_close(&btv->prio,&fh->prio);
3219         file->private_data = NULL;
3220         kfree(fh);
3221
3222         btv->users--;
3223         bttv_field_count(btv);
3224         return 0;
3225 }
3226
3227 static int
3228 bttv_mmap(struct file *file, struct vm_area_struct *vma)
3229 {
3230         struct bttv_fh *fh = file->private_data;
3231
3232         dprintk("bttv%d: mmap type=%s 0x%lx+%ld\n",
3233                 fh->btv->c.nr, v4l2_type_names[fh->type],
3234                 vma->vm_start, vma->vm_end - vma->vm_start);
3235         return videobuf_mmap_mapper(bttv_queue(fh),vma);
3236 }
3237
3238 static const struct file_operations bttv_fops =
3239 {
3240         .owner    = THIS_MODULE,
3241         .open     = bttv_open,
3242         .release  = bttv_release,
3243         .ioctl    = bttv_ioctl,
3244         .compat_ioctl   = v4l_compat_ioctl32,
3245         .llseek   = no_llseek,
3246         .read     = bttv_read,
3247         .mmap     = bttv_mmap,
3248         .poll     = bttv_poll,
3249 };
3250
3251 static struct video_device bttv_video_template =
3252 {
3253         .name     = "UNSET",
3254         .type     = VID_TYPE_CAPTURE|VID_TYPE_TUNER|
3255                     VID_TYPE_CLIPPING|VID_TYPE_SCALES,
3256         .fops     = &bttv_fops,
3257         .minor    = -1,
3258 };
3259
3260 static struct video_device bttv_vbi_template =
3261 {
3262         .name     = "bt848/878 vbi",
3263         .type     = VID_TYPE_TUNER|VID_TYPE_TELETEXT,
3264         .fops     = &bttv_fops,
3265         .minor    = -1,
3266 };
3267
3268 /* ----------------------------------------------------------------------- */
3269 /* radio interface                                                         */
3270
3271 static int radio_open(struct inode *inode, struct file *file)
3272 {
3273         int minor = iminor(inode);
3274         struct bttv *btv = NULL;
3275         unsigned int i;
3276
3277         dprintk("bttv: open minor=%d\n",minor);
3278
3279         for (i = 0; i < bttv_num; i++) {
3280                 if (bttvs[i].radio_dev->minor == minor) {
3281                         btv = &bttvs[i];
3282                         break;
3283                 }
3284         }
3285         if (NULL == btv)
3286                 return -ENODEV;
3287
3288         dprintk("bttv%d: open called (radio)\n",btv->c.nr);
3289         mutex_lock(&btv->lock);
3290
3291         btv->radio_user++;
3292
3293         file->private_data = btv;
3294
3295         bttv_call_i2c_clients(btv,AUDC_SET_RADIO,NULL);
3296         audio_input(btv,TVAUDIO_INPUT_RADIO);
3297
3298         mutex_unlock(&btv->lock);
3299         return 0;
3300 }
3301
3302 static int radio_release(struct inode *inode, struct file *file)
3303 {
3304         struct bttv        *btv = file->private_data;
3305         struct rds_command cmd;
3306
3307         btv->radio_user--;
3308
3309         bttv_call_i2c_clients(btv, RDS_CMD_CLOSE, &cmd);
3310
3311         return 0;
3312 }
3313
3314 static int radio_do_ioctl(struct inode *inode, struct file *file,
3315                           unsigned int cmd, void *arg)
3316 {
3317         struct bttv    *btv = file->private_data;
3318
3319         switch (cmd) {
3320         case VIDIOC_QUERYCAP:
3321         {
3322                 struct v4l2_capability *cap = arg;
3323
3324                 memset(cap,0,sizeof(*cap));
3325                 strcpy(cap->driver, "bttv");
3326                 strlcpy(cap->card, btv->radio_dev->name,sizeof(cap->card));
3327                 sprintf(cap->bus_info,"PCI:%s",pci_name(btv->c.pci));
3328                 cap->version = BTTV_VERSION_CODE;
3329                 cap->capabilities = V4L2_CAP_TUNER;
3330                 return 0;
3331         }
3332         case VIDIOC_G_TUNER:
3333         {
3334                 struct v4l2_tuner *t = arg;
3335
3336                 if (UNSET == bttv_tvcards[btv->c.type].tuner)
3337                         return -EINVAL;
3338                 if (0 != t->index)
3339                         return -EINVAL;
3340                 mutex_lock(&btv->lock);
3341                 memset(t,0,sizeof(*t));
3342                 strcpy(t->name, "Radio");
3343                 t->type = V4L2_TUNER_RADIO;
3344
3345                 bttv_call_i2c_clients(btv, VIDIOC_G_TUNER, t);
3346
3347                 if (btv->audio_mode_gpio) {
3348                         btv->audio_mode_gpio (btv,t,0);
3349                 }
3350
3351                 mutex_unlock(&btv->lock);
3352
3353                 return 0;
3354         }
3355         case VIDIOC_S_TUNER:
3356         case VIDIOC_G_FREQUENCY:
3357         case VIDIOC_S_FREQUENCY:
3358         case VIDIOC_G_CTRL:
3359         case VIDIOC_S_CTRL:
3360         case VIDIOC_LOG_STATUS:
3361         case VIDIOC_DBG_G_REGISTER:
3362         case VIDIOC_DBG_S_REGISTER:
3363                 return bttv_common_ioctls(btv,cmd,arg);
3364         default:
3365                 return v4l_compat_translate_ioctl(inode,file,cmd,arg,
3366                                                   radio_do_ioctl);
3367         }
3368         return 0;
3369 }
3370
3371 static int radio_ioctl(struct inode *inode, struct file *file,
3372                        unsigned int cmd, unsigned long arg)
3373 {
3374         return video_usercopy(inode, file, cmd, arg, radio_do_ioctl);
3375 }
3376
3377 static ssize_t radio_read(struct file *file, char __user *data,
3378                          size_t count, loff_t *ppos)
3379 {
3380         struct bttv    *btv = file->private_data;
3381         struct rds_command cmd;
3382         cmd.block_count = count/3;
3383         cmd.buffer = data;
3384         cmd.instance = file;
3385         cmd.result = -ENODEV;
3386
3387         bttv_call_i2c_clients(btv, RDS_CMD_READ, &cmd);
3388
3389         return cmd.result;
3390 }
3391
3392 static unsigned int radio_poll(struct file *file, poll_table *wait)
3393 {
3394         struct bttv    *btv = file->private_data;
3395         struct rds_command cmd;
3396         cmd.instance = file;
3397         cmd.event_list = wait;
3398         cmd.result = -ENODEV;
3399         bttv_call_i2c_clients(btv, RDS_CMD_POLL, &cmd);
3400
3401         return cmd.result;
3402 }
3403
3404 static const struct file_operations radio_fops =
3405 {
3406         .owner    = THIS_MODULE,
3407         .open     = radio_open,
3408         .read     = radio_read,
3409         .release  = radio_release,
3410         .ioctl    = radio_ioctl,
3411         .llseek   = no_llseek,
3412         .poll     = radio_poll,
3413 };
3414
3415 static struct video_device radio_template =
3416 {
3417         .name     = "bt848/878 radio",
3418         .type     = VID_TYPE_TUNER,
3419         .fops     = &radio_fops,
3420         .minor    = -1,
3421 };
3422
3423 /* ----------------------------------------------------------------------- */
3424 /* some debug code                                                         */
3425
3426 static int bttv_risc_decode(u32 risc)
3427 {
3428         static char *instr[16] = {
3429                 [ BT848_RISC_WRITE     >> 28 ] = "write",
3430                 [ BT848_RISC_SKIP      >> 28 ] = "skip",
3431                 [ BT848_RISC_WRITEC    >> 28 ] = "writec",
3432                 [ BT848_RISC_JUMP      >> 28 ] = "jump",
3433                 [ BT848_RISC_SYNC      >> 28 ] = "sync",
3434                 [ BT848_RISC_WRITE123  >> 28 ] = "write123",
3435                 [ BT848_RISC_SKIP123   >> 28 ] = "skip123",
3436                 [ BT848_RISC_WRITE1S23 >> 28 ] = "write1s23",
3437         };
3438         static int incr[16] = {
3439                 [ BT848_RISC_WRITE     >> 28 ] = 2,
3440                 [ BT848_RISC_JUMP      >> 28 ] = 2,
3441                 [ BT848_RISC_SYNC      >> 28 ] = 2,
3442                 [ BT848_RISC_WRITE123  >> 28 ] = 5,
3443                 [ BT848_RISC_SKIP123   >> 28 ] = 2,
3444                 [ BT848_RISC_WRITE1S23 >> 28 ] = 3,
3445         };
3446         static char *bits[] = {
3447                 "be0",  "be1",  "be2",  "be3/resync",
3448                 "set0", "set1", "set2", "set3",
3449                 "clr0", "clr1", "clr2", "clr3",
3450                 "irq",  "res",  "eol",  "sol",
3451         };
3452         int i;
3453
3454         printk("0x%08x [ %s", risc,
3455                instr[risc >> 28] ? instr[risc >> 28] : "INVALID");
3456         for (i = ARRAY_SIZE(bits)-1; i >= 0; i--)
3457                 if (risc & (1 << (i + 12)))
3458                         printk(" %s",bits[i]);
3459         printk(" count=%d ]\n", risc & 0xfff);
3460         return incr[risc >> 28] ? incr[risc >> 28] : 1;
3461 }
3462
3463 static void bttv_risc_disasm(struct bttv *btv,
3464                              struct btcx_riscmem *risc)
3465 {
3466         unsigned int i,j,n;
3467
3468         printk("%s: risc disasm: %p [dma=0x%08lx]\n",
3469                btv->c.name, risc->cpu, (unsigned long)risc->dma);
3470         for (i = 0; i < (risc->size >> 2); i += n) {
3471                 printk("%s:   0x%lx: ", btv->c.name,
3472                        (unsigned long)(risc->dma + (i<<2)));
3473                 n = bttv_risc_decode(risc->cpu[i]);
3474                 for (j = 1; j < n; j++)
3475                         printk("%s:   0x%lx: 0x%08x [ arg #%d ]\n",
3476                                btv->c.name, (unsigned long)(risc->dma + ((i+j)<<2)),
3477                                risc->cpu[i+j], j);
3478                 if (0 == risc->cpu[i])
3479                         break;
3480         }
3481 }
3482
3483 static void bttv_print_riscaddr(struct bttv *btv)
3484 {
3485         printk("  main: %08Lx\n",
3486                (unsigned long long)btv->main.dma);
3487         printk("  vbi : o=%08Lx e=%08Lx\n",
3488                btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
3489                btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
3490         printk("  cap : o=%08Lx e=%08Lx\n",
3491                btv->curr.top    ? (unsigned long long)btv->curr.top->top.dma : 0,
3492                btv->curr.bottom ? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
3493         printk("  scr : o=%08Lx e=%08Lx\n",
3494                btv->screen ? (unsigned long long)btv->screen->top.dma : 0,
3495                btv->screen ? (unsigned long long)btv->screen->bottom.dma : 0);
3496         bttv_risc_disasm(btv, &btv->main);
3497 }
3498
3499 /* ----------------------------------------------------------------------- */
3500 /* irq handler                                                             */
3501
3502 static char *irq_name[] = {
3503         "FMTCHG",  // format change detected (525 vs. 625)
3504         "VSYNC",   // vertical sync (new field)
3505         "HSYNC",   // horizontal sync
3506         "OFLOW",   // chroma/luma AGC overflow
3507         "HLOCK",   // horizontal lock changed
3508         "VPRES",   // video presence changed
3509         "6", "7",
3510         "I2CDONE", // hw irc operation finished
3511         "GPINT",   // gpio port triggered irq
3512         "10",
3513         "RISCI",   // risc instruction triggered irq
3514         "FBUS",    // pixel data fifo dropped data (high pci bus latencies)
3515         "FTRGT",   // pixel data fifo overrun
3516         "FDSR",    // fifo data stream resyncronisation
3517         "PPERR",   // parity error (data transfer)
3518         "RIPERR",  // parity error (read risc instructions)
3519         "PABORT",  // pci abort
3520         "OCERR",   // risc instruction error
3521         "SCERR",   // syncronisation error
3522 };
3523
3524 static void bttv_print_irqbits(u32 print, u32 mark)
3525 {
3526         unsigned int i;
3527
3528         printk("bits:");
3529         for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
3530                 if (print & (1 << i))
3531                         printk(" %s",irq_name[i]);
3532                 if (mark & (1 << i))
3533                         printk("*");
3534         }
3535 }
3536
3537 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
3538 {
3539         printk("bttv%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
3540                btv->c.nr,
3541                (unsigned long)btv->main.dma,
3542                (unsigned long)btv->main.cpu[RISC_SLOT_O_VBI+1],
3543                (unsigned long)btv->main.cpu[RISC_SLOT_O_FIELD+1],
3544                (unsigned long)rc);
3545
3546         if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
3547                 printk("bttv%d: Oh, there (temporarely?) is no input signal. "
3548                        "Ok, then this is harmless, don't worry ;)\n",
3549                        btv->c.nr);
3550                 return;
3551         }
3552         printk("bttv%d: Uhm. Looks like we have unusual high IRQ latencies.\n",
3553                btv->c.nr);
3554         printk("bttv%d: Lets try to catch the culpit red-handed ...\n",
3555                btv->c.nr);
3556         dump_stack();
3557 }
3558
3559 static int
3560 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
3561 {
3562         struct bttv_buffer *item;
3563
3564         memset(set,0,sizeof(*set));
3565
3566         /* capture request ? */
3567         if (!list_empty(&btv->capture)) {
3568                 set->frame_irq = 1;
3569                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3570                 if (V4L2_FIELD_HAS_TOP(item->vb.field))
3571                         set->top    = item;
3572                 if (V4L2_FIELD_HAS_BOTTOM(item->vb.field))
3573                         set->bottom = item;
3574
3575                 /* capture request for other field ? */
3576                 if (!V4L2_FIELD_HAS_BOTH(item->vb.field) &&
3577                     (item->vb.queue.next != &btv->capture)) {
3578                         item = list_entry(item->vb.queue.next, struct bttv_buffer, vb.queue);
3579                         if (!V4L2_FIELD_HAS_BOTH(item->vb.field)) {
3580                                 if (NULL == set->top &&
3581                                     V4L2_FIELD_TOP == item->vb.field) {
3582                                         set->top = item;
3583                                 }
3584                                 if (NULL == set->bottom &&
3585                                     V4L2_FIELD_BOTTOM == item->vb.field) {
3586                                         set->bottom = item;
3587                                 }
3588                                 if (NULL != set->top  &&  NULL != set->bottom)
3589                                         set->top_irq = 2;
3590                         }
3591                 }
3592         }
3593
3594         /* screen overlay ? */
3595         if (NULL != btv->screen) {
3596                 if (V4L2_FIELD_HAS_BOTH(btv->screen->vb.field)) {
3597                         if (NULL == set->top && NULL == set->bottom) {
3598                                 set->top    = btv->screen;
3599                                 set->bottom = btv->screen;
3600                         }
3601                 } else {
3602                         if (V4L2_FIELD_TOP == btv->screen->vb.field &&
3603                             NULL == set->top) {
3604                                 set->top = btv->screen;
3605                         }
3606                         if (V4L2_FIELD_BOTTOM == btv->screen->vb.field &&
3607                             NULL == set->bottom) {
3608                                 set->bottom = btv->screen;
3609                         }
3610                 }
3611         }
3612
3613         dprintk("bttv%d: next set: top=%p bottom=%p [screen=%p,irq=%d,%d]\n",
3614                 btv->c.nr,set->top, set->bottom,
3615                 btv->screen,set->frame_irq,set->top_irq);
3616         return 0;
3617 }
3618
3619 static void
3620 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
3621                       struct bttv_buffer_set *curr, unsigned int state)
3622 {
3623         struct timeval ts;
3624
3625         do_gettimeofday(&ts);
3626
3627         if (wakeup->top == wakeup->bottom) {
3628                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3629                         if (irq_debug > 1)
3630                                 printk("bttv%d: wakeup: both=%p\n",btv->c.nr,wakeup->top);
3631                         wakeup->top->vb.ts = ts;
3632                         wakeup->top->vb.field_count = btv->field_count;
3633                         wakeup->top->vb.state = state;
3634                         wake_up(&wakeup->top->vb.done);
3635                 }
3636         } else {
3637                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3638                         if (irq_debug > 1)
3639                                 printk("bttv%d: wakeup: top=%p\n",btv->c.nr,wakeup->top);
3640                         wakeup->top->vb.ts = ts;
3641                         wakeup->top->vb.field_count = btv->field_count;
3642                         wakeup->top->vb.state = state;
3643                         wake_up(&wakeup->top->vb.done);
3644                 }
3645                 if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
3646                         if (irq_debug > 1)
3647                                 printk("bttv%d: wakeup: bottom=%p\n",btv->c.nr,wakeup->bottom);
3648                         wakeup->bottom->vb.ts = ts;
3649                         wakeup->bottom->vb.field_count = btv->field_count;
3650                         wakeup->bottom->vb.state = state;
3651                         wake_up(&wakeup->bottom->vb.done);
3652                 }
3653         }
3654 }
3655
3656 static void
3657 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
3658                     unsigned int state)
3659 {
3660         struct timeval ts;
3661
3662         if (NULL == wakeup)
3663                 return;
3664
3665         do_gettimeofday(&ts);
3666         wakeup->vb.ts = ts;
3667         wakeup->vb.field_count = btv->field_count;
3668         wakeup->vb.state = state;
3669         wake_up(&wakeup->vb.done);
3670 }
3671
3672 static void bttv_irq_timeout(unsigned long data)
3673 {
3674         struct bttv *btv = (struct bttv *)data;
3675         struct bttv_buffer_set old,new;
3676         struct bttv_buffer *ovbi;
3677         struct bttv_buffer *item;
3678         unsigned long flags;
3679
3680         if (bttv_verbose) {
3681                 printk(KERN_INFO "bttv%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
3682                        btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
3683                        btread(BT848_RISC_COUNT));
3684                 bttv_print_irqbits(btread(BT848_INT_STAT),0);
3685                 printk("\n");
3686         }
3687
3688         spin_lock_irqsave(&btv->s_lock,flags);
3689
3690         /* deactivate stuff */
3691         memset(&new,0,sizeof(new));
3692         old  = btv->curr;
3693         ovbi = btv->cvbi;
3694         btv->curr = new;
3695         btv->cvbi = NULL;
3696         btv->loop_irq = 0;
3697         bttv_buffer_activate_video(btv, &new);
3698         bttv_buffer_activate_vbi(btv,   NULL);
3699         bttv_set_dma(btv, 0);
3700
3701         /* wake up */
3702         bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_ERROR);
3703         bttv_irq_wakeup_vbi(btv, ovbi, VIDEOBUF_ERROR);
3704
3705         /* cancel all outstanding capture / vbi requests */
3706         while (!list_empty(&btv->capture)) {
3707                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3708                 list_del(&item->vb.queue);
3709                 item->vb.state = VIDEOBUF_ERROR;
3710                 wake_up(&item->vb.done);
3711         }
3712         while (!list_empty(&btv->vcapture)) {
3713                 item = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3714                 list_del(&item->vb.queue);
3715                 item->vb.state = VIDEOBUF_ERROR;
3716                 wake_up(&item->vb.done);
3717         }
3718
3719         btv->errors++;
3720         spin_unlock_irqrestore(&btv->s_lock,flags);
3721 }
3722
3723 static void
3724 bttv_irq_wakeup_top(struct bttv *btv)
3725 {
3726         struct bttv_buffer *wakeup = btv->curr.top;
3727
3728         if (NULL == wakeup)
3729                 return;
3730
3731         spin_lock(&btv->s_lock);
3732         btv->curr.top_irq = 0;
3733         btv->curr.top = NULL;
3734         bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
3735
3736         do_gettimeofday(&wakeup->vb.ts);
3737         wakeup->vb.field_count = btv->field_count;
3738         wakeup->vb.state = VIDEOBUF_DONE;
3739         wake_up(&wakeup->vb.done);
3740         spin_unlock(&btv->s_lock);
3741 }
3742
3743 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
3744 {
3745         if (rc < risc->dma)
3746                 return 0;
3747         if (rc > risc->dma + risc->size)
3748                 return 0;
3749         return 1;
3750 }
3751
3752 static void
3753 bttv_irq_switch_video(struct bttv *btv)
3754 {
3755         struct bttv_buffer_set new;
3756         struct bttv_buffer_set old;
3757         dma_addr_t rc;
3758
3759         spin_lock(&btv->s_lock);
3760
3761         /* new buffer set */
3762         bttv_irq_next_video(btv, &new);
3763         rc = btread(BT848_RISC_COUNT);
3764         if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
3765             (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
3766                 btv->framedrop++;
3767                 if (debug_latency)
3768                         bttv_irq_debug_low_latency(btv, rc);
3769                 spin_unlock(&btv->s_lock);
3770                 return;
3771         }
3772
3773         /* switch over */
3774         old = btv->curr;
3775         btv->curr = new;
3776         btv->loop_irq &= ~1;
3777         bttv_buffer_activate_video(btv, &new);
3778         bttv_set_dma(btv, 0);
3779
3780         /* switch input */
3781         if (UNSET != btv->new_input) {
3782                 video_mux(btv,btv->new_input);
3783                 btv->new_input = UNSET;
3784         }
3785
3786         /* wake up finished buffers */
3787         bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_DONE);
3788         spin_unlock(&btv->s_lock);
3789 }
3790
3791 static void
3792 bttv_irq_switch_vbi(struct bttv *btv)
3793 {
3794         struct bttv_buffer *new = NULL;
3795         struct bttv_buffer *old;
3796         u32 rc;
3797
3798         spin_lock(&btv->s_lock);
3799
3800         if (!list_empty(&btv->vcapture))
3801                 new = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3802         old = btv->cvbi;
3803
3804         rc = btread(BT848_RISC_COUNT);
3805         if (NULL != old && (is_active(&old->top,    rc) ||
3806                             is_active(&old->bottom, rc))) {
3807                 btv->framedrop++;
3808                 if (debug_latency)
3809                         bttv_irq_debug_low_latency(btv, rc);
3810                 spin_unlock(&btv->s_lock);
3811                 return;
3812         }
3813
3814         /* switch */
3815         btv->cvbi = new;
3816         btv->loop_irq &= ~4;
3817         bttv_buffer_activate_vbi(btv, new);
3818         bttv_set_dma(btv, 0);
3819
3820         bttv_irq_wakeup_vbi(btv, old, VIDEOBUF_DONE);
3821         spin_unlock(&btv->s_lock);
3822 }
3823
3824 static irqreturn_t bttv_irq(int irq, void *dev_id)
3825 {
3826         u32 stat,astat;
3827         u32 dstat;
3828         int count;
3829         struct bttv *btv;
3830         int handled = 0;
3831
3832         btv=(struct bttv *)dev_id;
3833
3834         if (btv->custom_irq)
3835                 handled = btv->custom_irq(btv);
3836
3837         count=0;
3838         while (1) {
3839                 /* get/clear interrupt status bits */
3840                 stat=btread(BT848_INT_STAT);
3841                 astat=stat&btread(BT848_INT_MASK);
3842                 if (!astat)
3843                         break;
3844                 handled = 1;
3845                 btwrite(stat,BT848_INT_STAT);
3846
3847                 /* get device status bits */
3848                 dstat=btread(BT848_DSTATUS);
3849
3850                 if (irq_debug) {
3851                         printk(KERN_DEBUG "bttv%d: irq loop=%d fc=%d "
3852                                "riscs=%x, riscc=%08x, ",
3853                                btv->c.nr, count, btv->field_count,
3854                                stat>>28, btread(BT848_RISC_COUNT));
3855                         bttv_print_irqbits(stat,astat);
3856                         if (stat & BT848_INT_HLOCK)
3857                                 printk("   HLOC => %s", (dstat & BT848_DSTATUS_HLOC)
3858                                        ? "yes" : "no");
3859                         if (stat & BT848_INT_VPRES)
3860                                 printk("   PRES => %s", (dstat & BT848_DSTATUS_PRES)
3861                                        ? "yes" : "no");
3862                         if (stat & BT848_INT_FMTCHG)
3863                                 printk("   NUML => %s", (dstat & BT848_DSTATUS_NUML)
3864                                        ? "625" : "525");
3865                         printk("\n");
3866                 }
3867
3868                 if (astat&BT848_INT_VSYNC)
3869                         btv->field_count++;
3870
3871                 if ((astat & BT848_INT_GPINT) && btv->remote) {
3872                         wake_up(&btv->gpioq);
3873                         bttv_input_irq(btv);
3874                 }
3875
3876                 if (astat & BT848_INT_I2CDONE) {
3877                         btv->i2c_done = stat;
3878                         wake_up(&btv->i2c_queue);
3879                 }
3880
3881                 if ((astat & BT848_INT_RISCI)  &&  (stat & (4<<28)))
3882                         bttv_irq_switch_vbi(btv);
3883
3884                 if ((astat & BT848_INT_RISCI)  &&  (stat & (2<<28)))
3885                         bttv_irq_wakeup_top(btv);
3886
3887                 if ((astat & BT848_INT_RISCI)  &&  (stat & (1<<28)))
3888                         bttv_irq_switch_video(btv);
3889
3890                 if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3891                         audio_mute(btv, btv->mute);  /* trigger automute */
3892
3893                 if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3894                         printk(KERN_INFO "bttv%d: %s%s @ %08x,",btv->c.nr,
3895                                (astat & BT848_INT_SCERR) ? "SCERR" : "",
3896                                (astat & BT848_INT_OCERR) ? "OCERR" : "",
3897                                btread(BT848_RISC_COUNT));
3898                         bttv_print_irqbits(stat,astat);
3899                         printk("\n");
3900                         if (bttv_debug)
3901                                 bttv_print_riscaddr(btv);
3902                 }
3903                 if (fdsr && astat & BT848_INT_FDSR) {
3904                         printk(KERN_INFO "bttv%d: FDSR @ %08x\n",
3905                                btv->c.nr,btread(BT848_RISC_COUNT));
3906                         if (bttv_debug)
3907                                 bttv_print_riscaddr(btv);
3908                 }
3909
3910                 count++;
3911                 if (count > 4) {
3912
3913                         if (count > 8 || !(astat & BT848_INT_GPINT)) {
3914                                 btwrite(0, BT848_INT_MASK);
3915
3916                                 printk(KERN_ERR
3917                                            "bttv%d: IRQ lockup, cleared int mask [", btv->c.nr);
3918                         } else {
3919                                 printk(KERN_ERR
3920                                            "bttv%d: IRQ lockup, clearing GPINT from int mask [", btv->c.nr);
3921
3922                                 btwrite(btread(BT848_INT_MASK) & (-1 ^ BT848_INT_GPINT),
3923                                                 BT848_INT_MASK);
3924                         };
3925
3926                         bttv_print_irqbits(stat,astat);
3927
3928                         printk("]\n");
3929                 }
3930         }
3931         btv->irq_total++;
3932         if (handled)
3933                 btv->irq_me++;
3934         return IRQ_RETVAL(handled);
3935 }
3936
3937
3938 /* ----------------------------------------------------------------------- */
3939 /* initialitation                                                          */
3940
3941 static struct video_device *vdev_init(struct bttv *btv,
3942                                       struct video_device *template,
3943                                       char *type)
3944 {
3945         struct video_device *vfd;
3946
3947         vfd = video_device_alloc();
3948         if (NULL == vfd)
3949                 return NULL;
3950         *vfd = *template;
3951         vfd->minor   = -1;
3952         vfd->dev     = &btv->c.pci->dev;
3953         vfd->release = video_device_release;
3954         snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3955                  btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3956                  type, bttv_tvcards[btv->c.type].name);
3957         return vfd;
3958 }
3959
3960 static void bttv_unregister_video(struct bttv *btv)
3961 {
3962         if (btv->video_dev) {
3963                 if (-1 != btv->video_dev->minor)
3964                         video_unregister_device(btv->video_dev);
3965                 else
3966                         video_device_release(btv->video_dev);
3967                 btv->video_dev = NULL;
3968         }
3969         if (btv->vbi_dev) {
3970                 if (-1 != btv->vbi_dev->minor)
3971                         video_unregister_device(btv->vbi_dev);
3972                 else
3973                         video_device_release(btv->vbi_dev);
3974                 btv->vbi_dev = NULL;
3975         }
3976         if (btv->radio_dev) {
3977                 if (-1 != btv->radio_dev->minor)
3978                         video_unregister_device(btv->radio_dev);
3979                 else
3980                         video_device_release(btv->radio_dev);
3981                 btv->radio_dev = NULL;
3982         }
3983 }
3984
3985 /* register video4linux devices */
3986 static int __devinit bttv_register_video(struct bttv *btv)
3987 {
3988         if (no_overlay <= 0) {
3989                 bttv_video_template.type |= VID_TYPE_OVERLAY;
3990         } else {
3991                 printk("bttv: Overlay support disabled.\n");
3992         }
3993
3994         /* video */
3995         btv->video_dev = vdev_init(btv, &bttv_video_template, "video");
3996         if (NULL == btv->video_dev)
3997                 goto err;
3998         if (video_register_device(btv->video_dev,VFL_TYPE_GRABBER,video_nr)<0)
3999                 goto err;
4000         printk(KERN_INFO "bttv%d: registered device video%d\n",
4001                btv->c.nr,btv->video_dev->minor & 0x1f);
4002         if (device_create_file(&btv->video_dev->class_dev,
4003                                      &dev_attr_card)<0) {
4004                 printk(KERN_ERR "bttv%d: device_create_file 'card' "
4005                        "failed\n", btv->c.nr);
4006                 goto err;
4007         }
4008
4009         /* vbi */
4010         btv->vbi_dev = vdev_init(btv, &bttv_vbi_template, "vbi");
4011         if (NULL == btv->vbi_dev)
4012                 goto err;
4013         if (video_register_device(btv->vbi_dev,VFL_TYPE_VBI,vbi_nr)<0)
4014                 goto err;
4015         printk(KERN_INFO "bttv%d: registered device vbi%d\n",
4016                btv->c.nr,btv->vbi_dev->minor & 0x1f);
4017
4018         if (!btv->has_radio)
4019                 return 0;
4020         /* radio */
4021         btv->radio_dev = vdev_init(btv, &radio_template, "radio");
4022         if (NULL == btv->radio_dev)
4023                 goto err;
4024         if (video_register_device(btv->radio_dev, VFL_TYPE_RADIO,radio_nr)<0)
4025                 goto err;
4026         printk(KERN_INFO "bttv%d: registered device radio%d\n",
4027                btv->c.nr,btv->radio_dev->minor & 0x1f);
4028
4029         /* all done */
4030         return 0;
4031
4032  err:
4033         bttv_unregister_video(btv);
4034         return -1;
4035 }
4036
4037
4038 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
4039 /* response on cards with no firmware is not enabled by OF */
4040 static void pci_set_command(struct pci_dev *dev)
4041 {
4042 #if defined(__powerpc__)
4043         unsigned int cmd;
4044
4045         pci_read_config_dword(dev, PCI_COMMAND, &cmd);
4046         cmd = (cmd | PCI_COMMAND_MEMORY );
4047         pci_write_config_dword(dev, PCI_COMMAND, cmd);
4048 #endif
4049 }
4050
4051 static int __devinit bttv_probe(struct pci_dev *dev,
4052                                 const struct pci_device_id *pci_id)
4053 {
4054         int result;
4055         unsigned char lat;
4056         struct bttv *btv;
4057
4058         if (bttv_num == BTTV_MAX)
4059                 return -ENOMEM;
4060         printk(KERN_INFO "bttv: Bt8xx card found (%d).\n", bttv_num);
4061         btv=&bttvs[bttv_num];
4062         memset(btv,0,sizeof(*btv));
4063         btv->c.nr  = bttv_num;
4064         sprintf(btv->c.name,"bttv%d",btv->c.nr);
4065
4066         /* initialize structs / fill in defaults */
4067         mutex_init(&btv->lock);
4068         spin_lock_init(&btv->s_lock);
4069         spin_lock_init(&btv->gpio_lock);
4070         init_waitqueue_head(&btv->gpioq);
4071         init_waitqueue_head(&btv->i2c_queue);
4072         INIT_LIST_HEAD(&btv->c.subs);
4073         INIT_LIST_HEAD(&btv->capture);
4074         INIT_LIST_HEAD(&btv->vcapture);
4075         v4l2_prio_init(&btv->prio);
4076
4077         init_timer(&btv->timeout);
4078         btv->timeout.function = bttv_irq_timeout;
4079         btv->timeout.data     = (unsigned long)btv;
4080
4081         btv->i2c_rc = -1;
4082         btv->tuner_type  = UNSET;
4083         btv->new_input   = UNSET;
4084         btv->has_radio=radio[btv->c.nr];
4085
4086         /* pci stuff (init, get irq/mmio, ... */
4087         btv->c.pci = dev;
4088         btv->id  = dev->device;
4089         if (pci_enable_device(dev)) {
4090                 printk(KERN_WARNING "bttv%d: Can't enable device.\n",
4091                        btv->c.nr);
4092                 return -EIO;
4093         }
4094         if (pci_set_dma_mask(dev, DMA_32BIT_MASK)) {
4095                 printk(KERN_WARNING "bttv%d: No suitable DMA available.\n",
4096                        btv->c.nr);
4097                 return -EIO;
4098         }
4099         if (!request_mem_region(pci_resource_start(dev,0),
4100                                 pci_resource_len(dev,0),
4101                                 btv->c.name)) {
4102                 printk(KERN_WARNING "bttv%d: can't request iomem (0x%llx).\n",
4103                        btv->c.nr,
4104                        (unsigned long long)pci_resource_start(dev,0));
4105                 return -EBUSY;
4106         }
4107         pci_set_master(dev);
4108         pci_set_command(dev);
4109         pci_set_drvdata(dev,btv);
4110
4111         pci_read_config_byte(dev, PCI_CLASS_REVISION, &btv->revision);
4112         pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
4113         printk(KERN_INFO "bttv%d: Bt%d (rev %d) at %s, ",
4114                bttv_num,btv->id, btv->revision, pci_name(dev));
4115         printk("irq: %d, latency: %d, mmio: 0x%llx\n",
4116                btv->c.pci->irq, lat,
4117                (unsigned long long)pci_resource_start(dev,0));
4118         schedule();
4119
4120         btv->bt848_mmio = ioremap(pci_resource_start(dev, 0), 0x1000);
4121         if (NULL == btv->bt848_mmio) {
4122                 printk("bttv%d: ioremap() failed\n", btv->c.nr);
4123                 result = -EIO;
4124                 goto fail1;
4125         }
4126
4127         /* identify card */
4128         bttv_idcard(btv);
4129
4130         /* disable irqs, register irq handler */
4131         btwrite(0, BT848_INT_MASK);
4132         result = request_irq(btv->c.pci->irq, bttv_irq,
4133                              IRQF_SHARED | IRQF_DISABLED,btv->c.name,(void *)btv);
4134         if (result < 0) {
4135                 printk(KERN_ERR "bttv%d: can't get IRQ %d\n",
4136                        bttv_num,btv->c.pci->irq);
4137                 goto fail1;
4138         }
4139
4140         if (0 != bttv_handle_chipset(btv)) {
4141                 result = -EIO;
4142                 goto fail2;
4143         }
4144
4145         /* init options from insmod args */
4146         btv->opt_combfilter = combfilter;
4147         btv->opt_lumafilter = lumafilter;
4148         btv->opt_automute   = automute;
4149         btv->opt_chroma_agc = chroma_agc;
4150         btv->opt_adc_crush  = adc_crush;
4151         btv->opt_vcr_hack   = vcr_hack;
4152         btv->opt_whitecrush_upper  = whitecrush_upper;
4153         btv->opt_whitecrush_lower  = whitecrush_lower;
4154         btv->opt_uv_ratio   = uv_ratio;
4155         btv->opt_full_luma_range   = full_luma_range;
4156         btv->opt_coring     = coring;
4157
4158         /* fill struct bttv with some useful defaults */
4159         btv->init.btv         = btv;
4160         btv->init.ov.w.width  = 320;
4161         btv->init.ov.w.height = 240;
4162         btv->init.fmt         = format_by_fourcc(V4L2_PIX_FMT_BGR24);
4163         btv->init.width       = 320;
4164         btv->init.height      = 240;
4165         btv->input = 0;
4166
4167         /* initialize hardware */
4168         if (bttv_gpio)
4169                 bttv_gpio_tracking(btv,"pre-init");
4170
4171         bttv_risc_init_main(btv);
4172         init_bt848(btv);
4173
4174         /* gpio */
4175         btwrite(0x00, BT848_GPIO_REG_INP);
4176         btwrite(0x00, BT848_GPIO_OUT_EN);
4177         if (bttv_verbose)
4178                 bttv_gpio_tracking(btv,"init");
4179
4180         /* needs to be done before i2c is registered */
4181         bttv_init_card1(btv);
4182
4183         /* register i2c + gpio */
4184         init_bttv_i2c(btv);
4185
4186         /* some card-specific stuff (needs working i2c) */
4187         bttv_init_card2(btv);
4188         init_irqreg(btv);
4189
4190         /* register video4linux + input */
4191         if (!bttv_tvcards[btv->c.type].no_video) {
4192                 bttv_register_video(btv);
4193                 bt848_bright(btv,32768);
4194                 bt848_contrast(btv,32768);
4195                 bt848_hue(btv,32768);
4196                 bt848_sat(btv,32768);
4197                 audio_mute(btv, 1);
4198                 set_input(btv, 0, btv->tvnorm);
4199                 bttv_crop_reset(&btv->crop[0], btv->tvnorm);
4200                 btv->crop[1] = btv->crop[0]; /* current = default */
4201                 disclaim_vbi_lines(btv);
4202                 disclaim_video_lines(btv);
4203         }
4204
4205         /* add subdevices and autoload dvb-bt8xx if needed */
4206         if (bttv_tvcards[btv->c.type].has_dvb) {
4207                 bttv_sub_add_device(&btv->c, "dvb");
4208                 request_modules(btv);
4209         }
4210
4211         bttv_input_init(btv);
4212
4213         /* everything is fine */
4214         bttv_num++;
4215         return 0;
4216
4217  fail2:
4218         free_irq(btv->c.pci->irq,btv);
4219
4220  fail1:
4221         if (btv->bt848_mmio)
4222                 iounmap(btv->bt848_mmio);
4223         release_mem_region(pci_resource_start(btv->c.pci,0),
4224                            pci_resource_len(btv->c.pci,0));
4225         pci_set_drvdata(dev,NULL);
4226         return result;
4227 }
4228
4229 static void __devexit bttv_remove(struct pci_dev *pci_dev)
4230 {
4231         struct bttv *btv = pci_get_drvdata(pci_dev);
4232
4233         if (bttv_verbose)
4234                 printk("bttv%d: unloading\n",btv->c.nr);
4235
4236         /* shutdown everything (DMA+IRQs) */
4237         btand(~15, BT848_GPIO_DMA_CTL);
4238         btwrite(0, BT848_INT_MASK);
4239         btwrite(~0x0, BT848_INT_STAT);
4240         btwrite(0x0, BT848_GPIO_OUT_EN);
4241         if (bttv_gpio)
4242                 bttv_gpio_tracking(btv,"cleanup");
4243
4244         /* tell gpio modules we are leaving ... */
4245         btv->shutdown=1;
4246         wake_up(&btv->gpioq);
4247         bttv_input_fini(btv);
4248         bttv_sub_del_devices(&btv->c);
4249
4250         /* unregister i2c_bus + input */
4251         fini_bttv_i2c(btv);
4252
4253         /* unregister video4linux */
4254         bttv_unregister_video(btv);
4255
4256         /* free allocated memory */
4257         btcx_riscmem_free(btv->c.pci,&btv->main);
4258
4259         /* free ressources */
4260         free_irq(btv->c.pci->irq,btv);
4261         iounmap(btv->bt848_mmio);
4262         release_mem_region(pci_resource_start(btv->c.pci,0),
4263                            pci_resource_len(btv->c.pci,0));
4264
4265         pci_set_drvdata(pci_dev, NULL);
4266         return;
4267 }
4268
4269 #ifdef CONFIG_PM
4270 static int bttv_suspend(struct pci_dev *pci_dev, pm_message_t state)
4271 {
4272         struct bttv *btv = pci_get_drvdata(pci_dev);
4273         struct bttv_buffer_set idle;
4274         unsigned long flags;
4275
4276         dprintk("bttv%d: suspend %d\n", btv->c.nr, state.event);
4277
4278         /* stop dma + irqs */
4279         spin_lock_irqsave(&btv->s_lock,flags);
4280         memset(&idle, 0, sizeof(idle));
4281         btv->state.video = btv->curr;
4282         btv->state.vbi   = btv->cvbi;
4283         btv->state.loop_irq = btv->loop_irq;
4284         btv->curr = idle;
4285         btv->loop_irq = 0;
4286         bttv_buffer_activate_video(btv, &idle);
4287         bttv_buffer_activate_vbi(btv, NULL);
4288         bttv_set_dma(btv, 0);
4289         btwrite(0, BT848_INT_MASK);
4290         spin_unlock_irqrestore(&btv->s_lock,flags);
4291
4292         /* save bt878 state */
4293         btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
4294         btv->state.gpio_data   = gpio_read();
4295
4296         /* save pci state */
4297         pci_save_state(pci_dev);
4298         if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) {
4299                 pci_disable_device(pci_dev);
4300                 btv->state.disabled = 1;
4301         }
4302         return 0;
4303 }
4304
4305 static int bttv_resume(struct pci_dev *pci_dev)
4306 {
4307         struct bttv *btv = pci_get_drvdata(pci_dev);
4308         unsigned long flags;
4309         int err;
4310
4311         dprintk("bttv%d: resume\n", btv->c.nr);
4312
4313         /* restore pci state */
4314         if (btv->state.disabled) {
4315                 err=pci_enable_device(pci_dev);
4316                 if (err) {
4317                         printk(KERN_WARNING "bttv%d: Can't enable device.\n",
4318                                                                 btv->c.nr);
4319                         return err;
4320                 }
4321                 btv->state.disabled = 0;
4322         }
4323         err=pci_set_power_state(pci_dev, PCI_D0);
4324         if (err) {
4325                 pci_disable_device(pci_dev);
4326                 printk(KERN_WARNING "bttv%d: Can't enable device.\n",
4327                                                         btv->c.nr);
4328                 btv->state.disabled = 1;
4329                 return err;
4330         }
4331
4332         pci_restore_state(pci_dev);
4333
4334         /* restore bt878 state */
4335         bttv_reinit_bt848(btv);
4336         gpio_inout(0xffffff, btv->state.gpio_enable);
4337         gpio_write(btv->state.gpio_data);
4338
4339         /* restart dma */
4340         spin_lock_irqsave(&btv->s_lock,flags);
4341         btv->curr = btv->state.video;
4342         btv->cvbi = btv->state.vbi;
4343         btv->loop_irq = btv->state.loop_irq;
4344         bttv_buffer_activate_video(btv, &btv->curr);
4345         bttv_buffer_activate_vbi(btv, btv->cvbi);
4346         bttv_set_dma(btv, 0);
4347         spin_unlock_irqrestore(&btv->s_lock,flags);
4348         return 0;
4349 }
4350 #endif
4351
4352 static struct pci_device_id bttv_pci_tbl[] = {
4353         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT848,
4354          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4355         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT849,
4356          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4357         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT878,
4358          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4359         {PCI_VENDOR_ID_BROOKTREE, PCI_DEVICE_ID_BT879,
4360          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4361         {0,}
4362 };
4363
4364 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
4365
4366 static struct pci_driver bttv_pci_driver = {
4367         .name     = "bttv",
4368         .id_table = bttv_pci_tbl,
4369         .probe    = bttv_probe,
4370         .remove   = __devexit_p(bttv_remove),
4371 #ifdef CONFIG_PM
4372         .suspend  = bttv_suspend,
4373         .resume   = bttv_resume,
4374 #endif
4375 };
4376
4377 static int __init bttv_init_module(void)
4378 {
4379         int ret;
4380
4381         bttv_num = 0;
4382
4383         printk(KERN_INFO "bttv: driver version %d.%d.%d loaded\n",
4384                (BTTV_VERSION_CODE >> 16) & 0xff,
4385                (BTTV_VERSION_CODE >> 8) & 0xff,
4386                BTTV_VERSION_CODE & 0xff);
4387 #ifdef SNAPSHOT
4388         printk(KERN_INFO "bttv: snapshot date %04d-%02d-%02d\n",
4389                SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100);
4390 #endif
4391         if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
4392                 gbuffers = 2;
4393         if (gbufsize < 0 || gbufsize > BTTV_MAX_FBUF)
4394                 gbufsize = BTTV_MAX_FBUF;
4395         gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
4396         if (bttv_verbose)
4397                 printk(KERN_INFO "bttv: using %d buffers with %dk (%d pages) each for capture\n",
4398                        gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
4399
4400         bttv_check_chipset();
4401
4402         ret = bus_register(&bttv_sub_bus_type);
4403         if (ret < 0) {
4404                 printk(KERN_WARNING "bttv: bus_register error: %d\n", ret);
4405                 return ret;
4406         }
4407         return pci_register_driver(&bttv_pci_driver);
4408 }
4409
4410 static void __exit bttv_cleanup_module(void)
4411 {
4412         pci_unregister_driver(&bttv_pci_driver);
4413         bus_unregister(&bttv_sub_bus_type);
4414         return;
4415 }
4416
4417 module_init(bttv_init_module);
4418 module_exit(bttv_cleanup_module);
4419
4420 /*
4421  * Local variables:
4422  * c-basic-offset: 8
4423  * End:
4424  */