Version:  2.0.40 2.2.26 2.4.37 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18

Linux/drivers/media/pci/bt8xx/bttv-driver.c

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

This page was automatically generated by LXR 0.3.1 (source).  •  Linux is a registered trademark of Linus Torvalds  •  Contact us