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