Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/sparc-2.6
[linux-2.6.git] / drivers / media / video / cx18 / cx18-driver.c
1 /*
2  *  cx18 driver initialization and card probing
3  *
4  *  Derived from ivtv-driver.c
5  *
6  *  Copyright (C) 2007  Hans Verkuil <hverkuil@xs4all.nl>
7  *  Copyright (C) 2008  Andy Walls <awalls@radix.net>
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22  *  02111-1307  USA
23  */
24
25 #include "cx18-driver.h"
26 #include "cx18-io.h"
27 #include "cx18-version.h"
28 #include "cx18-cards.h"
29 #include "cx18-i2c.h"
30 #include "cx18-irq.h"
31 #include "cx18-gpio.h"
32 #include "cx18-firmware.h"
33 #include "cx18-queue.h"
34 #include "cx18-streams.h"
35 #include "cx18-av-core.h"
36 #include "cx18-scb.h"
37 #include "cx18-mailbox.h"
38 #include "cx18-ioctl.h"
39 #include "tuner-xc2028.h"
40
41 #include <media/tveeprom.h>
42
43 /* If you have already X v4l cards, then set this to X. This way
44    the device numbers stay matched. Example: you have a WinTV card
45    without radio and a Compro H900 with. Normally this would give a
46    video1 device together with a radio0 device for the Compro. By
47    setting this to 1 you ensure that radio0 is now also radio1. */
48 int cx18_first_minor;
49
50 /* Callback for registering extensions */
51 int (*cx18_ext_init)(struct cx18 *);
52 EXPORT_SYMBOL(cx18_ext_init);
53
54 /* add your revision and whatnot here */
55 static struct pci_device_id cx18_pci_tbl[] __devinitdata = {
56         {PCI_VENDOR_ID_CX, PCI_DEVICE_ID_CX23418,
57          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
58         {0,}
59 };
60
61 MODULE_DEVICE_TABLE(pci, cx18_pci_tbl);
62
63 static atomic_t cx18_instance = ATOMIC_INIT(0);
64
65 /* Parameter declarations */
66 static int cardtype[CX18_MAX_CARDS];
67 static int tuner[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
68                                      -1, -1, -1, -1, -1, -1, -1, -1,
69                                      -1, -1, -1, -1, -1, -1, -1, -1,
70                                      -1, -1, -1, -1, -1, -1, -1, -1 };
71 static int radio[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
72                                      -1, -1, -1, -1, -1, -1, -1, -1,
73                                      -1, -1, -1, -1, -1, -1, -1, -1,
74                                      -1, -1, -1, -1, -1, -1, -1, -1 };
75 static unsigned cardtype_c = 1;
76 static unsigned tuner_c = 1;
77 static unsigned radio_c = 1;
78 static char pal[] = "--";
79 static char secam[] = "--";
80 static char ntsc[] = "-";
81
82 /* Buffers */
83 static int enc_ts_buffers = CX18_DEFAULT_ENC_TS_BUFFERS;
84 static int enc_mpg_buffers = CX18_DEFAULT_ENC_MPG_BUFFERS;
85 static int enc_idx_buffers = CX18_DEFAULT_ENC_IDX_BUFFERS;
86 static int enc_yuv_buffers = CX18_DEFAULT_ENC_YUV_BUFFERS;
87 static int enc_vbi_buffers = CX18_DEFAULT_ENC_VBI_BUFFERS;
88 static int enc_pcm_buffers = CX18_DEFAULT_ENC_PCM_BUFFERS;
89
90 static int enc_ts_bufsize = CX18_DEFAULT_ENC_TS_BUFSIZE;
91 static int enc_mpg_bufsize = CX18_DEFAULT_ENC_MPG_BUFSIZE;
92 static int enc_idx_bufsize = CX18_DEFAULT_ENC_IDX_BUFSIZE;
93 static int enc_yuv_bufsize = CX18_DEFAULT_ENC_YUV_BUFSIZE;
94 static int enc_pcm_bufsize = CX18_DEFAULT_ENC_PCM_BUFSIZE;
95
96 static int enc_ts_bufs = -1;
97 static int enc_mpg_bufs = -1;
98 static int enc_idx_bufs = CX18_MAX_FW_MDLS_PER_STREAM;
99 static int enc_yuv_bufs = -1;
100 static int enc_vbi_bufs = -1;
101 static int enc_pcm_bufs = -1;
102
103
104 static int cx18_pci_latency = 1;
105
106 static int mmio_ndelay;
107 static int retry_mmio = 1;
108
109 int cx18_debug;
110
111 module_param_array(tuner, int, &tuner_c, 0644);
112 module_param_array(radio, bool, &radio_c, 0644);
113 module_param_array(cardtype, int, &cardtype_c, 0644);
114 module_param_string(pal, pal, sizeof(pal), 0644);
115 module_param_string(secam, secam, sizeof(secam), 0644);
116 module_param_string(ntsc, ntsc, sizeof(ntsc), 0644);
117 module_param_named(debug, cx18_debug, int, 0644);
118 module_param(mmio_ndelay, int, 0644);
119 module_param(retry_mmio, int, 0644);
120 module_param(cx18_pci_latency, int, 0644);
121 module_param(cx18_first_minor, int, 0644);
122
123 module_param(enc_ts_buffers, int, 0644);
124 module_param(enc_mpg_buffers, int, 0644);
125 module_param(enc_idx_buffers, int, 0644);
126 module_param(enc_yuv_buffers, int, 0644);
127 module_param(enc_vbi_buffers, int, 0644);
128 module_param(enc_pcm_buffers, int, 0644);
129
130 module_param(enc_ts_bufsize, int, 0644);
131 module_param(enc_mpg_bufsize, int, 0644);
132 module_param(enc_idx_bufsize, int, 0644);
133 module_param(enc_yuv_bufsize, int, 0644);
134 module_param(enc_pcm_bufsize, int, 0644);
135
136 module_param(enc_ts_bufs, int, 0644);
137 module_param(enc_mpg_bufs, int, 0644);
138 module_param(enc_idx_bufs, int, 0644);
139 module_param(enc_yuv_bufs, int, 0644);
140 module_param(enc_vbi_bufs, int, 0644);
141 module_param(enc_pcm_bufs, int, 0644);
142
143 MODULE_PARM_DESC(tuner, "Tuner type selection,\n"
144                         "\t\t\tsee tuner.h for values");
145 MODULE_PARM_DESC(radio,
146                  "Enable or disable the radio. Use only if autodetection\n"
147                  "\t\t\tfails. 0 = disable, 1 = enable");
148 MODULE_PARM_DESC(cardtype,
149                  "Only use this option if your card is not detected properly.\n"
150                  "\t\tSpecify card type:\n"
151                  "\t\t\t 1 = Hauppauge HVR 1600 (ESMT memory)\n"
152                  "\t\t\t 2 = Hauppauge HVR 1600 (Samsung memory)\n"
153                  "\t\t\t 3 = Compro VideoMate H900\n"
154                  "\t\t\t 4 = Yuan MPC718\n"
155                  "\t\t\t 5 = Conexant Raptor PAL/SECAM\n"
156                  "\t\t\t 6 = Toshiba Qosmio DVB-T/Analog\n"
157                  "\t\t\t 7 = Leadtek WinFast PVR2100\n"
158                  "\t\t\t 8 = Leadtek WinFast DVR3100 H\n"
159                  "\t\t\t 0 = Autodetect (default)\n"
160                  "\t\t\t-1 = Ignore this card\n\t\t");
161 MODULE_PARM_DESC(pal, "Set PAL standard: B, G, H, D, K, I, M, N, Nc, 60");
162 MODULE_PARM_DESC(secam, "Set SECAM standard: B, G, H, D, K, L, LC");
163 MODULE_PARM_DESC(ntsc, "Set NTSC standard: M, J, K");
164 MODULE_PARM_DESC(debug,
165                  "Debug level (bitmask). Default: 0\n"
166                  "\t\t\t  1/0x0001: warning\n"
167                  "\t\t\t  2/0x0002: info\n"
168                  "\t\t\t  4/0x0004: mailbox\n"
169                  "\t\t\t  8/0x0008: dma\n"
170                  "\t\t\t 16/0x0010: ioctl\n"
171                  "\t\t\t 32/0x0020: file\n"
172                  "\t\t\t 64/0x0040: i2c\n"
173                  "\t\t\t128/0x0080: irq\n"
174                  "\t\t\t256/0x0100: high volume\n");
175 MODULE_PARM_DESC(cx18_pci_latency,
176                  "Change the PCI latency to 64 if lower: 0 = No, 1 = Yes,\n"
177                  "\t\t\tDefault: Yes");
178 MODULE_PARM_DESC(retry_mmio,
179                  "(Deprecated) MMIO writes are now always checked and retried\n"
180                  "\t\t\tEffectively: 1 [Yes]");
181 MODULE_PARM_DESC(mmio_ndelay,
182                  "(Deprecated) MMIO accesses are now never purposely delayed\n"
183                  "\t\t\tEffectively: 0 ns");
184 MODULE_PARM_DESC(enc_ts_buffers,
185                  "Encoder TS buffer memory (MB). (enc_ts_bufs can override)\n"
186                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_TS_BUFFERS));
187 MODULE_PARM_DESC(enc_ts_bufsize,
188                  "Size of an encoder TS buffer (kB)\n"
189                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_TS_BUFSIZE));
190 MODULE_PARM_DESC(enc_ts_bufs,
191                  "Number of encoder TS buffers\n"
192                  "\t\t\tDefault is computed from other enc_ts_* parameters");
193 MODULE_PARM_DESC(enc_mpg_buffers,
194                  "Encoder MPG buffer memory (MB). (enc_mpg_bufs can override)\n"
195                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_MPG_BUFFERS));
196 MODULE_PARM_DESC(enc_mpg_bufsize,
197                  "Size of an encoder MPG buffer (kB)\n"
198                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_MPG_BUFSIZE));
199 MODULE_PARM_DESC(enc_mpg_bufs,
200                  "Number of encoder MPG buffers\n"
201                  "\t\t\tDefault is computed from other enc_mpg_* parameters");
202 MODULE_PARM_DESC(enc_idx_buffers,
203                  "(Deprecated) Encoder IDX buffer memory (MB)\n"
204                  "\t\t\tIgnored, except 0 disables IDX buffer allocations\n"
205                  "\t\t\tDefault: 1 [Enabled]");
206 MODULE_PARM_DESC(enc_idx_bufsize,
207                  "Size of an encoder IDX buffer (kB)\n"
208                  "\t\t\tAllowed values are multiples of 1.5 kB rounded up\n"
209                  "\t\t\t(multiples of size required for 64 index entries)\n"
210                  "\t\t\tDefault: 2");
211 MODULE_PARM_DESC(enc_idx_bufs,
212                  "Number of encoder IDX buffers\n"
213                  "\t\t\tDefault: " __stringify(CX18_MAX_FW_MDLS_PER_STREAM));
214 MODULE_PARM_DESC(enc_yuv_buffers,
215                  "Encoder YUV buffer memory (MB). (enc_yuv_bufs can override)\n"
216                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_YUV_BUFFERS));
217 MODULE_PARM_DESC(enc_yuv_bufsize,
218                  "Size of an encoder YUV buffer (kB)\n"
219                  "\t\t\tAllowed values are multiples of 33.75 kB rounded up\n"
220                  "\t\t\t(multiples of size required for 32 screen lines)\n"
221                  "\t\t\tDefault: 102");
222 MODULE_PARM_DESC(enc_yuv_bufs,
223                  "Number of encoder YUV buffers\n"
224                  "\t\t\tDefault is computed from other enc_yuv_* parameters");
225 MODULE_PARM_DESC(enc_vbi_buffers,
226                  "Encoder VBI buffer memory (MB). (enc_vbi_bufs can override)\n"
227                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_VBI_BUFFERS));
228 MODULE_PARM_DESC(enc_vbi_bufs,
229                  "Number of encoder VBI buffers\n"
230                  "\t\t\tDefault is computed from enc_vbi_buffers");
231 MODULE_PARM_DESC(enc_pcm_buffers,
232                  "Encoder PCM buffer memory (MB). (enc_pcm_bufs can override)\n"
233                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_PCM_BUFFERS));
234 MODULE_PARM_DESC(enc_pcm_bufsize,
235                  "Size of an encoder PCM buffer (kB)\n"
236                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_PCM_BUFSIZE));
237 MODULE_PARM_DESC(enc_pcm_bufs,
238                  "Number of encoder PCM buffers\n"
239                  "\t\t\tDefault is computed from other enc_pcm_* parameters");
240
241 MODULE_PARM_DESC(cx18_first_minor,
242                  "Set device node number assigned to first card");
243
244 MODULE_AUTHOR("Hans Verkuil");
245 MODULE_DESCRIPTION("CX23418 driver");
246 MODULE_SUPPORTED_DEVICE("CX23418 MPEG2 encoder");
247 MODULE_LICENSE("GPL");
248
249 MODULE_VERSION(CX18_VERSION);
250
251 #if defined(CONFIG_MODULES) && defined(MODULE)
252 static void request_module_async(struct work_struct *work)
253 {
254         struct cx18 *dev = container_of(work, struct cx18, request_module_wk);
255
256         /* Make sure cx18-alsa module is loaded */
257         request_module("cx18-alsa");
258
259         /* Initialize cx18-alsa for this instance of the cx18 device */
260         if (cx18_ext_init != NULL)
261                 cx18_ext_init(dev);
262 }
263
264 static void request_modules(struct cx18 *dev)
265 {
266         INIT_WORK(&dev->request_module_wk, request_module_async);
267         schedule_work(&dev->request_module_wk);
268 }
269 #else
270 #define request_modules(dev)
271 #endif /* CONFIG_MODULES */
272
273 /* Generic utility functions */
274 int cx18_msleep_timeout(unsigned int msecs, int intr)
275 {
276         long int timeout = msecs_to_jiffies(msecs);
277         int sig;
278
279         do {
280                 set_current_state(intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
281                 timeout = schedule_timeout(timeout);
282                 sig = intr ? signal_pending(current) : 0;
283         } while (!sig && timeout);
284         return sig;
285 }
286
287 /* Release ioremapped memory */
288 static void cx18_iounmap(struct cx18 *cx)
289 {
290         if (cx == NULL)
291                 return;
292
293         /* Release io memory */
294         if (cx->enc_mem != NULL) {
295                 CX18_DEBUG_INFO("releasing enc_mem\n");
296                 iounmap(cx->enc_mem);
297                 cx->enc_mem = NULL;
298         }
299 }
300
301 static void cx18_eeprom_dump(struct cx18 *cx, unsigned char *eedata, int len)
302 {
303         int i;
304
305         CX18_INFO("eeprom dump:\n");
306         for (i = 0; i < len; i++) {
307                 if (0 == (i % 16))
308                         CX18_INFO("eeprom %02x:", i);
309                 printk(KERN_CONT " %02x", eedata[i]);
310                 if (15 == (i % 16))
311                         printk(KERN_CONT "\n");
312         }
313 }
314
315 /* Hauppauge card? get values from tveeprom */
316 void cx18_read_eeprom(struct cx18 *cx, struct tveeprom *tv)
317 {
318         struct i2c_client c;
319         u8 eedata[256];
320
321         memset(&c, 0, sizeof(c));
322         strlcpy(c.name, "cx18 tveeprom tmp", sizeof(c.name));
323         c.adapter = &cx->i2c_adap[0];
324         c.addr = 0xA0 >> 1;
325
326         memset(tv, 0, sizeof(*tv));
327         if (tveeprom_read(&c, eedata, sizeof(eedata)))
328                 return;
329
330         switch (cx->card->type) {
331         case CX18_CARD_HVR_1600_ESMT:
332         case CX18_CARD_HVR_1600_SAMSUNG:
333                 tveeprom_hauppauge_analog(&c, tv, eedata);
334                 break;
335         case CX18_CARD_YUAN_MPC718:
336                 tv->model = 0x718;
337                 cx18_eeprom_dump(cx, eedata, sizeof(eedata));
338                 CX18_INFO("eeprom PCI ID: %02x%02x:%02x%02x\n",
339                           eedata[2], eedata[1], eedata[4], eedata[3]);
340                 break;
341         default:
342                 tv->model = 0xffffffff;
343                 cx18_eeprom_dump(cx, eedata, sizeof(eedata));
344                 break;
345         }
346 }
347
348 static void cx18_process_eeprom(struct cx18 *cx)
349 {
350         struct tveeprom tv;
351
352         cx18_read_eeprom(cx, &tv);
353
354         /* Many thanks to Steven Toth from Hauppauge for providing the
355            model numbers */
356         /* Note: the Samsung memory models cannot be reliably determined
357            from the model number. Use the cardtype module option if you
358            have one of these preproduction models. */
359         switch (tv.model) {
360         case 74000 ... 74999:
361                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
362                 break;
363         case 0x718:
364                 return;
365         case 0xffffffff:
366                 CX18_INFO("Unknown EEPROM encoding\n");
367                 return;
368         case 0:
369                 CX18_ERR("Invalid EEPROM\n");
370                 return;
371         default:
372                 CX18_ERR("Unknown model %d, defaulting to HVR-1600\n", tv.model);
373                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
374                 break;
375         }
376
377         cx->v4l2_cap = cx->card->v4l2_capabilities;
378         cx->card_name = cx->card->name;
379         cx->card_i2c = cx->card->i2c;
380
381         CX18_INFO("Autodetected %s\n", cx->card_name);
382
383         if (tv.tuner_type == TUNER_ABSENT)
384                 CX18_ERR("tveeprom cannot autodetect tuner!\n");
385
386         if (cx->options.tuner == -1)
387                 cx->options.tuner = tv.tuner_type;
388         if (cx->options.radio == -1)
389                 cx->options.radio = (tv.has_radio != 0);
390
391         if (cx->std != 0)
392                 /* user specified tuner standard */
393                 return;
394
395         /* autodetect tuner standard */
396         if (tv.tuner_formats & V4L2_STD_PAL) {
397                 CX18_DEBUG_INFO("PAL tuner detected\n");
398                 cx->std |= V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
399         } else if (tv.tuner_formats & V4L2_STD_NTSC) {
400                 CX18_DEBUG_INFO("NTSC tuner detected\n");
401                 cx->std |= V4L2_STD_NTSC_M;
402         } else if (tv.tuner_formats & V4L2_STD_SECAM) {
403                 CX18_DEBUG_INFO("SECAM tuner detected\n");
404                 cx->std |= V4L2_STD_SECAM_L;
405         } else {
406                 CX18_INFO("No tuner detected, default to NTSC-M\n");
407                 cx->std |= V4L2_STD_NTSC_M;
408         }
409 }
410
411 static v4l2_std_id cx18_parse_std(struct cx18 *cx)
412 {
413         switch (pal[0]) {
414         case '6':
415                 return V4L2_STD_PAL_60;
416         case 'b':
417         case 'B':
418         case 'g':
419         case 'G':
420                 return V4L2_STD_PAL_BG;
421         case 'h':
422         case 'H':
423                 return V4L2_STD_PAL_H;
424         case 'n':
425         case 'N':
426                 if (pal[1] == 'c' || pal[1] == 'C')
427                         return V4L2_STD_PAL_Nc;
428                 return V4L2_STD_PAL_N;
429         case 'i':
430         case 'I':
431                 return V4L2_STD_PAL_I;
432         case 'd':
433         case 'D':
434         case 'k':
435         case 'K':
436                 return V4L2_STD_PAL_DK;
437         case 'M':
438         case 'm':
439                 return V4L2_STD_PAL_M;
440         case '-':
441                 break;
442         default:
443                 CX18_WARN("pal= argument not recognised\n");
444                 return 0;
445         }
446
447         switch (secam[0]) {
448         case 'b':
449         case 'B':
450         case 'g':
451         case 'G':
452         case 'h':
453         case 'H':
454                 return V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H;
455         case 'd':
456         case 'D':
457         case 'k':
458         case 'K':
459                 return V4L2_STD_SECAM_DK;
460         case 'l':
461         case 'L':
462                 if (secam[1] == 'C' || secam[1] == 'c')
463                         return V4L2_STD_SECAM_LC;
464                 return V4L2_STD_SECAM_L;
465         case '-':
466                 break;
467         default:
468                 CX18_WARN("secam= argument not recognised\n");
469                 return 0;
470         }
471
472         switch (ntsc[0]) {
473         case 'm':
474         case 'M':
475                 return V4L2_STD_NTSC_M;
476         case 'j':
477         case 'J':
478                 return V4L2_STD_NTSC_M_JP;
479         case 'k':
480         case 'K':
481                 return V4L2_STD_NTSC_M_KR;
482         case '-':
483                 break;
484         default:
485                 CX18_WARN("ntsc= argument not recognised\n");
486                 return 0;
487         }
488
489         /* no match found */
490         return 0;
491 }
492
493 static void cx18_process_options(struct cx18 *cx)
494 {
495         int i, j;
496
497         cx->options.megabytes[CX18_ENC_STREAM_TYPE_TS] = enc_ts_buffers;
498         cx->options.megabytes[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_buffers;
499         cx->options.megabytes[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_buffers;
500         cx->options.megabytes[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_buffers;
501         cx->options.megabytes[CX18_ENC_STREAM_TYPE_VBI] = enc_vbi_buffers;
502         cx->options.megabytes[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_buffers;
503         cx->options.megabytes[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control only */
504
505         cx->stream_buffers[CX18_ENC_STREAM_TYPE_TS] = enc_ts_bufs;
506         cx->stream_buffers[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_bufs;
507         cx->stream_buffers[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_bufs;
508         cx->stream_buffers[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_bufs;
509         cx->stream_buffers[CX18_ENC_STREAM_TYPE_VBI] = enc_vbi_bufs;
510         cx->stream_buffers[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_bufs;
511         cx->stream_buffers[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control, no data */
512
513         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_TS] = enc_ts_bufsize;
514         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_bufsize;
515         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_bufsize;
516         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_bufsize;
517         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_VBI] = vbi_active_samples * 36;
518         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_bufsize;
519         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control no data */
520
521         /* Ensure stream_buffers & stream_buf_size are valid */
522         for (i = 0; i < CX18_MAX_STREAMS; i++) {
523                 if (cx->stream_buffers[i] == 0 ||     /* User said 0 buffers */
524                     cx->options.megabytes[i] <= 0 ||  /* User said 0 MB total */
525                     cx->stream_buf_size[i] <= 0) {    /* User said buf size 0 */
526                         cx->options.megabytes[i] = 0;
527                         cx->stream_buffers[i] = 0;
528                         cx->stream_buf_size[i] = 0;
529                         continue;
530                 }
531                 /*
532                  * YUV is a special case where the stream_buf_size needs to be
533                  * an integral multiple of 33.75 kB (storage for 32 screens
534                  * lines to maintain alignment in case of lost buffers).
535                  *
536                  * IDX is a special case where the stream_buf_size should be
537                  * an integral multiple of 1.5 kB (storage for 64 index entries
538                  * to maintain alignment in case of lost buffers).
539                  *
540                  */
541                 if (i == CX18_ENC_STREAM_TYPE_YUV) {
542                         cx->stream_buf_size[i] *= 1024;
543                         cx->stream_buf_size[i] -=
544                            (cx->stream_buf_size[i] % CX18_UNIT_ENC_YUV_BUFSIZE);
545
546                         if (cx->stream_buf_size[i] < CX18_UNIT_ENC_YUV_BUFSIZE)
547                                 cx->stream_buf_size[i] =
548                                                 CX18_UNIT_ENC_YUV_BUFSIZE;
549                 } else if (i == CX18_ENC_STREAM_TYPE_IDX) {
550                         cx->stream_buf_size[i] *= 1024;
551                         cx->stream_buf_size[i] -=
552                            (cx->stream_buf_size[i] % CX18_UNIT_ENC_IDX_BUFSIZE);
553
554                         if (cx->stream_buf_size[i] < CX18_UNIT_ENC_IDX_BUFSIZE)
555                                 cx->stream_buf_size[i] =
556                                                 CX18_UNIT_ENC_IDX_BUFSIZE;
557                 }
558                 /*
559                  * YUV and IDX are special cases where the stream_buf_size is
560                  * now in bytes.
561                  * VBI is a special case where the stream_buf_size is fixed
562                  * and already in bytes
563                  */
564                 if (i == CX18_ENC_STREAM_TYPE_VBI ||
565                     i == CX18_ENC_STREAM_TYPE_YUV ||
566                     i == CX18_ENC_STREAM_TYPE_IDX) {
567                         if (cx->stream_buffers[i] < 0) {
568                                 cx->stream_buffers[i] =
569                                         cx->options.megabytes[i] * 1024 * 1024
570                                         / cx->stream_buf_size[i];
571                         } else {
572                                 /* N.B. This might round down to 0 */
573                                 cx->options.megabytes[i] =
574                                         cx->stream_buffers[i]
575                                         * cx->stream_buf_size[i]/(1024 * 1024);
576                         }
577                 } else {
578                         /* All other streams have stream_buf_size in kB here */
579                         if (cx->stream_buffers[i] < 0) {
580                                 cx->stream_buffers[i] =
581                                                 cx->options.megabytes[i] * 1024
582                                                 / cx->stream_buf_size[i];
583                         } else {
584                                 /* N.B. This might round down to 0 */
585                                 cx->options.megabytes[i] =
586                                                 cx->stream_buffers[i]
587                                                 * cx->stream_buf_size[i] / 1024;
588                         }
589                         /* convert from kB to bytes */
590                         cx->stream_buf_size[i] *= 1024;
591                 }
592                 CX18_DEBUG_INFO("Stream type %d options: %d MB, %d buffers, "
593                                 "%d bytes\n", i, cx->options.megabytes[i],
594                                 cx->stream_buffers[i], cx->stream_buf_size[i]);
595         }
596
597         cx->options.cardtype = cardtype[cx->instance];
598         cx->options.tuner = tuner[cx->instance];
599         cx->options.radio = radio[cx->instance];
600
601         cx->std = cx18_parse_std(cx);
602         if (cx->options.cardtype == -1) {
603                 CX18_INFO("Ignore card\n");
604                 return;
605         }
606         cx->card = cx18_get_card(cx->options.cardtype - 1);
607         if (cx->card)
608                 CX18_INFO("User specified %s card\n", cx->card->name);
609         else if (cx->options.cardtype != 0)
610                 CX18_ERR("Unknown user specified type, trying to autodetect card\n");
611         if (cx->card == NULL) {
612                 if (cx->pci_dev->subsystem_vendor == CX18_PCI_ID_HAUPPAUGE) {
613                         cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
614                         CX18_INFO("Autodetected Hauppauge card\n");
615                 }
616         }
617         if (cx->card == NULL) {
618                 for (i = 0; (cx->card = cx18_get_card(i)); i++) {
619                         if (cx->card->pci_list == NULL)
620                                 continue;
621                         for (j = 0; cx->card->pci_list[j].device; j++) {
622                                 if (cx->pci_dev->device !=
623                                     cx->card->pci_list[j].device)
624                                         continue;
625                                 if (cx->pci_dev->subsystem_vendor !=
626                                     cx->card->pci_list[j].subsystem_vendor)
627                                         continue;
628                                 if (cx->pci_dev->subsystem_device !=
629                                     cx->card->pci_list[j].subsystem_device)
630                                         continue;
631                                 CX18_INFO("Autodetected %s card\n", cx->card->name);
632                                 goto done;
633                         }
634                 }
635         }
636 done:
637
638         if (cx->card == NULL) {
639                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
640                 CX18_ERR("Unknown card: vendor/device: [%04x:%04x]\n",
641                          cx->pci_dev->vendor, cx->pci_dev->device);
642                 CX18_ERR("              subsystem vendor/device: [%04x:%04x]\n",
643                          cx->pci_dev->subsystem_vendor,
644                          cx->pci_dev->subsystem_device);
645                 CX18_ERR("Defaulting to %s card\n", cx->card->name);
646                 CX18_ERR("Please mail the vendor/device and subsystem vendor/device IDs and what kind of\n");
647                 CX18_ERR("card you have to the ivtv-devel mailinglist (www.ivtvdriver.org)\n");
648                 CX18_ERR("Prefix your subject line with [UNKNOWN CX18 CARD].\n");
649         }
650         cx->v4l2_cap = cx->card->v4l2_capabilities;
651         cx->card_name = cx->card->name;
652         cx->card_i2c = cx->card->i2c;
653 }
654
655 static int __devinit cx18_create_in_workq(struct cx18 *cx)
656 {
657         snprintf(cx->in_workq_name, sizeof(cx->in_workq_name), "%s-in",
658                  cx->v4l2_dev.name);
659         cx->in_work_queue = create_singlethread_workqueue(cx->in_workq_name);
660         if (cx->in_work_queue == NULL) {
661                 CX18_ERR("Unable to create incoming mailbox handler thread\n");
662                 return -ENOMEM;
663         }
664         return 0;
665 }
666
667 static int __devinit cx18_create_out_workq(struct cx18 *cx)
668 {
669         snprintf(cx->out_workq_name, sizeof(cx->out_workq_name), "%s-out",
670                  cx->v4l2_dev.name);
671         cx->out_work_queue = create_workqueue(cx->out_workq_name);
672         if (cx->out_work_queue == NULL) {
673                 CX18_ERR("Unable to create outgoing mailbox handler threads\n");
674                 return -ENOMEM;
675         }
676         return 0;
677 }
678
679 static void __devinit cx18_init_in_work_orders(struct cx18 *cx)
680 {
681         int i;
682         for (i = 0; i < CX18_MAX_IN_WORK_ORDERS; i++) {
683                 cx->in_work_order[i].cx = cx;
684                 cx->in_work_order[i].str = cx->epu_debug_str;
685                 INIT_WORK(&cx->in_work_order[i].work, cx18_in_work_handler);
686         }
687 }
688
689 /* Precondition: the cx18 structure has been memset to 0. Only
690    the dev and instance fields have been filled in.
691    No assumptions on the card type may be made here (see cx18_init_struct2
692    for that).
693  */
694 static int __devinit cx18_init_struct1(struct cx18 *cx)
695 {
696         int ret;
697
698         cx->base_addr = pci_resource_start(cx->pci_dev, 0);
699
700         mutex_init(&cx->serialize_lock);
701         mutex_init(&cx->gpio_lock);
702         mutex_init(&cx->epu2apu_mb_lock);
703         mutex_init(&cx->epu2cpu_mb_lock);
704
705         ret = cx18_create_out_workq(cx);
706         if (ret)
707                 return ret;
708
709         ret = cx18_create_in_workq(cx);
710         if (ret) {
711                 destroy_workqueue(cx->out_work_queue);
712                 return ret;
713         }
714
715         cx18_init_in_work_orders(cx);
716
717         /* start counting open_id at 1 */
718         cx->open_id = 1;
719
720         /* Initial settings */
721         cx2341x_fill_defaults(&cx->params);
722         cx->temporal_strength = cx->params.video_temporal_filter;
723         cx->spatial_strength = cx->params.video_spatial_filter;
724         cx->filter_mode = cx->params.video_spatial_filter_mode |
725                 (cx->params.video_temporal_filter_mode << 1) |
726                 (cx->params.video_median_filter_type << 2);
727         cx->params.port = CX2341X_PORT_MEMORY;
728         cx->params.capabilities =
729                                 CX2341X_CAP_HAS_TS | CX2341X_CAP_HAS_SLICED_VBI;
730         init_waitqueue_head(&cx->cap_w);
731         init_waitqueue_head(&cx->mb_apu_waitq);
732         init_waitqueue_head(&cx->mb_cpu_waitq);
733         init_waitqueue_head(&cx->dma_waitq);
734
735         /* VBI */
736         cx->vbi.in.type = V4L2_BUF_TYPE_VBI_CAPTURE;
737         cx->vbi.sliced_in = &cx->vbi.in.fmt.sliced;
738
739         /* IVTV style VBI insertion into MPEG streams */
740         INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_buf.list);
741         INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_mdl.list);
742         INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_mdl.buf_list);
743         list_add(&cx->vbi.sliced_mpeg_buf.list,
744                  &cx->vbi.sliced_mpeg_mdl.buf_list);
745         return 0;
746 }
747
748 /* Second initialization part. Here the card type has been
749    autodetected. */
750 static void __devinit cx18_init_struct2(struct cx18 *cx)
751 {
752         int i;
753
754         for (i = 0; i < CX18_CARD_MAX_VIDEO_INPUTS; i++)
755                 if (cx->card->video_inputs[i].video_type == 0)
756                         break;
757         cx->nof_inputs = i;
758         for (i = 0; i < CX18_CARD_MAX_AUDIO_INPUTS; i++)
759                 if (cx->card->audio_inputs[i].audio_type == 0)
760                         break;
761         cx->nof_audio_inputs = i;
762
763         /* Find tuner input */
764         for (i = 0; i < cx->nof_inputs; i++) {
765                 if (cx->card->video_inputs[i].video_type ==
766                                 CX18_CARD_INPUT_VID_TUNER)
767                         break;
768         }
769         if (i == cx->nof_inputs)
770                 i = 0;
771         cx->active_input = i;
772         cx->audio_input = cx->card->video_inputs[i].audio_index;
773 }
774
775 static int cx18_setup_pci(struct cx18 *cx, struct pci_dev *pci_dev,
776                           const struct pci_device_id *pci_id)
777 {
778         u16 cmd;
779         unsigned char pci_latency;
780
781         CX18_DEBUG_INFO("Enabling pci device\n");
782
783         if (pci_enable_device(pci_dev)) {
784                 CX18_ERR("Can't enable device %d!\n", cx->instance);
785                 return -EIO;
786         }
787         if (pci_set_dma_mask(pci_dev, 0xffffffff)) {
788                 CX18_ERR("No suitable DMA available, card %d\n", cx->instance);
789                 return -EIO;
790         }
791         if (!request_mem_region(cx->base_addr, CX18_MEM_SIZE, "cx18 encoder")) {
792                 CX18_ERR("Cannot request encoder memory region, card %d\n",
793                          cx->instance);
794                 return -EIO;
795         }
796
797         /* Enable bus mastering and memory mapped IO for the CX23418 */
798         pci_read_config_word(pci_dev, PCI_COMMAND, &cmd);
799         cmd |= PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER;
800         pci_write_config_word(pci_dev, PCI_COMMAND, cmd);
801
802         pci_read_config_byte(pci_dev, PCI_CLASS_REVISION, &cx->card_rev);
803         pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &pci_latency);
804
805         if (pci_latency < 64 && cx18_pci_latency) {
806                 CX18_INFO("Unreasonably low latency timer, "
807                                "setting to 64 (was %d)\n", pci_latency);
808                 pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, 64);
809                 pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &pci_latency);
810         }
811
812         CX18_DEBUG_INFO("cx%d (rev %d) at %02x:%02x.%x, "
813                    "irq: %d, latency: %d, memory: 0x%lx\n",
814                    cx->pci_dev->device, cx->card_rev, pci_dev->bus->number,
815                    PCI_SLOT(pci_dev->devfn), PCI_FUNC(pci_dev->devfn),
816                    cx->pci_dev->irq, pci_latency, (unsigned long)cx->base_addr);
817
818         return 0;
819 }
820
821 static void cx18_init_subdevs(struct cx18 *cx)
822 {
823         u32 hw = cx->card->hw_all;
824         u32 device;
825         int i;
826
827         for (i = 0, device = 1; i < 32; i++, device <<= 1) {
828
829                 if (!(device & hw))
830                         continue;
831
832                 switch (device) {
833                 case CX18_HW_DVB:
834                 case CX18_HW_TVEEPROM:
835                         /* These subordinate devices do not use probing */
836                         cx->hw_flags |= device;
837                         break;
838                 case CX18_HW_418_AV:
839                         /* The A/V decoder gets probed earlier to set PLLs */
840                         /* Just note that the card uses it (i.e. has analog) */
841                         cx->hw_flags |= device;
842                         break;
843                 case CX18_HW_GPIO_RESET_CTRL:
844                         /*
845                          * The Reset Controller gets probed and added to
846                          * hw_flags earlier for i2c adapter/bus initialization
847                          */
848                         break;
849                 case CX18_HW_GPIO_MUX:
850                         if (cx18_gpio_register(cx, device) == 0)
851                                 cx->hw_flags |= device;
852                         break;
853                 default:
854                         if (cx18_i2c_register(cx, i) == 0)
855                                 cx->hw_flags |= device;
856                         break;
857                 }
858         }
859
860         if (cx->hw_flags & CX18_HW_418_AV)
861                 cx->sd_av = cx18_find_hw(cx, CX18_HW_418_AV);
862
863         if (cx->card->hw_muxer != 0)
864                 cx->sd_extmux = cx18_find_hw(cx, cx->card->hw_muxer);
865 }
866
867 static int __devinit cx18_probe(struct pci_dev *pci_dev,
868                                 const struct pci_device_id *pci_id)
869 {
870         int retval = 0;
871         int i;
872         u32 devtype;
873         struct cx18 *cx;
874
875         /* FIXME - module parameter arrays constrain max instances */
876         i = atomic_inc_return(&cx18_instance) - 1;
877         if (i >= CX18_MAX_CARDS) {
878                 printk(KERN_ERR "cx18: cannot manage card %d, driver has a "
879                        "limit of 0 - %d\n", i, CX18_MAX_CARDS - 1);
880                 return -ENOMEM;
881         }
882
883         cx = kzalloc(sizeof(struct cx18), GFP_ATOMIC);
884         if (cx == NULL) {
885                 printk(KERN_ERR "cx18: cannot manage card %d, out of memory\n",
886                        i);
887                 return -ENOMEM;
888         }
889         cx->pci_dev = pci_dev;
890         cx->instance = i;
891
892         retval = v4l2_device_register(&pci_dev->dev, &cx->v4l2_dev);
893         if (retval) {
894                 printk(KERN_ERR "cx18: v4l2_device_register of card %d failed"
895                        "\n", cx->instance);
896                 kfree(cx);
897                 return retval;
898         }
899         snprintf(cx->v4l2_dev.name, sizeof(cx->v4l2_dev.name), "cx18-%d",
900                  cx->instance);
901         CX18_INFO("Initializing card %d\n", cx->instance);
902
903         cx18_process_options(cx);
904         if (cx->options.cardtype == -1) {
905                 retval = -ENODEV;
906                 goto err;
907         }
908
909         retval = cx18_init_struct1(cx);
910         if (retval)
911                 goto err;
912
913         CX18_DEBUG_INFO("base addr: 0x%08x\n", cx->base_addr);
914
915         /* PCI Device Setup */
916         retval = cx18_setup_pci(cx, pci_dev, pci_id);
917         if (retval != 0)
918                 goto free_workqueues;
919
920         /* map io memory */
921         CX18_DEBUG_INFO("attempting ioremap at 0x%08x len 0x%08x\n",
922                    cx->base_addr + CX18_MEM_OFFSET, CX18_MEM_SIZE);
923         cx->enc_mem = ioremap_nocache(cx->base_addr + CX18_MEM_OFFSET,
924                                        CX18_MEM_SIZE);
925         if (!cx->enc_mem) {
926                 CX18_ERR("ioremap failed, perhaps increasing __VMALLOC_RESERVE in page.h\n");
927                 CX18_ERR("or disabling CONFIG_HIGHMEM4G into the kernel would help\n");
928                 retval = -ENOMEM;
929                 goto free_mem;
930         }
931         cx->reg_mem = cx->enc_mem + CX18_REG_OFFSET;
932         devtype = cx18_read_reg(cx, 0xC72028);
933         switch (devtype & 0xff000000) {
934         case 0xff000000:
935                 CX18_INFO("cx23418 revision %08x (A)\n", devtype);
936                 break;
937         case 0x01000000:
938                 CX18_INFO("cx23418 revision %08x (B)\n", devtype);
939                 break;
940         default:
941                 CX18_INFO("cx23418 revision %08x (Unknown)\n", devtype);
942                 break;
943         }
944
945         cx18_init_power(cx, 1);
946         cx18_init_memory(cx);
947
948         cx->scb = (struct cx18_scb __iomem *)(cx->enc_mem + SCB_OFFSET);
949         cx18_init_scb(cx);
950
951         cx18_gpio_init(cx);
952
953         /* Initialize integrated A/V decoder early to set PLLs, just in case */
954         retval = cx18_av_probe(cx);
955         if (retval) {
956                 CX18_ERR("Could not register A/V decoder subdevice\n");
957                 goto free_map;
958         }
959
960         /* Initialize GPIO Reset Controller to do chip resets during i2c init */
961         if (cx->card->hw_all & CX18_HW_GPIO_RESET_CTRL) {
962                 if (cx18_gpio_register(cx, CX18_HW_GPIO_RESET_CTRL) != 0)
963                         CX18_WARN("Could not register GPIO reset controller"
964                                   "subdevice; proceeding anyway.\n");
965                 else
966                         cx->hw_flags |= CX18_HW_GPIO_RESET_CTRL;
967         }
968
969         /* active i2c  */
970         CX18_DEBUG_INFO("activating i2c...\n");
971         retval = init_cx18_i2c(cx);
972         if (retval) {
973                 CX18_ERR("Could not initialize i2c\n");
974                 goto free_map;
975         }
976
977         if (cx->card->hw_all & CX18_HW_TVEEPROM) {
978                 /* Based on the model number the cardtype may be changed.
979                    The PCI IDs are not always reliable. */
980                 cx18_process_eeprom(cx);
981         }
982         if (cx->card->comment)
983                 CX18_INFO("%s", cx->card->comment);
984         if (cx->card->v4l2_capabilities == 0) {
985                 retval = -ENODEV;
986                 goto free_i2c;
987         }
988         cx18_init_memory(cx);
989         cx18_init_scb(cx);
990
991         /* Register IRQ */
992         retval = request_irq(cx->pci_dev->irq, cx18_irq_handler,
993                              IRQF_SHARED | IRQF_DISABLED,
994                              cx->v4l2_dev.name, (void *)cx);
995         if (retval) {
996                 CX18_ERR("Failed to register irq %d\n", retval);
997                 goto free_i2c;
998         }
999
1000         if (cx->std == 0)
1001                 cx->std = V4L2_STD_NTSC_M;
1002
1003         if (cx->options.tuner == -1) {
1004                 for (i = 0; i < CX18_CARD_MAX_TUNERS; i++) {
1005                         if ((cx->std & cx->card->tuners[i].std) == 0)
1006                                 continue;
1007                         cx->options.tuner = cx->card->tuners[i].tuner;
1008                         break;
1009                 }
1010         }
1011         /* if no tuner was found, then pick the first tuner in the card list */
1012         if (cx->options.tuner == -1 && cx->card->tuners[0].std) {
1013                 cx->std = cx->card->tuners[0].std;
1014                 if (cx->std & V4L2_STD_PAL)
1015                         cx->std = V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
1016                 else if (cx->std & V4L2_STD_NTSC)
1017                         cx->std = V4L2_STD_NTSC_M;
1018                 else if (cx->std & V4L2_STD_SECAM)
1019                         cx->std = V4L2_STD_SECAM_L;
1020                 cx->options.tuner = cx->card->tuners[0].tuner;
1021         }
1022         if (cx->options.radio == -1)
1023                 cx->options.radio = (cx->card->radio_input.audio_type != 0);
1024
1025         /* The card is now fully identified, continue with card-specific
1026            initialization. */
1027         cx18_init_struct2(cx);
1028
1029         cx18_init_subdevs(cx);
1030
1031         if (cx->std & V4L2_STD_525_60)
1032                 cx->is_60hz = 1;
1033         else
1034                 cx->is_50hz = 1;
1035
1036         cx->params.video_gop_size = cx->is_60hz ? 15 : 12;
1037
1038         if (cx->options.radio > 0)
1039                 cx->v4l2_cap |= V4L2_CAP_RADIO;
1040
1041         if (cx->options.tuner > -1) {
1042                 struct tuner_setup setup;
1043
1044                 setup.addr = ADDR_UNSET;
1045                 setup.type = cx->options.tuner;
1046                 setup.mode_mask = T_ANALOG_TV;  /* matches TV tuners */
1047                 setup.tuner_callback = (setup.type == TUNER_XC2028) ?
1048                         cx18_reset_tuner_gpio : NULL;
1049                 cx18_call_all(cx, tuner, s_type_addr, &setup);
1050                 if (setup.type == TUNER_XC2028) {
1051                         static struct xc2028_ctrl ctrl = {
1052                                 .fname = XC2028_DEFAULT_FIRMWARE,
1053                                 .max_len = 64,
1054                         };
1055                         struct v4l2_priv_tun_config cfg = {
1056                                 .tuner = cx->options.tuner,
1057                                 .priv = &ctrl,
1058                         };
1059                         cx18_call_all(cx, tuner, s_config, &cfg);
1060                 }
1061         }
1062
1063         /* The tuner is fixed to the standard. The other inputs (e.g. S-Video)
1064            are not. */
1065         cx->tuner_std = cx->std;
1066
1067         retval = cx18_streams_setup(cx);
1068         if (retval) {
1069                 CX18_ERR("Error %d setting up streams\n", retval);
1070                 goto free_irq;
1071         }
1072         retval = cx18_streams_register(cx);
1073         if (retval) {
1074                 CX18_ERR("Error %d registering devices\n", retval);
1075                 goto free_streams;
1076         }
1077
1078         CX18_INFO("Initialized card: %s\n", cx->card_name);
1079
1080         /* Load cx18 submodules (cx18-alsa) */
1081         request_modules(cx);
1082
1083         return 0;
1084
1085 free_streams:
1086         cx18_streams_cleanup(cx, 1);
1087 free_irq:
1088         free_irq(cx->pci_dev->irq, (void *)cx);
1089 free_i2c:
1090         exit_cx18_i2c(cx);
1091 free_map:
1092         cx18_iounmap(cx);
1093 free_mem:
1094         release_mem_region(cx->base_addr, CX18_MEM_SIZE);
1095 free_workqueues:
1096         destroy_workqueue(cx->in_work_queue);
1097         destroy_workqueue(cx->out_work_queue);
1098 err:
1099         if (retval == 0)
1100                 retval = -ENODEV;
1101         CX18_ERR("Error %d on initialization\n", retval);
1102
1103         v4l2_device_unregister(&cx->v4l2_dev);
1104         kfree(cx);
1105         return retval;
1106 }
1107
1108 int cx18_init_on_first_open(struct cx18 *cx)
1109 {
1110         int video_input;
1111         int fw_retry_count = 3;
1112         struct v4l2_frequency vf;
1113         struct cx18_open_id fh;
1114
1115         fh.cx = cx;
1116
1117         if (test_bit(CX18_F_I_FAILED, &cx->i_flags))
1118                 return -ENXIO;
1119
1120         if (test_and_set_bit(CX18_F_I_INITED, &cx->i_flags))
1121                 return 0;
1122
1123         while (--fw_retry_count > 0) {
1124                 /* load firmware */
1125                 if (cx18_firmware_init(cx) == 0)
1126                         break;
1127                 if (fw_retry_count > 1)
1128                         CX18_WARN("Retry loading firmware\n");
1129         }
1130
1131         if (fw_retry_count == 0) {
1132                 set_bit(CX18_F_I_FAILED, &cx->i_flags);
1133                 return -ENXIO;
1134         }
1135         set_bit(CX18_F_I_LOADED_FW, &cx->i_flags);
1136
1137         /*
1138          * Init the firmware twice to work around a silicon bug
1139          * with the digital TS.
1140          *
1141          * The second firmware load requires us to normalize the APU state,
1142          * or the audio for the first analog capture will be badly incorrect.
1143          *
1144          * I can't seem to call APU_RESETAI and have it succeed without the
1145          * APU capturing audio, so we start and stop it here to do the reset
1146          */
1147
1148         /* MPEG Encoding, 224 kbps, MPEG Layer II, 48 ksps */
1149         cx18_vapi(cx, CX18_APU_START, 2, CX18_APU_ENCODING_METHOD_MPEG|0xb9, 0);
1150         cx18_vapi(cx, CX18_APU_RESETAI, 0);
1151         cx18_vapi(cx, CX18_APU_STOP, 1, CX18_APU_ENCODING_METHOD_MPEG);
1152
1153         fw_retry_count = 3;
1154         while (--fw_retry_count > 0) {
1155                 /* load firmware */
1156                 if (cx18_firmware_init(cx) == 0)
1157                         break;
1158                 if (fw_retry_count > 1)
1159                         CX18_WARN("Retry loading firmware\n");
1160         }
1161
1162         if (fw_retry_count == 0) {
1163                 set_bit(CX18_F_I_FAILED, &cx->i_flags);
1164                 return -ENXIO;
1165         }
1166
1167         /*
1168          * The second firmware load requires us to normalize the APU state,
1169          * or the audio for the first analog capture will be badly incorrect.
1170          *
1171          * I can't seem to call APU_RESETAI and have it succeed without the
1172          * APU capturing audio, so we start and stop it here to do the reset
1173          */
1174
1175         /* MPEG Encoding, 224 kbps, MPEG Layer II, 48 ksps */
1176         cx18_vapi(cx, CX18_APU_START, 2, CX18_APU_ENCODING_METHOD_MPEG|0xb9, 0);
1177         cx18_vapi(cx, CX18_APU_RESETAI, 0);
1178         cx18_vapi(cx, CX18_APU_STOP, 1, CX18_APU_ENCODING_METHOD_MPEG);
1179
1180         /* Init the A/V decoder, if it hasn't been already */
1181         v4l2_subdev_call(cx->sd_av, core, load_fw);
1182
1183         vf.tuner = 0;
1184         vf.type = V4L2_TUNER_ANALOG_TV;
1185         vf.frequency = 6400; /* the tuner 'baseline' frequency */
1186
1187         /* Set initial frequency. For PAL/SECAM broadcasts no
1188            'default' channel exists AFAIK. */
1189         if (cx->std == V4L2_STD_NTSC_M_JP)
1190                 vf.frequency = 1460;    /* ch. 1 91250*16/1000 */
1191         else if (cx->std & V4L2_STD_NTSC_M)
1192                 vf.frequency = 1076;    /* ch. 4 67250*16/1000 */
1193
1194         video_input = cx->active_input;
1195         cx->active_input++;     /* Force update of input */
1196         cx18_s_input(NULL, &fh, video_input);
1197
1198         /* Let the VIDIOC_S_STD ioctl do all the work, keeps the code
1199            in one place. */
1200         cx->std++;              /* Force full standard initialization */
1201         cx18_s_std(NULL, &fh, &cx->tuner_std);
1202         cx18_s_frequency(NULL, &fh, &vf);
1203         return 0;
1204 }
1205
1206 static void cx18_cancel_in_work_orders(struct cx18 *cx)
1207 {
1208         int i;
1209         for (i = 0; i < CX18_MAX_IN_WORK_ORDERS; i++)
1210                 cancel_work_sync(&cx->in_work_order[i].work);
1211 }
1212
1213 static void cx18_cancel_out_work_orders(struct cx18 *cx)
1214 {
1215         int i;
1216         for (i = 0; i < CX18_MAX_STREAMS; i++)
1217                 if (&cx->streams[i].video_dev != NULL)
1218                         cancel_work_sync(&cx->streams[i].out_work_order);
1219 }
1220
1221 static void cx18_remove(struct pci_dev *pci_dev)
1222 {
1223         struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
1224         struct cx18 *cx = to_cx18(v4l2_dev);
1225         int i;
1226
1227         CX18_DEBUG_INFO("Removing Card\n");
1228
1229         /* Stop all captures */
1230         CX18_DEBUG_INFO("Stopping all streams\n");
1231         if (atomic_read(&cx->tot_capturing) > 0)
1232                 cx18_stop_all_captures(cx);
1233
1234         /* Stop interrupts that cause incoming work to be queued */
1235         cx18_sw1_irq_disable(cx, IRQ_CPU_TO_EPU | IRQ_APU_TO_EPU);
1236
1237         /* Incoming work can cause outgoing work, so clean up incoming first */
1238         cx18_cancel_in_work_orders(cx);
1239         cx18_cancel_out_work_orders(cx);
1240
1241         /* Stop ack interrupts that may have been needed for work to finish */
1242         cx18_sw2_irq_disable(cx, IRQ_CPU_TO_EPU_ACK | IRQ_APU_TO_EPU_ACK);
1243
1244         cx18_halt_firmware(cx);
1245
1246         destroy_workqueue(cx->in_work_queue);
1247         destroy_workqueue(cx->out_work_queue);
1248
1249         cx18_streams_cleanup(cx, 1);
1250
1251         exit_cx18_i2c(cx);
1252
1253         free_irq(cx->pci_dev->irq, (void *)cx);
1254
1255         cx18_iounmap(cx);
1256
1257         release_mem_region(cx->base_addr, CX18_MEM_SIZE);
1258
1259         pci_disable_device(cx->pci_dev);
1260
1261         if (cx->vbi.sliced_mpeg_data[0] != NULL)
1262                 for (i = 0; i < CX18_VBI_FRAMES; i++)
1263                         kfree(cx->vbi.sliced_mpeg_data[i]);
1264
1265         CX18_INFO("Removed %s\n", cx->card_name);
1266
1267         v4l2_device_unregister(v4l2_dev);
1268         kfree(cx);
1269 }
1270
1271
1272 /* define a pci_driver for card detection */
1273 static struct pci_driver cx18_pci_driver = {
1274       .name =     "cx18",
1275       .id_table = cx18_pci_tbl,
1276       .probe =    cx18_probe,
1277       .remove =   cx18_remove,
1278 };
1279
1280 static int __init module_start(void)
1281 {
1282         printk(KERN_INFO "cx18:  Start initialization, version %s\n",
1283                CX18_VERSION);
1284
1285         /* Validate parameters */
1286         if (cx18_first_minor < 0 || cx18_first_minor >= CX18_MAX_CARDS) {
1287                 printk(KERN_ERR "cx18:  Exiting, cx18_first_minor must be between 0 and %d\n",
1288                      CX18_MAX_CARDS - 1);
1289                 return -1;
1290         }
1291
1292         if (cx18_debug < 0 || cx18_debug > 511) {
1293                 cx18_debug = 0;
1294                 printk(KERN_INFO "cx18:   Debug value must be >= 0 and <= 511!\n");
1295         }
1296
1297         if (pci_register_driver(&cx18_pci_driver)) {
1298                 printk(KERN_ERR "cx18:   Error detecting PCI card\n");
1299                 return -ENODEV;
1300         }
1301         printk(KERN_INFO "cx18:  End initialization\n");
1302         return 0;
1303 }
1304
1305 static void __exit module_cleanup(void)
1306 {
1307         pci_unregister_driver(&cx18_pci_driver);
1308 }
1309
1310 module_init(module_start);
1311 module_exit(module_cleanup);