Acurite minor bugfixes
[rtl-433.git] / src / tuner_e4k.c
1 /*
2  * Elonics E4000 tuner driver
3  *
4  * (C) 2011-2012 by Harald Welte <laforge@gnumonks.org>
5  * (C) 2012 by Sylvain Munaut <tnt@246tNt.com>
6  * (C) 2012 by Hoernchen <la@tfc-server.de>
7  *
8  * All Rights Reserved
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  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include <limits.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <stdio.h>
29
30 #include <reg_field.h>
31 #include <tuner_e4k.h>
32
33 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
34
35 /* If this is defined, the limits are somewhat relaxed compared to what the
36  * vendor claims is possible */
37 #define OUT_OF_SPEC
38
39 #define MHZ(x)  ((x)*1000*1000)
40 #define KHZ(x)  ((x)*1000)
41
42 uint32_t unsigned_delta(uint32_t a, uint32_t b)
43 {
44         if (a > b)
45                 return a - b;
46         else
47                 return b - a;
48 }
49
50 /* look-up table bit-width -> mask */
51 static const uint8_t width2mask[] = {
52         0, 1, 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 0xff
53 };
54
55 /***********************************************************************
56  * Register Access */
57
58 #if 0
59 /*! \brief Write a register of the tuner chip
60  *  \param[in] e4k reference to the tuner
61  *  \param[in] reg number of the register
62  *  \param[in] val value to be written
63  *  \returns 0 on success, negative in case of error
64  */
65 int e4k_reg_write(struct e4k_state *e4k, uint8_t reg, uint8_t val)
66 {
67         /* FIXME */
68         return 0;
69 }
70
71 /*! \brief Read a register of the tuner chip
72  *  \param[in] e4k reference to the tuner
73  *  \param[in] reg number of the register
74  *  \returns positive 8bit register contents on success, negative in case of error
75  */
76 int e4k_reg_read(struct e4k_state *e4k, uint8_t reg)
77 {
78         /* FIXME */
79         return 0;
80 }
81 #endif
82
83 /*! \brief Set or clear some (masked) bits inside a register
84  *  \param[in] e4k reference to the tuner
85  *  \param[in] reg number of the register
86  *  \param[in] mask bit-mask of the value
87  *  \param[in] val data value to be written to register
88  *  \returns 0 on success, negative in case of error
89  */
90 static int e4k_reg_set_mask(struct e4k_state *e4k, uint8_t reg,
91                      uint8_t mask, uint8_t val)
92 {
93         uint8_t tmp = e4k_reg_read(e4k, reg);
94
95         if ((tmp & mask) == val)
96                 return 0;
97
98         return e4k_reg_write(e4k, reg, (tmp & ~mask) | (val & mask));
99 }
100
101 /*! \brief Write a given field inside a register
102  *  \param[in] e4k reference to the tuner
103  *  \param[in] field structure describing the field
104  *  \param[in] val value to be written
105  *  \returns 0 on success, negative in case of error
106  */
107 static int e4k_field_write(struct e4k_state *e4k, const struct reg_field *field, uint8_t val)
108 {
109         int rc;
110         uint8_t mask;
111
112         rc = e4k_reg_read(e4k, field->reg);
113         if (rc < 0)
114                 return rc;
115
116         mask = width2mask[field->width] << field->shift;
117
118         return e4k_reg_set_mask(e4k, field->reg, mask, val << field->shift);
119 }
120
121 /*! \brief Read a given field inside a register
122  *  \param[in] e4k reference to the tuner
123  *  \param[in] field structure describing the field
124  *  \returns positive value of the field, negative in case of error
125  */
126 static int e4k_field_read(struct e4k_state *e4k, const struct reg_field *field)
127 {
128         int rc;
129
130         rc = e4k_reg_read(e4k, field->reg);
131         if (rc < 0)
132                 return rc;
133
134         rc = (rc >> field->shift) & width2mask[field->width];
135
136         return rc;
137 }
138
139 /***********************************************************************
140  * Filter Control */
141
142 static const uint32_t rf_filt_center_uhf[] = {
143         MHZ(360), MHZ(380), MHZ(405), MHZ(425),
144         MHZ(450), MHZ(475), MHZ(505), MHZ(540),
145         MHZ(575), MHZ(615), MHZ(670), MHZ(720),
146         MHZ(760), MHZ(840), MHZ(890), MHZ(970)
147 };
148
149 static const uint32_t rf_filt_center_l[] = {
150         MHZ(1300), MHZ(1320), MHZ(1360), MHZ(1410),
151         MHZ(1445), MHZ(1460), MHZ(1490), MHZ(1530),
152         MHZ(1560), MHZ(1590), MHZ(1640), MHZ(1660),
153         MHZ(1680), MHZ(1700), MHZ(1720), MHZ(1750)
154 };
155
156 static int closest_arr_idx(const uint32_t *arr, unsigned int arr_size, uint32_t freq)
157 {
158         unsigned int i, bi = 0;
159         uint32_t best_delta = 0xffffffff;
160
161         /* iterate over the array containing a list of the center
162          * frequencies, selecting the closest one */
163         for (i = 0; i < arr_size; i++) {
164                 uint32_t delta = unsigned_delta(freq, arr[i]);
165                 if (delta < best_delta) {
166                         best_delta = delta;
167                         bi = i;
168                 }
169         }
170
171         return bi;
172 }
173
174 /* return 4-bit index as to which RF filter to select */
175 static int choose_rf_filter(enum e4k_band band, uint32_t freq)
176 {
177         int rc;
178
179         switch (band) {
180                 case E4K_BAND_VHF2:
181                 case E4K_BAND_VHF3:
182                         rc = 0;
183                         break;
184                 case E4K_BAND_UHF:
185                         rc = closest_arr_idx(rf_filt_center_uhf,
186                                                  ARRAY_SIZE(rf_filt_center_uhf),
187                                                  freq);
188                         break;
189                 case E4K_BAND_L:
190                         rc = closest_arr_idx(rf_filt_center_l,
191                                                  ARRAY_SIZE(rf_filt_center_l),
192                                                  freq);
193                         break;
194                 default:
195                         rc = -EINVAL;
196                         break;
197         }
198
199         return rc;
200 }
201
202 /* \brief Automatically select apropriate RF filter based on e4k state */
203 int e4k_rf_filter_set(struct e4k_state *e4k)
204 {
205         int rc;
206
207         rc = choose_rf_filter(e4k->band, e4k->vco.flo);
208         if (rc < 0)
209                 return rc;
210
211         return e4k_reg_set_mask(e4k, E4K_REG_FILT1, 0xF, rc);
212 }
213
214 /* Mixer Filter */
215 static const uint32_t mix_filter_bw[] = {
216         KHZ(27000), KHZ(27000), KHZ(27000), KHZ(27000),
217         KHZ(27000), KHZ(27000), KHZ(27000), KHZ(27000),
218         KHZ(4600), KHZ(4200), KHZ(3800), KHZ(3400),
219         KHZ(3300), KHZ(2700), KHZ(2300), KHZ(1900)
220 };
221
222 /* IF RC Filter */
223 static const uint32_t ifrc_filter_bw[] = {
224         KHZ(21400), KHZ(21000), KHZ(17600), KHZ(14700),
225         KHZ(12400), KHZ(10600), KHZ(9000), KHZ(7700),
226         KHZ(6400), KHZ(5300), KHZ(4400), KHZ(3400),
227         KHZ(2600), KHZ(1800), KHZ(1200), KHZ(1000)
228 };
229
230 /* IF Channel Filter */
231 static const uint32_t ifch_filter_bw[] = {
232         KHZ(5500), KHZ(5300), KHZ(5000), KHZ(4800),
233         KHZ(4600), KHZ(4400), KHZ(4300), KHZ(4100),
234         KHZ(3900), KHZ(3800), KHZ(3700), KHZ(3600),
235         KHZ(3400), KHZ(3300), KHZ(3200), KHZ(3100),
236         KHZ(3000), KHZ(2950), KHZ(2900), KHZ(2800),
237         KHZ(2750), KHZ(2700), KHZ(2600), KHZ(2550),
238         KHZ(2500), KHZ(2450), KHZ(2400), KHZ(2300),
239         KHZ(2280), KHZ(2240), KHZ(2200), KHZ(2150)
240 };
241
242 static const uint32_t *if_filter_bw[] = {
243         mix_filter_bw,
244         ifch_filter_bw,
245         ifrc_filter_bw,
246 };
247
248 static const uint32_t if_filter_bw_len[] = {
249         ARRAY_SIZE(mix_filter_bw),
250         ARRAY_SIZE(ifch_filter_bw),
251         ARRAY_SIZE(ifrc_filter_bw),
252 };
253
254 static const struct reg_field if_filter_fields[] = {
255         {
256                 E4K_REG_FILT2, 4, 4,
257         },
258         {
259                 E4K_REG_FILT3, 0, 5,
260         },
261         {
262                 E4K_REG_FILT2, 0, 4,
263         }
264 };
265
266 static int find_if_bw(enum e4k_if_filter filter, uint32_t bw)
267 {
268         if (filter >= ARRAY_SIZE(if_filter_bw))
269                 return -EINVAL;
270
271         return closest_arr_idx(if_filter_bw[filter],
272                                if_filter_bw_len[filter], bw);
273 }
274
275 /*! \brief Set the filter band-width of any of the IF filters
276  *  \param[in] e4k reference to the tuner chip
277  *  \param[in] filter filter to be configured
278  *  \param[in] bandwidth bandwidth to be configured
279  *  \returns positive actual filter band-width, negative in case of error
280  */
281 int e4k_if_filter_bw_set(struct e4k_state *e4k, enum e4k_if_filter filter,
282                          uint32_t bandwidth)
283 {
284         int bw_idx;
285         const struct reg_field *field;
286
287         if (filter >= ARRAY_SIZE(if_filter_bw))
288                 return -EINVAL;
289
290         bw_idx = find_if_bw(filter, bandwidth);
291
292         field = &if_filter_fields[filter];
293
294         return e4k_field_write(e4k, field, bw_idx);
295 }
296
297 /*! \brief Enables / Disables the channel filter
298  *  \param[in] e4k reference to the tuner chip
299  *  \param[in] on 1=filter enabled, 0=filter disabled
300  *  \returns 0 success, negative errors
301  */
302 int e4k_if_filter_chan_enable(struct e4k_state *e4k, int on)
303 {
304         return e4k_reg_set_mask(e4k, E4K_REG_FILT3, E4K_FILT3_DISABLE,
305                                 on ? 0 : E4K_FILT3_DISABLE);
306 }
307
308 int e4k_if_filter_bw_get(struct e4k_state *e4k, enum e4k_if_filter filter)
309 {
310         const uint32_t *arr;
311         int rc;
312         const struct reg_field *field;
313
314         if (filter >= ARRAY_SIZE(if_filter_bw))
315                 return -EINVAL;
316
317         field = &if_filter_fields[filter];
318
319         rc = e4k_field_read(e4k, field);
320         if (rc < 0)
321                 return rc;
322
323         arr = if_filter_bw[filter];
324
325         return arr[rc];
326 }
327
328
329 /***********************************************************************
330  * Frequency Control */
331
332 #define E4K_FVCO_MIN_KHZ        2600000 /* 2.6 GHz */
333 #define E4K_FVCO_MAX_KHZ        3900000 /* 3.9 GHz */
334 #define E4K_PLL_Y               65536
335
336 #ifdef OUT_OF_SPEC
337 #define E4K_FLO_MIN_MHZ         50
338 #define E4K_FLO_MAX_MHZ         2200UL
339 #else
340 #define E4K_FLO_MIN_MHZ         64
341 #define E4K_FLO_MAX_MHZ         1700
342 #endif
343
344 struct pll_settings {
345         uint32_t freq;
346         uint8_t reg_synth7;
347         uint8_t mult;
348 };
349
350 static const struct pll_settings pll_vars[] = {
351         {KHZ(72400),    (1 << 3) | 7,   48},
352         {KHZ(81200),    (1 << 3) | 6,   40},
353         {KHZ(108300),   (1 << 3) | 5,   32},
354         {KHZ(162500),   (1 << 3) | 4,   24},
355         {KHZ(216600),   (1 << 3) | 3,   16},
356         {KHZ(325000),   (1 << 3) | 2,   12},
357         {KHZ(350000),   (1 << 3) | 1,   8},
358         {KHZ(432000),   (0 << 3) | 3,   8},
359         {KHZ(667000),   (0 << 3) | 2,   6},
360         {KHZ(1200000),  (0 << 3) | 1,   4}
361 };
362
363 static int is_fvco_valid(uint32_t fvco_z)
364 {
365         /* check if the resulting fosc is valid */
366         if (fvco_z/1000 < E4K_FVCO_MIN_KHZ ||
367             fvco_z/1000 > E4K_FVCO_MAX_KHZ) {
368                 fprintf(stderr, "[E4K] Fvco %u invalid\n", fvco_z);
369                 return 0;
370         }
371
372         return 1;
373 }
374
375 static int is_fosc_valid(uint32_t fosc)
376 {
377         if (fosc < MHZ(16) || fosc > MHZ(30)) {
378                 fprintf(stderr, "[E4K] Fosc %u invalid\n", fosc);
379                 return 0;
380         }
381
382         return 1;
383 }
384
385 static int is_z_valid(uint32_t z)
386 {
387         if (z > 255) {
388                 fprintf(stderr, "[E4K] Z %u invalid\n", z);
389                 return 0;
390         }
391
392         return 1;
393 }
394
395 /*! \brief Determine if 3-phase mixing shall be used or not */
396 static int use_3ph_mixing(uint32_t flo)
397 {
398         /* this is a magic number somewhre between VHF and UHF */
399         if (flo < MHZ(350))
400                 return 1;
401
402         return 0;
403 }
404
405 /* \brief compute Fvco based on Fosc, Z and X
406  * \returns positive value (Fvco in Hz), 0 in case of error */
407 static uint64_t compute_fvco(uint32_t f_osc, uint8_t z, uint16_t x)
408 {
409         uint64_t fvco_z, fvco_x, fvco;
410
411         /* We use the following transformation in order to
412          * handle the fractional part with integer arithmetic:
413          *  Fvco = Fosc * (Z + X/Y) <=> Fvco = Fosc * Z + (Fosc * X)/Y
414          * This avoids X/Y = 0.  However, then we would overflow a 32bit
415          * integer, as we cannot hold e.g. 26 MHz * 65536 either.
416          */
417         fvco_z = (uint64_t)f_osc * z;
418
419 #if 0
420         if (!is_fvco_valid(fvco_z))
421                 return 0;
422 #endif
423
424         fvco_x = ((uint64_t)f_osc * x) / E4K_PLL_Y;
425
426         fvco = fvco_z + fvco_x;
427
428         return fvco;
429 }
430
431 static uint32_t compute_flo(uint32_t f_osc, uint8_t z, uint16_t x, uint8_t r)
432 {
433         uint64_t fvco = compute_fvco(f_osc, z, x);
434         if (fvco == 0)
435                 return -EINVAL;
436
437         return fvco / r;
438 }
439
440 static int e4k_band_set(struct e4k_state *e4k, enum e4k_band band)
441 {
442         int rc;
443
444         switch (band) {
445         case E4K_BAND_VHF2:
446         case E4K_BAND_VHF3:
447         case E4K_BAND_UHF:
448                 e4k_reg_write(e4k, E4K_REG_BIAS, 3);
449                 break;
450         case E4K_BAND_L:
451                 e4k_reg_write(e4k, E4K_REG_BIAS, 0);
452                 break;
453         }
454
455         /* workaround: if we don't reset this register before writing to it,
456          * we get a gap between 325-350 MHz */
457         rc = e4k_reg_set_mask(e4k, E4K_REG_SYNTH1, 0x06, 0);
458         rc = e4k_reg_set_mask(e4k, E4K_REG_SYNTH1, 0x06, band << 1);
459         if (rc >= 0)
460                 e4k->band = band;
461
462         return rc;
463 }
464
465 /*! \brief Compute PLL parameters for givent target frequency
466  *  \param[out] oscp Oscillator parameters, if computation successful
467  *  \param[in] fosc Clock input frequency applied to the chip (Hz)
468  *  \param[in] intended_flo target tuning frequency (Hz)
469  *  \returns actual PLL frequency, as close as possible to intended_flo,
470  *           0 in case of error
471  */
472 uint32_t e4k_compute_pll_params(struct e4k_pll_params *oscp, uint32_t fosc, uint32_t intended_flo)
473 {
474         uint32_t i;
475         uint8_t r = 2;
476         uint64_t intended_fvco, remainder;
477         uint64_t z = 0;
478         uint32_t x;
479         int flo;
480         int three_phase_mixing = 0;
481         oscp->r_idx = 0;
482
483         if (!is_fosc_valid(fosc))
484                 return 0;
485
486         for(i = 0; i < ARRAY_SIZE(pll_vars); ++i) {
487                 if(intended_flo < pll_vars[i].freq) {
488                         three_phase_mixing = (pll_vars[i].reg_synth7 & 0x08) ? 1 : 0;
489                         oscp->r_idx = pll_vars[i].reg_synth7;
490                         r = pll_vars[i].mult;
491                         break;
492                 }
493         }
494
495         //fprintf(stderr, "[E4K] Fint=%u, R=%u\n", intended_flo, r);
496
497         /* flo(max) = 1700MHz, R(max) = 48, we need 64bit! */
498         intended_fvco = (uint64_t)intended_flo * r;
499
500         /* compute integral component of multiplier */
501         z = intended_fvco / fosc;
502
503         /* compute fractional part.  this will not overflow,
504         * as fosc(max) = 30MHz and z(max) = 255 */
505         remainder = intended_fvco - (fosc * z);
506         /* remainder(max) = 30MHz, E4K_PLL_Y = 65536 -> 64bit! */
507         x = (remainder * E4K_PLL_Y) / fosc;
508         /* x(max) as result of this computation is 65536 */
509
510         flo = compute_flo(fosc, z, x, r);
511
512         oscp->fosc = fosc;
513         oscp->flo = flo;
514         oscp->intended_flo = intended_flo;
515         oscp->r = r;
516 //      oscp->r_idx = pll_vars[i].reg_synth7 & 0x0;
517         oscp->threephase = three_phase_mixing;
518         oscp->x = x;
519         oscp->z = z;
520
521         return flo;
522 }
523
524 int e4k_tune_params(struct e4k_state *e4k, struct e4k_pll_params *p)
525 {
526         uint8_t val;
527
528         /* program R + 3phase/2phase */
529         e4k_reg_write(e4k, E4K_REG_SYNTH7, p->r_idx);
530         /* program Z */
531         e4k_reg_write(e4k, E4K_REG_SYNTH3, p->z);
532         /* program X */
533         e4k_reg_write(e4k, E4K_REG_SYNTH4, p->x & 0xff);
534         e4k_reg_write(e4k, E4K_REG_SYNTH5, p->x >> 8);
535
536         /* we're in auto calibration mode, so there's no need to trigger it */
537
538         memcpy(&e4k->vco, p, sizeof(e4k->vco));
539
540         /* set the band */
541         if (e4k->vco.flo < MHZ(140))
542                 e4k_band_set(e4k, E4K_BAND_VHF2);
543         else if (e4k->vco.flo < MHZ(350))
544                 e4k_band_set(e4k, E4K_BAND_VHF3);
545         else if (e4k->vco.flo < MHZ(1135))
546                 e4k_band_set(e4k, E4K_BAND_UHF);
547         else
548                 e4k_band_set(e4k, E4K_BAND_L);
549
550         /* select and set proper RF filter */
551         e4k_rf_filter_set(e4k);
552
553         return e4k->vco.flo;
554 }
555
556 /*! \brief High-level tuning API, just specify frquency
557  *
558  *  This function will compute matching PLL parameters, program them into the
559  *  hardware and set the band as well as RF filter.
560  *
561  *  \param[in] e4k reference to tuner
562  *  \param[in] freq frequency in Hz
563  *  \returns actual tuned frequency, negative in case of error
564  */
565 int e4k_tune_freq(struct e4k_state *e4k, uint32_t freq)
566 {
567         uint32_t rc;
568         struct e4k_pll_params p;
569
570         /* determine PLL parameters */
571         rc = e4k_compute_pll_params(&p, e4k->vco.fosc, freq);
572         if (!rc)
573                 return -EINVAL;
574
575         /* actually tune to those parameters */
576         rc = e4k_tune_params(e4k, &p);
577
578         /* check PLL lock */
579         rc = e4k_reg_read(e4k, E4K_REG_SYNTH1);
580         if (!(rc & 0x01)) {
581                 fprintf(stderr, "[E4K] PLL not locked for %u Hz!\n", freq);
582                 return -1;
583         }
584
585         return 0;
586 }
587
588 /***********************************************************************
589  * Gain Control */
590
591 static const int8_t if_stage1_gain[] = {
592         -3, 6
593 };
594
595 static const int8_t if_stage23_gain[] = {
596         0, 3, 6, 9
597 };
598
599 static const int8_t if_stage4_gain[] = {
600         0, 1, 2, 2
601 };
602
603 static const int8_t if_stage56_gain[] = {
604         3, 6, 9, 12, 15, 15, 15, 15
605 };
606
607 static const int8_t *if_stage_gain[] = {
608         0,
609         if_stage1_gain,
610         if_stage23_gain,
611         if_stage23_gain,
612         if_stage4_gain,
613         if_stage56_gain,
614         if_stage56_gain
615 };
616
617 static const uint8_t if_stage_gain_len[] = {
618         0,
619         ARRAY_SIZE(if_stage1_gain),
620         ARRAY_SIZE(if_stage23_gain),
621         ARRAY_SIZE(if_stage23_gain),
622         ARRAY_SIZE(if_stage4_gain),
623         ARRAY_SIZE(if_stage56_gain),
624         ARRAY_SIZE(if_stage56_gain)
625 };
626
627 static const struct reg_field if_stage_gain_regs[] = {
628         { 0, 0, 0 },
629         { E4K_REG_GAIN3, 0, 1 },
630         { E4K_REG_GAIN3, 1, 2 },
631         { E4K_REG_GAIN3, 3, 2 },
632         { E4K_REG_GAIN3, 5, 2 },
633         { E4K_REG_GAIN4, 0, 3 },
634         { E4K_REG_GAIN4, 3, 3 }
635 };
636
637 static const int32_t lnagain[] = {
638         -50,    0,
639         -25,    1,
640         0,      4,
641         25,     5,
642         50,     6,
643         75,     7,
644         100,    8,
645         125,    9,
646         150,    10,
647         175,    11,
648         200,    12,
649         250,    13,
650         300,    14,
651 };
652
653 static const int32_t enhgain[] = {
654         10, 30, 50, 70
655 };
656
657 int e4k_set_lna_gain(struct e4k_state *e4k, int32_t gain)
658 {
659         uint32_t i;
660         for(i = 0; i < ARRAY_SIZE(lnagain)/2; ++i) {
661                 if(lnagain[i*2] == gain) {
662                         e4k_reg_set_mask(e4k, E4K_REG_GAIN1, 0xf, lnagain[i*2+1]);
663                         return gain;
664                 }
665         }
666         return -EINVAL;
667 }
668
669 int e4k_set_enh_gain(struct e4k_state *e4k, int32_t gain)
670 {
671         uint32_t i;
672         for(i = 0; i < ARRAY_SIZE(enhgain); ++i) {
673                 if(enhgain[i] == gain) {
674                         e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, E4K_AGC11_LNA_GAIN_ENH | (i << 1));
675                         return gain;
676                 }
677         }
678         e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, 0);
679
680         /* special case: 0 = off*/
681         if(0 == gain)
682                 return 0;
683         else
684                 return -EINVAL;
685 }
686
687 int e4k_enable_manual_gain(struct e4k_state *e4k, uint8_t manual)
688 {
689         if (manual) {
690                 /* Set LNA mode to manual */
691                 e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, E4K_AGC_MOD_SERIAL);
692
693                 /* Set Mixer Gain Control to manual */
694                 e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0);
695         } else {
696                 /* Set LNA mode to auto */
697                 e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, E4K_AGC_MOD_IF_SERIAL_LNA_AUTON);
698                 /* Set Mixer Gain Control to auto */
699                 e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 1);
700
701                 e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, 0);
702         }
703
704         return 0;
705 }
706
707 static int find_stage_gain(uint8_t stage, int8_t val)
708 {
709         const int8_t *arr;
710         int i;
711
712         if (stage >= ARRAY_SIZE(if_stage_gain))
713                 return -EINVAL;
714
715         arr = if_stage_gain[stage];
716
717         for (i = 0; i < if_stage_gain_len[stage]; i++) {
718                 if (arr[i] == val)
719                         return i;
720         }
721         return -EINVAL;
722 }
723
724 /*! \brief Set the gain of one of the IF gain stages
725  *  \param [e4k] handle to the tuner chip
726  *  \param [stage] number of the stage (1..6)
727  *  \param [value] gain value in dB
728  *  \returns 0 on success, negative in case of error
729  */
730 int e4k_if_gain_set(struct e4k_state *e4k, uint8_t stage, int8_t value)
731 {
732         int rc;
733         uint8_t mask;
734         const struct reg_field *field;
735
736         rc = find_stage_gain(stage, value);
737         if (rc < 0)
738                 return rc;
739
740         /* compute the bit-mask for the given gain field */
741         field = &if_stage_gain_regs[stage];
742         mask = width2mask[field->width] << field->shift;
743
744         return e4k_reg_set_mask(e4k, field->reg, mask, rc << field->shift);
745 }
746
747 int e4k_mixer_gain_set(struct e4k_state *e4k, int8_t value)
748 {
749         uint8_t bit;
750
751         switch (value) {
752         case 4:
753                 bit = 0;
754                 break;
755         case 12:
756                 bit = 1;
757                 break;
758         default:
759                 return -EINVAL;
760         }
761
762         return e4k_reg_set_mask(e4k, E4K_REG_GAIN2, 1, bit);
763 }
764
765 int e4k_commonmode_set(struct e4k_state *e4k, int8_t value)
766 {
767         if(value < 0)
768                 return -EINVAL;
769         else if(value > 7)
770                 return -EINVAL;
771
772         return e4k_reg_set_mask(e4k, E4K_REG_DC7, 7, value);
773 }
774
775 /***********************************************************************
776  * DC Offset */
777
778 int e4k_manual_dc_offset(struct e4k_state *e4k, int8_t iofs, int8_t irange, int8_t qofs, int8_t qrange)
779 {
780         int res;
781
782         if((iofs < 0x00) || (iofs > 0x3f))
783                 return -EINVAL;
784         if((irange < 0x00) || (irange > 0x03))
785                 return -EINVAL;
786         if((qofs < 0x00) || (qofs > 0x3f))
787                 return -EINVAL;
788         if((qrange < 0x00) || (qrange > 0x03))
789                 return -EINVAL;
790
791         res = e4k_reg_set_mask(e4k, E4K_REG_DC2, 0x3f, iofs);
792         if(res < 0)
793                 return res;
794
795         res = e4k_reg_set_mask(e4k, E4K_REG_DC3, 0x3f, qofs);
796         if(res < 0)
797                 return res;
798
799         res = e4k_reg_set_mask(e4k, E4K_REG_DC4, 0x33, (qrange << 4) | irange);
800         return res;
801 }
802
803 /*! \brief Perform a DC offset calibration right now
804  *  \param [e4k] handle to the tuner chip
805  */
806 int e4k_dc_offset_calibrate(struct e4k_state *e4k)
807 {
808         /* make sure the DC range detector is enabled */
809         e4k_reg_set_mask(e4k, E4K_REG_DC5, E4K_DC5_RANGE_DET_EN, E4K_DC5_RANGE_DET_EN);
810
811         return e4k_reg_write(e4k, E4K_REG_DC1, 0x01);
812 }
813
814
815 static const int8_t if_gains_max[] = {
816         0, 6, 9, 9, 2, 15, 15
817 };
818
819 struct gain_comb {
820         int8_t mixer_gain;
821         int8_t if1_gain;
822         uint8_t reg;
823 };
824
825 static const struct gain_comb dc_gain_comb[] = {
826         { 4,  -3, 0x50 },
827         { 4,   6, 0x51 },
828         { 12, -3, 0x52 },
829         { 12,  6, 0x53 },
830 };
831
832 #define TO_LUT(offset, range)   (offset | (range << 6))
833
834 int e4k_dc_offset_gen_table(struct e4k_state *e4k)
835 {
836         uint32_t i;
837
838         /* FIXME: read ont current gain values and write them back
839          * before returning to the caller */
840
841         /* disable auto mixer gain */
842         e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0);
843
844         /* set LNA/IF gain to full manual */
845         e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK,
846                          E4K_AGC_MOD_SERIAL);
847
848         /* set all 'other' gains to maximum */
849         for (i = 2; i <= 6; i++)
850                 e4k_if_gain_set(e4k, i, if_gains_max[i]);
851
852         /* iterate over all mixer + if_stage_1 gain combinations */
853         for (i = 0; i < ARRAY_SIZE(dc_gain_comb); i++) {
854                 uint8_t offs_i, offs_q, range, range_i, range_q;
855
856                 /* set the combination of mixer / if1 gain */
857                 e4k_mixer_gain_set(e4k, dc_gain_comb[i].mixer_gain);
858                 e4k_if_gain_set(e4k, 1, dc_gain_comb[i].if1_gain);
859
860                 /* perform actual calibration */
861                 e4k_dc_offset_calibrate(e4k);
862
863                 /* extract I/Q offset and range values */
864                 offs_i = e4k_reg_read(e4k, E4K_REG_DC2) & 0x3f;
865                 offs_q = e4k_reg_read(e4k, E4K_REG_DC3) & 0x3f;
866                 range  = e4k_reg_read(e4k, E4K_REG_DC4);
867                 range_i = range & 0x3;
868                 range_q = (range >> 4) & 0x3;
869
870                 fprintf(stderr, "[E4K] Table %u I=%u/%u, Q=%u/%u\n",
871                         i, range_i, offs_i, range_q, offs_q);
872
873                 /* write into the table */
874                 e4k_reg_write(e4k, dc_gain_comb[i].reg,
875                               TO_LUT(offs_q, range_q));
876                 e4k_reg_write(e4k, dc_gain_comb[i].reg + 0x10,
877                               TO_LUT(offs_i, range_i));
878         }
879
880         return 0;
881 }
882
883 /***********************************************************************
884  * Initialization */
885
886 static int magic_init(struct e4k_state *e4k)
887 {
888         e4k_reg_write(e4k, 0x7e, 0x01);
889         e4k_reg_write(e4k, 0x7f, 0xfe);
890         e4k_reg_write(e4k, 0x82, 0x00);
891         e4k_reg_write(e4k, 0x86, 0x50); /* polarity A */
892         e4k_reg_write(e4k, 0x87, 0x20);
893         e4k_reg_write(e4k, 0x88, 0x01);
894         e4k_reg_write(e4k, 0x9f, 0x7f);
895         e4k_reg_write(e4k, 0xa0, 0x07);
896
897         return 0;
898 }
899
900 /*! \brief Initialize the E4K tuner
901  */
902 int e4k_init(struct e4k_state *e4k)
903 {
904         /* make a dummy i2c read or write command, will not be ACKed! */
905         e4k_reg_read(e4k, 0);
906
907         /* Make sure we reset everything and clear POR indicator */
908         e4k_reg_write(e4k, E4K_REG_MASTER1,
909                 E4K_MASTER1_RESET |
910                 E4K_MASTER1_NORM_STBY |
911                 E4K_MASTER1_POR_DET
912         );
913
914         /* Configure clock input */
915         e4k_reg_write(e4k, E4K_REG_CLK_INP, 0x00);
916
917         /* Disable clock output */
918         e4k_reg_write(e4k, E4K_REG_REF_CLK, 0x00);
919         e4k_reg_write(e4k, E4K_REG_CLKOUT_PWDN, 0x96);
920
921         /* Write some magic values into registers */
922         magic_init(e4k);
923 #if 0
924         /* Set common mode voltage a bit higher for more margin 850 mv */
925         e4k_commonmode_set(e4k, 4);
926
927         /* Initialize DC offset lookup tables */
928         e4k_dc_offset_gen_table(e4k);
929
930         /* Enable time variant DC correction */
931         e4k_reg_write(e4k, E4K_REG_DCTIME1, 0x01);
932         e4k_reg_write(e4k, E4K_REG_DCTIME2, 0x01);
933 #endif
934
935         /* Set LNA mode to manual */
936         e4k_reg_write(e4k, E4K_REG_AGC4, 0x10); /* High threshold */
937         e4k_reg_write(e4k, E4K_REG_AGC5, 0x04); /* Low threshold */
938         e4k_reg_write(e4k, E4K_REG_AGC6, 0x1a); /* LNA calib + loop rate */
939
940         e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK,
941                 E4K_AGC_MOD_SERIAL);
942
943         /* Set Mixer Gain Control to manual */
944         e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0);
945
946 #if 0
947         /* Enable LNA Gain enhancement */
948         e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7,
949                          E4K_AGC11_LNA_GAIN_ENH | (2 << 1));
950
951         /* Enable automatic IF gain mode switching */
952         e4k_reg_set_mask(e4k, E4K_REG_AGC8, 0x1, E4K_AGC8_SENS_LIN_AUTO);
953 #endif
954
955         /* Use auto-gain as default */
956         e4k_enable_manual_gain(e4k, 0);
957
958         /* Select moderate gain levels */
959         e4k_if_gain_set(e4k, 1, 6);
960         e4k_if_gain_set(e4k, 2, 0);
961         e4k_if_gain_set(e4k, 3, 0);
962         e4k_if_gain_set(e4k, 4, 0);
963         e4k_if_gain_set(e4k, 5, 9);
964         e4k_if_gain_set(e4k, 6, 9);
965
966         /* Set the most narrow filter we can possibly use */
967         e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_MIX, KHZ(1900));
968         e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_RC, KHZ(1000));
969         e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_CHAN, KHZ(2150));
970         e4k_if_filter_chan_enable(e4k, 1);
971
972         /* Disable time variant DC correction and LUT */
973         e4k_reg_set_mask(e4k, E4K_REG_DC5, 0x03, 0);
974         e4k_reg_set_mask(e4k, E4K_REG_DCTIME1, 0x03, 0);
975         e4k_reg_set_mask(e4k, E4K_REG_DCTIME2, 0x03, 0);
976
977         return 0;
978 }