[media] xc4000: simplified load_scode
[pandora-kernel.git] / drivers / media / common / tuners / xc4000.c
1 /*
2  *  Driver for Xceive XC4000 "QAM/8VSB single chip tuner"
3  *
4  *  Copyright (c) 2007 Xceive Corporation
5  *  Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
6  *  Copyright (c) 2009 Devin Heitmueller <dheitmueller@kernellabs.com>
7  *  Copyright (c) 2009 Davide Ferri <d.ferri@zero11.it>
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  *
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include <linux/module.h>
26 #include <linux/moduleparam.h>
27 #include <linux/videodev2.h>
28 #include <linux/delay.h>
29 #include <linux/dvb/frontend.h>
30 #include <linux/i2c.h>
31 #include <linux/mutex.h>
32 #include <asm/unaligned.h>
33
34 #include "dvb_frontend.h"
35
36 #include "xc4000.h"
37 #include "tuner-i2c.h"
38 #include "tuner-xc2028-types.h"
39
40 static int debug;
41 module_param(debug, int, 0644);
42 MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
43
44 static int no_poweroff;
45 module_param(no_poweroff, int, 0644);
46 MODULE_PARM_DESC(no_poweroff, "0 (default) powers device off when not used.\n"
47         "\t\t1 keep device energized and with tuner ready all the times.\n"
48         "\t\tFaster, but consumes more power and keeps the device hotter");
49
50 #define XC4000_DEFAULT_FIRMWARE "xc4000.fw"
51
52 static char firmware_name[30];
53 module_param_string(firmware_name, firmware_name, sizeof(firmware_name), 0);
54 MODULE_PARM_DESC(firmware_name, "\n\t\tFirmware file name. Allows overriding "
55         "the default firmware\n"
56         "\t\tname.");
57
58 static DEFINE_MUTEX(xc4000_list_mutex);
59 static LIST_HEAD(hybrid_tuner_instance_list);
60
61 #define dprintk(level, fmt, arg...) if (debug >= level) \
62         printk(KERN_INFO "%s: " fmt, "xc4000", ## arg)
63
64 /* struct for storing firmware table */
65 struct firmware_description {
66         unsigned int  type;
67         v4l2_std_id   id;
68         __u16         int_freq;
69         unsigned char *ptr;
70         unsigned int  size;
71 };
72
73 struct firmware_properties {
74         unsigned int    type;
75         v4l2_std_id     id;
76         v4l2_std_id     std_req;
77         __u16           int_freq;
78         unsigned int    scode_table;
79         int             scode_nr;
80 };
81
82 struct xc4000_priv {
83         struct tuner_i2c_props i2c_props;
84         struct list_head hybrid_tuner_instance_list;
85         struct firmware_description *firm;
86         int     firm_size;
87         __u16   firm_version;
88         u32     if_khz;
89         u32     freq_hz;
90         u32     bandwidth;
91         u8      video_standard;
92         u8      rf_mode;
93         u8      ignore_i2c_write_errors;
94  /*     struct xc2028_ctrl      ctrl; */
95         struct firmware_properties cur_fw;
96         __u16   hwmodel;
97         __u16   hwvers;
98         struct mutex    lock;
99 };
100
101 /* Misc Defines */
102 #define MAX_TV_STANDARD                 24
103 #define XC_MAX_I2C_WRITE_LENGTH         64
104
105 /* Signal Types */
106 #define XC_RF_MODE_AIR                  0
107 #define XC_RF_MODE_CABLE                1
108
109 /* Result codes */
110 #define XC_RESULT_SUCCESS               0
111 #define XC_RESULT_RESET_FAILURE         1
112 #define XC_RESULT_I2C_WRITE_FAILURE     2
113 #define XC_RESULT_I2C_READ_FAILURE      3
114 #define XC_RESULT_OUT_OF_RANGE          5
115
116 /* Product id */
117 #define XC_PRODUCT_ID_FW_NOT_LOADED     0x2000
118 #define XC_PRODUCT_ID_FW_LOADED 0x0FA0
119
120 /* Registers (Write-only) */
121 #define XREG_INIT         0x00
122 #define XREG_VIDEO_MODE   0x01
123 #define XREG_AUDIO_MODE   0x02
124 #define XREG_RF_FREQ      0x03
125 #define XREG_D_CODE       0x04
126 #define XREG_DIRECTSITTING_MODE 0x05
127 #define XREG_SEEK_MODE    0x06
128 #define XREG_POWER_DOWN   0x08
129 #define XREG_SIGNALSOURCE 0x0A
130 #define XREG_AMPLITUDE    0x10
131
132 /* Registers (Read-only) */
133 #define XREG_ADC_ENV      0x00
134 #define XREG_QUALITY      0x01
135 #define XREG_FRAME_LINES  0x02
136 #define XREG_HSYNC_FREQ   0x03
137 #define XREG_LOCK         0x04
138 #define XREG_FREQ_ERROR   0x05
139 #define XREG_SNR          0x06
140 #define XREG_VERSION      0x07
141 #define XREG_PRODUCT_ID   0x08
142
143 /*
144    Basic firmware description. This will remain with
145    the driver for documentation purposes.
146
147    This represents an I2C firmware file encoded as a
148    string of unsigned char. Format is as follows:
149
150    char[0  ]=len0_MSB  -> len = len_MSB * 256 + len_LSB
151    char[1  ]=len0_LSB  -> length of first write transaction
152    char[2  ]=data0 -> first byte to be sent
153    char[3  ]=data1
154    char[4  ]=data2
155    char[   ]=...
156    char[M  ]=dataN  -> last byte to be sent
157    char[M+1]=len1_MSB  -> len = len_MSB * 256 + len_LSB
158    char[M+2]=len1_LSB  -> length of second write transaction
159    char[M+3]=data0
160    char[M+4]=data1
161    ...
162    etc.
163
164    The [len] value should be interpreted as follows:
165
166    len= len_MSB _ len_LSB
167    len=1111_1111_1111_1111   : End of I2C_SEQUENCE
168    len=0000_0000_0000_0000   : Reset command: Do hardware reset
169    len=0NNN_NNNN_NNNN_NNNN   : Normal transaction: number of bytes = {1:32767)
170    len=1WWW_WWWW_WWWW_WWWW   : Wait command: wait for {1:32767} ms
171
172    For the RESET and WAIT commands, the two following bytes will contain
173    immediately the length of the following transaction.
174 */
175
176 struct XC_TV_STANDARD {
177         const char  *Name;
178         u16         AudioMode;
179         u16         VideoMode;
180         u16         int_freq;
181 };
182
183 /* Tuner standards */
184 #define XC4000_MN_NTSC_PAL_BTSC         0
185 #define XC4000_MN_NTSC_PAL_A2           1
186 #define XC4000_MN_NTSC_PAL_EIAJ         2
187 #define XC4000_MN_NTSC_PAL_Mono         3
188 #define XC4000_BG_PAL_A2                4
189 #define XC4000_BG_PAL_NICAM             5
190 #define XC4000_BG_PAL_MONO              6
191 #define XC4000_I_PAL_NICAM              7
192 #define XC4000_I_PAL_NICAM_MONO         8
193 #define XC4000_DK_PAL_A2                9
194 #define XC4000_DK_PAL_NICAM             10
195 #define XC4000_DK_PAL_MONO              11
196 #define XC4000_DK_SECAM_A2DK1           12
197 #define XC4000_DK_SECAM_A2LDK3          13
198 #define XC4000_DK_SECAM_A2MONO          14
199 #define XC4000_DK_SECAM_NICAM           15
200 #define XC4000_L_SECAM_NICAM            16
201 #define XC4000_LC_SECAM_NICAM           17
202 #define XC4000_DTV6                     18
203 #define XC4000_DTV8                     19
204 #define XC4000_DTV7_8                   20
205 #define XC4000_DTV7                     21
206 #define XC4000_FM_Radio_INPUT2          22
207 #define XC4000_FM_Radio_INPUT1          23
208
209 static struct XC_TV_STANDARD XC4000_Standard[MAX_TV_STANDARD] = {
210         {"M/N-NTSC/PAL-BTSC",   0x0000, 0x80A0, 4500},
211         {"M/N-NTSC/PAL-A2",     0x0000, 0x80A0, 4600},
212         {"M/N-NTSC/PAL-EIAJ",   0x0040, 0x80A0, 4500},
213         {"M/N-NTSC/PAL-Mono",   0x0078, 0x80A0, 4500},
214         {"B/G-PAL-A2",          0x0000, 0x8159, 5640},
215         {"B/G-PAL-NICAM",       0x0004, 0x8159, 5740},
216         {"B/G-PAL-MONO",        0x0078, 0x8159, 5500},
217         {"I-PAL-NICAM",         0x0080, 0x8049, 6240},
218         {"I-PAL-NICAM-MONO",    0x0078, 0x8049, 6000},
219         {"D/K-PAL-A2",          0x0000, 0x8049, 6380},
220         {"D/K-PAL-NICAM",       0x0080, 0x8049, 6200},
221         {"D/K-PAL-MONO",        0x0078, 0x8049, 6500},
222         {"D/K-SECAM-A2 DK1",    0x0000, 0x8049, 6340},
223         {"D/K-SECAM-A2 L/DK3",  0x0000, 0x8049, 6000},
224         {"D/K-SECAM-A2 MONO",   0x0078, 0x8049, 6500},
225         {"D/K-SECAM-NICAM",     0x0080, 0x8049, 6200},
226         {"L-SECAM-NICAM",       0x8080, 0x0009, 6200},
227         {"L'-SECAM-NICAM",      0x8080, 0x4009, 6200},
228         {"DTV6",                0x00C0, 0x8002,    0},
229         {"DTV8",                0x00C0, 0x800B,    0},
230         {"DTV7/8",              0x00C0, 0x801B,    0},
231         {"DTV7",                0x00C0, 0x8007,    0},
232         {"FM Radio-INPUT2",     0x0008, 0x9800,10700},
233         {"FM Radio-INPUT1",     0x0008, 0x9000,10700}
234 };
235
236 static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val);
237 static int xc4000_TunerReset(struct dvb_frontend *fe);
238
239 static int xc_send_i2c_data(struct xc4000_priv *priv, u8 *buf, int len)
240 {
241         struct i2c_msg msg = { .addr = priv->i2c_props.addr,
242                                .flags = 0, .buf = buf, .len = len };
243         if (i2c_transfer(priv->i2c_props.adap, &msg, 1) != 1) {
244                 if (priv->ignore_i2c_write_errors == 0) {
245                         printk(KERN_ERR "xc4000: I2C write failed (len=%i)\n",
246                                len);
247                         if (len == 4) {
248                                 printk("bytes %02x %02x %02x %02x\n", buf[0],
249                                        buf[1], buf[2], buf[3]);
250                         }
251                         return XC_RESULT_I2C_WRITE_FAILURE;
252                 }
253         }
254         return XC_RESULT_SUCCESS;
255 }
256
257 static void xc_wait(int wait_ms)
258 {
259         msleep(wait_ms);
260 }
261
262 static int xc4000_TunerReset(struct dvb_frontend *fe)
263 {
264         struct xc4000_priv *priv = fe->tuner_priv;
265         int ret;
266
267         dprintk(1, "%s()\n", __func__);
268
269         if (fe->callback) {
270                 ret = fe->callback(((fe->dvb) && (fe->dvb->priv)) ?
271                                            fe->dvb->priv :
272                                            priv->i2c_props.adap->algo_data,
273                                            DVB_FRONTEND_COMPONENT_TUNER,
274                                            XC4000_TUNER_RESET, 0);
275                 if (ret) {
276                         printk(KERN_ERR "xc4000: reset failed\n");
277                         return XC_RESULT_RESET_FAILURE;
278                 }
279         } else {
280                 printk(KERN_ERR "xc4000: no tuner reset callback function, fatal\n");
281                 return XC_RESULT_RESET_FAILURE;
282         }
283         return XC_RESULT_SUCCESS;
284 }
285
286 static int xc_write_reg(struct xc4000_priv *priv, u16 regAddr, u16 i2cData)
287 {
288         u8 buf[4];
289         int result;
290
291         buf[0] = (regAddr >> 8) & 0xFF;
292         buf[1] = regAddr & 0xFF;
293         buf[2] = (i2cData >> 8) & 0xFF;
294         buf[3] = i2cData & 0xFF;
295         result = xc_send_i2c_data(priv, buf, 4);
296
297         return result;
298 }
299
300 static int xc_load_i2c_sequence(struct dvb_frontend *fe, const u8 *i2c_sequence)
301 {
302         struct xc4000_priv *priv = fe->tuner_priv;
303
304         int i, nbytes_to_send, result;
305         unsigned int len, pos, index;
306         u8 buf[XC_MAX_I2C_WRITE_LENGTH];
307
308         index = 0;
309         while ((i2c_sequence[index] != 0xFF) ||
310                 (i2c_sequence[index + 1] != 0xFF)) {
311                 len = i2c_sequence[index] * 256 + i2c_sequence[index+1];
312                 if (len == 0x0000) {
313                         /* RESET command */
314                         result = xc4000_TunerReset(fe);
315                         index += 2;
316                         if (result != XC_RESULT_SUCCESS)
317                                 return result;
318                 } else if (len & 0x8000) {
319                         /* WAIT command */
320                         xc_wait(len & 0x7FFF);
321                         index += 2;
322                 } else {
323                         /* Send i2c data whilst ensuring individual transactions
324                          * do not exceed XC_MAX_I2C_WRITE_LENGTH bytes.
325                          */
326                         index += 2;
327                         buf[0] = i2c_sequence[index];
328                         buf[1] = i2c_sequence[index + 1];
329                         pos = 2;
330                         while (pos < len) {
331                                 if ((len - pos) > XC_MAX_I2C_WRITE_LENGTH - 2)
332                                         nbytes_to_send =
333                                                 XC_MAX_I2C_WRITE_LENGTH;
334                                 else
335                                         nbytes_to_send = (len - pos + 2);
336                                 for (i = 2; i < nbytes_to_send; i++) {
337                                         buf[i] = i2c_sequence[index + pos +
338                                                 i - 2];
339                                 }
340                                 result = xc_send_i2c_data(priv, buf,
341                                         nbytes_to_send);
342
343                                 if (result != XC_RESULT_SUCCESS)
344                                         return result;
345
346                                 pos += nbytes_to_send - 2;
347                         }
348                         index += len;
349                 }
350         }
351         return XC_RESULT_SUCCESS;
352 }
353
354 static int xc_SetTVStandard(struct xc4000_priv *priv,
355         u16 VideoMode, u16 AudioMode)
356 {
357         int ret;
358         dprintk(1, "%s(0x%04x,0x%04x)\n", __func__, VideoMode, AudioMode);
359         dprintk(1, "%s() Standard = %s\n",
360                 __func__,
361                 XC4000_Standard[priv->video_standard].Name);
362
363         /* Don't complain when the request fails because of i2c stretching */
364         priv->ignore_i2c_write_errors = 1;
365
366         ret = xc_write_reg(priv, XREG_VIDEO_MODE, VideoMode);
367         if (ret == XC_RESULT_SUCCESS)
368                 ret = xc_write_reg(priv, XREG_AUDIO_MODE, AudioMode);
369
370         priv->ignore_i2c_write_errors = 0;
371
372         return ret;
373 }
374
375 static int xc_SetSignalSource(struct xc4000_priv *priv, u16 rf_mode)
376 {
377         dprintk(1, "%s(%d) Source = %s\n", __func__, rf_mode,
378                 rf_mode == XC_RF_MODE_AIR ? "ANTENNA" : "CABLE");
379
380         if ((rf_mode != XC_RF_MODE_AIR) && (rf_mode != XC_RF_MODE_CABLE)) {
381                 rf_mode = XC_RF_MODE_CABLE;
382                 printk(KERN_ERR
383                         "%s(), Invalid mode, defaulting to CABLE",
384                         __func__);
385         }
386         return xc_write_reg(priv, XREG_SIGNALSOURCE, rf_mode);
387 }
388
389 static const struct dvb_tuner_ops xc4000_tuner_ops;
390
391 static int xc_set_RF_frequency(struct xc4000_priv *priv, u32 freq_hz)
392 {
393         u16 freq_code;
394
395         dprintk(1, "%s(%u)\n", __func__, freq_hz);
396
397         if ((freq_hz > xc4000_tuner_ops.info.frequency_max) ||
398                 (freq_hz < xc4000_tuner_ops.info.frequency_min))
399                 return XC_RESULT_OUT_OF_RANGE;
400
401         freq_code = (u16)(freq_hz / 15625);
402
403         /* WAS: Starting in firmware version 1.1.44, Xceive recommends using the
404            FINERFREQ for all normal tuning (the doc indicates reg 0x03 should
405            only be used for fast scanning for channel lock) */
406         return xc_write_reg(priv, XREG_RF_FREQ, freq_code); /* WAS: XREG_FINERFREQ */
407 }
408
409 static int xc_get_ADC_Envelope(struct xc4000_priv *priv, u16 *adc_envelope)
410 {
411         return xc4000_readreg(priv, XREG_ADC_ENV, adc_envelope);
412 }
413
414 static int xc_get_frequency_error(struct xc4000_priv *priv, u32 *freq_error_hz)
415 {
416         int result;
417         u16 regData;
418         u32 tmp;
419
420         result = xc4000_readreg(priv, XREG_FREQ_ERROR, &regData);
421         if (result != XC_RESULT_SUCCESS)
422                 return result;
423
424         tmp = (u32)regData & 0xFFFFU;
425         tmp = (tmp < 0x8000U ? tmp : 0x10000U - tmp);
426         (*freq_error_hz) = tmp * 15625;
427         return result;
428 }
429
430 static int xc_get_lock_status(struct xc4000_priv *priv, u16 *lock_status)
431 {
432         return xc4000_readreg(priv, XREG_LOCK, lock_status);
433 }
434
435 static int xc_get_version(struct xc4000_priv *priv,
436         u8 *hw_majorversion, u8 *hw_minorversion,
437         u8 *fw_majorversion, u8 *fw_minorversion)
438 {
439         u16 data;
440         int result;
441
442         result = xc4000_readreg(priv, XREG_VERSION, &data);
443         if (result != XC_RESULT_SUCCESS)
444                 return result;
445
446         (*hw_majorversion) = (data >> 12) & 0x0F;
447         (*hw_minorversion) = (data >>  8) & 0x0F;
448         (*fw_majorversion) = (data >>  4) & 0x0F;
449         (*fw_minorversion) = data & 0x0F;
450
451         return 0;
452 }
453
454 static int xc_get_hsync_freq(struct xc4000_priv *priv, u32 *hsync_freq_hz)
455 {
456         u16 regData;
457         int result;
458
459         result = xc4000_readreg(priv, XREG_HSYNC_FREQ, &regData);
460         if (result != XC_RESULT_SUCCESS)
461                 return result;
462
463         (*hsync_freq_hz) = ((regData & 0x0fff) * 763)/100;
464         return result;
465 }
466
467 static int xc_get_frame_lines(struct xc4000_priv *priv, u16 *frame_lines)
468 {
469         return xc4000_readreg(priv, XREG_FRAME_LINES, frame_lines);
470 }
471
472 static int xc_get_quality(struct xc4000_priv *priv, u16 *quality)
473 {
474         return xc4000_readreg(priv, XREG_QUALITY, quality);
475 }
476
477 static u16 WaitForLock(struct xc4000_priv *priv)
478 {
479         u16 lockState = 0;
480         int watchDogCount = 40;
481
482         while ((lockState == 0) && (watchDogCount > 0)) {
483                 xc_get_lock_status(priv, &lockState);
484                 if (lockState != 1) {
485                         xc_wait(5);
486                         watchDogCount--;
487                 }
488         }
489         return lockState;
490 }
491
492 #define XC_TUNE_ANALOG  0
493 #define XC_TUNE_DIGITAL 1
494 static int xc_tune_channel(struct xc4000_priv *priv, u32 freq_hz, int mode)
495 {
496         int     found = 0;
497         int     result = 0;
498
499         dprintk(1, "%s(%u)\n", __func__, freq_hz);
500
501         /* Don't complain when the request fails because of i2c stretching */
502         priv->ignore_i2c_write_errors = 1;
503         result = xc_set_RF_frequency(priv, freq_hz);
504         priv->ignore_i2c_write_errors = 0;
505
506         if (result != XC_RESULT_SUCCESS)
507                 return 0;
508
509         if (mode == XC_TUNE_ANALOG) {
510                 if (WaitForLock(priv) == 1)
511                         found = 1;
512         }
513
514         return found;
515 }
516
517 static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val)
518 {
519         u8 buf[2] = { reg >> 8, reg & 0xff };
520         u8 bval[2] = { 0, 0 };
521         struct i2c_msg msg[2] = {
522                 { .addr = priv->i2c_props.addr,
523                         .flags = 0, .buf = &buf[0], .len = 2 },
524                 { .addr = priv->i2c_props.addr,
525                         .flags = I2C_M_RD, .buf = &bval[0], .len = 2 },
526         };
527
528         if (i2c_transfer(priv->i2c_props.adap, msg, 2) != 2) {
529                 printk(KERN_WARNING "xc4000: I2C read failed\n");
530                 return -EREMOTEIO;
531         }
532
533         *val = (bval[0] << 8) | bval[1];
534         return XC_RESULT_SUCCESS;
535 }
536
537 #define dump_firm_type(t)       dump_firm_type_and_int_freq(t, 0)
538 static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq)
539 {
540          if (type & BASE)
541                 printk("BASE ");
542          if (type & INIT1)
543                 printk("INIT1 ");
544          if (type & F8MHZ)
545                 printk("F8MHZ ");
546          if (type & MTS)
547                 printk("MTS ");
548          if (type & D2620)
549                 printk("D2620 ");
550          if (type & D2633)
551                 printk("D2633 ");
552          if (type & DTV6)
553                 printk("DTV6 ");
554          if (type & QAM)
555                 printk("QAM ");
556          if (type & DTV7)
557                 printk("DTV7 ");
558          if (type & DTV78)
559                 printk("DTV78 ");
560          if (type & DTV8)
561                 printk("DTV8 ");
562          if (type & FM)
563                 printk("FM ");
564          if (type & INPUT1)
565                 printk("INPUT1 ");
566          if (type & LCD)
567                 printk("LCD ");
568          if (type & NOGD)
569                 printk("NOGD ");
570          if (type & MONO)
571                 printk("MONO ");
572          if (type & ATSC)
573                 printk("ATSC ");
574          if (type & IF)
575                 printk("IF ");
576          if (type & LG60)
577                 printk("LG60 ");
578          if (type & ATI638)
579                 printk("ATI638 ");
580          if (type & OREN538)
581                 printk("OREN538 ");
582          if (type & OREN36)
583                 printk("OREN36 ");
584          if (type & TOYOTA388)
585                 printk("TOYOTA388 ");
586          if (type & TOYOTA794)
587                 printk("TOYOTA794 ");
588          if (type & DIBCOM52)
589                 printk("DIBCOM52 ");
590          if (type & ZARLINK456)
591                 printk("ZARLINK456 ");
592          if (type & CHINA)
593                 printk("CHINA ");
594          if (type & F6MHZ)
595                 printk("F6MHZ ");
596          if (type & INPUT2)
597                 printk("INPUT2 ");
598          if (type & SCODE)
599                 printk("SCODE ");
600          if (type & HAS_IF)
601                 printk("HAS_IF_%d ", int_freq);
602 }
603
604 static int seek_firmware(struct dvb_frontend *fe, unsigned int type,
605                          v4l2_std_id *id)
606 {
607         struct xc4000_priv *priv = fe->tuner_priv;
608         int             i, best_i = -1;
609         unsigned int    best_nr_diffs = 255U;
610
611         if (!priv->firm) {
612                 printk("Error! firmware not loaded\n");
613                 return -EINVAL;
614         }
615
616         if (((type & ~SCODE) == 0) && (*id == 0))
617                 *id = V4L2_STD_PAL;
618
619         /* Seek for generic video standard match */
620         for (i = 0; i < priv->firm_size; i++) {
621                 v4l2_std_id     id_diff_mask =
622                         (priv->firm[i].id ^ (*id)) & (*id);
623                 unsigned int    type_diff_mask =
624                         (priv->firm[i].type ^ type)
625                         & (BASE_TYPES | DTV_TYPES | LCD | NOGD | MONO | SCODE);
626                 unsigned int    nr_diffs;
627
628                 if (type_diff_mask
629                     & (BASE | INIT1 | FM | DTV6 | DTV7 | DTV78 | DTV8 | SCODE))
630                         continue;
631
632                 nr_diffs = hweight64(id_diff_mask) + hweight32(type_diff_mask);
633                 if (!nr_diffs)  /* Supports all the requested standards */
634                         goto found;
635
636                 if (nr_diffs < best_nr_diffs) {
637                         best_nr_diffs = nr_diffs;
638                         best_i = i;
639                 }
640         }
641
642         /* FIXME: Would make sense to seek for type "hint" match ? */
643         if (best_i < 0) {
644                 i = -ENOENT;
645                 goto ret;
646         }
647
648         if (best_nr_diffs > 0U) {
649                 printk("Selecting best matching firmware (%u bits differ) for "
650                        "type=", best_nr_diffs);
651                 printk("(%x), id %016llx:\n", type, (unsigned long long)*id);
652                 i = best_i;
653         }
654
655 found:
656         *id = priv->firm[i].id;
657
658 ret:
659         if (debug) {
660                 printk("%s firmware for type=", (i < 0) ? "Can't find" :
661                        "Found");
662                 dump_firm_type(type);
663                 printk("(%x), id %016llx.\n", type, (unsigned long long)*id);
664         }
665         return i;
666 }
667
668 static int load_firmware(struct dvb_frontend *fe, unsigned int type,
669                          v4l2_std_id *id)
670 {
671         struct xc4000_priv *priv = fe->tuner_priv;
672         int                pos, rc;
673         unsigned char      *p;
674
675         pos = seek_firmware(fe, type, id);
676         if (pos < 0)
677                 return pos;
678
679         p = priv->firm[pos].ptr;
680
681         /* Don't complain when the request fails because of i2c stretching */
682         priv->ignore_i2c_write_errors = 1;
683
684         rc = xc_load_i2c_sequence(fe, p);
685
686         priv->ignore_i2c_write_errors = 0;
687
688         return rc;
689 }
690
691 static int xc4000_fwupload(struct dvb_frontend *fe)
692 {
693         struct xc4000_priv *priv = fe->tuner_priv;
694         const struct firmware *fw   = NULL;
695         const unsigned char   *p, *endp;
696         int                   rc = 0;
697         int                   n, n_array;
698         char                  name[33];
699         const char            *fname;
700
701         if (firmware_name[0] != '\0')
702                 fname = firmware_name;
703         else
704                 fname = XC4000_DEFAULT_FIRMWARE;
705
706         printk("Reading firmware %s\n",  fname);
707         rc = request_firmware(&fw, fname, priv->i2c_props.adap->dev.parent);
708         if (rc < 0) {
709                 if (rc == -ENOENT)
710                         printk("Error: firmware %s not found.\n",
711                                    fname);
712                 else
713                         printk("Error %d while requesting firmware %s \n",
714                                    rc, fname);
715
716                 return rc;
717         }
718         p = fw->data;
719         endp = p + fw->size;
720
721         if (fw->size < sizeof(name) - 1 + 2 + 2) {
722                 printk("Error: firmware file %s has invalid size!\n",
723                        fname);
724                 goto corrupt;
725         }
726
727         memcpy(name, p, sizeof(name) - 1);
728         name[sizeof(name) - 1] = 0;
729         p += sizeof(name) - 1;
730
731         priv->firm_version = get_unaligned_le16(p);
732         p += 2;
733
734         n_array = get_unaligned_le16(p);
735         p += 2;
736
737         dprintk(1, "Loading %d firmware images from %s, type: %s, ver %d.%d\n",
738                 n_array, fname, name,
739                 priv->firm_version >> 8, priv->firm_version & 0xff);
740
741         priv->firm = kzalloc(sizeof(*priv->firm) * n_array, GFP_KERNEL);
742         if (priv->firm == NULL) {
743                 printk("Not enough memory to load firmware file.\n");
744                 rc = -ENOMEM;
745                 goto err;
746         }
747         priv->firm_size = n_array;
748
749         n = -1;
750         while (p < endp) {
751                 __u32 type, size;
752                 v4l2_std_id id;
753                 __u16 int_freq = 0;
754
755                 n++;
756                 if (n >= n_array) {
757                         printk("More firmware images in file than "
758                                "were expected!\n");
759                         goto corrupt;
760                 }
761
762                 /* Checks if there's enough bytes to read */
763                 if (endp - p < sizeof(type) + sizeof(id) + sizeof(size))
764                         goto header;
765
766                 type = get_unaligned_le32(p);
767                 p += sizeof(type);
768
769                 id = get_unaligned_le64(p);
770                 p += sizeof(id);
771
772                 if (type & HAS_IF) {
773                         int_freq = get_unaligned_le16(p);
774                         p += sizeof(int_freq);
775                         if (endp - p < sizeof(size))
776                                 goto header;
777                 }
778
779                 size = get_unaligned_le32(p);
780                 p += sizeof(size);
781
782                 if (!size || size > endp - p) {
783                         printk("Firmware type (%x), id %llx is corrupted "
784                                "(size=%d, expected %d)\n",
785                                type, (unsigned long long)id,
786                                (unsigned)(endp - p), size);
787                         goto corrupt;
788                 }
789
790                 priv->firm[n].ptr = kzalloc(size, GFP_KERNEL);
791                 if (priv->firm[n].ptr == NULL) {
792                         printk("Not enough memory to load firmware file.\n");
793                         rc = -ENOMEM;
794                         goto err;
795                 }
796
797                 if (debug) {
798                         printk("Reading firmware type ");
799                         dump_firm_type_and_int_freq(type, int_freq);
800                         printk("(%x), id %llx, size=%d.\n",
801                                type, (unsigned long long)id, size);
802                 }
803
804                 memcpy(priv->firm[n].ptr, p, size);
805                 priv->firm[n].type = type;
806                 priv->firm[n].id   = id;
807                 priv->firm[n].size = size;
808                 priv->firm[n].int_freq = int_freq;
809
810                 p += size;
811         }
812
813         if (n + 1 != priv->firm_size) {
814                 printk("Firmware file is incomplete!\n");
815                 goto corrupt;
816         }
817
818         goto done;
819
820 header:
821         printk("Firmware header is incomplete!\n");
822 corrupt:
823         rc = -EINVAL;
824         printk("Error: firmware file is corrupted!\n");
825
826 err:
827         printk("Releasing partially loaded firmware file.\n");
828
829 done:
830         release_firmware(fw);
831         if (rc == 0)
832                 dprintk(1, "Firmware files loaded.\n");
833
834         return rc;
835 }
836
837 static int load_scode(struct dvb_frontend *fe, unsigned int type,
838                          v4l2_std_id *id, __u16 int_freq, int scode)
839 {
840         struct xc4000_priv *priv = fe->tuner_priv;
841         int             pos, rc;
842         unsigned char   *p;
843         u8              scode_buf[13];
844         u8              indirect_mode[5];
845
846         dprintk(1, "%s called int_freq=%d\n", __func__, int_freq);
847
848         if (!int_freq) {
849                 pos = seek_firmware(fe, type, id);
850                 if (pos < 0)
851                         return pos;
852         } else {
853                 for (pos = 0; pos < priv->firm_size; pos++) {
854                         if ((priv->firm[pos].int_freq == int_freq) &&
855                             (priv->firm[pos].type & HAS_IF))
856                                 break;
857                 }
858                 if (pos == priv->firm_size)
859                         return -ENOENT;
860         }
861
862         p = priv->firm[pos].ptr;
863
864         if (priv->firm[pos].size != 12 * 16 || scode >= 16)
865                 return -EINVAL;
866         p += 12 * scode;
867
868         tuner_info("Loading SCODE for type=");
869         dump_firm_type_and_int_freq(priv->firm[pos].type,
870                                     priv->firm[pos].int_freq);
871         printk("(%x), id %016llx.\n", priv->firm[pos].type,
872                (unsigned long long)*id);
873
874         scode_buf[0] = 0x00;
875         memcpy(&scode_buf[1], p, 12);
876
877         /* Enter direct-mode */
878         rc = xc_write_reg(priv, XREG_DIRECTSITTING_MODE, 0);
879         if (rc < 0) {
880                 printk("failed to put device into direct mode!\n");
881                 return -EIO;
882         }
883
884         rc = xc_send_i2c_data(priv, scode_buf, 13);
885         if (rc != XC_RESULT_SUCCESS) {
886                 /* Even if the send failed, make sure we set back to indirect
887                    mode */
888                 printk("Failed to set scode %d\n", rc);
889         }
890
891         /* Switch back to indirect-mode */
892         memset(indirect_mode, 0, sizeof(indirect_mode));
893         indirect_mode[4] = 0x88;
894         xc_send_i2c_data(priv, indirect_mode, sizeof(indirect_mode));
895         msleep(10);
896
897         return 0;
898 }
899
900 static int check_firmware(struct dvb_frontend *fe, unsigned int type,
901                           v4l2_std_id std, __u16 int_freq)
902 {
903         struct xc4000_priv         *priv = fe->tuner_priv;
904         struct firmware_properties new_fw;
905         int                        rc = 0, is_retry = 0;
906         u16                        version, hwmodel;
907         v4l2_std_id                std0;
908         u8                         hw_major, hw_minor, fw_major, fw_minor;
909
910         dprintk(1, "%s called\n", __func__);
911
912         if (!priv->firm) {
913                 rc = xc4000_fwupload(fe);
914                 if (rc < 0)
915                         return rc;
916         }
917
918 #ifdef DJH_DEBUG
919         if (priv->ctrl.mts && !(type & FM))
920                 type |= MTS;
921 #endif
922
923 retry:
924         new_fw.type = type;
925         new_fw.id = std;
926         new_fw.std_req = std;
927         new_fw.scode_table = SCODE /* | priv->ctrl.scode_table */;
928         new_fw.scode_nr = 0;
929         new_fw.int_freq = int_freq;
930
931         dprintk(1, "checking firmware, user requested type=");
932         if (debug) {
933                 dump_firm_type(new_fw.type);
934                 printk("(%x), id %016llx, ", new_fw.type,
935                        (unsigned long long)new_fw.std_req);
936                 if (!int_freq) {
937                         printk("scode_tbl ");
938 #ifdef DJH_DEBUG
939                         dump_firm_type(priv->ctrl.scode_table);
940                         printk("(%x), ", priv->ctrl.scode_table);
941 #endif
942                 } else
943                         printk("int_freq %d, ", new_fw.int_freq);
944                 printk("scode_nr %d\n", new_fw.scode_nr);
945         }
946
947         /* No need to reload base firmware if it matches */
948         if (((BASE | new_fw.type) & BASE_TYPES) ==
949             (priv->cur_fw.type & BASE_TYPES)) {
950                 dprintk(1, "BASE firmware not changed.\n");
951                 goto skip_base;
952         }
953
954         /* Updating BASE - forget about all currently loaded firmware */
955         memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
956
957         /* Reset is needed before loading firmware */
958         rc = xc4000_TunerReset(fe);
959         if (rc < 0)
960                 goto fail;
961
962         /* BASE firmwares are all std0 */
963         std0 = 0;
964         rc = load_firmware(fe, BASE | new_fw.type, &std0);
965         if (rc < 0) {
966                 printk("Error %d while loading base firmware\n", rc);
967                 goto fail;
968         }
969
970         /* Load INIT1, if needed */
971         dprintk(1, "Load init1 firmware, if exists\n");
972
973         rc = load_firmware(fe, BASE | INIT1 | new_fw.type, &std0);
974         if (rc == -ENOENT)
975                 rc = load_firmware(fe, (BASE | INIT1 | new_fw.type) & ~F8MHZ,
976                                    &std0);
977         if (rc < 0 && rc != -ENOENT) {
978                 tuner_err("Error %d while loading init1 firmware\n",
979                           rc);
980                 goto fail;
981         }
982
983 skip_base:
984         /*
985          * No need to reload standard specific firmware if base firmware
986          * was not reloaded and requested video standards have not changed.
987          */
988         if (priv->cur_fw.type == (BASE | new_fw.type) &&
989             priv->cur_fw.std_req == std) {
990                 dprintk(1, "Std-specific firmware already loaded.\n");
991                 goto skip_std_specific;
992         }
993
994         /* Reloading std-specific firmware forces a SCODE update */
995         priv->cur_fw.scode_table = 0;
996
997         /* Load the standard firmware */
998         rc = load_firmware(fe, new_fw.type, &new_fw.id);
999
1000         if (rc < 0)
1001                 goto fail;
1002
1003 skip_std_specific:
1004         if (priv->cur_fw.scode_table == new_fw.scode_table &&
1005             priv->cur_fw.scode_nr == new_fw.scode_nr) {
1006                 dprintk(1, "SCODE firmware already loaded.\n");
1007                 goto check_device;
1008         }
1009
1010         if (new_fw.type & FM)
1011                 goto check_device;
1012
1013         /* Load SCODE firmware, if exists */
1014         rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id,
1015                         new_fw.int_freq, new_fw.scode_nr);
1016         if (rc != XC_RESULT_SUCCESS)
1017                 dprintk(1, "load scode failed %d\n", rc);
1018
1019 check_device:
1020         rc = xc4000_readreg(priv, XREG_PRODUCT_ID, &hwmodel);
1021
1022         if (xc_get_version(priv, &hw_major, &hw_minor, &fw_major,
1023                            &fw_minor) != XC_RESULT_SUCCESS) {
1024                 printk("Unable to read tuner registers.\n");
1025                 goto fail;
1026         }
1027
1028         dprintk(1, "Device is Xceive %d version %d.%d, "
1029                 "firmware version %d.%d\n",
1030                 hwmodel, hw_major, hw_minor, fw_major, fw_minor);
1031
1032         /* Check firmware version against what we downloaded. */
1033 #ifdef DJH_DEBUG
1034         if (priv->firm_version != ((version & 0xf0) << 4 | (version & 0x0f))) {
1035                 printk("Incorrect readback of firmware version %x.\n",
1036                        (version & 0xff));
1037                 goto fail;
1038         }
1039 #endif
1040
1041         /* Check that the tuner hardware model remains consistent over time. */
1042         if (priv->hwmodel == 0 && hwmodel == 4000) {
1043                 priv->hwmodel = hwmodel;
1044                 priv->hwvers  = version & 0xff00;
1045         } else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel ||
1046                    priv->hwvers != (version & 0xff00)) {
1047                 printk("Read invalid device hardware information - tuner "
1048                        "hung?\n");
1049                 goto fail;
1050         }
1051
1052         memcpy(&priv->cur_fw, &new_fw, sizeof(priv->cur_fw));
1053
1054         /*
1055          * By setting BASE in cur_fw.type only after successfully loading all
1056          * firmwares, we can:
1057          * 1. Identify that BASE firmware with type=0 has been loaded;
1058          * 2. Tell whether BASE firmware was just changed the next time through.
1059          */
1060         priv->cur_fw.type |= BASE;
1061
1062         return 0;
1063
1064 fail:
1065         memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
1066         if (!is_retry) {
1067                 msleep(50);
1068                 is_retry = 1;
1069                 dprintk(1, "Retrying firmware load\n");
1070                 goto retry;
1071         }
1072
1073         if (rc == -ENOENT)
1074                 rc = -EINVAL;
1075         return rc;
1076 }
1077
1078 static void xc_debug_dump(struct xc4000_priv *priv)
1079 {
1080         u16     adc_envelope;
1081         u32     freq_error_hz = 0;
1082         u16     lock_status;
1083         u32     hsync_freq_hz = 0;
1084         u16     frame_lines;
1085         u16     quality;
1086         u8      hw_majorversion = 0, hw_minorversion = 0;
1087         u8      fw_majorversion = 0, fw_minorversion = 0;
1088
1089         /* Wait for stats to stabilize.
1090          * Frame Lines needs two frame times after initial lock
1091          * before it is valid.
1092          */
1093         xc_wait(100);
1094
1095         xc_get_ADC_Envelope(priv, &adc_envelope);
1096         dprintk(1, "*** ADC envelope (0-1023) = %d\n", adc_envelope);
1097
1098         xc_get_frequency_error(priv, &freq_error_hz);
1099         dprintk(1, "*** Frequency error = %d Hz\n", freq_error_hz);
1100
1101         xc_get_lock_status(priv, &lock_status);
1102         dprintk(1, "*** Lock status (0-Wait, 1-Locked, 2-No-signal) = %d\n",
1103                 lock_status);
1104
1105         xc_get_version(priv, &hw_majorversion, &hw_minorversion,
1106                        &fw_majorversion, &fw_minorversion);
1107
1108         dprintk(1, "*** HW: V%02x.%02x, FW: V%02x.%02x\n",
1109                 hw_majorversion, hw_minorversion,
1110                 fw_majorversion, fw_minorversion);
1111
1112         xc_get_hsync_freq(priv, &hsync_freq_hz);
1113         dprintk(1, "*** Horizontal sync frequency = %d Hz\n", hsync_freq_hz);
1114
1115         xc_get_frame_lines(priv, &frame_lines);
1116         dprintk(1, "*** Frame lines = %d\n", frame_lines);
1117
1118         xc_get_quality(priv, &quality);
1119         dprintk(1, "*** Quality (0:<8dB, 7:>56dB) = %d\n", quality);
1120 }
1121
1122 static int xc4000_set_params(struct dvb_frontend *fe,
1123         struct dvb_frontend_parameters *params)
1124 {
1125         struct xc4000_priv *priv = fe->tuner_priv;
1126         unsigned int type;
1127         int     ret = -EREMOTEIO;
1128
1129         dprintk(1, "%s() frequency=%d (Hz)\n", __func__, params->frequency);
1130
1131         mutex_lock(&priv->lock);
1132
1133         if (fe->ops.info.type == FE_ATSC) {
1134                 dprintk(1, "%s() ATSC\n", __func__);
1135                 switch (params->u.vsb.modulation) {
1136                 case VSB_8:
1137                 case VSB_16:
1138                         dprintk(1, "%s() VSB modulation\n", __func__);
1139                         priv->rf_mode = XC_RF_MODE_AIR;
1140                         priv->freq_hz = params->frequency - 1750000;
1141                         priv->bandwidth = BANDWIDTH_6_MHZ;
1142                         priv->video_standard = XC4000_DTV6;
1143                         type = DTV6;
1144                         break;
1145                 case QAM_64:
1146                 case QAM_256:
1147                 case QAM_AUTO:
1148                         dprintk(1, "%s() QAM modulation\n", __func__);
1149                         priv->rf_mode = XC_RF_MODE_CABLE;
1150                         priv->freq_hz = params->frequency - 1750000;
1151                         priv->bandwidth = BANDWIDTH_6_MHZ;
1152                         priv->video_standard = XC4000_DTV6;
1153                         type = DTV6;
1154                         break;
1155                 default:
1156                         ret = -EINVAL;
1157                         goto fail;
1158                 }
1159         } else if (fe->ops.info.type == FE_OFDM) {
1160                 dprintk(1, "%s() OFDM\n", __func__);
1161                 switch (params->u.ofdm.bandwidth) {
1162                 case BANDWIDTH_6_MHZ:
1163                         priv->bandwidth = BANDWIDTH_6_MHZ;
1164                         priv->video_standard = XC4000_DTV6;
1165                         priv->freq_hz = params->frequency - 1750000;
1166                         type = DTV6;
1167                         break;
1168                 case BANDWIDTH_7_MHZ:
1169                         priv->bandwidth = BANDWIDTH_7_MHZ;
1170                         priv->video_standard = XC4000_DTV7;
1171                         priv->freq_hz = params->frequency - 2250000;
1172                         type = DTV7;
1173                         break;
1174                 case BANDWIDTH_8_MHZ:
1175                         priv->bandwidth = BANDWIDTH_8_MHZ;
1176                         priv->video_standard = XC4000_DTV8;
1177                         priv->freq_hz = params->frequency - 2750000;
1178                         type = DTV8;
1179                         break;
1180                 case BANDWIDTH_AUTO:
1181                         if (params->frequency < 400000000) {
1182                                 priv->bandwidth = BANDWIDTH_7_MHZ;
1183                                 priv->freq_hz = params->frequency - 2250000;
1184                         } else {
1185                                 priv->bandwidth = BANDWIDTH_8_MHZ;
1186                                 priv->freq_hz = params->frequency - 2750000;
1187                         }
1188                         priv->video_standard = XC4000_DTV7_8;
1189                         type = DTV78;
1190                         break;
1191                 default:
1192                         printk(KERN_ERR "xc4000 bandwidth not set!\n");
1193                         ret = -EINVAL;
1194                         goto fail;
1195                 }
1196                 priv->rf_mode = XC_RF_MODE_AIR;
1197         } else {
1198                 printk(KERN_ERR "xc4000 modulation type not supported!\n");
1199                 ret = -EINVAL;
1200                 goto fail;
1201         }
1202
1203         dprintk(1, "%s() frequency=%d (compensated)\n",
1204                 __func__, priv->freq_hz);
1205
1206         /* Make sure the correct firmware type is loaded */
1207         if (check_firmware(fe, type, 0, priv->if_khz) != XC_RESULT_SUCCESS)
1208                 goto fail;
1209
1210         ret = xc_SetSignalSource(priv, priv->rf_mode);
1211         if (ret != XC_RESULT_SUCCESS) {
1212                 printk(KERN_ERR
1213                        "xc4000: xc_SetSignalSource(%d) failed\n",
1214                        priv->rf_mode);
1215                 goto fail;
1216         }
1217
1218         ret = xc_SetTVStandard(priv,
1219                 XC4000_Standard[priv->video_standard].VideoMode,
1220                 XC4000_Standard[priv->video_standard].AudioMode);
1221         if (ret != XC_RESULT_SUCCESS) {
1222                 printk(KERN_ERR "xc4000: xc_SetTVStandard failed\n");
1223                 goto fail;
1224         }
1225         xc_tune_channel(priv, priv->freq_hz, XC_TUNE_DIGITAL);
1226
1227         if (debug)
1228                 xc_debug_dump(priv);
1229
1230         ret = 0;
1231
1232 fail:
1233         mutex_unlock(&priv->lock);
1234
1235         return ret;
1236 }
1237
1238 static int xc4000_set_analog_params(struct dvb_frontend *fe,
1239         struct analog_parameters *params)
1240 {
1241         struct xc4000_priv *priv = fe->tuner_priv;
1242         int     ret = -EREMOTEIO;
1243
1244         dprintk(1, "%s() frequency=%d (in units of 62.5khz)\n",
1245                 __func__, params->frequency);
1246
1247         mutex_lock(&priv->lock);
1248
1249         /* Fix me: it could be air. */
1250         priv->rf_mode = params->mode;
1251         if (params->mode > XC_RF_MODE_CABLE)
1252                 priv->rf_mode = XC_RF_MODE_CABLE;
1253
1254         /* params->frequency is in units of 62.5khz */
1255         priv->freq_hz = params->frequency * 62500;
1256
1257         /* FIX ME: Some video standards may have several possible audio
1258                    standards. We simply default to one of them here.
1259          */
1260         if (params->std & V4L2_STD_MN) {
1261                 /* default to BTSC audio standard */
1262                 priv->video_standard = XC4000_MN_NTSC_PAL_BTSC;
1263                 goto tune_channel;
1264         }
1265
1266         if (params->std & V4L2_STD_PAL_BG) {
1267                 /* default to NICAM audio standard */
1268                 priv->video_standard = XC4000_BG_PAL_NICAM;
1269                 goto tune_channel;
1270         }
1271
1272         if (params->std & V4L2_STD_PAL_I) {
1273                 /* default to NICAM audio standard */
1274                 priv->video_standard = XC4000_I_PAL_NICAM;
1275                 goto tune_channel;
1276         }
1277
1278         if (params->std & V4L2_STD_PAL_DK) {
1279                 /* default to NICAM audio standard */
1280                 priv->video_standard = XC4000_DK_PAL_NICAM;
1281                 goto tune_channel;
1282         }
1283
1284         if (params->std & V4L2_STD_SECAM_DK) {
1285                 /* default to A2 DK1 audio standard */
1286                 priv->video_standard = XC4000_DK_SECAM_A2DK1;
1287                 goto tune_channel;
1288         }
1289
1290         if (params->std & V4L2_STD_SECAM_L) {
1291                 priv->video_standard = XC4000_L_SECAM_NICAM;
1292                 goto tune_channel;
1293         }
1294
1295         if (params->std & V4L2_STD_SECAM_LC) {
1296                 priv->video_standard = XC4000_LC_SECAM_NICAM;
1297                 goto tune_channel;
1298         }
1299
1300 tune_channel:
1301
1302         /* FIXME - firmware type not being set properly */
1303         if (check_firmware(fe, DTV8, 0, priv->if_khz) != XC_RESULT_SUCCESS)
1304                 goto fail;
1305
1306         ret = xc_SetSignalSource(priv, priv->rf_mode);
1307         if (ret != XC_RESULT_SUCCESS) {
1308                 printk(KERN_ERR
1309                        "xc4000: xc_SetSignalSource(%d) failed\n",
1310                        priv->rf_mode);
1311                 goto fail;
1312         }
1313
1314         ret = xc_SetTVStandard(priv,
1315                 XC4000_Standard[priv->video_standard].VideoMode,
1316                 XC4000_Standard[priv->video_standard].AudioMode);
1317         if (ret != XC_RESULT_SUCCESS) {
1318                 printk(KERN_ERR "xc4000: xc_SetTVStandard failed\n");
1319                 goto fail;
1320         }
1321
1322         xc_tune_channel(priv, priv->freq_hz, XC_TUNE_ANALOG);
1323
1324         if (debug)
1325                 xc_debug_dump(priv);
1326
1327         ret = 0;
1328
1329 fail:
1330         mutex_unlock(&priv->lock);
1331
1332         return ret;
1333 }
1334
1335 static int xc4000_get_frequency(struct dvb_frontend *fe, u32 *freq)
1336 {
1337         struct xc4000_priv *priv = fe->tuner_priv;
1338         dprintk(1, "%s()\n", __func__);
1339         *freq = priv->freq_hz;
1340         return 0;
1341 }
1342
1343 static int xc4000_get_bandwidth(struct dvb_frontend *fe, u32 *bw)
1344 {
1345         struct xc4000_priv *priv = fe->tuner_priv;
1346         dprintk(1, "%s()\n", __func__);
1347
1348         *bw = priv->bandwidth;
1349         return 0;
1350 }
1351
1352 static int xc4000_get_status(struct dvb_frontend *fe, u32 *status)
1353 {
1354         struct xc4000_priv *priv = fe->tuner_priv;
1355         u16     lock_status = 0;
1356
1357         mutex_lock(&priv->lock);
1358
1359         xc_get_lock_status(priv, &lock_status);
1360
1361         mutex_unlock(&priv->lock);
1362
1363         dprintk(1, "%s() lock_status = 0x%08x\n", __func__, lock_status);
1364
1365         *status = lock_status;
1366
1367         return 0;
1368 }
1369
1370 static int xc4000_sleep(struct dvb_frontend *fe)
1371 {
1372         /* FIXME: djh disable this for now... */
1373         return XC_RESULT_SUCCESS;
1374 }
1375
1376 static int xc4000_init(struct dvb_frontend *fe)
1377 {
1378         struct xc4000_priv *priv = fe->tuner_priv;
1379         int     ret;
1380         dprintk(1, "%s()\n", __func__);
1381
1382         mutex_lock(&priv->lock);
1383         ret = check_firmware(fe, DTV8, 0, priv->if_khz);
1384         mutex_unlock(&priv->lock);
1385         if (ret != XC_RESULT_SUCCESS) {
1386                 printk(KERN_ERR "xc4000: Unable to initialise tuner\n");
1387                 return -EREMOTEIO;
1388         }
1389
1390         if (debug)
1391                 xc_debug_dump(priv);
1392
1393         return 0;
1394 }
1395
1396 static int xc4000_release(struct dvb_frontend *fe)
1397 {
1398         struct xc4000_priv *priv = fe->tuner_priv;
1399
1400         dprintk(1, "%s()\n", __func__);
1401
1402         mutex_lock(&xc4000_list_mutex);
1403
1404         if (priv)
1405                 hybrid_tuner_release_state(priv);
1406
1407         mutex_unlock(&xc4000_list_mutex);
1408
1409         fe->tuner_priv = NULL;
1410
1411         return 0;
1412 }
1413
1414 static const struct dvb_tuner_ops xc4000_tuner_ops = {
1415         .info = {
1416                 .name           = "Xceive XC4000",
1417                 .frequency_min  =    1000000,
1418                 .frequency_max  = 1023000000,
1419                 .frequency_step =      50000,
1420         },
1421
1422         .release           = xc4000_release,
1423         .init              = xc4000_init,
1424         .sleep             = xc4000_sleep,
1425
1426         .set_params        = xc4000_set_params,
1427         .set_analog_params = xc4000_set_analog_params,
1428         .get_frequency     = xc4000_get_frequency,
1429         .get_bandwidth     = xc4000_get_bandwidth,
1430         .get_status        = xc4000_get_status
1431 };
1432
1433 struct dvb_frontend *xc4000_attach(struct dvb_frontend *fe,
1434                                    struct i2c_adapter *i2c,
1435                                    struct xc4000_config *cfg)
1436 {
1437         struct xc4000_priv *priv = NULL;
1438         int     instance;
1439         u16     id = 0;
1440
1441         dprintk(1, "%s(%d-%04x)\n", __func__,
1442                 i2c ? i2c_adapter_id(i2c) : -1,
1443                 cfg ? cfg->i2c_address : -1);
1444
1445         mutex_lock(&xc4000_list_mutex);
1446
1447         instance = hybrid_tuner_request_state(struct xc4000_priv, priv,
1448                                               hybrid_tuner_instance_list,
1449                                               i2c, cfg->i2c_address, "xc4000");
1450         switch (instance) {
1451         case 0:
1452                 goto fail;
1453                 break;
1454         case 1:
1455                 /* new tuner instance */
1456                 priv->bandwidth = BANDWIDTH_6_MHZ;
1457                 mutex_init(&priv->lock);
1458                 fe->tuner_priv = priv;
1459                 break;
1460         default:
1461                 /* existing tuner instance */
1462                 fe->tuner_priv = priv;
1463                 break;
1464         }
1465
1466         if (priv->if_khz == 0) {
1467                 /* If the IF hasn't been set yet, use the value provided by
1468                    the caller (occurs in hybrid devices where the analog
1469                    call to xc4000_attach occurs before the digital side) */
1470                 priv->if_khz = cfg->if_khz;
1471         }
1472
1473         /* Check if firmware has been loaded. It is possible that another
1474            instance of the driver has loaded the firmware.
1475          */
1476
1477         if (xc4000_readreg(priv, XREG_PRODUCT_ID, &id) != XC_RESULT_SUCCESS)
1478                         goto fail;
1479
1480         switch (id) {
1481         case XC_PRODUCT_ID_FW_LOADED:
1482                 printk(KERN_INFO
1483                         "xc4000: Successfully identified at address 0x%02x\n",
1484                         cfg->i2c_address);
1485                 printk(KERN_INFO
1486                         "xc4000: Firmware has been loaded previously\n");
1487                 break;
1488         case XC_PRODUCT_ID_FW_NOT_LOADED:
1489                 printk(KERN_INFO
1490                         "xc4000: Successfully identified at address 0x%02x\n",
1491                         cfg->i2c_address);
1492                 printk(KERN_INFO
1493                         "xc4000: Firmware has not been loaded previously\n");
1494                 break;
1495         default:
1496                 printk(KERN_ERR
1497                         "xc4000: Device not found at addr 0x%02x (0x%x)\n",
1498                         cfg->i2c_address, id);
1499                 goto fail;
1500         }
1501
1502         mutex_unlock(&xc4000_list_mutex);
1503
1504         memcpy(&fe->ops.tuner_ops, &xc4000_tuner_ops,
1505                 sizeof(struct dvb_tuner_ops));
1506
1507         /* FIXME: For now, load the firmware at startup.  We will remove this
1508            before the code goes to production... */
1509         mutex_lock(&priv->lock);
1510         check_firmware(fe, DTV8, 0, priv->if_khz);
1511         mutex_unlock(&priv->lock);
1512
1513         return fe;
1514 fail:
1515         mutex_unlock(&xc4000_list_mutex);
1516
1517         xc4000_release(fe);
1518         return NULL;
1519 }
1520 EXPORT_SYMBOL(xc4000_attach);
1521
1522 MODULE_AUTHOR("Steven Toth, Davide Ferri");
1523 MODULE_DESCRIPTION("Xceive xc4000 silicon tuner driver");
1524 MODULE_LICENSE("GPL");