V4L/DVB (9727): cx18: Adjust outgoing mailbox timeouts and remove statistics logging
[safe/jmp/linux-2.6] / 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-streams.h"
34 #include "cx18-av-core.h"
35 #include "cx18-scb.h"
36 #include "cx18-mailbox.h"
37 #include "cx18-ioctl.h"
38 #include "tuner-xc2028.h"
39
40 #include <media/tveeprom.h>
41
42
43 /* var to keep track of the number of array elements in use */
44 int cx18_cards_active;
45
46 /* If you have already X v4l cards, then set this to X. This way
47    the device numbers stay matched. Example: you have a WinTV card
48    without radio and a Compro H900 with. Normally this would give a
49    video1 device together with a radio0 device for the Compro. By
50    setting this to 1 you ensure that radio0 is now also radio1. */
51 int cx18_first_minor;
52
53 /* Master variable for all cx18 info */
54 struct cx18 *cx18_cards[CX18_MAX_CARDS];
55
56 /* Protects cx18_cards_active */
57 DEFINE_SPINLOCK(cx18_cards_lock);
58
59 /* Queue for deferrable IRQ handling work for all cx18 cards in system */
60 struct workqueue_struct *cx18_work_queue;
61
62 /* add your revision and whatnot here */
63 static struct pci_device_id cx18_pci_tbl[] __devinitdata = {
64         {PCI_VENDOR_ID_CX, PCI_DEVICE_ID_CX23418,
65          PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
66         {0,}
67 };
68
69 MODULE_DEVICE_TABLE(pci, cx18_pci_tbl);
70
71 /* Parameter declarations */
72 static int cardtype[CX18_MAX_CARDS];
73 static int tuner[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
74                                      -1, -1, -1, -1, -1, -1, -1, -1,
75                                      -1, -1, -1, -1, -1, -1, -1, -1,
76                                      -1, -1, -1, -1, -1, -1, -1, -1 };
77 static int radio[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
78                                      -1, -1, -1, -1, -1, -1, -1, -1,
79                                      -1, -1, -1, -1, -1, -1, -1, -1,
80                                      -1, -1, -1, -1, -1, -1, -1, -1 };
81 static unsigned cardtype_c = 1;
82 static unsigned tuner_c = 1;
83 static unsigned radio_c = 1;
84 static char pal[] = "--";
85 static char secam[] = "--";
86 static char ntsc[] = "-";
87
88 /* Buffers */
89 static int enc_mpg_buffers = CX18_DEFAULT_ENC_MPG_BUFFERS;
90 static int enc_ts_buffers = CX18_DEFAULT_ENC_TS_BUFFERS;
91 static int enc_yuv_buffers = CX18_DEFAULT_ENC_YUV_BUFFERS;
92 static int enc_vbi_buffers = CX18_DEFAULT_ENC_VBI_BUFFERS;
93 static int enc_pcm_buffers = CX18_DEFAULT_ENC_PCM_BUFFERS;
94
95 static int cx18_pci_latency = 1;
96
97 static int mmio_ndelay;
98 static int retry_mmio = 1;
99
100 int cx18_debug;
101
102 module_param_array(tuner, int, &tuner_c, 0644);
103 module_param_array(radio, bool, &radio_c, 0644);
104 module_param_array(cardtype, int, &cardtype_c, 0644);
105 module_param_string(pal, pal, sizeof(pal), 0644);
106 module_param_string(secam, secam, sizeof(secam), 0644);
107 module_param_string(ntsc, ntsc, sizeof(ntsc), 0644);
108 module_param_named(debug, cx18_debug, int, 0644);
109 module_param(mmio_ndelay, int, 0644);
110 module_param(retry_mmio, int, 0644);
111 module_param(cx18_pci_latency, int, 0644);
112 module_param(cx18_first_minor, int, 0644);
113
114 module_param(enc_mpg_buffers, int, 0644);
115 module_param(enc_ts_buffers, int, 0644);
116 module_param(enc_yuv_buffers, int, 0644);
117 module_param(enc_vbi_buffers, int, 0644);
118 module_param(enc_pcm_buffers, int, 0644);
119
120 MODULE_PARM_DESC(tuner, "Tuner type selection,\n"
121                         "\t\t\tsee tuner.h for values");
122 MODULE_PARM_DESC(radio,
123                  "Enable or disable the radio. Use only if autodetection\n"
124                  "\t\t\tfails. 0 = disable, 1 = enable");
125 MODULE_PARM_DESC(cardtype,
126                  "Only use this option if your card is not detected properly.\n"
127                  "\t\tSpecify card type:\n"
128                  "\t\t\t 1 = Hauppauge HVR 1600 (ESMT memory)\n"
129                  "\t\t\t 2 = Hauppauge HVR 1600 (Samsung memory)\n"
130                  "\t\t\t 3 = Compro VideoMate H900\n"
131                  "\t\t\t 4 = Yuan MPC718\n"
132                  "\t\t\t 5 = Conexant Raptor PAL/SECAM\n"
133                  "\t\t\t 6 = Toshiba Qosmio DVB-T/Analog\n"
134                  "\t\t\t 7 = Leadtek WinFast PVR2100\n"
135                  "\t\t\t 0 = Autodetect (default)\n"
136                  "\t\t\t-1 = Ignore this card\n\t\t");
137 MODULE_PARM_DESC(pal, "Set PAL standard: B, G, H, D, K, I, M, N, Nc, 60");
138 MODULE_PARM_DESC(secam, "Set SECAM standard: B, G, H, D, K, L, LC");
139 MODULE_PARM_DESC(ntsc, "Set NTSC standard: M, J, K");
140 MODULE_PARM_DESC(debug,
141                  "Debug level (bitmask). Default: 0\n"
142                  "\t\t\t  1/0x0001: warning\n"
143                  "\t\t\t  2/0x0002: info\n"
144                  "\t\t\t  4/0x0004: mailbox\n"
145                  "\t\t\t  8/0x0008: dma\n"
146                  "\t\t\t 16/0x0010: ioctl\n"
147                  "\t\t\t 32/0x0020: file\n"
148                  "\t\t\t 64/0x0040: i2c\n"
149                  "\t\t\t128/0x0080: irq\n"
150                  "\t\t\t256/0x0100: high volume\n");
151 MODULE_PARM_DESC(cx18_pci_latency,
152                  "Change the PCI latency to 64 if lower: 0 = No, 1 = Yes,\n"
153                  "\t\t\tDefault: Yes");
154 MODULE_PARM_DESC(retry_mmio,
155                  "(Deprecated) MMIO writes are now always checked and retried\n"
156                  "\t\t\tEffectively: 1 [Yes]");
157 MODULE_PARM_DESC(mmio_ndelay,
158                  "(Deprecated) MMIO accesses are now never purposely delayed\n"
159                  "\t\t\tEffectively: 0 ns");
160 MODULE_PARM_DESC(enc_mpg_buffers,
161                  "Encoder MPG Buffers (in MB)\n"
162                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_MPG_BUFFERS));
163 MODULE_PARM_DESC(enc_ts_buffers,
164                  "Encoder TS Buffers (in MB)\n"
165                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_TS_BUFFERS));
166 MODULE_PARM_DESC(enc_yuv_buffers,
167                  "Encoder YUV Buffers (in MB)\n"
168                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_YUV_BUFFERS));
169 MODULE_PARM_DESC(enc_vbi_buffers,
170                  "Encoder VBI Buffers (in MB)\n"
171                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_VBI_BUFFERS));
172 MODULE_PARM_DESC(enc_pcm_buffers,
173                  "Encoder PCM buffers (in MB)\n"
174                  "\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_PCM_BUFFERS));
175
176 MODULE_PARM_DESC(cx18_first_minor, "Set kernel number assigned to first card");
177
178 MODULE_AUTHOR("Hans Verkuil");
179 MODULE_DESCRIPTION("CX23418 driver");
180 MODULE_SUPPORTED_DEVICE("CX23418 MPEG2 encoder");
181 MODULE_LICENSE("GPL");
182
183 MODULE_VERSION(CX18_VERSION);
184
185 /* Generic utility functions */
186 int cx18_msleep_timeout(unsigned int msecs, int intr)
187 {
188         long int timeout = msecs_to_jiffies(msecs);
189         int sig;
190
191         do {
192                 set_current_state(intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
193                 timeout = schedule_timeout(timeout);
194                 sig = intr ? signal_pending(current) : 0;
195         } while (!sig && timeout);
196         return sig;
197 }
198
199 /* Release ioremapped memory */
200 static void cx18_iounmap(struct cx18 *cx)
201 {
202         if (cx == NULL)
203                 return;
204
205         /* Release io memory */
206         if (cx->enc_mem != NULL) {
207                 CX18_DEBUG_INFO("releasing enc_mem\n");
208                 iounmap(cx->enc_mem);
209                 cx->enc_mem = NULL;
210         }
211 }
212
213 /* Hauppauge card? get values from tveeprom */
214 void cx18_read_eeprom(struct cx18 *cx, struct tveeprom *tv)
215 {
216         u8 eedata[256];
217
218         cx->i2c_client[0].addr = 0xA0 >> 1;
219         tveeprom_read(&cx->i2c_client[0], eedata, sizeof(eedata));
220         tveeprom_hauppauge_analog(&cx->i2c_client[0], tv, eedata);
221 }
222
223 static void cx18_process_eeprom(struct cx18 *cx)
224 {
225         struct tveeprom tv;
226
227         cx18_read_eeprom(cx, &tv);
228
229         /* Many thanks to Steven Toth from Hauppauge for providing the
230            model numbers */
231         /* Note: the Samsung memory models cannot be reliably determined
232            from the model number. Use the cardtype module option if you
233            have one of these preproduction models. */
234         switch (tv.model) {
235         case 74000 ... 74999:
236                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
237                 break;
238         case 0:
239                 CX18_ERR("Invalid EEPROM\n");
240                 return;
241         default:
242                 CX18_ERR("Unknown model %d, defaulting to HVR-1600\n", tv.model);
243                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
244                 break;
245         }
246
247         cx->v4l2_cap = cx->card->v4l2_capabilities;
248         cx->card_name = cx->card->name;
249         cx->card_i2c = cx->card->i2c;
250
251         CX18_INFO("Autodetected %s\n", cx->card_name);
252
253         if (tv.tuner_type == TUNER_ABSENT)
254                 CX18_ERR("tveeprom cannot autodetect tuner!");
255
256         if (cx->options.tuner == -1)
257                 cx->options.tuner = tv.tuner_type;
258         if (cx->options.radio == -1)
259                 cx->options.radio = (tv.has_radio != 0);
260
261         if (cx->std != 0)
262                 /* user specified tuner standard */
263                 return;
264
265         /* autodetect tuner standard */
266         if (tv.tuner_formats & V4L2_STD_PAL) {
267                 CX18_DEBUG_INFO("PAL tuner detected\n");
268                 cx->std |= V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
269         } else if (tv.tuner_formats & V4L2_STD_NTSC) {
270                 CX18_DEBUG_INFO("NTSC tuner detected\n");
271                 cx->std |= V4L2_STD_NTSC_M;
272         } else if (tv.tuner_formats & V4L2_STD_SECAM) {
273                 CX18_DEBUG_INFO("SECAM tuner detected\n");
274                 cx->std |= V4L2_STD_SECAM_L;
275         } else {
276                 CX18_INFO("No tuner detected, default to NTSC-M\n");
277                 cx->std |= V4L2_STD_NTSC_M;
278         }
279 }
280
281 static v4l2_std_id cx18_parse_std(struct cx18 *cx)
282 {
283         switch (pal[0]) {
284         case '6':
285                 return V4L2_STD_PAL_60;
286         case 'b':
287         case 'B':
288         case 'g':
289         case 'G':
290                 return V4L2_STD_PAL_BG;
291         case 'h':
292         case 'H':
293                 return V4L2_STD_PAL_H;
294         case 'n':
295         case 'N':
296                 if (pal[1] == 'c' || pal[1] == 'C')
297                         return V4L2_STD_PAL_Nc;
298                 return V4L2_STD_PAL_N;
299         case 'i':
300         case 'I':
301                 return V4L2_STD_PAL_I;
302         case 'd':
303         case 'D':
304         case 'k':
305         case 'K':
306                 return V4L2_STD_PAL_DK;
307         case 'M':
308         case 'm':
309                 return V4L2_STD_PAL_M;
310         case '-':
311                 break;
312         default:
313                 CX18_WARN("pal= argument not recognised\n");
314                 return 0;
315         }
316
317         switch (secam[0]) {
318         case 'b':
319         case 'B':
320         case 'g':
321         case 'G':
322         case 'h':
323         case 'H':
324                 return V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H;
325         case 'd':
326         case 'D':
327         case 'k':
328         case 'K':
329                 return V4L2_STD_SECAM_DK;
330         case 'l':
331         case 'L':
332                 if (secam[1] == 'C' || secam[1] == 'c')
333                         return V4L2_STD_SECAM_LC;
334                 return V4L2_STD_SECAM_L;
335         case '-':
336                 break;
337         default:
338                 CX18_WARN("secam= argument not recognised\n");
339                 return 0;
340         }
341
342         switch (ntsc[0]) {
343         case 'm':
344         case 'M':
345                 return V4L2_STD_NTSC_M;
346         case 'j':
347         case 'J':
348                 return V4L2_STD_NTSC_M_JP;
349         case 'k':
350         case 'K':
351                 return V4L2_STD_NTSC_M_KR;
352         case '-':
353                 break;
354         default:
355                 CX18_WARN("ntsc= argument not recognised\n");
356                 return 0;
357         }
358
359         /* no match found */
360         return 0;
361 }
362
363 static void cx18_process_options(struct cx18 *cx)
364 {
365         int i, j;
366
367         cx->options.megabytes[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_buffers;
368         cx->options.megabytes[CX18_ENC_STREAM_TYPE_TS] = enc_ts_buffers;
369         cx->options.megabytes[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_buffers;
370         cx->options.megabytes[CX18_ENC_STREAM_TYPE_VBI] = enc_vbi_buffers;
371         cx->options.megabytes[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_buffers;
372         cx->options.cardtype = cardtype[cx->num];
373         cx->options.tuner = tuner[cx->num];
374         cx->options.radio = radio[cx->num];
375
376         cx->std = cx18_parse_std(cx);
377         if (cx->options.cardtype == -1) {
378                 CX18_INFO("Ignore card\n");
379                 return;
380         }
381         cx->card = cx18_get_card(cx->options.cardtype - 1);
382         if (cx->card)
383                 CX18_INFO("User specified %s card\n", cx->card->name);
384         else if (cx->options.cardtype != 0)
385                 CX18_ERR("Unknown user specified type, trying to autodetect card\n");
386         if (cx->card == NULL) {
387                 if (cx->dev->subsystem_vendor == CX18_PCI_ID_HAUPPAUGE) {
388                         cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
389                         CX18_INFO("Autodetected Hauppauge card\n");
390                 }
391         }
392         if (cx->card == NULL) {
393                 for (i = 0; (cx->card = cx18_get_card(i)); i++) {
394                         if (cx->card->pci_list == NULL)
395                                 continue;
396                         for (j = 0; cx->card->pci_list[j].device; j++) {
397                                 if (cx->dev->device !=
398                                     cx->card->pci_list[j].device)
399                                         continue;
400                                 if (cx->dev->subsystem_vendor !=
401                                     cx->card->pci_list[j].subsystem_vendor)
402                                         continue;
403                                 if (cx->dev->subsystem_device !=
404                                     cx->card->pci_list[j].subsystem_device)
405                                         continue;
406                                 CX18_INFO("Autodetected %s card\n", cx->card->name);
407                                 goto done;
408                         }
409                 }
410         }
411 done:
412
413         if (cx->card == NULL) {
414                 cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
415                 CX18_ERR("Unknown card: vendor/device: [%04x:%04x]\n",
416                      cx->dev->vendor, cx->dev->device);
417                 CX18_ERR("              subsystem vendor/device: [%04x:%04x]\n",
418                      cx->dev->subsystem_vendor, cx->dev->subsystem_device);
419                 CX18_ERR("Defaulting to %s card\n", cx->card->name);
420                 CX18_ERR("Please mail the vendor/device and subsystem vendor/device IDs and what kind of\n");
421                 CX18_ERR("card you have to the ivtv-devel mailinglist (www.ivtvdriver.org)\n");
422                 CX18_ERR("Prefix your subject line with [UNKNOWN CX18 CARD].\n");
423         }
424         cx->v4l2_cap = cx->card->v4l2_capabilities;
425         cx->card_name = cx->card->name;
426         cx->card_i2c = cx->card->i2c;
427 }
428
429 /* Precondition: the cx18 structure has been memset to 0. Only
430    the dev and num fields have been filled in.
431    No assumptions on the card type may be made here (see cx18_init_struct2
432    for that).
433  */
434 static int __devinit cx18_init_struct1(struct cx18 *cx)
435 {
436         int i;
437
438         cx->base_addr = pci_resource_start(cx->dev, 0);
439
440         mutex_init(&cx->serialize_lock);
441         mutex_init(&cx->i2c_bus_lock[0]);
442         mutex_init(&cx->i2c_bus_lock[1]);
443         mutex_init(&cx->gpio_lock);
444         mutex_init(&cx->epu2apu_mb_lock);
445         mutex_init(&cx->epu2cpu_mb_lock);
446
447         spin_lock_init(&cx->lock);
448
449         for (i = 0; i < CX18_MAX_EPU_WORK_ORDERS; i++) {
450                 cx->epu_work_order[i].cx = cx;
451                 cx->epu_work_order[i].str = cx->epu_debug_str;
452                 INIT_WORK(&cx->epu_work_order[i].work, cx18_epu_work_handler);
453         }
454
455         /* start counting open_id at 1 */
456         cx->open_id = 1;
457
458         /* Initial settings */
459         cx2341x_fill_defaults(&cx->params);
460         cx->temporal_strength = cx->params.video_temporal_filter;
461         cx->spatial_strength = cx->params.video_spatial_filter;
462         cx->filter_mode = cx->params.video_spatial_filter_mode |
463                 (cx->params.video_temporal_filter_mode << 1) |
464                 (cx->params.video_median_filter_type << 2);
465         cx->params.port = CX2341X_PORT_MEMORY;
466         cx->params.capabilities = CX2341X_CAP_HAS_TS;
467         init_waitqueue_head(&cx->cap_w);
468         init_waitqueue_head(&cx->mb_apu_waitq);
469         init_waitqueue_head(&cx->mb_cpu_waitq);
470         init_waitqueue_head(&cx->dma_waitq);
471
472         /* VBI */
473         cx->vbi.in.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
474         cx->vbi.sliced_in = &cx->vbi.in.fmt.sliced;
475         cx->vbi.raw_size = 1456;
476         cx->vbi.raw_decoder_line_size = 1456;
477         cx->vbi.raw_decoder_sav_odd_field = 0x20;
478         cx->vbi.raw_decoder_sav_even_field = 0x60;
479         cx->vbi.sliced_decoder_line_size = 272;
480         cx->vbi.sliced_decoder_sav_odd_field = 0xB0;
481         cx->vbi.sliced_decoder_sav_even_field = 0xF0;
482         return 0;
483 }
484
485 /* Second initialization part. Here the card type has been
486    autodetected. */
487 static void __devinit cx18_init_struct2(struct cx18 *cx)
488 {
489         int i;
490
491         for (i = 0; i < CX18_CARD_MAX_VIDEO_INPUTS; i++)
492                 if (cx->card->video_inputs[i].video_type == 0)
493                         break;
494         cx->nof_inputs = i;
495         for (i = 0; i < CX18_CARD_MAX_AUDIO_INPUTS; i++)
496                 if (cx->card->audio_inputs[i].audio_type == 0)
497                         break;
498         cx->nof_audio_inputs = i;
499
500         /* Find tuner input */
501         for (i = 0; i < cx->nof_inputs; i++) {
502                 if (cx->card->video_inputs[i].video_type ==
503                                 CX18_CARD_INPUT_VID_TUNER)
504                         break;
505         }
506         if (i == cx->nof_inputs)
507                 i = 0;
508         cx->active_input = i;
509         cx->audio_input = cx->card->video_inputs[i].audio_index;
510         cx->av_state.vid_input = CX18_AV_COMPOSITE7;
511         cx->av_state.aud_input = CX18_AV_AUDIO8;
512         cx->av_state.audclk_freq = 48000;
513         cx->av_state.audmode = V4L2_TUNER_MODE_LANG1;
514         cx->av_state.vbi_line_offset = 8;
515 }
516
517 static int cx18_setup_pci(struct cx18 *cx, struct pci_dev *dev,
518                           const struct pci_device_id *pci_id)
519 {
520         u16 cmd;
521         unsigned char pci_latency;
522
523         CX18_DEBUG_INFO("Enabling pci device\n");
524
525         if (pci_enable_device(dev)) {
526                 CX18_ERR("Can't enable device %d!\n", cx->num);
527                 return -EIO;
528         }
529         if (pci_set_dma_mask(dev, 0xffffffff)) {
530                 CX18_ERR("No suitable DMA available on card %d.\n", cx->num);
531                 return -EIO;
532         }
533         if (!request_mem_region(cx->base_addr, CX18_MEM_SIZE, "cx18 encoder")) {
534                 CX18_ERR("Cannot request encoder memory region on card %d.\n", cx->num);
535                 return -EIO;
536         }
537
538         /* Enable bus mastering and memory mapped IO for the CX23418 */
539         pci_read_config_word(dev, PCI_COMMAND, &cmd);
540         cmd |= PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER;
541         pci_write_config_word(dev, PCI_COMMAND, cmd);
542
543         pci_read_config_byte(dev, PCI_CLASS_REVISION, &cx->card_rev);
544         pci_read_config_byte(dev, PCI_LATENCY_TIMER, &pci_latency);
545
546         if (pci_latency < 64 && cx18_pci_latency) {
547                 CX18_INFO("Unreasonably low latency timer, "
548                                "setting to 64 (was %d)\n", pci_latency);
549                 pci_write_config_byte(dev, PCI_LATENCY_TIMER, 64);
550                 pci_read_config_byte(dev, PCI_LATENCY_TIMER, &pci_latency);
551         }
552
553         CX18_DEBUG_INFO("cx%d (rev %d) at %02x:%02x.%x, "
554                    "irq: %d, latency: %d, memory: 0x%lx\n",
555                    cx->dev->device, cx->card_rev, dev->bus->number,
556                    PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
557                    cx->dev->irq, pci_latency, (unsigned long)cx->base_addr);
558
559         return 0;
560 }
561
562 #ifdef MODULE
563 static u32 cx18_request_module(struct cx18 *cx, u32 hw,
564                 const char *name, u32 id)
565 {
566         if ((hw & id) == 0)
567                 return hw;
568         if (request_module(name) != 0) {
569                 CX18_ERR("Failed to load module %s\n", name);
570                 return hw & ~id;
571         }
572         CX18_DEBUG_INFO("Loaded module %s\n", name);
573         return hw;
574 }
575 #endif
576
577 static void cx18_load_and_init_modules(struct cx18 *cx)
578 {
579         u32 hw = cx->card->hw_all;
580         int i;
581
582 #ifdef MODULE
583         /* load modules */
584 #ifdef CONFIG_MEDIA_TUNER_MODULE
585         hw = cx18_request_module(cx, hw, "tuner", CX18_HW_TUNER);
586 #endif
587 #ifdef CONFIG_VIDEO_CS5345_MODULE
588         hw = cx18_request_module(cx, hw, "cs5345", CX18_HW_CS5345);
589 #endif
590 #endif
591
592         /* check which i2c devices are actually found */
593         for (i = 0; i < 32; i++) {
594                 u32 device = 1 << i;
595
596                 if (!(device & hw))
597                         continue;
598                 if (device == CX18_HW_GPIO || device == CX18_HW_TVEEPROM ||
599                     device == CX18_HW_CX23418 || device == CX18_HW_DVB) {
600                         /* These 'devices' do not use i2c probing */
601                         cx->hw_flags |= device;
602                         continue;
603                 }
604                 cx18_i2c_register(cx, i);
605                 if (cx18_i2c_hw_addr(cx, device) > 0)
606                         cx->hw_flags |= device;
607         }
608
609         hw = cx->hw_flags;
610 }
611
612 static int __devinit cx18_probe(struct pci_dev *dev,
613                                 const struct pci_device_id *pci_id)
614 {
615         int retval = 0;
616         int i;
617         int vbi_buf_size;
618         u32 devtype;
619         struct cx18 *cx;
620
621         spin_lock(&cx18_cards_lock);
622
623         /* Make sure we've got a place for this card */
624         if (cx18_cards_active == CX18_MAX_CARDS) {
625                 printk(KERN_ERR "cx18:  Maximum number of cards detected (%d).\n",
626                               cx18_cards_active);
627                 spin_unlock(&cx18_cards_lock);
628                 return -ENOMEM;
629         }
630
631         cx = kzalloc(sizeof(struct cx18), GFP_ATOMIC);
632         if (!cx) {
633                 spin_unlock(&cx18_cards_lock);
634                 return -ENOMEM;
635         }
636         cx18_cards[cx18_cards_active] = cx;
637         cx->dev = dev;
638         cx->num = cx18_cards_active++;
639         snprintf(cx->name, sizeof(cx->name), "cx18-%d", cx->num);
640         CX18_INFO("Initializing card #%d\n", cx->num);
641
642         spin_unlock(&cx18_cards_lock);
643
644         cx18_process_options(cx);
645         if (cx->options.cardtype == -1) {
646                 retval = -ENODEV;
647                 goto err;
648         }
649         if (cx18_init_struct1(cx)) {
650                 retval = -ENOMEM;
651                 goto err;
652         }
653
654         CX18_DEBUG_INFO("base addr: 0x%08x\n", cx->base_addr);
655
656         /* PCI Device Setup */
657         retval = cx18_setup_pci(cx, dev, pci_id);
658         if (retval != 0) {
659                 if (retval == -EIO)
660                         goto free_workqueue;
661                 else if (retval == -ENXIO)
662                         goto free_mem;
663         }
664         /* save cx in the pci struct for later use */
665         pci_set_drvdata(dev, cx);
666
667         /* map io memory */
668         CX18_DEBUG_INFO("attempting ioremap at 0x%08x len 0x%08x\n",
669                    cx->base_addr + CX18_MEM_OFFSET, CX18_MEM_SIZE);
670         cx->enc_mem = ioremap_nocache(cx->base_addr + CX18_MEM_OFFSET,
671                                        CX18_MEM_SIZE);
672         if (!cx->enc_mem) {
673                 CX18_ERR("ioremap failed, perhaps increasing __VMALLOC_RESERVE in page.h\n");
674                 CX18_ERR("or disabling CONFIG_HIGHMEM4G into the kernel would help\n");
675                 retval = -ENOMEM;
676                 goto free_mem;
677         }
678         cx->reg_mem = cx->enc_mem + CX18_REG_OFFSET;
679         devtype = cx18_read_reg(cx, 0xC72028);
680         switch (devtype & 0xff000000) {
681         case 0xff000000:
682                 CX18_INFO("cx23418 revision %08x (A)\n", devtype);
683                 break;
684         case 0x01000000:
685                 CX18_INFO("cx23418 revision %08x (B)\n", devtype);
686                 break;
687         default:
688                 CX18_INFO("cx23418 revision %08x (Unknown)\n", devtype);
689                 break;
690         }
691
692         cx18_init_power(cx, 1);
693         cx18_init_memory(cx);
694
695         cx->scb = (struct cx18_scb __iomem *)(cx->enc_mem + SCB_OFFSET);
696         cx18_init_scb(cx);
697
698         cx18_gpio_init(cx);
699
700         /* active i2c  */
701         CX18_DEBUG_INFO("activating i2c...\n");
702         retval = init_cx18_i2c(cx);
703         if (retval) {
704                 CX18_ERR("Could not initialize i2c\n");
705                 goto free_map;
706         }
707
708         CX18_DEBUG_INFO("Active card count: %d.\n", cx18_cards_active);
709
710         if (cx->card->hw_all & CX18_HW_TVEEPROM) {
711                 /* Based on the model number the cardtype may be changed.
712                    The PCI IDs are not always reliable. */
713                 cx18_process_eeprom(cx);
714         }
715         if (cx->card->comment)
716                 CX18_INFO("%s", cx->card->comment);
717         if (cx->card->v4l2_capabilities == 0) {
718                 retval = -ENODEV;
719                 goto free_i2c;
720         }
721         cx18_init_memory(cx);
722
723         /* Register IRQ */
724         retval = request_irq(cx->dev->irq, cx18_irq_handler,
725                              IRQF_SHARED | IRQF_DISABLED, cx->name, (void *)cx);
726         if (retval) {
727                 CX18_ERR("Failed to register irq %d\n", retval);
728                 goto free_i2c;
729         }
730
731         if (cx->std == 0)
732                 cx->std = V4L2_STD_NTSC_M;
733
734         if (cx->options.tuner == -1) {
735                 for (i = 0; i < CX18_CARD_MAX_TUNERS; i++) {
736                         if ((cx->std & cx->card->tuners[i].std) == 0)
737                                 continue;
738                         cx->options.tuner = cx->card->tuners[i].tuner;
739                         break;
740                 }
741         }
742         /* if no tuner was found, then pick the first tuner in the card list */
743         if (cx->options.tuner == -1 && cx->card->tuners[0].std) {
744                 cx->std = cx->card->tuners[0].std;
745                 if (cx->std & V4L2_STD_PAL)
746                         cx->std = V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
747                 else if (cx->std & V4L2_STD_NTSC)
748                         cx->std = V4L2_STD_NTSC_M;
749                 else if (cx->std & V4L2_STD_SECAM)
750                         cx->std = V4L2_STD_SECAM_L;
751                 cx->options.tuner = cx->card->tuners[0].tuner;
752         }
753         if (cx->options.radio == -1)
754                 cx->options.radio = (cx->card->radio_input.audio_type != 0);
755
756         /* The card is now fully identified, continue with card-specific
757            initialization. */
758         cx18_init_struct2(cx);
759
760         cx18_load_and_init_modules(cx);
761
762         if (cx->std & V4L2_STD_525_60) {
763                 cx->is_60hz = 1;
764                 cx->is_out_60hz = 1;
765         } else {
766                 cx->is_50hz = 1;
767                 cx->is_out_50hz = 1;
768         }
769         cx->params.video_gop_size = cx->is_60hz ? 15 : 12;
770
771         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_MPG] = 0x08000;
772         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_TS] = 0x08000;
773         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_PCM] = 0x01200;
774         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_YUV] = 0x20000;
775         vbi_buf_size = cx->vbi.raw_size * (cx->is_60hz ? 24 : 36) / 2;
776         cx->stream_buf_size[CX18_ENC_STREAM_TYPE_VBI] = vbi_buf_size;
777
778         if (cx->options.radio > 0)
779                 cx->v4l2_cap |= V4L2_CAP_RADIO;
780
781         if (cx->options.tuner > -1) {
782                 struct tuner_setup setup;
783
784                 setup.addr = ADDR_UNSET;
785                 setup.type = cx->options.tuner;
786                 setup.mode_mask = T_ANALOG_TV;  /* matches TV tuners */
787                 setup.tuner_callback = (setup.type == TUNER_XC2028) ?
788                         cx18_reset_tuner_gpio : NULL;
789                 cx18_call_i2c_clients(cx, TUNER_SET_TYPE_ADDR, &setup);
790                 if (setup.type == TUNER_XC2028) {
791                         static struct xc2028_ctrl ctrl = {
792                                 .fname = XC2028_DEFAULT_FIRMWARE,
793                                 .max_len = 64,
794                         };
795                         struct v4l2_priv_tun_config cfg = {
796                                 .tuner = cx->options.tuner,
797                                 .priv = &ctrl,
798                         };
799                         cx18_call_i2c_clients(cx, TUNER_SET_CONFIG, &cfg);
800                 }
801         }
802
803         /* The tuner is fixed to the standard. The other inputs (e.g. S-Video)
804            are not. */
805         cx->tuner_std = cx->std;
806
807         retval = cx18_streams_setup(cx);
808         if (retval) {
809                 CX18_ERR("Error %d setting up streams\n", retval);
810                 goto free_irq;
811         }
812         retval = cx18_streams_register(cx);
813         if (retval) {
814                 CX18_ERR("Error %d registering devices\n", retval);
815                 goto free_streams;
816         }
817
818         CX18_INFO("Initialized card #%d: %s\n", cx->num, cx->card_name);
819
820         return 0;
821
822 free_streams:
823         cx18_streams_cleanup(cx, 1);
824 free_irq:
825         free_irq(cx->dev->irq, (void *)cx);
826 free_i2c:
827         exit_cx18_i2c(cx);
828 free_map:
829         cx18_iounmap(cx);
830 free_mem:
831         release_mem_region(cx->base_addr, CX18_MEM_SIZE);
832 free_workqueue:
833 err:
834         if (retval == 0)
835                 retval = -ENODEV;
836         CX18_ERR("Error %d on initialization\n", retval);
837
838         i = cx->num;
839         spin_lock(&cx18_cards_lock);
840         kfree(cx18_cards[i]);
841         cx18_cards[i] = NULL;
842         spin_unlock(&cx18_cards_lock);
843         return retval;
844 }
845
846 int cx18_init_on_first_open(struct cx18 *cx)
847 {
848         int video_input;
849         int fw_retry_count = 3;
850         struct v4l2_frequency vf;
851         struct cx18_open_id fh;
852
853         fh.cx = cx;
854
855         if (test_bit(CX18_F_I_FAILED, &cx->i_flags))
856                 return -ENXIO;
857
858         if (test_and_set_bit(CX18_F_I_INITED, &cx->i_flags))
859                 return 0;
860
861         while (--fw_retry_count > 0) {
862                 /* load firmware */
863                 if (cx18_firmware_init(cx) == 0)
864                         break;
865                 if (fw_retry_count > 1)
866                         CX18_WARN("Retry loading firmware\n");
867         }
868
869         if (fw_retry_count == 0) {
870                 set_bit(CX18_F_I_FAILED, &cx->i_flags);
871                 return -ENXIO;
872         }
873         set_bit(CX18_F_I_LOADED_FW, &cx->i_flags);
874
875         /* Init the firmware twice to work around a silicon bug
876          * transport related. */
877
878         fw_retry_count = 3;
879         while (--fw_retry_count > 0) {
880                 /* load firmware */
881                 if (cx18_firmware_init(cx) == 0)
882                         break;
883                 if (fw_retry_count > 1)
884                         CX18_WARN("Retry loading firmware\n");
885         }
886
887         if (fw_retry_count == 0) {
888                 set_bit(CX18_F_I_FAILED, &cx->i_flags);
889                 return -ENXIO;
890         }
891
892         vf.tuner = 0;
893         vf.type = V4L2_TUNER_ANALOG_TV;
894         vf.frequency = 6400; /* the tuner 'baseline' frequency */
895
896         /* Set initial frequency. For PAL/SECAM broadcasts no
897            'default' channel exists AFAIK. */
898         if (cx->std == V4L2_STD_NTSC_M_JP)
899                 vf.frequency = 1460;    /* ch. 1 91250*16/1000 */
900         else if (cx->std & V4L2_STD_NTSC_M)
901                 vf.frequency = 1076;    /* ch. 4 67250*16/1000 */
902
903         video_input = cx->active_input;
904         cx->active_input++;     /* Force update of input */
905         cx18_s_input(NULL, &fh, video_input);
906
907         /* Let the VIDIOC_S_STD ioctl do all the work, keeps the code
908            in one place. */
909         cx->std++;              /* Force full standard initialization */
910         cx18_s_std(NULL, &fh, &cx->tuner_std);
911         cx18_s_frequency(NULL, &fh, &vf);
912         return 0;
913 }
914
915 static void cx18_cancel_epu_work_orders(struct cx18 *cx)
916 {
917         int i;
918         for (i = 0; i < CX18_MAX_EPU_WORK_ORDERS; i++)
919                 cancel_work_sync(&cx->epu_work_order[i].work);
920 }
921
922 static void cx18_remove(struct pci_dev *pci_dev)
923 {
924         struct cx18 *cx = pci_get_drvdata(pci_dev);
925
926         CX18_DEBUG_INFO("Removing Card #%d\n", cx->num);
927
928         /* Stop all captures */
929         CX18_DEBUG_INFO("Stopping all streams\n");
930         if (atomic_read(&cx->tot_capturing) > 0)
931                 cx18_stop_all_captures(cx);
932
933         /* Interrupts */
934         cx18_sw1_irq_disable(cx, IRQ_CPU_TO_EPU | IRQ_APU_TO_EPU);
935         cx18_sw2_irq_disable(cx, IRQ_CPU_TO_EPU_ACK | IRQ_APU_TO_EPU_ACK);
936
937         cx18_halt_firmware(cx);
938
939         cx18_cancel_epu_work_orders(cx);
940
941         cx18_streams_cleanup(cx, 1);
942
943         exit_cx18_i2c(cx);
944
945         free_irq(cx->dev->irq, (void *)cx);
946
947         cx18_iounmap(cx);
948
949         release_mem_region(cx->base_addr, CX18_MEM_SIZE);
950
951         pci_disable_device(cx->dev);
952
953         CX18_INFO("Removed %s, card #%d\n", cx->card_name, cx->num);
954 }
955
956 /* define a pci_driver for card detection */
957 static struct pci_driver cx18_pci_driver = {
958       .name =     "cx18",
959       .id_table = cx18_pci_tbl,
960       .probe =    cx18_probe,
961       .remove =   cx18_remove,
962 };
963
964 static int module_start(void)
965 {
966         printk(KERN_INFO "cx18:  Start initialization, version %s\n", CX18_VERSION);
967
968         memset(cx18_cards, 0, sizeof(cx18_cards));
969
970         /* Validate parameters */
971         if (cx18_first_minor < 0 || cx18_first_minor >= CX18_MAX_CARDS) {
972                 printk(KERN_ERR "cx18:  Exiting, cx18_first_minor must be between 0 and %d\n",
973                      CX18_MAX_CARDS - 1);
974                 return -1;
975         }
976
977         if (cx18_debug < 0 || cx18_debug > 511) {
978                 cx18_debug = 0;
979                 printk(KERN_INFO "cx18:   Debug value must be >= 0 and <= 511!\n");
980         }
981
982         cx18_work_queue = create_singlethread_workqueue("cx18");
983         if (cx18_work_queue == NULL) {
984                 printk(KERN_ERR
985                        "cx18:   Unable to create work hander thread\n");
986                 return -ENOMEM;
987         }
988
989         if (pci_register_driver(&cx18_pci_driver)) {
990                 printk(KERN_ERR "cx18:   Error detecting PCI card\n");
991                 destroy_workqueue(cx18_work_queue);
992                 cx18_work_queue = NULL;
993                 return -ENODEV;
994         }
995         printk(KERN_INFO "cx18:  End initialization\n");
996         return 0;
997 }
998
999 static void module_cleanup(void)
1000 {
1001         int i;
1002
1003         pci_unregister_driver(&cx18_pci_driver);
1004
1005         destroy_workqueue(cx18_work_queue);
1006         cx18_work_queue = NULL;
1007
1008         for (i = 0; i < cx18_cards_active; i++) {
1009                 if (cx18_cards[i] == NULL)
1010                         continue;
1011                 kfree(cx18_cards[i]);
1012         }
1013
1014 }
1015
1016 module_init(module_start);
1017 module_exit(module_cleanup);