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