]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/media/dvb-frontends/stv0367.c
Merge tag 'driver-core-4.13-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git...
[karo-tx-linux.git] / drivers / media / dvb-frontends / stv0367.c
1 /*
2  * stv0367.c
3  *
4  * Driver for ST STV0367 DVB-T & DVB-C demodulator IC.
5  *
6  * Copyright (C) ST Microelectronics.
7  * Copyright (C) 2010,2011 NetUP Inc.
8  * Copyright (C) 2010,2011 Igor M. Liplianin <liplianin@netup.ru>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *
19  * GNU General Public License for more details.
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/string.h>
25 #include <linux/slab.h>
26 #include <linux/i2c.h>
27
28 #include "dvb_math.h"
29
30 #include "stv0367.h"
31 #include "stv0367_defs.h"
32 #include "stv0367_regs.h"
33 #include "stv0367_priv.h"
34
35 /* Max transfer size done by I2C transfer functions */
36 #define MAX_XFER_SIZE  64
37
38 static int stvdebug;
39 module_param_named(debug, stvdebug, int, 0644);
40
41 static int i2cdebug;
42 module_param_named(i2c_debug, i2cdebug, int, 0644);
43
44 #define dprintk(args...) \
45         do { \
46                 if (stvdebug) \
47                         printk(KERN_DEBUG args); \
48         } while (0)
49         /* DVB-C */
50
51 enum active_demod_state { demod_none, demod_ter, demod_cab };
52
53 struct stv0367cab_state {
54         enum stv0367_cab_signal_type    state;
55         u32     mclk;
56         u32     adc_clk;
57         s32     search_range;
58         s32     derot_offset;
59         /* results */
60         int locked;                     /* channel found                */
61         u32 freq_khz;                   /* found frequency (in kHz)     */
62         u32 symbol_rate;                /* found symbol rate (in Bds)   */
63         enum fe_spectral_inversion spect_inv; /* Spectrum Inversion     */
64         u32 qamfec_status_reg;          /* status reg to poll for FEC Lock */
65 };
66
67 struct stv0367ter_state {
68         /* DVB-T */
69         enum stv0367_ter_signal_type state;
70         enum stv0367_ter_if_iq_mode if_iq_mode;
71         enum stv0367_ter_mode mode;/* mode 2K or 8K */
72         enum fe_guard_interval guard;
73         enum stv0367_ter_hierarchy hierarchy;
74         u32 frequency;
75         enum fe_spectral_inversion sense; /*  current search spectrum */
76         u8  force; /* force mode/guard */
77         u8  bw; /* channel width 6, 7 or 8 in MHz */
78         u8  pBW; /* channel width used during previous lock */
79         u32 pBER;
80         u32 pPER;
81         u32 ucblocks;
82         s8  echo_pos; /* echo position */
83         u8  first_lock;
84         u8  unlock_counter;
85         u32 agc_val;
86 };
87
88 struct stv0367_state {
89         struct dvb_frontend fe;
90         struct i2c_adapter *i2c;
91         /* config settings */
92         const struct stv0367_config *config;
93         u8 chip_id;
94         /* DVB-C */
95         struct stv0367cab_state *cab_state;
96         /* DVB-T */
97         struct stv0367ter_state *ter_state;
98         /* flags for operation control */
99         u8 use_i2c_gatectrl;
100         u8 deftabs;
101         u8 reinit_on_setfrontend;
102         u8 auto_if_khz;
103         enum active_demod_state activedemod;
104 };
105
106 #define RF_LOOKUP_TABLE_SIZE  31
107 #define RF_LOOKUP_TABLE2_SIZE 16
108 /* RF Level (for RF AGC->AGC1) Lookup Table, depends on the board and tuner.*/
109 static const s32 stv0367cab_RF_LookUp1[RF_LOOKUP_TABLE_SIZE][RF_LOOKUP_TABLE_SIZE] = {
110         {/*AGC1*/
111                 48, 50, 51, 53, 54, 56, 57, 58, 60, 61, 62, 63,
112                 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
113                 76, 77, 78, 80, 83, 85, 88,
114         }, {/*RF(dbm)*/
115                 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
116                 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 46, 47,
117                 49, 50, 52, 53, 54, 55, 56,
118         }
119 };
120 /* RF Level (for IF AGC->AGC2) Lookup Table, depends on the board and tuner.*/
121 static const s32 stv0367cab_RF_LookUp2[RF_LOOKUP_TABLE2_SIZE][RF_LOOKUP_TABLE2_SIZE] = {
122         {/*AGC2*/
123                 28, 29, 31, 32, 34, 35, 36, 37,
124                 38, 39, 40, 41, 42, 43, 44, 45,
125         }, {/*RF(dbm)*/
126                 57, 58, 59, 60, 61, 62, 63, 64,
127                 65, 66, 67, 68, 69, 70, 71, 72,
128         }
129 };
130
131 static
132 int stv0367_writeregs(struct stv0367_state *state, u16 reg, u8 *data, int len)
133 {
134         u8 buf[MAX_XFER_SIZE];
135         struct i2c_msg msg = {
136                 .addr = state->config->demod_address,
137                 .flags = 0,
138                 .buf = buf,
139                 .len = len + 2
140         };
141         int ret;
142
143         if (2 + len > sizeof(buf)) {
144                 printk(KERN_WARNING
145                        "%s: i2c wr reg=%04x: len=%d is too big!\n",
146                        KBUILD_MODNAME, reg, len);
147                 return -EINVAL;
148         }
149
150
151         buf[0] = MSB(reg);
152         buf[1] = LSB(reg);
153         memcpy(buf + 2, data, len);
154
155         if (i2cdebug)
156                 printk(KERN_DEBUG "%s: [%02x] %02x: %02x\n", __func__,
157                         state->config->demod_address, reg, buf[2]);
158
159         ret = i2c_transfer(state->i2c, &msg, 1);
160         if (ret != 1)
161                 printk(KERN_ERR "%s: i2c write error! ([%02x] %02x: %02x)\n",
162                         __func__, state->config->demod_address, reg, buf[2]);
163
164         return (ret != 1) ? -EREMOTEIO : 0;
165 }
166
167 static int stv0367_writereg(struct stv0367_state *state, u16 reg, u8 data)
168 {
169         return stv0367_writeregs(state, reg, &data, 1);
170 }
171
172 static u8 stv0367_readreg(struct stv0367_state *state, u16 reg)
173 {
174         u8 b0[] = { 0, 0 };
175         u8 b1[] = { 0 };
176         struct i2c_msg msg[] = {
177                 {
178                         .addr = state->config->demod_address,
179                         .flags = 0,
180                         .buf = b0,
181                         .len = 2
182                 }, {
183                         .addr = state->config->demod_address,
184                         .flags = I2C_M_RD,
185                         .buf = b1,
186                         .len = 1
187                 }
188         };
189         int ret;
190
191         b0[0] = MSB(reg);
192         b0[1] = LSB(reg);
193
194         ret = i2c_transfer(state->i2c, msg, 2);
195         if (ret != 2)
196                 printk(KERN_ERR "%s: i2c read error ([%02x] %02x: %02x)\n",
197                         __func__, state->config->demod_address, reg, b1[0]);
198
199         if (i2cdebug)
200                 printk(KERN_DEBUG "%s: [%02x] %02x: %02x\n", __func__,
201                         state->config->demod_address, reg, b1[0]);
202
203         return b1[0];
204 }
205
206 static void extract_mask_pos(u32 label, u8 *mask, u8 *pos)
207 {
208         u8 position = 0, i = 0;
209
210         (*mask) = label & 0xff;
211
212         while ((position == 0) && (i < 8)) {
213                 position = ((*mask) >> i) & 0x01;
214                 i++;
215         }
216
217         (*pos) = (i - 1);
218 }
219
220 static void stv0367_writebits(struct stv0367_state *state, u32 label, u8 val)
221 {
222         u8 reg, mask, pos;
223
224         reg = stv0367_readreg(state, (label >> 16) & 0xffff);
225         extract_mask_pos(label, &mask, &pos);
226
227         val = mask & (val << pos);
228
229         reg = (reg & (~mask)) | val;
230         stv0367_writereg(state, (label >> 16) & 0xffff, reg);
231
232 }
233
234 static void stv0367_setbits(u8 *reg, u32 label, u8 val)
235 {
236         u8 mask, pos;
237
238         extract_mask_pos(label, &mask, &pos);
239
240         val = mask & (val << pos);
241
242         (*reg) = ((*reg) & (~mask)) | val;
243 }
244
245 static u8 stv0367_readbits(struct stv0367_state *state, u32 label)
246 {
247         u8 val = 0xff;
248         u8 mask, pos;
249
250         extract_mask_pos(label, &mask, &pos);
251
252         val = stv0367_readreg(state, label >> 16);
253         val = (val & mask) >> pos;
254
255         return val;
256 }
257
258 #if 0 /* Currently, unused */
259 static u8 stv0367_getbits(u8 reg, u32 label)
260 {
261         u8 mask, pos;
262
263         extract_mask_pos(label, &mask, &pos);
264
265         return (reg & mask) >> pos;
266 }
267 #endif
268
269 static void stv0367_write_table(struct stv0367_state *state,
270                                 const struct st_register *deftab)
271 {
272         int i = 0;
273
274         while (1) {
275                 if (!deftab[i].addr)
276                         break;
277                 stv0367_writereg(state, deftab[i].addr, deftab[i].value);
278                 i++;
279         }
280 }
281
282 static void stv0367_pll_setup(struct stv0367_state *state,
283                                 u32 icspeed, u32 xtal)
284 {
285         /* note on regs: R367TER_* and R367CAB_* defines each point to
286          * 0xf0d8, so just use R367TER_ for both cases
287          */
288
289         switch (icspeed) {
290         case STV0367_ICSPEED_58000:
291                 switch (xtal) {
292                 default:
293                 case 27000000:
294                         dprintk("STV0367 SetCLKgen for 58MHz IC and 27Mhz crystal\n");
295                         /* PLLMDIV: 27, PLLNDIV: 232 */
296                         stv0367_writereg(state, R367TER_PLLMDIV, 0x1b);
297                         stv0367_writereg(state, R367TER_PLLNDIV, 0xe8);
298                         break;
299                 }
300                 break;
301         default:
302         case STV0367_ICSPEED_53125:
303                 switch (xtal) {
304                         /* set internal freq to 53.125MHz */
305                 case 16000000:
306                         stv0367_writereg(state, R367TER_PLLMDIV, 0x2);
307                         stv0367_writereg(state, R367TER_PLLNDIV, 0x1b);
308                         break;
309                 case 25000000:
310                         stv0367_writereg(state, R367TER_PLLMDIV, 0xa);
311                         stv0367_writereg(state, R367TER_PLLNDIV, 0x55);
312                         break;
313                 default:
314                 case 27000000:
315                         dprintk("FE_STV0367TER_SetCLKgen for 27Mhz\n");
316                         stv0367_writereg(state, R367TER_PLLMDIV, 0x1);
317                         stv0367_writereg(state, R367TER_PLLNDIV, 0x8);
318                         break;
319                 case 30000000:
320                         stv0367_writereg(state, R367TER_PLLMDIV, 0xc);
321                         stv0367_writereg(state, R367TER_PLLNDIV, 0x55);
322                         break;
323                 }
324         }
325
326         stv0367_writereg(state, R367TER_PLLSETUP, 0x18);
327 }
328
329 static int stv0367_get_if_khz(struct stv0367_state *state, u32 *ifkhz)
330 {
331         if (state->auto_if_khz && state->fe.ops.tuner_ops.get_if_frequency) {
332                 state->fe.ops.tuner_ops.get_if_frequency(&state->fe, ifkhz);
333                 *ifkhz = *ifkhz / 1000; /* hz -> khz */
334         } else
335                 *ifkhz = state->config->if_khz;
336
337         return 0;
338 }
339
340 static int stv0367ter_gate_ctrl(struct dvb_frontend *fe, int enable)
341 {
342         struct stv0367_state *state = fe->demodulator_priv;
343         u8 tmp = stv0367_readreg(state, R367TER_I2CRPT);
344
345         dprintk("%s:\n", __func__);
346
347         if (enable) {
348                 stv0367_setbits(&tmp, F367TER_STOP_ENABLE, 0);
349                 stv0367_setbits(&tmp, F367TER_I2CT_ON, 1);
350         } else {
351                 stv0367_setbits(&tmp, F367TER_STOP_ENABLE, 1);
352                 stv0367_setbits(&tmp, F367TER_I2CT_ON, 0);
353         }
354
355         stv0367_writereg(state, R367TER_I2CRPT, tmp);
356
357         return 0;
358 }
359
360 static u32 stv0367_get_tuner_freq(struct dvb_frontend *fe)
361 {
362         struct dvb_frontend_ops *frontend_ops = &fe->ops;
363         struct dvb_tuner_ops    *tuner_ops = &frontend_ops->tuner_ops;
364         u32 freq = 0;
365         int err = 0;
366
367         dprintk("%s:\n", __func__);
368
369         if (tuner_ops->get_frequency) {
370                 err = tuner_ops->get_frequency(fe, &freq);
371                 if (err < 0) {
372                         printk(KERN_ERR "%s: Invalid parameter\n", __func__);
373                         return err;
374                 }
375
376                 dprintk("%s: frequency=%d\n", __func__, freq);
377
378         } else
379                 return -1;
380
381         return freq;
382 }
383
384 static u16 CellsCoeffs_8MHz_367cofdm[3][6][5] = {
385         {
386                 {0x10EF, 0xE205, 0x10EF, 0xCE49, 0x6DA7}, /* CELL 1 COEFFS 27M*/
387                 {0x2151, 0xc557, 0x2151, 0xc705, 0x6f93}, /* CELL 2 COEFFS */
388                 {0x2503, 0xc000, 0x2503, 0xc375, 0x7194}, /* CELL 3 COEFFS */
389                 {0x20E9, 0xca94, 0x20e9, 0xc153, 0x7194}, /* CELL 4 COEFFS */
390                 {0x06EF, 0xF852, 0x06EF, 0xC057, 0x7207}, /* CELL 5 COEFFS */
391                 {0x0000, 0x0ECC, 0x0ECC, 0x0000, 0x3647} /* CELL 6 COEFFS */
392         }, {
393                 {0x10A0, 0xE2AF, 0x10A1, 0xCE76, 0x6D6D}, /* CELL 1 COEFFS 25M*/
394                 {0x20DC, 0xC676, 0x20D9, 0xC80A, 0x6F29},
395                 {0x2532, 0xC000, 0x251D, 0xC391, 0x706F},
396                 {0x1F7A, 0xCD2B, 0x2032, 0xC15E, 0x711F},
397                 {0x0698, 0xFA5E, 0x0568, 0xC059, 0x7193},
398                 {0x0000, 0x0918, 0x149C, 0x0000, 0x3642} /* CELL 6 COEFFS */
399         }, {
400                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, /* 30M */
401                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
402                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
403                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
404                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
405                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}
406         }
407 };
408
409 static u16 CellsCoeffs_7MHz_367cofdm[3][6][5] = {
410         {
411                 {0x12CA, 0xDDAF, 0x12CA, 0xCCEB, 0x6FB1}, /* CELL 1 COEFFS 27M*/
412                 {0x2329, 0xC000, 0x2329, 0xC6B0, 0x725F}, /* CELL 2 COEFFS */
413                 {0x2394, 0xC000, 0x2394, 0xC2C7, 0x7410}, /* CELL 3 COEFFS */
414                 {0x251C, 0xC000, 0x251C, 0xC103, 0x74D9}, /* CELL 4 COEFFS */
415                 {0x0804, 0xF546, 0x0804, 0xC040, 0x7544}, /* CELL 5 COEFFS */
416                 {0x0000, 0x0CD9, 0x0CD9, 0x0000, 0x370A} /* CELL 6 COEFFS */
417         }, {
418                 {0x1285, 0xDE47, 0x1285, 0xCD17, 0x6F76}, /*25M*/
419                 {0x234C, 0xC000, 0x2348, 0xC6DA, 0x7206},
420                 {0x23B4, 0xC000, 0x23AC, 0xC2DB, 0x73B3},
421                 {0x253D, 0xC000, 0x25B6, 0xC10B, 0x747F},
422                 {0x0721, 0xF79C, 0x065F, 0xC041, 0x74EB},
423                 {0x0000, 0x08FA, 0x1162, 0x0000, 0x36FF}
424         }, {
425                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, /* 30M */
426                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
427                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
428                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
429                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
430                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}
431         }
432 };
433
434 static u16 CellsCoeffs_6MHz_367cofdm[3][6][5] = {
435         {
436                 {0x1699, 0xD5B8, 0x1699, 0xCBC3, 0x713B}, /* CELL 1 COEFFS 27M*/
437                 {0x2245, 0xC000, 0x2245, 0xC568, 0x74D5}, /* CELL 2 COEFFS */
438                 {0x227F, 0xC000, 0x227F, 0xC1FC, 0x76C6}, /* CELL 3 COEFFS */
439                 {0x235E, 0xC000, 0x235E, 0xC0A7, 0x778A}, /* CELL 4 COEFFS */
440                 {0x0ECB, 0xEA0B, 0x0ECB, 0xC027, 0x77DD}, /* CELL 5 COEFFS */
441                 {0x0000, 0x0B68, 0x0B68, 0x0000, 0xC89A}, /* CELL 6 COEFFS */
442         }, {
443                 {0x1655, 0xD64E, 0x1658, 0xCBEF, 0x70FE}, /*25M*/
444                 {0x225E, 0xC000, 0x2256, 0xC589, 0x7489},
445                 {0x2293, 0xC000, 0x2295, 0xC209, 0x767E},
446                 {0x2377, 0xC000, 0x23AA, 0xC0AB, 0x7746},
447                 {0x0DC7, 0xEBC8, 0x0D07, 0xC027, 0x7799},
448                 {0x0000, 0x0888, 0x0E9C, 0x0000, 0x3757}
449
450         }, {
451                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, /* 30M */
452                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
453                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
454                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
455                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
456                 {0x0000, 0x0000, 0x0000, 0x0000, 0x0000}
457         }
458 };
459
460 static u32 stv0367ter_get_mclk(struct stv0367_state *state, u32 ExtClk_Hz)
461 {
462         u32 mclk_Hz = 0; /* master clock frequency (Hz) */
463         u32 m, n, p;
464
465         dprintk("%s:\n", __func__);
466
467         if (stv0367_readbits(state, F367TER_BYPASS_PLLXN) == 0) {
468                 n = (u32)stv0367_readbits(state, F367TER_PLL_NDIV);
469                 if (n == 0)
470                         n = n + 1;
471
472                 m = (u32)stv0367_readbits(state, F367TER_PLL_MDIV);
473                 if (m == 0)
474                         m = m + 1;
475
476                 p = (u32)stv0367_readbits(state, F367TER_PLL_PDIV);
477                 if (p > 5)
478                         p = 5;
479
480                 mclk_Hz = ((ExtClk_Hz / 2) * n) / (m * (1 << p));
481
482                 dprintk("N=%d M=%d P=%d mclk_Hz=%d ExtClk_Hz=%d\n",
483                                 n, m, p, mclk_Hz, ExtClk_Hz);
484         } else
485                 mclk_Hz = ExtClk_Hz;
486
487         dprintk("%s: mclk_Hz=%d\n", __func__, mclk_Hz);
488
489         return mclk_Hz;
490 }
491
492 static int stv0367ter_filt_coeff_init(struct stv0367_state *state,
493                                 u16 CellsCoeffs[3][6][5], u32 DemodXtal)
494 {
495         int i, j, k, freq;
496
497         dprintk("%s:\n", __func__);
498
499         freq = stv0367ter_get_mclk(state, DemodXtal);
500
501         if (freq == 53125000)
502                 k = 1; /* equivalent to Xtal 25M on 362*/
503         else if (freq == 54000000)
504                 k = 0; /* equivalent to Xtal 27M on 362*/
505         else if (freq == 52500000)
506                 k = 2; /* equivalent to Xtal 30M on 362*/
507         else
508                 return 0;
509
510         for (i = 1; i <= 6; i++) {
511                 stv0367_writebits(state, F367TER_IIR_CELL_NB, i - 1);
512
513                 for (j = 1; j <= 5; j++) {
514                         stv0367_writereg(state,
515                                 (R367TER_IIRCX_COEFF1_MSB + 2 * (j - 1)),
516                                 MSB(CellsCoeffs[k][i-1][j-1]));
517                         stv0367_writereg(state,
518                                 (R367TER_IIRCX_COEFF1_LSB + 2 * (j - 1)),
519                                 LSB(CellsCoeffs[k][i-1][j-1]));
520                 }
521         }
522
523         return 1;
524
525 }
526
527 static void stv0367ter_agc_iir_lock_detect_set(struct stv0367_state *state)
528 {
529         dprintk("%s:\n", __func__);
530
531         stv0367_writebits(state, F367TER_LOCK_DETECT_LSB, 0x00);
532
533         /* Lock detect 1 */
534         stv0367_writebits(state, F367TER_LOCK_DETECT_CHOICE, 0x00);
535         stv0367_writebits(state, F367TER_LOCK_DETECT_MSB, 0x06);
536         stv0367_writebits(state, F367TER_AUT_AGC_TARGET_LSB, 0x04);
537
538         /* Lock detect 2 */
539         stv0367_writebits(state, F367TER_LOCK_DETECT_CHOICE, 0x01);
540         stv0367_writebits(state, F367TER_LOCK_DETECT_MSB, 0x06);
541         stv0367_writebits(state, F367TER_AUT_AGC_TARGET_LSB, 0x04);
542
543         /* Lock detect 3 */
544         stv0367_writebits(state, F367TER_LOCK_DETECT_CHOICE, 0x02);
545         stv0367_writebits(state, F367TER_LOCK_DETECT_MSB, 0x01);
546         stv0367_writebits(state, F367TER_AUT_AGC_TARGET_LSB, 0x00);
547
548         /* Lock detect 4 */
549         stv0367_writebits(state, F367TER_LOCK_DETECT_CHOICE, 0x03);
550         stv0367_writebits(state, F367TER_LOCK_DETECT_MSB, 0x01);
551         stv0367_writebits(state, F367TER_AUT_AGC_TARGET_LSB, 0x00);
552
553 }
554
555 static int stv0367_iir_filt_init(struct stv0367_state *state, u8 Bandwidth,
556                                                         u32 DemodXtalValue)
557 {
558         dprintk("%s:\n", __func__);
559
560         stv0367_writebits(state, F367TER_NRST_IIR, 0);
561
562         switch (Bandwidth) {
563         case 6:
564                 if (!stv0367ter_filt_coeff_init(state,
565                                 CellsCoeffs_6MHz_367cofdm,
566                                 DemodXtalValue))
567                         return 0;
568                 break;
569         case 7:
570                 if (!stv0367ter_filt_coeff_init(state,
571                                 CellsCoeffs_7MHz_367cofdm,
572                                 DemodXtalValue))
573                         return 0;
574                 break;
575         case 8:
576                 if (!stv0367ter_filt_coeff_init(state,
577                                 CellsCoeffs_8MHz_367cofdm,
578                                 DemodXtalValue))
579                         return 0;
580                 break;
581         default:
582                 return 0;
583         }
584
585         stv0367_writebits(state, F367TER_NRST_IIR, 1);
586
587         return 1;
588 }
589
590 static void stv0367ter_agc_iir_rst(struct stv0367_state *state)
591 {
592
593         u8 com_n;
594
595         dprintk("%s:\n", __func__);
596
597         com_n = stv0367_readbits(state, F367TER_COM_N);
598
599         stv0367_writebits(state, F367TER_COM_N, 0x07);
600
601         stv0367_writebits(state, F367TER_COM_SOFT_RSTN, 0x00);
602         stv0367_writebits(state, F367TER_COM_AGC_ON, 0x00);
603
604         stv0367_writebits(state, F367TER_COM_SOFT_RSTN, 0x01);
605         stv0367_writebits(state, F367TER_COM_AGC_ON, 0x01);
606
607         stv0367_writebits(state, F367TER_COM_N, com_n);
608
609 }
610
611 static int stv0367ter_duration(s32 mode, int tempo1, int tempo2, int tempo3)
612 {
613         int local_tempo = 0;
614         switch (mode) {
615         case 0:
616                 local_tempo = tempo1;
617                 break;
618         case 1:
619                 local_tempo = tempo2;
620                 break ;
621
622         case 2:
623                 local_tempo = tempo3;
624                 break;
625
626         default:
627                 break;
628         }
629         /*      msleep(local_tempo);  */
630         return local_tempo;
631 }
632
633 static enum
634 stv0367_ter_signal_type stv0367ter_check_syr(struct stv0367_state *state)
635 {
636         int wd = 100;
637         unsigned short int SYR_var;
638         s32 SYRStatus;
639
640         dprintk("%s:\n", __func__);
641
642         SYR_var = stv0367_readbits(state, F367TER_SYR_LOCK);
643
644         while ((!SYR_var) && (wd > 0)) {
645                 usleep_range(2000, 3000);
646                 wd -= 2;
647                 SYR_var = stv0367_readbits(state, F367TER_SYR_LOCK);
648         }
649
650         if (!SYR_var)
651                 SYRStatus = FE_TER_NOSYMBOL;
652         else
653                 SYRStatus =  FE_TER_SYMBOLOK;
654
655         dprintk("stv0367ter_check_syr SYRStatus %s\n",
656                                 SYR_var == 0 ? "No Symbol" : "OK");
657
658         return SYRStatus;
659 }
660
661 static enum
662 stv0367_ter_signal_type stv0367ter_check_cpamp(struct stv0367_state *state,
663                                                                 s32 FFTmode)
664 {
665
666         s32  CPAMPvalue = 0, CPAMPStatus, CPAMPMin;
667         int wd = 0;
668
669         dprintk("%s:\n", __func__);
670
671         switch (FFTmode) {
672         case 0: /*2k mode*/
673                 CPAMPMin = 20;
674                 wd = 10;
675                 break;
676         case 1: /*8k mode*/
677                 CPAMPMin = 80;
678                 wd = 55;
679                 break;
680         case 2: /*4k mode*/
681                 CPAMPMin = 40;
682                 wd = 30;
683                 break;
684         default:
685                 CPAMPMin = 0xffff;  /*drives to NOCPAMP */
686                 break;
687         }
688
689         dprintk("%s: CPAMPMin=%d wd=%d\n", __func__, CPAMPMin, wd);
690
691         CPAMPvalue = stv0367_readbits(state, F367TER_PPM_CPAMP_DIRECT);
692         while ((CPAMPvalue < CPAMPMin) && (wd > 0)) {
693                 usleep_range(1000, 2000);
694                 wd -= 1;
695                 CPAMPvalue = stv0367_readbits(state, F367TER_PPM_CPAMP_DIRECT);
696                 /*dprintk("CPAMPvalue= %d at wd=%d\n",CPAMPvalue,wd); */
697         }
698         dprintk("******last CPAMPvalue= %d at wd=%d\n", CPAMPvalue, wd);
699         if (CPAMPvalue < CPAMPMin) {
700                 CPAMPStatus = FE_TER_NOCPAMP;
701                 dprintk("%s: CPAMP failed\n", __func__);
702         } else {
703                 dprintk("%s: CPAMP OK !\n", __func__);
704                 CPAMPStatus = FE_TER_CPAMPOK;
705         }
706
707         return CPAMPStatus;
708 }
709
710 static enum stv0367_ter_signal_type
711 stv0367ter_lock_algo(struct stv0367_state *state)
712 {
713         enum stv0367_ter_signal_type ret_flag;
714         short int wd, tempo;
715         u8 try, u_var1 = 0, u_var2 = 0, u_var3 = 0, u_var4 = 0, mode, guard;
716         u8 tmp, tmp2;
717
718         dprintk("%s:\n", __func__);
719
720         if (state == NULL)
721                 return FE_TER_SWNOK;
722
723         try = 0;
724         do {
725                 ret_flag = FE_TER_LOCKOK;
726
727                 stv0367_writebits(state, F367TER_CORE_ACTIVE, 0);
728
729                 if (state->config->if_iq_mode != 0)
730                         stv0367_writebits(state, F367TER_COM_N, 0x07);
731
732                 stv0367_writebits(state, F367TER_GUARD, 3);/* suggest 2k 1/4 */
733                 stv0367_writebits(state, F367TER_MODE, 0);
734                 stv0367_writebits(state, F367TER_SYR_TR_DIS, 0);
735                 usleep_range(5000, 10000);
736
737                 stv0367_writebits(state, F367TER_CORE_ACTIVE, 1);
738
739
740                 if (stv0367ter_check_syr(state) == FE_TER_NOSYMBOL)
741                         return FE_TER_NOSYMBOL;
742                 else { /*
743                         if chip locked on wrong mode first try,
744                         it must lock correctly second try */
745                         mode = stv0367_readbits(state, F367TER_SYR_MODE);
746                         if (stv0367ter_check_cpamp(state, mode) ==
747                                                         FE_TER_NOCPAMP) {
748                                 if (try == 0)
749                                         ret_flag = FE_TER_NOCPAMP;
750
751                         }
752                 }
753
754                 try++;
755         } while ((try < 10) && (ret_flag != FE_TER_LOCKOK));
756
757         tmp  = stv0367_readreg(state, R367TER_SYR_STAT);
758         tmp2 = stv0367_readreg(state, R367TER_STATUS);
759         dprintk("state=%p\n", state);
760         dprintk("LOCK OK! mode=%d SYR_STAT=0x%x R367TER_STATUS=0x%x\n",
761                                                         mode, tmp, tmp2);
762
763         tmp  = stv0367_readreg(state, R367TER_PRVIT);
764         tmp2 = stv0367_readreg(state, R367TER_I2CRPT);
765         dprintk("PRVIT=0x%x I2CRPT=0x%x\n", tmp, tmp2);
766
767         tmp  = stv0367_readreg(state, R367TER_GAIN_SRC1);
768         dprintk("GAIN_SRC1=0x%x\n", tmp);
769
770         if ((mode != 0) && (mode != 1) && (mode != 2))
771                 return FE_TER_SWNOK;
772
773         /*guard=stv0367_readbits(state,F367TER_SYR_GUARD); */
774
775         /*suppress EPQ auto for SYR_GARD 1/16 or 1/32
776         and set channel predictor in automatic */
777 #if 0
778         switch (guard) {
779
780         case 0:
781         case 1:
782                 stv0367_writebits(state, F367TER_AUTO_LE_EN, 0);
783                 stv0367_writereg(state, R367TER_CHC_CTL, 0x01);
784                 break;
785         case 2:
786         case 3:
787                 stv0367_writebits(state, F367TER_AUTO_LE_EN, 1);
788                 stv0367_writereg(state, R367TER_CHC_CTL, 0x11);
789                 break;
790
791         default:
792                 return FE_TER_SWNOK;
793         }
794 #endif
795
796         /*reset fec an reedsolo FOR 367 only*/
797         stv0367_writebits(state, F367TER_RST_SFEC, 1);
798         stv0367_writebits(state, F367TER_RST_REEDSOLO, 1);
799         usleep_range(1000, 2000);
800         stv0367_writebits(state, F367TER_RST_SFEC, 0);
801         stv0367_writebits(state, F367TER_RST_REEDSOLO, 0);
802
803         u_var1 = stv0367_readbits(state, F367TER_LK);
804         u_var2 = stv0367_readbits(state, F367TER_PRF);
805         u_var3 = stv0367_readbits(state, F367TER_TPS_LOCK);
806         /*      u_var4=stv0367_readbits(state,F367TER_TSFIFO_LINEOK); */
807
808         wd = stv0367ter_duration(mode, 125, 500, 250);
809         tempo = stv0367ter_duration(mode, 4, 16, 8);
810
811         /*while ( ((!u_var1)||(!u_var2)||(!u_var3)||(!u_var4))  && (wd>=0)) */
812         while (((!u_var1) || (!u_var2) || (!u_var3)) && (wd >= 0)) {
813                 usleep_range(1000 * tempo, 1000 * (tempo + 1));
814                 wd -= tempo;
815                 u_var1 = stv0367_readbits(state, F367TER_LK);
816                 u_var2 = stv0367_readbits(state, F367TER_PRF);
817                 u_var3 = stv0367_readbits(state, F367TER_TPS_LOCK);
818                 /*u_var4=stv0367_readbits(state, F367TER_TSFIFO_LINEOK); */
819         }
820
821         if (!u_var1)
822                 return FE_TER_NOLOCK;
823
824
825         if (!u_var2)
826                 return FE_TER_NOPRFOUND;
827
828         if (!u_var3)
829                 return FE_TER_NOTPS;
830
831         guard = stv0367_readbits(state, F367TER_SYR_GUARD);
832         stv0367_writereg(state, R367TER_CHC_CTL, 0x11);
833         switch (guard) {
834         case 0:
835         case 1:
836                 stv0367_writebits(state, F367TER_AUTO_LE_EN, 0);
837                 /*stv0367_writereg(state,R367TER_CHC_CTL, 0x1);*/
838                 stv0367_writebits(state, F367TER_SYR_FILTER, 0);
839                 break;
840         case 2:
841         case 3:
842                 stv0367_writebits(state, F367TER_AUTO_LE_EN, 1);
843                 /*stv0367_writereg(state,R367TER_CHC_CTL, 0x11);*/
844                 stv0367_writebits(state, F367TER_SYR_FILTER, 1);
845                 break;
846
847         default:
848                 return FE_TER_SWNOK;
849         }
850
851         /* apply Sfec workaround if 8K 64QAM CR!=1/2*/
852         if ((stv0367_readbits(state, F367TER_TPS_CONST) == 2) &&
853                         (mode == 1) &&
854                         (stv0367_readbits(state, F367TER_TPS_HPCODE) != 0)) {
855                 stv0367_writereg(state, R367TER_SFDLYSETH, 0xc0);
856                 stv0367_writereg(state, R367TER_SFDLYSETM, 0x60);
857                 stv0367_writereg(state, R367TER_SFDLYSETL, 0x0);
858         } else
859                 stv0367_writereg(state, R367TER_SFDLYSETH, 0x0);
860
861         wd = stv0367ter_duration(mode, 125, 500, 250);
862         u_var4 = stv0367_readbits(state, F367TER_TSFIFO_LINEOK);
863
864         while ((!u_var4) && (wd >= 0)) {
865                 usleep_range(1000 * tempo, 1000 * (tempo + 1));
866                 wd -= tempo;
867                 u_var4 = stv0367_readbits(state, F367TER_TSFIFO_LINEOK);
868         }
869
870         if (!u_var4)
871                 return FE_TER_NOLOCK;
872
873         /* for 367 leave COM_N at 0x7 for IQ_mode*/
874         /*if(ter_state->if_iq_mode!=FE_TER_NORMAL_IF_TUNER) {
875                 tempo=0;
876                 while ((stv0367_readbits(state,F367TER_COM_USEGAINTRK)!=1) &&
877                 (stv0367_readbits(state,F367TER_COM_AGCLOCK)!=1)&&(tempo<100)) {
878                         ChipWaitOrAbort(state,1);
879                         tempo+=1;
880                 }
881
882                 stv0367_writebits(state,F367TER_COM_N,0x17);
883         } */
884
885         stv0367_writebits(state, F367TER_SYR_TR_DIS, 1);
886
887         dprintk("FE_TER_LOCKOK !!!\n");
888
889         return  FE_TER_LOCKOK;
890
891 }
892
893 static void stv0367ter_set_ts_mode(struct stv0367_state *state,
894                                         enum stv0367_ts_mode PathTS)
895 {
896
897         dprintk("%s:\n", __func__);
898
899         if (state == NULL)
900                 return;
901
902         stv0367_writebits(state, F367TER_TS_DIS, 0);
903         switch (PathTS) {
904         default:
905                 /*for removing warning :default we can assume in parallel mode*/
906         case STV0367_PARALLEL_PUNCT_CLOCK:
907                 stv0367_writebits(state, F367TER_TSFIFO_SERIAL, 0);
908                 stv0367_writebits(state, F367TER_TSFIFO_DVBCI, 0);
909                 break;
910         case STV0367_SERIAL_PUNCT_CLOCK:
911                 stv0367_writebits(state, F367TER_TSFIFO_SERIAL, 1);
912                 stv0367_writebits(state, F367TER_TSFIFO_DVBCI, 1);
913                 break;
914         }
915 }
916
917 static void stv0367ter_set_clk_pol(struct stv0367_state *state,
918                                         enum stv0367_clk_pol clock)
919 {
920
921         dprintk("%s:\n", __func__);
922
923         if (state == NULL)
924                 return;
925
926         switch (clock) {
927         case STV0367_RISINGEDGE_CLOCK:
928                 stv0367_writebits(state, F367TER_TS_BYTE_CLK_INV, 1);
929                 break;
930         case STV0367_FALLINGEDGE_CLOCK:
931                 stv0367_writebits(state, F367TER_TS_BYTE_CLK_INV, 0);
932                 break;
933                 /*case FE_TER_CLOCK_POLARITY_DEFAULT:*/
934         default:
935                 stv0367_writebits(state, F367TER_TS_BYTE_CLK_INV, 0);
936                 break;
937         }
938 }
939
940 #if 0
941 static void stv0367ter_core_sw(struct stv0367_state *state)
942 {
943
944         dprintk("%s:\n", __func__);
945
946         stv0367_writebits(state, F367TER_CORE_ACTIVE, 0);
947         stv0367_writebits(state, F367TER_CORE_ACTIVE, 1);
948         msleep(350);
949 }
950 #endif
951 static int stv0367ter_standby(struct dvb_frontend *fe, u8 standby_on)
952 {
953         struct stv0367_state *state = fe->demodulator_priv;
954
955         dprintk("%s:\n", __func__);
956
957         if (standby_on) {
958                 stv0367_writebits(state, F367TER_STDBY, 1);
959                 stv0367_writebits(state, F367TER_STDBY_FEC, 1);
960                 stv0367_writebits(state, F367TER_STDBY_CORE, 1);
961         } else {
962                 stv0367_writebits(state, F367TER_STDBY, 0);
963                 stv0367_writebits(state, F367TER_STDBY_FEC, 0);
964                 stv0367_writebits(state, F367TER_STDBY_CORE, 0);
965         }
966
967         return 0;
968 }
969
970 static int stv0367ter_sleep(struct dvb_frontend *fe)
971 {
972         return stv0367ter_standby(fe, 1);
973 }
974
975 static int stv0367ter_init(struct dvb_frontend *fe)
976 {
977         struct stv0367_state *state = fe->demodulator_priv;
978         struct stv0367ter_state *ter_state = state->ter_state;
979
980         dprintk("%s:\n", __func__);
981
982         ter_state->pBER = 0;
983
984         stv0367_write_table(state,
985                 stv0367_deftabs[state->deftabs][STV0367_TAB_TER]);
986
987         stv0367_pll_setup(state, STV0367_ICSPEED_53125, state->config->xtal);
988
989         stv0367_writereg(state, R367TER_I2CRPT, 0xa0);
990         stv0367_writereg(state, R367TER_ANACTRL, 0x00);
991
992         /*Set TS1 and TS2 to serial or parallel mode */
993         stv0367ter_set_ts_mode(state, state->config->ts_mode);
994         stv0367ter_set_clk_pol(state, state->config->clk_pol);
995
996         state->chip_id = stv0367_readreg(state, R367TER_ID);
997         ter_state->first_lock = 0;
998         ter_state->unlock_counter = 2;
999
1000         return 0;
1001 }
1002
1003 static int stv0367ter_algo(struct dvb_frontend *fe)
1004 {
1005         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
1006         struct stv0367_state *state = fe->demodulator_priv;
1007         struct stv0367ter_state *ter_state = state->ter_state;
1008         int offset = 0, tempo = 0;
1009         u8 u_var;
1010         u8 /*constell,*/ counter;
1011         s8 step;
1012         s32 timing_offset = 0;
1013         u32 trl_nomrate = 0, InternalFreq = 0, temp = 0, ifkhz = 0;
1014
1015         dprintk("%s:\n", __func__);
1016
1017         stv0367_get_if_khz(state, &ifkhz);
1018
1019         ter_state->frequency = p->frequency;
1020         ter_state->force = FE_TER_FORCENONE
1021                         + stv0367_readbits(state, F367TER_FORCE) * 2;
1022         ter_state->if_iq_mode = state->config->if_iq_mode;
1023         switch (state->config->if_iq_mode) {
1024         case FE_TER_NORMAL_IF_TUNER:  /* Normal IF mode */
1025                 dprintk("ALGO: FE_TER_NORMAL_IF_TUNER selected\n");
1026                 stv0367_writebits(state, F367TER_TUNER_BB, 0);
1027                 stv0367_writebits(state, F367TER_LONGPATH_IF, 0);
1028                 stv0367_writebits(state, F367TER_DEMUX_SWAP, 0);
1029                 break;
1030         case FE_TER_LONGPATH_IF_TUNER:  /* Long IF mode */
1031                 dprintk("ALGO: FE_TER_LONGPATH_IF_TUNER selected\n");
1032                 stv0367_writebits(state, F367TER_TUNER_BB, 0);
1033                 stv0367_writebits(state, F367TER_LONGPATH_IF, 1);
1034                 stv0367_writebits(state, F367TER_DEMUX_SWAP, 1);
1035                 break;
1036         case FE_TER_IQ_TUNER:  /* IQ mode */
1037                 dprintk("ALGO: FE_TER_IQ_TUNER selected\n");
1038                 stv0367_writebits(state, F367TER_TUNER_BB, 1);
1039                 stv0367_writebits(state, F367TER_PPM_INVSEL, 0);
1040                 break;
1041         default:
1042                 printk(KERN_ERR "ALGO: wrong TUNER type selected\n");
1043                 return -EINVAL;
1044         }
1045
1046         usleep_range(5000, 7000);
1047
1048         switch (p->inversion) {
1049         case INVERSION_AUTO:
1050         default:
1051                 dprintk("%s: inversion AUTO\n", __func__);
1052                 if (ter_state->if_iq_mode == FE_TER_IQ_TUNER)
1053                         stv0367_writebits(state, F367TER_IQ_INVERT,
1054                                                 ter_state->sense);
1055                 else
1056                         stv0367_writebits(state, F367TER_INV_SPECTR,
1057                                                 ter_state->sense);
1058
1059                 break;
1060         case INVERSION_ON:
1061         case INVERSION_OFF:
1062                 if (ter_state->if_iq_mode == FE_TER_IQ_TUNER)
1063                         stv0367_writebits(state, F367TER_IQ_INVERT,
1064                                                 p->inversion);
1065                 else
1066                         stv0367_writebits(state, F367TER_INV_SPECTR,
1067                                                 p->inversion);
1068
1069                 break;
1070         }
1071
1072         if ((ter_state->if_iq_mode != FE_TER_NORMAL_IF_TUNER) &&
1073                                 (ter_state->pBW != ter_state->bw)) {
1074                 stv0367ter_agc_iir_lock_detect_set(state);
1075
1076                 /*set fine agc target to 180 for LPIF or IQ mode*/
1077                 /* set Q_AGCTarget */
1078                 stv0367_writebits(state, F367TER_SEL_IQNTAR, 1);
1079                 stv0367_writebits(state, F367TER_AUT_AGC_TARGET_MSB, 0xB);
1080                 /*stv0367_writebits(state,AUT_AGC_TARGET_LSB,0x04); */
1081
1082                 /* set Q_AGCTarget */
1083                 stv0367_writebits(state, F367TER_SEL_IQNTAR, 0);
1084                 stv0367_writebits(state, F367TER_AUT_AGC_TARGET_MSB, 0xB);
1085                 /*stv0367_writebits(state,AUT_AGC_TARGET_LSB,0x04); */
1086
1087                 if (!stv0367_iir_filt_init(state, ter_state->bw,
1088                                                 state->config->xtal))
1089                         return -EINVAL;
1090                 /*set IIR filter once for 6,7 or 8MHz BW*/
1091                 ter_state->pBW = ter_state->bw;
1092
1093                 stv0367ter_agc_iir_rst(state);
1094         }
1095
1096         if (ter_state->hierarchy == FE_TER_HIER_LOW_PRIO)
1097                 stv0367_writebits(state, F367TER_BDI_LPSEL, 0x01);
1098         else
1099                 stv0367_writebits(state, F367TER_BDI_LPSEL, 0x00);
1100
1101         InternalFreq = stv0367ter_get_mclk(state, state->config->xtal) / 1000;
1102         temp = (int)
1103                 ((((ter_state->bw * 64 * (1 << 15) * 100)
1104                                                 / (InternalFreq)) * 10) / 7);
1105
1106         stv0367_writebits(state, F367TER_TRL_NOMRATE_LSB, temp % 2);
1107         temp = temp / 2;
1108         stv0367_writebits(state, F367TER_TRL_NOMRATE_HI, temp / 256);
1109         stv0367_writebits(state, F367TER_TRL_NOMRATE_LO, temp % 256);
1110
1111         temp = stv0367_readbits(state, F367TER_TRL_NOMRATE_HI) * 512 +
1112                         stv0367_readbits(state, F367TER_TRL_NOMRATE_LO) * 2 +
1113                         stv0367_readbits(state, F367TER_TRL_NOMRATE_LSB);
1114         temp = (int)(((1 << 17) * ter_state->bw * 1000) / (7 * (InternalFreq)));
1115         stv0367_writebits(state, F367TER_GAIN_SRC_HI, temp / 256);
1116         stv0367_writebits(state, F367TER_GAIN_SRC_LO, temp % 256);
1117         temp = stv0367_readbits(state, F367TER_GAIN_SRC_HI) * 256 +
1118                         stv0367_readbits(state, F367TER_GAIN_SRC_LO);
1119
1120         temp = (int)
1121                 ((InternalFreq - ifkhz) * (1 << 16) / (InternalFreq));
1122
1123         dprintk("DEROT temp=0x%x\n", temp);
1124         stv0367_writebits(state, F367TER_INC_DEROT_HI, temp / 256);
1125         stv0367_writebits(state, F367TER_INC_DEROT_LO, temp % 256);
1126
1127         ter_state->echo_pos = 0;
1128         ter_state->ucblocks = 0; /* liplianin */
1129         ter_state->pBER = 0; /* liplianin */
1130         stv0367_writebits(state, F367TER_LONG_ECHO, ter_state->echo_pos);
1131
1132         if (stv0367ter_lock_algo(state) != FE_TER_LOCKOK)
1133                 return 0;
1134
1135         ter_state->state = FE_TER_LOCKOK;
1136
1137         ter_state->mode = stv0367_readbits(state, F367TER_SYR_MODE);
1138         ter_state->guard = stv0367_readbits(state, F367TER_SYR_GUARD);
1139
1140         ter_state->first_lock = 1; /* we know sense now :) */
1141
1142         ter_state->agc_val =
1143                         (stv0367_readbits(state, F367TER_AGC1_VAL_LO) << 16) +
1144                         (stv0367_readbits(state, F367TER_AGC1_VAL_HI) << 24) +
1145                         stv0367_readbits(state, F367TER_AGC2_VAL_LO) +
1146                         (stv0367_readbits(state, F367TER_AGC2_VAL_HI) << 8);
1147
1148         /* Carrier offset calculation */
1149         stv0367_writebits(state, F367TER_FREEZE, 1);
1150         offset = (stv0367_readbits(state, F367TER_CRL_FOFFSET_VHI) << 16) ;
1151         offset += (stv0367_readbits(state, F367TER_CRL_FOFFSET_HI) << 8);
1152         offset += (stv0367_readbits(state, F367TER_CRL_FOFFSET_LO));
1153         stv0367_writebits(state, F367TER_FREEZE, 0);
1154         if (offset > 8388607)
1155                 offset -= 16777216;
1156
1157         offset = offset * 2 / 16384;
1158
1159         if (ter_state->mode == FE_TER_MODE_2K)
1160                 offset = (offset * 4464) / 1000;/*** 1 FFT BIN=4.464khz***/
1161         else if (ter_state->mode == FE_TER_MODE_4K)
1162                 offset = (offset * 223) / 100;/*** 1 FFT BIN=2.23khz***/
1163         else  if (ter_state->mode == FE_TER_MODE_8K)
1164                 offset = (offset * 111) / 100;/*** 1 FFT BIN=1.1khz***/
1165
1166         if (stv0367_readbits(state, F367TER_PPM_INVSEL) == 1) {
1167                 if ((stv0367_readbits(state, F367TER_INV_SPECTR) ==
1168                                 (stv0367_readbits(state,
1169                                         F367TER_STATUS_INV_SPECRUM) == 1)))
1170                         offset = offset * -1;
1171         }
1172
1173         if (ter_state->bw == 6)
1174                 offset = (offset * 6) / 8;
1175         else if (ter_state->bw == 7)
1176                 offset = (offset * 7) / 8;
1177
1178         ter_state->frequency += offset;
1179
1180         tempo = 10;  /* exit even if timing_offset stays null */
1181         while ((timing_offset == 0) && (tempo > 0)) {
1182                 usleep_range(10000, 20000);     /*was 20ms  */
1183                 /* fine tuning of timing offset if required */
1184                 timing_offset = stv0367_readbits(state, F367TER_TRL_TOFFSET_LO)
1185                                 + 256 * stv0367_readbits(state,
1186                                                         F367TER_TRL_TOFFSET_HI);
1187                 if (timing_offset >= 32768)
1188                         timing_offset -= 65536;
1189                 trl_nomrate = (512 * stv0367_readbits(state,
1190                                                         F367TER_TRL_NOMRATE_HI)
1191                         + stv0367_readbits(state, F367TER_TRL_NOMRATE_LO) * 2
1192                         + stv0367_readbits(state, F367TER_TRL_NOMRATE_LSB));
1193
1194                 timing_offset = ((signed)(1000000 / trl_nomrate) *
1195                                                         timing_offset) / 2048;
1196                 tempo--;
1197         }
1198
1199         if (timing_offset <= 0) {
1200                 timing_offset = (timing_offset - 11) / 22;
1201                 step = -1;
1202         } else {
1203                 timing_offset = (timing_offset + 11) / 22;
1204                 step = 1;
1205         }
1206
1207         for (counter = 0; counter < abs(timing_offset); counter++) {
1208                 trl_nomrate += step;
1209                 stv0367_writebits(state, F367TER_TRL_NOMRATE_LSB,
1210                                                 trl_nomrate % 2);
1211                 stv0367_writebits(state, F367TER_TRL_NOMRATE_LO,
1212                                                 trl_nomrate / 2);
1213                 usleep_range(1000, 2000);
1214         }
1215
1216         usleep_range(5000, 6000);
1217         /* unlocks could happen in case of trl centring big step,
1218         then a core off/on restarts demod */
1219         u_var = stv0367_readbits(state, F367TER_LK);
1220
1221         if (!u_var) {
1222                 stv0367_writebits(state, F367TER_CORE_ACTIVE, 0);
1223                 msleep(20);
1224                 stv0367_writebits(state, F367TER_CORE_ACTIVE, 1);
1225         }
1226
1227         return 0;
1228 }
1229
1230 static int stv0367ter_set_frontend(struct dvb_frontend *fe)
1231 {
1232         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
1233         struct stv0367_state *state = fe->demodulator_priv;
1234         struct stv0367ter_state *ter_state = state->ter_state;
1235
1236         /*u8 trials[2]; */
1237         s8 num_trials, index;
1238         u8 SenseTrials[] = { INVERSION_ON, INVERSION_OFF };
1239
1240         if (state->reinit_on_setfrontend)
1241                 stv0367ter_init(fe);
1242
1243         if (fe->ops.tuner_ops.set_params) {
1244                 if (state->use_i2c_gatectrl && fe->ops.i2c_gate_ctrl)
1245                         fe->ops.i2c_gate_ctrl(fe, 1);
1246                 fe->ops.tuner_ops.set_params(fe);
1247                 if (state->use_i2c_gatectrl && fe->ops.i2c_gate_ctrl)
1248                         fe->ops.i2c_gate_ctrl(fe, 0);
1249         }
1250
1251         switch (p->transmission_mode) {
1252         default:
1253         case TRANSMISSION_MODE_AUTO:
1254         case TRANSMISSION_MODE_2K:
1255                 ter_state->mode = FE_TER_MODE_2K;
1256                 break;
1257 /*      case TRANSMISSION_MODE_4K:
1258                 pLook.mode = FE_TER_MODE_4K;
1259                 break;*/
1260         case TRANSMISSION_MODE_8K:
1261                 ter_state->mode = FE_TER_MODE_8K;
1262                 break;
1263         }
1264
1265         switch (p->guard_interval) {
1266         default:
1267         case GUARD_INTERVAL_1_32:
1268         case GUARD_INTERVAL_1_16:
1269         case GUARD_INTERVAL_1_8:
1270         case GUARD_INTERVAL_1_4:
1271                 ter_state->guard = p->guard_interval;
1272                 break;
1273         case GUARD_INTERVAL_AUTO:
1274                 ter_state->guard = GUARD_INTERVAL_1_32;
1275                 break;
1276         }
1277
1278         switch (p->bandwidth_hz) {
1279         case 6000000:
1280                 ter_state->bw = FE_TER_CHAN_BW_6M;
1281                 break;
1282         case 7000000:
1283                 ter_state->bw = FE_TER_CHAN_BW_7M;
1284                 break;
1285         case 8000000:
1286         default:
1287                 ter_state->bw = FE_TER_CHAN_BW_8M;
1288         }
1289
1290         ter_state->hierarchy = FE_TER_HIER_NONE;
1291
1292         switch (p->inversion) {
1293         case INVERSION_OFF:
1294         case INVERSION_ON:
1295                 num_trials = 1;
1296                 break;
1297         default:
1298                 num_trials = 2;
1299                 if (ter_state->first_lock)
1300                         num_trials = 1;
1301                 break;
1302         }
1303
1304         ter_state->state = FE_TER_NOLOCK;
1305         index = 0;
1306
1307         while (((index) < num_trials) && (ter_state->state != FE_TER_LOCKOK)) {
1308                 if (!ter_state->first_lock) {
1309                         if (p->inversion == INVERSION_AUTO)
1310                                 ter_state->sense = SenseTrials[index];
1311
1312                 }
1313                 stv0367ter_algo(fe);
1314
1315                 if ((ter_state->state == FE_TER_LOCKOK) &&
1316                                 (p->inversion == INVERSION_AUTO) &&
1317                                                                 (index == 1)) {
1318                         /* invert spectrum sense */
1319                         SenseTrials[index] = SenseTrials[0];
1320                         SenseTrials[(index + 1) % 2] = (SenseTrials[1] + 1) % 2;
1321                 }
1322
1323                 index++;
1324         }
1325
1326         return 0;
1327 }
1328
1329 static int stv0367ter_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
1330 {
1331         struct stv0367_state *state = fe->demodulator_priv;
1332         struct stv0367ter_state *ter_state = state->ter_state;
1333         u32 errs = 0;
1334
1335         /*wait for counting completion*/
1336         if (stv0367_readbits(state, F367TER_SFERRC_OLDVALUE) == 0) {
1337                 errs =
1338                         ((u32)stv0367_readbits(state, F367TER_ERR_CNT1)
1339                         * (1 << 16))
1340                         + ((u32)stv0367_readbits(state, F367TER_ERR_CNT1_HI)
1341                         * (1 << 8))
1342                         + ((u32)stv0367_readbits(state, F367TER_ERR_CNT1_LO));
1343                 ter_state->ucblocks = errs;
1344         }
1345
1346         (*ucblocks) = ter_state->ucblocks;
1347
1348         return 0;
1349 }
1350
1351 static int stv0367ter_get_frontend(struct dvb_frontend *fe,
1352                                    struct dtv_frontend_properties *p)
1353 {
1354         struct stv0367_state *state = fe->demodulator_priv;
1355         struct stv0367ter_state *ter_state = state->ter_state;
1356         enum stv0367_ter_mode mode;
1357         int constell = 0,/* snr = 0,*/ Data = 0;
1358
1359         p->frequency = stv0367_get_tuner_freq(fe);
1360         if ((int)p->frequency < 0)
1361                 p->frequency = -p->frequency;
1362
1363         constell = stv0367_readbits(state, F367TER_TPS_CONST);
1364         if (constell == 0)
1365                 p->modulation = QPSK;
1366         else if (constell == 1)
1367                 p->modulation = QAM_16;
1368         else
1369                 p->modulation = QAM_64;
1370
1371         p->inversion = stv0367_readbits(state, F367TER_INV_SPECTR);
1372
1373         /* Get the Hierarchical mode */
1374         Data = stv0367_readbits(state, F367TER_TPS_HIERMODE);
1375
1376         switch (Data) {
1377         case 0:
1378                 p->hierarchy = HIERARCHY_NONE;
1379                 break;
1380         case 1:
1381                 p->hierarchy = HIERARCHY_1;
1382                 break;
1383         case 2:
1384                 p->hierarchy = HIERARCHY_2;
1385                 break;
1386         case 3:
1387                 p->hierarchy = HIERARCHY_4;
1388                 break;
1389         default:
1390                 p->hierarchy = HIERARCHY_AUTO;
1391                 break; /* error */
1392         }
1393
1394         /* Get the FEC Rate */
1395         if (ter_state->hierarchy == FE_TER_HIER_LOW_PRIO)
1396                 Data = stv0367_readbits(state, F367TER_TPS_LPCODE);
1397         else
1398                 Data = stv0367_readbits(state, F367TER_TPS_HPCODE);
1399
1400         switch (Data) {
1401         case 0:
1402                 p->code_rate_HP = FEC_1_2;
1403                 break;
1404         case 1:
1405                 p->code_rate_HP = FEC_2_3;
1406                 break;
1407         case 2:
1408                 p->code_rate_HP = FEC_3_4;
1409                 break;
1410         case 3:
1411                 p->code_rate_HP = FEC_5_6;
1412                 break;
1413         case 4:
1414                 p->code_rate_HP = FEC_7_8;
1415                 break;
1416         default:
1417                 p->code_rate_HP = FEC_AUTO;
1418                 break; /* error */
1419         }
1420
1421         mode = stv0367_readbits(state, F367TER_SYR_MODE);
1422
1423         switch (mode) {
1424         case FE_TER_MODE_2K:
1425                 p->transmission_mode = TRANSMISSION_MODE_2K;
1426                 break;
1427 /*      case FE_TER_MODE_4K:
1428                 p->transmission_mode = TRANSMISSION_MODE_4K;
1429                 break;*/
1430         case FE_TER_MODE_8K:
1431                 p->transmission_mode = TRANSMISSION_MODE_8K;
1432                 break;
1433         default:
1434                 p->transmission_mode = TRANSMISSION_MODE_AUTO;
1435         }
1436
1437         p->guard_interval = stv0367_readbits(state, F367TER_SYR_GUARD);
1438
1439         return 0;
1440 }
1441
1442 static u32 stv0367ter_snr_readreg(struct dvb_frontend *fe)
1443 {
1444         struct stv0367_state *state = fe->demodulator_priv;
1445         u32 snru32 = 0;
1446         int cpt = 0;
1447         u8 cut = stv0367_readbits(state, F367TER_IDENTIFICATIONREG);
1448
1449         while (cpt < 10) {
1450                 usleep_range(2000, 3000);
1451                 if (cut == 0x50) /*cut 1.0 cut 1.1*/
1452                         snru32 += stv0367_readbits(state, F367TER_CHCSNR) / 4;
1453                 else /*cu2.0*/
1454                         snru32 += 125 * stv0367_readbits(state, F367TER_CHCSNR);
1455
1456                 cpt++;
1457         }
1458         snru32 /= 10;/*average on 10 values*/
1459
1460         return snru32;
1461 }
1462
1463 static int stv0367ter_read_snr(struct dvb_frontend *fe, u16 *snr)
1464 {
1465         u32 snrval = stv0367ter_snr_readreg(fe);
1466
1467         *snr = snrval / 1000;
1468
1469         return 0;
1470 }
1471
1472 #if 0
1473 static int stv0367ter_status(struct dvb_frontend *fe)
1474 {
1475
1476         struct stv0367_state *state = fe->demodulator_priv;
1477         struct stv0367ter_state *ter_state = state->ter_state;
1478         int locked = FALSE;
1479
1480         locked = (stv0367_readbits(state, F367TER_LK));
1481         if (!locked)
1482                 ter_state->unlock_counter += 1;
1483         else
1484                 ter_state->unlock_counter = 0;
1485
1486         if (ter_state->unlock_counter > 2) {
1487                 if (!stv0367_readbits(state, F367TER_TPS_LOCK) ||
1488                                 (!stv0367_readbits(state, F367TER_LK))) {
1489                         stv0367_writebits(state, F367TER_CORE_ACTIVE, 0);
1490                         usleep_range(2000, 3000);
1491                         stv0367_writebits(state, F367TER_CORE_ACTIVE, 1);
1492                         msleep(350);
1493                         locked = (stv0367_readbits(state, F367TER_TPS_LOCK)) &&
1494                                         (stv0367_readbits(state, F367TER_LK));
1495                 }
1496
1497         }
1498
1499         return locked;
1500 }
1501 #endif
1502 static int stv0367ter_read_status(struct dvb_frontend *fe,
1503                                   enum fe_status *status)
1504 {
1505         struct stv0367_state *state = fe->demodulator_priv;
1506
1507         dprintk("%s:\n", __func__);
1508
1509         *status = 0;
1510
1511         if (stv0367_readbits(state, F367TER_LK)) {
1512                 *status = FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI
1513                           | FE_HAS_SYNC | FE_HAS_LOCK;
1514                 dprintk("%s: stv0367 has locked\n", __func__);
1515         }
1516
1517         return 0;
1518 }
1519
1520 static int stv0367ter_read_ber(struct dvb_frontend *fe, u32 *ber)
1521 {
1522         struct stv0367_state *state = fe->demodulator_priv;
1523         struct stv0367ter_state *ter_state = state->ter_state;
1524         u32 Errors = 0, tber = 0, temporary = 0;
1525         int abc = 0, def = 0;
1526
1527
1528         /*wait for counting completion*/
1529         if (stv0367_readbits(state, F367TER_SFERRC_OLDVALUE) == 0)
1530                 Errors = ((u32)stv0367_readbits(state, F367TER_SFEC_ERR_CNT)
1531                         * (1 << 16))
1532                         + ((u32)stv0367_readbits(state, F367TER_SFEC_ERR_CNT_HI)
1533                         * (1 << 8))
1534                         + ((u32)stv0367_readbits(state,
1535                                                 F367TER_SFEC_ERR_CNT_LO));
1536         /*measurement not completed, load previous value*/
1537         else {
1538                 tber = ter_state->pBER;
1539                 return 0;
1540         }
1541
1542         abc = stv0367_readbits(state, F367TER_SFEC_ERR_SOURCE);
1543         def = stv0367_readbits(state, F367TER_SFEC_NUM_EVENT);
1544
1545         if (Errors == 0) {
1546                 tber = 0;
1547         } else if (abc == 0x7) {
1548                 if (Errors <= 4) {
1549                         temporary = (Errors * 1000000000) / (8 * (1 << 14));
1550                         temporary =  temporary;
1551                 } else if (Errors <= 42) {
1552                         temporary = (Errors * 100000000) / (8 * (1 << 14));
1553                         temporary = temporary * 10;
1554                 } else if (Errors <= 429) {
1555                         temporary = (Errors * 10000000) / (8 * (1 << 14));
1556                         temporary = temporary * 100;
1557                 } else if (Errors <= 4294) {
1558                         temporary = (Errors * 1000000) / (8 * (1 << 14));
1559                         temporary = temporary * 1000;
1560                 } else if (Errors <= 42949) {
1561                         temporary = (Errors * 100000) / (8 * (1 << 14));
1562                         temporary = temporary * 10000;
1563                 } else if (Errors <= 429496) {
1564                         temporary = (Errors * 10000) / (8 * (1 << 14));
1565                         temporary = temporary * 100000;
1566                 } else { /*if (Errors<4294967) 2^22 max error*/
1567                         temporary = (Errors * 1000) / (8 * (1 << 14));
1568                         temporary = temporary * 100000; /* still to *10 */
1569                 }
1570
1571                 /* Byte error*/
1572                 if (def == 2)
1573                         /*tber=Errors/(8*(1 <<14));*/
1574                         tber = temporary;
1575                 else if (def == 3)
1576                         /*tber=Errors/(8*(1 <<16));*/
1577                         tber = temporary / 4;
1578                 else if (def == 4)
1579                         /*tber=Errors/(8*(1 <<18));*/
1580                         tber = temporary / 16;
1581                 else if (def == 5)
1582                         /*tber=Errors/(8*(1 <<20));*/
1583                         tber = temporary / 64;
1584                 else if (def == 6)
1585                         /*tber=Errors/(8*(1 <<22));*/
1586                         tber = temporary / 256;
1587                 else
1588                         /* should not pass here*/
1589                         tber = 0;
1590
1591                 if ((Errors < 4294967) && (Errors > 429496))
1592                         tber *= 10;
1593
1594         }
1595
1596         /* save actual value */
1597         ter_state->pBER = tber;
1598
1599         (*ber) = tber;
1600
1601         return 0;
1602 }
1603 #if 0
1604 static u32 stv0367ter_get_per(struct stv0367_state *state)
1605 {
1606         struct stv0367ter_state *ter_state = state->ter_state;
1607         u32 Errors = 0, Per = 0, temporary = 0;
1608         int abc = 0, def = 0, cpt = 0;
1609
1610         while (((stv0367_readbits(state, F367TER_SFERRC_OLDVALUE) == 1) &&
1611                         (cpt < 400)) || ((Errors == 0) && (cpt < 400))) {
1612                 usleep_range(1000, 2000);
1613                 Errors = ((u32)stv0367_readbits(state, F367TER_ERR_CNT1)
1614                         * (1 << 16))
1615                         + ((u32)stv0367_readbits(state, F367TER_ERR_CNT1_HI)
1616                         * (1 << 8))
1617                         + ((u32)stv0367_readbits(state, F367TER_ERR_CNT1_LO));
1618                 cpt++;
1619         }
1620         abc = stv0367_readbits(state, F367TER_ERR_SRC1);
1621         def = stv0367_readbits(state, F367TER_NUM_EVT1);
1622
1623         if (Errors == 0)
1624                 Per = 0;
1625         else if (abc == 0x9) {
1626                 if (Errors <= 4) {
1627                         temporary = (Errors * 1000000000) / (8 * (1 << 8));
1628                         temporary =  temporary;
1629                 } else if (Errors <= 42) {
1630                         temporary = (Errors * 100000000) / (8 * (1 << 8));
1631                         temporary = temporary * 10;
1632                 } else if (Errors <= 429) {
1633                         temporary = (Errors * 10000000) / (8 * (1 << 8));
1634                         temporary = temporary * 100;
1635                 } else if (Errors <= 4294) {
1636                         temporary = (Errors * 1000000) / (8 * (1 << 8));
1637                         temporary = temporary * 1000;
1638                 } else if (Errors <= 42949) {
1639                         temporary = (Errors * 100000) / (8 * (1 << 8));
1640                         temporary = temporary * 10000;
1641                 } else { /*if(Errors<=429496)  2^16 errors max*/
1642                         temporary = (Errors * 10000) / (8 * (1 << 8));
1643                         temporary = temporary * 100000;
1644                 }
1645
1646                 /* pkt error*/
1647                 if (def == 2)
1648                         /*Per=Errors/(1 << 8);*/
1649                         Per = temporary;
1650                 else if (def == 3)
1651                         /*Per=Errors/(1 << 10);*/
1652                         Per = temporary / 4;
1653                 else if (def == 4)
1654                         /*Per=Errors/(1 << 12);*/
1655                         Per = temporary / 16;
1656                 else if (def == 5)
1657                         /*Per=Errors/(1 << 14);*/
1658                         Per = temporary / 64;
1659                 else if (def == 6)
1660                         /*Per=Errors/(1 << 16);*/
1661                         Per = temporary / 256;
1662                 else
1663                         Per = 0;
1664
1665         }
1666         /* save actual value */
1667         ter_state->pPER = Per;
1668
1669         return Per;
1670 }
1671 #endif
1672 static int stv0367_get_tune_settings(struct dvb_frontend *fe,
1673                                         struct dvb_frontend_tune_settings
1674                                         *fe_tune_settings)
1675 {
1676         fe_tune_settings->min_delay_ms = 1000;
1677         fe_tune_settings->step_size = 0;
1678         fe_tune_settings->max_drift = 0;
1679
1680         return 0;
1681 }
1682
1683 static void stv0367_release(struct dvb_frontend *fe)
1684 {
1685         struct stv0367_state *state = fe->demodulator_priv;
1686
1687         kfree(state->ter_state);
1688         kfree(state->cab_state);
1689         kfree(state);
1690 }
1691
1692 static const struct dvb_frontend_ops stv0367ter_ops = {
1693         .delsys = { SYS_DVBT },
1694         .info = {
1695                 .name                   = "ST STV0367 DVB-T",
1696                 .frequency_min          = 47000000,
1697                 .frequency_max          = 862000000,
1698                 .frequency_stepsize     = 15625,
1699                 .frequency_tolerance    = 0,
1700                 .caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 |
1701                         FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 |
1702                         FE_CAN_FEC_AUTO |
1703                         FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 |
1704                         FE_CAN_QAM_128 | FE_CAN_QAM_256 | FE_CAN_QAM_AUTO |
1705                         FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_RECOVER |
1706                         FE_CAN_INVERSION_AUTO |
1707                         FE_CAN_MUTE_TS
1708         },
1709         .release = stv0367_release,
1710         .init = stv0367ter_init,
1711         .sleep = stv0367ter_sleep,
1712         .i2c_gate_ctrl = stv0367ter_gate_ctrl,
1713         .set_frontend = stv0367ter_set_frontend,
1714         .get_frontend = stv0367ter_get_frontend,
1715         .get_tune_settings = stv0367_get_tune_settings,
1716         .read_status = stv0367ter_read_status,
1717         .read_ber = stv0367ter_read_ber,/* too slow */
1718 /*      .read_signal_strength = stv0367_read_signal_strength,*/
1719         .read_snr = stv0367ter_read_snr,
1720         .read_ucblocks = stv0367ter_read_ucblocks,
1721 };
1722
1723 struct dvb_frontend *stv0367ter_attach(const struct stv0367_config *config,
1724                                    struct i2c_adapter *i2c)
1725 {
1726         struct stv0367_state *state = NULL;
1727         struct stv0367ter_state *ter_state = NULL;
1728
1729         /* allocate memory for the internal state */
1730         state = kzalloc(sizeof(struct stv0367_state), GFP_KERNEL);
1731         if (state == NULL)
1732                 goto error;
1733         ter_state = kzalloc(sizeof(struct stv0367ter_state), GFP_KERNEL);
1734         if (ter_state == NULL)
1735                 goto error;
1736
1737         /* setup the state */
1738         state->i2c = i2c;
1739         state->config = config;
1740         state->ter_state = ter_state;
1741         state->fe.ops = stv0367ter_ops;
1742         state->fe.demodulator_priv = state;
1743         state->chip_id = stv0367_readreg(state, 0xf000);
1744
1745         /* demod operation options */
1746         state->use_i2c_gatectrl = 1;
1747         state->deftabs = STV0367_DEFTAB_GENERIC;
1748         state->reinit_on_setfrontend = 1;
1749         state->auto_if_khz = 0;
1750
1751         dprintk("%s: chip_id = 0x%x\n", __func__, state->chip_id);
1752
1753         /* check if the demod is there */
1754         if ((state->chip_id != 0x50) && (state->chip_id != 0x60))
1755                 goto error;
1756
1757         return &state->fe;
1758
1759 error:
1760         kfree(ter_state);
1761         kfree(state);
1762         return NULL;
1763 }
1764 EXPORT_SYMBOL(stv0367ter_attach);
1765
1766 static int stv0367cab_gate_ctrl(struct dvb_frontend *fe, int enable)
1767 {
1768         struct stv0367_state *state = fe->demodulator_priv;
1769
1770         dprintk("%s:\n", __func__);
1771
1772         stv0367_writebits(state, F367CAB_I2CT_ON, (enable > 0) ? 1 : 0);
1773
1774         return 0;
1775 }
1776
1777 static u32 stv0367cab_get_mclk(struct dvb_frontend *fe, u32 ExtClk_Hz)
1778 {
1779         struct stv0367_state *state = fe->demodulator_priv;
1780         u32 mclk_Hz = 0;/* master clock frequency (Hz) */
1781         u32 M, N, P;
1782
1783
1784         if (stv0367_readbits(state, F367CAB_BYPASS_PLLXN) == 0) {
1785                 N = (u32)stv0367_readbits(state, F367CAB_PLL_NDIV);
1786                 if (N == 0)
1787                         N = N + 1;
1788
1789                 M = (u32)stv0367_readbits(state, F367CAB_PLL_MDIV);
1790                 if (M == 0)
1791                         M = M + 1;
1792
1793                 P = (u32)stv0367_readbits(state, F367CAB_PLL_PDIV);
1794
1795                 if (P > 5)
1796                         P = 5;
1797
1798                 mclk_Hz = ((ExtClk_Hz / 2) * N) / (M * (1 << P));
1799                 dprintk("stv0367cab_get_mclk BYPASS_PLLXN mclk_Hz=%d\n",
1800                                                                 mclk_Hz);
1801         } else
1802                 mclk_Hz = ExtClk_Hz;
1803
1804         dprintk("stv0367cab_get_mclk final mclk_Hz=%d\n", mclk_Hz);
1805
1806         return mclk_Hz;
1807 }
1808
1809 static u32 stv0367cab_get_adc_freq(struct dvb_frontend *fe, u32 ExtClk_Hz)
1810 {
1811         u32 ADCClk_Hz = ExtClk_Hz;
1812
1813         ADCClk_Hz = stv0367cab_get_mclk(fe, ExtClk_Hz);
1814
1815         return ADCClk_Hz;
1816 }
1817
1818 static enum stv0367cab_mod stv0367cab_SetQamSize(struct stv0367_state *state,
1819                                                  u32 SymbolRate,
1820                                                  enum stv0367cab_mod QAMSize)
1821 {
1822         /* Set QAM size */
1823         stv0367_writebits(state, F367CAB_QAM_MODE, QAMSize);
1824
1825         /* Set Registers settings specific to the QAM size */
1826         switch (QAMSize) {
1827         case FE_CAB_MOD_QAM4:
1828                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1829                 break;
1830         case FE_CAB_MOD_QAM16:
1831                 stv0367_writereg(state, R367CAB_AGC_PWR_REF_L, 0x64);
1832                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1833                 stv0367_writereg(state, R367CAB_FSM_STATE, 0x90);
1834                 stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1835                 stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa7);
1836                 stv0367_writereg(state, R367CAB_EQU_CRL_LD_SEN, 0x95);
1837                 stv0367_writereg(state, R367CAB_EQU_CRL_LIMITER, 0x40);
1838                 stv0367_writereg(state, R367CAB_EQU_PNT_GAIN, 0x8a);
1839                 break;
1840         case FE_CAB_MOD_QAM32:
1841                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1842                 stv0367_writereg(state, R367CAB_AGC_PWR_REF_L, 0x6e);
1843                 stv0367_writereg(state, R367CAB_FSM_STATE, 0xb0);
1844                 stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1845                 stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xb7);
1846                 stv0367_writereg(state, R367CAB_EQU_CRL_LD_SEN, 0x9d);
1847                 stv0367_writereg(state, R367CAB_EQU_CRL_LIMITER, 0x7f);
1848                 stv0367_writereg(state, R367CAB_EQU_PNT_GAIN, 0xa7);
1849                 break;
1850         case FE_CAB_MOD_QAM64:
1851                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x82);
1852                 stv0367_writereg(state, R367CAB_AGC_PWR_REF_L, 0x5a);
1853                 if (SymbolRate > 4500000) {
1854                         stv0367_writereg(state, R367CAB_FSM_STATE, 0xb0);
1855                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1856                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa5);
1857                 } else if (SymbolRate > 2500000) {
1858                         stv0367_writereg(state, R367CAB_FSM_STATE, 0xa0);
1859                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1860                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa6);
1861                 } else {
1862                         stv0367_writereg(state, R367CAB_FSM_STATE, 0xa0);
1863                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xd1);
1864                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa7);
1865                 }
1866                 stv0367_writereg(state, R367CAB_EQU_CRL_LD_SEN, 0x95);
1867                 stv0367_writereg(state, R367CAB_EQU_CRL_LIMITER, 0x40);
1868                 stv0367_writereg(state, R367CAB_EQU_PNT_GAIN, 0x99);
1869                 break;
1870         case FE_CAB_MOD_QAM128:
1871                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1872                 stv0367_writereg(state, R367CAB_AGC_PWR_REF_L, 0x76);
1873                 stv0367_writereg(state, R367CAB_FSM_STATE, 0x90);
1874                 stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xb1);
1875                 if (SymbolRate > 4500000)
1876                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa7);
1877                 else if (SymbolRate > 2500000)
1878                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa6);
1879                 else
1880                         stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0x97);
1881
1882                 stv0367_writereg(state, R367CAB_EQU_CRL_LD_SEN, 0x8e);
1883                 stv0367_writereg(state, R367CAB_EQU_CRL_LIMITER, 0x7f);
1884                 stv0367_writereg(state, R367CAB_EQU_PNT_GAIN, 0xa7);
1885                 break;
1886         case FE_CAB_MOD_QAM256:
1887                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x94);
1888                 stv0367_writereg(state, R367CAB_AGC_PWR_REF_L, 0x5a);
1889                 stv0367_writereg(state, R367CAB_FSM_STATE, 0xa0);
1890                 if (SymbolRate > 4500000)
1891                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1892                 else if (SymbolRate > 2500000)
1893                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xc1);
1894                 else
1895                         stv0367_writereg(state, R367CAB_EQU_CTR_LPF_GAIN, 0xd1);
1896
1897                 stv0367_writereg(state, R367CAB_EQU_CRL_LPF_GAIN, 0xa7);
1898                 stv0367_writereg(state, R367CAB_EQU_CRL_LD_SEN, 0x85);
1899                 stv0367_writereg(state, R367CAB_EQU_CRL_LIMITER, 0x40);
1900                 stv0367_writereg(state, R367CAB_EQU_PNT_GAIN, 0xa7);
1901                 break;
1902         case FE_CAB_MOD_QAM512:
1903                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1904                 break;
1905         case FE_CAB_MOD_QAM1024:
1906                 stv0367_writereg(state, R367CAB_IQDEM_ADJ_AGC_REF, 0x00);
1907                 break;
1908         default:
1909                 break;
1910         }
1911
1912         return QAMSize;
1913 }
1914
1915 static u32 stv0367cab_set_derot_freq(struct stv0367_state *state,
1916                                         u32 adc_hz, s32 derot_hz)
1917 {
1918         u32 sampled_if = 0;
1919         u32 adc_khz;
1920
1921         adc_khz = adc_hz / 1000;
1922
1923         dprintk("%s: adc_hz=%d derot_hz=%d\n", __func__, adc_hz, derot_hz);
1924
1925         if (adc_khz != 0) {
1926                 if (derot_hz < 1000000)
1927                         derot_hz = adc_hz / 4; /* ZIF operation */
1928                 if (derot_hz > adc_hz)
1929                         derot_hz = derot_hz - adc_hz;
1930                 sampled_if = (u32)derot_hz / 1000;
1931                 sampled_if *= 32768;
1932                 sampled_if /= adc_khz;
1933                 sampled_if *= 256;
1934         }
1935
1936         if (sampled_if > 8388607)
1937                 sampled_if = 8388607;
1938
1939         dprintk("%s: sampled_if=0x%x\n", __func__, sampled_if);
1940
1941         stv0367_writereg(state, R367CAB_MIX_NCO_LL, sampled_if);
1942         stv0367_writereg(state, R367CAB_MIX_NCO_HL, (sampled_if >> 8));
1943         stv0367_writebits(state, F367CAB_MIX_NCO_INC_HH, (sampled_if >> 16));
1944
1945         return derot_hz;
1946 }
1947
1948 static u32 stv0367cab_get_derot_freq(struct stv0367_state *state, u32 adc_hz)
1949 {
1950         u32 sampled_if;
1951
1952         sampled_if = stv0367_readbits(state, F367CAB_MIX_NCO_INC_LL) +
1953                         (stv0367_readbits(state, F367CAB_MIX_NCO_INC_HL) << 8) +
1954                         (stv0367_readbits(state, F367CAB_MIX_NCO_INC_HH) << 16);
1955
1956         sampled_if /= 256;
1957         sampled_if *= (adc_hz / 1000);
1958         sampled_if += 1;
1959         sampled_if /= 32768;
1960
1961         return sampled_if;
1962 }
1963
1964 static u32 stv0367cab_set_srate(struct stv0367_state *state, u32 adc_hz,
1965                         u32 mclk_hz, u32 SymbolRate,
1966                         enum stv0367cab_mod QAMSize)
1967 {
1968         u32 QamSizeCorr = 0;
1969         u32 u32_tmp = 0, u32_tmp1 = 0;
1970         u32 adp_khz;
1971
1972         dprintk("%s:\n", __func__);
1973
1974         /* Set Correction factor of SRC gain */
1975         switch (QAMSize) {
1976         case FE_CAB_MOD_QAM4:
1977                 QamSizeCorr = 1110;
1978                 break;
1979         case FE_CAB_MOD_QAM16:
1980                 QamSizeCorr = 1032;
1981                 break;
1982         case FE_CAB_MOD_QAM32:
1983                 QamSizeCorr =  954;
1984                 break;
1985         case FE_CAB_MOD_QAM64:
1986                 QamSizeCorr =  983;
1987                 break;
1988         case FE_CAB_MOD_QAM128:
1989                 QamSizeCorr =  957;
1990                 break;
1991         case FE_CAB_MOD_QAM256:
1992                 QamSizeCorr =  948;
1993                 break;
1994         case FE_CAB_MOD_QAM512:
1995                 QamSizeCorr =    0;
1996                 break;
1997         case FE_CAB_MOD_QAM1024:
1998                 QamSizeCorr =  944;
1999                 break;
2000         default:
2001                 break;
2002         }
2003
2004         /* Transfer ratio calculation */
2005         if (adc_hz != 0) {
2006                 u32_tmp = 256 * SymbolRate;
2007                 u32_tmp = u32_tmp / adc_hz;
2008         }
2009         stv0367_writereg(state, R367CAB_EQU_CRL_TFR, (u8)u32_tmp);
2010
2011         /* Symbol rate and SRC gain calculation */
2012         adp_khz = (mclk_hz >> 1) / 1000;/* TRL works at half the system clock */
2013         if (adp_khz != 0) {
2014                 u32_tmp = SymbolRate;
2015                 u32_tmp1 = SymbolRate;
2016
2017                 if (u32_tmp < 2097152) { /* 2097152 = 2^21 */
2018                         /* Symbol rate calculation */
2019                         u32_tmp *= 2048; /* 2048 = 2^11 */
2020                         u32_tmp = u32_tmp / adp_khz;
2021                         u32_tmp = u32_tmp * 16384; /* 16384 = 2^14 */
2022                         u32_tmp /= 125 ; /* 125 = 1000/2^3 */
2023                         u32_tmp = u32_tmp * 8; /* 8 = 2^3 */
2024
2025                         /* SRC Gain Calculation */
2026                         u32_tmp1 *= 2048; /* *2*2^10 */
2027                         u32_tmp1 /= 439; /* *2/878 */
2028                         u32_tmp1 *= 256; /* *2^8 */
2029                         u32_tmp1 = u32_tmp1 / adp_khz; /* /(AdpClk in kHz) */
2030                         u32_tmp1 *= QamSizeCorr * 9; /* *1000*corr factor */
2031                         u32_tmp1 = u32_tmp1 / 10000000;
2032
2033                 } else if (u32_tmp < 4194304) { /* 4194304 = 2**22 */
2034                         /* Symbol rate calculation */
2035                         u32_tmp *= 1024 ; /* 1024 = 2**10 */
2036                         u32_tmp = u32_tmp / adp_khz;
2037                         u32_tmp = u32_tmp * 16384; /* 16384 = 2**14 */
2038                         u32_tmp /= 125 ; /* 125 = 1000/2**3 */
2039                         u32_tmp = u32_tmp * 16; /* 16 = 2**4 */
2040
2041                         /* SRC Gain Calculation */
2042                         u32_tmp1 *= 1024; /* *2*2^9 */
2043                         u32_tmp1 /= 439; /* *2/878 */
2044                         u32_tmp1 *= 256; /* *2^8 */
2045                         u32_tmp1 = u32_tmp1 / adp_khz; /* /(AdpClk in kHz)*/
2046                         u32_tmp1 *= QamSizeCorr * 9; /* *1000*corr factor */
2047                         u32_tmp1 = u32_tmp1 / 5000000;
2048                 } else if (u32_tmp < 8388607) { /* 8388607 = 2**23 */
2049                         /* Symbol rate calculation */
2050                         u32_tmp *= 512 ; /* 512 = 2**9 */
2051                         u32_tmp = u32_tmp / adp_khz;
2052                         u32_tmp = u32_tmp * 16384; /* 16384 = 2**14 */
2053                         u32_tmp /= 125 ; /* 125 = 1000/2**3 */
2054                         u32_tmp = u32_tmp * 32; /* 32 = 2**5 */
2055
2056                         /* SRC Gain Calculation */
2057                         u32_tmp1 *= 512; /* *2*2^8 */
2058                         u32_tmp1 /= 439; /* *2/878 */
2059                         u32_tmp1 *= 256; /* *2^8 */
2060                         u32_tmp1 = u32_tmp1 / adp_khz; /* /(AdpClk in kHz) */
2061                         u32_tmp1 *= QamSizeCorr * 9; /* *1000*corr factor */
2062                         u32_tmp1 = u32_tmp1 / 2500000;
2063                 } else {
2064                         /* Symbol rate calculation */
2065                         u32_tmp *= 256 ; /* 256 = 2**8 */
2066                         u32_tmp = u32_tmp / adp_khz;
2067                         u32_tmp = u32_tmp * 16384; /* 16384 = 2**13 */
2068                         u32_tmp /= 125 ; /* 125 = 1000/2**3 */
2069                         u32_tmp = u32_tmp * 64; /* 64 = 2**6 */
2070
2071                         /* SRC Gain Calculation */
2072                         u32_tmp1 *= 256; /* 2*2^7 */
2073                         u32_tmp1 /= 439; /* *2/878 */
2074                         u32_tmp1 *= 256; /* *2^8 */
2075                         u32_tmp1 = u32_tmp1 / adp_khz; /* /(AdpClk in kHz) */
2076                         u32_tmp1 *= QamSizeCorr * 9; /* *1000*corr factor */
2077                         u32_tmp1 = u32_tmp1 / 1250000;
2078                 }
2079         }
2080 #if 0
2081         /* Filters' coefficients are calculated and written
2082         into registers only if the filters are enabled */
2083         if (stv0367_readbits(state, F367CAB_ADJ_EN)) {
2084                 stv0367cab_SetIirAdjacentcoefficient(state, mclk_hz,
2085                                                                 SymbolRate);
2086                 /* AllPass filter must be enabled
2087                 when the adjacents filter is used */
2088                 stv0367_writebits(state, F367CAB_ALLPASSFILT_EN, 1);
2089                 stv0367cab_SetAllPasscoefficient(state, mclk_hz, SymbolRate);
2090         } else
2091                 /* AllPass filter must be disabled
2092                 when the adjacents filter is not used */
2093 #endif
2094         stv0367_writebits(state, F367CAB_ALLPASSFILT_EN, 0);
2095
2096         stv0367_writereg(state, R367CAB_SRC_NCO_LL, u32_tmp);
2097         stv0367_writereg(state, R367CAB_SRC_NCO_LH, (u32_tmp >> 8));
2098         stv0367_writereg(state, R367CAB_SRC_NCO_HL, (u32_tmp >> 16));
2099         stv0367_writereg(state, R367CAB_SRC_NCO_HH, (u32_tmp >> 24));
2100
2101         stv0367_writereg(state, R367CAB_IQDEM_GAIN_SRC_L, u32_tmp1 & 0x00ff);
2102         stv0367_writebits(state, F367CAB_GAIN_SRC_HI, (u32_tmp1 >> 8) & 0x00ff);
2103
2104         return SymbolRate ;
2105 }
2106
2107 static u32 stv0367cab_GetSymbolRate(struct stv0367_state *state, u32 mclk_hz)
2108 {
2109         u32 regsym;
2110         u32 adp_khz;
2111
2112         regsym = stv0367_readreg(state, R367CAB_SRC_NCO_LL) +
2113                 (stv0367_readreg(state, R367CAB_SRC_NCO_LH) << 8) +
2114                 (stv0367_readreg(state, R367CAB_SRC_NCO_HL) << 16) +
2115                 (stv0367_readreg(state, R367CAB_SRC_NCO_HH) << 24);
2116
2117         adp_khz = (mclk_hz >> 1) / 1000;/* TRL works at half the system clock */
2118
2119         if (regsym < 134217728) {               /* 134217728L = 2**27*/
2120                 regsym = regsym * 32;           /* 32 = 2**5 */
2121                 regsym = regsym / 32768;        /* 32768L = 2**15 */
2122                 regsym = adp_khz * regsym;      /* AdpClk in kHz */
2123                 regsym = regsym / 128;          /* 128 = 2**7 */
2124                 regsym *= 125 ;                 /* 125 = 1000/2**3 */
2125                 regsym /= 2048 ;                /* 2048 = 2**11 */
2126         } else if (regsym < 268435456) {        /* 268435456L = 2**28 */
2127                 regsym = regsym * 16;           /* 16 = 2**4 */
2128                 regsym = regsym / 32768;        /* 32768L = 2**15 */
2129                 regsym = adp_khz * regsym;      /* AdpClk in kHz */
2130                 regsym = regsym / 128;          /* 128 = 2**7 */
2131                 regsym *= 125 ;                 /* 125 = 1000/2**3*/
2132                 regsym /= 1024 ;                /* 256 = 2**10*/
2133         } else if (regsym < 536870912) {        /* 536870912L = 2**29*/
2134                 regsym = regsym * 8;            /* 8 = 2**3 */
2135                 regsym = regsym / 32768;        /* 32768L = 2**15 */
2136                 regsym = adp_khz * regsym;      /* AdpClk in kHz */
2137                 regsym = regsym / 128;          /* 128 = 2**7 */
2138                 regsym *= 125 ;                 /* 125 = 1000/2**3 */
2139                 regsym /= 512 ;                 /* 128 = 2**9 */
2140         } else {
2141                 regsym = regsym * 4;            /* 4 = 2**2 */
2142                 regsym = regsym / 32768;        /* 32768L = 2**15 */
2143                 regsym = adp_khz * regsym;      /* AdpClk in kHz */
2144                 regsym = regsym / 128;          /* 128 = 2**7 */
2145                 regsym *= 125 ;                 /* 125 = 1000/2**3 */
2146                 regsym /= 256 ;                 /* 64 = 2**8 */
2147         }
2148
2149         return regsym;
2150 }
2151
2152 static int stv0367cab_read_status(struct dvb_frontend *fe,
2153                                   enum fe_status *status)
2154 {
2155         struct stv0367_state *state = fe->demodulator_priv;
2156
2157         dprintk("%s:\n", __func__);
2158
2159         *status = 0;
2160
2161         if (state->cab_state->state > FE_CAB_NOSIGNAL)
2162                 *status |= FE_HAS_SIGNAL;
2163
2164         if (state->cab_state->state > FE_CAB_NOCARRIER)
2165                 *status |= FE_HAS_CARRIER;
2166
2167         if (state->cab_state->state >= FE_CAB_DEMODOK)
2168                 *status |= FE_HAS_VITERBI;
2169
2170         if (state->cab_state->state >= FE_CAB_DATAOK)
2171                 *status |= FE_HAS_SYNC;
2172
2173         if (stv0367_readbits(state, (state->cab_state->qamfec_status_reg ?
2174                 state->cab_state->qamfec_status_reg : F367CAB_QAMFEC_LOCK))) {
2175                 *status |= FE_HAS_LOCK;
2176                 dprintk("%s: stv0367 has locked\n", __func__);
2177         }
2178
2179         return 0;
2180 }
2181
2182 static int stv0367cab_standby(struct dvb_frontend *fe, u8 standby_on)
2183 {
2184         struct stv0367_state *state = fe->demodulator_priv;
2185
2186         dprintk("%s:\n", __func__);
2187
2188         if (standby_on) {
2189                 stv0367_writebits(state, F367CAB_BYPASS_PLLXN, 0x03);
2190                 stv0367_writebits(state, F367CAB_STDBY_PLLXN, 0x01);
2191                 stv0367_writebits(state, F367CAB_STDBY, 1);
2192                 stv0367_writebits(state, F367CAB_STDBY_CORE, 1);
2193                 stv0367_writebits(state, F367CAB_EN_BUFFER_I, 0);
2194                 stv0367_writebits(state, F367CAB_EN_BUFFER_Q, 0);
2195                 stv0367_writebits(state, F367CAB_POFFQ, 1);
2196                 stv0367_writebits(state, F367CAB_POFFI, 1);
2197         } else {
2198                 stv0367_writebits(state, F367CAB_STDBY_PLLXN, 0x00);
2199                 stv0367_writebits(state, F367CAB_BYPASS_PLLXN, 0x00);
2200                 stv0367_writebits(state, F367CAB_STDBY, 0);
2201                 stv0367_writebits(state, F367CAB_STDBY_CORE, 0);
2202                 stv0367_writebits(state, F367CAB_EN_BUFFER_I, 1);
2203                 stv0367_writebits(state, F367CAB_EN_BUFFER_Q, 1);
2204                 stv0367_writebits(state, F367CAB_POFFQ, 0);
2205                 stv0367_writebits(state, F367CAB_POFFI, 0);
2206         }
2207
2208         return 0;
2209 }
2210
2211 static int stv0367cab_sleep(struct dvb_frontend *fe)
2212 {
2213         return stv0367cab_standby(fe, 1);
2214 }
2215
2216 static int stv0367cab_init(struct dvb_frontend *fe)
2217 {
2218         struct stv0367_state *state = fe->demodulator_priv;
2219         struct stv0367cab_state *cab_state = state->cab_state;
2220
2221         dprintk("%s:\n", __func__);
2222
2223         stv0367_write_table(state,
2224                 stv0367_deftabs[state->deftabs][STV0367_TAB_CAB]);
2225
2226         switch (state->config->ts_mode) {
2227         case STV0367_DVBCI_CLOCK:
2228                 dprintk("Setting TSMode = STV0367_DVBCI_CLOCK\n");
2229                 stv0367_writebits(state, F367CAB_OUTFORMAT, 0x03);
2230                 break;
2231         case STV0367_SERIAL_PUNCT_CLOCK:
2232         case STV0367_SERIAL_CONT_CLOCK:
2233                 stv0367_writebits(state, F367CAB_OUTFORMAT, 0x01);
2234                 break;
2235         case STV0367_PARALLEL_PUNCT_CLOCK:
2236         case STV0367_OUTPUTMODE_DEFAULT:
2237                 stv0367_writebits(state, F367CAB_OUTFORMAT, 0x00);
2238                 break;
2239         }
2240
2241         switch (state->config->clk_pol) {
2242         case STV0367_RISINGEDGE_CLOCK:
2243                 stv0367_writebits(state, F367CAB_CLK_POLARITY, 0x00);
2244                 break;
2245         case STV0367_FALLINGEDGE_CLOCK:
2246         case STV0367_CLOCKPOLARITY_DEFAULT:
2247                 stv0367_writebits(state, F367CAB_CLK_POLARITY, 0x01);
2248                 break;
2249         }
2250
2251         stv0367_writebits(state, F367CAB_SYNC_STRIP, 0x00);
2252
2253         stv0367_writebits(state, F367CAB_CT_NBST, 0x01);
2254
2255         stv0367_writebits(state, F367CAB_TS_SWAP, 0x01);
2256
2257         stv0367_writebits(state, F367CAB_FIFO_BYPASS, 0x00);
2258
2259         stv0367_writereg(state, R367CAB_ANACTRL, 0x00);/*PLL enabled and used */
2260
2261         cab_state->mclk = stv0367cab_get_mclk(fe, state->config->xtal);
2262         cab_state->adc_clk = stv0367cab_get_adc_freq(fe, state->config->xtal);
2263
2264         return 0;
2265 }
2266 static
2267 enum stv0367_cab_signal_type stv0367cab_algo(struct stv0367_state *state,
2268                                              struct dtv_frontend_properties *p)
2269 {
2270         struct stv0367cab_state *cab_state = state->cab_state;
2271         enum stv0367_cab_signal_type signalType = FE_CAB_NOAGC;
2272         u32     QAMFEC_Lock, QAM_Lock, u32_tmp, ifkhz,
2273                 LockTime, TRLTimeOut, AGCTimeOut, CRLSymbols,
2274                 CRLTimeOut, EQLTimeOut, DemodTimeOut, FECTimeOut;
2275         u8      TrackAGCAccum;
2276         s32     tmp;
2277
2278         dprintk("%s:\n", __func__);
2279
2280         stv0367_get_if_khz(state, &ifkhz);
2281
2282         /* Timeouts calculation */
2283         /* A max lock time of 25 ms is allowed for delayed AGC */
2284         AGCTimeOut = 25;
2285         /* 100000 symbols needed by the TRL as a maximum value */
2286         TRLTimeOut = 100000000 / p->symbol_rate;
2287         /* CRLSymbols is the needed number of symbols to achieve a lock
2288            within [-4%, +4%] of the symbol rate.
2289            CRL timeout is calculated
2290            for a lock within [-search_range, +search_range].
2291            EQL timeout can be changed depending on
2292            the micro-reflections we want to handle.
2293            A characterization must be performed
2294            with these echoes to get new timeout values.
2295         */
2296         switch (p->modulation) {
2297         case QAM_16:
2298                 CRLSymbols = 150000;
2299                 EQLTimeOut = 100;
2300                 break;
2301         case QAM_32:
2302                 CRLSymbols = 250000;
2303                 EQLTimeOut = 100;
2304                 break;
2305         case QAM_64:
2306                 CRLSymbols = 200000;
2307                 EQLTimeOut = 100;
2308                 break;
2309         case QAM_128:
2310                 CRLSymbols = 250000;
2311                 EQLTimeOut = 100;
2312                 break;
2313         case QAM_256:
2314                 CRLSymbols = 250000;
2315                 EQLTimeOut = 100;
2316                 break;
2317         default:
2318                 CRLSymbols = 200000;
2319                 EQLTimeOut = 100;
2320                 break;
2321         }
2322 #if 0
2323         if (pIntParams->search_range < 0) {
2324                 CRLTimeOut = (25 * CRLSymbols *
2325                                 (-pIntParams->search_range / 1000)) /
2326                                         (pIntParams->symbol_rate / 1000);
2327         } else
2328 #endif
2329         CRLTimeOut = (25 * CRLSymbols * (cab_state->search_range / 1000)) /
2330                                         (p->symbol_rate / 1000);
2331
2332         CRLTimeOut = (1000 * CRLTimeOut) / p->symbol_rate;
2333         /* Timeouts below 50ms are coerced */
2334         if (CRLTimeOut < 50)
2335                 CRLTimeOut = 50;
2336         /* A maximum of 100 TS packets is needed to get FEC lock even in case
2337         the spectrum inversion needs to be changed.
2338            This is equal to 20 ms in case of the lowest symbol rate of 0.87Msps
2339         */
2340         FECTimeOut = 20;
2341         DemodTimeOut = AGCTimeOut + TRLTimeOut + CRLTimeOut + EQLTimeOut;
2342
2343         dprintk("%s: DemodTimeOut=%d\n", __func__, DemodTimeOut);
2344
2345         /* Reset the TRL to ensure nothing starts until the
2346            AGC is stable which ensures a better lock time
2347         */
2348         stv0367_writereg(state, R367CAB_CTRL_1, 0x04);
2349         /* Set AGC accumulation time to minimum and lock threshold to maximum
2350         in order to speed up the AGC lock */
2351         TrackAGCAccum = stv0367_readbits(state, F367CAB_AGC_ACCUMRSTSEL);
2352         stv0367_writebits(state, F367CAB_AGC_ACCUMRSTSEL, 0x0);
2353         /* Modulus Mapper is disabled */
2354         stv0367_writebits(state, F367CAB_MODULUSMAP_EN, 0);
2355         /* Disable the sweep function */
2356         stv0367_writebits(state, F367CAB_SWEEP_EN, 0);
2357         /* The sweep function is never used, Sweep rate must be set to 0 */
2358         /* Set the derotator frequency in Hz */
2359         stv0367cab_set_derot_freq(state, cab_state->adc_clk,
2360                 (1000 * (s32)ifkhz + cab_state->derot_offset));
2361         /* Disable the Allpass Filter when the symbol rate is out of range */
2362         if ((p->symbol_rate > 10800000) | (p->symbol_rate < 1800000)) {
2363                 stv0367_writebits(state, F367CAB_ADJ_EN, 0);
2364                 stv0367_writebits(state, F367CAB_ALLPASSFILT_EN, 0);
2365         }
2366 #if 0
2367         /* Check if the tuner is locked */
2368         tuner_lock = stv0367cab_tuner_get_status(fe);
2369         if (tuner_lock == 0)
2370                 return FE_367CAB_NOTUNER;
2371 #endif
2372         /* Release the TRL to start demodulator acquisition */
2373         /* Wait for QAM lock */
2374         LockTime = 0;
2375         stv0367_writereg(state, R367CAB_CTRL_1, 0x00);
2376         do {
2377                 QAM_Lock = stv0367_readbits(state, F367CAB_FSM_STATUS);
2378                 if ((LockTime >= (DemodTimeOut - EQLTimeOut)) &&
2379                                                         (QAM_Lock == 0x04))
2380                         /*
2381                          * We don't wait longer, the frequency/phase offset
2382                          * must be too big
2383                          */
2384                         LockTime = DemodTimeOut;
2385                 else if ((LockTime >= (AGCTimeOut + TRLTimeOut)) &&
2386                                                         (QAM_Lock == 0x02))
2387                         /*
2388                          * We don't wait longer, either there is no signal or
2389                          * it is not the right symbol rate or it is an analog
2390                          * carrier
2391                          */
2392                 {
2393                         LockTime = DemodTimeOut;
2394                         u32_tmp = stv0367_readbits(state,
2395                                                 F367CAB_AGC_PWR_WORD_LO) +
2396                                         (stv0367_readbits(state,
2397                                                 F367CAB_AGC_PWR_WORD_ME) << 8) +
2398                                         (stv0367_readbits(state,
2399                                                 F367CAB_AGC_PWR_WORD_HI) << 16);
2400                         if (u32_tmp >= 131072)
2401                                 u32_tmp = 262144 - u32_tmp;
2402                         u32_tmp = u32_tmp / (1 << (11 - stv0367_readbits(state,
2403                                                         F367CAB_AGC_IF_BWSEL)));
2404
2405                         if (u32_tmp < stv0367_readbits(state,
2406                                                 F367CAB_AGC_PWRREF_LO) +
2407                                         256 * stv0367_readbits(state,
2408                                                 F367CAB_AGC_PWRREF_HI) - 10)
2409                                 QAM_Lock = 0x0f;
2410                 } else {
2411                         usleep_range(10000, 20000);
2412                         LockTime += 10;
2413                 }
2414                 dprintk("QAM_Lock=0x%x LockTime=%d\n", QAM_Lock, LockTime);
2415                 tmp = stv0367_readreg(state, R367CAB_IT_STATUS1);
2416
2417                 dprintk("R367CAB_IT_STATUS1=0x%x\n", tmp);
2418
2419         } while (((QAM_Lock != 0x0c) && (QAM_Lock != 0x0b)) &&
2420                                                 (LockTime < DemodTimeOut));
2421
2422         dprintk("QAM_Lock=0x%x\n", QAM_Lock);
2423
2424         tmp = stv0367_readreg(state, R367CAB_IT_STATUS1);
2425         dprintk("R367CAB_IT_STATUS1=0x%x\n", tmp);
2426         tmp = stv0367_readreg(state, R367CAB_IT_STATUS2);
2427         dprintk("R367CAB_IT_STATUS2=0x%x\n", tmp);
2428
2429         tmp  = stv0367cab_get_derot_freq(state, cab_state->adc_clk);
2430         dprintk("stv0367cab_get_derot_freq=0x%x\n", tmp);
2431
2432         if ((QAM_Lock == 0x0c) || (QAM_Lock == 0x0b)) {
2433                 /* Wait for FEC lock */
2434                 LockTime = 0;
2435                 do {
2436                         usleep_range(5000, 7000);
2437                         LockTime += 5;
2438                         QAMFEC_Lock = stv0367_readbits(state,
2439                                 (state->cab_state->qamfec_status_reg ?
2440                                 state->cab_state->qamfec_status_reg :
2441                                 F367CAB_QAMFEC_LOCK));
2442                 } while (!QAMFEC_Lock && (LockTime < FECTimeOut));
2443         } else
2444                 QAMFEC_Lock = 0;
2445
2446         if (QAMFEC_Lock) {
2447                 signalType = FE_CAB_DATAOK;
2448                 cab_state->spect_inv = stv0367_readbits(state,
2449                                                         F367CAB_QUAD_INV);
2450 #if 0
2451 /* not clear for me */
2452                 if (ifkhz != 0) {
2453                         if (ifkhz > cab_state->adc_clk / 1000) {
2454                                 cab_state->freq_khz =
2455                                         FE_Cab_TunerGetFrequency(pIntParams->hTuner)
2456                                 - stv0367cab_get_derot_freq(state, cab_state->adc_clk)
2457                                 - cab_state->adc_clk / 1000 + ifkhz;
2458                         } else {
2459                                 cab_state->freq_khz =
2460                                                 FE_Cab_TunerGetFrequency(pIntParams->hTuner)
2461                                                 - stv0367cab_get_derot_freq(state, cab_state->adc_clk)
2462                                                 + ifkhz;
2463                         }
2464                 } else {
2465                         cab_state->freq_khz =
2466                                 FE_Cab_TunerGetFrequency(pIntParams->hTuner) +
2467                                 stv0367cab_get_derot_freq(state,
2468                                                         cab_state->adc_clk) -
2469                                 cab_state->adc_clk / 4000;
2470                 }
2471 #endif
2472                 cab_state->symbol_rate = stv0367cab_GetSymbolRate(state,
2473                                                         cab_state->mclk);
2474                 cab_state->locked = 1;
2475
2476                 /* stv0367_setbits(state, F367CAB_AGC_ACCUMRSTSEL,7);*/
2477         } else {
2478                 switch (QAM_Lock) {
2479                 case 1:
2480                         signalType = FE_CAB_NOAGC;
2481                         break;
2482                 case 2:
2483                         signalType = FE_CAB_NOTIMING;
2484                         break;
2485                 case 3:
2486                         signalType = FE_CAB_TIMINGOK;
2487                         break;
2488                 case 4:
2489                         signalType = FE_CAB_NOCARRIER;
2490                         break;
2491                 case 5:
2492                         signalType = FE_CAB_CARRIEROK;
2493                         break;
2494                 case 7:
2495                         signalType = FE_CAB_NOBLIND;
2496                         break;
2497                 case 8:
2498                         signalType = FE_CAB_BLINDOK;
2499                         break;
2500                 case 10:
2501                         signalType = FE_CAB_NODEMOD;
2502                         break;
2503                 case 11:
2504                         signalType = FE_CAB_DEMODOK;
2505                         break;
2506                 case 12:
2507                         signalType = FE_CAB_DEMODOK;
2508                         break;
2509                 case 13:
2510                         signalType = FE_CAB_NODEMOD;
2511                         break;
2512                 case 14:
2513                         signalType = FE_CAB_NOBLIND;
2514                         break;
2515                 case 15:
2516                         signalType = FE_CAB_NOSIGNAL;
2517                         break;
2518                 default:
2519                         break;
2520                 }
2521
2522         }
2523
2524         /* Set the AGC control values to tracking values */
2525         stv0367_writebits(state, F367CAB_AGC_ACCUMRSTSEL, TrackAGCAccum);
2526         return signalType;
2527 }
2528
2529 static int stv0367cab_set_frontend(struct dvb_frontend *fe)
2530 {
2531         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
2532         struct stv0367_state *state = fe->demodulator_priv;
2533         struct stv0367cab_state *cab_state = state->cab_state;
2534         enum stv0367cab_mod QAMSize = 0;
2535
2536         dprintk("%s: freq = %d, srate = %d\n", __func__,
2537                                         p->frequency, p->symbol_rate);
2538
2539         cab_state->derot_offset = 0;
2540
2541         switch (p->modulation) {
2542         case QAM_16:
2543                 QAMSize = FE_CAB_MOD_QAM16;
2544                 break;
2545         case QAM_32:
2546                 QAMSize = FE_CAB_MOD_QAM32;
2547                 break;
2548         case QAM_64:
2549                 QAMSize = FE_CAB_MOD_QAM64;
2550                 break;
2551         case QAM_128:
2552                 QAMSize = FE_CAB_MOD_QAM128;
2553                 break;
2554         case QAM_256:
2555                 QAMSize = FE_CAB_MOD_QAM256;
2556                 break;
2557         default:
2558                 break;
2559         }
2560
2561         if (state->reinit_on_setfrontend)
2562                 stv0367cab_init(fe);
2563
2564         /* Tuner Frequency Setting */
2565         if (fe->ops.tuner_ops.set_params) {
2566                 if (state->use_i2c_gatectrl && fe->ops.i2c_gate_ctrl)
2567                         fe->ops.i2c_gate_ctrl(fe, 1);
2568                 fe->ops.tuner_ops.set_params(fe);
2569                 if (state->use_i2c_gatectrl && fe->ops.i2c_gate_ctrl)
2570                         fe->ops.i2c_gate_ctrl(fe, 0);
2571         }
2572
2573         stv0367cab_SetQamSize(
2574                         state,
2575                         p->symbol_rate,
2576                         QAMSize);
2577
2578         stv0367cab_set_srate(state,
2579                         cab_state->adc_clk,
2580                         cab_state->mclk,
2581                         p->symbol_rate,
2582                         QAMSize);
2583         /* Search algorithm launch, [-1.1*RangeOffset, +1.1*RangeOffset] scan */
2584         cab_state->state = stv0367cab_algo(state, p);
2585         return 0;
2586 }
2587
2588 static int stv0367cab_get_frontend(struct dvb_frontend *fe,
2589                                    struct dtv_frontend_properties *p)
2590 {
2591         struct stv0367_state *state = fe->demodulator_priv;
2592         struct stv0367cab_state *cab_state = state->cab_state;
2593         u32 ifkhz = 0;
2594
2595         enum stv0367cab_mod QAMSize;
2596
2597         dprintk("%s:\n", __func__);
2598
2599         stv0367_get_if_khz(state, &ifkhz);
2600         p->symbol_rate = stv0367cab_GetSymbolRate(state, cab_state->mclk);
2601
2602         QAMSize = stv0367_readbits(state, F367CAB_QAM_MODE);
2603         switch (QAMSize) {
2604         case FE_CAB_MOD_QAM16:
2605                 p->modulation = QAM_16;
2606                 break;
2607         case FE_CAB_MOD_QAM32:
2608                 p->modulation = QAM_32;
2609                 break;
2610         case FE_CAB_MOD_QAM64:
2611                 p->modulation = QAM_64;
2612                 break;
2613         case FE_CAB_MOD_QAM128:
2614                 p->modulation = QAM_128;
2615                 break;
2616         case FE_CAB_MOD_QAM256:
2617                 p->modulation = QAM_256;
2618                 break;
2619         default:
2620                 break;
2621         }
2622
2623         p->frequency = stv0367_get_tuner_freq(fe);
2624
2625         dprintk("%s: tuner frequency = %d\n", __func__, p->frequency);
2626
2627         if (ifkhz == 0) {
2628                 p->frequency +=
2629                         (stv0367cab_get_derot_freq(state, cab_state->adc_clk) -
2630                         cab_state->adc_clk / 4000);
2631                 return 0;
2632         }
2633
2634         if (ifkhz > cab_state->adc_clk / 1000)
2635                 p->frequency += (ifkhz
2636                         - stv0367cab_get_derot_freq(state, cab_state->adc_clk)
2637                         - cab_state->adc_clk / 1000);
2638         else
2639                 p->frequency += (ifkhz
2640                         - stv0367cab_get_derot_freq(state, cab_state->adc_clk));
2641
2642         return 0;
2643 }
2644
2645 #if 0
2646 void stv0367cab_GetErrorCount(state, enum stv0367cab_mod QAMSize,
2647                         u32 symbol_rate, FE_367qam_Monitor *Monitor_results)
2648 {
2649         stv0367cab_OptimiseNByteAndGetBER(state, QAMSize, symbol_rate, Monitor_results);
2650         stv0367cab_GetPacketsCount(state, Monitor_results);
2651
2652         return;
2653 }
2654
2655 static int stv0367cab_read_ber(struct dvb_frontend *fe, u32 *ber)
2656 {
2657         struct stv0367_state *state = fe->demodulator_priv;
2658
2659         return 0;
2660 }
2661 #endif
2662 static s32 stv0367cab_get_rf_lvl(struct stv0367_state *state)
2663 {
2664         s32 rfLevel = 0;
2665         s32 RfAgcPwm = 0, IfAgcPwm = 0;
2666         u8 i;
2667
2668         stv0367_writebits(state, F367CAB_STDBY_ADCGP, 0x0);
2669
2670         RfAgcPwm =
2671                 (stv0367_readbits(state, F367CAB_RF_AGC1_LEVEL_LO) & 0x03) +
2672                 (stv0367_readbits(state, F367CAB_RF_AGC1_LEVEL_HI) << 2);
2673         RfAgcPwm = 100 * RfAgcPwm / 1023;
2674
2675         IfAgcPwm =
2676                 stv0367_readbits(state, F367CAB_AGC_IF_PWMCMD_LO) +
2677                 (stv0367_readbits(state, F367CAB_AGC_IF_PWMCMD_HI) << 8);
2678         if (IfAgcPwm >= 2048)
2679                 IfAgcPwm -= 2048;
2680         else
2681                 IfAgcPwm += 2048;
2682
2683         IfAgcPwm = 100 * IfAgcPwm / 4095;
2684
2685         /* For DTT75467 on NIM */
2686         if (RfAgcPwm < 90  && IfAgcPwm < 28) {
2687                 for (i = 0; i < RF_LOOKUP_TABLE_SIZE; i++) {
2688                         if (RfAgcPwm <= stv0367cab_RF_LookUp1[0][i]) {
2689                                 rfLevel = (-1) * stv0367cab_RF_LookUp1[1][i];
2690                                 break;
2691                         }
2692                 }
2693                 if (i == RF_LOOKUP_TABLE_SIZE)
2694                         rfLevel = -56;
2695         } else { /*if IF AGC>10*/
2696                 for (i = 0; i < RF_LOOKUP_TABLE2_SIZE; i++) {
2697                         if (IfAgcPwm <= stv0367cab_RF_LookUp2[0][i]) {
2698                                 rfLevel = (-1) * stv0367cab_RF_LookUp2[1][i];
2699                                 break;
2700                         }
2701                 }
2702                 if (i == RF_LOOKUP_TABLE2_SIZE)
2703                         rfLevel = -72;
2704         }
2705         return rfLevel;
2706 }
2707
2708 static int stv0367cab_read_strength(struct dvb_frontend *fe, u16 *strength)
2709 {
2710         struct stv0367_state *state = fe->demodulator_priv;
2711
2712         s32 signal =  stv0367cab_get_rf_lvl(state);
2713
2714         dprintk("%s: signal=%d dBm\n", __func__, signal);
2715
2716         if (signal <= -72)
2717                 *strength = 65535;
2718         else
2719                 *strength = (22 + signal) * (-1311);
2720
2721         dprintk("%s: strength=%d\n", __func__, (*strength));
2722
2723         return 0;
2724 }
2725
2726 static int stv0367cab_snr_power(struct dvb_frontend *fe)
2727 {
2728         struct stv0367_state *state = fe->demodulator_priv;
2729         enum stv0367cab_mod QAMSize;
2730
2731         QAMSize = stv0367_readbits(state, F367CAB_QAM_MODE);
2732         switch (QAMSize) {
2733         case FE_CAB_MOD_QAM4:
2734                 return 21904;
2735         case FE_CAB_MOD_QAM16:
2736                 return 20480;
2737         case FE_CAB_MOD_QAM32:
2738                 return 23040;
2739         case FE_CAB_MOD_QAM64:
2740                 return 21504;
2741         case FE_CAB_MOD_QAM128:
2742                 return 23616;
2743         case FE_CAB_MOD_QAM256:
2744                 return 21760;
2745         case FE_CAB_MOD_QAM1024:
2746                 return 21280;
2747         default:
2748                 break;
2749         }
2750
2751         return 1;
2752 }
2753
2754 static int stv0367cab_snr_readreg(struct dvb_frontend *fe, int avgdiv)
2755 {
2756         struct stv0367_state *state = fe->demodulator_priv;
2757         u32 regval = 0;
2758         int i;
2759
2760         for (i = 0; i < 10; i++) {
2761                 regval += (stv0367_readbits(state, F367CAB_SNR_LO)
2762                         + 256 * stv0367_readbits(state, F367CAB_SNR_HI));
2763         }
2764
2765         if (avgdiv)
2766                 regval /= 10;
2767
2768         return regval;
2769 }
2770
2771 static int stv0367cab_read_snr(struct dvb_frontend *fe, u16 *snr)
2772 {
2773         struct stv0367_state *state = fe->demodulator_priv;
2774         u32 noisepercentage;
2775         u32 regval = 0, temp = 0;
2776         int power;
2777
2778         power = stv0367cab_snr_power(fe);
2779         regval = stv0367cab_snr_readreg(fe, 1);
2780
2781         if (regval != 0) {
2782                 temp = power
2783                         * (1 << (3 + stv0367_readbits(state, F367CAB_SNR_PER)));
2784                 temp /= regval;
2785         }
2786
2787         /* table values, not needed to calculate logarithms */
2788         if (temp >= 5012)
2789                 noisepercentage = 100;
2790         else if (temp >= 3981)
2791                 noisepercentage = 93;
2792         else if (temp >= 3162)
2793                 noisepercentage = 86;
2794         else if (temp >= 2512)
2795                 noisepercentage = 79;
2796         else if (temp >= 1995)
2797                 noisepercentage = 72;
2798         else if (temp >= 1585)
2799                 noisepercentage = 65;
2800         else if (temp >= 1259)
2801                 noisepercentage = 58;
2802         else if (temp >= 1000)
2803                 noisepercentage = 50;
2804         else if (temp >= 794)
2805                 noisepercentage = 43;
2806         else if (temp >= 501)
2807                 noisepercentage = 36;
2808         else if (temp >= 316)
2809                 noisepercentage = 29;
2810         else if (temp >= 200)
2811                 noisepercentage = 22;
2812         else if (temp >= 158)
2813                 noisepercentage = 14;
2814         else if (temp >= 126)
2815                 noisepercentage = 7;
2816         else
2817                 noisepercentage = 0;
2818
2819         dprintk("%s: noisepercentage=%d\n", __func__, noisepercentage);
2820
2821         *snr = (noisepercentage * 65535) / 100;
2822
2823         return 0;
2824 }
2825
2826 static int stv0367cab_read_ucblcks(struct dvb_frontend *fe, u32 *ucblocks)
2827 {
2828         struct stv0367_state *state = fe->demodulator_priv;
2829         int corrected, tscount;
2830
2831         *ucblocks = (stv0367_readreg(state, R367CAB_RS_COUNTER_5) << 8)
2832                         | stv0367_readreg(state, R367CAB_RS_COUNTER_4);
2833         corrected = (stv0367_readreg(state, R367CAB_RS_COUNTER_3) << 8)
2834                         | stv0367_readreg(state, R367CAB_RS_COUNTER_2);
2835         tscount = (stv0367_readreg(state, R367CAB_RS_COUNTER_2) << 8)
2836                         | stv0367_readreg(state, R367CAB_RS_COUNTER_1);
2837
2838         dprintk("%s: uncorrected blocks=%d corrected blocks=%d tscount=%d\n",
2839                                 __func__, *ucblocks, corrected, tscount);
2840
2841         return 0;
2842 };
2843
2844 static const struct dvb_frontend_ops stv0367cab_ops = {
2845         .delsys = { SYS_DVBC_ANNEX_A },
2846         .info = {
2847                 .name = "ST STV0367 DVB-C",
2848                 .frequency_min = 47000000,
2849                 .frequency_max = 862000000,
2850                 .frequency_stepsize = 62500,
2851                 .symbol_rate_min = 870000,
2852                 .symbol_rate_max = 11700000,
2853                 .caps = 0x400 |/* FE_CAN_QAM_4 */
2854                         FE_CAN_QAM_16 | FE_CAN_QAM_32  |
2855                         FE_CAN_QAM_64 | FE_CAN_QAM_128 |
2856                         FE_CAN_QAM_256 | FE_CAN_FEC_AUTO
2857         },
2858         .release                                = stv0367_release,
2859         .init                                   = stv0367cab_init,
2860         .sleep                                  = stv0367cab_sleep,
2861         .i2c_gate_ctrl                          = stv0367cab_gate_ctrl,
2862         .set_frontend                           = stv0367cab_set_frontend,
2863         .get_frontend                           = stv0367cab_get_frontend,
2864         .read_status                            = stv0367cab_read_status,
2865 /*      .read_ber                               = stv0367cab_read_ber, */
2866         .read_signal_strength                   = stv0367cab_read_strength,
2867         .read_snr                               = stv0367cab_read_snr,
2868         .read_ucblocks                          = stv0367cab_read_ucblcks,
2869         .get_tune_settings                      = stv0367_get_tune_settings,
2870 };
2871
2872 struct dvb_frontend *stv0367cab_attach(const struct stv0367_config *config,
2873                                    struct i2c_adapter *i2c)
2874 {
2875         struct stv0367_state *state = NULL;
2876         struct stv0367cab_state *cab_state = NULL;
2877
2878         /* allocate memory for the internal state */
2879         state = kzalloc(sizeof(struct stv0367_state), GFP_KERNEL);
2880         if (state == NULL)
2881                 goto error;
2882         cab_state = kzalloc(sizeof(struct stv0367cab_state), GFP_KERNEL);
2883         if (cab_state == NULL)
2884                 goto error;
2885
2886         /* setup the state */
2887         state->i2c = i2c;
2888         state->config = config;
2889         cab_state->search_range = 280000;
2890         cab_state->qamfec_status_reg = F367CAB_QAMFEC_LOCK;
2891         state->cab_state = cab_state;
2892         state->fe.ops = stv0367cab_ops;
2893         state->fe.demodulator_priv = state;
2894         state->chip_id = stv0367_readreg(state, 0xf000);
2895
2896         /* demod operation options */
2897         state->use_i2c_gatectrl = 1;
2898         state->deftabs = STV0367_DEFTAB_GENERIC;
2899         state->reinit_on_setfrontend = 1;
2900         state->auto_if_khz = 0;
2901
2902         dprintk("%s: chip_id = 0x%x\n", __func__, state->chip_id);
2903
2904         /* check if the demod is there */
2905         if ((state->chip_id != 0x50) && (state->chip_id != 0x60))
2906                 goto error;
2907
2908         return &state->fe;
2909
2910 error:
2911         kfree(cab_state);
2912         kfree(state);
2913         return NULL;
2914 }
2915 EXPORT_SYMBOL(stv0367cab_attach);
2916
2917 /*
2918  * Functions for operation on Digital Devices hardware
2919  */
2920
2921 static void stv0367ddb_setup_ter(struct stv0367_state *state)
2922 {
2923         stv0367_writereg(state, R367TER_DEBUG_LT4, 0x00);
2924         stv0367_writereg(state, R367TER_DEBUG_LT5, 0x00);
2925         stv0367_writereg(state, R367TER_DEBUG_LT6, 0x00); /* R367CAB_CTRL_1 */
2926         stv0367_writereg(state, R367TER_DEBUG_LT7, 0x00); /* R367CAB_CTRL_2 */
2927         stv0367_writereg(state, R367TER_DEBUG_LT8, 0x00);
2928         stv0367_writereg(state, R367TER_DEBUG_LT9, 0x00);
2929
2930         /* Tuner Setup */
2931         /* Buffer Q disabled, I Enabled, unsigned ADC */
2932         stv0367_writereg(state, R367TER_ANADIGCTRL, 0x89);
2933         stv0367_writereg(state, R367TER_DUAL_AD12, 0x04); /* ADCQ disabled */
2934
2935         /* Clock setup */
2936         /* PLL bypassed and disabled */
2937         stv0367_writereg(state, R367TER_ANACTRL, 0x0D);
2938         stv0367_writereg(state, R367TER_TOPCTRL, 0x00); /* Set OFDM */
2939
2940         /* IC runs at 54 MHz with a 27 MHz crystal */
2941         stv0367_pll_setup(state, STV0367_ICSPEED_53125, state->config->xtal);
2942
2943         msleep(50);
2944         /* PLL enabled and used */
2945         stv0367_writereg(state, R367TER_ANACTRL, 0x00);
2946
2947         state->activedemod = demod_ter;
2948 }
2949
2950 static void stv0367ddb_setup_cab(struct stv0367_state *state)
2951 {
2952         stv0367_writereg(state, R367TER_DEBUG_LT4, 0x00);
2953         stv0367_writereg(state, R367TER_DEBUG_LT5, 0x01);
2954         stv0367_writereg(state, R367TER_DEBUG_LT6, 0x06); /* R367CAB_CTRL_1 */
2955         stv0367_writereg(state, R367TER_DEBUG_LT7, 0x03); /* R367CAB_CTRL_2 */
2956         stv0367_writereg(state, R367TER_DEBUG_LT8, 0x00);
2957         stv0367_writereg(state, R367TER_DEBUG_LT9, 0x00);
2958
2959         /* Tuner Setup */
2960         /* Buffer Q disabled, I Enabled, signed ADC */
2961         stv0367_writereg(state, R367TER_ANADIGCTRL, 0x8B);
2962         /* ADCQ disabled */
2963         stv0367_writereg(state, R367TER_DUAL_AD12, 0x04);
2964
2965         /* Clock setup */
2966         /* PLL bypassed and disabled */
2967         stv0367_writereg(state, R367TER_ANACTRL, 0x0D);
2968         /* Set QAM */
2969         stv0367_writereg(state, R367TER_TOPCTRL, 0x10);
2970
2971         /* IC runs at 58 MHz with a 27 MHz crystal */
2972         stv0367_pll_setup(state, STV0367_ICSPEED_58000, state->config->xtal);
2973
2974         msleep(50);
2975         /* PLL enabled and used */
2976         stv0367_writereg(state, R367TER_ANACTRL, 0x00);
2977
2978         state->cab_state->mclk = stv0367cab_get_mclk(&state->fe,
2979                 state->config->xtal);
2980         state->cab_state->adc_clk = stv0367cab_get_adc_freq(&state->fe,
2981                 state->config->xtal);
2982
2983         state->activedemod = demod_cab;
2984 }
2985
2986 static int stv0367ddb_set_frontend(struct dvb_frontend *fe)
2987 {
2988         struct stv0367_state *state = fe->demodulator_priv;
2989
2990         switch (fe->dtv_property_cache.delivery_system) {
2991         case SYS_DVBT:
2992                 if (state->activedemod != demod_ter)
2993                         stv0367ddb_setup_ter(state);
2994
2995                 return stv0367ter_set_frontend(fe);
2996         case SYS_DVBC_ANNEX_A:
2997                 if (state->activedemod != demod_cab)
2998                         stv0367ddb_setup_cab(state);
2999
3000                 /* protect against division error oopses */
3001                 if (fe->dtv_property_cache.symbol_rate == 0) {
3002                         printk(KERN_ERR "Invalid symbol rate\n");
3003                         return -EINVAL;
3004                 }
3005
3006                 return stv0367cab_set_frontend(fe);
3007         default:
3008                 break;
3009         }
3010
3011         return -EINVAL;
3012 }
3013
3014 static void stv0367ddb_read_signal_strength(struct dvb_frontend *fe)
3015 {
3016         struct stv0367_state *state = fe->demodulator_priv;
3017         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
3018         s32 signalstrength;
3019
3020         switch (state->activedemod) {
3021         case demod_cab:
3022                 signalstrength = stv0367cab_get_rf_lvl(state) * 1000;
3023                 break;
3024         default:
3025                 p->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3026                 return;
3027         }
3028
3029         p->strength.stat[0].scale = FE_SCALE_DECIBEL;
3030         p->strength.stat[0].uvalue = signalstrength;
3031 }
3032
3033 static void stv0367ddb_read_snr(struct dvb_frontend *fe)
3034 {
3035         struct stv0367_state *state = fe->demodulator_priv;
3036         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
3037         int cab_pwr;
3038         u32 regval, tmpval, snrval = 0;
3039
3040         switch (state->activedemod) {
3041         case demod_ter:
3042                 snrval = stv0367ter_snr_readreg(fe);
3043                 break;
3044         case demod_cab:
3045                 cab_pwr = stv0367cab_snr_power(fe);
3046                 regval = stv0367cab_snr_readreg(fe, 0);
3047
3048                 /* prevent division by zero */
3049                 if (!regval) {
3050                         snrval = 0;
3051                         break;
3052                 }
3053
3054                 tmpval = (cab_pwr * 320) / regval;
3055                 snrval = ((tmpval != 0) ? (intlog2(tmpval) / 5581) : 0);
3056                 break;
3057         default:
3058                 p->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3059                 return;
3060         }
3061
3062         p->cnr.stat[0].scale = FE_SCALE_DECIBEL;
3063         p->cnr.stat[0].uvalue = snrval;
3064 }
3065
3066 static void stv0367ddb_read_ucblocks(struct dvb_frontend *fe)
3067 {
3068         struct stv0367_state *state = fe->demodulator_priv;
3069         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
3070         u32 ucblocks = 0;
3071
3072         switch (state->activedemod) {
3073         case demod_ter:
3074                 stv0367ter_read_ucblocks(fe, &ucblocks);
3075                 break;
3076         case demod_cab:
3077                 stv0367cab_read_ucblcks(fe, &ucblocks);
3078                 break;
3079         default:
3080                 p->block_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3081                 return;
3082         }
3083
3084         p->block_error.stat[0].scale = FE_SCALE_COUNTER;
3085         p->block_error.stat[0].uvalue = ucblocks;
3086 }
3087
3088 static int stv0367ddb_read_status(struct dvb_frontend *fe,
3089                                   enum fe_status *status)
3090 {
3091         struct stv0367_state *state = fe->demodulator_priv;
3092         struct dtv_frontend_properties *p = &fe->dtv_property_cache;
3093         int ret;
3094
3095         switch (state->activedemod) {
3096         case demod_ter:
3097                 ret = stv0367ter_read_status(fe, status);
3098                 break;
3099         case demod_cab:
3100                 ret = stv0367cab_read_status(fe, status);
3101                 break;
3102         default:
3103                 return 0;
3104         }
3105
3106         /* stop and report on *_read_status failure */
3107         if (ret)
3108                 return ret;
3109
3110         stv0367ddb_read_signal_strength(fe);
3111
3112         /* read carrier/noise when a carrier is detected */
3113         if (*status & FE_HAS_CARRIER)
3114                 stv0367ddb_read_snr(fe);
3115         else
3116                 p->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3117
3118         /* read uncorrected blocks on FE_HAS_LOCK */
3119         if (*status & FE_HAS_LOCK)
3120                 stv0367ddb_read_ucblocks(fe);
3121         else
3122                 p->block_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3123
3124         return 0;
3125 }
3126
3127 static int stv0367ddb_get_frontend(struct dvb_frontend *fe,
3128                                    struct dtv_frontend_properties *p)
3129 {
3130         struct stv0367_state *state = fe->demodulator_priv;
3131
3132         switch (state->activedemod) {
3133         case demod_ter:
3134                 return stv0367ter_get_frontend(fe, p);
3135         case demod_cab:
3136                 return stv0367cab_get_frontend(fe, p);
3137         default:
3138                 break;
3139         }
3140
3141         return -EINVAL;
3142 }
3143
3144 static int stv0367ddb_sleep(struct dvb_frontend *fe)
3145 {
3146         struct stv0367_state *state = fe->demodulator_priv;
3147
3148         switch (state->activedemod) {
3149         case demod_ter:
3150                 state->activedemod = demod_none;
3151                 return stv0367ter_sleep(fe);
3152         case demod_cab:
3153                 state->activedemod = demod_none;
3154                 return stv0367cab_sleep(fe);
3155         default:
3156                 break;
3157         }
3158
3159         return -EINVAL;
3160 }
3161
3162 static int stv0367ddb_init(struct stv0367_state *state)
3163 {
3164         struct stv0367ter_state *ter_state = state->ter_state;
3165         struct dtv_frontend_properties *p = &state->fe.dtv_property_cache;
3166
3167         stv0367_writereg(state, R367TER_TOPCTRL, 0x10);
3168
3169         if (stv0367_deftabs[state->deftabs][STV0367_TAB_BASE])
3170                 stv0367_write_table(state,
3171                         stv0367_deftabs[state->deftabs][STV0367_TAB_BASE]);
3172
3173         stv0367_write_table(state,
3174                 stv0367_deftabs[state->deftabs][STV0367_TAB_CAB]);
3175
3176         stv0367_writereg(state, R367TER_TOPCTRL, 0x00);
3177         stv0367_write_table(state,
3178                 stv0367_deftabs[state->deftabs][STV0367_TAB_TER]);
3179
3180         stv0367_writereg(state, R367TER_GAIN_SRC1, 0x2A);
3181         stv0367_writereg(state, R367TER_GAIN_SRC2, 0xD6);
3182         stv0367_writereg(state, R367TER_INC_DEROT1, 0x55);
3183         stv0367_writereg(state, R367TER_INC_DEROT2, 0x55);
3184         stv0367_writereg(state, R367TER_TRL_CTL, 0x14);
3185         stv0367_writereg(state, R367TER_TRL_NOMRATE1, 0xAE);
3186         stv0367_writereg(state, R367TER_TRL_NOMRATE2, 0x56);
3187         stv0367_writereg(state, R367TER_FEPATH_CFG, 0x0);
3188
3189         /* OFDM TS Setup */
3190
3191         stv0367_writereg(state, R367TER_TSCFGH, 0x70);
3192         stv0367_writereg(state, R367TER_TSCFGM, 0xC0);
3193         stv0367_writereg(state, R367TER_TSCFGL, 0x20);
3194         stv0367_writereg(state, R367TER_TSSPEED, 0x40); /* Fixed at 54 MHz */
3195
3196         stv0367_writereg(state, R367TER_TSCFGH, 0x71);
3197         stv0367_writereg(state, R367TER_TSCFGH, 0x70);
3198
3199         stv0367_writereg(state, R367TER_TOPCTRL, 0x10);
3200
3201         /* Also needed for QAM */
3202         stv0367_writereg(state, R367TER_AGC12C, 0x01); /* AGC Pin setup */
3203
3204         stv0367_writereg(state, R367TER_AGCCTRL1, 0x8A);
3205
3206         /* QAM TS setup, note exact format also depends on descrambler */
3207         /* settings */
3208         /* Inverted Clock, Swap, serial */
3209         stv0367_writereg(state, R367CAB_OUTFORMAT_0, 0x85);
3210
3211         /* Clock setup (PLL bypassed and disabled) */
3212         stv0367_writereg(state, R367TER_ANACTRL, 0x0D);
3213
3214         /* IC runs at 58 MHz with a 27 MHz crystal */
3215         stv0367_pll_setup(state, STV0367_ICSPEED_58000, state->config->xtal);
3216
3217         /* Tuner setup */
3218         /* Buffer Q disabled, I Enabled, signed ADC */
3219         stv0367_writereg(state, R367TER_ANADIGCTRL, 0x8b);
3220         stv0367_writereg(state, R367TER_DUAL_AD12, 0x04); /* ADCQ disabled */
3221
3222         /* Improves the C/N lock limit */
3223         stv0367_writereg(state, R367CAB_FSM_SNR2_HTH, 0x23);
3224         /* ZIF/IF Automatic mode */
3225         stv0367_writereg(state, R367CAB_IQ_QAM, 0x01);
3226         /* Improving burst noise performances */
3227         stv0367_writereg(state, R367CAB_EQU_FFE_LEAKAGE, 0x83);
3228         /* Improving ACI performances */
3229         stv0367_writereg(state, R367CAB_IQDEM_ADJ_EN, 0x05);
3230
3231         /* PLL enabled and used */
3232         stv0367_writereg(state, R367TER_ANACTRL, 0x00);
3233
3234         stv0367_writereg(state, R367TER_I2CRPT, (0x08 | ((5 & 0x07) << 4)));
3235
3236         ter_state->pBER = 0;
3237         ter_state->first_lock = 0;
3238         ter_state->unlock_counter = 2;
3239
3240         p->strength.len = 1;
3241         p->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3242         p->cnr.len = 1;
3243         p->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3244         p->block_error.len = 1;
3245         p->block_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
3246
3247         return 0;
3248 }
3249
3250 static const struct dvb_frontend_ops stv0367ddb_ops = {
3251         .delsys = { SYS_DVBC_ANNEX_A, SYS_DVBT },
3252         .info = {
3253                 .name                   = "ST STV0367 DDB DVB-C/T",
3254                 .frequency_min          = 47000000,
3255                 .frequency_max          = 865000000,
3256                 .frequency_stepsize     = 166667,
3257                 .frequency_tolerance    = 0,
3258                 .symbol_rate_min        = 870000,
3259                 .symbol_rate_max        = 11700000,
3260                 .caps = /* DVB-C */
3261                         0x400 |/* FE_CAN_QAM_4 */
3262                         FE_CAN_QAM_16 | FE_CAN_QAM_32  |
3263                         FE_CAN_QAM_64 | FE_CAN_QAM_128 |
3264                         FE_CAN_QAM_256 | FE_CAN_QAM_AUTO |
3265                         /* DVB-T */
3266                         FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
3267                         FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
3268                         FE_CAN_QPSK | FE_CAN_TRANSMISSION_MODE_AUTO |
3269                         FE_CAN_RECOVER | FE_CAN_INVERSION_AUTO |
3270                         FE_CAN_MUTE_TS
3271         },
3272         .release = stv0367_release,
3273         .sleep = stv0367ddb_sleep,
3274         .i2c_gate_ctrl = stv0367cab_gate_ctrl, /* valid for TER and CAB */
3275         .set_frontend = stv0367ddb_set_frontend,
3276         .get_frontend = stv0367ddb_get_frontend,
3277         .get_tune_settings = stv0367_get_tune_settings,
3278         .read_status = stv0367ddb_read_status,
3279 };
3280
3281 struct dvb_frontend *stv0367ddb_attach(const struct stv0367_config *config,
3282                                    struct i2c_adapter *i2c)
3283 {
3284         struct stv0367_state *state = NULL;
3285         struct stv0367ter_state *ter_state = NULL;
3286         struct stv0367cab_state *cab_state = NULL;
3287
3288         /* allocate memory for the internal state */
3289         state = kzalloc(sizeof(struct stv0367_state), GFP_KERNEL);
3290         if (state == NULL)
3291                 goto error;
3292         ter_state = kzalloc(sizeof(struct stv0367ter_state), GFP_KERNEL);
3293         if (ter_state == NULL)
3294                 goto error;
3295         cab_state = kzalloc(sizeof(struct stv0367cab_state), GFP_KERNEL);
3296         if (cab_state == NULL)
3297                 goto error;
3298
3299         /* setup the state */
3300         state->i2c = i2c;
3301         state->config = config;
3302         state->ter_state = ter_state;
3303         cab_state->search_range = 280000;
3304         cab_state->qamfec_status_reg = F367CAB_DESCR_SYNCSTATE;
3305         state->cab_state = cab_state;
3306         state->fe.ops = stv0367ddb_ops;
3307         state->fe.demodulator_priv = state;
3308         state->chip_id = stv0367_readreg(state, R367TER_ID);
3309
3310         /* demod operation options */
3311         state->use_i2c_gatectrl = 0;
3312         state->deftabs = STV0367_DEFTAB_DDB;
3313         state->reinit_on_setfrontend = 0;
3314         state->auto_if_khz = 1;
3315         state->activedemod = demod_none;
3316
3317         dprintk("%s: chip_id = 0x%x\n", __func__, state->chip_id);
3318
3319         /* check if the demod is there */
3320         if ((state->chip_id != 0x50) && (state->chip_id != 0x60))
3321                 goto error;
3322
3323         dev_info(&i2c->dev, "Found %s with ChipID %02X at adr %02X\n",
3324                 state->fe.ops.info.name, state->chip_id,
3325                 config->demod_address);
3326
3327         stv0367ddb_init(state);
3328
3329         return &state->fe;
3330
3331 error:
3332         kfree(cab_state);
3333         kfree(ter_state);
3334         kfree(state);
3335         return NULL;
3336 }
3337 EXPORT_SYMBOL(stv0367ddb_attach);
3338
3339 MODULE_PARM_DESC(debug, "Set debug");
3340 MODULE_PARM_DESC(i2c_debug, "Set i2c debug");
3341
3342 MODULE_AUTHOR("Igor M. Liplianin");
3343 MODULE_DESCRIPTION("ST STV0367 DVB-C/T demodulator driver");
3344 MODULE_LICENSE("GPL");